@visa/cli 5.0.0-rc.407 → 5.0.0-rc.409
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +249 -70
- package/dist/cli.js +136 -212
- package/dist/enrollment-finisher.js +37 -0
- package/dist/mcp-server/index.js +465 -407
- package/dist/skills/pair-visa-agent/RUNTIMES.md +3 -2
- package/dist/skills/pair-visa-agent/SKILL.md +71 -18
- package/dist/skills/pair-visa-agent/scripts/__tests__/setup.test.mjs +5 -9
- package/package.json +9 -12
- package/server.json +2 -2
- package/dist/mcp-apps/ucp-checkout.html +0 -280
- package/dist/merchant-ucp-mcp/index.js +0 -7
- package/dist/skills/visa-shopify-checkout/SKILL.md +0 -95
- package/dist/skills/visa-shopify-checkout/references/evidence-and-states.md +0 -43
- package/dist/skills/visa-ucp-shopping/SKILL.md +0 -90
|
@@ -0,0 +1,37 @@
|
|
|
1
|
+
"use strict";var mP=Object.create;var Nu=Object.defineProperty;var gP=Object.getOwnPropertyDescriptor;var yP=Object.getOwnPropertyNames;var _P=Object.getPrototypeOf,wP=Object.prototype.hasOwnProperty;var y=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(n){throw t=0,n}},EP=(e,t)=>{for(var n in t)Nu(e,n,{get:t[n],enumerable:!0})},vP=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of yP(t))!wP.call(e,i)&&i!==n&&Nu(e,i,{get:()=>t[i],enumerable:!(r=gP(t,i))||r.enumerable});return e};var x=(e,t,n)=>(n=e!=null?mP(_P(e)):{},vP(t||!e||!e.__esModule?Nu(n,"default",{value:e,enumerable:!0}):n,e));var e_=y((hK,TP)=>{TP.exports={name:"@visa/cli",version:"5.0.0-rc.409",description:"Visa CLI runtime for stable agent identity and separately authorized payment capabilities",bin:{"visa-cli":"./bin/visa-cli.js",visa:"./bin/visa-cli.js","visa-runtime-converge":"./dist/managed-runtime/resolve-and-update.mjs"},scripts:{"sync:server-json":"node scripts/sync-server-json.mjs","check:server-json":"node scripts/sync-server-json.mjs --check",prebuild:"node scripts/sync-server-json.mjs",build:"pnpm test:types && node esbuild.config.js",prepack:"node scripts/sync-server-json.mjs --check",dev:"tsc --watch",pretest:"pnpm build",start:"node dist/mcp-server/index.js",test:"jest --config jest.config.js","test:types":"tsc -p tsconfig.test.json","pretest:unit":"pnpm test:types","test:unit":"jest --config jest.config.js","pretest:unit:watch":"pnpm test:types","test:unit:watch":"jest --config jest.config.js --watch","pretest:unit:coverage":"pnpm test:types","test:unit:coverage":"jest --config jest.config.js --coverage","test:smoke":"VISA_AUTH_URL=https://auth.visacli.sh jest --config jest.smoke.config.js","test:packed":"node scripts/packed-cli-smoke.mjs","test:e2e":"jest --config jest.e2e.config.js","coinbase:onramp":"pnpm exec tsx tests/e2e/coinbase-onramp-harness/run.ts","test:all":"npm run test:unit && npm run test:e2e",prepublishOnly:"npm run build && npm test",lint:"eslint src/**/*.ts",format:'prettier --write "src/**/*.ts"',"format:check":'prettier --check "src/**/*.ts"'},keywords:["visa","checkout","mcp","ai-agent","payments","click-to-pay","usdc","stablecoin"],author:"Visa Crypto Labs",license:"SEE LICENSE IN LICENSE",dependencies:{"@modelcontextprotocol/server":"2.0.0",commander:"^12.1.0",punycode:"^2.3.1",zod:"^3.25.76"},devDependencies:{"@types/express":"^5.0.0","@types/jest":"^30.0.0","@types/node":"^22.20.5","@typescript-eslint/eslint-plugin":"^8.68.0","@typescript-eslint/parser":"^8.68.0","@visa/crypto":"workspace:*","@visa/financial-core":"workspace:*","@visa/identity":"workspace:*","@visa/contracts":"workspace:*","@visa/observability":"workspace:*","@visa/shared":"workspace:*","@visa/wallet":"workspace:*","@visa/wallet-tools":"workspace:*",esbuild:"^0.28.1",eslint:"^10.0.2",express:"^4.21.0",jest:"^30.3.0",prettier:"^3.9.6","ts-jest":"^29.4.12",typescript:"^5.7.0",viem:"^2.56.0"},engines:{node:">=20.0.0"},mcpName:"io.github.visa-crypto-labs/visa-cli",files:["bin/visa-cli.js","dist/","install.ps1","install.sh","server.json","README.md"]}});var m_=y(Er=>{"use strict";Object.defineProperty(Er,"__esModule",{value:!0});Er.PAYMENT_APPROVAL_PATH_PREFIX=void 0;Er.paymentApprovalPath=h_;Er.paymentApprovalUrl=UP;Er.PAYMENT_APPROVAL_PATH_PREFIX="/agent/enroll/approvals/";function h_(e){let t=e.rail==="wallet"?e.approvalId:e.rail==="hosted"?e.draftId:e.attemptId,n=new URLSearchParams({rail:e.rail});return e.rail==="card"&&(n.set("agent",e.agentId),n.set("purchase",e.purchaseId),n.set("runtime",e.runtimeId)),`${Er.PAYMENT_APPROVAL_PATH_PREFIX}${encodeURIComponent(t)}?${n.toString()}`}function UP(e,t){let n=t.rail==="wallet"?`${Er.PAYMENT_APPROVAL_PATH_PREFIX}wallet/${encodeURIComponent(t.approvalId)}`:h_(t);return new URL(n,e).toString()}});var Q_=y(Qa=>{"use strict";Object.defineProperty(Qa,"__esModule",{value:!0});Qa.signedPost=X_;Qa.signedJsonPost=Z_;Qa.cardExecutorTransport=wk;function X_(e,t,n,r=fetch){return r(e,{...n,method:"POST",headers:{"content-type":"application/json",...n.headers},body:t})}async function Z_(e,t,n,r){let i=null,o="transport_failure";try{let a;try{a=await X_(e,typeof t=="function"?t():t,{headers:n.headers,redirect:"error",signal:AbortSignal.timeout(n.timeoutMs)},r)}catch(c){let d=c&&typeof c=="object"&&"name"in c?c.name:"";throw n.transportError(d==="TimeoutError"||d==="AbortError"?"timeout":"network")}i=a.status,o=a.ok?"invalid_response":"refused";let s;try{let c=await a.text();if(n.maxResponseChars===void 0||c.length<=n.maxResponseChars)s=JSON.parse(c);else if(a.ok)throw n.transportError("response")}catch{if(a.ok)throw n.transportError("response")}if(!a.ok)throw n.refusal(i,s);return o="response",s}finally{n.completed?.(i,o)}}function wk(e){let t=(n,r,i)=>Z_(e.origin+n,e.encode(r),e.policy(i,e.origin+n),e.fetch);return{issue:n=>t("/api/vgs/payment-cryptogram",n,!0),retrieve:n=>t("/api/financial-runtime/purchase-retrieve",n,!1)}}});var rw=y(le=>{"use strict";Object.defineProperty(le,"__esModule",{value:!0});le.GRANT_EXPIRED_MESSAGE=le.DEVICE_KEY_REPLACED_MESSAGE=le.AGENT_REVOKED_MESSAGE=le.AGENT_PAUSED_MESSAGE=le.INSTALLATION_CUSTODY_MESSAGE=le.LIFECYCLE_REFUSAL_CODES=void 0;le.isLifecycleRefusalCode=Xu;le.lifecycleRefusalBody=tw;le.decodeRefusal=nw;le.isRefusedResult=Ak;le.refusalMessage=Sk;le.refusalFromError=Ik;le.LIFECYCLE_REFUSAL_CODES=["agent_paused","agent_revoked","device_key_replaced","grant_expired"];le.INSTALLATION_CUSTODY_MESSAGE="A hosted app and a laptop need separate agents. Connect this as its own agent and approve its spending limits.";le.AGENT_PAUSED_MESSAGE="This agent is paused by its owner, so no payment was made. The owner can resume it in the Visa Console (Agents); retry once it is active.";le.AGENT_REVOKED_MESSAGE="This agent has been revoked, so no payment was made, and it cannot pay again. To keep paying, the owner connects a new agent from the Visa Console (Agents): with Visa CLI, update it and run `visa connect`; in an agent app, call `agent_enroll`.";le.DEVICE_KEY_REPLACED_MESSAGE="This computer's keys for the agent were replaced on another computer, so no payment was made and this one can no longer pay or sign for it. To use this computer too, run `visa connect` here and connect it as a new agent.";le.GRANT_EXPIRED_MESSAGE="This agent's spending approval from its owner has expired, so no payment was made and nothing was charged. The owner renews it in the Visa Console (Agents, then Limits) with the same limits; retry once it is renewed.";var Ek={agent_paused:{message:le.AGENT_PAUSED_MESSAGE,fix:null,stage:"lifecycle"},agent_revoked:{message:le.AGENT_REVOKED_MESSAGE,fix:null,stage:"lifecycle"},device_key_replaced:{message:le.DEVICE_KEY_REPLACED_MESSAGE,fix:"agent_enroll (MCP) or visa connect (shell)",stage:"lifecycle"},grant_expired:{message:le.GRANT_EXPIRED_MESSAGE,fix:null,stage:"authority_expiry"}};function Xu(e){return typeof e=="string"&&le.LIFECYCLE_REFUSAL_CODES.includes(e)}function tw(e,t){let n=Ek[e];return{code:e,stage:n.stage,message:t??n.message,fix:n.fix,retryable:!1}}var Zu={};function ve(e,t){for(let n of e)Zu[n]=t}ve(["spending_limit_required","protected_grant_missing"],{family:"spending_approval",stage:"grant_row",message:"This agent has no current spending approval.",fix:"The owner sets a spending limit in the Visa Console (Agents)."});ve(["pending_activation","connector_agent_pending_activation"],{family:"agent_setup",stage:"activation",message:"This agent has not finished connecting.",fix:"The owner finishes the existing connection request in the Visa Console."});ve(["connector_authority_lookup_unavailable","connector_authority_unavailable","runtime_authority_unavailable","unreachable"],{family:"unavailable",stage:"transport_read",message:"Visa could not be reached.",fix:"Keep the existing token and request reference. Check the same request before attempting another payment."});ve(["malformed_response"],{family:"unavailable",stage:"malformed_read",message:"Visa answered, but its answer could not be read.",fix:"Keep the existing token and request reference. Check the same request before attempting another payment."});ve(["auth_required","session_required","invalid_app_token"],{family:"credential_required",stage:"authentication",message:"Visa did not accept this credential.",fix:"Sign in for an owner action; for an app token, ask the owner to replace that token in the Visa Console."});ve(["connector_disabled","app_connections_not_configured","agent_apps_not_configured","hosted_payments_not_enabled"],{family:"deployment_unavailable",stage:"deployment",message:"This feature is unavailable on this Visa deployment.",fix:"Tell the operator which feature you were trying to use; account setup or a replacement token cannot enable it."});ve(["connector_runtime_required","hosted_runtime_required"],{family:"runtime_setup_required",stage:"runtime_setup",message:"This app needs a protected runtime.",fix:"The owner finishes this app\u2019s runtime setup in the Visa Console."});ve(["not_connected","connector_has_no_selected_agent","connector_runtime_not_found_for_owner","connector_agent_binding_not_found_for_owner"],{family:"app_connection_required",stage:"app_binding",message:"This app has no approved agent connection.",fix:"The owner connects this app in the Visa Console."});ve(["invalid_argument","invalid_arguments","invalid_intent","invalid_app_token_request","invalid_delivery_request","invalid_harness","request_too_large"],{family:"invalid_request",stage:"request",message:"Visa could not accept the supplied request fields.",fix:"Correct the input using this operation\u2019s schema. Keep the original reference when checking an existing purchase."});ve(["agent_not_found","token_not_found","app_not_found","draft_not_found","route_not_found"],{family:"not_found",stage:"resource_read",message:"That resource was not found in this request\u2019s scope.",fix:"Check the resource reference and the selected owner or app."});ve(["draft_expired","handoff_expired"],{family:"handoff_expired",stage:"handoff",message:"That request expired before it was completed.",fix:"Check the original request\u2019s delivery or purchase outcome before starting another request."});ve(["installation_custody_mismatch"],{family:"agent_setup",stage:"installation_custody",message:le.INSTALLATION_CUSTODY_MESSAGE,fix:"Connect this as its own agent."});ve(["harness_mismatch"],{family:"request_binding_mismatch",stage:"handoff",message:"This connection request belongs to a different app.",fix:"Use the original request in the app that opened it. Do not mint another token to resolve this request."});ve(["handoff_already_delivered","idempotency_conflict","purchase_request_changed","draft_not_pending","terms_conflict"],{family:"conflict",stage:"request_identity",message:"An existing request conflicts with this action.",fix:"Read the original delivery or purchase using its existing reference; do not create a replacement to hide uncertainty."});ve(["owner_approval_required","wallet_owner_approval_required","card_owner_approval_required"],{family:"owner_approval",stage:"payment_mode",message:"The owner must approve this payment.",fix:"Show the approval link returned for this exact payment and wait for the owner."});ve(["owner_declined"],{family:"owner_declined",stage:"owner_decision",message:"The owner declined this operation.",fix:"Stop this operation. Do not retry it automatically."});ve(["kill_switch_engaged","budget_draw_refused","merchant_not_allowed","merchant_blocked"],{family:"spending_policy",stage:"spending_policy",message:"The current spending policy refused this payment.",fix:"Tell the owner the recorded restriction. Do not switch agents or payment rails to bypass it."});ve(["operator_daily_cap_reached"],{family:"spending_policy",stage:"operator_daily_cap_reached",message:"The operator\u2019s 24-hour spending limit is reached. No new hold or signature was issued.",fix:"Check any earlier attempt using its original reference, then try the same purchase again later only after usage leaves the 24-hour window or the operator changes the limit. A purchase above the entire cap needs a limit change. Do not loop or switch agents or rails to bypass the limit."});ve(["operator_daily_cap_unavailable"],{family:"unavailable",stage:"operator_daily_cap_unavailable",message:"Visa could not read the operator\u2019s 24-hour limit. No new hold or signature was issued.",fix:"Check any earlier attempt using its original reference, then tell the operator if the control needs repair; retry the same purchase later only after the control is readable. Do not switch agents or rails."});ve(["owner_signature_unconfirmed"],{family:"outcome_unknown",stage:"owner_signature",message:"The owner signature has not been confirmed.",fix:"Check or resend the same stamped request; keep its original identity."});ve(["outcome_unknown"],{family:"outcome_unknown",stage:"transport",message:"The result of this operation is unknown.",fix:"Reconcile the original request or purchase. Do not make a replacement payment or mint another token."});ve(["cancellation_pending"],{family:"outcome_pending",stage:"cancellation",message:"Cancellation is pending; payment liability is unresolved.",fix:"Retrieve the same purchase to check reconciliation. Do not create a replacement purchase or assume funds were released."});var vk=/^[a-z][a-z0-9_]{0,63}$/,bk=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,es=e=>typeof e=="string"&&vk.test(e)?e:null,ew=e=>typeof e=="string"&&bk.test(e)?e:null;function nw(e,t=null){let n=e&&typeof e=="object"&&!Array.isArray(e)?e:{},r=es(n.code)??es(n.error)??es(n.reason)??"unknown_refusal",i=r.startsWith("connector_")&&Xu(r.slice(10))?r.slice(10):r,o=es(n.reason),a=Xu(i)?tw(i):null,s=Object.hasOwn(Zu,i)?Zu[i]:void 0,c=a?i==="grant_expired"?"spending_approval":"agent_lifecycle":s?.family??(t===401?"credential_required":t===403?"forbidden":"unknown"),d=c==="credential_required"?{message:"Visa requires a valid credential for this action.",fix:"Sign in or ask the owner to check the credential for this app."}:c==="forbidden"?{message:"Visa did not authorize this action.",fix:"Ask the owner to check this action\u2019s permissions. Keep the current token unless it is explicitly rejected."}:{message:"Visa could not complete this request.",fix:"Keep the original request reference and ask the operator to check its outcome. Do not retry a payment automatically."};return{code:i,reason:o,family:c,stage:es(n.stage)??a?.stage??s?.stage??null,message:a?.message??s?.message??d.message,fix:a?.fix??(a?a.message:s?.fix??d.fix),retryable:!a&&n.retryable===!0&&i!=="outcome_unknown"&&i!=="cancellation_pending"&&c!=="agent_lifecycle"&&c!=="deployment_unavailable"&&t!==500,status:t,requestId:typeof n.requestId=="string"&&/^[a-zA-Z0-9_-]{1,128}$/.test(n.requestId)?n.requestId:null,purchaseId:ew(n.purchaseId),minted:typeof n.minted=="boolean"?n.minted:null,deliveredAgentId:ew(n.deliveredAgentId)}}function Ak(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.success===!1||t.status==="refused"}function Sk(e){return e.fix&&e.fix!==e.message&&!e.message.includes(e.fix)?`${e.message} ${e.fix}`:e.message}function Ik(e){if(!e||typeof e!="object")return null;let t=e.refusal??e.diagnostic;if(!t||typeof t!="object"||!("family"in t))return null;let n="status"in t&&typeof t.status=="number"?t.status:null;return nw(t,n)}});var yi=y((GK,hw)=>{"use strict";var rf=Object.defineProperty,Tk=Object.getOwnPropertyDescriptor,Pk=Object.getOwnPropertyNames,kk=Object.prototype.hasOwnProperty,Ck=(e,t)=>{for(var n in t)rf(e,n,{get:t[n],enumerable:!0})},Rk=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Pk(t))!kk.call(e,i)&&i!==n&&rf(e,i,{get:()=>t[i],enumerable:!(r=Tk(t,i))||r.enumerable});return e},xk=e=>Rk(rf({},"__esModule",{value:!0}),e),dw={};Ck(dw,{base64UrlToBytes:()=>Bk,bytesToBase64Url:()=>Fk,bytesToHex:()=>Hk,hexToBytes:()=>Vk});hw.exports=xk(dw);var of=Object.freeze,Do=0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,ef=0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,Gc=0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,tf=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,nf=0x6666666666666666666666666666666666666666666666666666666666666658n,Yc=Do-1n,Ok=of({p:Do,n:ef,h:8n,a:Yc,d:Gc,Gx:tf,Gy:nf}),lw=32,iw=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&e.BYTES_PER_ELEMENT===1,zc=(e,t,n="")=>{if(iw(e)&&(t===void 0||e.length===t))return e;let r=iw(e),i=t!==void 0?` of length ${t}`:"",o=r?`length=${e.length}`:`type=${typeof e}`,a=(n?`"${n}" `:"")+"expected Uint8Array"+i+", got "+o;throw r?new RangeError(a):new TypeError(a)},Nk=(e,t="",n)=>Uint8Array.from(zc(e,n,t)),uw=(e,t)=>e.toString(16).padStart(t,"0"),af=e=>{let t="";for(let n of zc(e))t+=uw(n,2);return t},sf=e=>{let t="hex invalid";if(typeof e!="string")throw new TypeError(t);if(e.length%2||!/^[\da-f]*$/i.test(e))throw new RangeError(t);let n=new Uint8Array(e.length/2);for(let r=0,i=0;r<n.length;r++,i+=2){let o=e.charCodeAt(i),a=e.charCodeAt(i+1);n[r]=((o&15)+(o>>6)*9)*16+(a&15)+(a>>6)*9}return n},Dk=(...e)=>{let t=0;for(let i of e)t+=zc(i).length;let n=new Uint8Array(t),r=0;for(let i of e)n.set(i,r),r+=i.length;return n},Mk=(e=lw)=>{let t=globalThis?.crypto;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined, consider polyfill");return t.getRandomValues(new Uint8Array(e))},hi=(e,t,n,r="bad number: out of range")=>{if(typeof e!="bigint")throw new TypeError(r);if(t<=e&&e<n)return e;throw new RangeError(r)},ye=(e,t=Do)=>(e%=t)>=0n?e:t+e,ow=(1n<<255n)-1n,O=e=>{if(e<0n)throw new RangeError("negative coordinate");let t=(e>>255n)*19n+(e&ow);return t=(t>>255n)*19n+(t&ow),t%Do},fw=(e,t)=>{if(e===0n)throw new Error("invert: expected non-zero number");if(t<=1n)throw new Error("invert: expected modulus > 1, got "+t);let n=ye(e,t),r=t,i=0n,o=1n;for(;n!==0n;){let s=r/n,c=r-n*s,d=i-o*s;r=n,n=c,i=o,o=d}if(r!==1n)throw new Error("invert: does not exist");return ye(i,t)},Qu=e=>{if(e instanceof ns)return e;throw new TypeError("Point expected")},pw=2n**256n,ns=class mi{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,i){let o=pw;this.X=hi(t,0n,o),this.Y=hi(n,0n,o),this.Z=hi(r,1n,o),this.T=hi(i,0n,o),of(this)}static CURVE(){return Ok}static fromAffine(t){return new mi(t.x,t.y,1n,O(t.x*t.y))}static fromBytes(t,n=!1){let r=Nk(t,"point",lw),i=r[31];r[31]=i&-129;let o=Jk(r);n||hi(o,0n,Do);let a=O(o*o),s=ye(a-1n),c=O(Gc*a+1n),{isValid:d,value:l}=jk(s,c);if(!d)throw new Error("bad point: y not sqrt");let u=!!(i&128);if(!n&&l===0n&&u)throw new Error("bad point: x==0, isLastByteOdd");return u!==!!(l&1n)&&(l=ye(-l)),new mi(l,o,1n,O(l*o))}static fromHex(t,n){return mi.fromBytes(sf(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=Yc,n=Gc,r=this;if(r.is0())throw new Error("bad point: ZERO");let{X:i,Y:o,Z:a,T:s}=r,c=O(i*i),d=O(o*o),l=O(a*a),u=O(l*l),f=O(c*t),h=O(l*(f+d)),p=ye(u+O(n*O(c*d)));if(h!==p)throw new Error("bad point: equation left != right (1)");let m=O(i*o),w=O(a*s);if(m!==w)throw new Error("bad point: equation left != right (2)");return this}equals(t){let{X:n,Y:r,Z:i}=this,{X:o,Y:a,Z:s}=Qu(t);return O(n*s)===O(o*i)&&O(r*s)===O(a*i)}is0(){return this.equals(gi)}negate(){return new mi(ye(-this.X),this.Y,this.Z,ye(-this.T))}double(){let{X:t,Y:n,Z:r}=this,i=Yc,o=O(t*t),a=O(n*n),s=O(2n*r*r),c=O(i*o),d=ye(t+n),l=ye(O(d*d)-o-a),u=ye(c+a),f=ye(u-s),h=ye(c-a),p=O(l*f),m=O(u*h),w=O(l*h),v=O(f*u);return new mi(p,m,v,w)}add(t){let{X:n,Y:r,Z:i,T:o}=this,{X:a,Y:s,Z:c,T:d}=Qu(t),l=Yc,u=Gc,f=O(n*a),h=O(r*s),p=O(O(o*u)*d),m=O(i*c),w=ye(O(ye(n+r)*ye(a+s))-f-h),v=ye(m-p),_=ye(m+p),A=ye(h-O(l*f)),j=O(w*v),Q=O(_*A),X=O(w*A),H=O(v*_);return new mi(j,Q,H,X)}subtract(t){return this.add(Qu(t).negate())}multiply(t,n=!0){if(!n&&t===0n||(hi(t,1n,ef),!n&&this.is0()))return gi;if(t===1n)return this;if(this.equals(ts))return Kk(t).p;let r=gi,i=ts,o=this;for(let a=0;n?a<256:t>0n;a++)t&1n?r=r.add(o):n&&(i=i.add(o)),o=o.double(),t>>=1n;return r}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){let{X:t,Y:n,Z:r}=this;if(this.equals(gi))return{x:0n,y:1n};let i=fw(r,Do);if(O(r*i)!==1n)throw new Error("invalid inverse");return{x:O(t*i),y:O(n*i)}}toBytes(){let{x:t,y:n}=this.toAffine(),r=Lk(n);return r[31]|=t&1n?128:0,r}toHex(){return af(this.toBytes())}clearCofactor(){return this.multiply(8n,!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return this.multiply(ef/2n,!1).double().add(this).is0()}},ts=new ns(tf,nf,1n,ye(tf*nf)),gi=new ns(0n,1n,1n,0n);ns.BASE=ts;ns.ZERO=gi;var Lk=e=>sf(uw(hi(e,0n,pw),64)).reverse(),Jk=e=>BigInt("0x"+af(Uint8Array.from(zc(e)).reverse())),dn=(e,t)=>{let n=e;for(;t-- >0;)n=O(n*n);return n},Uk=e=>{let t=O(e*e),n=O(t*e),r=O(dn(n,2)*n),i=O(dn(r,1)*e),o=O(dn(i,5)*i),a=O(dn(o,10)*o),s=O(dn(a,20)*a),c=O(dn(s,40)*s),d=O(dn(c,80)*c),l=O(dn(d,80)*c),u=O(dn(l,10)*o);return O(dn(u,2)*e)},aw=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,jk=(e,t)=>{let n=O(t*O(t*t)),r=O(O(n*n)*t),i=Uk(O(e*r)),o=O(e*O(n*i)),a=O(t*O(o*o)),s=o,c=O(o*aw),d=a===e,l=a===ye(-e),u=a===ye(-e*aw);return d&&(o=s),(l||u)&&(o=c),(ye(o)&1n)===1n&&(o=ye(-o)),{isValid:d||l,value:o}},cf=of({bytesToHex:af,hexToBytes:sf,concatBytes:Dk,mod:ye,invert:fw,randomBytes:Mk}),qk=()=>{let e=[],t=ts,n;for(let r=0;r<33;r++){n=t,e.push(n);for(let i=1;i<128;i++)n=n.add(t),e.push(n);t=n.double()}return e},sw=void 0,cw=(e,t)=>{let n=t.negate();return e?n:t},Kk=e=>{let t=sw||(sw=qk()),n=gi,r=ts;for(let i=0;i<33;i++){let o=Number(e&255n);e>>=8n,o>128&&(o-=256,e+=1n);let a=i*128,s=a+Math.abs(o)-1,c=i%2!==0,d=o<0;o===0?r=r.add(cw(c,t[a])):n=n.add(cw(d,t[s]))}if(e!==0n)throw new Error("invalid wnaf");return{p:n,f:r}},Hk=cf.bytesToHex,Vk=cf.hexToBytes,BK=cf.concatBytes;function $k(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function Wk(e){let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function Fk(e){return $k(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Bk(e){let t=e.length%4===0?0:4-e.length%4,n=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat(t);return Wk(n)}});var rs=y((ZK,Fw)=>{"use strict";var hf=Object.defineProperty,Gk=Object.getOwnPropertyDescriptor,Yk=Object.getOwnPropertyNames,zk=Object.prototype.hasOwnProperty,Xk=(e,t)=>{for(var n in t)hf(e,n,{get:t[n],enumerable:!0})},Zk=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Yk(t))!zk.call(e,i)&&i!==n&&hf(e,i,{get:()=>t[i],enumerable:!(r=Gk(t,i))||r.enumerable});return e},Qk=e=>Zk(hf({},"__esModule",{value:!0}),e),Pw={};Xk(Pw,{computeJkt:()=>FC,sha256:()=>Ww,sign:()=>qC,signAsync:()=>HC,verify:()=>KC,verifyAsync:()=>VC});Fw.exports=Qk(Pw);var mf=Object.freeze,Jo=0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,nd=0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,ed=0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,uf=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,ff=0x6666666666666666666666666666666666666666666666666666666666666658n,td=Jo-1n,eC=mf({p:Jo,n:nd,h:8n,a:td,d:ed,Gx:uf,Gy:ff}),vi=32,mw=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&e.BYTES_PER_ELEMENT===1,St=(e,t,n="")=>{if(mw(e)&&(t===void 0||e.length===t))return e;let r=mw(e),i=t!==void 0?` of length ${t}`:"",o=r?`length=${e.length}`:`type=${typeof e}`,a=(n?`"${n}" `:"")+"expected Uint8Array"+i+", got "+o;throw r?new RangeError(a):new TypeError(a)},od=(e,t="",n)=>Uint8Array.from(St(e,n,t)),kw=(e,t)=>e.toString(16).padStart(t,"0"),gf=e=>{let t="";for(let n of St(e))t+=kw(n,2);return t},yf=e=>{let t="hex invalid";if(typeof e!="string")throw new TypeError(t);if(e.length%2||!/^[\da-f]*$/i.test(e))throw new RangeError(t);let n=new Uint8Array(e.length/2);for(let r=0,i=0;r<n.length;r++,i+=2){let o=e.charCodeAt(i),a=e.charCodeAt(i+1);n[r]=((o&15)+(o>>6)*9)*16+(a&15)+(a>>6)*9}return n},bi=(...e)=>{let t=0;for(let i of e)t+=St(i).length;let n=new Uint8Array(t),r=0;for(let i of e)n.set(i,r),r+=i.length;return n},tC=(e=vi)=>{let t=globalThis?.crypto;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined, consider polyfill");return t.getRandomValues(new Uint8Array(e))},_i=(e,t,n,r="bad number: out of range")=>{if(typeof e!="bigint")throw new TypeError(r);if(t<=e&&e<n)return e;throw new RangeError(r)},fe=(e,t=Jo)=>(e%=t)>=0n?e:t+e,gw=(1n<<255n)-1n,N=e=>{if(e<0n)throw new RangeError("negative coordinate");let t=(e>>255n)*19n+(e&gw);return t=(t>>255n)*19n+(t&gw),t%Jo},Cw=e=>fe(e,nd),Rw=(e,t)=>{if(e===0n)throw new Error("invert: expected non-zero number");if(t<=1n)throw new Error("invert: expected modulus > 1, got "+t);let n=fe(e,t),r=t,i=0n,o=1n;for(;n!==0n;){let s=r/n,c=r-n*s,d=i-o*s;r=n,n=c,i=o,o=d}if(r!==1n)throw new Error("invert: does not exist");return fe(i,t)},xw=e=>{let t=jw[e];if(typeof t!="function")throw new Error("hashes."+e+" not set");return t},_f=(e,...t)=>St(xw(e)(bi(...t)),64,"digest"),wf=async(e,...t)=>St(await xw(e)(bi(...t)),64,"digest"),df=e=>{if(e instanceof Ai)return e;throw new TypeError("Point expected")},Ow=2n**256n,Ai=class wi{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,i){let o=Ow;this.X=_i(t,0n,o),this.Y=_i(n,0n,o),this.Z=_i(r,1n,o),this.T=_i(i,0n,o),mf(this)}static CURVE(){return eC}static fromAffine(t){return new wi(t.x,t.y,1n,N(t.x*t.y))}static fromBytes(t,n=!1){let r=od(t,"point",vi),i=r[31];r[31]=i&-129;let o=Ef(r);n||_i(o,0n,Jo);let a=N(o*o),s=fe(a-1n),c=N(ed*a+1n),{isValid:d,value:l}=rC(s,c);if(!d)throw new Error("bad point: y not sqrt");let u=!!(i&128);if(!n&&l===0n&&u)throw new Error("bad point: x==0, isLastByteOdd");return u!==!!(l&1n)&&(l=fe(-l)),new wi(l,o,1n,N(l*o))}static fromHex(t,n){return wi.fromBytes(yf(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=td,n=ed,r=this;if(r.is0())throw new Error("bad point: ZERO");let{X:i,Y:o,Z:a,T:s}=r,c=N(i*i),d=N(o*o),l=N(a*a),u=N(l*l),f=N(c*t),h=N(l*(f+d)),p=fe(u+N(n*N(c*d)));if(h!==p)throw new Error("bad point: equation left != right (1)");let m=N(i*o),w=N(a*s);if(m!==w)throw new Error("bad point: equation left != right (2)");return this}equals(t){let{X:n,Y:r,Z:i}=this,{X:o,Y:a,Z:s}=df(t);return N(n*s)===N(o*i)&&N(r*s)===N(a*i)}is0(){return this.equals(Ei)}negate(){return new wi(fe(-this.X),this.Y,this.Z,fe(-this.T))}double(){let{X:t,Y:n,Z:r}=this,i=td,o=N(t*t),a=N(n*n),s=N(2n*r*r),c=N(i*o),d=fe(t+n),l=fe(N(d*d)-o-a),u=fe(c+a),f=fe(u-s),h=fe(c-a),p=N(l*f),m=N(u*h),w=N(l*h),v=N(f*u);return new wi(p,m,v,w)}add(t){let{X:n,Y:r,Z:i,T:o}=this,{X:a,Y:s,Z:c,T:d}=df(t),l=td,u=ed,f=N(n*a),h=N(r*s),p=N(N(o*u)*d),m=N(i*c),w=fe(N(fe(n+r)*fe(a+s))-f-h),v=fe(m-p),_=fe(m+p),A=fe(h-N(l*f)),j=N(w*v),Q=N(_*A),X=N(w*A),H=N(v*_);return new wi(j,Q,H,X)}subtract(t){return this.add(df(t).negate())}multiply(t,n=!0){if(!n&&t===0n||(_i(t,1n,nd),!n&&this.is0()))return Ei;if(t===1n)return this;if(this.equals(Tr))return fC(t).p;let r=Ei,i=Tr,o=this;for(let a=0;n?a<256:t>0n;a++)t&1n?r=r.add(o):n&&(i=i.add(o)),o=o.double(),t>>=1n;return r}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){let{X:t,Y:n,Z:r}=this;if(this.equals(Ei))return{x:0n,y:1n};let i=Rw(r,Jo);if(N(r*i)!==1n)throw new Error("invalid inverse");return{x:N(t*i),y:N(n*i)}}toBytes(){let{x:t,y:n}=this.toAffine(),r=Nw(n);return r[31]|=t&1n?128:0,r}toHex(){return gf(this.toBytes())}clearCofactor(){return this.multiply(8n,!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return this.multiply(nd/2n,!1).double().add(this).is0()}},Tr=new Ai(uf,ff,1n,fe(uf*ff)),Ei=new Ai(0n,1n,1n,0n);Ai.BASE=Tr;Ai.ZERO=Ei;var Nw=e=>yf(kw(_i(e,0n,Ow),64)).reverse(),Ef=e=>BigInt("0x"+gf(Uint8Array.from(St(e)).reverse())),ln=(e,t)=>{let n=e;for(;t-- >0;)n=N(n*n);return n},nC=e=>{let t=N(e*e),n=N(t*e),r=N(ln(n,2)*n),i=N(ln(r,1)*e),o=N(ln(i,5)*i),a=N(ln(o,10)*o),s=N(ln(a,20)*a),c=N(ln(s,40)*s),d=N(ln(c,80)*c),l=N(ln(d,80)*c),u=N(ln(l,10)*o);return N(ln(u,2)*e)},yw=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,rC=(e,t)=>{let n=N(t*N(t*t)),r=N(N(n*n)*t),i=nC(N(e*r)),o=N(e*N(n*i)),a=N(t*N(o*o)),s=o,c=N(o*yw),d=a===e,l=a===fe(-e),u=a===fe(-e*yw);return d&&(o=s),(l||u)&&(o=c),(fe(o)&1n)===1n&&(o=fe(-o)),{isValid:d||l,value:o}},rd=e=>Cw(Ef(e)),Dw=e=>{let t=od(e),n=t.slice(0,32);n[0]&=248,n[31]&=127,n[31]|=64;let r=t.slice(32),i=rd(n),o=Tr.multiply(i),a=o.toBytes();return{head:n,prefix:r,scalar:i,point:o,pointBytes:a}},iC=e=>wf("sha512Async",St(e,vi,"secretKey")).then(Dw),oC=e=>Dw(_f("sha512",St(e,vi,"secretKey"))),Mw=async e=>e[1](await wf("sha512Async",e[0])),Lw=e=>e[1](_f("sha512",e[0])),Jw=(e,t,n)=>{let{pointBytes:r,scalar:i}=e,o=rd(t),a=Tr.multiply(o).toBytes();return[bi(a,r,n),d=>{let l=Cw(o+rd(d)*i);return St(bi(a,Nw(l)),64)}]},aC=async(e,t)=>{let n=od(e,"message"),r=await iC(t);return Mw(Jw(r,await wf("sha512Async",r.prefix,n),n))},sC=(e,t)=>{let n=od(e,"message"),r=oC(t);return Lw(Jw(r,_f("sha512",r.prefix,n),n))},cC=e=>{if(e===null||typeof e!="object")throw new TypeError("expected valid options object");return e.zip215??!0},Uw=(e,t,n,r)=>{e=St(e,64,"signature"),t=St(t,void 0,"message"),n=St(n,vi,"publicKey");let i=cC(r),o=e.subarray(0,vi),a=Ef(e.subarray(vi,64)),s,c,d,l=Uint8Array.of(),u=!1;try{s=Ai.fromBytes(n,i),c=Ai.fromBytes(o,i),d=Tr.multiply(a,!1),l=bi(o,n,t),u=!0}catch{}return[l,h=>{if(!u||!i&&s.isSmallOrder())return!1;let p=rd(h);return c.add(s.multiply(p,!1)).subtract(d).clearCofactor().is0()}]},dC=async(e,t,n,r={})=>Mw(Uw(e,t,n,r)),lC=(e,t,n,r={})=>Lw(Uw(e,t,n,r)),vf=mf({bytesToHex:gf,hexToBytes:yf,concatBytes:bi,mod:fe,invert:Rw,randomBytes:tC}),jw={sha512Async:async e=>{let t=globalThis?.crypto?.subtle;if(!t)throw new Error("crypto.subtle must be defined, consider polyfill");return new Uint8Array(await t.digest("SHA-512",bi(e)))},sha512:void 0},uC=()=>{let e=[],t=Tr,n;for(let r=0;r<33;r++){n=t,e.push(n);for(let i=1;i<128;i++)n=n.add(t),e.push(n);t=n.double()}return e},_w=void 0,ww=(e,t)=>{let n=t.negate();return e?n:t},fC=e=>{let t=_w||(_w=uC()),n=Ei,r=Tr;for(let i=0;i<33;i++){let o=Number(e&255n);e>>=8n,o>128&&(o-=256,e+=1n);let a=i*128,s=a+Math.abs(o)-1,c=i%2!==0,d=o<0;o===0?r=r.add(ww(c,t[a])):n=n.add(ww(d,t[s]))}if(e!==0n)throw new Error("invalid wnaf");return{p:n,f:r}},Xc=BigInt(2**32-1),Ew=BigInt(32);function pC(e,t=!1){return t?{h:Number(e&Xc),l:Number(e>>Ew&Xc)}:{h:Number(e>>Ew&Xc)|0,l:Number(e&Xc)|0}}function hC(e,t=!1){let n=e.length,r=new Uint32Array(n),i=new Uint32Array(n);for(let o=0;o<n;o++){let{h:a,l:s}=pC(e[o],t);[r[o],i[o]]=[a,s]}return[r,i]}var mC=e=>e/2**32|0,gC=e=>e>>>0;function yC(e,t,n,r){let i=mC(n),o=gC(n);e.setUint32(t,r?o:i,r),e.setUint32(t+4,r?i:o,r)}var vw=(e,t,n)=>e>>>n,bw=(e,t,n)=>e<<32-n|t>>>n,Mo=(e,t,n)=>e>>>n|t<<32-n,Lo=(e,t,n)=>e<<32-n|t>>>n,Zc=(e,t,n)=>e<<64-n|t>>>n-32,Qc=(e,t,n)=>e>>>n-32|t<<64-n;function Un(e,t,n,r){let i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:i|0}}var _C=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),wC=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,EC=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),vC=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0,bC=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0),AC=(e,t,n,r,i,o)=>t+n+r+i+o+(e/2**32|0)|0;function Aw(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var pf=e=>e?`"${e}" `:"";function SC(e,t=""){if(typeof e!="number")throw new TypeError(pf(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(pf(t)+"expected integer >= 0, got "+e);return e}function qw(e,t,n=""){if(Aw(e)&&(t===void 0||e.length===t))return e;t!==void 0&&SC(t,"length");let r=Aw(e),i=t!==void 0?` of length ${t}`:"",o=r?`length=${e.length}`:`type=${typeof e}`,a=pf(n)+"expected Uint8Array"+i+", got "+o;throw r?new RangeError(a):new TypeError(a)}var IC=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},Sw=(e,t)=>{IC(e,t);let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw new TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw new TypeError(`"${t}.__proto__" is not allowed`)};function Iw(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function TC(e,t){qw(e,void 0,"output");let n=t.outputLen;if(!(e.length>=n))throw new RangeError('"output" expected length >= '+n)}function id(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function lf(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function un(e,t){return e<<32-t|e>>>t}function PC(e,t,n="opts"){return Sw(e,"defaults"),t!==void 0&&Sw(t,n),Object.assign(Object.create(null),e,t)}function Kw(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=PC({},t,"info");let n=(i,o)=>e(o).update(i).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=i=>e(i),Object.assign(n,t),Object.freeze(n)}var Hw=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function kC(e,t,n){return e&t^~e&n}function CC(e,t,n){return e&t^e&n^t&n}var Vw=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,r){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=lf(this.buffer)}update(e){Iw(this),qw(e);let{view:t,buffer:n,blockLen:r}=this,i=e.length,o=!1;for(let a=0;a<i;){let s=Math.min(r-this.pos,i-a);if(s===r){let c=lf(e);for(;r<=i-a;a+=r)this.process(c,a);o=!0;continue}n.set(a===0&&s===i?e:e.subarray(a,a+s),this.pos),this.pos+=s,a+=s,this.pos===r&&(this.process(t,0),this.pos=0,o=!0)}return this.length+=e.length,o&&this.roundClean(),this}digestInto(e){Iw(this),TC(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:o}=this;t[o++]=128,t.fill(0,o),this.padOffset>r-o&&(this.process(n,0),t.fill(0)),yC(n,r-8,this.length*8,i),this.process(n,0),this.roundClean();let a=e===t?n:lf(e),s=this.outputLen,c=s/4,d=this.get();if(s%4||c>d.length)throw new Error("invalid outputLen");for(let l=0;l<c;l++)a.setUint32(4*l,d[l],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneIntoMeta(e){let{buffer:t,length:n,finished:r,destroyed:i,pos:o}=this;return e.destroyed=i,e.finished=r,e.length=n,e.pos=o,o&&e.buffer.set(t),e}clone(){return this._cloneInto()}},RC=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),xC=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),OC=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Ar=new Uint32Array(64),NC=class extends Vw{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:n,D:r,E:i,F:o,G:a,H:s}=this;return[e,t,n,r,i,o,a,s]}set(e,t,n,r,i,o,a,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=s|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let l=0;l<16;l++,t+=4)Ar[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let u=Ar[l-15],f=Ar[l-2],h=un(u,7)^un(u,18)^u>>>3,p=un(f,17)^un(f,19)^f>>>10;Ar[l]=p+Ar[l-7]+h+Ar[l-16]|0}let{A:n,B:r,C:i,D:o,E:a,F:s,G:c,H:d}=this;for(let l=0;l<64;l++){let u=un(a,6)^un(a,11)^un(a,25),f=d+u+kC(a,s,c)+OC[l]+Ar[l]|0,p=(un(n,2)^un(n,13)^un(n,22))+CC(n,r,i)|0;d=c,c=s,s=a,a=o+f|0,o=i,i=r,r=n,n=f+p|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,s=s+this.F|0,c=c+this.G|0,d=d+this.H|0,this.set(n,r,i,o,a,s,c,d)}roundClean(){id(Ar)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),id(this.buffer)}},DC=class extends NC{constructor(){super(32,RC)}},$w=hC(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),MC=$w[0],LC=$w[1],Sr=new Uint32Array(80),Ir=new Uint32Array(80),JC=class extends Vw{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(e,t){super(128,e,16,!1),this.Ah=t[0]|0,this.Al=t[1]|0,this.Bh=t[2]|0,this.Bl=t[3]|0,this.Ch=t[4]|0,this.Cl=t[5]|0,this.Dh=t[6]|0,this.Dl=t[7]|0,this.Eh=t[8]|0,this.El=t[9]|0,this.Fh=t[10]|0,this.Fl=t[11]|0,this.Gh=t[12]|0,this.Gl=t[13]|0,this.Hh=t[14]|0,this.Hl=t[15]|0}get(){let{Ah:e,Al:t,Bh:n,Bl:r,Ch:i,Cl:o,Dh:a,Dl:s,Eh:c,El:d,Fh:l,Fl:u,Gh:f,Gl:h,Hh:p,Hl:m}=this;return[e,t,n,r,i,o,a,s,c,d,l,u,f,h,p,m]}set(e,t,n,r,i,o,a,s,c,d,l,u,f,h,p,m){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=r|0,this.Ch=i|0,this.Cl=o|0,this.Dh=a|0,this.Dl=s|0,this.Eh=c|0,this.El=d|0,this.Fh=l|0,this.Fl=u|0,this.Gh=f|0,this.Gl=h|0,this.Hh=p|0,this.Hl=m|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let _=0;_<16;_++,t+=4)Sr[_]=e.getUint32(t),Ir[_]=e.getUint32(t+=4);for(let _=16;_<80;_++){let A=Sr[_-15]|0,j=Ir[_-15]|0,Q=Mo(A,j,1)^Mo(A,j,8)^vw(A,j,7),X=Lo(A,j,1)^Lo(A,j,8)^bw(A,j,7),H=Sr[_-2]|0,V=Ir[_-2]|0,Ee=Mo(H,V,19)^Zc(H,V,61)^vw(H,V,6),Ge=Lo(H,V,19)^Qc(H,V,61)^bw(H,V,6),jt=EC(X,Ge,Ir[_-7],Ir[_-16]),ee=vC(jt,Q,Ee,Sr[_-7],Sr[_-16]);Sr[_]=ee|0,Ir[_]=jt|0}let{Ah:n,Al:r,Bh:i,Bl:o,Ch:a,Cl:s,Dh:c,Dl:d,Eh:l,El:u,Fh:f,Fl:h,Gh:p,Gl:m,Hh:w,Hl:v}=this;for(let _=0;_<80;_++){let A=Mo(l,u,14)^Mo(l,u,18)^Zc(l,u,41),j=Lo(l,u,14)^Lo(l,u,18)^Qc(l,u,41),Q=l&f^~l&p,X=u&h^~u&m,H=bC(v,j,X,LC[_],Ir[_]),V=AC(H,w,A,Q,MC[_],Sr[_]),Ee=H|0,Ge=Mo(n,r,28)^Zc(n,r,34)^Zc(n,r,39),jt=Lo(n,r,28)^Qc(n,r,34)^Qc(n,r,39),ee=n&i^n&a^i&a,On=r&o^r&s^o&s;w=p|0,v=m|0,p=f|0,m=h|0,f=l|0,h=u|0,{h:l,l:u}=Un(c|0,d|0,V|0,Ee|0),c=a|0,d=s|0,a=i|0,s=o|0,i=n|0,o=r|0;let qt=_C(Ee,jt,On);n=wC(qt,V,Ge,ee),r=qt|0}({h:n,l:r}=Un(this.Ah|0,this.Al|0,n|0,r|0)),{h:i,l:o}=Un(this.Bh|0,this.Bl|0,i|0,o|0),{h:a,l:s}=Un(this.Ch|0,this.Cl|0,a|0,s|0),{h:c,l:d}=Un(this.Dh|0,this.Dl|0,c|0,d|0),{h:l,l:u}=Un(this.Eh|0,this.El|0,l|0,u|0),{h:f,l:h}=Un(this.Fh|0,this.Fl|0,f|0,h|0),{h:p,l:m}=Un(this.Gh|0,this.Gl|0,p|0,m|0),{h:w,l:v}=Un(this.Hh|0,this.Hl|0,w|0,v|0),this.set(n,r,i,o,a,s,c,d,l,u,f,h,p,m,w,v)}roundClean(){id(Sr,Ir)}destroy(){this.destroyed=!0,id(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},UC=class extends JC{constructor(){super(64,xC)}},Ww=Kw(()=>new DC,Hw(1)),jC=Kw(()=>new UC,Hw(3)),Tw=jw;Tw.sha512||(Tw.sha512=e=>jC(e));function qC(e,t){return sC(t,e)}function KC(e,t,n){return lC(t,n,e)}function HC(e,t){return aC(t,e)}function VC(e,t,n){return dC(t,n,e)}var YK=vf.bytesToHex,zK=vf.hexToBytes,XK=vf.concatBytes;function $C(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function WC(e){return $C(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function FC(e){if(e.kty!=="OKP")throw new Error(`computeJkt expects an OKP JWK; got kty="${e.kty}"`);let t=JSON.stringify({crv:e.crv,kty:e.kty,x:e.x});return WC(Ww(new TextEncoder().encode(t)))}});var is=y(ad=>{"use strict";Object.defineProperty(ad,"__esModule",{value:!0});ad.computeJkt=void 0;var BC=rs();Object.defineProperty(ad,"computeJkt",{enumerable:!0,get:function(){return BC.computeJkt}})});var Uo=y(sd=>{"use strict";Object.defineProperty(sd,"__esModule",{value:!0});sd.prepareRootSignedJws=GC;sd.completeRootSignedJws=YC;var bf=yi();function GC(e,t,n){let r=(0,bf.bytesToBase64Url)(new TextEncoder().encode(JSON.stringify({alg:"EdDSA",kid:t,typ:e}))),i=(0,bf.bytesToBase64Url)(new TextEncoder().encode(JSON.stringify(n)));return{signingInput:`${r}.${i}`}}function YC(e,t,n){if(!(t instanceof Uint8Array)||t.length!==64)throw new Error(`${n} signature must be exactly 64 raw Ed25519 bytes`);return`${e}.${(0,bf.bytesToBase64Url)(t)}`}});var jn=y(E=>{"use strict";Object.defineProperty(E,"__esModule",{value:!0});E.CLOCK_SKEW_SECONDS=E.PUBLIC_MATERIAL_TTL_SECONDS=E.ENROLLMENT_RECEIPT_TTL_SECONDS=E.AGENT_OPERATION_MAX_TTL_SECONDS=E.AGENT_OPERATION_MAX_AGE_SECONDS=E.MAX_OWNER_APPROVED_CHARGE_WINDOW_SECONDS=E.MAX_CHARGE_WINDOW_AFTER_ADMISSION_SECONDS=E.OWNER_STATEMENT_MAX_SECONDS=E.TAP_MAX_AGE_SECONDS=E.POP_MAX_AGE_SECONDS=E.WALLET_BINDING_MAX_TTL_SECONDS=E.RUNTIME_CERTIFICATE_MAX_TTL_SECONDS=E.REGISTRY_ENTRY_MAX_TTL_SECONDS=E.IDENTITY_GATE_ENROLLMENT_MAX_TTL_SECONDS=E.IDENTITY_GATE_AUTHORIZATION_MAX_TTL_SECONDS=E.FINANCIAL_ADMISSION_MAX_TTL_SECONDS=E.ASSOCIATION_ADMISSION_MAX_TTL_SECONDS=E.RUNTIME_ADMISSION_MAX_TTL_SECONDS=E.IDENTITY_SLIP_MAX_TTL_SECONDS=E.RENEWAL_MARGIN_SECONDS=E.TAP_DIRECTORY_RENEW_WINDOW_SECONDS=E.TAP_KEY_TTL_DAYS=E.APP_CONNECT_TTL_SECONDS=E.APP_TOKEN_IDLE_SECONDS=E.CLI_CEREMONY_GRACE_MS=E.CLI_HANDOFF_TTL_MS=E.OWNER_ENROLLMENT_CLAIM_WINDOW_SECONDS=E.OWNER_PAYMENT_APPROVAL_SECONDS=E.RUNTIME_LEASE_REQUEST_MAX_AGE_SECONDS=E.ENROLLMENT_CHALLENGE_MAX_AGE_MS=E.AGENT_PAIRING_TTL_SECONDS=E.HOSTED_CONNECTOR_PROOF_TTL_SECONDS=E.RUNTIME_LEASE_MAX_TTL_SECONDS=E.RUNTIME_DELEGATION_MAX_TTL_SECONDS=E.WALLET_GRANT_MAX_TERM_SECONDS=E.WALLET_GRANT_DEFAULT_DAYS=E.CARD_MANDATE_MAX_SECONDS=E.CARD_GRANT_DEFAULT_TERM_SECONDS=E.CARD_GRANT_MAX_TERM_SECONDS=E.DAY_SECONDS=void 0;E.defaultGrantExpiry=zC;E.renewalDue=XC;E.DAY_SECONDS=86400;E.CARD_GRANT_MAX_TERM_SECONDS=7*E.DAY_SECONDS;E.CARD_GRANT_DEFAULT_TERM_SECONDS=E.CARD_GRANT_MAX_TERM_SECONDS-3600;E.CARD_MANDATE_MAX_SECONDS=E.CARD_GRANT_DEFAULT_TERM_SECONDS;E.WALLET_GRANT_DEFAULT_DAYS=30;E.WALLET_GRANT_MAX_TERM_SECONDS=90*E.DAY_SECONDS;function zC(e,t){return t.card?new Date(e.getTime()+E.CARD_GRANT_DEFAULT_TERM_SECONDS*1e3):new Date(e.getTime()+E.WALLET_GRANT_DEFAULT_DAYS*E.DAY_SECONDS*1e3)}E.RUNTIME_DELEGATION_MAX_TTL_SECONDS=366*E.DAY_SECONDS;E.RUNTIME_LEASE_MAX_TTL_SECONDS=300;E.HOSTED_CONNECTOR_PROOF_TTL_SECONDS=300;E.AGENT_PAIRING_TTL_SECONDS=3600;E.ENROLLMENT_CHALLENGE_MAX_AGE_MS=6e4;E.RUNTIME_LEASE_REQUEST_MAX_AGE_SECONDS=60;E.OWNER_PAYMENT_APPROVAL_SECONDS=240;E.OWNER_ENROLLMENT_CLAIM_WINDOW_SECONDS=600;E.CLI_HANDOFF_TTL_MS=15*6e4;E.CLI_CEREMONY_GRACE_MS=45*6e4;E.APP_TOKEN_IDLE_SECONDS=90*E.DAY_SECONDS;E.APP_CONNECT_TTL_SECONDS=900;E.TAP_KEY_TTL_DAYS=365;E.TAP_DIRECTORY_RENEW_WINDOW_SECONDS=30*E.DAY_SECONDS;E.RENEWAL_MARGIN_SECONDS=30*E.DAY_SECONDS;function XC(e){let t=e.marginSeconds??E.RENEWAL_MARGIN_SECONDS,n=Math.max(e.nowSec,e.grantEndSec??e.nowSec)+t,r=e.maxLifetimeSeconds===void 0?n:e.nowSec+e.maxLifetimeSeconds-t;return e.endSec<=Math.min(n,r)}E.IDENTITY_SLIP_MAX_TTL_SECONDS=60;E.RUNTIME_ADMISSION_MAX_TTL_SECONDS=600;E.ASSOCIATION_ADMISSION_MAX_TTL_SECONDS=60;E.FINANCIAL_ADMISSION_MAX_TTL_SECONDS=60;E.IDENTITY_GATE_AUTHORIZATION_MAX_TTL_SECONDS=366*E.DAY_SECONDS;E.IDENTITY_GATE_ENROLLMENT_MAX_TTL_SECONDS=366*E.DAY_SECONDS;E.REGISTRY_ENTRY_MAX_TTL_SECONDS=366*E.DAY_SECONDS;E.RUNTIME_CERTIFICATE_MAX_TTL_SECONDS=E.DAY_SECONDS;E.WALLET_BINDING_MAX_TTL_SECONDS=366*E.DAY_SECONDS;E.POP_MAX_AGE_SECONDS=120;E.TAP_MAX_AGE_SECONDS=480;E.OWNER_STATEMENT_MAX_SECONDS=300;E.MAX_CHARGE_WINDOW_AFTER_ADMISSION_SECONDS=30;E.MAX_OWNER_APPROVED_CHARGE_WINDOW_SECONDS=300;E.AGENT_OPERATION_MAX_AGE_SECONDS=300;E.AGENT_OPERATION_MAX_TTL_SECONDS=600;E.ENROLLMENT_RECEIPT_TTL_SECONDS=366*E.DAY_SECONDS;E.PUBLIC_MATERIAL_TTL_SECONDS=300;E.CLOCK_SKEW_SECONDS=30});var os=y(Te=>{"use strict";Object.defineProperty(Te,"__esModule",{value:!0});Te.HOSTED_RUNTIME_CERTIFICATE_PURPOSES=Te.RUNTIME_CERTIFICATE_PURPOSES=Te.CARD_RUNTIME_CERTIFICATE_MAX_TTL_SECONDS=Te.RUNTIME_CERTIFICATE_VERSION=Te.RUNTIME_CERTIFICATE_TYP=Te.RUNTIME_CERTIFICATE_MAX_TTL_SECONDS=void 0;Te.runtimeCertificateMaxTtl=zw;Te.isCanonicalBase64Url32=Sf;Te.prepareRuntimeCertificate=oR;var Bw=yi(),Gw=is(),ZC=Uo(),QC=jn();Object.defineProperty(Te,"RUNTIME_CERTIFICATE_MAX_TTL_SECONDS",{enumerable:!0,get:function(){return QC.RUNTIME_CERTIFICATE_MAX_TTL_SECONDS}});var Yw=jn();Te.RUNTIME_CERTIFICATE_TYP="visa-agent-runtime-cert+jwt";Te.RUNTIME_CERTIFICATE_VERSION=1;Te.CARD_RUNTIME_CERTIFICATE_MAX_TTL_SECONDS=366*24*60*60;function zw(e){return e.length===1&&e[0]==="card:vic"?Te.CARD_RUNTIME_CERTIFICATE_MAX_TTL_SECONDS:Yw.RUNTIME_CERTIFICATE_MAX_TTL_SECONDS}Te.RUNTIME_CERTIFICATE_PURPOSES=["tap","subway","card:vic","wallet:x402"];Te.HOSTED_RUNTIME_CERTIFICATE_PURPOSES=["card:vic","wallet:x402","tap"];var eR=new Set(Te.RUNTIME_CERTIFICATE_PURPOSES),Af=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,tR=/^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/;function Sf(e){if(typeof e!="string"||!tR.test(e))return!1;let t=(0,Bw.base64UrlToBytes)(e);return t.length===32&&(0,Bw.bytesToBase64Url)(t)===e}function nR(e){return{kty:"OKP",crv:"Ed25519",x:e.x}}function rR(e){if(!Array.isArray(e)||e.length===0)throw new Error("runtime certificate requires at least one purpose");let t=[...new Set(e)];if(t.length!==e.length||t.some(n=>!eR.has(n)))throw new Error("runtime certificate purposes must be unique supported values");return t.sort()}function iR(e,t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative unix-seconds integer`)}function oR(e){let t=e.nowSec??Math.floor(Date.now()/1e3),n=e.ttlSeconds??Yw.RUNTIME_CERTIFICATE_MAX_TTL_SECONDS,r=zw(e.purposes),i=e.certificateId??globalThis.crypto.randomUUID();if(iR("nowSec",t),!Number.isSafeInteger(n)||n<=0||n>r)throw new Error(`runtime certificate ttlSeconds must be in (0, ${r}]`);if(!Af.test(e.agentId)||!Af.test(e.runtimeId))throw new Error("runtime certificate agentId/runtimeId must be canonical UUIDs");if(!Af.test(i))throw new Error("runtime certificate certificateId must be a canonical UUID");if(!Sf(e.rootJkt))throw new Error("runtime certificate rootJkt must be a canonical RFC 7638 thumbprint");if(!e.rootKid||e.rootKid.length>256)throw new Error("runtime certificate rootKid must be a bounded non-empty identifier");if((0,Gw.computeJkt)(e.rootPublicJwk)!==e.rootJkt)throw new Error("runtime certificate signer public key does not match rootJkt");let a=nR(e.runtimePublicJwk);if(!Sf(a.x))throw new Error("runtime certificate child key must be canonical Ed25519");let s=(0,Gw.computeJkt)(a);if(s===e.rootJkt)throw new Error("runtime certificate child key must differ from the identity root");let c={v:Te.RUNTIME_CERTIFICATE_VERSION,iss:e.rootJkt,sub:e.agentId,jti:i,runtimeId:e.runtimeId,cnf:{jwk:a,jkt:s},purposes:rR(e.purposes),iat:t,nbf:t,exp:t+n};return{...(0,ZC.prepareRootSignedJws)(Te.RUNTIME_CERTIFICATE_TYP,e.rootKid,c),claims:c}}});var Tf=y(If=>{"use strict";Object.defineProperty(If,"__esModule",{value:!0});If.signJwtWithSigner=aR;var Zw=yi(),Xw=e=>(0,Zw.bytesToBase64Url)(new TextEncoder().encode(JSON.stringify(e)));async function aR(e,t,n){let r=Xw({alg:"EdDSA",kid:e.kid,typ:t.typ}),i=Xw(n),o=`${r}.${i}`,a=await e.sign(new TextEncoder().encode(o));if(!(a instanceof Uint8Array)||a.length!==64)throw new Error(`signer.sign must return a raw 64-byte Ed25519 signature; got ${a instanceof Uint8Array?`${a.length} bytes`:typeof a} (check the vault adapter is not DER-wrapping or re-encoding)`);return`${o}.${(0,Zw.bytesToBase64Url)(a)}`}});var as=y(jo=>{"use strict";Object.defineProperty(jo,"__esModule",{value:!0});jo.POP_JWT_TYP=void 0;jo.createPopProofWithSigner=cR;var sR=Tf();jo.POP_JWT_TYP="visa-agent-pop+jwt";async function cR(e,t){let r={cnf:{jwk:{kty:e.publicJwk.kty,crv:e.publicJwk.crv,x:e.publicJwk.x}},nonce:t.nonce,aud:t.audience,iat:t.nowSec};return t.intentHash!==void 0&&(r.int=t.intentHash),t.runtimeCertificate!==void 0&&(r.rkc=t.runtimeCertificate),(0,sR.signJwtWithSigner)(e,{typ:jo.POP_JWT_TYP},r)}});var ss=y(st=>{"use strict";Object.defineProperty(st,"__esModule",{value:!0});st.WALLET_BINDING_TYP=st.RUNTIME_AUTHORITY_CLOCK_SKEW_SECONDS=st.RUNTIME_LEASE_MAX_TTL_SECONDS=st.RUNTIME_DELEGATION_MAX_TTL_SECONDS=st.RUNTIME_LEASE_SIGNING_MODES=st.RUNTIME_DELEGATION_TYP=void 0;st.RUNTIME_DELEGATION_TYP="visa-agent-runtime-delegation+jwt";st.RUNTIME_LEASE_SIGNING_MODES=["eip3009:exact","permit2:upto"];var Qw=jn();Object.defineProperty(st,"RUNTIME_DELEGATION_MAX_TTL_SECONDS",{enumerable:!0,get:function(){return Qw.RUNTIME_DELEGATION_MAX_TTL_SECONDS}});Object.defineProperty(st,"RUNTIME_LEASE_MAX_TTL_SECONDS",{enumerable:!0,get:function(){return Qw.RUNTIME_LEASE_MAX_TTL_SECONDS}});var dR=jn();st.RUNTIME_AUTHORITY_CLOCK_SKEW_SECONDS=dR.CLOCK_SKEW_SECONDS;st.WALLET_BINDING_TYP="visa-agent-wallet-binding+jwt"});var tE=y(It=>{"use strict";Object.defineProperty(It,"__esModule",{value:!0});It.RUNTIME_LEASE_REQUEST_MAX_AGE_SECONDS=It.RUNTIME_LEASE_REQUEST_AUDIENCE=It.RUNTIME_LEASE_REQUEST_VERSION=void 0;It.runtimeLeaseRequestIntentHash=eE;It.createRuntimeLeaseRequestProofWithSigner=_R;var lR=rs(),uR=yi(),fR=as(),pR=ss(),hR=jn();Object.defineProperty(It,"RUNTIME_LEASE_REQUEST_MAX_AGE_SECONDS",{enumerable:!0,get:function(){return hR.RUNTIME_LEASE_REQUEST_MAX_AGE_SECONDS}});It.RUNTIME_LEASE_REQUEST_VERSION=1;It.RUNTIME_LEASE_REQUEST_AUDIENCE="visa-runtime-lease-requests:v1";var mR=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,gR=new Set(pR.RUNTIME_LEASE_SIGNING_MODES);function Pf(e,t){if(!mR.test(t))throw new Error(`${e} must be a canonical UUID`)}function yR(e){if(Pf("agentId",e.agentId),Pf("runtimeId",e.runtimeId),Pf("requestId",e.requestId),!gR.has(e.signingMode))throw new Error("runtime lease request signingMode is unsupported");return{v:It.RUNTIME_LEASE_REQUEST_VERSION,agentId:e.agentId,runtimeId:e.runtimeId,requestId:e.requestId,signingMode:e.signingMode}}function eE(e){return(0,uR.bytesToBase64Url)((0,lR.sha256)(new TextEncoder().encode(JSON.stringify(yR(e)))))}function _R(e,t){if(!Number.isSafeInteger(t.nowSec)||t.nowSec<0)throw new Error("runtime lease request nowSec must be a non-negative safe integer");return(0,fR.createPopProofWithSigner)(e,{nonce:t.requestId,audience:It.RUNTIME_LEASE_REQUEST_AUDIENCE,nowSec:t.nowSec,intentHash:eE(t)})}});var qo=y(yt=>{"use strict";var wR=yt&&yt.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),cs=yt&&yt.__exportStar||function(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&wR(t,e,n)};Object.defineProperty(yt,"__esModule",{value:!0});yt.computeJkt=void 0;cs(os(),yt);cs(tE(),yt);cs(as(),yt);cs(Tf(),yt);cs(ss(),yt);var ER=is();Object.defineProperty(yt,"computeJkt",{enumerable:!0,get:function(){return ER.computeJkt}})});var xf=y(Ce=>{"use strict";Object.defineProperty(Ce,"__esModule",{value:!0});Ce.CanonicalJsonError=Ce.CANONICAL_OPAQUE_ID_MAX_BYTES=Ce.CANONICAL_OPAQUE_ID_RE=Ce.CANONICAL_OPAQUE_ID_PATTERN=void 0;Ce.utf8ByteLength=Rf;Ce.isCanonicalText=nE;Ce.compareCanonicalKeys=rE;Ce.isCanonicalOpaqueId=iE;Ce.assertCanonicalOpaqueId=bR;Ce.canonicalJsonExact=Cf;Ce.isValidCalendarDateTime=SR;Ce.CANONICAL_OPAQUE_ID_PATTERN="^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$";Ce.CANONICAL_OPAQUE_ID_RE=new RegExp(Ce.CANONICAL_OPAQUE_ID_PATTERN);Ce.CANONICAL_OPAQUE_ID_MAX_BYTES=128;var vR=/[\u0000-\u001f\u007f\u2028\u2029]/,kf=new TextEncoder;function Rf(e){return kf.encode(e).length}function nE(e,t){return typeof e=="string"&&e.length>0&&Rf(e)<=t&&e.trim()===e&&e.normalize("NFC")===e&&!vR.test(e)}function rE(e,t){let n=kf.encode(e),r=kf.encode(t),i=Math.min(n.length,r.length);for(let o=0;o<i;o+=1)if(n[o]!==r[o])return n[o]-r[o];return n.length-r.length}function iE(e){return typeof e=="string"&&Rf(e)<=Ce.CANONICAL_OPAQUE_ID_MAX_BYTES&&Ce.CANONICAL_OPAQUE_ID_RE.test(e)}function bR(e,t="value"){if(!iE(e))throw new Error(`${t} must be a canonical opaque id (max 128 ASCII bytes)`)}var AR=/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/,fn=class extends Error{constructor(t){super(t),this.name="CanonicalJsonError"}};Ce.CanonicalJsonError=fn;function Cf(e,t=0){if(t>16)throw new fn("nesting is deeper than 16");if(e===null||typeof e=="boolean")return JSON.stringify(e);if(typeof e=="string"){if(AR.test(e))throw new fn("text is not valid Unicode");return JSON.stringify(e)}if(typeof e=="number"){if(!Number.isSafeInteger(e)||Object.is(e,-0))throw new fn("numbers must be whole and at most 2^53 - 1; put amounts and decimals in strings");return JSON.stringify(e)}if(Array.isArray(e)){if(e.length>1024)throw new fn("an array has more than 1024 items");return`[${e.map(r=>Cf(r,t+1)).join(",")}]`}if(typeof e!="object"||Object.getPrototypeOf(e)!==Object.prototype)throw new fn("only JSON objects, arrays, strings, whole numbers and booleans");let n=Object.keys(e);if(n.length>512)throw new fn("an object has more than 512 keys");for(let r of n)if(!nE(r,128))throw new fn("keys must be non-empty trimmed NFC text of at most 128 bytes");return`{${n.sort(rE).map(r=>`${JSON.stringify(r)}:${Cf(e[r],t+1)}`).join(",")}}`}function SR(e,t,n,r,i,o){let a=new Date(0);return a.setUTCFullYear(e,t-1,n),a.setUTCHours(r,i,o,0),e!==0&&a.getUTCFullYear()===e&&a.getUTCMonth()===t-1&&a.getUTCDate()===n&&a.getUTCHours()===r&&a.getUTCMinutes()===i&&a.getUTCSeconds()===o}});var Pr=y(Vt=>{"use strict";Object.defineProperty(Vt,"__esModule",{value:!0});Vt.AgentOperationContractError=Vt.AGENT_OPERATION_CONTRACT_ERROR_CODES=void 0;Vt.record=aE;Vt.bounded=sE;Vt.canonicalJsonValue=cE;Vt.canonicalJson=IR;Vt.canonicalEnvelopeJson=TR;var oE=xf();Vt.AGENT_OPERATION_CONTRACT_ERROR_CODES=["commitment_mismatch","intent_mismatch","invalid_amount","invalid_contract","invalid_currency","invalid_effect","invalid_evidence","invalid_principal","invalid_window","settlement_amount_invalid","unsupported_version"];var qn=class extends Error{code;constructor(t,n){super(n),this.code=t,this.name="AgentOperationContractError"}};Vt.AgentOperationContractError=qn;function aE(e,t){if(typeof e!="object"||e===null||Array.isArray(e))throw new qn("invalid_contract",`${t} must be an object`);return e}function sE(e,t,n=4096){if(!(0,oE.isCanonicalText)(e,n))throw new qn("invalid_contract",`${t} is not bounded canonical text`);return e}function cE(e,t=0){return cd(e,t,16)}function cd(e,t,n){if(t>n)throw new qn("invalid_contract","payload nesting is too deep");if(e===null||typeof e=="string"||typeof e=="boolean"||typeof e=="number"&&Number.isSafeInteger(e)&&!Object.is(e,-0))return e;if(typeof e=="number")throw new qn("invalid_contract","JSON numbers must be safe canonical integers; use strings for larger or decimal values");if(Array.isArray(e)){if(e.length>1024)throw new qn("invalid_contract","payload array is too large");return e.map(o=>cd(o,t+1,n))}let r=aE(e,"payload"),i=Object.entries(r);if(i.length>512)throw new qn("invalid_contract","payload object is too large");return Object.fromEntries(i.sort(([o],[a])=>(0,oE.compareCanonicalKeys)(o,a)).map(([o,a])=>[sE(o,"payload key",128),cd(a,t+1,n)]))}function IR(e){return JSON.stringify(cE(e))}function TR(e){return JSON.stringify(cd(e,0,64))}});var Kn=y(ae=>{"use strict";Object.defineProperty(ae,"__esModule",{value:!0});ae.EXECUTOR_BINDING_VERSION=ae.EXECUTION_EVIDENCE_VERSION=ae.AGENT_OPERATION_RESULT_VERSION=ae.AGENT_OPERATION_VERSION=ae.canonicalJsonValue=ae.canonicalJson=ae.AgentOperationContractError=ae.AGENT_OPERATION_CONTRACT_ERROR_CODES=ae.canonicalEnvelopeJson=void 0;ae.agentOperationIntentPreimage=xR;ae.parseAgentMoneyEconomics=uE;ae.parseAgentOperationStructure=fE;ae.parseExecutionEvidence=DR;ae.parsePreparedAgentOperationStructure=MR;ae.agentOperationPopSigningInput=LR;var U=Pr(),Of=jn(),ds=Pr();Object.defineProperty(ae,"canonicalEnvelopeJson",{enumerable:!0,get:function(){return ds.canonicalEnvelopeJson}});Object.defineProperty(ae,"AGENT_OPERATION_CONTRACT_ERROR_CODES",{enumerable:!0,get:function(){return ds.AGENT_OPERATION_CONTRACT_ERROR_CODES}});Object.defineProperty(ae,"AgentOperationContractError",{enumerable:!0,get:function(){return ds.AgentOperationContractError}});Object.defineProperty(ae,"canonicalJson",{enumerable:!0,get:function(){return ds.canonicalJson}});Object.defineProperty(ae,"canonicalJsonValue",{enumerable:!0,get:function(){return ds.canonicalJsonValue}});ae.AGENT_OPERATION_VERSION=1;ae.AGENT_OPERATION_RESULT_VERSION=1;ae.EXECUTION_EVIDENCE_VERSION=1;ae.EXECUTOR_BINDING_VERSION=1;var PR=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,kR=/^[A-Za-z0-9_-]{43}$/,CR=/^[a-z][a-z0-9]*(?:[._:-][a-z0-9]+)*$/,RR=/^[A-Z][A-Z0-9]{2,11}$/,lE=96*1024,Nf=9223372036854775807n;function Tt(e,t,n=[]){let r=new Set([...t,...n]);if(t.some(i=>!(i in e))||Object.keys(e).some(i=>!r.has(i)))throw new U.AgentOperationContractError("invalid_contract","contract contains missing or unknown fields")}function Ko(e,t){let n=(0,U.bounded)(e,t,36).toLowerCase();if(!PR.test(n))throw new U.AgentOperationContractError("invalid_contract",`${t} must be a UUID`);return n}function pn(e,t){let n=(0,U.bounded)(e,t,43);if(!kR.test(n)||!/[AEIMQUYcgkosw048]$/.test(n))throw new U.AgentOperationContractError("invalid_contract",`${t} must be a canonical 32-byte hash`);return n}function dd(e,t){let n=(0,U.bounded)(e,t,128);if(!CR.test(n))throw new U.AgentOperationContractError("invalid_contract",`${t} must be a stable lowercase token`);return n}function dE(e,t){let n=(0,U.bounded)(e,t,32),r=Date.parse(n);if(!Number.isFinite(r)||new Date(r).toISOString()!==n)throw new U.AgentOperationContractError("invalid_contract",`${t} must be canonical ISO-8601`);return n}function xR(e){let t={domain:"visa.agent-operation-intent.v1",operationId:e.operationId,idempotencyKey:e.idempotencyKey,agentId:e.agentId,runtimeId:e.runtimeId,rail:e.rail,effect:e.effect,execution:{adapter:e.execution.adapter,commitment:e.execution.commitment,payloadHash:e.execution.payloadHash},createdAt:e.createdAt,expiresAt:e.expiresAt};return(0,U.canonicalJson)(t)}function OR(e){let t=(0,U.record)(e,"principal");if(t.kind==="identity_pop")return Tt(t,["kind","popJwt","keyJkt"]),{kind:t.kind,popJwt:(0,U.bounded)(t.popJwt,"popJwt",16384),keyJkt:pn(t.keyJkt,"keyJkt")};if(t.kind==="certified_runtime_pop")return Tt(t,["kind","popJwt","runtimeCertificate","rootJkt","childJkt"]),{kind:t.kind,popJwt:(0,U.bounded)(t.popJwt,"popJwt",16384),runtimeCertificate:(0,U.bounded)(t.runtimeCertificate,"runtimeCertificate",32768),rootJkt:pn(t.rootJkt,"rootJkt"),childJkt:pn(t.childJkt,"childJkt")};if(t.kind==="delegated_runtime_lease_pop"){if(Tt(t,["kind","v","popJwt","delegation","lease","rootJkt","runtimeJkt"]),t.v!==2)throw new U.AgentOperationContractError("invalid_principal","delegated runtime lease principal must use version 2");return{kind:t.kind,v:t.v,popJwt:(0,U.bounded)(t.popJwt,"popJwt",16384),delegation:(0,U.bounded)(t.delegation,"delegation",32768),lease:(0,U.bounded)(t.lease,"lease",32768),rootJkt:pn(t.rootJkt,"rootJkt"),runtimeJkt:pn(t.runtimeJkt,"runtimeJkt")}}if(t.kind==="tap_signature")return Tt(t,["kind","signature","runtimeCertificate","signedPayload"]),{kind:t.kind,signature:(0,U.bounded)(t.signature,"signature",2048),runtimeCertificate:(0,U.bounded)(t.runtimeCertificate,"runtimeCertificate",32768),signedPayload:pn(t.signedPayload,"signedPayload")};throw new U.AgentOperationContractError("invalid_principal","unsupported principal proof kind")}function uE(e){let t=(0,U.record)(e,"money economics");Tt(t,["amountMicros","currency","merchant"]);let n=(0,U.bounded)(t.amountMicros,"amountMicros",40);if(!/^[1-9][0-9]*$/.test(n)||BigInt(n)>Nf)throw new U.AgentOperationContractError("invalid_amount","amountMicros must be positive and canonical");let r=(0,U.bounded)(t.currency,"currency",12);if(!RR.test(r))throw new U.AgentOperationContractError("invalid_currency","currency must be canonical");let i=(0,U.record)(t.merchant,"merchant");return Tt(i,["id"],["name","url"]),{amountMicros:n,currency:r,merchant:{id:(0,U.bounded)(i.id,"merchant.id",512),...i.name===void 0?{}:{name:(0,U.bounded)(i.name,"merchant.name",255)},...i.url===void 0?{}:{url:(0,U.bounded)(i.url,"merchant.url",2048)}}}}function NR(e){let t=(0,U.record)(e,"effect");if(t.kind==="money"){Tt(t,["kind","amountMicros","currency","merchant","grantId","budgetEpochId"],["maxAmountMicros"]);let n=uE({amountMicros:t.amountMicros,currency:t.currency,merchant:t.merchant}),r;if(t.maxAmountMicros!==void 0&&(r=(0,U.bounded)(t.maxAmountMicros,"maxAmountMicros",40),!/^[1-9][0-9]*$/.test(r)||BigInt(r)>Nf))throw new U.AgentOperationContractError("invalid_amount","maxAmountMicros must be positive and canonical");return{kind:t.kind,...n,grantId:Ko(t.grantId,"grantId"),budgetEpochId:Ko(t.budgetEpochId,"budgetEpochId"),...r===void 0?{}:{maxAmountMicros:r}}}if(t.kind==="resource")return Tt(t,["kind","resource","action","audience"]),{kind:t.kind,resource:(0,U.bounded)(t.resource,"resource",4096),action:dd(t.action,"action"),audience:(0,U.bounded)(t.audience,"audience",255)};throw new U.AgentOperationContractError("invalid_effect","unsupported operation effect")}function fE(e,t=Date.now()){let n=(0,U.record)(e,"operation");if(Tt(n,["v","operationId","idempotencyKey","agentId","runtimeId","rail","intentHash","principal","effect","execution","createdAt","expiresAt"]),n.v!==ae.AGENT_OPERATION_VERSION)throw new U.AgentOperationContractError("unsupported_version","unsupported operation version");let r=(0,U.record)(n.execution,"execution");Tt(r,["adapter","commitment","payloadHash","payload"]);let i=(0,U.canonicalJsonValue)(r.payload);if(new TextEncoder().encode(JSON.stringify(i)).length>lE)throw new U.AgentOperationContractError("invalid_contract","execution payload is too large");let o=pn(r.commitment,"execution.commitment"),a=pn(r.payloadHash,"execution.payloadHash"),s=dE(n.createdAt,"createdAt"),c=dE(n.expiresAt,"expiresAt");if(!Number.isFinite(t)||Date.parse(s)>t+Of.CLOCK_SKEW_SECONDS*1e3||Date.parse(s)<t-Of.AGENT_OPERATION_MAX_AGE_SECONDS*1e3||Date.parse(c)<=t||Date.parse(c)<=Date.parse(s)||Date.parse(c)-Date.parse(s)>Of.AGENT_OPERATION_MAX_TTL_SECONDS*1e3)throw new U.AgentOperationContractError("invalid_window","operation validity window is not currently usable");let d={v:ae.AGENT_OPERATION_VERSION,operationId:Ko(n.operationId,"operationId"),idempotencyKey:(0,U.bounded)(n.idempotencyKey,"idempotencyKey",255),agentId:Ko(n.agentId,"agentId"),runtimeId:Ko(n.runtimeId,"runtimeId"),rail:dd(n.rail,"rail"),intentHash:pn(n.intentHash,"intentHash"),principal:OR(n.principal),effect:NR(n.effect),execution:{adapter:dd(r.adapter,"execution.adapter"),commitment:o,payloadHash:a,payload:i},createdAt:s,expiresAt:c};if(d.rail==="wallet:x402"&&d.effect.kind==="money"&&d.effect.merchant.url===void 0)throw new U.AgentOperationContractError("invalid_contract","merchant.url is required for wallet:x402 operations");if(d.principal.kind==="tap_signature"&&d.principal.signedPayload!==d.intentHash)throw new U.AgentOperationContractError("intent_mismatch","TAP signedPayload must equal the universal operation intentHash");return d}function DR(e){let t=(0,U.record)(e,"evidence");if(Tt(t,["v","operationId","adapter","outcome","artifactHash","providerReference","proof"],["settledMicros"]),t.v!==ae.EXECUTION_EVIDENCE_VERSION||t.outcome!=="committed"&&t.outcome!=="released")throw new U.AgentOperationContractError("invalid_evidence","unsupported evidence version or outcome");let n;if(t.settledMicros!==void 0){if(n=(0,U.bounded)(t.settledMicros,"settledMicros",40),!/^(?:0|[1-9][0-9]*)$/.test(n)||BigInt(n)>Nf)throw new U.AgentOperationContractError("invalid_evidence","settledMicros is not canonical");if(t.outcome==="released"&&n!=="0")throw new U.AgentOperationContractError("settlement_amount_invalid","released evidence must settle zero")}let r=(0,U.canonicalJsonValue)(t.proof);if(new TextEncoder().encode(JSON.stringify(r)).length>lE)throw new U.AgentOperationContractError("invalid_evidence","evidence proof is too large");return{v:ae.EXECUTION_EVIDENCE_VERSION,operationId:Ko(t.operationId,"operationId"),adapter:dd(t.adapter,"adapter"),outcome:t.outcome,artifactHash:pn(t.artifactHash,"artifactHash"),...n===void 0?{}:{settledMicros:n},providerReference:(0,U.bounded)(t.providerReference,"providerReference",255),proof:r}}function MR(e,t=Date.now()){let n=(0,U.record)(e,"prepared operation");Tt(n,["operationId","idempotencyKey","agentId","runtimeId","rail","intentHash","effect","execution","createdAt","expiresAt"]);let{v:r,principal:i,...o}=fE({...n,v:1,principal:{kind:"identity_pop",popJwt:"unsigned",keyJkt:"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"}},t);return o}function LR(e){let t=n=>btoa(String.fromCharCode(...new TextEncoder().encode(JSON.stringify(n)))).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"");return`${t({alg:"EdDSA",kid:e.childJkt,typ:"visa-agent-pop+jwt"})}.${t({cnf:{jwk:{kty:e.childPublicJwk.kty,crv:e.childPublicJwk.crv,x:e.childPublicJwk.x}},nonce:e.operationId,aud:"visa-agent-operations:v1",iat:e.issuedAtSec,int:e.intentHash,...e.runtimeCertificate?{rkc:e.runtimeCertificate}:{}})}`}});var WE=y((wH,$E)=>{"use strict";var JR=Object.create,pd=Object.defineProperty,UR=Object.getOwnPropertyDescriptor,SE=Object.getOwnPropertyNames,jR=Object.getPrototypeOf,qR=Object.prototype.hasOwnProperty,KR=(e,t)=>function(){try{return t||(0,e[SE(e)[0]])((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},HR=(e,t)=>{for(var n in t)pd(e,n,{get:t[n],enumerable:!0})},IE=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of SE(t))!qR.call(e,i)&&i!==n&&pd(e,i,{get:()=>t[i],enumerable:!(r=UR(t,i))||r.enumerable});return e},VR=(e,t,n)=>(n=e!=null?JR(jR(e)):{},IE(t||!e||!e.__esModule?pd(n,"default",{value:e,enumerable:!0}):n,e)),$R=e=>IE(pd({},"__esModule",{value:!0}),e),WR=KR({"../shared/dist/canonical-contract.js"(e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.CanonicalJsonError=e.CANONICAL_OPAQUE_ID_MAX_BYTES=e.CANONICAL_OPAQUE_ID_RE=e.CANONICAL_OPAQUE_ID_PATTERN=void 0,e.utf8ByteLength=r,e.isCanonicalText=i,e.compareCanonicalKeys=o,e.isCanonicalOpaqueId=a,e.assertCanonicalOpaqueId=s,e.canonicalJsonExact=l,e.isValidCalendarDateTime=u,e.CANONICAL_OPAQUE_ID_PATTERN="^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$",e.CANONICAL_OPAQUE_ID_RE=new RegExp(e.CANONICAL_OPAQUE_ID_PATTERN),e.CANONICAL_OPAQUE_ID_MAX_BYTES=128;var t=/[\u0000-\u001f\u007f\u2028\u2029]/,n=new TextEncoder;function r(f){return n.encode(f).length}function i(f,h){return typeof f=="string"&&f.length>0&&r(f)<=h&&f.trim()===f&&f.normalize("NFC")===f&&!t.test(f)}function o(f,h){let p=n.encode(f),m=n.encode(h),w=Math.min(p.length,m.length);for(let v=0;v<w;v+=1)if(p[v]!==m[v])return p[v]-m[v];return p.length-m.length}function a(f){return typeof f=="string"&&r(f)<=e.CANONICAL_OPAQUE_ID_MAX_BYTES&&e.CANONICAL_OPAQUE_ID_RE.test(f)}function s(f,h="value"){if(!a(f))throw new Error(`${h} must be a canonical opaque id (max 128 ASCII bytes)`)}var c=/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/,d=class extends Error{constructor(f){super(f),this.name="CanonicalJsonError"}};e.CanonicalJsonError=d;function l(f,h=0){if(h>16)throw new d("nesting is deeper than 16");if(f===null||typeof f=="boolean")return JSON.stringify(f);if(typeof f=="string"){if(c.test(f))throw new d("text is not valid Unicode");return JSON.stringify(f)}if(typeof f=="number"){if(!Number.isSafeInteger(f)||Object.is(f,-0))throw new d("numbers must be whole and at most 2^53 - 1; put amounts and decimals in strings");return JSON.stringify(f)}if(Array.isArray(f)){if(f.length>1024)throw new d("an array has more than 1024 items");return`[${f.map(m=>l(m,h+1)).join(",")}]`}if(typeof f!="object"||Object.getPrototypeOf(f)!==Object.prototype)throw new d("only JSON objects, arrays, strings, whole numbers and booleans");let p=Object.keys(f);if(p.length>512)throw new d("an object has more than 512 keys");for(let m of p)if(!i(m,128))throw new d("keys must be non-empty trimmed NFC text of at most 128 bytes");return`{${p.sort(o).map(m=>`${JSON.stringify(m)}:${l(f[m],h+1)}`).join(",")}}`}function u(f,h,p,m,w,v){let _=new Date(0);return _.setUTCFullYear(f,h-1,p),_.setUTCHours(m,w,v,0),f!==0&&_.getUTCFullYear()===f&&_.getUTCMonth()===h-1&&_.getUTCDate()===p&&_.getUTCHours()===m&&_.getUTCMinutes()===w&&_.getUTCSeconds()===v}}}),TE={};HR(TE,{AGENT_AUTHORITY_VALUATION_POLICY:()=>fd,AGENT_AUTHORITY_VERSION:()=>fs,AGENT_AUTHORIZATION_SCOPES:()=>Xf,AGENT_BUDGET_EPOCH_MODES:()=>OE,AGENT_CHANNEL_ASSURANCES:()=>LE,AGENT_CHANNEL_KINDS:()=>DE,AGENT_CHANNEL_STATUSES:()=>ME,AGENT_EXECUTION_READINESS_REASONS:()=>Sx,AGENT_KEY_CUSTODIES:()=>Ix,AGENT_KEY_STATUSES:()=>Tx,AGENT_PAYMENT_MODE_NAMES:()=>bx,AGENT_PAYMENT_RAILS:()=>Kf,AGENT_PAYMENT_SURFACES:()=>qf,USD_MICROS_PER_CENT:()=>zf,VIC_PROCESSOR_ACTIONS:()=>vx,WALLET_GRANT_SCOPE:()=>NE,agentAuthorityGrantHash:()=>qx,authorizationScopeFacts:()=>Jx,canonicalAgentAuthorityGrant:()=>HE,canonicalAgentChannelDescriptor:()=>jx,canonicalPayWithinBudget:()=>KE,canonicalSpendAuthorizationIntent:()=>ep,centsToUsdMicros:()=>Mx,defaultPayWithinBudget:()=>Ax,grantPaymentRails:()=>Zf,isCanonicalBase64Url32:()=>hs,spendAuthorizationIntentHash:()=>VE,usdcAtomicToUsdMicros:()=>Lx,walletAuthorizationRequestHash:()=>Kx});$E.exports=$R(TE);var FR=e=>e/2**32|0,BR=e=>e>>>0;function GR(e,t,n,r){let i=FR(n),o=BR(n);e.setUint32(t,r?o:i,r),e.setUint32(t+4,r?i:o,r)}function pE(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var Lf=e=>e?`"${e}" `:"";function YR(e,t=""){if(typeof e!="number")throw new TypeError(Lf(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(Lf(t)+"expected integer >= 0, got "+e);return e}function PE(e,t,n=""){if(pE(e)&&(t===void 0||e.length===t))return e;t!==void 0&&YR(t,"length");let r=pE(e),i=t!==void 0?` of length ${t}`:"",o=r?`length=${e.length}`:`type=${typeof e}`,a=Lf(n)+"expected Uint8Array"+i+", got "+o;throw r?new RangeError(a):new TypeError(a)}var zR=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},hE=(e,t)=>{zR(e,t);let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw new TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw new TypeError(`"${t}.__proto__" is not allowed`)};function mE(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function XR(e,t){PE(e,void 0,"output");let n=t.outputLen;if(!(e.length>=n))throw new RangeError('"output" expected length >= '+n)}function gE(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Df(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function hn(e,t){return e<<32-t|e>>>t}function ZR(e,t,n="opts"){return hE(e,"defaults"),t!==void 0&&hE(t,n),Object.assign(Object.create(null),e,t)}function QR(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=ZR({},t,"info");let n=(i,o)=>e(o).update(i).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=i=>e(i),Object.assign(n,t),Object.freeze(n)}var ex=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function tx(e,t,n){return e&t^~e&n}function nx(e,t,n){return e&t^e&n^t&n}var rx=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,r){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=Df(this.buffer)}update(e){mE(this),PE(e);let{view:t,buffer:n,blockLen:r}=this,i=e.length,o=!1;for(let a=0;a<i;){let s=Math.min(r-this.pos,i-a);if(s===r){let c=Df(e);for(;r<=i-a;a+=r)this.process(c,a);o=!0;continue}n.set(a===0&&s===i?e:e.subarray(a,a+s),this.pos),this.pos+=s,a+=s,this.pos===r&&(this.process(t,0),this.pos=0,o=!0)}return this.length+=e.length,o&&this.roundClean(),this}digestInto(e){mE(this),XR(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:o}=this;t[o++]=128,t.fill(0,o),this.padOffset>r-o&&(this.process(n,0),t.fill(0)),GR(n,r-8,this.length*8,i),this.process(n,0),this.roundClean();let a=e===t?n:Df(e),s=this.outputLen,c=s/4,d=this.get();if(s%4||c>d.length)throw new Error("invalid outputLen");for(let l=0;l<c;l++)a.setUint32(4*l,d[l],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneIntoMeta(e){let{buffer:t,length:n,finished:r,destroyed:i,pos:o}=this;return e.destroyed=i,e.finished=r,e.length=n,e.pos=o,o&&e.buffer.set(t),e}clone(){return this._cloneInto()}},ix=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ox=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),kr=new Uint32Array(64),ax=class extends rx{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:n,D:r,E:i,F:o,G:a,H:s}=this;return[e,t,n,r,i,o,a,s]}set(e,t,n,r,i,o,a,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=s|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let l=0;l<16;l++,t+=4)kr[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let u=kr[l-15],f=kr[l-2],h=hn(u,7)^hn(u,18)^u>>>3,p=hn(f,17)^hn(f,19)^f>>>10;kr[l]=p+kr[l-7]+h+kr[l-16]|0}let{A:n,B:r,C:i,D:o,E:a,F:s,G:c,H:d}=this;for(let l=0;l<64;l++){let u=hn(a,6)^hn(a,11)^hn(a,25),f=d+u+tx(a,s,c)+ox[l]+kr[l]|0,p=(hn(n,2)^hn(n,13)^hn(n,22))+nx(n,r,i)|0;d=c,c=s,s=a,a=o+f|0,o=i,i=r,r=n,n=f+p|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,s=s+this.F|0,c=c+this.G|0,d=d+this.H|0,this.set(n,r,i,o,a,s,c,d)}roundClean(){gE(kr)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),gE(this.buffer)}},sx=class extends ax{constructor(){super(32,ix)}},$f=QR(()=>new sx,ex(1)),Wf=VR(WR()),Ff=Object.freeze,Vo=0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,Jf=0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,ld=0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Uf=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,jf=0x6666666666666666666666666666666666666666666666666666666666666658n,ud=Vo-1n,cx=Ff({p:Vo,n:Jf,h:8n,a:ud,d:ld,Gx:Uf,Gy:jf}),kE=32,yE=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&e.BYTES_PER_ELEMENT===1,hd=(e,t,n="")=>{if(yE(e)&&(t===void 0||e.length===t))return e;let r=yE(e),i=t!==void 0?` of length ${t}`:"",o=r?`length=${e.length}`:`type=${typeof e}`,a=(n?`"${n}" `:"")+"expected Uint8Array"+i+", got "+o;throw r?new RangeError(a):new TypeError(a)},dx=(e,t="",n)=>Uint8Array.from(hd(e,n,t)),CE=(e,t)=>e.toString(16).padStart(t,"0"),Bf=e=>{let t="";for(let n of hd(e))t+=CE(n,2);return t},Gf=e=>{let t="hex invalid";if(typeof e!="string")throw new TypeError(t);if(e.length%2||!/^[\da-f]*$/i.test(e))throw new RangeError(t);let n=new Uint8Array(e.length/2);for(let r=0,i=0;r<n.length;r++,i+=2){let o=e.charCodeAt(i),a=e.charCodeAt(i+1);n[r]=((o&15)+(o>>6)*9)*16+(a&15)+(a>>6)*9}return n},lx=(...e)=>{let t=0;for(let i of e)t+=hd(i).length;let n=new Uint8Array(t),r=0;for(let i of e)n.set(i,r),r+=i.length;return n},ux=(e=kE)=>{let t=globalThis?.crypto;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined, consider polyfill");return t.getRandomValues(new Uint8Array(e))},Si=(e,t,n,r="bad number: out of range")=>{if(typeof e!="bigint")throw new TypeError(r);if(t<=e&&e<n)return e;throw new RangeError(r)},_e=(e,t=Vo)=>(e%=t)>=0n?e:t+e,_E=(1n<<255n)-1n,D=e=>{if(e<0n)throw new RangeError("negative coordinate");let t=(e>>255n)*19n+(e&_E);return t=(t>>255n)*19n+(t&_E),t%Vo},RE=(e,t)=>{if(e===0n)throw new Error("invert: expected non-zero number");if(t<=1n)throw new Error("invert: expected modulus > 1, got "+t);let n=_e(e,t),r=t,i=0n,o=1n;for(;n!==0n;){let s=r/n,c=r-n*s,d=i-o*s;r=n,n=c,i=o,o=d}if(r!==1n)throw new Error("invert: does not exist");return _e(i,t)},Mf=e=>{if(e instanceof ms)return e;throw new TypeError("Point expected")},xE=2n**256n,ms=class Ii{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,i){let o=xE;this.X=Si(t,0n,o),this.Y=Si(n,0n,o),this.Z=Si(r,1n,o),this.T=Si(i,0n,o),Ff(this)}static CURVE(){return cx}static fromAffine(t){return new Ii(t.x,t.y,1n,D(t.x*t.y))}static fromBytes(t,n=!1){let r=dx(t,"point",kE),i=r[31];r[31]=i&-129;let o=px(r);n||Si(o,0n,Vo);let a=D(o*o),s=_e(a-1n),c=D(ld*a+1n),{isValid:d,value:l}=mx(s,c);if(!d)throw new Error("bad point: y not sqrt");let u=!!(i&128);if(!n&&l===0n&&u)throw new Error("bad point: x==0, isLastByteOdd");return u!==!!(l&1n)&&(l=_e(-l)),new Ii(l,o,1n,D(l*o))}static fromHex(t,n){return Ii.fromBytes(Gf(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=ud,n=ld,r=this;if(r.is0())throw new Error("bad point: ZERO");let{X:i,Y:o,Z:a,T:s}=r,c=D(i*i),d=D(o*o),l=D(a*a),u=D(l*l),f=D(c*t),h=D(l*(f+d)),p=_e(u+D(n*D(c*d)));if(h!==p)throw new Error("bad point: equation left != right (1)");let m=D(i*o),w=D(a*s);if(m!==w)throw new Error("bad point: equation left != right (2)");return this}equals(t){let{X:n,Y:r,Z:i}=this,{X:o,Y:a,Z:s}=Mf(t);return D(n*s)===D(o*i)&&D(r*s)===D(a*i)}is0(){return this.equals(Ti)}negate(){return new Ii(_e(-this.X),this.Y,this.Z,_e(-this.T))}double(){let{X:t,Y:n,Z:r}=this,i=ud,o=D(t*t),a=D(n*n),s=D(2n*r*r),c=D(i*o),d=_e(t+n),l=_e(D(d*d)-o-a),u=_e(c+a),f=_e(u-s),h=_e(c-a),p=D(l*f),m=D(u*h),w=D(l*h),v=D(f*u);return new Ii(p,m,v,w)}add(t){let{X:n,Y:r,Z:i,T:o}=this,{X:a,Y:s,Z:c,T:d}=Mf(t),l=ud,u=ld,f=D(n*a),h=D(r*s),p=D(D(o*u)*d),m=D(i*c),w=_e(D(_e(n+r)*_e(a+s))-f-h),v=_e(m-p),_=_e(m+p),A=_e(h-D(l*f)),j=D(w*v),Q=D(_*A),X=D(w*A),H=D(v*_);return new Ii(j,Q,H,X)}subtract(t){return this.add(Mf(t).negate())}multiply(t,n=!0){if(!n&&t===0n||(Si(t,1n,Jf),!n&&this.is0()))return Ti;if(t===1n)return this;if(this.equals(us))return yx(t).p;let r=Ti,i=us,o=this;for(let a=0;n?a<256:t>0n;a++)t&1n?r=r.add(o):n&&(i=i.add(o)),o=o.double(),t>>=1n;return r}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){let{X:t,Y:n,Z:r}=this;if(this.equals(Ti))return{x:0n,y:1n};let i=RE(r,Vo);if(D(r*i)!==1n)throw new Error("invalid inverse");return{x:D(t*i),y:D(n*i)}}toBytes(){let{x:t,y:n}=this.toAffine(),r=fx(n);return r[31]|=t&1n?128:0,r}toHex(){return Bf(this.toBytes())}clearCofactor(){return this.multiply(8n,!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return this.multiply(Jf/2n,!1).double().add(this).is0()}},us=new ms(Uf,jf,1n,_e(Uf*jf)),Ti=new ms(0n,1n,1n,0n);ms.BASE=us;ms.ZERO=Ti;var fx=e=>Gf(CE(Si(e,0n,xE),64)).reverse(),px=e=>BigInt("0x"+Bf(Uint8Array.from(hd(e)).reverse())),mn=(e,t)=>{let n=e;for(;t-- >0;)n=D(n*n);return n},hx=e=>{let t=D(e*e),n=D(t*e),r=D(mn(n,2)*n),i=D(mn(r,1)*e),o=D(mn(i,5)*i),a=D(mn(o,10)*o),s=D(mn(a,20)*a),c=D(mn(s,40)*s),d=D(mn(c,80)*c),l=D(mn(d,80)*c),u=D(mn(l,10)*o);return D(mn(u,2)*e)},wE=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,mx=(e,t)=>{let n=D(t*D(t*t)),r=D(D(n*n)*t),i=hx(D(e*r)),o=D(e*D(n*i)),a=D(t*D(o*o)),s=o,c=D(o*wE),d=a===e,l=a===_e(-e),u=a===_e(-e*wE);return d&&(o=s),(l||u)&&(o=c),(_e(o)&1n)===1n&&(o=_e(-o)),{isValid:d||l,value:o}},Yf=Ff({bytesToHex:Bf,hexToBytes:Gf,concatBytes:lx,mod:_e,invert:RE,randomBytes:ux}),gx=()=>{let e=[],t=us,n;for(let r=0;r<33;r++){n=t,e.push(n);for(let i=1;i<128;i++)n=n.add(t),e.push(n);t=n.double()}return e},EE=void 0,vE=(e,t)=>{let n=t.negate();return e?n:t},yx=e=>{let t=EE||(EE=gx()),n=Ti,r=us;for(let i=0;i<33;i++){let o=Number(e&255n);e>>=8n,o>128&&(o-=256,e+=1n);let a=i*128,s=a+Math.abs(o)-1,c=i%2!==0,d=o<0;o===0?r=r.add(vE(c,t[a])):n=n.add(vE(d,t[s]))}if(e!==0n)throw new Error("invalid wnaf");return{p:n,f:r}},gH=Yf.bytesToHex,yH=Yf.hexToBytes,_H=Yf.concatBytes;function _x(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function wx(e){let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function md(e){return _x(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Ex(e){let t=e.length%4===0?0:4-e.length%4,n=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat(t);return wx(n)}var fs=2,OE=["new","continue"],vx=["charge_and_capture","authorize_only"],zf=10000n,fd="nominal_usd_usdc_parity",Xf=["card:vic","wallet:x402"],NE="wallet:x402",qf=["connector","laptop"],Kf=["card:vic","wallet:tempo","wallet:x402"];function Zf(e){let t=new Set(e);return e.includes(NE)&&t.add("wallet:tempo"),[...t].sort((n,r)=>ps(n,r))}var bx={ask:"Ask me each time",budget:"Pay within my budget"};function Ax(e,t){return e!=="laptop"?[]:Zf(t).map(n=>({surface:"laptop",scope:n}))}var Sx=["hosted_identity_key_migration_required","identity_key_expired","identity_key_rotated","identity_key_lost","identity_key_inactive","agent_inactive","current_grant_missing","current_grant_replaced","current_grant_expired","current_grant_inactive","required_scope_missing","managed_wallet_authority_unverified","authority_projection_unknown","authorization_version_unsupported","identity_key_custody_unsupported","owner_eligibility_required"],Ix=["runtime","turnkey","server_encrypted","server_kms","external"],Tx=["pending","active","retired","revoked","lost"],DE=["dotvisa","tap","email","messaging"],ME=["provisioning","active","needs_attention","suspended","disabled"],LE=["routing_only","provider_verified","agent_key_bound"],Px=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,kx=/^[A-Za-z0-9_-]{43}$/,Cx=/^(?:0|[1-9][0-9]*)$/,Rx=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,6})?(?:Z|[+-]\d{2}:\d{2})$/,JE=/[\u0000-\u001f\u007f]/,xx=2147483647,UE=9223372036854775807n,bE=100,Ox=512,AE=32,Nx=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.visa$/,jE=/^0x[0-9a-f]{40}$/,Qf=new TextEncoder;function ps(e,t){return(0,Wf.compareCanonicalKeys)(e,t)}function ki(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function hs(e){if(typeof e!="string"||!kx.test(e))return!1;try{let t=Ex(e);return t.byteLength===32&&md(t)===e}catch{return!1}}function Ci(e,t,n){let r=Object.keys(t).filter(i=>!n.has(i));if(r.length>0)throw new Error(`${e} contains unknown field(s): ${r.sort().join(", ")}`)}function Dx(e,t){if(typeof t!="string"||!Px.test(t))throw new Error(`${e} must be a UUID`)}function ct(e,t){return Dx(e,t),t.toLowerCase()}function Hf(e,t){if(!(0,Wf.isCanonicalOpaqueId)(t))throw new Error(`${e} must be a non-empty opaque id (max 128 chars)`)}function Ho(e,t){if(typeof t!="string")throw new Error(`${e} must be an ISO timestamp with an explicit time-zone offset`);let n=Rx.exec(t);if(!n)throw new Error(`${e} must be an ISO timestamp with an explicit time-zone offset`);let[r,i,o,a,s,c]=n.slice(1,7).map(Number);if(!(0,Wf.isValidCalendarDateTime)(r,i,o,a,s,c))throw new Error(`${e} must be a valid calendar timestamp`);let d=Date.parse(t);if(!Number.isFinite(d))throw new Error(`${e} must be a valid ISO timestamp`);return new Date(d).toISOString()}function Pi(e,t,n=!1){if(typeof t!="string"||!Cx.test(t))throw new Error(`${e} must be a canonical non-negative integer micros string`);if(!n&&t==="0")throw new Error(`${e} must be positive`);if(BigInt(t)>UE)throw new Error(`${e} exceeds the PostgreSQL BIGINT range`);return t}function qE(e,t){if(typeof t!="number"||!Number.isInteger(t)||t<=0||t>xx)throw new Error(`${e} must be a positive PostgreSQL INTEGER`);return t}function Vf(e,t){if(typeof t!="string")throw new Error(`${e} must be a string`);if(JE.test(t))throw new Error(`${e} must be a bounded non-empty payee without control characters`);let n=t.normalize("NFC").trim();if(n.length===0||n.length>Ox)throw new Error(`${e} must be a bounded non-empty payee without control characters`);return n}function ls(e,t,n){if(typeof t!="string")throw new Error(`${e} must be a string`);if(JE.test(t))throw new Error(`${e} must be bounded, non-empty text without control characters`);let r=t.normalize("NFC").trim();if(r.length===0||r.length>n)throw new Error(`${e} must be bounded, non-empty text without control characters`);return r}function gn(e,t){return typeof e=="string"&&t.includes(e)}function Mx(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("cents must be a non-negative safe integer");let t=BigInt(e)*zf;if(t>UE)throw new Error("cents exceed the PostgreSQL BIGINT micros range");return t.toString()}function Lx(e){return Pi("amountAtomic",e,!0)}function Jx(e){if(e==="card:vic")return{scope:e,paymentRail:"card",protocol:null,instrumentKind:"vic_card"};if(e==="wallet:x402")return{scope:e,paymentRail:"stablecoin",protocol:"x402",instrumentKind:"turnkey_wallet"};throw new Error(`unknown authorization scope: ${String(e)}`)}function Ux(e,t,n){if(!ki(e))throw new Error("keyLink must be an object");Ci("channel keyLink",e,new Set(["keyId","agentId","purpose","fingerprint"]));let r=ct("keyLink.keyId",e.keyId),i=ct("keyLink.agentId",e.agentId);if(i!==t)throw new Error("keyLink.agentId must match the channel agentId");if(!gn(e.purpose,["identity","email_signing"]))throw new Error("channel keyLink cannot use a wallet-signing key");if(n==="email"&&e.purpose!=="email_signing")throw new Error("an agent-key-bound email channel requires an email_signing key");if((n==="tap"||n==="dotvisa")&&e.purpose!=="identity")throw new Error(`${n} requires an identity key`);let o=ls("keyLink.fingerprint",e.fingerprint,255);if(!hs(o))throw new Error(`an ${e.purpose} key link fingerprint must be a 43-char RFC 7638 JKT`);return{keyId:r,agentId:i,purpose:e.purpose,fingerprint:o}}function jx(e){if(!ki(e))throw new Error("agent channel descriptor must be an object");Ci("agent channel descriptor",e,new Set(["channelId","agentId","kind","status","assurance","address","providerRef","keyLink","capabilities","createdAt","verifiedAt","disabledAt"])),Hf("channelId",e.channelId);let t=ct("agentId",e.agentId);if(!gn(e.kind,DE))throw new Error("invalid channel kind");if(!gn(e.status,ME))throw new Error("invalid channel status");if(!gn(e.assurance,LE))throw new Error("invalid channel assurance");let n=e.address===void 0?void 0:ls("address",e.address,320),r=e.kind==="dotvisa"?n?.toLowerCase():n;if((e.kind==="email"||e.kind==="dotvisa")&&r===void 0)throw new Error(`${e.kind} channels require an address`);if(e.kind==="dotvisa"&&r!==void 0&&!Nx.test(r))throw new Error("dotvisa channel address must be a canonical lowercase .visa address");if(e.kind==="tap"&&r!==void 0)throw new Error("tap channels use providerRef and cannot claim a public address");let i=e.providerRef===void 0?void 0:ls("providerRef",e.providerRef,255);if(!Array.isArray(e.capabilities)||e.capabilities.length===0||e.capabilities.length>AE)throw new Error(`capabilities must contain between 1 and ${AE} entries`);let o=e.capabilities.map(u=>ls("capability",u,64));if(new Set(o).size!==o.length)throw new Error("capabilities must not repeat");let a=Ho("createdAt",e.createdAt),s=e.verifiedAt===void 0?void 0:Ho("verifiedAt",e.verifiedAt),c=e.disabledAt===void 0?void 0:Ho("disabledAt",e.disabledAt);if(s!==void 0&&Date.parse(s)<Date.parse(a))throw new Error("verifiedAt cannot be before createdAt");if(c!==void 0&&Date.parse(c)<Date.parse(a))throw new Error("disabledAt cannot be before createdAt");if(c!==void 0&&s!==void 0&&Date.parse(c)<Date.parse(s))throw new Error("disabledAt cannot be before verifiedAt");if(e.status==="disabled"!=(c!==void 0))throw new Error("status='disabled' and disabledAt must be set together");let d={channelId:e.channelId,agentId:t,kind:e.kind,status:e.status,...r!==void 0?{address:r}:{},...i!==void 0?{providerRef:i}:{},capabilities:[...o].sort(ps),createdAt:a,...c!==void 0?{disabledAt:c}:{}};if(e.assurance==="routing_only"){if(s!==void 0||e.keyLink!==void 0)throw new Error("routing_only channels cannot claim verification or an agent key link");return{...d,assurance:"routing_only"}}if(i===void 0||s===void 0)throw new Error(`${e.assurance} channels require providerRef and verifiedAt`);if(e.assurance==="provider_verified"){if(e.keyLink!==void 0)throw new Error("provider_verified channels cannot claim an agent key link");return{...d,assurance:"provider_verified",providerRef:i,verifiedAt:s}}let l=Ux(e.keyLink,t,e.kind);return{...d,assurance:"agent_key_bound",providerRef:i,verifiedAt:s,keyLink:l}}function KE(e,t){if(!Array.isArray(e)||e.length>qf.length*Kf.length)throw new Error("payWithinBudget must be an array of surface/scope entries");let n=e.map(i=>{if(!ki(i))throw new Error("payWithinBudget entry must be an object");if(Ci("payWithinBudget entry",i,new Set(["surface","scope"])),!gn(i.surface,qf))throw new Error("payWithinBudget surface must be laptop or connector");if(!gn(i.scope,Kf))throw new Error("payWithinBudget scope is not a payment rail");if(!Zf(t).includes(i.scope))throw new Error(i.scope==="wallet:tempo"?"payWithinBudget wallet:tempo needs the wallet:x402 grant scope":"payWithinBudget scope must be present in grant scopes");return{surface:i.surface,scope:i.scope}}),r=n.map(({surface:i,scope:o})=>`${i}:${o}`);if(new Set(r).size!==r.length)throw new Error("payWithinBudget must not repeat");return[...n].sort((i,o)=>ps(`${i.surface}:${i.scope}`,`${o.surface}:${o.scope}`))}function HE(e){if(!ki(e))throw new Error("agent authority grant must be an object");if(Ci("agent authority grant",e,new Set(["v","grantId","agentId","version","budgetEpochId","budgetEpochMode","status","currency","valuationPolicy","totalMicros","perTransactionMicros","dailyMicros","scopes","payWithinBudget","payeeConstraints","effectiveAt","expiresAt","supersedesGrantId"])),e.v!==fs)throw new Error("grant.v must be 2");let t=ct("grantId",e.grantId),n=ct("agentId",e.agentId),r=qE("version",e.version),i=ct("budgetEpochId",e.budgetEpochId);if(!gn(e.budgetEpochMode,OE))throw new Error("budgetEpochMode must be new or continue");if(!gn(e.status,["active","superseded","revoked"]))throw new Error("invalid grant status");if(e.currency!=="USD")throw new Error("currency must be 'USD'");if(e.valuationPolicy!==fd)throw new Error(`valuationPolicy must be '${fd}'`);let o=Pi("totalMicros",e.totalMicros),a=Pi("perTransactionMicros",e.perTransactionMicros);if(BigInt(a)>BigInt(o))throw new Error("perTransactionMicros cannot exceed totalMicros");let s=e.dailyMicros===void 0?void 0:Pi("dailyMicros",e.dailyMicros);if(s!==void 0){if(BigInt(s)>BigInt(o))throw new Error("dailyMicros cannot exceed totalMicros");if(BigInt(a)>BigInt(s))throw new Error("perTransactionMicros cannot exceed dailyMicros")}if(!Array.isArray(e.scopes)||e.scopes.length===0)throw new Error("scopes must be a non-empty array");let c=e.scopes.map(h=>{if(!ki(h))throw new Error("grant scope must be an object");if(Ci("grant scope",h,new Set(["scope","totalMicros","perTransactionMicros","instrumentRef"])),!gn(h.scope,Xf))throw new Error("invalid authorization scope");let p=h.totalMicros===void 0?void 0:Pi("scope.totalMicros",h.totalMicros),m=h.perTransactionMicros===void 0?void 0:Pi("scope.perTransactionMicros",h.perTransactionMicros);if(p!==void 0&&BigInt(p)>BigInt(o))throw new Error("scope.totalMicros cannot exceed the aggregate totalMicros");if(m!==void 0&&BigInt(m)>BigInt(a))throw new Error("scope.perTransactionMicros cannot exceed the aggregate perTransactionMicros");if(p!==void 0&&m!==void 0&&BigInt(m)>BigInt(p))throw new Error("scope.perTransactionMicros cannot exceed scope.totalMicros");let w=ls("scope.instrumentRef",h.instrumentRef,255);return{scope:h.scope,...p!==void 0?{totalMicros:p}:{},...m!==void 0?{perTransactionMicros:m}:{},instrumentRef:w}});if(new Set(c.map(({scope:h})=>h)).size!==c.length)throw new Error("scopes must not repeat");let d=e.payWithinBudget===void 0?void 0:KE(e.payWithinBudget,c.map(({scope:h})=>h)),l;if(e.payeeConstraints!==void 0){if(!Array.isArray(e.payeeConstraints)||e.payeeConstraints.length===0||e.payeeConstraints.length>bE)throw new Error(`payeeConstraints must contain between 1 and ${bE} entries`);if(l=e.payeeConstraints.map(p=>{if(!ki(p))throw new Error("payee constraint must be an object");if(Ci("payee constraint",p,new Set(["scope","kind","canonicalId"])),p.scope==="card:vic"&&p.kind==="processor_merchant_id")return{scope:p.scope,kind:p.kind,canonicalId:Vf("payee constraint canonicalId",p.canonicalId)};if(p.scope==="wallet:x402"&&p.kind==="evm_address"){let m=Vf("payee constraint canonicalId",p.canonicalId).toLowerCase();if(!jE.test(m))throw new Error("wallet payee constraint canonicalId must be an EVM address");return{scope:p.scope,kind:p.kind,canonicalId:m}}throw new Error("payee constraint scope/kind combination is invalid")}),l.some(p=>!c.some(({scope:m})=>m===p.scope)))throw new Error("payee constraint scope must be present in grant scopes");let h=l.map(({scope:p,kind:m,canonicalId:w})=>`${p}:${m}:${w}`);if(new Set(h).size!==h.length)throw new Error("payeeConstraints must not repeat after normalization")}let u=Ho("effectiveAt",e.effectiveAt),f=Ho("expiresAt",e.expiresAt);if(Date.parse(f)<=Date.parse(u))throw new Error("expiresAt must be after effectiveAt");if(e.supersedesGrantId!==void 0&&ct("supersedesGrantId",e.supersedesGrantId)===t)throw new Error("a grant cannot supersede itself");return{v:fs,grantId:t,agentId:n,version:r,budgetEpochId:i,budgetEpochMode:e.budgetEpochMode,status:e.status,currency:"USD",valuationPolicy:fd,totalMicros:o,perTransactionMicros:a,...s!==void 0?{dailyMicros:s}:{},scopes:[...c].sort((h,p)=>ps(h.scope,p.scope)),...d!==void 0?{payWithinBudget:d}:{},...l!==void 0?{payeeConstraints:[...l].sort((h,p)=>ps(`${h.scope}:${h.kind}:${h.canonicalId}`,`${p.scope}:${p.kind}:${p.canonicalId}`))}:{},effectiveAt:u,expiresAt:f,...e.supersedesGrantId!==void 0?{supersedesGrantId:ct("supersedesGrantId",e.supersedesGrantId)}:{}}}function qx(e){let t=HE(e),{status:n,...r}=t;return md($f(Qf.encode(`visa-agent-authority-grant:v2:${JSON.stringify(r)}`)))}function ep(e){if(!ki(e))throw new Error("spend authorization intent must be an object");if(Ci("spend authorization intent",e,new Set(["v","authorizationId","agentId","keyJkt","grantId","grantVersion","budgetEpochId","scope","amountMicros","currency","payee","intentId","economicIntentId","settlementHash","settlementExpiresAt"])),e.v!==fs)throw new Error("intent.v must be 2");let t=ct("authorizationId",e.authorizationId),n=ct("agentId",e.agentId);if(!hs(e.keyJkt))throw new Error("keyJkt must be a 43-char RFC 7638 thumbprint");let r=ct("grantId",e.grantId),i=qE("grantVersion",e.grantVersion),o=ct("budgetEpochId",e.budgetEpochId);if(!gn(e.scope,Xf))throw new Error("invalid authorization scope");let a=Pi("amountMicros",e.amountMicros);if(e.scope==="card:vic"&&BigInt(a)%zf!==0n)throw new Error("card:vic amountMicros must represent a whole number of card cents");if(e.currency!=="USD")throw new Error("currency must be 'USD'");let s=Vf("payee",e.payee),c=e.scope==="wallet:x402"?s.toLowerCase():s;if(e.scope==="wallet:x402"&&!jE.test(c))throw new Error("wallet:x402 payee must be an EVM address");if(Hf("intentId",e.intentId),Hf("economicIntentId",e.economicIntentId),!hs(e.settlementHash))throw new Error("settlementHash is required and must be a 32-byte base64url commitment");let d=Ho("settlementExpiresAt",e.settlementExpiresAt);return{v:fs,authorizationId:t,agentId:n,keyJkt:e.keyJkt,grantId:r,grantVersion:i,budgetEpochId:o,scope:e.scope,amountMicros:a,currency:"USD",payee:c,intentId:e.intentId,economicIntentId:e.economicIntentId,settlementHash:e.settlementHash,settlementExpiresAt:d}}function VE(e){let t=ep(e),n=JSON.stringify({v:t.v,authorizationId:t.authorizationId,agentId:t.agentId,keyJkt:t.keyJkt,grantId:t.grantId,grantVersion:t.grantVersion,budgetEpochId:t.budgetEpochId,scope:t.scope,amountMicros:t.amountMicros,currency:t.currency,payee:t.payee,intentId:t.intentId,economicIntentId:t.economicIntentId,settlementHash:t.settlementHash,settlementExpiresAt:t.settlementExpiresAt});return md($f(Qf.encode(`visa-agent-spend-authorization:v2:${n}`)))}function Kx(e){let t=ep(e.intent),n=ct("walletApiKeyId",e.walletApiKeyId),r=ct("runtimeSessionId",e.runtimeSessionId);if(e.executionChannel!=="cli"&&e.executionChannel!=="mcp")throw new Error("executionChannel must be cli or mcp");if(!hs(e.resourceCommitment))throw new Error("resourceCommitment must be a 32-byte base64url commitment");let i=JSON.stringify({v:1,intentHash:VE(t),walletApiKeyId:n,runtimeSessionId:r,executionChannel:e.executionChannel,resourceCommitment:e.resourceCommitment});return md($f(Qf.encode(`visa-wallet-authorization-request:v1:${i}`)))}});var YE=y(F=>{"use strict";Object.defineProperty(F,"__esModule",{value:!0});F.FINANCIAL_REVOCATION_TYPE=F.FinancialProofError=F.FINANCIAL_REQUEST_MAX_BYTES=F.FINANCIAL_JWS_MAX_BYTES=F.FINANCIAL_MODE_CHANGE_TYPE=F.FINANCIAL_APPROVAL_TYPE=F.FINANCIAL_APPROVAL_AUDIENCE=void 0;F.parseFinancialCanonicalJson=ys;F.parseCardDisclosureConsent=tp;F.parseFinancialOwnerApproval=np;F.isPaymentModeOnlyReplacement=Wx;F.financialRootJkt=wd;F.prepareFinancialOwnerApproval=rp;F.verifyFinancialOwnerApproval=FE;F.completeFinancialOwnerApproval=Fx;F.parseFinancialOwnerChallengeView=Bx;F.parseFinancialOwnerRevocation=ip;F.prepareFinancialOwnerRevocation=BE;F.verifyFinancialOwnerRevocation=GE;F.completeFinancialOwnerRevocation=Gx;var gs=WE(),Cr=yi(),Hx=rs(),Wt=Kn();F.FINANCIAL_APPROVAL_AUDIENCE="urn:visa:authority:financial";F.FINANCIAL_APPROVAL_TYPE="visa-financial-grant-approval+jwt";F.FINANCIAL_MODE_CHANGE_TYPE="visa-financial-mode-change+jwt";F.FINANCIAL_JWS_MAX_BYTES=16384;F.FINANCIAL_REQUEST_MAX_BYTES=262144;var Vx=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,Vn=new TextEncoder,yd=new TextDecoder("utf-8",{fatal:!0}),$x=["v","purpose","audience","approvalId","challenge","ownerPrincipalId","associationId","associationVersion","agentId","rootJkt","grantHash","previousGrantId","previousGrantVersion","iat","exp"],_d=class extends Error{constructor(t){super(t),this.name="FinancialProofError"}};F.FinancialProofError=_d;function z(e){throw new _d(e)}function Hn(e,t){if(!e||typeof e!="object"||Array.isArray(e))return z("Expected a closed object");let n=e;return Object.keys(n).length!==t.length||t.some(r=>!Object.hasOwn(n,r))?z("Unexpected or missing field"):n}function $t(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>0}function $o(e){return typeof e=="string"&&Vx.test(e)}function Pt(e,t){if(typeof e!="string"||!/^[A-Za-z0-9_-]+$/.test(e))return z("Invalid base64url");let n=new Uint8Array((0,Cr.base64UrlToBytes)(e));return(0,Cr.bytesToBase64Url)(n)!==e||t!==void 0&&n.length!==t?z("Noncanonical base64url"):n}function gd(e){if(typeof e=="string")for(let t=0;t<e.length;t++){let n=e.charCodeAt(t);if(n>=55296&&n<=56319){let r=e.charCodeAt(++t);r>=56320&&r<=57343||z("Invalid Unicode")}else n>=56320&&n<=57343&&z("Invalid Unicode")}else if(Array.isArray(e))for(let t of e)gd(t);else if(e&&typeof e=="object")for(let[t,n]of Object.entries(e))gd(t),gd(n)}function ys(e,t=F.FINANCIAL_REQUEST_MAX_BYTES){if(Vn.encode(e).length>t)return z("Financial input too large");let n;try{n=JSON.parse(e)}catch{return z("Invalid JSON")}return gd(n),(0,Wt.canonicalEnvelopeJson)(n)!==e?z("Noncanonical JSON"):n}function tp(e){let t=Hn(e,["v","runtimeId","mode"]);return t.v!==1||!$o(t.runtimeId)||t.mode!=="private"&&t.mode!=="agent_history"?z("Invalid card disclosure consent"):{v:1,runtimeId:t.runtimeId,mode:t.mode}}function np(e){let t=e?.v,n=Hn(e,[...$x,...t===2?["cardDisclosure"]:t===3?["previousGrantHash","payWithinBudget","cardDisclosure"]:[]]);if(n.v!==1&&n.v!==2&&n.v!==3||n.purpose!==(n.v===3?"financial.mode.change":"financial.grant.approve")||n.audience!==F.FINANCIAL_APPROVAL_AUDIENCE)return z("Wrong financial approval profile");for(let r of["approvalId","ownerPrincipalId","associationId","agentId"])if(!$o(n[r]))return z("Invalid approval identity");for(let r of["challenge","rootJkt","grantHash"])Pt(n[r],32);if(!$t(n.associationVersion)||!$t(n.iat)||!$t(n.exp)||n.exp<=n.iat||n.exp-n.iat>300)return z("Invalid approval version or window");if(n.previousGrantId===null?n.previousGrantVersion!==null:!$o(n.previousGrantId)||!$t(n.previousGrantVersion))return z("Invalid grant predecessor");if(n.v===3){if(!$o(n.previousGrantId)||!$t(n.previousGrantVersion))return z("Mode change requires a predecessor");Pt(n.previousGrantHash,32)}return{...n,...n.v===2?{cardDisclosure:tp(n.cardDisclosure)}:{},...n.v===3?{payWithinBudget:(0,gs.canonicalPayWithinBudget)(n.payWithinBudget,["wallet:x402","card:vic"]),cardDisclosure:n.cardDisclosure===null?null:tp(n.cardDisclosure)}:{}}}function Wx(e,t){let n=(0,gs.canonicalAgentAuthorityGrant)(e),r=(0,gs.canonicalAgentAuthorityGrant)(t);if(r.supersedesGrantId!==n.grantId||r.version!==n.version+1||r.grantId===n.grantId||r.budgetEpochMode!=="continue"||r.payWithinBudget===void 0||(0,Wt.canonicalJson)(r.payWithinBudget)===(0,Wt.canonicalJson)(n.payWithinBudget??null))return!1;let i=({grantId:o,version:a,supersedesGrantId:s,budgetEpochMode:c,payWithinBudget:d,...l})=>l;return(0,Wt.canonicalJson)(i(n))===(0,Wt.canonicalJson)(i(r))}async function wd(e){let t=Hn(e,["kty","crv","x"]);return t.kty!=="OKP"||t.crv!=="Ed25519"?z("Expected owner Ed25519 root"):(Pt(t.x,32),(0,Hx.computeJkt)(t))}function rp(e,t){let n=np(e),r=(0,gs.canonicalAgentAuthorityGrant)(t);if(r.status!=="active"||r.agentId!==n.agentId||(0,gs.agentAuthorityGrantHash)(r)!==n.grantHash)return z("Displayed grant does not match approval");if(n.v===2&&!r.scopes.some(a=>a.scope==="card:vic"))return z("Card disclosure requires a card spending scope");if(n.v===3&&(r.supersedesGrantId!==n.previousGrantId||r.version!==n.previousGrantVersion+1||(0,Wt.canonicalJson)(r.payWithinBudget??null)!==(0,Wt.canonicalJson)(n.payWithinBudget)))return z("Displayed modes do not match approval");let i={alg:"EdDSA",typ:n.v===3?F.FINANCIAL_MODE_CHANGE_TYPE:F.FINANCIAL_APPROVAL_TYPE,kid:n.rootJkt},o=`${(0,Cr.bytesToBase64Url)(Vn.encode((0,Wt.canonicalJson)(i)))}.${(0,Cr.bytesToBase64Url)(Vn.encode((0,Wt.canonicalJson)(n)))}`;return{statement:n,grant:r,signingInput:o}}async function FE(e,t,n){if(typeof e!="string"||Vn.encode(e).length>F.FINANCIAL_JWS_MAX_BYTES)return z("Financial proof too large");let r=e.split(".");if(r.length!==3)return z("Invalid compact JWS");let i=Hn(ys(yd.decode(Pt(r[0])),F.FINANCIAL_JWS_MAX_BYTES),["alg","typ","kid"]),o=np(ys(yd.decode(Pt(r[1])),F.FINANCIAL_JWS_MAX_BYTES));if(i.alg!=="EdDSA"||i.typ!==(o.v===3?F.FINANCIAL_MODE_CHANGE_TYPE:F.FINANCIAL_APPROVAL_TYPE)||i.kid!==o.rootJkt||await wd(t)!==o.rootJkt)return z("Wrong owner approval key or purpose");if(!$t(n)||o.iat>n+5||n>=o.exp)return z("Owner approval expired or not yet valid");let a=await crypto.subtle.importKey("raw",Pt(t.x,32),{name:"Ed25519"},!1,["verify"]);return await crypto.subtle.verify("Ed25519",a,Pt(r[2],64),Vn.encode(`${r[0]}.${r[1]}`))?o:z("Invalid owner signature")}async function Fx(e,t,n,r,i){if(r.length!==64)return z("Invalid owner signature length");let{signingInput:o}=rp(e,t),a=`${o}.${(0,Cr.bytesToBase64Url)(r)}`;return await FE(a,n,i),a}async function Bx(e){let t=Hn(e,["v","statement","grant","root","projection"]);if(t.v!==1)return z("Unknown owner review version");let{statement:n,grant:r}=rp(t.statement,t.grant),i=Hn(t.root,["organizationId","rootKeyId","publicJwk"]);for(let a of["organizationId","rootKeyId"])if(typeof i[a]!="string"||!/^[-_A-Za-z0-9]{1,256}$/.test(i[a]))return z("Invalid protected root coordinates");if(await wd(i.publicJwk)!==n.rootJkt)return z("Protected root does not match owner approval");let o=Hn(t.projection,["agentId","ownerPublicId"]);return o.agentId!==n.agentId||!$o(o.ownerPublicId)||o.ownerPublicId===n.ownerPrincipalId?z("Invalid protected owner projection"):{v:1,statement:n,grant:r,root:{organizationId:i.organizationId,rootKeyId:i.rootKeyId,publicJwk:{...i.publicJwk}},projection:{agentId:n.agentId,ownerPublicId:o.ownerPublicId}}}F.FINANCIAL_REVOCATION_TYPE="visa-financial-grant-revocation+jwt";function ip(e){let t=Hn(e,["v","purpose","audience","approvalId","ownerPrincipalId","associationId","associationVersion","agentId","rootJkt","grantId","grantVersion","grantHash","iat","exp"]);if(t.v!==1||t.purpose!=="financial.grant.revoke"||t.audience!==F.FINANCIAL_APPROVAL_AUDIENCE)return z("Wrong financial revocation profile");for(let n of["approvalId","ownerPrincipalId","associationId","agentId","grantId"])if(!$o(t[n]))return z("Invalid revocation identity");for(let n of["rootJkt","grantHash"])Pt(t[n],32);return!$t(t.associationVersion)||!$t(t.grantVersion)||!$t(t.iat)||!$t(t.exp)||t.exp<=t.iat||t.exp-t.iat>300?z("Invalid revocation version or window"):{...t}}function BE(e){let t=ip(e),n={alg:"EdDSA",typ:F.FINANCIAL_REVOCATION_TYPE,kid:t.rootJkt};return{statement:t,signingInput:`${(0,Cr.bytesToBase64Url)(Vn.encode((0,Wt.canonicalJson)(n)))}.${(0,Cr.bytesToBase64Url)(Vn.encode((0,Wt.canonicalJson)(t)))}`}}async function GE(e,t,n){if(typeof e!="string"||Vn.encode(e).length>F.FINANCIAL_JWS_MAX_BYTES)return z("Financial proof too large");let r=e.split(".");if(r.length!==3)return z("Invalid compact JWS");let i=Hn(ys(yd.decode(Pt(r[0])),F.FINANCIAL_JWS_MAX_BYTES),["alg","typ","kid"]),o=ip(ys(yd.decode(Pt(r[1])),F.FINANCIAL_JWS_MAX_BYTES));if(i.alg!=="EdDSA"||i.typ!==F.FINANCIAL_REVOCATION_TYPE||i.kid!==o.rootJkt||await wd(t)!==o.rootJkt)return z("Wrong owner revocation key or purpose");if(!$t(n)||o.iat>n+5||n>=o.exp)return z("Owner revocation expired or not yet valid");let a=await crypto.subtle.importKey("raw",Pt(t.x,32),{name:"Ed25519"},!1,["verify"]);return await crypto.subtle.verify("Ed25519",a,Pt(r[2],64),Vn.encode(`${r[0]}.${r[1]}`))?o:z("Invalid owner signature")}async function Gx(e,t,n,r){if(n.length!==64)return z("Invalid owner signature length");let i=`${BE(e).signingInput}.${(0,Cr.bytesToBase64Url)(n)}`;return await GE(i,t,r),i}});var lp=y(dt=>{"use strict";Object.defineProperty(dt,"__esModule",{value:!0});dt.FINANCIAL_DEVICE_OPERATIONS_AUDIENCE=dt.FINANCIAL_DEVICE_ENROLLMENT_AUDIENCE=dt.WALLET_DEVICE_HANDOFF_AUDIENCE=dt.CARD_DEVICE_HANDOFF_AUDIENCE=void 0;dt.assertFinancialDevicePair=zx;dt.financialDeviceProposalHash=ap;dt.financialDeviceOperationsRequestHash=Xx;dt.financialDeviceEnrollmentChallengeHash=Zx;var sp=rs(),cp=yi(),Ed=Kn(),Yx=YE(),op=os();function zx(e,t){if(ap(e),ap(t),e.v!==1||t.v!==2||e.agentId!==t.agentId||e.associationId!==t.associationId||e.associationVersion!==t.associationVersion||e.rootJkt!==t.rootJkt||e.requestId===t.requestId||e.runtimeId===t.runtimeId||e.publicJwk.x===t.publicJwk.x)throw new Error("financial_device_pair_invalid")}dt.CARD_DEVICE_HANDOFF_AUDIENCE="visa:financial:card-device-handoff:v1";dt.WALLET_DEVICE_HANDOFF_AUDIENCE="visa:financial:wallet-device-handoff:v1";function ap(e){let t=["v","purpose","requestId","associationId","associationVersion","agentId","runtimeId","rootJkt","publicJwk"];if(e?.v===2&&t.push("rail"),e?.tempoCosign!==void 0&&t.push("tempoCosign"),!e||Object.keys(e).sort().join(",")!==t.sort().join(",")||!(e.v===1||e.v===2&&e.rail==="card:vic")||e.tempoCosign!==void 0&&(e.v!==1||e.tempoCosign!=="v1")||e.purpose!=="financial.runtime.device.proposal"||![e.requestId,e.associationId,e.runtimeId].every(n=>typeof n=="string"&&dp.test(n))||typeof e.agentId!="string"||!e.agentId||e.agentId.length>256||!Number.isSafeInteger(e.associationVersion)||e.associationVersion<1||!(0,op.isCanonicalBase64Url32)(e.rootJkt)||!e.publicJwk||Object.keys(e.publicJwk).sort().join(",")!=="crv,kty,x"||e.publicJwk.crv!=="Ed25519"||e.publicJwk.kty!=="OKP"||!(0,op.isCanonicalBase64Url32)(e.publicJwk.x))throw new Error("financial_device_proposal_invalid");return(0,cp.bytesToBase64Url)((0,sp.sha256)(new TextEncoder().encode((0,Ed.canonicalJson)(e))))}dt.FINANCIAL_DEVICE_ENROLLMENT_AUDIENCE="visa:financial:device-enrollment:v1";dt.FINANCIAL_DEVICE_OPERATIONS_AUDIENCE="visa:financial:device-operations:v1";function Xx(e){let t=["v","purpose","requestId","agentId","runtimeId","limit"];if(!e||typeof e!="object"||Object.keys(e).sort().join(",")!==t.sort().join(",")||e.v!==1||e.purpose!=="financial.wallet.operations.read"||![e.requestId,e.agentId,e.runtimeId].every(n=>typeof n=="string"&&dp.test(n))||!Number.isSafeInteger(e.limit)||e.limit<1||e.limit>50)throw new Error("financial_device_operations_request_invalid");return(0,cp.bytesToBase64Url)((0,sp.sha256)(new TextEncoder().encode((0,Ed.canonicalJson)(e))))}var zE=["v","purpose","requestId","associationId","associationVersion","runtimeId","runtimeGeneration","childJkt","preparedCertificate","preparedDelegation","expiresAt"],dp=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;function Zx(e){let t=(0,Yx.parseFinancialCanonicalJson)((0,Ed.canonicalJson)(e));if(!t||Array.isArray(t)||Object.keys(t).length!==zE.length||zE.some(n=>!Object.hasOwn(t,n))||t.v!==1||t.purpose!=="financial.runtime.device.enroll"||!["requestId","associationId","runtimeId"].every(n=>typeof t[n]=="string"&&dp.test(t[n]))||!["associationVersion","runtimeGeneration","expiresAt"].every(n=>Number.isSafeInteger(t[n])&&t[n]>0)||!(0,op.isCanonicalBase64Url32)(t.childJkt))throw new Error("financial_device_challenge_invalid");for(let n of["preparedCertificate","preparedDelegation"]){let r=t[n];if(!r||Array.isArray(r)||Object.keys(r).sort().join(",")!=="claims,signingInput"||typeof r.signingInput!="string"||r.signingInput.length>16384||!r.claims||typeof r.claims!="object"||Array.isArray(r.claims))throw new Error("financial_device_challenge_invalid")}return(0,cp.bytesToBase64Url)((0,sp.sha256)(new TextEncoder().encode((0,Ed.canonicalJson)(t))))}});var bd=y(vd=>{"use strict";Object.defineProperty(vd,"__esModule",{value:!0});vd.parsePurchaseTerms=XE;vd.purchaseTermsPreimage=tO;var oe=Pr(),Qx=Kn();function Wo(e,t){if(Object.keys(e).sort().join(",")!==[...t].sort().join(","))throw new oe.AgentOperationContractError("invalid_contract","purchase terms fields are not canonical")}function XE(e){let t=(0,oe.record)(e,"purchase terms"),n=t.profile==="exact_card_checkout_v1";if(Wo(t,["v","profile","alternatives",...n?["checkout","disclosureMode",...t.merchantCountryCode===void 0?[]:["merchantCountryCode"]]:[]]),t.v!==1||typeof t.profile!="string"||!["url_resource_v1","approved_x402_request_v1","exact_card_checkout_v1"].includes(String(t.profile)))throw new oe.AgentOperationContractError("unsupported_version","unsupported purchase terms profile");if(!Array.isArray(t.alternatives)||t.alternatives.length<1||t.alternatives.length>2)throw new oe.AgentOperationContractError("invalid_contract","purchase requires one or two exact rail alternatives");let r=t.profile==="approved_x402_request_v1";if(r&&t.alternatives.length!==1)throw new oe.AgentOperationContractError("invalid_contract","request-bound purchase requires one wallet alternative");let i=t.alternatives.map(o=>{let a=(0,oe.record)(o,"purchase alternative"),s=(0,Qx.parseAgentMoneyEconomics)(a.economics),c=(0,oe.bounded)(s.merchant.url,"purchase resource URL",2048),d;try{d=new URL(c)}catch{throw new oe.AgentOperationContractError("invalid_contract","purchase resource URL is invalid")}if(d.protocol!=="https:"||d.username||d.password||d.hash)throw new oe.AgentOperationContractError("invalid_contract","purchase requires an HTTPS resource without credentials or fragment");if(a.rail==="wallet:x402"){Wo(a,["rail","economics","network","asset","payee",...r?["requestHash"]:[]]);let l=r?(0,oe.bounded)(a.requestHash,"request hash",43):void 0;if(l!==void 0&&!/^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/.test(l))throw new oe.AgentOperationContractError("invalid_contract","invalid request hash");let u=(0,oe.bounded)(a.network,"network",64),f=(0,oe.bounded)(a.asset,"asset",128),h=(0,oe.bounded)(a.payee,"payee",42);if(!/^eip155:[1-9][0-9]{0,15}$/.test(u)||!new RegExp(`^${u}/erc20:0x[0-9a-f]{40}$`).test(f)||!/^0x[0-9a-f]{40}$/.test(h)||s.currency!=="USDC")throw new oe.AgentOperationContractError("invalid_contract","invalid exact wallet economic coordinates");return{rail:a.rail,economics:s,network:u,asset:f,payee:h,...l?{requestHash:l}:{}}}if(a.rail==="card:vic"&&!r){if(Wo(a,["rail","economics","processorAction","captureMode"]),a.processorAction!=="charge_and_capture"||a.captureMode!=="exact"||s.currency!=="USD"||BigInt(s.amountMicros)%10000n!==0n)throw new oe.AgentOperationContractError("invalid_contract","purchase card profile requires exact whole-cent capture");return{rail:a.rail,economics:s,processorAction:"charge_and_capture",captureMode:"exact"}}throw new oe.AgentOperationContractError("invalid_contract","unsupported purchase rail")});if(new Set(i.map(o=>o.rail)).size!==i.length)throw new oe.AgentOperationContractError("invalid_contract","purchase rail alternatives must be unique");if(i.sort((o,a)=>o.rail<a.rail?-1:o.rail>a.rail?1:0),n){if(i.length!==1||i[0].rail!=="card:vic"||!i[0].economics.merchant.name)throw new oe.AgentOperationContractError("invalid_contract","exact checkout requires one card alternative");if(t.disclosureMode!=="private"&&t.disclosureMode!=="agent_history")throw new oe.AgentOperationContractError("invalid_contract","unsupported card disclosure mode");if(t.merchantCountryCode!==void 0&&(typeof t.merchantCountryCode!="string"||!/^[A-Z]{2}$/.test(t.merchantCountryCode)))throw new oe.AgentOperationContractError("invalid_contract","invalid merchant country");return{v:1,profile:"exact_card_checkout_v1",...t.merchantCountryCode===void 0?{}:{merchantCountryCode:t.merchantCountryCode},alternatives:i,checkout:eO(t.checkout,i[0].economics.amountMicros),disclosureMode:t.disclosureMode}}return{v:1,profile:t.profile,alternatives:i}}function eO(e,t){let n=(0,oe.record)(e,"checkout");Wo(n,["id","revision","source","expiresAt","items","taxMicros","shippingMicros","discountMicros","fulfillment","customerHash"]);let r=()=>{throw new oe.AgentOperationContractError("invalid_contract","invalid exact card checkout")},i=u=>((typeof u!="string"||!/^(0|[1-9][0-9]{0,17})$/.test(u)||BigInt(u)%10000n!==0n)&&r(),u),o=u=>((typeof u!="string"||!/^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$/.test(u))&&r(),u);(n.source!=="runtime_observed"||typeof n.expiresAt!="string"||!Number.isFinite(Date.parse(n.expiresAt))||new Date(n.expiresAt).toISOString()!==n.expiresAt||!Array.isArray(n.items)||n.items.length<1||n.items.length>100)&&r();let a=n.items.map(u=>{let f=(0,oe.record)(u,"checkout item");return Wo(f,["id","name","quantity","totalMicros"]),(!Number.isSafeInteger(f.quantity)||Number(f.quantity)<1||Number(f.quantity)>1e6)&&r(),{id:(0,oe.bounded)(f.id,"checkout item ID",256),name:(0,oe.bounded)(f.name,"checkout item name",512),quantity:f.quantity,totalMicros:i(f.totalMicros)}});new Set(a.map(u=>u.id)).size!==a.length&&r();let s=i(n.taxMicros),c=i(n.shippingMicros),d=i(n.discountMicros);a.reduce((u,f)=>u+BigInt(f.totalMicros),0n)+BigInt(s)+BigInt(c)-BigInt(d)!==BigInt(t)&&r();let l=(0,oe.record)(n.fulfillment,"checkout fulfillment");return Wo(l,["method","detailsHash"]),{id:(0,oe.bounded)(n.id,"checkout ID",256),revision:(0,oe.bounded)(n.revision,"checkout revision",256),source:"runtime_observed",expiresAt:n.expiresAt,items:a,taxMicros:s,shippingMicros:c,discountMicros:d,fulfillment:{method:(0,oe.bounded)(l.method,"fulfillment method",256),detailsHash:o(l.detailsHash)},customerHash:o(n.customerHash)}}function tO(e){return(0,oe.canonicalJson)({domain:"visa.purchase-terms.v1",terms:XE(e)})}});var up=y(Xe=>{"use strict";Object.defineProperty(Xe,"__esModule",{value:!0});Xe.ACCOUNT_OPERATION_EVIDENCE_TYPES=Xe.ACCOUNT_OPERATION_PROOF_LEVELS=Xe.ACCOUNT_OPERATION_OUTCOMES=Xe.ACCOUNT_OPERATION_RECEIPT_SCHEMA_VERSION=void 0;Xe.parseAccountOperationReceipt=iO;Xe.ACCOUNT_OPERATION_RECEIPT_SCHEMA_VERSION=1;Xe.ACCOUNT_OPERATION_OUTCOMES=["pending","completed","failed","uncertain","released","reversed","disputed"];Xe.ACCOUNT_OPERATION_PROOF_LEVELS=["none","platform_observed","merchant_reported","owner_attested","processor_confirmed","network_verified","settled"];Xe.ACCOUNT_OPERATION_EVIDENCE_TYPES=["platform_activity","merchant_confirmation","card_lifecycle","onchain_transaction"];function Rr(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function $n(e){return e===null||typeof e=="string"}function _s(e){return typeof e=="string"&&e.length>0&&!Number.isNaN(Date.parse(e))}function xr(e,t){let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((i,o)=>i===r[o])}function nO(e){return Rr(e)?xr(e,["type","source","observedAt","reference","url"])&&typeof e.type=="string"&&Xe.ACCOUNT_OPERATION_EVIDENCE_TYPES.includes(e.type)&&typeof e.source=="string"&&_s(e.observedAt)&&$n(e.reference)&&$n(e.url):!1}function rO(e){return Rr(e)?xr(e,["type","at"])&&typeof e.type=="string"&&e.type.length>0&&_s(e.at):!1}function iO(e){if(!Rr(e)||!xr(e,["schemaVersion","operationId","activityId","payment","route","party","authority","outcome","evidence","timeline","dataCompleteness"])||e.schemaVersion!==Xe.ACCOUNT_OPERATION_RECEIPT_SCHEMA_VERSION||typeof e.operationId!="string"||typeof e.activityId!="string"||e.dataCompleteness!=="complete"&&e.dataCompleteness!=="partial"||!Array.isArray(e.evidence)||!e.evidence.every(nO)||!Array.isArray(e.timeline)||!e.timeline.every(rO))return null;let t=e.payment,n=e.route,r=e.party,i=e.authority,o=e.outcome;return!Rr(t)||!xr(t,["amountAtomic","decimals","currency","merchant","description","createdAt"])||typeof t.amountAtomic!="string"||!/^\d+$/.test(t.amountAtomic)||typeof t.decimals!="number"||!Number.isInteger(t.decimals)||t.decimals<0||t.decimals>18||typeof t.currency!="string"||typeof t.merchant!="string"||typeof t.description!="string"||!_s(t.createdAt)||!Rr(n)||!xr(n,["rail","protocol","network","cardLast4"])||n.rail!=="wallet"&&n.rail!=="card"||!(n.protocol===null||n.protocol==="x402"||n.protocol==="mpp"||n.protocol==="vic"||n.protocol==="virtual_card")||!$n(n.network)||!$n(n.cardLast4)||!Rr(r)||!xr(r,["agentId","agentName"])||!$n(r.agentId)||!$n(r.agentName)||!Rr(i)||!xr(i,["grantId","mandateId","drawId"])||!$n(i.grantId)||!$n(i.mandateId)||!$n(i.drawId)||!Rr(o)||!xr(o,["status","proofLevel","final","updatedAt","finalizesBy",..."held"in o?["held"]:[]])||typeof o.status!="string"||!Xe.ACCOUNT_OPERATION_OUTCOMES.includes(o.status)||typeof o.proofLevel!="string"||!Xe.ACCOUNT_OPERATION_PROOF_LEVELS.includes(o.proofLevel)||typeof o.final!="boolean"||"held"in o&&(o.held!==!0||n.rail!=="wallet"||n.protocol!=="mpp"||o.status!=="failed"||o.final!==!0)||!_s(o.updatedAt)||!(o.finalizesBy===null||_s(o.finalizesBy))?null:e}});var ev=y(_t=>{"use strict";Object.defineProperty(_t,"__esModule",{value:!0});_t.PURCHASE_RESOURCE_AUDIENCE=_t.PURCHASE_OBSERVATIONS=void 0;_t.parsePurchaseReceipt=sO;_t.parsePurchaseResourceRequest=QE;_t.purchaseResourceRequestHash=cO;var oO=require("node:crypto"),yn=Pr(),aO=bd(),ZE=up();_t.PURCHASE_OBSERVATIONS=["credential_delivered","submission_started","buyer_action_required","order_reported","submission_failed"];function sO(e,t){let n=(0,yn.record)(e,"purchase receipt"),r=(0,yn.record)(n.outcome,"purchase outcome");if(!t||n.operationId!==t||typeof n.credentialIssued!="boolean"||!ZE.ACCOUNT_OPERATION_OUTCOMES.includes(r.status)||!ZE.ACCOUNT_OPERATION_PROOF_LEVELS.includes(r.proofLevel)||typeof r.final!="boolean"||!Array.isArray(n.observations)||n.observations.length>_t.PURCHASE_OBSERVATIONS.length||n.observations.some(o=>!_t.PURCHASE_OBSERVATIONS.includes(o))||new Set(n.observations).size!==n.observations.length)throw new yn.AgentOperationContractError("invalid_contract","invalid purchase receipt");let i=n.refusal===void 0?void 0:(0,yn.record)(n.refusal,"refusal");if(i!==void 0&&(!Number.isSafeInteger(i.providerStatus)||Number(i.providerStatus)<100||Number(i.providerStatus)>999||typeof i.providerCode!="string"||!/^[a-z0-9_]{1,64}$/.test(i.providerCode)||r.status!=="failed"||r.final!==!0||n.credentialIssued!==!1))throw new yn.AgentOperationContractError("invalid_contract","invalid purchase refusal");return{operationId:t,credentialIssued:n.credentialIssued,outcome:{status:r.status,proofLevel:r.proofLevel,final:r.final},observations:n.observations,...i?{refusal:{providerStatus:Number(i.providerStatus),providerCode:i.providerCode}}:{}}}_t.PURCHASE_RESOURCE_AUDIENCE="visa:purchase-resource:v1";function QE(e){let t=(0,yn.record)(e,"purchase request"),n=()=>{throw new yn.AgentOperationContractError("invalid_contract","invalid purchase request")};(t.v!==1||typeof t.action!="string"||!["create","retrieve","cancel"].includes(t.action))&&n();let r=["v","action","requestId","agentId","runtimeId",...t.action==="create"?["requestKey","terms"]:["purchaseId"],...t.action==="retrieve"&&t.include!==void 0?["include"]:[],...t.action==="retrieve"&&t.observation!==void 0?["observation"]:[]];Object.keys(t).sort().join(",")!==r.sort().join(",")&&n(),t.include!==void 0&&t.include!=="card"&&n();let i;if(t.observation!==void 0){t.include!==void 0&&n();let a=(0,yn.record)(t.observation,"purchase observation");(Object.keys(a).sort().join(",")!=="attemptId,kind,termsHash"||!_t.PURCHASE_OBSERVATIONS.includes(a.kind)||typeof a.attemptId!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(a.attemptId)||typeof a.termsHash!="string"||!/^[A-Za-z0-9_-]{43}$/.test(a.termsHash))&&n(),i=a}for(let a of["requestId","agentId","runtimeId",...t.action==="create"?[]:["purchaseId"]])(typeof t[a]!="string"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(t[a]))&&n();let o={v:1,requestId:t.requestId,agentId:t.agentId,runtimeId:t.runtimeId};if(t.action==="create"){let a=(0,aO.parsePurchaseTerms)(t.terms);return(a.profile!=="exact_card_checkout_v1"||a.alternatives.length!==1||a.alternatives[0].rail!=="card:vic")&&n(),{...o,action:"create",requestKey:(0,yn.bounded)(t.requestKey,"purchase request key",256),terms:a}}return{...o,action:t.action,purchaseId:t.purchaseId,...t.action==="retrieve"&&t.include==="card"?{include:"card"}:{},...i?{observation:i}:{}}}function cO(e){return(0,oO.createHash)("sha256").update((0,yn.canonicalJson)({domain:_t.PURCHASE_RESOURCE_AUDIENCE,request:QE(e)})).digest("base64url")}});var nv=y(Ft=>{"use strict";Object.defineProperty(Ft,"__esModule",{value:!0});Ft.PURCHASE_TERMS_INPUT_SCHEMA=Ft.PURCHASE_MERCHANT_COUNTRY_SCHEMA=Ft.PURCHASE_REQUEST_KEY_SCHEMA=Ft.purchaseSchemaObject=void 0;var Or={type:"string",minLength:1},Ad={type:"string",pattern:"^(0|[1-9][0-9]{0,13}0000)$",description:"Canonical nonnegative whole-cent USD micros; one cent is 10000. No leading zeros."},dO={type:"string",pattern:"^[1-9][0-9]{0,14}0000$",description:"Positive exact final USD total in whole-cent micros, no greater than 9223372036854775807. Must equal the sum of item totalMicros plus taxMicros and shippingMicros minus discountMicros."},tv={type:"string",pattern:"^[A-Za-z0-9_-]{42}[AEIMQUYcgkosw048]$"},lO=(e,t=Object.keys(e))=>({type:"object",additionalProperties:!1,properties:e,required:t});Ft.purchaseSchemaObject=lO;var Ri=Ft.purchaseSchemaObject;Ft.PURCHASE_REQUEST_KEY_SCHEMA={...Or,maxLength:256,description:"Optional stable retry key; otherwise derived from the exact terms. Changing keys cannot create a second purchase for the same checkout."};Ft.PURCHASE_MERCHANT_COUNTRY_SCHEMA={type:"string",pattern:"^[A-Z]{2}$",description:"Actual two-letter merchant country. Do not infer it from the currency."};Ft.PURCHASE_TERMS_INPUT_SCHEMA=Ri({v:{const:1},profile:{const:"exact_card_checkout_v1"},merchantCountryCode:{type:"string",pattern:"^[A-Z]{2}$"},disclosureMode:{const:"agent_history"},alternatives:{type:"array",minItems:1,maxItems:1,items:Ri({rail:{const:"card:vic"},processorAction:{const:"charge_and_capture"},captureMode:{const:"exact"},economics:Ri({amountMicros:dO,currency:{const:"USD"},merchant:Ri({id:{...Or,maxLength:512},name:{...Or,maxLength:255},url:{type:"string",format:"uri",pattern:"^https://[^/#?@]+(?:[/?][^#]*)?$",maxLength:2048,description:"HTTPS checkout URL with no username, password or fragment."}},["name","url"])},["amountMicros","merchant"])},["economics"])},checkout:Ri({id:{...Or,maxLength:256},revision:{...Or,maxLength:256},source:{const:"runtime_observed"},expiresAt:{type:"string",format:"date-time",pattern:"^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z$",description:"Exact UTC ISO instant with milliseconds and Z, as produced by Date.toISOString(), for example 2026-09-17T12:00:00.000Z. Use the final quote expiry, at most 24 hours ahead; preserve it unchanged on retry."},items:{type:"array",minItems:1,maxItems:100,items:Ri({id:{...Or,maxLength:256},name:{...Or,maxLength:512},quantity:{type:"integer",minimum:1,maximum:1e6},totalMicros:{...Ad,description:"This line total already includes quantity. Each item ID must be unique."}})},taxMicros:Ad,shippingMicros:Ad,discountMicros:Ad,fulfillment:Ri({method:{...Or,maxLength:256},detailsHash:{...tv,description:"SHA-256 commitment to the exact private fulfillment snapshot. Keep its nonce and address in the host."}}),customerHash:{...tv,description:"SHA-256 commitment to the exact private customer snapshot. Never pass an address or card number here."}},["id","revision","expiresAt","items","taxMicros","shippingMicros","discountMicros","fulfillment","customerHash"])},["alternatives","checkout"])});var hp=y(se=>{"use strict";var uO=se&&se.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),Sd=se&&se.__exportStar||function(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&uO(t,e,n)};Object.defineProperty(se,"__esModule",{value:!0});se.CARD_ADMISSION_RECOVERY_AUDIENCE=void 0;se.cardAdmissionRecoveryRequestHash=fO;se.agentOperationIntentHash=fp;se.agentExecutionCommitment=pp;se.purchaseTermsHash=pO;se.purchaseAlternativeFromOperation=hO;se.x402ResourceCommitment=mO;se.agentOperationIdempotencyKey=iv;se.purchaseAttemptIdempotencyKey=gO;se.agentOperationTermsFingerprint=ov;se.legacyAgentOperationEnvelopeFingerprint=av;se.persistedAgentOperationMatchesTerms=yO;se.artifactHash=_O;se.prepareAgentOperationV1=sv;se.finalizeAgentOperationV1=cv;se.createAgentOperationV1=EO;se.parseHistoricalAgentOperation=vO;se.parseAgentOperation=ws;var _n=require("node:crypto"),be=Pr(),rv=bd();Sd(bd(),se);Sd(ev(),se);Sd(nv(),se);var Id=Kn();Sd(Kn(),se);se.CARD_ADMISSION_RECOVERY_AUDIENCE="visa:card-admission-recovery:v1";function fO(e,t){return(0,_n.createHash)("sha256").update("visa:card-admission-recovery:v1\0","utf8").update((0,be.canonicalJson)({original:e,replacement:t}),"utf8").digest("base64url")}function fp(e){return(0,_n.createHash)("sha256").update((0,Id.agentOperationIntentPreimage)(e)).digest("base64url")}function pp(e){return(0,_n.createHash)("sha256").update((0,be.canonicalJson)(e)).digest("base64url")}function pO(e){return(0,_n.createHash)("sha256").update((0,rv.purchaseTermsPreimage)(e)).digest("base64url")}function hO(e,t=Date.now()){let n=ws(e,t);if(n.effect.kind!=="money")throw new be.AgentOperationContractError("invalid_effect","purchase requires financial economics");let{amountMicros:r,currency:i,merchant:o}=n.effect,a={amountMicros:r,currency:i,merchant:o},s=(0,be.record)(n.execution.payload,"purchase native payload"),c=n.rail==="wallet:x402"?["scheme","network","asset","payer","typedData","nonce","keyRef",...s.walletBinding===void 0?[]:["walletBinding"],...s.approvedRequest===void 0&&s.requestHash===void 0?[]:["approvedRequest","requestHash"]]:["mandateId","tokenId","processorIntentId","processorAction","captureMode"];if(Object.keys(s).sort().join(",")!==c.sort().join(","))throw new be.AgentOperationContractError("invalid_contract","purchase producer has unrepresented native fields");let d;if(n.rail==="wallet:x402"&&n.execution.adapter==="wallet.eip3009"){let l=(0,be.record)(s.typedData,"wallet typed data"),u=(0,be.record)(l.message,"wallet message");if(s.scheme!=="exact"||u.value!==r)throw new be.AgentOperationContractError("invalid_amount","wallet value differs from purchase amount");d={rail:n.rail,economics:a,network:s.network,asset:s.asset,payee:u.to,...s.approvedRequest===void 0&&s.requestHash===void 0?{}:{requestHash:s.requestHash}}}else if(n.rail==="card:vic"&&n.execution.adapter==="card.vic")d={rail:n.rail,economics:a,processorAction:s.processorAction,captureMode:s.captureMode};else throw new be.AgentOperationContractError("invalid_contract","unsupported purchase producer profile");if(s.requestHash!==void 0&&(0,_n.createHash)("sha256").update((0,be.canonicalJson)(s.approvedRequest)).digest("base64url")!==s.requestHash)throw new be.AgentOperationContractError("invalid_contract","purchase request hash mismatch");return(0,rv.parsePurchaseTerms)({v:1,profile:s.requestHash===void 0?"url_resource_v1":"approved_x402_request_v1",alternatives:[d]}).alternatives[0]}function mO(e){let t=(0,be.bounded)(e,"x402 resource",2048);return(0,_n.createHash)("sha256").update(`visa-x402-resource:v1:${t}`,"utf8").digest("base64url")}function iv(e){return`economic:${(0,_n.createHash)("sha256").update((0,be.canonicalJson)({domain:"visa.agent-operation-idempotency.v1",agentId:e.agentId,economicIntentId:e.economicIntentId})).digest("base64url")}`}function gO(e){let t=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;for(let n of["agentId","purchaseId","attemptId"])if(typeof e[n]!="string"||!t.test(e[n]))throw new be.AgentOperationContractError("invalid_contract",`${n} must be a canonical UUID`);if(typeof e.termsHash!="string"||!/^[A-Za-z0-9_-]{43}$/.test(e.termsHash)||Buffer.from(e.termsHash,"base64url").toString("base64url")!==e.termsHash)throw new be.AgentOperationContractError("invalid_contract","termsHash must be canonical SHA-256");return iv({agentId:e.agentId,economicIntentId:`purchase:${e.purchaseId}:attempt:${e.attemptId}:terms:${e.termsHash}`})}function ov(e){return(0,_n.createHash)("sha256").update((0,be.canonicalJson)({domain:"visa.agent-operation-terms.v1",operationId:e.operationId,idempotencyKey:e.idempotencyKey,agentId:e.agentId,runtimeId:e.runtimeId,rail:e.rail,effect:e.effect,execution:e.execution})).digest("base64url")}function av(e){return(0,_n.createHash)("sha256").update((0,be.canonicalJson)(e)).digest("base64url")}function yO(e,t,n){return t===n?!0:ov(e)!==n?!1:t===av(e)}function _O(e){return(0,_n.createHash)("sha256").update((0,be.canonicalJson)(e)).digest("base64url")}var wO={kind:"identity_pop",popJwt:"unsigned",keyJkt:Buffer.alloc(32).toString("base64url")};function sv(e,t=Date.now()){let n={v:Id.AGENT_OPERATION_VERSION,...e,principal:wO,intentHash:Buffer.alloc(32).toString("base64url"),execution:{...e.execution,payloadHash:pp(e.execution.payload)}};n.intentHash=fp(n);let r=ws(n,t),{v:i,principal:o,...a}=r;return a}function cv(e,t,n=Date.now()){return ws({v:Id.AGENT_OPERATION_VERSION,...e,principal:t},n)}function EO(e,t=Date.now()){let{principal:n,...r}=e;return cv(sv(r,t),n,t)}function vO(e){let t=(0,be.record)(e,"historical operation");if(typeof t.createdAt!="string")throw new be.AgentOperationContractError("invalid_window","historical operation creation time is missing");return ws(e,Date.parse(t.createdAt))}function ws(e,t=Date.now()){let n=(0,Id.parseAgentOperationStructure)(e,t);if(pp(n.execution.payload)!==n.execution.payloadHash)throw new be.AgentOperationContractError("commitment_mismatch","execution payload does not match its commitment");if(fp(n)!==n.intentHash)throw new be.AgentOperationContractError("intent_mismatch","intentHash does not bind the exact operation effect and execution commitment");return n}});var Tb=y((KH,Ib)=>{"use strict";var AO=Object.create,Ld=Object.defineProperty,SO=Object.getOwnPropertyDescriptor,Dv=Object.getOwnPropertyNames,IO=Object.getPrototypeOf,TO=Object.prototype.hasOwnProperty,PO=(e,t)=>function(){try{return t||(0,e[Dv(e)[0]])((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},kO=(e,t)=>{for(var n in t)Ld(e,n,{get:t[n],enumerable:!0})},Mv=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of Dv(t))!TO.call(e,i)&&i!==n&&Ld(e,i,{get:()=>t[i],enumerable:!(r=SO(t,i))||r.enumerable});return e},Lv=(e,t,n)=>(n=e!=null?AO(IO(e)):{},Mv(t||!e||!e.__esModule?Ld(n,"default",{value:e,enumerable:!0}):n,e)),CO=e=>Mv(Ld({},"__esModule",{value:!0}),e),RO=PO({"../shared/dist/canonical-contract.js"(e){"use strict";Object.defineProperty(e,"__esModule",{value:!0}),e.CanonicalJsonError=e.CANONICAL_OPAQUE_ID_MAX_BYTES=e.CANONICAL_OPAQUE_ID_RE=e.CANONICAL_OPAQUE_ID_PATTERN=void 0,e.utf8ByteLength=r,e.isCanonicalText=i,e.compareCanonicalKeys=o,e.isCanonicalOpaqueId=a,e.assertCanonicalOpaqueId=s,e.canonicalJsonExact=l,e.isValidCalendarDateTime=u,e.CANONICAL_OPAQUE_ID_PATTERN="^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$",e.CANONICAL_OPAQUE_ID_RE=new RegExp(e.CANONICAL_OPAQUE_ID_PATTERN),e.CANONICAL_OPAQUE_ID_MAX_BYTES=128;var t=/[\u0000-\u001f\u007f\u2028\u2029]/,n=new TextEncoder;function r(f){return n.encode(f).length}function i(f,h){return typeof f=="string"&&f.length>0&&r(f)<=h&&f.trim()===f&&f.normalize("NFC")===f&&!t.test(f)}function o(f,h){let p=n.encode(f),m=n.encode(h),w=Math.min(p.length,m.length);for(let v=0;v<w;v+=1)if(p[v]!==m[v])return p[v]-m[v];return p.length-m.length}function a(f){return typeof f=="string"&&r(f)<=e.CANONICAL_OPAQUE_ID_MAX_BYTES&&e.CANONICAL_OPAQUE_ID_RE.test(f)}function s(f,h="value"){if(!a(f))throw new Error(`${h} must be a canonical opaque id (max 128 ASCII bytes)`)}var c=/[\ud800-\udbff](?![\udc00-\udfff])|(?<![\ud800-\udbff])[\udc00-\udfff]/,d=class extends Error{constructor(f){super(f),this.name="CanonicalJsonError"}};e.CanonicalJsonError=d;function l(f,h=0){if(h>16)throw new d("nesting is deeper than 16");if(f===null||typeof f=="boolean")return JSON.stringify(f);if(typeof f=="string"){if(c.test(f))throw new d("text is not valid Unicode");return JSON.stringify(f)}if(typeof f=="number"){if(!Number.isSafeInteger(f)||Object.is(f,-0))throw new d("numbers must be whole and at most 2^53 - 1; put amounts and decimals in strings");return JSON.stringify(f)}if(Array.isArray(f)){if(f.length>1024)throw new d("an array has more than 1024 items");return`[${f.map(m=>l(m,h+1)).join(",")}]`}if(typeof f!="object"||Object.getPrototypeOf(f)!==Object.prototype)throw new d("only JSON objects, arrays, strings, whole numbers and booleans");let p=Object.keys(f);if(p.length>512)throw new d("an object has more than 512 keys");for(let m of p)if(!i(m,128))throw new d("keys must be non-empty trimmed NFC text of at most 128 bytes");return`{${p.sort(o).map(m=>`${JSON.stringify(m)}:${l(f[m],h+1)}`).join(",")}}`}function u(f,h,p,m,w,v){let _=new Date(0);return _.setUTCFullYear(f,h-1,p),_.setUTCHours(m,w,v,0),f!==0&&_.getUTCFullYear()===f&&_.getUTCMonth()===h-1&&_.getUTCDate()===p&&_.getUTCHours()===m&&_.getUTCMinutes()===w&&_.getUTCSeconds()===v}}}),Jv={};kO(Jv,{AGENT_AUTHORITY_VALUATION_POLICY:()=>xd,AGENT_AUTHORITY_VERSION:()=>ji,AGENT_AUTHORIZATION_SCOPES:()=>Lp,AGENT_BUDGET_EPOCH_MODES:()=>ub,AGENT_CHANNEL_ASSURANCES:()=>mb,AGENT_CHANNEL_KINDS:()=>pb,AGENT_CHANNEL_STATUSES:()=>hb,AGENT_EXECUTION_READINESS_REASONS:()=>ON,AGENT_KEY_CUSTODIES:()=>NN,AGENT_KEY_STATUSES:()=>DN,AGENT_PAIRING_PROTOCOL_VERSION_V2:()=>Ip,AGENT_PAYMENT_MODE_NAMES:()=>RN,AGENT_PAYMENT_RAILS:()=>bp,AGENT_PAYMENT_SURFACES:()=>vp,USD_MICROS_PER_CENT:()=>Mp,VIC_PROCESSOR_ACTIONS:()=>CN,WALLET_GRANT_SCOPE:()=>fb,agentAuthorityGrantHash:()=>GN,authorizationScopeFacts:()=>WN,base64ToBytes:()=>ab,base64UrlToBytes:()=>Kd,bytesToBase64:()=>ob,bytesToBase64Url:()=>Fn,bytesToHex:()=>bN,canonicalAgentAuthorityGrant:()=>vb,canonicalAgentChannelDescriptor:()=>BN,canonicalPairingDeliveryArtifactV2:()=>a1,canonicalPairingTermsV2:()=>Kp,canonicalPayWithinBudget:()=>Eb,canonicalSpendAuthorizationIntent:()=>jp,centsToUsdMicros:()=>VN,computeJkt:()=>db,concatBytes:()=>SN,defaultPayWithinBudget:()=>xN,generateKeyPair:()=>yN,generateSeed:()=>rb,getPublicKey:()=>qd,grantPaymentRails:()=>Jp,hexToBytes:()=>AN,isCanonicalBase64Url32:()=>jr,jwkToKeyPair:()=>kN,jwkToPublicKey:()=>PN,jwkToSeed:()=>cb,keyPairFromSeed:()=>ib,pairingClaimTokenHash:()=>o1,pairingSha256:()=>Hp,pairingTermsV2Hash:()=>Sb,publicKeyToJwk:()=>TN,randomPairingClaimToken:()=>i1,seedToJwk:()=>IN,sign:()=>_N,signAsync:()=>EN,spendAuthorizationIntentHash:()=>bb,usdcAtomicToUsdMicros:()=>$N,verify:()=>wN,verifyAsync:()=>vN,walletAuthorizationRequestHash:()=>YN});Ib.exports=CO(Jv);var Jd=Object.freeze,Yo=0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,Nd=0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,Cd=0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,_p=0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,wp=0x6666666666666666666666666666666666666666666666666666666666666658n,Rd=Yo-1n,xO=Jd({p:Yo,n:Nd,h:8n,a:Rd,d:Cd,Gx:_p,Gy:wp}),Jr=32,mv=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&e.BYTES_PER_ELEMENT===1,wt=(e,t,n="")=>{if(mv(e)&&(t===void 0||e.length===t))return e;let r=mv(e),i=t!==void 0?` of length ${t}`:"",o=r?`length=${e.length}`:`type=${typeof e}`,a=(n?`"${n}" `:"")+"expected Uint8Array"+i+", got "+o;throw r?new RangeError(a):new TypeError(a)},Ud=(e,t="",n)=>Uint8Array.from(wt(e,n,t)),Uv=(e,t)=>e.toString(16).padStart(t,"0"),Pp=e=>{let t="";for(let n of wt(e))t+=Uv(n,2);return t},kp=e=>{let t="hex invalid";if(typeof e!="string")throw new TypeError(t);if(e.length%2||!/^[\da-f]*$/i.test(e))throw new RangeError(t);let n=new Uint8Array(e.length/2);for(let r=0,i=0;r<n.length;r++,i+=2){let o=e.charCodeAt(i),a=e.charCodeAt(i+1);n[r]=((o&15)+(o>>6)*9)*16+(a&15)+(a>>6)*9}return n},Ji=(...e)=>{let t=0;for(let i of e)t+=wt(i).length;let n=new Uint8Array(t),r=0;for(let i of e)n.set(i,r),r+=i.length;return n},jv=(e=Jr)=>{let t=globalThis?.crypto;if(typeof t?.getRandomValues!="function")throw new Error("crypto.getRandomValues must be defined, consider polyfill");return t.getRandomValues(new Uint8Array(e))},xi=(e,t,n,r="bad number: out of range")=>{if(typeof e!="bigint")throw new TypeError(r);if(t<=e&&e<n)return e;throw new RangeError(r)},he=(e,t=Yo)=>(e%=t)>=0n?e:t+e,gv=(1n<<255n)-1n,M=e=>{if(e<0n)throw new RangeError("negative coordinate");let t=(e>>255n)*19n+(e&gv);return t=(t>>255n)*19n+(t&gv),t%Yo},qv=e=>he(e,Nd),Kv=(e,t)=>{if(e===0n)throw new Error("invert: expected non-zero number");if(t<=1n)throw new Error("invert: expected modulus > 1, got "+t);let n=he(e,t),r=t,i=0n,o=1n;for(;n!==0n;){let s=r/n,c=r-n*s,d=i-o*s;r=n,n=c,i=o,o=d}if(r!==1n)throw new Error("invert: does not exist");return he(i,t)},Hv=e=>{let t=Xv[e];if(typeof t!="function")throw new Error("hashes."+e+" not set");return t},Cp=(e,...t)=>wt(Hv(e)(Ji(...t)),64,"digest"),Rp=async(e,...t)=>wt(await Hv(e)(Ji(...t)),64,"digest"),mp=e=>{if(e instanceof Ui)return e;throw new TypeError("Point expected")},Vv=2n**256n,Ui=class Oi{static BASE;static ZERO;X;Y;Z;T;constructor(t,n,r,i){let o=Vv;this.X=xi(t,0n,o),this.Y=xi(n,0n,o),this.Z=xi(r,1n,o),this.T=xi(i,0n,o),Jd(this)}static CURVE(){return xO}static fromAffine(t){return new Oi(t.x,t.y,1n,M(t.x*t.y))}static fromBytes(t,n=!1){let r=Ud(t,"point",Jr),i=r[31];r[31]=i&-129;let o=xp(r);n||xi(o,0n,Yo);let a=M(o*o),s=he(a-1n),c=M(Cd*a+1n),{isValid:d,value:l}=NO(s,c);if(!d)throw new Error("bad point: y not sqrt");let u=!!(i&128);if(!n&&l===0n&&u)throw new Error("bad point: x==0, isLastByteOdd");return u!==!!(l&1n)&&(l=he(-l)),new Oi(l,o,1n,M(l*o))}static fromHex(t,n){return Oi.fromBytes(kp(t),n)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=Rd,n=Cd,r=this;if(r.is0())throw new Error("bad point: ZERO");let{X:i,Y:o,Z:a,T:s}=r,c=M(i*i),d=M(o*o),l=M(a*a),u=M(l*l),f=M(c*t),h=M(l*(f+d)),p=he(u+M(n*M(c*d)));if(h!==p)throw new Error("bad point: equation left != right (1)");let m=M(i*o),w=M(a*s);if(m!==w)throw new Error("bad point: equation left != right (2)");return this}equals(t){let{X:n,Y:r,Z:i}=this,{X:o,Y:a,Z:s}=mp(t);return M(n*s)===M(o*i)&&M(r*s)===M(a*i)}is0(){return this.equals(Ni)}negate(){return new Oi(he(-this.X),this.Y,this.Z,he(-this.T))}double(){let{X:t,Y:n,Z:r}=this,i=Rd,o=M(t*t),a=M(n*n),s=M(2n*r*r),c=M(i*o),d=he(t+n),l=he(M(d*d)-o-a),u=he(c+a),f=he(u-s),h=he(c-a),p=M(l*f),m=M(u*h),w=M(l*h),v=M(f*u);return new Oi(p,m,v,w)}add(t){let{X:n,Y:r,Z:i,T:o}=this,{X:a,Y:s,Z:c,T:d}=mp(t),l=Rd,u=Cd,f=M(n*a),h=M(r*s),p=M(M(o*u)*d),m=M(i*c),w=he(M(he(n+r)*he(a+s))-f-h),v=he(m-p),_=he(m+p),A=he(h-M(l*f)),j=M(w*v),Q=M(_*A),X=M(w*A),H=M(v*_);return new Oi(j,Q,H,X)}subtract(t){return this.add(mp(t).negate())}multiply(t,n=!0){if(!n&&t===0n||(xi(t,1n,Nd),!n&&this.is0()))return Ni;if(t===1n)return this;if(this.equals(Ur))return VO(t).p;let r=Ni,i=Ur,o=this;for(let a=0;n?a<256:t>0n;a++)t&1n?r=r.add(o):n&&(i=i.add(o)),o=o.double(),t>>=1n;return r}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){let{X:t,Y:n,Z:r}=this;if(this.equals(Ni))return{x:0n,y:1n};let i=Kv(r,Yo);if(M(r*i)!==1n)throw new Error("invalid inverse");return{x:M(t*i),y:M(n*i)}}toBytes(){let{x:t,y:n}=this.toAffine(),r=$v(n);return r[31]|=t&1n?128:0,r}toHex(){return Pp(this.toBytes())}clearCofactor(){return this.multiply(8n,!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){return this.multiply(Nd/2n,!1).double().add(this).is0()}},Ur=new Ui(_p,wp,1n,he(_p*wp)),Ni=new Ui(0n,1n,1n,0n);Ui.BASE=Ur;Ui.ZERO=Ni;var $v=e=>kp(Uv(xi(e,0n,Vv),64)).reverse(),xp=e=>BigInt("0x"+Pp(Uint8Array.from(wt(e)).reverse())),wn=(e,t)=>{let n=e;for(;t-- >0;)n=M(n*n);return n},OO=e=>{let t=M(e*e),n=M(t*e),r=M(wn(n,2)*n),i=M(wn(r,1)*e),o=M(wn(i,5)*i),a=M(wn(o,10)*o),s=M(wn(a,20)*a),c=M(wn(s,40)*s),d=M(wn(c,80)*c),l=M(wn(d,80)*c),u=M(wn(l,10)*o);return M(wn(u,2)*e)},yv=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,NO=(e,t)=>{let n=M(t*M(t*t)),r=M(M(n*n)*t),i=OO(M(e*r)),o=M(e*M(n*i)),a=M(t*M(o*o)),s=o,c=M(o*yv),d=a===e,l=a===he(-e),u=a===he(-e*yv);return d&&(o=s),(l||u)&&(o=c),(he(o)&1n)===1n&&(o=he(-o)),{isValid:d||l,value:o}},Dd=e=>qv(xp(e)),Wv=e=>{let t=Ud(e),n=t.slice(0,32);n[0]&=248,n[31]&=127,n[31]|=64;let r=t.slice(32),i=Dd(n),o=Ur.multiply(i),a=o.toBytes();return{head:n,prefix:r,scalar:i,point:o,pointBytes:a}},Fv=e=>Rp("sha512Async",wt(e,Jr,"secretKey")).then(Wv),Op=e=>Wv(Cp("sha512",wt(e,Jr,"secretKey"))),DO=e=>Op(e).pointBytes,Bv=async e=>e[1](await Rp("sha512Async",e[0])),Gv=e=>e[1](Cp("sha512",e[0])),Yv=(e,t,n)=>{let{pointBytes:r,scalar:i}=e,o=Dd(t),a=Ur.multiply(o).toBytes();return[Ji(a,r,n),d=>{let l=qv(o+Dd(d)*i);return wt(Ji(a,$v(l)),64)}]},MO=async(e,t)=>{let n=Ud(e,"message"),r=await Fv(t);return Bv(Yv(r,await Rp("sha512Async",r.prefix,n),n))},LO=(e,t)=>{let n=Ud(e,"message"),r=Op(t);return Gv(Yv(r,Cp("sha512",r.prefix,n),n))},JO=e=>{if(e===null||typeof e!="object")throw new TypeError("expected valid options object");return e.zip215??!0},zv=(e,t,n,r)=>{e=wt(e,64,"signature"),t=wt(t,void 0,"message"),n=wt(n,Jr,"publicKey");let i=JO(r),o=e.subarray(0,Jr),a=xp(e.subarray(Jr,64)),s,c,d,l=Uint8Array.of(),u=!1;try{s=Ui.fromBytes(n,i),c=Ui.fromBytes(o,i),d=Ur.multiply(a,!1),l=Ji(o,n,t),u=!0}catch{}return[l,h=>{if(!u||!i&&s.isSmallOrder())return!1;let p=Dd(h);return c.add(s.multiply(p,!1)).subtract(d).clearCofactor().is0()}]},UO=async(e,t,n,r={})=>Bv(zv(e,t,n,r)),jO=(e,t,n,r={})=>Gv(zv(e,t,n,r)),Np=Jd({bytesToHex:Pp,hexToBytes:kp,concatBytes:Ji,mod:he,invert:Kv,randomBytes:jv}),Xv={sha512Async:async e=>{let t=globalThis?.crypto?.subtle;if(!t)throw new Error("crypto.subtle must be defined, consider polyfill");return new Uint8Array(await t.digest("SHA-512",Ji(e)))},sha512:void 0},qO=e=>wt(e===void 0?jv():e,Jr,"seed"),KO=Jd({getExtendedPublicKeyAsync:Fv,getExtendedPublicKey:Op,randomSecretKey:qO}),HO=()=>{let e=[],t=Ur,n;for(let r=0;r<33;r++){n=t,e.push(n);for(let i=1;i<128;i++)n=n.add(t),e.push(n);t=n.double()}return e},_v=void 0,wv=(e,t)=>{let n=t.negate();return e?n:t},VO=e=>{let t=_v||(_v=HO()),n=Ni,r=Ur;for(let i=0;i<33;i++){let o=Number(e&255n);e>>=8n,o>128&&(o-=256,e+=1n);let a=i*128,s=a+Math.abs(o)-1,c=i%2!==0,d=o<0;o===0?r=r.add(wv(c,t[a])):n=n.add(wv(d,t[s]))}if(e!==0n)throw new Error("invalid wnaf");return{p:n,f:r}},Td=BigInt(2**32-1),Ev=BigInt(32);function $O(e,t=!1){return t?{h:Number(e&Td),l:Number(e>>Ev&Td)}:{h:Number(e>>Ev&Td)|0,l:Number(e&Td)|0}}function WO(e,t=!1){let n=e.length,r=new Uint32Array(n),i=new Uint32Array(n);for(let o=0;o<n;o++){let{h:a,l:s}=$O(e[o],t);[r[o],i[o]]=[a,s]}return[r,i]}var FO=e=>e/2**32|0,BO=e=>e>>>0;function GO(e,t,n,r){let i=FO(n),o=BO(n);e.setUint32(t,r?o:i,r),e.setUint32(t+4,r?i:o,r)}var vv=(e,t,n)=>e>>>n,bv=(e,t,n)=>e<<32-n|t>>>n,Fo=(e,t,n)=>e>>>n|t<<32-n,Bo=(e,t,n)=>e<<32-n|t>>>n,Pd=(e,t,n)=>e<<64-n|t>>>n-32,kd=(e,t,n)=>e>>>n-32|t<<64-n;function Wn(e,t,n,r){let i=(t>>>0)+(r>>>0);return{h:e+n+(i/2**32|0)|0,l:i|0}}var YO=(e,t,n)=>(e>>>0)+(t>>>0)+(n>>>0),zO=(e,t,n,r)=>t+n+r+(e/2**32|0)|0,XO=(e,t,n,r)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0),ZO=(e,t,n,r,i)=>t+n+r+i+(e/2**32|0)|0,QO=(e,t,n,r,i)=>(e>>>0)+(t>>>0)+(n>>>0)+(r>>>0)+(i>>>0),eN=(e,t,n,r,i,o)=>t+n+r+i+o+(e/2**32|0)|0;function Av(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}var Ep=e=>e?`"${e}" `:"";function tN(e,t=""){if(typeof e!="number")throw new TypeError(Ep(t)+"expected number, got "+typeof e);if(!Number.isSafeInteger(e)||e<0)throw new RangeError(Ep(t)+"expected integer >= 0, got "+e);return e}function Zv(e,t,n=""){if(Av(e)&&(t===void 0||e.length===t))return e;t!==void 0&&tN(t,"length");let r=Av(e),i=t!==void 0?` of length ${t}`:"",o=r?`length=${e.length}`:`type=${typeof e}`,a=Ep(n)+"expected Uint8Array"+i+", got "+o;throw r?new RangeError(a):new TypeError(a)}var nN=(e,t)=>{if(e===null||typeof e!="object"||Array.isArray(e))throw new TypeError((t==="object"?"":`"${t}" `)+"expected object, got type="+typeof e)},Sv=(e,t)=>{nN(e,t);let n=Object.getPrototypeOf(e);if(n!==Object.prototype&&n!==null)throw new TypeError(`"${t}" expected plain object`);if(Object.hasOwn(e,"__proto__"))throw new TypeError(`"${t}.__proto__" is not allowed`)};function Iv(e,t=!0){if(e.destroyed)throw new Error("hash was destroyed");if(t&&e.finished)throw new Error("digest() was already called")}function rN(e,t){Zv(e,void 0,"output");let n=t.outputLen;if(!(e.length>=n))throw new RangeError('"output" expected length >= '+n)}function Md(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function gp(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function En(e,t){return e<<32-t|e>>>t}function iN(e,t,n="opts"){return Sv(e,"defaults"),t!==void 0&&Sv(t,n),Object.assign(Object.create(null),e,t)}function Qv(e,t={}){if(typeof e!="function")throw new TypeError('"hashCons" expected function, got type='+typeof e);t=iN({},t,"info");let n=(i,o)=>e(o).update(i).digest(),r=e(void 0);return n.outputLen=r.outputLen,n.blockLen=r.blockLen,n.canXOF=r.canXOF,n.create=i=>e(i),Object.assign(n,t),Object.freeze(n)}var eb=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});function oN(e,t,n){return e&t^~e&n}function aN(e,t,n){return e&t^e&n^t&n}var tb=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,n,r){this.blockLen=e,this.outputLen=t,this.padOffset=n,this.isLE=r,this.buffer=new Uint8Array(e),this.view=gp(this.buffer)}update(e){Iv(this),Zv(e);let{view:t,buffer:n,blockLen:r}=this,i=e.length,o=!1;for(let a=0;a<i;){let s=Math.min(r-this.pos,i-a);if(s===r){let c=gp(e);for(;r<=i-a;a+=r)this.process(c,a);o=!0;continue}n.set(a===0&&s===i?e:e.subarray(a,a+s),this.pos),this.pos+=s,a+=s,this.pos===r&&(this.process(t,0),this.pos=0,o=!0)}return this.length+=e.length,o&&this.roundClean(),this}digestInto(e){Iv(this),rN(e,this),this.finished=!0;let{buffer:t,view:n,blockLen:r,isLE:i}=this,{pos:o}=this;t[o++]=128,t.fill(0,o),this.padOffset>r-o&&(this.process(n,0),t.fill(0)),GO(n,r-8,this.length*8,i),this.process(n,0),this.roundClean();let a=e===t?n:gp(e),s=this.outputLen,c=s/4,d=this.get();if(s%4||c>d.length)throw new Error("invalid outputLen");for(let l=0;l<c;l++)a.setUint32(4*l,d[l],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let n=e.slice(0,t);return this.destroy(),n}_cloneIntoMeta(e){let{buffer:t,length:n,finished:r,destroyed:i,pos:o}=this;return e.destroyed=i,e.finished=r,e.length=n,e.pos=o,o&&e.buffer.set(t),e}clone(){return this._cloneInto()}},sN=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),cN=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),dN=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Dr=new Uint32Array(64),lN=class extends tb{A=0;B=0;C=0;D=0;E=0;F=0;G=0;H=0;constructor(e,t){super(64,e,8,!1),this.A=t[0]|0,this.B=t[1]|0,this.C=t[2]|0,this.D=t[3]|0,this.E=t[4]|0,this.F=t[5]|0,this.G=t[6]|0,this.H=t[7]|0}get(){let{A:e,B:t,C:n,D:r,E:i,F:o,G:a,H:s}=this;return[e,t,n,r,i,o,a,s]}set(e,t,n,r,i,o,a,s){this.A=e|0,this.B=t|0,this.C=n|0,this.D=r|0,this.E=i|0,this.F=o|0,this.G=a|0,this.H=s|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let l=0;l<16;l++,t+=4)Dr[l]=e.getUint32(t,!1);for(let l=16;l<64;l++){let u=Dr[l-15],f=Dr[l-2],h=En(u,7)^En(u,18)^u>>>3,p=En(f,17)^En(f,19)^f>>>10;Dr[l]=p+Dr[l-7]+h+Dr[l-16]|0}let{A:n,B:r,C:i,D:o,E:a,F:s,G:c,H:d}=this;for(let l=0;l<64;l++){let u=En(a,6)^En(a,11)^En(a,25),f=d+u+oN(a,s,c)+dN[l]+Dr[l]|0,p=(En(n,2)^En(n,13)^En(n,22))+aN(n,r,i)|0;d=c,c=s,s=a,a=o+f|0,o=i,i=r,r=n,n=f+p|0}n=n+this.A|0,r=r+this.B|0,i=i+this.C|0,o=o+this.D|0,a=a+this.E|0,s=s+this.F|0,c=c+this.G|0,d=d+this.H|0,this.set(n,r,i,o,a,s,c,d)}roundClean(){Md(Dr)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Md(this.buffer)}},uN=class extends lN{constructor(){super(32,sN)}},nb=WO(["0x428a2f98d728ae22","0x7137449123ef65cd","0xb5c0fbcfec4d3b2f","0xe9b5dba58189dbbc","0x3956c25bf348b538","0x59f111f1b605d019","0x923f82a4af194f9b","0xab1c5ed5da6d8118","0xd807aa98a3030242","0x12835b0145706fbe","0x243185be4ee4b28c","0x550c7dc3d5ffb4e2","0x72be5d74f27b896f","0x80deb1fe3b1696b1","0x9bdc06a725c71235","0xc19bf174cf692694","0xe49b69c19ef14ad2","0xefbe4786384f25e3","0x0fc19dc68b8cd5b5","0x240ca1cc77ac9c65","0x2de92c6f592b0275","0x4a7484aa6ea6e483","0x5cb0a9dcbd41fbd4","0x76f988da831153b5","0x983e5152ee66dfab","0xa831c66d2db43210","0xb00327c898fb213f","0xbf597fc7beef0ee4","0xc6e00bf33da88fc2","0xd5a79147930aa725","0x06ca6351e003826f","0x142929670a0e6e70","0x27b70a8546d22ffc","0x2e1b21385c26c926","0x4d2c6dfc5ac42aed","0x53380d139d95b3df","0x650a73548baf63de","0x766a0abb3c77b2a8","0x81c2c92e47edaee6","0x92722c851482353b","0xa2bfe8a14cf10364","0xa81a664bbc423001","0xc24b8b70d0f89791","0xc76c51a30654be30","0xd192e819d6ef5218","0xd69906245565a910","0xf40e35855771202a","0x106aa07032bbd1b8","0x19a4c116b8d2d0c8","0x1e376c085141ab53","0x2748774cdf8eeb99","0x34b0bcb5e19b48a8","0x391c0cb3c5c95a63","0x4ed8aa4ae3418acb","0x5b9cca4f7763e373","0x682e6ff3d6b2b8a3","0x748f82ee5defb2fc","0x78a5636f43172f60","0x84c87814a1f0ab72","0x8cc702081a6439ec","0x90befffa23631e28","0xa4506cebde82bde9","0xbef9a3f7b2c67915","0xc67178f2e372532b","0xca273eceea26619c","0xd186b8c721c0c207","0xeada7dd6cde0eb1e","0xf57d4f7fee6ed178","0x06f067aa72176fba","0x0a637dc5a2c898a6","0x113f9804bef90dae","0x1b710b35131c471b","0x28db77f523047d84","0x32caab7b40c72493","0x3c9ebe0a15c9bebc","0x431d67c49c100d4c","0x4cc5d4becb3e42b6","0x597f299cfc657e2a","0x5fcb6fab3ad6faec","0x6c44198c4a475817"].map(e=>BigInt(e))),fN=nb[0],pN=nb[1],Mr=new Uint32Array(80),Lr=new Uint32Array(80),hN=class extends tb{Ah=0;Al=0;Bh=0;Bl=0;Ch=0;Cl=0;Dh=0;Dl=0;Eh=0;El=0;Fh=0;Fl=0;Gh=0;Gl=0;Hh=0;Hl=0;constructor(e,t){super(128,e,16,!1),this.Ah=t[0]|0,this.Al=t[1]|0,this.Bh=t[2]|0,this.Bl=t[3]|0,this.Ch=t[4]|0,this.Cl=t[5]|0,this.Dh=t[6]|0,this.Dl=t[7]|0,this.Eh=t[8]|0,this.El=t[9]|0,this.Fh=t[10]|0,this.Fl=t[11]|0,this.Gh=t[12]|0,this.Gl=t[13]|0,this.Hh=t[14]|0,this.Hl=t[15]|0}get(){let{Ah:e,Al:t,Bh:n,Bl:r,Ch:i,Cl:o,Dh:a,Dl:s,Eh:c,El:d,Fh:l,Fl:u,Gh:f,Gl:h,Hh:p,Hl:m}=this;return[e,t,n,r,i,o,a,s,c,d,l,u,f,h,p,m]}set(e,t,n,r,i,o,a,s,c,d,l,u,f,h,p,m){this.Ah=e|0,this.Al=t|0,this.Bh=n|0,this.Bl=r|0,this.Ch=i|0,this.Cl=o|0,this.Dh=a|0,this.Dl=s|0,this.Eh=c|0,this.El=d|0,this.Fh=l|0,this.Fl=u|0,this.Gh=f|0,this.Gl=h|0,this.Hh=p|0,this.Hl=m|0}_cloneInto(e){return(e||=new this.constructor).set(...this.get()),this._cloneIntoMeta(e)}process(e,t){for(let _=0;_<16;_++,t+=4)Mr[_]=e.getUint32(t),Lr[_]=e.getUint32(t+=4);for(let _=16;_<80;_++){let A=Mr[_-15]|0,j=Lr[_-15]|0,Q=Fo(A,j,1)^Fo(A,j,8)^vv(A,j,7),X=Bo(A,j,1)^Bo(A,j,8)^bv(A,j,7),H=Mr[_-2]|0,V=Lr[_-2]|0,Ee=Fo(H,V,19)^Pd(H,V,61)^vv(H,V,6),Ge=Bo(H,V,19)^kd(H,V,61)^bv(H,V,6),jt=XO(X,Ge,Lr[_-7],Lr[_-16]),ee=ZO(jt,Q,Ee,Mr[_-7],Mr[_-16]);Mr[_]=ee|0,Lr[_]=jt|0}let{Ah:n,Al:r,Bh:i,Bl:o,Ch:a,Cl:s,Dh:c,Dl:d,Eh:l,El:u,Fh:f,Fl:h,Gh:p,Gl:m,Hh:w,Hl:v}=this;for(let _=0;_<80;_++){let A=Fo(l,u,14)^Fo(l,u,18)^Pd(l,u,41),j=Bo(l,u,14)^Bo(l,u,18)^kd(l,u,41),Q=l&f^~l&p,X=u&h^~u&m,H=QO(v,j,X,pN[_],Lr[_]),V=eN(H,w,A,Q,fN[_],Mr[_]),Ee=H|0,Ge=Fo(n,r,28)^Pd(n,r,34)^Pd(n,r,39),jt=Bo(n,r,28)^kd(n,r,34)^kd(n,r,39),ee=n&i^n&a^i&a,On=r&o^r&s^o&s;w=p|0,v=m|0,p=f|0,m=h|0,f=l|0,h=u|0,{h:l,l:u}=Wn(c|0,d|0,V|0,Ee|0),c=a|0,d=s|0,a=i|0,s=o|0,i=n|0,o=r|0;let qt=YO(Ee,jt,On);n=zO(qt,V,Ge,ee),r=qt|0}({h:n,l:r}=Wn(this.Ah|0,this.Al|0,n|0,r|0)),{h:i,l:o}=Wn(this.Bh|0,this.Bl|0,i|0,o|0),{h:a,l:s}=Wn(this.Ch|0,this.Cl|0,a|0,s|0),{h:c,l:d}=Wn(this.Dh|0,this.Dl|0,c|0,d|0),{h:l,l:u}=Wn(this.Eh|0,this.El|0,l|0,u|0),{h:f,l:h}=Wn(this.Fh|0,this.Fl|0,f|0,h|0),{h:p,l:m}=Wn(this.Gh|0,this.Gl|0,p|0,m|0),{h:w,l:v}=Wn(this.Hh|0,this.Hl|0,w|0,v|0),this.set(n,r,i,o,a,s,c,d,l,u,f,h,p,m,w,v)}roundClean(){Md(Mr,Lr)}destroy(){this.destroyed=!0,Md(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},mN=class extends hN{constructor(){super(64,cN)}},jd=Qv(()=>new uN,eb(1)),gN=Qv(()=>new mN,eb(3)),Tv=Xv;Tv.sha512||(Tv.sha512=e=>gN(e));var Pv=32;function rb(){return KO.randomSecretKey()}function qd(e){return DO(e)}function yN(){let e=rb();return{secretKey:e,publicKey:qd(e)}}function ib(e){if(e.length!==Pv)throw new Error(`Ed25519 seed must be ${Pv} bytes, got ${e.length}`);return{secretKey:e,publicKey:qd(e)}}function _N(e,t){return LO(t,e)}function wN(e,t,n){return jO(t,n,e)}function EN(e,t){return MO(t,e)}function vN(e,t,n){return UO(t,n,e)}var bN=Np.bytesToHex,AN=Np.hexToBytes,SN=Np.concatBytes;function ob(e){let t="";for(let n=0;n<e.length;n++)t+=String.fromCharCode(e[n]);return btoa(t)}function ab(e){let t=atob(e),n=new Uint8Array(t.length);for(let r=0;r<t.length;r++)n[r]=t.charCodeAt(r);return n}function Fn(e){return ob(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Kd(e){let t=e.length%4===0?0:4-e.length%4,n=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat(t);return ab(n)}function sb(e){if(e.kty!=="OKP"||e.crv!=="Ed25519")throw new Error("not an Ed25519 OKP JWK")}function IN(e){let t=qd(e);return{kty:"OKP",crv:"Ed25519",x:Fn(t),d:Fn(e)}}function TN(e){return{kty:"OKP",crv:"Ed25519",x:Fn(e)}}function cb(e){if(sb(e),!e.d)throw new Error("Ed25519 JWK has no private component (d)");return Kd(e.d)}function PN(e){return sb(e),Kd(e.x)}function kN(e){return ib(cb(e))}function db(e){if(e.kty!=="OKP")throw new Error(`computeJkt expects an OKP JWK; got kty="${e.kty}"`);let t=JSON.stringify({crv:e.crv,kty:e.kty,x:e.x});return Fn(jd(new TextEncoder().encode(t)))}var lb=Lv(require("node:crypto")),Dp=Lv(RO()),ji=2,ub=["new","continue"],CN=["charge_and_capture","authorize_only"],Mp=10000n,xd="nominal_usd_usdc_parity",Lp=["card:vic","wallet:x402"],fb="wallet:x402",vp=["connector","laptop"],bp=["card:vic","wallet:tempo","wallet:x402"];function Jp(e){let t=new Set(e);return e.includes(fb)&&t.add("wallet:tempo"),[...t].sort((n,r)=>bs(n,r))}var RN={ask:"Ask me each time",budget:"Pay within my budget"};function xN(e,t){return e!=="laptop"?[]:Jp(t).map(n=>({surface:"laptop",scope:n}))}var ON=["hosted_identity_key_migration_required","identity_key_expired","identity_key_rotated","identity_key_lost","identity_key_inactive","agent_inactive","current_grant_missing","current_grant_replaced","current_grant_expired","current_grant_inactive","required_scope_missing","managed_wallet_authority_unverified","authority_projection_unknown","authorization_version_unsupported","identity_key_custody_unsupported","owner_eligibility_required"],NN=["runtime","turnkey","server_encrypted","server_kms","external"],DN=["pending","active","retired","revoked","lost"],pb=["dotvisa","tap","email","messaging"],hb=["provisioning","active","needs_attention","suspended","disabled"],mb=["routing_only","provider_verified","agent_key_bound"],MN=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,LN=/^[A-Za-z0-9_-]{43}$/,JN=/^(?:0|[1-9][0-9]*)$/,UN=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,6})?(?:Z|[+-]\d{2}:\d{2})$/,gb=/[\u0000-\u001f\u007f]/,jN=2147483647,yb=9223372036854775807n,kv=100,qN=512,Cv=32,KN=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.visa$/,_b=/^0x[0-9a-f]{40}$/,Up=new TextEncoder;function bs(e,t){return(0,Dp.compareCanonicalKeys)(e,t)}function Mi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function jr(e){if(typeof e!="string"||!LN.test(e))return!1;try{let t=Kd(e);return t.byteLength===32&&Fn(t)===e}catch{return!1}}function Li(e,t,n){let r=Object.keys(t).filter(i=>!n.has(i));if(r.length>0)throw new Error(`${e} contains unknown field(s): ${r.sort().join(", ")}`)}function HN(e,t){if(typeof t!="string"||!MN.test(t))throw new Error(`${e} must be a UUID`)}function ut(e,t){return HN(e,t),t.toLowerCase()}function Ap(e,t){if(!(0,Dp.isCanonicalOpaqueId)(t))throw new Error(`${e} must be a non-empty opaque id (max 128 chars)`)}function Go(e,t){if(typeof t!="string")throw new Error(`${e} must be an ISO timestamp with an explicit time-zone offset`);let n=UN.exec(t);if(!n)throw new Error(`${e} must be an ISO timestamp with an explicit time-zone offset`);let[r,i,o,a,s,c]=n.slice(1,7).map(Number);if(!(0,Dp.isValidCalendarDateTime)(r,i,o,a,s,c))throw new Error(`${e} must be a valid calendar timestamp`);let d=Date.parse(t);if(!Number.isFinite(d))throw new Error(`${e} must be a valid ISO timestamp`);return new Date(d).toISOString()}function Di(e,t,n=!1){if(typeof t!="string"||!JN.test(t))throw new Error(`${e} must be a canonical non-negative integer micros string`);if(!n&&t==="0")throw new Error(`${e} must be positive`);if(BigInt(t)>yb)throw new Error(`${e} exceeds the PostgreSQL BIGINT range`);return t}function wb(e,t){if(typeof t!="number"||!Number.isInteger(t)||t<=0||t>jN)throw new Error(`${e} must be a positive PostgreSQL INTEGER`);return t}function Sp(e,t){if(typeof t!="string")throw new Error(`${e} must be a string`);if(gb.test(t))throw new Error(`${e} must be a bounded non-empty payee without control characters`);let n=t.normalize("NFC").trim();if(n.length===0||n.length>qN)throw new Error(`${e} must be a bounded non-empty payee without control characters`);return n}function vs(e,t,n){if(typeof t!="string")throw new Error(`${e} must be a string`);if(gb.test(t))throw new Error(`${e} must be bounded, non-empty text without control characters`);let r=t.normalize("NFC").trim();if(r.length===0||r.length>n)throw new Error(`${e} must be bounded, non-empty text without control characters`);return r}function vn(e,t){return typeof e=="string"&&t.includes(e)}function VN(e){if(!Number.isSafeInteger(e)||e<0)throw new Error("cents must be a non-negative safe integer");let t=BigInt(e)*Mp;if(t>yb)throw new Error("cents exceed the PostgreSQL BIGINT micros range");return t.toString()}function $N(e){return Di("amountAtomic",e,!0)}function WN(e){if(e==="card:vic")return{scope:e,paymentRail:"card",protocol:null,instrumentKind:"vic_card"};if(e==="wallet:x402")return{scope:e,paymentRail:"stablecoin",protocol:"x402",instrumentKind:"turnkey_wallet"};throw new Error(`unknown authorization scope: ${String(e)}`)}function FN(e,t,n){if(!Mi(e))throw new Error("keyLink must be an object");Li("channel keyLink",e,new Set(["keyId","agentId","purpose","fingerprint"]));let r=ut("keyLink.keyId",e.keyId),i=ut("keyLink.agentId",e.agentId);if(i!==t)throw new Error("keyLink.agentId must match the channel agentId");if(!vn(e.purpose,["identity","email_signing"]))throw new Error("channel keyLink cannot use a wallet-signing key");if(n==="email"&&e.purpose!=="email_signing")throw new Error("an agent-key-bound email channel requires an email_signing key");if((n==="tap"||n==="dotvisa")&&e.purpose!=="identity")throw new Error(`${n} requires an identity key`);let o=vs("keyLink.fingerprint",e.fingerprint,255);if(!jr(o))throw new Error(`an ${e.purpose} key link fingerprint must be a 43-char RFC 7638 JKT`);return{keyId:r,agentId:i,purpose:e.purpose,fingerprint:o}}function BN(e){if(!Mi(e))throw new Error("agent channel descriptor must be an object");Li("agent channel descriptor",e,new Set(["channelId","agentId","kind","status","assurance","address","providerRef","keyLink","capabilities","createdAt","verifiedAt","disabledAt"])),Ap("channelId",e.channelId);let t=ut("agentId",e.agentId);if(!vn(e.kind,pb))throw new Error("invalid channel kind");if(!vn(e.status,hb))throw new Error("invalid channel status");if(!vn(e.assurance,mb))throw new Error("invalid channel assurance");let n=e.address===void 0?void 0:vs("address",e.address,320),r=e.kind==="dotvisa"?n?.toLowerCase():n;if((e.kind==="email"||e.kind==="dotvisa")&&r===void 0)throw new Error(`${e.kind} channels require an address`);if(e.kind==="dotvisa"&&r!==void 0&&!KN.test(r))throw new Error("dotvisa channel address must be a canonical lowercase .visa address");if(e.kind==="tap"&&r!==void 0)throw new Error("tap channels use providerRef and cannot claim a public address");let i=e.providerRef===void 0?void 0:vs("providerRef",e.providerRef,255);if(!Array.isArray(e.capabilities)||e.capabilities.length===0||e.capabilities.length>Cv)throw new Error(`capabilities must contain between 1 and ${Cv} entries`);let o=e.capabilities.map(u=>vs("capability",u,64));if(new Set(o).size!==o.length)throw new Error("capabilities must not repeat");let a=Go("createdAt",e.createdAt),s=e.verifiedAt===void 0?void 0:Go("verifiedAt",e.verifiedAt),c=e.disabledAt===void 0?void 0:Go("disabledAt",e.disabledAt);if(s!==void 0&&Date.parse(s)<Date.parse(a))throw new Error("verifiedAt cannot be before createdAt");if(c!==void 0&&Date.parse(c)<Date.parse(a))throw new Error("disabledAt cannot be before createdAt");if(c!==void 0&&s!==void 0&&Date.parse(c)<Date.parse(s))throw new Error("disabledAt cannot be before verifiedAt");if(e.status==="disabled"!=(c!==void 0))throw new Error("status='disabled' and disabledAt must be set together");let d={channelId:e.channelId,agentId:t,kind:e.kind,status:e.status,...r!==void 0?{address:r}:{},...i!==void 0?{providerRef:i}:{},capabilities:[...o].sort(bs),createdAt:a,...c!==void 0?{disabledAt:c}:{}};if(e.assurance==="routing_only"){if(s!==void 0||e.keyLink!==void 0)throw new Error("routing_only channels cannot claim verification or an agent key link");return{...d,assurance:"routing_only"}}if(i===void 0||s===void 0)throw new Error(`${e.assurance} channels require providerRef and verifiedAt`);if(e.assurance==="provider_verified"){if(e.keyLink!==void 0)throw new Error("provider_verified channels cannot claim an agent key link");return{...d,assurance:"provider_verified",providerRef:i,verifiedAt:s}}let l=FN(e.keyLink,t,e.kind);return{...d,assurance:"agent_key_bound",providerRef:i,verifiedAt:s,keyLink:l}}function Eb(e,t){if(!Array.isArray(e)||e.length>vp.length*bp.length)throw new Error("payWithinBudget must be an array of surface/scope entries");let n=e.map(i=>{if(!Mi(i))throw new Error("payWithinBudget entry must be an object");if(Li("payWithinBudget entry",i,new Set(["surface","scope"])),!vn(i.surface,vp))throw new Error("payWithinBudget surface must be laptop or connector");if(!vn(i.scope,bp))throw new Error("payWithinBudget scope is not a payment rail");if(!Jp(t).includes(i.scope))throw new Error(i.scope==="wallet:tempo"?"payWithinBudget wallet:tempo needs the wallet:x402 grant scope":"payWithinBudget scope must be present in grant scopes");return{surface:i.surface,scope:i.scope}}),r=n.map(({surface:i,scope:o})=>`${i}:${o}`);if(new Set(r).size!==r.length)throw new Error("payWithinBudget must not repeat");return[...n].sort((i,o)=>bs(`${i.surface}:${i.scope}`,`${o.surface}:${o.scope}`))}function vb(e){if(!Mi(e))throw new Error("agent authority grant must be an object");if(Li("agent authority grant",e,new Set(["v","grantId","agentId","version","budgetEpochId","budgetEpochMode","status","currency","valuationPolicy","totalMicros","perTransactionMicros","dailyMicros","scopes","payWithinBudget","payeeConstraints","effectiveAt","expiresAt","supersedesGrantId"])),e.v!==ji)throw new Error("grant.v must be 2");let t=ut("grantId",e.grantId),n=ut("agentId",e.agentId),r=wb("version",e.version),i=ut("budgetEpochId",e.budgetEpochId);if(!vn(e.budgetEpochMode,ub))throw new Error("budgetEpochMode must be new or continue");if(!vn(e.status,["active","superseded","revoked"]))throw new Error("invalid grant status");if(e.currency!=="USD")throw new Error("currency must be 'USD'");if(e.valuationPolicy!==xd)throw new Error(`valuationPolicy must be '${xd}'`);let o=Di("totalMicros",e.totalMicros),a=Di("perTransactionMicros",e.perTransactionMicros);if(BigInt(a)>BigInt(o))throw new Error("perTransactionMicros cannot exceed totalMicros");let s=e.dailyMicros===void 0?void 0:Di("dailyMicros",e.dailyMicros);if(s!==void 0){if(BigInt(s)>BigInt(o))throw new Error("dailyMicros cannot exceed totalMicros");if(BigInt(a)>BigInt(s))throw new Error("perTransactionMicros cannot exceed dailyMicros")}if(!Array.isArray(e.scopes)||e.scopes.length===0)throw new Error("scopes must be a non-empty array");let c=e.scopes.map(h=>{if(!Mi(h))throw new Error("grant scope must be an object");if(Li("grant scope",h,new Set(["scope","totalMicros","perTransactionMicros","instrumentRef"])),!vn(h.scope,Lp))throw new Error("invalid authorization scope");let p=h.totalMicros===void 0?void 0:Di("scope.totalMicros",h.totalMicros),m=h.perTransactionMicros===void 0?void 0:Di("scope.perTransactionMicros",h.perTransactionMicros);if(p!==void 0&&BigInt(p)>BigInt(o))throw new Error("scope.totalMicros cannot exceed the aggregate totalMicros");if(m!==void 0&&BigInt(m)>BigInt(a))throw new Error("scope.perTransactionMicros cannot exceed the aggregate perTransactionMicros");if(p!==void 0&&m!==void 0&&BigInt(m)>BigInt(p))throw new Error("scope.perTransactionMicros cannot exceed scope.totalMicros");let w=vs("scope.instrumentRef",h.instrumentRef,255);return{scope:h.scope,...p!==void 0?{totalMicros:p}:{},...m!==void 0?{perTransactionMicros:m}:{},instrumentRef:w}});if(new Set(c.map(({scope:h})=>h)).size!==c.length)throw new Error("scopes must not repeat");let d=e.payWithinBudget===void 0?void 0:Eb(e.payWithinBudget,c.map(({scope:h})=>h)),l;if(e.payeeConstraints!==void 0){if(!Array.isArray(e.payeeConstraints)||e.payeeConstraints.length===0||e.payeeConstraints.length>kv)throw new Error(`payeeConstraints must contain between 1 and ${kv} entries`);if(l=e.payeeConstraints.map(p=>{if(!Mi(p))throw new Error("payee constraint must be an object");if(Li("payee constraint",p,new Set(["scope","kind","canonicalId"])),p.scope==="card:vic"&&p.kind==="processor_merchant_id")return{scope:p.scope,kind:p.kind,canonicalId:Sp("payee constraint canonicalId",p.canonicalId)};if(p.scope==="wallet:x402"&&p.kind==="evm_address"){let m=Sp("payee constraint canonicalId",p.canonicalId).toLowerCase();if(!_b.test(m))throw new Error("wallet payee constraint canonicalId must be an EVM address");return{scope:p.scope,kind:p.kind,canonicalId:m}}throw new Error("payee constraint scope/kind combination is invalid")}),l.some(p=>!c.some(({scope:m})=>m===p.scope)))throw new Error("payee constraint scope must be present in grant scopes");let h=l.map(({scope:p,kind:m,canonicalId:w})=>`${p}:${m}:${w}`);if(new Set(h).size!==h.length)throw new Error("payeeConstraints must not repeat after normalization")}let u=Go("effectiveAt",e.effectiveAt),f=Go("expiresAt",e.expiresAt);if(Date.parse(f)<=Date.parse(u))throw new Error("expiresAt must be after effectiveAt");if(e.supersedesGrantId!==void 0&&ut("supersedesGrantId",e.supersedesGrantId)===t)throw new Error("a grant cannot supersede itself");return{v:ji,grantId:t,agentId:n,version:r,budgetEpochId:i,budgetEpochMode:e.budgetEpochMode,status:e.status,currency:"USD",valuationPolicy:xd,totalMicros:o,perTransactionMicros:a,...s!==void 0?{dailyMicros:s}:{},scopes:[...c].sort((h,p)=>bs(h.scope,p.scope)),...d!==void 0?{payWithinBudget:d}:{},...l!==void 0?{payeeConstraints:[...l].sort((h,p)=>bs(`${h.scope}:${h.kind}:${h.canonicalId}`,`${p.scope}:${p.kind}:${p.canonicalId}`))}:{},effectiveAt:u,expiresAt:f,...e.supersedesGrantId!==void 0?{supersedesGrantId:ut("supersedesGrantId",e.supersedesGrantId)}:{}}}function GN(e){let t=vb(e),{status:n,...r}=t;return Fn(jd(Up.encode(`visa-agent-authority-grant:v2:${JSON.stringify(r)}`)))}function jp(e){if(!Mi(e))throw new Error("spend authorization intent must be an object");if(Li("spend authorization intent",e,new Set(["v","authorizationId","agentId","keyJkt","grantId","grantVersion","budgetEpochId","scope","amountMicros","currency","payee","intentId","economicIntentId","settlementHash","settlementExpiresAt"])),e.v!==ji)throw new Error("intent.v must be 2");let t=ut("authorizationId",e.authorizationId),n=ut("agentId",e.agentId);if(!jr(e.keyJkt))throw new Error("keyJkt must be a 43-char RFC 7638 thumbprint");let r=ut("grantId",e.grantId),i=wb("grantVersion",e.grantVersion),o=ut("budgetEpochId",e.budgetEpochId);if(!vn(e.scope,Lp))throw new Error("invalid authorization scope");let a=Di("amountMicros",e.amountMicros);if(e.scope==="card:vic"&&BigInt(a)%Mp!==0n)throw new Error("card:vic amountMicros must represent a whole number of card cents");if(e.currency!=="USD")throw new Error("currency must be 'USD'");let s=Sp("payee",e.payee),c=e.scope==="wallet:x402"?s.toLowerCase():s;if(e.scope==="wallet:x402"&&!_b.test(c))throw new Error("wallet:x402 payee must be an EVM address");if(Ap("intentId",e.intentId),Ap("economicIntentId",e.economicIntentId),!jr(e.settlementHash))throw new Error("settlementHash is required and must be a 32-byte base64url commitment");let d=Go("settlementExpiresAt",e.settlementExpiresAt);return{v:ji,authorizationId:t,agentId:n,keyJkt:e.keyJkt,grantId:r,grantVersion:i,budgetEpochId:o,scope:e.scope,amountMicros:a,currency:"USD",payee:c,intentId:e.intentId,economicIntentId:e.economicIntentId,settlementHash:e.settlementHash,settlementExpiresAt:d}}function bb(e){let t=jp(e),n=JSON.stringify({v:t.v,authorizationId:t.authorizationId,agentId:t.agentId,keyJkt:t.keyJkt,grantId:t.grantId,grantVersion:t.grantVersion,budgetEpochId:t.budgetEpochId,scope:t.scope,amountMicros:t.amountMicros,currency:t.currency,payee:t.payee,intentId:t.intentId,economicIntentId:t.economicIntentId,settlementHash:t.settlementHash,settlementExpiresAt:t.settlementExpiresAt});return Fn(jd(Up.encode(`visa-agent-spend-authorization:v2:${n}`)))}function YN(e){let t=jp(e.intent),n=ut("walletApiKeyId",e.walletApiKeyId),r=ut("runtimeSessionId",e.runtimeSessionId);if(e.executionChannel!=="cli"&&e.executionChannel!=="mcp")throw new Error("executionChannel must be cli or mcp");if(!jr(e.resourceCommitment))throw new Error("resourceCommitment must be a 32-byte base64url commitment");let i=JSON.stringify({v:1,intentHash:bb(t),walletApiKeyId:n,runtimeSessionId:r,executionChannel:e.executionChannel,resourceCommitment:e.resourceCommitment});return Fn(jd(Up.encode(`visa-wallet-authorization-request:v1:${i}`)))}var Ip=2,Ab=/^ap_[A-Za-z0-9_-]{24}$/,Rv=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,qp=/[\p{Cc}\p{Cf}]/u,zN=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.visa$/,XN=255,ZN=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,xv=2048,QN=/[\u0080-\u009f\u2028\u2029]/;function e1(e,t){return e<t?-1:e>t?1:0}function Es(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Od(e,t,n){let r=new Set(n),i=Object.keys(t).filter(o=>!r.has(o));if(i.length>0)throw new Error(`${e} contains unknown field(s): ${i.sort().join(", ")}`)}function t1(e){if(typeof e!="string")throw new Error("displayName must be a string");if(qp.test(e))throw new Error("displayName must be bounded, non-empty text without control characters");let t=e.normalize("NFC").trim().replace(/ {2,}/g," ");if(t.length===0||t.length>XN)throw new Error("displayName must be bounded, non-empty text without control characters");return t}function n1(e){if(typeof e!="string")throw new Error("dotVisaAddress must be a string");if(qp.test(e))throw new Error("dotVisaAddress must be a valid .visa address");let t=e.trim().toLowerCase();if(!zN.test(t))throw new Error("dotVisaAddress must be a valid .visa address");return t}function r1(e){if(typeof e!="string"||!Ab.test(e))throw new Error("pairingId must be a server-generated pairing id")}function Ov(e,t){if(typeof t!="string"||!ZN.test(t))throw new Error(`${e} must be a canonical lowercase UUID`)}function yp(e,t){if(!jr(t))throw new Error(`${e} must be 32 canonical unpadded base64url bytes`)}function Nv(e,t){if(typeof t!="string"||t.length===0||t.length>xv||qp.test(t)||QN.test(t))throw new Error(`${e} must be a bounded absolute HTTP(S) URL`);let n;try{n=new URL(t)}catch{throw new Error(`${e} must be a bounded absolute HTTP(S) URL`)}if(n.protocol!=="https:"&&n.protocol!=="http:"||n.hostname.length===0||n.username.length>0||n.password.length>0||n.hash.length>0)throw new Error(`${e} must be a bounded absolute HTTP(S) URL`);let r=n.toString();if(r.length>xv)throw new Error(`${e} must be a bounded absolute HTTP(S) URL`);return r}function i1(){return lb.default.randomBytes(32).toString("base64url")}function o1(e){if(!jr(e))throw new Error("claim token must be 32 unpadded base64url bytes");return Hp(`visa-agent-pairing-claim-token:v1:${e}`)}function Kp(e){if(!Es(e))throw new Error("pairing terms v2 must be an object");if(Od("pairing terms v2",e,["v","pairingId","agentId","agentSelection","identityKeyJkt","ownerPublicId","displayName","dotVisaAddress","authority"]),e.v!==ji)throw new Error("pairing terms v2 must carry v=2");if(typeof e.pairingId!="string"||!Ab.test(e.pairingId))throw new Error("pairingId must be a server-issued pairing id");if(typeof e.agentId!="string"||!Rv.test(e.agentId))throw new Error("agentId must be a UUID");if(e.agentSelection!=="new"&&e.agentSelection!=="existing")throw new Error("agentSelection must be new or existing");if(!jr(e.identityKeyJkt))throw new Error("identityKeyJkt must be a canonical 32-byte base64url thumbprint");if(typeof e.ownerPublicId!="string"||!Rv.test(e.ownerPublicId))throw new Error("ownerPublicId must be a UUID");let t=e.agentId.toLowerCase(),n=e.ownerPublicId.toLowerCase(),r=t1(e.displayName),i=e.dotVisaAddress===void 0?void 0:n1(e.dotVisaAddress);if(e.authority!==null)throw new Error("pairing terms v2 must be identity-only (authority:null)");if(e.agentSelection==="existing")throw new Error("an existing-agent pairing must bind its exact current authority; identity-only attachment requires a future explicit no-spend key policy");return JSON.stringify({agentId:t,agentSelection:e.agentSelection,authority:null,displayName:r,identityKeyJkt:e.identityKeyJkt,...i!==void 0?{dotVisaAddress:i}:{},ownerPublicId:n,pairingId:e.pairingId,v:ji})}function Sb(e){return Hp(`visa-agent-pairing-terms:v2:${Kp(e)}`)}function a1(e){if(!Es(e))throw new Error("pairing delivery artifact v2 must be an object");if(Od("pairing delivery artifact v2",e,["v","kind","pairingId","agentId","ownerPublicId","identityKey","terms","ceremonyHash","issuer","activationAudience"]),e.v!==Ip)throw new Error("pairing delivery artifact v2 must carry v=2");if(e.kind!=="agent-pairing-delivery")throw new Error("pairing delivery artifact kind must be agent-pairing-delivery");if(r1(e.pairingId),Ov("agentId",e.agentId),Ov("ownerPublicId",e.ownerPublicId),yp("ceremonyHash",e.ceremonyHash),!Es(e.identityKey))throw new Error("pairing delivery identityKey must be an object");if(Od("pairing delivery identityKey",e.identityKey,["jkt","publicJwk"]),yp("identityKey.jkt",e.identityKey.jkt),!Es(e.identityKey.publicJwk))throw new Error("pairing delivery identityKey.publicJwk must be an object");let t=e.identityKey.publicJwk;if(Od("pairing delivery identityKey.publicJwk",t,["kty","crv","x"]),t.kty!=="OKP"||t.crv!=="Ed25519")throw new Error("pairing delivery identity key must be a public Ed25519 OKP JWK");yp("identityKey.publicJwk.x",t.x);let n=db({kty:"OKP",crv:"Ed25519",x:t.x});if(e.identityKey.jkt!==n)throw new Error("identityKey.jkt must equal the RFC 7638 thumbprint of publicJwk");if(!Es(e.terms))throw new Error("pairing delivery terms must be PairingTermsV2");if(e.terms.agentSelection!=="new"||e.terms.authority!==null)throw new Error("pairing delivery terms must be a new identity-only pairing");if(e.terms.pairingId!==e.pairingId||e.terms.agentId!==e.agentId||e.terms.ownerPublicId!==e.ownerPublicId||e.terms.identityKeyJkt!==e.identityKey.jkt)throw new Error("pairing delivery terms must match the exact ceremony principals and key");let r=Kp(e.terms);if(Sb(e.terms)!==e.ceremonyHash)throw new Error("ceremonyHash must equal the hash of the exact canonical v2 terms");let i=Nv("issuer",e.issuer),o=Nv("activationAudience",e.activationAudience);return Tp({activationAudience:o,agentId:e.agentId,ceremonyHash:e.ceremonyHash,identityKey:{jkt:e.identityKey.jkt,publicJwk:{crv:"Ed25519",kty:"OKP",x:t.x}},issuer:i,kind:"agent-pairing-delivery",ownerPublicId:e.ownerPublicId,pairingId:e.pairingId,terms:JSON.parse(r),v:Ip})}function Hp(e){return lb.default.createHash("sha256").update(e,"utf8").digest("base64url")}function Tp(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(Tp).join(",")}]`;let t=e;return`{${Object.keys(t).sort(e1).map(n=>`${JSON.stringify(n)}:${Tp(t[n])}`).join(",")}}`}});var qi=y(Gn=>{"use strict";Object.defineProperty(Gn,"__esModule",{value:!0});Gn.computeJkt=void 0;Gn.generateAgentKey=c1;Gn.agentKeyFromSeed=d1;Gn.generateAnchorKey=l1;Gn.anchorKeyFromSeed=u1;Gn.buildJwks=f1;var Bn=Tb(),s1=is();Object.defineProperty(Gn,"computeJkt",{enumerable:!0,get:function(){return s1.computeJkt}});var Pb=is();function c1(){let{secretKey:e,publicKey:t}=(0,Bn.generateKeyPair)(),n=(0,Bn.seedToJwk)(e),r=(0,Bn.publicKeyToJwk)(t);return{privateJwk:n,publicJwk:r,jkt:(0,Pb.computeJkt)(r)}}function d1(e){let{secretKey:t,publicKey:n}=(0,Bn.keyPairFromSeed)(e),r=(0,Bn.seedToJwk)(t),i=(0,Bn.publicKeyToJwk)(n);return{privateJwk:r,publicJwk:i,jkt:(0,Pb.computeJkt)(i)}}function kb(e,t,n){let r={...(0,Bn.seedToJwk)(e),kid:t,use:"sig",alg:"EdDSA",...n?{role:n}:{}},{d:i,...o}=r;return{kid:t,privateJwk:r,publicJwk:o,...n?{role:n}:{}}}function l1(e,t){return kb((0,Bn.generateKeyPair)().secretKey,e,t)}function u1(e,t,n){return kb((0,Bn.keyPairFromSeed)(e).secretKey,t,n)}function f1(e){let t=new Set;for(let n of e){if(t.has(n.kid))throw new Error(`buildJwks: duplicate kid ${JSON.stringify(n.kid)} \u2014 every key in a JWKS must have a unique kid`);t.add(n.kid)}return{keys:e.map(n=>({kty:n.publicJwk.kty,crv:n.publicJwk.crv,x:n.publicJwk.x,kid:n.kid,use:"sig",alg:"EdDSA",...n.role??n.publicJwk.role?{role:n.role??n.publicJwk.role}:{}}))}}});var $p=y(Vp=>{"use strict";Object.defineProperty(Vp,"__esModule",{value:!0});var p1=require("node:crypto"),h1=(e,t)=>(0,p1.createHash)(e).update(t).digest();Vp.default=h1});var Ae=y(Et=>{"use strict";Object.defineProperty(Et,"__esModule",{value:!0});Et.decoder=Et.encoder=void 0;Et.concat=Fp;Et.p2s=g1;Et.uint64be=y1;Et.uint32be=Bp;Et.lengthAndInput=_1;Et.concatKdf=w1;var m1=$p();Et.encoder=new TextEncoder;Et.decoder=new TextDecoder;var Hd=2**32;function Fp(...e){let t=e.reduce((i,{length:o})=>i+o,0),n=new Uint8Array(t),r=0;for(let i of e)n.set(i,r),r+=i.length;return n}function g1(e,t){return Fp(Et.encoder.encode(e),new Uint8Array([0]),t)}function Wp(e,t,n){if(t<0||t>=Hd)throw new RangeError(`value must be >= 0 and <= ${Hd-1}. Received ${t}`);e.set([t>>>24,t>>>16,t>>>8,t&255],n)}function y1(e){let t=Math.floor(e/Hd),n=e%Hd,r=new Uint8Array(8);return Wp(r,t,0),Wp(r,n,4),r}function Bp(e){let t=new Uint8Array(4);return Wp(t,e),t}function _1(e){return Fp(Bp(e.length),e)}async function w1(e,t,n){let r=Math.ceil((t>>3)/32),i=new Uint8Array(r*32);for(let o=0;o<r;o++){let a=new Uint8Array(4+e.length+n.length);a.set(Bp(o+1)),a.set(e,4),a.set(n,4+e.length),i.set(await(0,m1.default)("sha256",a),o*32)}return i.slice(0,t>>3)}});var Ze=y(bn=>{"use strict";Object.defineProperty(bn,"__esModule",{value:!0});bn.decode=bn.encode=bn.encodeBase64=bn.decodeBase64=void 0;var Vd=require("node:buffer"),E1=Ae();function v1(e){let t=e;return t instanceof Uint8Array&&(t=E1.decoder.decode(t)),t}var b1=e=>Vd.Buffer.from(e).toString("base64url");bn.encode=b1;var A1=e=>new Uint8Array(Vd.Buffer.from(e,"base64"));bn.decodeBase64=A1;var S1=e=>Vd.Buffer.from(e).toString("base64");bn.encodeBase64=S1;var I1=e=>new Uint8Array(Vd.Buffer.from(v1(e),"base64url"));bn.decode=I1});var B=y(ne=>{"use strict";Object.defineProperty(ne,"__esModule",{value:!0});ne.JWSSignatureVerificationFailed=ne.JWKSTimeout=ne.JWKSMultipleMatchingKeys=ne.JWKSNoMatchingKey=ne.JWKSInvalid=ne.JWKInvalid=ne.JWTInvalid=ne.JWSInvalid=ne.JWEInvalid=ne.JWEDecryptionFailed=ne.JOSENotSupported=ne.JOSEAlgNotAllowed=ne.JWTExpired=ne.JWTClaimValidationFailed=ne.JOSEError=void 0;var je=class extends Error{static code="ERR_JOSE_GENERIC";code="ERR_JOSE_GENERIC";constructor(t,n){super(t,n),this.name=this.constructor.name,Error.captureStackTrace?.(this,this.constructor)}};ne.JOSEError=je;var Gp=class extends je{static code="ERR_JWT_CLAIM_VALIDATION_FAILED";code="ERR_JWT_CLAIM_VALIDATION_FAILED";claim;reason;payload;constructor(t,n,r="unspecified",i="unspecified"){super(t,{cause:{claim:r,reason:i,payload:n}}),this.claim=r,this.reason=i,this.payload=n}};ne.JWTClaimValidationFailed=Gp;var Yp=class extends je{static code="ERR_JWT_EXPIRED";code="ERR_JWT_EXPIRED";claim;reason;payload;constructor(t,n,r="unspecified",i="unspecified"){super(t,{cause:{claim:r,reason:i,payload:n}}),this.claim=r,this.reason=i,this.payload=n}};ne.JWTExpired=Yp;var zp=class extends je{static code="ERR_JOSE_ALG_NOT_ALLOWED";code="ERR_JOSE_ALG_NOT_ALLOWED"};ne.JOSEAlgNotAllowed=zp;var Xp=class extends je{static code="ERR_JOSE_NOT_SUPPORTED";code="ERR_JOSE_NOT_SUPPORTED"};ne.JOSENotSupported=Xp;var Zp=class extends je{static code="ERR_JWE_DECRYPTION_FAILED";code="ERR_JWE_DECRYPTION_FAILED";constructor(t="decryption operation failed",n){super(t,n)}};ne.JWEDecryptionFailed=Zp;var Qp=class extends je{static code="ERR_JWE_INVALID";code="ERR_JWE_INVALID"};ne.JWEInvalid=Qp;var eh=class extends je{static code="ERR_JWS_INVALID";code="ERR_JWS_INVALID"};ne.JWSInvalid=eh;var th=class extends je{static code="ERR_JWT_INVALID";code="ERR_JWT_INVALID"};ne.JWTInvalid=th;var nh=class extends je{static code="ERR_JWK_INVALID";code="ERR_JWK_INVALID"};ne.JWKInvalid=nh;var rh=class extends je{static code="ERR_JWKS_INVALID";code="ERR_JWKS_INVALID"};ne.JWKSInvalid=rh;var ih=class extends je{static code="ERR_JWKS_NO_MATCHING_KEY";code="ERR_JWKS_NO_MATCHING_KEY";constructor(t="no applicable key found in the JSON Web Key Set",n){super(t,n)}};ne.JWKSNoMatchingKey=ih;var oh=class extends je{[Symbol.asyncIterator];static code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";constructor(t="multiple matching keys found in the JSON Web Key Set",n){super(t,n)}};ne.JWKSMultipleMatchingKeys=oh;var ah=class extends je{static code="ERR_JWKS_TIMEOUT";code="ERR_JWKS_TIMEOUT";constructor(t="request timed out",n){super(t,n)}};ne.JWKSTimeout=ah;var sh=class extends je{static code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";constructor(t="signature verification failed",n){super(t,n)}};ne.JWSSignatureVerificationFailed=sh});var As=y($d=>{"use strict";Object.defineProperty($d,"__esModule",{value:!0});$d.default=void 0;var T1=require("node:crypto");Object.defineProperty($d,"default",{enumerable:!0,get:function(){return T1.randomFillSync}})});var ch=y(Wd=>{"use strict";Object.defineProperty(Wd,"__esModule",{value:!0});Wd.bitLength=Cb;var P1=B(),k1=As();function Cb(e){switch(e){case"A128GCM":case"A128GCMKW":case"A192GCM":case"A192GCMKW":case"A256GCM":case"A256GCMKW":return 96;case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return 128;default:throw new P1.JOSENotSupported(`Unsupported JWE Algorithm: ${e}`)}}Wd.default=e=>(0,k1.default)(new Uint8Array(Cb(e)>>3))});var lh=y(dh=>{"use strict";Object.defineProperty(dh,"__esModule",{value:!0});var C1=B(),R1=ch(),x1=(e,t)=>{if(t.length<<3!==(0,R1.bitLength)(e))throw new C1.JWEInvalid("Invalid Initialization Vector length")};dh.default=x1});var kt=y(uh=>{"use strict";Object.defineProperty(uh,"__esModule",{value:!0});var O1=require("node:util");uh.default=e=>O1.types.isKeyObject(e)});var hh=y(ph=>{"use strict";Object.defineProperty(ph,"__esModule",{value:!0});var fh=B(),N1=kt(),D1=(e,t)=>{let n;switch(e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":n=parseInt(e.slice(-3),10);break;case"A128GCM":case"A192GCM":case"A256GCM":n=parseInt(e.slice(1,4),10);break;default:throw new fh.JOSENotSupported(`Content Encryption Algorithm ${e} is not supported either by JOSE or your javascript runtime`)}if(t instanceof Uint8Array){let r=t.byteLength<<3;if(r!==n)throw new fh.JWEInvalid(`Invalid Content Encryption Key length. Expected ${n} bits, got ${r} bits`);return}if((0,N1.default)(t)&&t.type==="secret"){let r=t.symmetricKeySize<<3;if(r!==n)throw new fh.JWEInvalid(`Invalid Content Encryption Key length. Expected ${n} bits, got ${r} bits`);return}throw new TypeError("Invalid Content Encryption Key type")};ph.default=D1});var Rb=y(mh=>{"use strict";Object.defineProperty(mh,"__esModule",{value:!0});var M1=require("node:crypto"),L1=M1.timingSafeEqual;mh.default=L1});var yh=y(gh=>{"use strict";Object.defineProperty(gh,"__esModule",{value:!0});gh.default=U1;var J1=require("node:crypto"),xb=Ae();function U1(e,t,n,r,i,o){let a=(0,xb.concat)(e,t,n,(0,xb.uint64be)(e.length<<3)),s=(0,J1.createHmac)(`sha${r}`,i);return s.update(a),s.digest().slice(0,o>>3)}});var Ct=y(Ss=>{"use strict";Object.defineProperty(Ss,"__esModule",{value:!0});Ss.isCryptoKey=void 0;var j1=require("node:crypto"),q1=require("node:util"),K1=j1.webcrypto;Ss.default=K1;var H1=e=>q1.types.isCryptoKey(e);Ss.isCryptoKey=H1});var qr=y(Bd=>{"use strict";Object.defineProperty(Bd,"__esModule",{value:!0});Bd.checkSigCryptoKey=$1;Bd.checkEncCryptoKey=W1;function Je(e,t="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${t} must be ${e}`)}function Yn(e,t){return e.name===t}function Fd(e){return parseInt(e.name.slice(4),10)}function V1(e){switch(e){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function Ob(e,t){if(t.length&&!t.some(n=>e.usages.includes(n))){let n="CryptoKey does not support this operation, its usages must include ";if(t.length>2){let r=t.pop();n+=`one of ${t.join(", ")}, or ${r}.`}else t.length===2?n+=`one of ${t[0]} or ${t[1]}.`:n+=`${t[0]}.`;throw new TypeError(n)}}function $1(e,t,...n){switch(t){case"HS256":case"HS384":case"HS512":{if(!Yn(e.algorithm,"HMAC"))throw Je("HMAC");let r=parseInt(t.slice(2),10);if(Fd(e.algorithm.hash)!==r)throw Je(`SHA-${r}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!Yn(e.algorithm,"RSASSA-PKCS1-v1_5"))throw Je("RSASSA-PKCS1-v1_5");let r=parseInt(t.slice(2),10);if(Fd(e.algorithm.hash)!==r)throw Je(`SHA-${r}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!Yn(e.algorithm,"RSA-PSS"))throw Je("RSA-PSS");let r=parseInt(t.slice(2),10);if(Fd(e.algorithm.hash)!==r)throw Je(`SHA-${r}`,"algorithm.hash");break}case"EdDSA":{if(e.algorithm.name!=="Ed25519"&&e.algorithm.name!=="Ed448")throw Je("Ed25519 or Ed448");break}case"Ed25519":{if(!Yn(e.algorithm,"Ed25519"))throw Je("Ed25519");break}case"ES256":case"ES384":case"ES512":{if(!Yn(e.algorithm,"ECDSA"))throw Je("ECDSA");let r=V1(t);if(e.algorithm.namedCurve!==r)throw Je(r,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}Ob(e,n)}function W1(e,t,...n){switch(t){case"A128GCM":case"A192GCM":case"A256GCM":{if(!Yn(e.algorithm,"AES-GCM"))throw Je("AES-GCM");let r=parseInt(t.slice(1,4),10);if(e.algorithm.length!==r)throw Je(r,"algorithm.length");break}case"A128KW":case"A192KW":case"A256KW":{if(!Yn(e.algorithm,"AES-KW"))throw Je("AES-KW");let r=parseInt(t.slice(1,4),10);if(e.algorithm.length!==r)throw Je(r,"algorithm.length");break}case"ECDH":{switch(e.algorithm.name){case"ECDH":case"X25519":case"X448":break;default:throw Je("ECDH, X25519, or X448")}break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":if(!Yn(e.algorithm,"PBKDF2"))throw Je("PBKDF2");break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(!Yn(e.algorithm,"RSA-OAEP"))throw Je("RSA-OAEP");let r=parseInt(t.slice(9),10)||1;if(Fd(e.algorithm.hash)!==r)throw Je(`SHA-${r}`,"algorithm.hash");break}default:throw new TypeError("CryptoKey does not support this operation")}Ob(e,n)}});var Rt=y(Gd=>{"use strict";Object.defineProperty(Gd,"__esModule",{value:!0});Gd.withAlg=F1;function Nb(e,t,...n){if(n=n.filter(Boolean),n.length>2){let r=n.pop();e+=`one of type ${n.join(", ")}, or ${r}.`}else n.length===2?e+=`one of type ${n[0]} or ${n[1]}.`:e+=`of type ${n[0]}.`;return t==null?e+=` Received ${t}`:typeof t=="function"&&t.name?e+=` Received function ${t.name}`:typeof t=="object"&&t!=null&&t.constructor?.name&&(e+=` Received an instance of ${t.constructor.name}`),e}Gd.default=(e,...t)=>Nb("Key must be ",e,...t);function F1(e,t,...n){return Nb(`Key for the ${e} algorithm must be `,t,...n)}});var Yd=y(_h=>{"use strict";Object.defineProperty(_h,"__esModule",{value:!0});var B1=require("node:crypto"),Db;_h.default=e=>(Db||=new Set((0,B1.getCiphers)()),Db.has(e))});var xt=y(Is=>{"use strict";Object.defineProperty(Is,"__esModule",{value:!0});Is.types=void 0;var Mb=Ct(),G1=kt();Is.default=e=>(0,G1.default)(e)||(0,Mb.isCryptoKey)(e);var Lb=["KeyObject"];Is.types=Lb;(globalThis.CryptoKey||Mb.default?.CryptoKey)&&Lb.push("CryptoKey")});var vh=y(Eh=>{"use strict";Object.defineProperty(Eh,"__esModule",{value:!0});var wh=require("node:crypto"),Y1=lh(),z1=hh(),X1=Ae(),Kr=B(),Z1=Rb(),Q1=yh(),eD=Ct(),tD=qr(),Jb=kt(),nD=Rt(),Ub=Yd(),rD=xt();function iD(e,t,n,r,i,o){let a=parseInt(e.slice(1,4),10);(0,Jb.default)(t)&&(t=t.export());let s=t.subarray(a>>3),c=t.subarray(0,a>>3),d=parseInt(e.slice(-3),10),l=`aes-${a}-cbc`;if(!(0,Ub.default)(l))throw new Kr.JOSENotSupported(`alg ${e} is not supported by your javascript runtime`);let u=(0,Q1.default)(o,r,n,d,c,a),f;try{f=(0,Z1.default)(i,u)}catch{}if(!f)throw new Kr.JWEDecryptionFailed;let h;try{let p=(0,wh.createDecipheriv)(l,s,r);h=(0,X1.concat)(p.update(n),p.final())}catch{}if(!h)throw new Kr.JWEDecryptionFailed;return h}function oD(e,t,n,r,i,o){let s=`aes-${parseInt(e.slice(1,4),10)}-gcm`;if(!(0,Ub.default)(s))throw new Kr.JOSENotSupported(`alg ${e} is not supported by your javascript runtime`);try{let c=(0,wh.createDecipheriv)(s,t,r,{authTagLength:16});c.setAuthTag(i),o.byteLength&&c.setAAD(o,{plaintextLength:n.length});let d=c.update(n);return c.final(),d}catch{throw new Kr.JWEDecryptionFailed}}var aD=(e,t,n,r,i,o)=>{let a;if((0,eD.isCryptoKey)(t))(0,tD.checkEncCryptoKey)(t,e,"decrypt"),a=wh.KeyObject.from(t);else if(t instanceof Uint8Array||(0,Jb.default)(t))a=t;else throw new TypeError((0,nD.default)(t,...rD.types,"Uint8Array"));if(!r)throw new Kr.JWEInvalid("JWE Initialization Vector missing");if(!i)throw new Kr.JWEInvalid("JWE Authentication Tag missing");switch((0,z1.default)(e,a),(0,Y1.default)(e,r),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return iD(e,a,n,r,i,o);case"A128GCM":case"A192GCM":case"A256GCM":return oD(e,a,n,r,i,o);default:throw new Kr.JOSENotSupported("Unsupported JWE Content Encryption Algorithm")}};Eh.default=aD});var zo=y(bh=>{"use strict";Object.defineProperty(bh,"__esModule",{value:!0});var sD=(...e)=>{let t=e.filter(Boolean);if(t.length===0||t.length===1)return!0;let n;for(let r of t){let i=Object.keys(r);if(!n||n.size===0){n=new Set(i);continue}for(let o of i){if(n.has(o))return!1;n.add(o)}}return!0};bh.default=sD});var $e=y(Ah=>{"use strict";Object.defineProperty(Ah,"__esModule",{value:!0});Ah.default=dD;function cD(e){return typeof e=="object"&&e!==null}function dD(e){if(!cD(e)||Object.prototype.toString.call(e)!=="[object Object]")return!1;if(Object.getPrototypeOf(e)===null)return!0;let t=e;for(;Object.getPrototypeOf(t)!==null;)t=Object.getPrototypeOf(t);return Object.getPrototypeOf(e)===t}});var Xd=y(Xo=>{"use strict";Object.defineProperty(Xo,"__esModule",{value:!0});Xo.unwrap=Xo.wrap=void 0;var jb=require("node:buffer"),zd=require("node:crypto"),qb=B(),Kb=Ae(),lD=Ct(),uD=qr(),fD=kt(),pD=Rt(),Hb=Yd(),hD=xt();function Vb(e,t){if(e.symmetricKeySize<<3!==parseInt(t.slice(1,4),10))throw new TypeError(`Invalid key size for alg: ${t}`)}function $b(e,t,n){if((0,fD.default)(e))return e;if(e instanceof Uint8Array)return(0,zd.createSecretKey)(e);if((0,lD.isCryptoKey)(e))return(0,uD.checkEncCryptoKey)(e,t,n),zd.KeyObject.from(e);throw new TypeError((0,pD.default)(e,...hD.types,"Uint8Array"))}var mD=(e,t,n)=>{let i=`aes${parseInt(e.slice(1,4),10)}-wrap`;if(!(0,Hb.default)(i))throw new qb.JOSENotSupported(`alg ${e} is not supported either by JOSE or your javascript runtime`);let o=$b(t,e,"wrapKey");Vb(o,e);let a=(0,zd.createCipheriv)(i,o,jb.Buffer.alloc(8,166));return(0,Kb.concat)(a.update(n),a.final())};Xo.wrap=mD;var gD=(e,t,n)=>{let i=`aes${parseInt(e.slice(1,4),10)}-wrap`;if(!(0,Hb.default)(i))throw new qb.JOSENotSupported(`alg ${e} is not supported either by JOSE or your javascript runtime`);let o=$b(t,e,"unwrapKey");Vb(o,e);let a=(0,zd.createDecipheriv)(i,o,jb.Buffer.alloc(8,166));return(0,Kb.concat)(a.update(n),a.final())};Xo.unwrap=gD});var Ts=y(Zo=>{"use strict";Object.defineProperty(Zo,"__esModule",{value:!0});Zo.isJWK=Wb;Zo.isPrivateJWK=_D;Zo.isPublicJWK=wD;Zo.isSecretJWK=ED;var yD=$e();function Wb(e){return(0,yD.default)(e)&&typeof e.kty=="string"}function _D(e){return e.kty!=="oct"&&typeof e.d=="string"}function wD(e){return e.kty!=="oct"&&typeof e.d>"u"}function ED(e){return Wb(e)&&e.kty==="oct"&&typeof e.k=="string"}});var Sh=y(Ps=>{"use strict";Object.defineProperty(Ps,"__esModule",{value:!0});Ps.weakMap=void 0;var vD=require("node:crypto"),bD=B(),AD=Ct(),SD=kt(),ID=Rt(),TD=xt(),PD=Ts();Ps.weakMap=new WeakMap;var kD=e=>{switch(e){case"prime256v1":return"P-256";case"secp384r1":return"P-384";case"secp521r1":return"P-521";case"secp256k1":return"secp256k1";default:throw new bD.JOSENotSupported("Unsupported key curve for this operation")}},CD=(e,t)=>{let n;if((0,AD.isCryptoKey)(e))n=vD.KeyObject.from(e);else if((0,SD.default)(e))n=e;else{if((0,PD.isJWK)(e))return e.crv;throw new TypeError((0,ID.default)(e,...TD.types))}if(n.type==="secret")throw new TypeError('only "private" or "public" type keys can be used for this operation');switch(n.asymmetricKeyType){case"ed25519":case"ed448":return`Ed${n.asymmetricKeyType.slice(2)}`;case"x25519":case"x448":return`X${n.asymmetricKeyType.slice(1)}`;case"ec":{let r=n.asymmetricKeyDetails.namedCurve;return t?r:kD(r)}default:throw new TypeError("Invalid asymmetric key type for this operation")}};Ps.default=CD});var Rh=y(Qo=>{"use strict";Object.defineProperty(Qo,"__esModule",{value:!0});Qo.ecdhAllowed=void 0;Qo.deriveKey=OD;Qo.generateEpk=ND;var ks=require("node:crypto"),RD=require("node:util"),Bb=Sh(),Ki=Ae(),xD=B(),Th=Ct(),Fb=qr(),Ph=kt(),kh=Rt(),Ch=xt(),Ih=(0,RD.promisify)(ks.generateKeyPair);async function OD(e,t,n,r,i=new Uint8Array(0),o=new Uint8Array(0)){let a;if((0,Th.isCryptoKey)(e))(0,Fb.checkEncCryptoKey)(e,"ECDH"),a=ks.KeyObject.from(e);else if((0,Ph.default)(e))a=e;else throw new TypeError((0,kh.default)(e,...Ch.types));let s;if((0,Th.isCryptoKey)(t))(0,Fb.checkEncCryptoKey)(t,"ECDH","deriveBits"),s=ks.KeyObject.from(t);else if((0,Ph.default)(t))s=t;else throw new TypeError((0,kh.default)(t,...Ch.types));let c=(0,Ki.concat)((0,Ki.lengthAndInput)(Ki.encoder.encode(n)),(0,Ki.lengthAndInput)(i),(0,Ki.lengthAndInput)(o),(0,Ki.uint32be)(r)),d=(0,ks.diffieHellman)({privateKey:s,publicKey:a});return(0,Ki.concatKdf)(d,r,c)}async function ND(e){let t;if((0,Th.isCryptoKey)(e))t=ks.KeyObject.from(e);else if((0,Ph.default)(e))t=e;else throw new TypeError((0,kh.default)(e,...Ch.types));switch(t.asymmetricKeyType){case"x25519":return Ih("x25519");case"x448":return Ih("x448");case"ec":{let n=(0,Bb.default)(t);return Ih("ec",{namedCurve:n})}default:throw new xD.JOSENotSupported("Invalid or unsupported EPK")}}var DD=e=>["P-256","P-384","P-521","X25519","X448"].includes((0,Bb.default)(e));Qo.ecdhAllowed=DD});var Gb=y(xh=>{"use strict";Object.defineProperty(xh,"__esModule",{value:!0});xh.default=LD;var MD=B();function LD(e){if(!(e instanceof Uint8Array)||e.length<8)throw new MD.JWEInvalid("PBES2 Salt Input must be 8 or more octets")}});var Oh=y(ea=>{"use strict";Object.defineProperty(ea,"__esModule",{value:!0});ea.decrypt=ea.encrypt=void 0;var JD=require("node:util"),Yb=require("node:crypto"),UD=As(),zb=Ae(),jD=Ze(),Xb=Xd(),Zb=Gb(),qD=Ct(),KD=qr(),HD=kt(),VD=Rt(),$D=xt(),Qb=(0,JD.promisify)(Yb.pbkdf2);function eA(e,t){if((0,HD.default)(e))return e.export();if(e instanceof Uint8Array)return e;if((0,qD.isCryptoKey)(e))return(0,KD.checkEncCryptoKey)(e,t,"deriveBits","deriveKey"),Yb.KeyObject.from(e).export();throw new TypeError((0,VD.default)(e,...$D.types,"Uint8Array"))}var WD=async(e,t,n,r=2048,i=(0,UD.default)(new Uint8Array(16)))=>{(0,Zb.default)(i);let o=(0,zb.p2s)(e,i),a=parseInt(e.slice(13,16),10)>>3,s=eA(t,e),c=await Qb(s,o,r,a,`sha${e.slice(8,11)}`);return{encryptedKey:await(0,Xb.wrap)(e.slice(-6),c,n),p2c:r,p2s:(0,jD.encode)(i)}};ea.encrypt=WD;var FD=async(e,t,n,r,i)=>{(0,Zb.default)(i);let o=(0,zb.p2s)(e,i),a=parseInt(e.slice(13,16),10)>>3,s=eA(t,e),c=await Qb(s,o,r,a,`sha${e.slice(8,11)}`);return(0,Xb.unwrap)(e.slice(-6),c,n)};ea.decrypt=FD});var Dh=y(Nh=>{"use strict";Object.defineProperty(Nh,"__esModule",{value:!0});var BD=require("node:crypto");Nh.default=(e,t)=>{let n;try{e instanceof BD.KeyObject?n=e.asymmetricKeyDetails?.modulusLength:n=Buffer.from(e.n,"base64url").byteLength<<3}catch{}if(typeof n!="number"||n<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)}});var Mh=y(ta=>{"use strict";Object.defineProperty(ta,"__esModule",{value:!0});ta.decrypt=ta.encrypt=void 0;var Cs=require("node:crypto"),GD=require("node:util"),YD=Dh(),zD=Ct(),XD=qr(),ZD=kt(),QD=Rt(),e2=xt(),tA=(e,t)=>{if(e.asymmetricKeyType!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");(0,YD.default)(e,t)},t2=(0,GD.deprecate)(()=>Cs.constants.RSA_PKCS1_PADDING,'The RSA1_5 "alg" (JWE Algorithm) is deprecated and will be removed in the next major revision.'),nA=e=>{switch(e){case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":return Cs.constants.RSA_PKCS1_OAEP_PADDING;case"RSA1_5":return t2();default:return}},rA=e=>{switch(e){case"RSA-OAEP":return"sha1";case"RSA-OAEP-256":return"sha256";case"RSA-OAEP-384":return"sha384";case"RSA-OAEP-512":return"sha512";default:return}};function iA(e,t,...n){if((0,ZD.default)(e))return e;if((0,zD.isCryptoKey)(e))return(0,XD.checkEncCryptoKey)(e,t,...n),Cs.KeyObject.from(e);throw new TypeError((0,QD.default)(e,...e2.types))}var n2=(e,t,n)=>{let r=nA(e),i=rA(e),o=iA(t,e,"wrapKey","encrypt");return tA(o,e),(0,Cs.publicEncrypt)({key:o,oaepHash:i,padding:r},n)};ta.encrypt=n2;var r2=(e,t,n)=>{let r=nA(e),i=rA(e),o=iA(t,e,"unwrapKey","decrypt");return tA(o,e),(0,Cs.privateDecrypt)({key:o,oaepHash:i,padding:r},n)};ta.decrypt=r2});var Jh=y(Lh=>{"use strict";Object.defineProperty(Lh,"__esModule",{value:!0});Lh.default={}});var Rs=y(Zd=>{"use strict";Object.defineProperty(Zd,"__esModule",{value:!0});Zd.bitLength=oA;var i2=B(),o2=As();function oA(e){switch(e){case"A128GCM":return 128;case"A192GCM":return 192;case"A256GCM":case"A128CBC-HS256":return 256;case"A192CBC-HS384":return 384;case"A256CBC-HS512":return 512;default:throw new i2.JOSENotSupported(`Unsupported JWE Algorithm: ${e}`)}}Zd.default=e=>(0,o2.default)(new Uint8Array(oA(e)>>3))});var el=y(Ot=>{"use strict";Object.defineProperty(Ot,"__esModule",{value:!0});Ot.fromX509=Ot.fromSPKI=Ot.fromPKCS8=Ot.toPKCS8=Ot.toSPKI=void 0;var Qd=require("node:crypto"),aA=require("node:buffer"),a2=Ct(),s2=kt(),c2=Rt(),d2=xt(),sA=(e,t,n)=>{let r;if((0,a2.isCryptoKey)(n)){if(!n.extractable)throw new TypeError("CryptoKey is not extractable");r=Qd.KeyObject.from(n)}else if((0,s2.default)(n))r=n;else throw new TypeError((0,c2.default)(n,...d2.types));if(r.type!==e)throw new TypeError(`key is not a ${e} key`);return r.export({format:"pem",type:t})},l2=e=>sA("public","spki",e);Ot.toSPKI=l2;var u2=e=>sA("private","pkcs8",e);Ot.toPKCS8=u2;var f2=e=>(0,Qd.createPrivateKey)({key:aA.Buffer.from(e.replace(/(?:-----(?:BEGIN|END) PRIVATE KEY-----|\s)/g,""),"base64"),type:"pkcs8",format:"der"});Ot.fromPKCS8=f2;var p2=e=>(0,Qd.createPublicKey)({key:aA.Buffer.from(e.replace(/(?:-----(?:BEGIN|END) PUBLIC KEY-----|\s)/g,""),"base64"),type:"spki",format:"der"});Ot.fromSPKI=p2;var h2=e=>(0,Qd.createPublicKey)({key:e,type:"spki",format:"pem"});Ot.fromX509=h2});var dA=y(Uh=>{"use strict";Object.defineProperty(Uh,"__esModule",{value:!0});var cA=require("node:crypto"),m2=e=>e.d?(0,cA.createPrivateKey)({format:"jwk",key:e}):(0,cA.createPublicKey)({format:"jwk",key:e});Uh.default=m2});var ra=y(na=>{"use strict";Object.defineProperty(na,"__esModule",{value:!0});na.importSPKI=w2;na.importX509=E2;na.importPKCS8=v2;na.importJWK=b2;var g2=Ze(),jh=el(),y2=dA(),lA=B(),_2=$e();async function w2(e,t,n){if(typeof e!="string"||e.indexOf("-----BEGIN PUBLIC KEY-----")!==0)throw new TypeError('"spki" must be SPKI formatted string');return(0,jh.fromSPKI)(e,t,n)}async function E2(e,t,n){if(typeof e!="string"||e.indexOf("-----BEGIN CERTIFICATE-----")!==0)throw new TypeError('"x509" must be X.509 formatted string');return(0,jh.fromX509)(e,t,n)}async function v2(e,t,n){if(typeof e!="string"||e.indexOf("-----BEGIN PRIVATE KEY-----")!==0)throw new TypeError('"pkcs8" must be PKCS#8 formatted string');return(0,jh.fromPKCS8)(e,t,n)}async function b2(e,t){if(!(0,_2.default)(e))throw new TypeError("JWK must be an object");switch(t||=e.alg,e.kty){case"oct":if(typeof e.k!="string"||!e.k)throw new TypeError('missing "k" (Key Value) Parameter value');return(0,g2.decode)(e.k);case"RSA":if("oth"in e&&e.oth!==void 0)throw new lA.JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');case"EC":case"OKP":return(0,y2.default)({...e,alg:t});default:throw new lA.JOSENotSupported('Unsupported "kty" (Key Type) Parameter value')}}});var Ns=y(Os=>{"use strict";Object.defineProperty(Os,"__esModule",{value:!0});Os.checkKeyTypeWithJwk=void 0;var uA=Rt(),tl=xt(),xs=Ts(),ia=e=>e?.[Symbol.toStringTag],qh=(e,t,n)=>{if(t.use!==void 0&&t.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(t.key_ops!==void 0&&t.key_ops.includes?.(n)!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${n}`);if(t.alg!==void 0&&t.alg!==e)throw new TypeError(`Invalid key for this operation, when present its alg must be ${e}`);return!0},A2=(e,t,n,r)=>{if(!(t instanceof Uint8Array)){if(r&&xs.isJWK(t)){if(xs.isSecretJWK(t)&&qh(e,t,n))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!(0,tl.default)(t))throw new TypeError((0,uA.withAlg)(e,t,...tl.types,"Uint8Array",r?"JSON Web Key":null));if(t.type!=="secret")throw new TypeError(`${ia(t)} instances for symmetric algorithms must be of type "secret"`)}},S2=(e,t,n,r)=>{if(r&&xs.isJWK(t))switch(n){case"sign":if(xs.isPrivateJWK(t)&&qh(e,t,n))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(xs.isPublicJWK(t)&&qh(e,t,n))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!(0,tl.default)(t))throw new TypeError((0,uA.withAlg)(e,t,...tl.types,r?"JSON Web Key":null));if(t.type==="secret")throw new TypeError(`${ia(t)} instances for asymmetric algorithms must not be of type "secret"`);if(n==="sign"&&t.type==="public")throw new TypeError(`${ia(t)} instances for asymmetric algorithm signing must be of type "private"`);if(n==="decrypt"&&t.type==="public")throw new TypeError(`${ia(t)} instances for asymmetric algorithm decryption must be of type "private"`);if(t.algorithm&&n==="verify"&&t.type==="private")throw new TypeError(`${ia(t)} instances for asymmetric algorithm verifying must be of type "public"`);if(t.algorithm&&n==="encrypt"&&t.type==="private")throw new TypeError(`${ia(t)} instances for asymmetric algorithm encryption must be of type "public"`)};function fA(e,t,n,r){t.startsWith("HS")||t==="dir"||t.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(t)?A2(t,n,r,e):S2(t,n,r,e)}Os.default=fA.bind(void 0,!1);Os.checkKeyTypeWithJwk=fA.bind(void 0,!0)});var $h=y(Vh=>{"use strict";Object.defineProperty(Vh,"__esModule",{value:!0});var Kh=require("node:crypto"),I2=lh(),T2=hh(),P2=Ae(),k2=yh(),C2=Ct(),R2=qr(),pA=kt(),x2=Rt(),O2=ch(),Hh=B(),hA=Yd(),N2=xt();function D2(e,t,n,r,i){let o=parseInt(e.slice(1,4),10);(0,pA.default)(n)&&(n=n.export());let a=n.subarray(o>>3),s=n.subarray(0,o>>3),c=`aes-${o}-cbc`;if(!(0,hA.default)(c))throw new Hh.JOSENotSupported(`alg ${e} is not supported by your javascript runtime`);let d=(0,Kh.createCipheriv)(c,a,r),l=(0,P2.concat)(d.update(t),d.final()),u=parseInt(e.slice(-3),10),f=(0,k2.default)(i,r,l,u,s,o);return{ciphertext:l,tag:f,iv:r}}function M2(e,t,n,r,i){let a=`aes-${parseInt(e.slice(1,4),10)}-gcm`;if(!(0,hA.default)(a))throw new Hh.JOSENotSupported(`alg ${e} is not supported by your javascript runtime`);let s=(0,Kh.createCipheriv)(a,n,r,{authTagLength:16});i.byteLength&&s.setAAD(i,{plaintextLength:t.length});let c=s.update(t);s.final();let d=s.getAuthTag();return{ciphertext:c,tag:d,iv:r}}var L2=(e,t,n,r,i)=>{let o;if((0,C2.isCryptoKey)(n))(0,R2.checkEncCryptoKey)(n,e,"encrypt"),o=Kh.KeyObject.from(n);else if(n instanceof Uint8Array||(0,pA.default)(n))o=n;else throw new TypeError((0,x2.default)(n,...N2.types,"Uint8Array"));switch((0,T2.default)(e,o),r?(0,I2.default)(e,r):r=(0,O2.default)(e),e){case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":return D2(e,t,o,r,i);case"A128GCM":case"A192GCM":case"A256GCM":return M2(e,t,o,r,i);default:throw new Hh.JOSENotSupported("Unsupported JWE Content Encryption Algorithm")}};Vh.default=L2});var Wh=y(nl=>{"use strict";Object.defineProperty(nl,"__esModule",{value:!0});nl.wrap=j2;nl.unwrap=q2;var J2=$h(),U2=vh(),mA=Ze();async function j2(e,t,n,r){let i=e.slice(0,7),o=await(0,J2.default)(i,n,t,r,new Uint8Array(0));return{encryptedKey:o.ciphertext,iv:(0,mA.encode)(o.iv),tag:(0,mA.encode)(o.tag)}}async function q2(e,t,n,r,i){let o=e.slice(0,7);return(0,U2.default)(o,t,n,r,i,new Uint8Array(0))}});var _A=y(Fh=>{"use strict";Object.defineProperty(Fh,"__esModule",{value:!0});var gA=Xd(),yA=Rh(),K2=Oh(),H2=Mh(),Ds=Ze(),V2=Jh(),Se=B(),$2=Rs(),W2=ra(),F2=Ns(),B2=$e(),G2=Wh();async function Y2(e,t,n,r,i){switch((0,F2.default)(e,t,"decrypt"),t=await V2.default.normalizePrivateKey?.(t,e)||t,e){case"dir":{if(n!==void 0)throw new Se.JWEInvalid("Encountered unexpected JWE Encrypted Key");return t}case"ECDH-ES":if(n!==void 0)throw new Se.JWEInvalid("Encountered unexpected JWE Encrypted Key");case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!(0,B2.default)(r.epk))throw new Se.JWEInvalid('JOSE Header "epk" (Ephemeral Public Key) missing or invalid');if(!yA.ecdhAllowed(t))throw new Se.JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime");let o=await(0,W2.importJWK)(r.epk,e),a,s;if(r.apu!==void 0){if(typeof r.apu!="string")throw new Se.JWEInvalid('JOSE Header "apu" (Agreement PartyUInfo) invalid');try{a=(0,Ds.decode)(r.apu)}catch{throw new Se.JWEInvalid("Failed to base64url decode the apu")}}if(r.apv!==void 0){if(typeof r.apv!="string")throw new Se.JWEInvalid('JOSE Header "apv" (Agreement PartyVInfo) invalid');try{s=(0,Ds.decode)(r.apv)}catch{throw new Se.JWEInvalid("Failed to base64url decode the apv")}}let c=await yA.deriveKey(o,t,e==="ECDH-ES"?r.enc:e,e==="ECDH-ES"?(0,$2.bitLength)(r.enc):parseInt(e.slice(-5,-2),10),a,s);if(e==="ECDH-ES")return c;if(n===void 0)throw new Se.JWEInvalid("JWE Encrypted Key missing");return(0,gA.unwrap)(e.slice(-6),c,n)}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{if(n===void 0)throw new Se.JWEInvalid("JWE Encrypted Key missing");return(0,H2.decrypt)(e,t,n)}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{if(n===void 0)throw new Se.JWEInvalid("JWE Encrypted Key missing");if(typeof r.p2c!="number")throw new Se.JWEInvalid('JOSE Header "p2c" (PBES2 Count) missing or invalid');let o=i?.maxPBES2Count||1e4;if(r.p2c>o)throw new Se.JWEInvalid('JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds');if(typeof r.p2s!="string")throw new Se.JWEInvalid('JOSE Header "p2s" (PBES2 Salt) missing or invalid');let a;try{a=(0,Ds.decode)(r.p2s)}catch{throw new Se.JWEInvalid("Failed to base64url decode the p2s")}return(0,K2.decrypt)(e,t,n,r.p2c,a)}case"A128KW":case"A192KW":case"A256KW":{if(n===void 0)throw new Se.JWEInvalid("JWE Encrypted Key missing");return(0,gA.unwrap)(e,t,n)}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{if(n===void 0)throw new Se.JWEInvalid("JWE Encrypted Key missing");if(typeof r.iv!="string")throw new Se.JWEInvalid('JOSE Header "iv" (Initialization Vector) missing or invalid');if(typeof r.tag!="string")throw new Se.JWEInvalid('JOSE Header "tag" (Authentication Tag) missing or invalid');let o;try{o=(0,Ds.decode)(r.iv)}catch{throw new Se.JWEInvalid("Failed to base64url decode the iv")}let a;try{a=(0,Ds.decode)(r.tag)}catch{throw new Se.JWEInvalid("Failed to base64url decode the tag")}return(0,G2.unwrap)(e,t,n,o,a)}default:throw new Se.JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value')}}Fh.default=Y2});var oa=y(Bh=>{"use strict";Object.defineProperty(Bh,"__esModule",{value:!0});var z2=B();function X2(e,t,n,r,i){if(i.crit!==void 0&&r?.crit===void 0)throw new e('"crit" (Critical) Header Parameter MUST be integrity protected');if(!r||r.crit===void 0)return new Set;if(!Array.isArray(r.crit)||r.crit.length===0||r.crit.some(a=>typeof a!="string"||a.length===0))throw new e('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let o;n!==void 0?o=new Map([...Object.entries(n),...t.entries()]):o=t;for(let a of r.crit){if(!o.has(a))throw new z2.JOSENotSupported(`Extension Header Parameter "${a}" is not recognized`);if(i[a]===void 0)throw new e(`Extension Header Parameter "${a}" is missing`);if(o.get(a)&&r[a]===void 0)throw new e(`Extension Header Parameter "${a}" MUST be integrity protected`)}return new Set(r.crit)}Bh.default=X2});var Yh=y(Gh=>{"use strict";Object.defineProperty(Gh,"__esModule",{value:!0});var Z2=(e,t)=>{if(t!==void 0&&(!Array.isArray(t)||t.some(n=>typeof n!="string")))throw new TypeError(`"${e}" option must be an array of strings`);if(t)return new Set(t)};Gh.default=Z2});var rl=y(Xh=>{"use strict";Object.defineProperty(Xh,"__esModule",{value:!0});Xh.flattenedDecrypt=iM;var aa=Ze(),Q2=vh(),me=B(),eM=zo(),zh=$e(),tM=_A(),Ms=Ae(),nM=Rs(),rM=oa(),wA=Yh();async function iM(e,t,n){if(!(0,zh.default)(e))throw new me.JWEInvalid("Flattened JWE must be an object");if(e.protected===void 0&&e.header===void 0&&e.unprotected===void 0)throw new me.JWEInvalid("JOSE Header missing");if(e.iv!==void 0&&typeof e.iv!="string")throw new me.JWEInvalid("JWE Initialization Vector incorrect type");if(typeof e.ciphertext!="string")throw new me.JWEInvalid("JWE Ciphertext missing or incorrect type");if(e.tag!==void 0&&typeof e.tag!="string")throw new me.JWEInvalid("JWE Authentication Tag incorrect type");if(e.protected!==void 0&&typeof e.protected!="string")throw new me.JWEInvalid("JWE Protected Header incorrect type");if(e.encrypted_key!==void 0&&typeof e.encrypted_key!="string")throw new me.JWEInvalid("JWE Encrypted Key incorrect type");if(e.aad!==void 0&&typeof e.aad!="string")throw new me.JWEInvalid("JWE AAD incorrect type");if(e.header!==void 0&&!(0,zh.default)(e.header))throw new me.JWEInvalid("JWE Shared Unprotected Header incorrect type");if(e.unprotected!==void 0&&!(0,zh.default)(e.unprotected))throw new me.JWEInvalid("JWE Per-Recipient Unprotected Header incorrect type");let r;if(e.protected)try{let A=(0,aa.decode)(e.protected);r=JSON.parse(Ms.decoder.decode(A))}catch{throw new me.JWEInvalid("JWE Protected Header is invalid")}if(!(0,eM.default)(r,e.header,e.unprotected))throw new me.JWEInvalid("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");let i={...r,...e.header,...e.unprotected};if((0,rM.default)(me.JWEInvalid,new Map,n?.crit,r,i),i.zip!==void 0)throw new me.JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');let{alg:o,enc:a}=i;if(typeof o!="string"||!o)throw new me.JWEInvalid("missing JWE Algorithm (alg) in JWE Header");if(typeof a!="string"||!a)throw new me.JWEInvalid("missing JWE Encryption Algorithm (enc) in JWE Header");let s=n&&(0,wA.default)("keyManagementAlgorithms",n.keyManagementAlgorithms),c=n&&(0,wA.default)("contentEncryptionAlgorithms",n.contentEncryptionAlgorithms);if(s&&!s.has(o)||!s&&o.startsWith("PBES2"))throw new me.JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');if(c&&!c.has(a))throw new me.JOSEAlgNotAllowed('"enc" (Encryption Algorithm) Header Parameter value not allowed');let d;if(e.encrypted_key!==void 0)try{d=(0,aa.decode)(e.encrypted_key)}catch{throw new me.JWEInvalid("Failed to base64url decode the encrypted_key")}let l=!1;typeof t=="function"&&(t=await t(r,e),l=!0);let u;try{u=await(0,tM.default)(o,t,d,i,n)}catch(A){if(A instanceof TypeError||A instanceof me.JWEInvalid||A instanceof me.JOSENotSupported)throw A;u=(0,nM.default)(a)}let f,h;if(e.iv!==void 0)try{f=(0,aa.decode)(e.iv)}catch{throw new me.JWEInvalid("Failed to base64url decode the iv")}if(e.tag!==void 0)try{h=(0,aa.decode)(e.tag)}catch{throw new me.JWEInvalid("Failed to base64url decode the tag")}let p=Ms.encoder.encode(e.protected??""),m;e.aad!==void 0?m=(0,Ms.concat)(p,Ms.encoder.encode("."),Ms.encoder.encode(e.aad)):m=p;let w;try{w=(0,aa.decode)(e.ciphertext)}catch{throw new me.JWEInvalid("Failed to base64url decode the ciphertext")}let _={plaintext:await(0,Q2.default)(a,u,w,f,h,m)};if(e.protected!==void 0&&(_.protectedHeader=r),e.aad!==void 0)try{_.additionalAuthenticatedData=(0,aa.decode)(e.aad)}catch{throw new me.JWEInvalid("Failed to base64url decode the aad")}return e.unprotected!==void 0&&(_.sharedUnprotectedHeader=e.unprotected),e.header!==void 0&&(_.unprotectedHeader=e.header),l?{..._,key:t}:_}});var Qh=y(Zh=>{"use strict";Object.defineProperty(Zh,"__esModule",{value:!0});Zh.compactDecrypt=sM;var oM=rl(),EA=B(),aM=Ae();async function sM(e,t,n){if(e instanceof Uint8Array&&(e=aM.decoder.decode(e)),typeof e!="string")throw new EA.JWEInvalid("Compact JWE must be a string or Uint8Array");let{0:r,1:i,2:o,3:a,4:s,length:c}=e.split(".");if(c!==5)throw new EA.JWEInvalid("Invalid Compact JWE");let d=await(0,oM.flattenedDecrypt)({ciphertext:a,iv:o||void 0,protected:r,tag:s||void 0,encrypted_key:i||void 0},t,n),l={plaintext:d.plaintext,protectedHeader:d.protectedHeader};return typeof t=="function"?{...l,key:d.key}:l}});var bA=y(em=>{"use strict";Object.defineProperty(em,"__esModule",{value:!0});em.generalDecrypt=dM;var cM=rl(),il=B(),vA=$e();async function dM(e,t,n){if(!(0,vA.default)(e))throw new il.JWEInvalid("General JWE must be an object");if(!Array.isArray(e.recipients)||!e.recipients.every(vA.default))throw new il.JWEInvalid("JWE Recipients missing or incorrect type");if(!e.recipients.length)throw new il.JWEInvalid("JWE Recipients has no members");for(let r of e.recipients)try{return await(0,cM.flattenedDecrypt)({aad:e.aad,ciphertext:e.ciphertext,encrypted_key:r.encrypted_key,header:r.header,iv:e.iv,protected:e.protected,tag:e.tag,unprotected:e.unprotected},t,n)}catch{}throw new il.JWEDecryptionFailed}});var tm=y(ol=>{"use strict";Object.defineProperty(ol,"__esModule",{value:!0});ol.unprotected=void 0;ol.unprotected=Symbol()});var AA=y(nm=>{"use strict";Object.defineProperty(nm,"__esModule",{value:!0});var lM=require("node:crypto"),uM=Ze(),fM=B(),pM=Ct(),hM=kt(),mM=Rt(),gM=xt(),yM=e=>{let t;if((0,pM.isCryptoKey)(e)){if(!e.extractable)throw new TypeError("CryptoKey is not extractable");t=lM.KeyObject.from(e)}else if((0,hM.default)(e))t=e;else{if(e instanceof Uint8Array)return{kty:"oct",k:(0,uM.encode)(e)};throw new TypeError((0,mM.default)(e,...gM.types,"Uint8Array"))}if(t.type!=="secret"&&!["rsa","ec","ed25519","x25519","ed448","x448"].includes(t.asymmetricKeyType))throw new fM.JOSENotSupported("Unsupported key asymmetricKeyType");return t.export({format:"jwk"})};nm.default=yM});var rm=y(Ls=>{"use strict";Object.defineProperty(Ls,"__esModule",{value:!0});Ls.exportSPKI=vM;Ls.exportPKCS8=bM;Ls.exportJWK=AM;var _M=el(),wM=el(),EM=AA();async function vM(e){return(0,_M.toSPKI)(e)}async function bM(e){return(0,wM.toPKCS8)(e)}async function AM(e){return(0,EM.default)(e)}});var am=y(om=>{"use strict";Object.defineProperty(om,"__esModule",{value:!0});var SA=Xd(),im=Rh(),SM=Oh(),IM=Mh(),IA=Ze(),TM=Jh(),sa=Rs(),TA=B(),PM=rm(),kM=Ns(),CM=Wh();async function RM(e,t,n,r,i={}){let o,a,s;switch((0,kM.default)(e,n,"encrypt"),n=await TM.default.normalizePublicKey?.(n,e)||n,e){case"dir":{s=n;break}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{if(!im.ecdhAllowed(n))throw new TA.JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime");let{apu:c,apv:d}=i,{epk:l}=i;l||=(await im.generateEpk(n)).privateKey;let{x:u,y:f,crv:h,kty:p}=await(0,PM.exportJWK)(l),m=await im.deriveKey(n,l,e==="ECDH-ES"?t:e,e==="ECDH-ES"?(0,sa.bitLength)(t):parseInt(e.slice(-5,-2),10),c,d);if(a={epk:{x:u,crv:h,kty:p}},p==="EC"&&(a.epk.y=f),c&&(a.apu=(0,IA.encode)(c)),d&&(a.apv=(0,IA.encode)(d)),e==="ECDH-ES"){s=m;break}s=r||(0,sa.default)(t);let w=e.slice(-6);o=await(0,SA.wrap)(w,m,s);break}case"RSA1_5":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":{s=r||(0,sa.default)(t),o=await(0,IM.encrypt)(e,n,s);break}case"PBES2-HS256+A128KW":case"PBES2-HS384+A192KW":case"PBES2-HS512+A256KW":{s=r||(0,sa.default)(t);let{p2c:c,p2s:d}=i;({encryptedKey:o,...a}=await(0,SM.encrypt)(e,n,s,c,d));break}case"A128KW":case"A192KW":case"A256KW":{s=r||(0,sa.default)(t),o=await(0,SA.wrap)(e,n,s);break}case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":{s=r||(0,sa.default)(t);let{iv:c}=i;({encryptedKey:o,...a}=await(0,CM.wrap)(e,n,s,c));break}default:throw new TA.JOSENotSupported('Invalid or unsupported "alg" (JWE Algorithm) header value')}return{cek:s,encryptedKey:o,parameters:a}}om.default=RM});var sl=y(al=>{"use strict";Object.defineProperty(al,"__esModule",{value:!0});al.FlattenedEncrypt=void 0;var ca=Ze(),xM=tm(),OM=$h(),NM=am(),da=B(),DM=zo(),la=Ae(),MM=oa(),sm=class{_plaintext;_protectedHeader;_sharedUnprotectedHeader;_unprotectedHeader;_aad;_cek;_iv;_keyManagementParameters;constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("plaintext must be an instance of Uint8Array");this._plaintext=t}setKeyManagementParameters(t){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=t,this}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setSharedUnprotectedHeader(t){if(this._sharedUnprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._sharedUnprotectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}setAdditionalAuthenticatedData(t){return this._aad=t,this}setContentEncryptionKey(t){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=t,this}setInitializationVector(t){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=t,this}async encrypt(t,n){if(!this._protectedHeader&&!this._unprotectedHeader&&!this._sharedUnprotectedHeader)throw new da.JWEInvalid("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");if(!(0,DM.default)(this._protectedHeader,this._unprotectedHeader,this._sharedUnprotectedHeader))throw new da.JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let r={...this._protectedHeader,...this._unprotectedHeader,...this._sharedUnprotectedHeader};if((0,MM.default)(da.JWEInvalid,new Map,n?.crit,this._protectedHeader,r),r.zip!==void 0)throw new da.JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.');let{alg:i,enc:o}=r;if(typeof i!="string"||!i)throw new da.JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(typeof o!="string"||!o)throw new da.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');let a;if(this._cek&&(i==="dir"||i==="ECDH-ES"))throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${i}`);let s;{let m;({cek:s,encryptedKey:a,parameters:m}=await(0,NM.default)(i,o,t,this._cek,this._keyManagementParameters)),m&&(n&&xM.unprotected in n?this._unprotectedHeader?this._unprotectedHeader={...this._unprotectedHeader,...m}:this.setUnprotectedHeader(m):this._protectedHeader?this._protectedHeader={...this._protectedHeader,...m}:this.setProtectedHeader(m))}let c,d,l;this._protectedHeader?d=la.encoder.encode((0,ca.encode)(JSON.stringify(this._protectedHeader))):d=la.encoder.encode(""),this._aad?(l=(0,ca.encode)(this._aad),c=(0,la.concat)(d,la.encoder.encode("."),la.encoder.encode(l))):c=d;let{ciphertext:u,tag:f,iv:h}=await(0,OM.default)(o,this._plaintext,s,this._iv,c),p={ciphertext:(0,ca.encode)(u)};return h&&(p.iv=(0,ca.encode)(h)),f&&(p.tag=(0,ca.encode)(f)),a&&(p.encrypted_key=(0,ca.encode)(a)),l&&(p.aad=l),this._protectedHeader&&(p.protected=la.decoder.decode(d)),this._sharedUnprotectedHeader&&(p.unprotected=this._sharedUnprotectedHeader),this._unprotectedHeader&&(p.header=this._unprotectedHeader),p}};al.FlattenedEncrypt=sm});var kA=y(cl=>{"use strict";Object.defineProperty(cl,"__esModule",{value:!0});cl.GeneralEncrypt=void 0;var PA=sl(),LM=tm(),Hr=B(),JM=Rs(),UM=zo(),jM=am(),qM=Ze(),KM=oa(),cm=class{parent;unprotectedHeader;key;options;constructor(t,n,r){this.parent=t,this.key=n,this.options=r}setUnprotectedHeader(t){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=t,this}addRecipient(...t){return this.parent.addRecipient(...t)}encrypt(...t){return this.parent.encrypt(...t)}done(){return this.parent}},dm=class{_plaintext;_recipients=[];_protectedHeader;_unprotectedHeader;_aad;constructor(t){this._plaintext=t}addRecipient(t,n){let r=new cm(this,t,{crit:n?.crit});return this._recipients.push(r),r}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setSharedUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setSharedUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}setAdditionalAuthenticatedData(t){return this._aad=t,this}async encrypt(){if(!this._recipients.length)throw new Hr.JWEInvalid("at least one recipient must be added");if(this._recipients.length===1){let[i]=this._recipients,o=await new PA.FlattenedEncrypt(this._plaintext).setAdditionalAuthenticatedData(this._aad).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(i.unprotectedHeader).encrypt(i.key,{...i.options}),a={ciphertext:o.ciphertext,iv:o.iv,recipients:[{}],tag:o.tag};return o.aad&&(a.aad=o.aad),o.protected&&(a.protected=o.protected),o.unprotected&&(a.unprotected=o.unprotected),o.encrypted_key&&(a.recipients[0].encrypted_key=o.encrypted_key),o.header&&(a.recipients[0].header=o.header),a}let t;for(let i=0;i<this._recipients.length;i++){let o=this._recipients[i];if(!(0,UM.default)(this._protectedHeader,this._unprotectedHeader,o.unprotectedHeader))throw new Hr.JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");let a={...this._protectedHeader,...this._unprotectedHeader,...o.unprotectedHeader},{alg:s}=a;if(typeof s!="string"||!s)throw new Hr.JWEInvalid('JWE "alg" (Algorithm) Header Parameter missing or invalid');if(s==="dir"||s==="ECDH-ES")throw new Hr.JWEInvalid('"dir" and "ECDH-ES" alg may only be used with a single recipient');if(typeof a.enc!="string"||!a.enc)throw new Hr.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter missing or invalid');if(!t)t=a.enc;else if(t!==a.enc)throw new Hr.JWEInvalid('JWE "enc" (Encryption Algorithm) Header Parameter must be the same for all recipients');if((0,KM.default)(Hr.JWEInvalid,new Map,o.options.crit,this._protectedHeader,a),a.zip!==void 0)throw new Hr.JOSENotSupported('JWE "zip" (Compression Algorithm) Header Parameter is not supported.')}let n=(0,JM.default)(t),r={ciphertext:"",iv:"",recipients:[],tag:""};for(let i=0;i<this._recipients.length;i++){let o=this._recipients[i],a={};r.recipients.push(a);let c={...this._protectedHeader,...this._unprotectedHeader,...o.unprotectedHeader}.alg.startsWith("PBES2")?2048+i:void 0;if(i===0){let u=await new PA.FlattenedEncrypt(this._plaintext).setAdditionalAuthenticatedData(this._aad).setContentEncryptionKey(n).setProtectedHeader(this._protectedHeader).setSharedUnprotectedHeader(this._unprotectedHeader).setUnprotectedHeader(o.unprotectedHeader).setKeyManagementParameters({p2c:c}).encrypt(o.key,{...o.options,[LM.unprotected]:!0});r.ciphertext=u.ciphertext,r.iv=u.iv,r.tag=u.tag,u.aad&&(r.aad=u.aad),u.protected&&(r.protected=u.protected),u.unprotected&&(r.unprotected=u.unprotected),a.encrypted_key=u.encrypted_key,u.header&&(a.header=u.header);continue}let{encryptedKey:d,parameters:l}=await(0,jM.default)(o.unprotectedHeader?.alg||this._protectedHeader?.alg||this._unprotectedHeader?.alg,t,o.key,n,{p2c:c});a.encrypted_key=(0,qM.encode)(d),(o.unprotectedHeader||l)&&(a.header={...o.unprotectedHeader,...l})}return r}};cl.GeneralEncrypt=dm});var um=y(lm=>{"use strict";Object.defineProperty(lm,"__esModule",{value:!0});lm.default=VM;var HM=B();function VM(e){switch(e){case"PS256":case"RS256":case"ES256":case"ES256K":return"sha256";case"PS384":case"RS384":case"ES384":return"sha384";case"PS512":case"RS512":case"ES512":return"sha512";case"Ed25519":case"EdDSA":return;default:throw new HM.JOSENotSupported(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}});var hm=y(pm=>{"use strict";Object.defineProperty(pm,"__esModule",{value:!0});pm.default=BM;var fm=require("node:crypto"),$M=Sh(),WM=B(),CA=Dh(),FM=new Map([["ES256","P-256"],["ES256K","secp256k1"],["ES384","P-384"],["ES512","P-521"]]);function BM(e,t){let n,r,i;if(t instanceof fm.KeyObject)n=t.asymmetricKeyType,r=t.asymmetricKeyDetails;else switch(i=!0,t.kty){case"RSA":n="rsa";break;case"EC":n="ec";break;case"OKP":{if(t.crv==="Ed25519"){n="ed25519";break}if(t.crv==="Ed448"){n="ed448";break}throw new TypeError("Invalid key for this operation, its crv must be Ed25519 or Ed448")}default:throw new TypeError("Invalid key for this operation, its kty must be RSA, OKP, or EC")}let o;switch(e){case"Ed25519":if(n!=="ed25519")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519");break;case"EdDSA":if(!["ed25519","ed448"].includes(n))throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448");break;case"RS256":case"RS384":case"RS512":if(n!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");(0,CA.default)(t,e);break;case"PS256":case"PS384":case"PS512":if(n==="rsa-pss"){let{hashAlgorithm:a,mgf1HashAlgorithm:s,saltLength:c}=r,d=parseInt(e.slice(-3),10);if(a!==void 0&&(a!==`sha${d}`||s!==a))throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${e}`);if(c!==void 0&&c>d>>3)throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${e}`)}else if(n!=="rsa")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss");(0,CA.default)(t,e),o={padding:fm.constants.RSA_PKCS1_PSS_PADDING,saltLength:fm.constants.RSA_PSS_SALTLEN_DIGEST};break;case"ES256":case"ES256K":case"ES384":case"ES512":{if(n!=="ec")throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ec");let a=(0,$M.default)(t),s=FM.get(e);if(a!==s)throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${s}, got ${a}`);o={dsaEncoding:"ieee-p1363"};break}default:throw new WM.JOSENotSupported(`alg ${e} is not supported either by JOSE or your javascript runtime`)}return i?{format:"jwk",key:t,...o}:o?{...o,key:t}:t}});var RA=y(mm=>{"use strict";Object.defineProperty(mm,"__esModule",{value:!0});mm.default=YM;var GM=B();function YM(e){switch(e){case"HS256":return"sha256";case"HS384":return"sha384";case"HS512":return"sha512";default:throw new GM.JOSENotSupported(`alg ${e} is not supported either by JOSE or your javascript runtime`)}}});var ym=y(gm=>{"use strict";Object.defineProperty(gm,"__esModule",{value:!0});gm.default=QM;var dl=require("node:crypto"),zM=Ct(),XM=qr(),xA=Rt(),OA=xt(),ZM=Ts();function QM(e,t,n){if(t instanceof Uint8Array){if(!e.startsWith("HS"))throw new TypeError((0,xA.default)(t,...OA.types));return(0,dl.createSecretKey)(t)}if(t instanceof dl.KeyObject)return t;if((0,zM.isCryptoKey)(t))return(0,XM.checkSigCryptoKey)(t,e,n),dl.KeyObject.from(t);if(ZM.isJWK(t))return e.startsWith("HS")?(0,dl.createSecretKey)(Buffer.from(t.k,"base64url")):t;throw new TypeError((0,xA.default)(t,...OA.types,"Uint8Array","JSON Web Key"))}});var wm=y(_m=>{"use strict";Object.defineProperty(_m,"__esModule",{value:!0});var NA=require("node:crypto"),eL=require("node:util"),tL=um(),nL=RA(),rL=hm(),iL=ym(),oL=(0,eL.promisify)(NA.sign),aL=async(e,t,n)=>{let r=(0,iL.default)(e,t,"sign");if(e.startsWith("HS")){let i=NA.createHmac((0,nL.default)(e),r);return i.update(n),i.digest()}return oL((0,tL.default)(e),n,(0,rL.default)(e,r))};_m.default=aL});var MA=y(Em=>{"use strict";Object.defineProperty(Em,"__esModule",{value:!0});var DA=require("node:crypto"),sL=require("node:util"),cL=um(),dL=hm(),lL=wm(),uL=ym(),fL=(0,sL.promisify)(DA.verify),pL=async(e,t,n,r)=>{let i=(0,uL.default)(e,t,"verify");if(e.startsWith("HS")){let s=await(0,lL.default)(e,i,r),c=n;try{return DA.timingSafeEqual(c,s)}catch{return!1}}let o=(0,cL.default)(e),a=(0,dL.default)(e,i);try{return await fL(o,r,a,n)}catch{return!1}};Em.default=pL});var ll=y(bm=>{"use strict";Object.defineProperty(bm,"__esModule",{value:!0});bm.flattenedVerify=EL;var vm=Ze(),hL=MA(),qe=B(),ua=Ae(),mL=zo(),LA=$e(),JA=Ns(),gL=oa(),yL=Yh(),_L=Ts(),wL=ra();async function EL(e,t,n){if(!(0,LA.default)(e))throw new qe.JWSInvalid("Flattened JWS must be an object");if(e.protected===void 0&&e.header===void 0)throw new qe.JWSInvalid('Flattened JWS must have either of the "protected" or "header" members');if(e.protected!==void 0&&typeof e.protected!="string")throw new qe.JWSInvalid("JWS Protected Header incorrect type");if(e.payload===void 0)throw new qe.JWSInvalid("JWS Payload missing");if(typeof e.signature!="string")throw new qe.JWSInvalid("JWS Signature missing or incorrect type");if(e.header!==void 0&&!(0,LA.default)(e.header))throw new qe.JWSInvalid("JWS Unprotected Header incorrect type");let r={};if(e.protected)try{let m=(0,vm.decode)(e.protected);r=JSON.parse(ua.decoder.decode(m))}catch{throw new qe.JWSInvalid("JWS Protected Header is invalid")}if(!(0,mL.default)(r,e.header))throw new qe.JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let i={...r,...e.header},o=(0,gL.default)(qe.JWSInvalid,new Map([["b64",!0]]),n?.crit,r,i),a=!0;if(o.has("b64")&&(a=r.b64,typeof a!="boolean"))throw new qe.JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:s}=i;if(typeof s!="string"||!s)throw new qe.JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');let c=n&&(0,yL.default)("algorithms",n.algorithms);if(c&&!c.has(s))throw new qe.JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');if(a){if(typeof e.payload!="string")throw new qe.JWSInvalid("JWS Payload must be a string")}else if(typeof e.payload!="string"&&!(e.payload instanceof Uint8Array))throw new qe.JWSInvalid("JWS Payload must be a string or an Uint8Array instance");let d=!1;typeof t=="function"?(t=await t(r,e),d=!0,(0,JA.checkKeyTypeWithJwk)(s,t,"verify"),(0,_L.isJWK)(t)&&(t=await(0,wL.importJWK)(t,s))):(0,JA.checkKeyTypeWithJwk)(s,t,"verify");let l=(0,ua.concat)(ua.encoder.encode(e.protected??""),ua.encoder.encode("."),typeof e.payload=="string"?ua.encoder.encode(e.payload):e.payload),u;try{u=(0,vm.decode)(e.signature)}catch{throw new qe.JWSInvalid("Failed to base64url decode the signature")}if(!await(0,hL.default)(s,t,u,l))throw new qe.JWSSignatureVerificationFailed;let h;if(a)try{h=(0,vm.decode)(e.payload)}catch{throw new qe.JWSInvalid("Failed to base64url decode the payload")}else typeof e.payload=="string"?h=ua.encoder.encode(e.payload):h=e.payload;let p={payload:h};return e.protected!==void 0&&(p.protectedHeader=r),e.header!==void 0&&(p.unprotectedHeader=e.header),d?{...p,key:t}:p}});var Sm=y(Am=>{"use strict";Object.defineProperty(Am,"__esModule",{value:!0});Am.compactVerify=AL;var vL=ll(),UA=B(),bL=Ae();async function AL(e,t,n){if(e instanceof Uint8Array&&(e=bL.decoder.decode(e)),typeof e!="string")throw new UA.JWSInvalid("Compact JWS must be a string or Uint8Array");let{0:r,1:i,2:o,length:a}=e.split(".");if(a!==3)throw new UA.JWSInvalid("Invalid Compact JWS");let s=await(0,vL.flattenedVerify)({payload:i,protected:r,signature:o},t,n),c={payload:s.payload,protectedHeader:s.protectedHeader};return typeof t=="function"?{...c,key:s.key}:c}});var qA=y(Tm=>{"use strict";Object.defineProperty(Tm,"__esModule",{value:!0});Tm.generalVerify=IL;var SL=ll(),Im=B(),jA=$e();async function IL(e,t,n){if(!(0,jA.default)(e))throw new Im.JWSInvalid("General JWS must be an object");if(!Array.isArray(e.signatures)||!e.signatures.every(jA.default))throw new Im.JWSInvalid("JWS Signatures missing or incorrect type");for(let r of e.signatures)try{return await(0,SL.flattenedVerify)({header:r.header,payload:e.payload,protected:r.protected,signature:r.signature},t,n)}catch{}throw new Im.JWSSignatureVerificationFailed}});var km=y(Pm=>{"use strict";Object.defineProperty(Pm,"__esModule",{value:!0});Pm.default=e=>Math.floor(e.getTime()/1e3)});var xm=y(Rm=>{"use strict";Object.defineProperty(Rm,"__esModule",{value:!0});var KA=60,HA=KA*60,Cm=HA*24,TL=Cm*7,PL=Cm*365.25,kL=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;Rm.default=e=>{let t=kL.exec(e);if(!t||t[4]&&t[1])throw new TypeError("Invalid time period format");let n=parseFloat(t[2]),r=t[3].toLowerCase(),i;switch(r){case"sec":case"secs":case"second":case"seconds":case"s":i=Math.round(n);break;case"minute":case"minutes":case"min":case"mins":case"m":i=Math.round(n*KA);break;case"hour":case"hours":case"hr":case"hrs":case"h":i=Math.round(n*HA);break;case"day":case"days":case"d":i=Math.round(n*Cm);break;case"week":case"weeks":case"w":i=Math.round(n*TL);break;default:i=Math.round(n*PL);break}return t[1]==="-"||t[4]==="ago"?-i:i}});var ul=y(Om=>{"use strict";Object.defineProperty(Om,"__esModule",{value:!0});var vt=B(),CL=Ae(),RL=km(),VA=xm(),xL=$e(),$A=e=>e.toLowerCase().replace(/^application\//,""),OL=(e,t)=>typeof e=="string"?t.includes(e):Array.isArray(e)?t.some(Set.prototype.has.bind(new Set(e))):!1;Om.default=(e,t,n={})=>{let r;try{r=JSON.parse(CL.decoder.decode(t))}catch{}if(!(0,xL.default)(r))throw new vt.JWTInvalid("JWT Claims Set must be a top-level JSON object");let{typ:i}=n;if(i&&(typeof e.typ!="string"||$A(e.typ)!==$A(i)))throw new vt.JWTClaimValidationFailed('unexpected "typ" JWT header value',r,"typ","check_failed");let{requiredClaims:o=[],issuer:a,subject:s,audience:c,maxTokenAge:d}=n,l=[...o];d!==void 0&&l.push("iat"),c!==void 0&&l.push("aud"),s!==void 0&&l.push("sub"),a!==void 0&&l.push("iss");for(let p of new Set(l.reverse()))if(!(p in r))throw new vt.JWTClaimValidationFailed(`missing required "${p}" claim`,r,p,"missing");if(a&&!(Array.isArray(a)?a:[a]).includes(r.iss))throw new vt.JWTClaimValidationFailed('unexpected "iss" claim value',r,"iss","check_failed");if(s&&r.sub!==s)throw new vt.JWTClaimValidationFailed('unexpected "sub" claim value',r,"sub","check_failed");if(c&&!OL(r.aud,typeof c=="string"?[c]:c))throw new vt.JWTClaimValidationFailed('unexpected "aud" claim value',r,"aud","check_failed");let u;switch(typeof n.clockTolerance){case"string":u=(0,VA.default)(n.clockTolerance);break;case"number":u=n.clockTolerance;break;case"undefined":u=0;break;default:throw new TypeError("Invalid clockTolerance option type")}let{currentDate:f}=n,h=(0,RL.default)(f||new Date);if((r.iat!==void 0||d)&&typeof r.iat!="number")throw new vt.JWTClaimValidationFailed('"iat" claim must be a number',r,"iat","invalid");if(r.nbf!==void 0){if(typeof r.nbf!="number")throw new vt.JWTClaimValidationFailed('"nbf" claim must be a number',r,"nbf","invalid");if(r.nbf>h+u)throw new vt.JWTClaimValidationFailed('"nbf" claim timestamp check failed',r,"nbf","check_failed")}if(r.exp!==void 0){if(typeof r.exp!="number")throw new vt.JWTClaimValidationFailed('"exp" claim must be a number',r,"exp","invalid");if(r.exp<=h-u)throw new vt.JWTExpired('"exp" claim timestamp check failed',r,"exp","check_failed")}if(d){let p=h-r.iat,m=typeof d=="number"?d:(0,VA.default)(d);if(p-u>m)throw new vt.JWTExpired('"iat" claim timestamp check failed (too far in the past)',r,"iat","check_failed");if(p<0-u)throw new vt.JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)',r,"iat","check_failed")}return r}});var WA=y(Nm=>{"use strict";Object.defineProperty(Nm,"__esModule",{value:!0});Nm.jwtVerify=LL;var NL=Sm(),DL=ul(),ML=B();async function LL(e,t,n){let r=await(0,NL.compactVerify)(e,t,n);if(r.protectedHeader.crit?.includes("b64")&&r.protectedHeader.b64===!1)throw new ML.JWTInvalid("JWTs MUST NOT use unencoded payload");let o={payload:(0,DL.default)(r.protectedHeader,r.payload,n),protectedHeader:r.protectedHeader};return typeof t=="function"?{...o,key:r.key}:o}});var FA=y(Mm=>{"use strict";Object.defineProperty(Mm,"__esModule",{value:!0});Mm.jwtDecrypt=jL;var JL=Qh(),UL=ul(),Dm=B();async function jL(e,t,n){let r=await(0,JL.compactDecrypt)(e,t,n),i=(0,UL.default)(r.protectedHeader,r.plaintext,n),{protectedHeader:o}=r;if(o.iss!==void 0&&o.iss!==i.iss)throw new Dm.JWTClaimValidationFailed('replicated "iss" claim header parameter mismatch',i,"iss","mismatch");if(o.sub!==void 0&&o.sub!==i.sub)throw new Dm.JWTClaimValidationFailed('replicated "sub" claim header parameter mismatch',i,"sub","mismatch");if(o.aud!==void 0&&JSON.stringify(o.aud)!==JSON.stringify(i.aud))throw new Dm.JWTClaimValidationFailed('replicated "aud" claim header parameter mismatch',i,"aud","mismatch");let a={payload:i,protectedHeader:o};return typeof t=="function"?{...a,key:r.key}:a}});var Jm=y(fl=>{"use strict";Object.defineProperty(fl,"__esModule",{value:!0});fl.CompactEncrypt=void 0;var qL=sl(),Lm=class{_flattened;constructor(t){this._flattened=new qL.FlattenedEncrypt(t)}setContentEncryptionKey(t){return this._flattened.setContentEncryptionKey(t),this}setInitializationVector(t){return this._flattened.setInitializationVector(t),this}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}setKeyManagementParameters(t){return this._flattened.setKeyManagementParameters(t),this}async encrypt(t,n){let r=await this._flattened.encrypt(t,n);return[r.protected,r.encrypted_key,r.iv,r.ciphertext,r.tag].join(".")}};fl.CompactEncrypt=Lm});var hl=y(pl=>{"use strict";Object.defineProperty(pl,"__esModule",{value:!0});pl.FlattenedSign=void 0;var Um=Ze(),KL=wm(),HL=zo(),Js=B(),Hi=Ae(),VL=Ns(),$L=oa(),jm=class{_payload;_protectedHeader;_unprotectedHeader;constructor(t){if(!(t instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=t}setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setUnprotectedHeader(t){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=t,this}async sign(t,n){if(!this._protectedHeader&&!this._unprotectedHeader)throw new Js.JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!(0,HL.default)(this._protectedHeader,this._unprotectedHeader))throw new Js.JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let r={...this._protectedHeader,...this._unprotectedHeader},i=(0,$L.default)(Js.JWSInvalid,new Map([["b64",!0]]),n?.crit,this._protectedHeader,r),o=!0;if(i.has("b64")&&(o=this._protectedHeader.b64,typeof o!="boolean"))throw new Js.JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:a}=r;if(typeof a!="string"||!a)throw new Js.JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');(0,VL.checkKeyTypeWithJwk)(a,t,"sign");let s=this._payload;o&&(s=Hi.encoder.encode((0,Um.encode)(s)));let c;this._protectedHeader?c=Hi.encoder.encode((0,Um.encode)(JSON.stringify(this._protectedHeader))):c=Hi.encoder.encode("");let d=(0,Hi.concat)(c,Hi.encoder.encode("."),s),l=await(0,KL.default)(a,t,d),u={signature:(0,Um.encode)(l),payload:""};return o&&(u.payload=Hi.decoder.decode(s)),this._unprotectedHeader&&(u.header=this._unprotectedHeader),this._protectedHeader&&(u.protected=Hi.decoder.decode(c)),u}};pl.FlattenedSign=jm});var Km=y(ml=>{"use strict";Object.defineProperty(ml,"__esModule",{value:!0});ml.CompactSign=void 0;var WL=hl(),qm=class{_flattened;constructor(t){this._flattened=new WL.FlattenedSign(t)}setProtectedHeader(t){return this._flattened.setProtectedHeader(t),this}async sign(t,n){let r=await this._flattened.sign(t,n);if(r.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${r.protected}.${r.payload}.${r.signature}`}};ml.CompactSign=qm});var GA=y(gl=>{"use strict";Object.defineProperty(gl,"__esModule",{value:!0});gl.GeneralSign=void 0;var FL=hl(),BA=B(),Hm=class{parent;protectedHeader;unprotectedHeader;options;key;constructor(t,n,r){this.parent=t,this.key=n,this.options=r}setProtectedHeader(t){if(this.protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this.protectedHeader=t,this}setUnprotectedHeader(t){if(this.unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this.unprotectedHeader=t,this}addSignature(...t){return this.parent.addSignature(...t)}sign(...t){return this.parent.sign(...t)}done(){return this.parent}},Vm=class{_payload;_signatures=[];constructor(t){this._payload=t}addSignature(t,n){let r=new Hm(this,t,n);return this._signatures.push(r),r}async sign(){if(!this._signatures.length)throw new BA.JWSInvalid("at least one signature must be added");let t={signatures:[],payload:""};for(let n=0;n<this._signatures.length;n++){let r=this._signatures[n],i=new FL.FlattenedSign(this._payload);i.setProtectedHeader(r.protectedHeader),i.setUnprotectedHeader(r.unprotectedHeader);let{payload:o,...a}=await i.sign(r.key,r.options);if(n===0)t.payload=o;else if(t.payload!==o)throw new BA.JWSInvalid("inconsistent use of JWS Unencoded Payload (RFC7797)");t.signatures.push(a)}return t}};gl.GeneralSign=Vm});var _l=y(yl=>{"use strict";Object.defineProperty(yl,"__esModule",{value:!0});yl.ProduceJWT=void 0;var Vi=km(),BL=$e(),$m=xm();function $i(e,t){if(!Number.isFinite(t))throw new TypeError(`Invalid ${e} input`);return t}var Wm=class{_payload;constructor(t={}){if(!(0,BL.default)(t))throw new TypeError("JWT Claims Set MUST be an object");this._payload=t}setIssuer(t){return this._payload={...this._payload,iss:t},this}setSubject(t){return this._payload={...this._payload,sub:t},this}setAudience(t){return this._payload={...this._payload,aud:t},this}setJti(t){return this._payload={...this._payload,jti:t},this}setNotBefore(t){return typeof t=="number"?this._payload={...this._payload,nbf:$i("setNotBefore",t)}:t instanceof Date?this._payload={...this._payload,nbf:$i("setNotBefore",(0,Vi.default)(t))}:this._payload={...this._payload,nbf:(0,Vi.default)(new Date)+(0,$m.default)(t)},this}setExpirationTime(t){return typeof t=="number"?this._payload={...this._payload,exp:$i("setExpirationTime",t)}:t instanceof Date?this._payload={...this._payload,exp:$i("setExpirationTime",(0,Vi.default)(t))}:this._payload={...this._payload,exp:(0,Vi.default)(new Date)+(0,$m.default)(t)},this}setIssuedAt(t){return typeof t>"u"?this._payload={...this._payload,iat:(0,Vi.default)(new Date)}:t instanceof Date?this._payload={...this._payload,iat:$i("setIssuedAt",(0,Vi.default)(t))}:typeof t=="string"?this._payload={...this._payload,iat:$i("setIssuedAt",(0,Vi.default)(new Date)+(0,$m.default)(t))}:this._payload={...this._payload,iat:$i("setIssuedAt",t)},this}};yl.ProduceJWT=Wm});var YA=y(wl=>{"use strict";Object.defineProperty(wl,"__esModule",{value:!0});wl.SignJWT=void 0;var GL=Km(),YL=B(),zL=Ae(),XL=_l(),Fm=class extends XL.ProduceJWT{_protectedHeader;setProtectedHeader(t){return this._protectedHeader=t,this}async sign(t,n){let r=new GL.CompactSign(zL.encoder.encode(JSON.stringify(this._payload)));if(r.setProtectedHeader(this._protectedHeader),Array.isArray(this._protectedHeader?.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new YL.JWTInvalid("JWTs MUST NOT use unencoded payload");return r.sign(t,n)}};wl.SignJWT=Fm});var zA=y(El=>{"use strict";Object.defineProperty(El,"__esModule",{value:!0});El.EncryptJWT=void 0;var ZL=Jm(),QL=Ae(),eJ=_l(),Bm=class extends eJ.ProduceJWT{_cek;_iv;_keyManagementParameters;_protectedHeader;_replicateIssuerAsHeader;_replicateSubjectAsHeader;_replicateAudienceAsHeader;setProtectedHeader(t){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=t,this}setKeyManagementParameters(t){if(this._keyManagementParameters)throw new TypeError("setKeyManagementParameters can only be called once");return this._keyManagementParameters=t,this}setContentEncryptionKey(t){if(this._cek)throw new TypeError("setContentEncryptionKey can only be called once");return this._cek=t,this}setInitializationVector(t){if(this._iv)throw new TypeError("setInitializationVector can only be called once");return this._iv=t,this}replicateIssuerAsHeader(){return this._replicateIssuerAsHeader=!0,this}replicateSubjectAsHeader(){return this._replicateSubjectAsHeader=!0,this}replicateAudienceAsHeader(){return this._replicateAudienceAsHeader=!0,this}async encrypt(t,n){let r=new ZL.CompactEncrypt(QL.encoder.encode(JSON.stringify(this._payload)));return this._replicateIssuerAsHeader&&(this._protectedHeader={...this._protectedHeader,iss:this._payload.iss}),this._replicateSubjectAsHeader&&(this._protectedHeader={...this._protectedHeader,sub:this._payload.sub}),this._replicateAudienceAsHeader&&(this._protectedHeader={...this._protectedHeader,aud:this._payload.aud}),r.setProtectedHeader(this._protectedHeader),this._iv&&r.setInitializationVector(this._iv),this._cek&&r.setContentEncryptionKey(this._cek),this._keyManagementParameters&&r.setKeyManagementParameters(this._keyManagementParameters),r.encrypt(t,n)}};El.EncryptJWT=Bm});var QA=y(vl=>{"use strict";Object.defineProperty(vl,"__esModule",{value:!0});vl.calculateJwkThumbprint=ZA;vl.calculateJwkThumbprintUri=oJ;var tJ=$p(),nJ=Ze(),XA=B(),rJ=Ae(),iJ=$e(),Vr=(e,t)=>{if(typeof e!="string"||!e)throw new XA.JWKInvalid(`${t} missing or invalid`)};async function ZA(e,t){if(!(0,iJ.default)(e))throw new TypeError("JWK must be an object");if(t??="sha256",t!=="sha256"&&t!=="sha384"&&t!=="sha512")throw new TypeError('digestAlgorithm must one of "sha256", "sha384", or "sha512"');let n;switch(e.kty){case"EC":Vr(e.crv,'"crv" (Curve) Parameter'),Vr(e.x,'"x" (X Coordinate) Parameter'),Vr(e.y,'"y" (Y Coordinate) Parameter'),n={crv:e.crv,kty:e.kty,x:e.x,y:e.y};break;case"OKP":Vr(e.crv,'"crv" (Subtype of Key Pair) Parameter'),Vr(e.x,'"x" (Public Key) Parameter'),n={crv:e.crv,kty:e.kty,x:e.x};break;case"RSA":Vr(e.e,'"e" (Exponent) Parameter'),Vr(e.n,'"n" (Modulus) Parameter'),n={e:e.e,kty:e.kty,n:e.n};break;case"oct":Vr(e.k,'"k" (Key Value) Parameter'),n={k:e.k,kty:e.kty};break;default:throw new XA.JOSENotSupported('"kty" (Key Type) Parameter missing or unsupported')}let r=rJ.encoder.encode(JSON.stringify(n));return(0,nJ.encode)(await(0,tJ.default)(t,r))}async function oJ(e,t){t??="sha256";let n=await ZA(e,t);return`urn:ietf:params:oauth:jwk-thumbprint:sha-${t.slice(-3)}:${n}`}});var tS=y(Gm=>{"use strict";Object.defineProperty(Gm,"__esModule",{value:!0});Gm.EmbeddedJWK=cJ;var aJ=ra(),sJ=$e(),eS=B();async function cJ(e,t){let n={...e,...t?.header};if(!(0,sJ.default)(n.jwk))throw new eS.JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a JSON object');let r=await(0,aJ.importJWK)({...n.jwk,ext:!0},n.alg);if(r instanceof Uint8Array||r.type!=="public")throw new eS.JWSInvalid('"jwk" (JSON Web Key) Header Parameter must be a public key');return r}});var Xm=y(zm=>{"use strict";Object.defineProperty(zm,"__esModule",{value:!0});zm.createLocalJWKSet=hJ;var dJ=ra(),Us=B(),lJ=$e();function uJ(e){switch(typeof e=="string"&&e.slice(0,2)){case"RS":case"PS":return"RSA";case"ES":return"EC";case"Ed":return"OKP";default:throw new Us.JOSENotSupported('Unsupported "alg" value for a JSON Web Key Set')}}function fJ(e){return e&&typeof e=="object"&&Array.isArray(e.keys)&&e.keys.every(pJ)}function pJ(e){return(0,lJ.default)(e)}function rS(e){return typeof structuredClone=="function"?structuredClone(e):JSON.parse(JSON.stringify(e))}var Ym=class{_jwks;_cached=new WeakMap;constructor(t){if(!fJ(t))throw new Us.JWKSInvalid("JSON Web Key Set malformed");this._jwks=rS(t)}async getKey(t,n){let{alg:r,kid:i}={...t,...n?.header},o=uJ(r),a=this._jwks.keys.filter(d=>{let l=o===d.kty;if(l&&typeof i=="string"&&(l=i===d.kid),l&&typeof d.alg=="string"&&(l=r===d.alg),l&&typeof d.use=="string"&&(l=d.use==="sig"),l&&Array.isArray(d.key_ops)&&(l=d.key_ops.includes("verify")),l)switch(r){case"ES256":l=d.crv==="P-256";break;case"ES256K":l=d.crv==="secp256k1";break;case"ES384":l=d.crv==="P-384";break;case"ES512":l=d.crv==="P-521";break;case"Ed25519":l=d.crv==="Ed25519";break;case"EdDSA":l=d.crv==="Ed25519"||d.crv==="Ed448";break}return l}),{0:s,length:c}=a;if(c===0)throw new Us.JWKSNoMatchingKey;if(c!==1){let d=new Us.JWKSMultipleMatchingKeys,{_cached:l}=this;throw d[Symbol.asyncIterator]=async function*(){for(let u of a)try{yield await nS(l,u,r)}catch{}},d}return nS(this._cached,s,r)}};async function nS(e,t,n){let r=e.get(t)||e.set(t,{}).get(t);if(r[n]===void 0){let i=await(0,dJ.importJWK)({...t,ext:!0},n);if(i instanceof Uint8Array||i.type!=="public")throw new Us.JWKSInvalid("JSON Web Key Set members must be public keys");r[n]=i}return r[n]}function hJ(e){let t=new Ym(e),n=async(r,i)=>t.getKey(r,i);return Object.defineProperties(n,{jwks:{value:()=>rS(t._jwks),enumerable:!0,configurable:!1,writable:!1}}),n}});var aS=y(Qm=>{"use strict";Object.defineProperty(Qm,"__esModule",{value:!0});var mJ=require("node:http"),gJ=require("node:https"),iS=require("node:events"),Zm=B(),oS=Ae(),yJ=async(e,t,n)=>{let r;switch(e.protocol){case"https:":r=gJ.get;break;case"http:":r=mJ.get;break;default:throw new TypeError("Unsupported URL protocol.")}let{agent:i,headers:o}=n,a=r(e.href,{agent:i,timeout:t,headers:o}),[s]=await Promise.race([(0,iS.once)(a,"response"),(0,iS.once)(a,"timeout")]);if(!s)throw a.destroy(),new Zm.JWKSTimeout;if(s.statusCode!==200)throw new Zm.JOSEError("Expected 200 OK from the JSON Web Key Set HTTP response");let c=[];for await(let d of s)c.push(d);try{return JSON.parse(oS.decoder.decode((0,oS.concat)(...c)))}catch{throw new Zm.JOSEError("Failed to parse the JSON Web Key Set HTTP response as JSON")}};Qm.default=yJ});var dS=y(Gt=>{"use strict";Object.defineProperty(Gt,"__esModule",{value:!0});Gt.experimental_jwksCache=Gt.jwksCache=void 0;Gt.createRemoteJWKSet=bJ;var _J=aS(),wJ=B(),sS=Xm(),cS=$e();function EJ(){return typeof WebSocketPair<"u"||typeof navigator<"u"&&navigator.userAgent==="Cloudflare-Workers"||typeof EdgeRuntime<"u"&&EdgeRuntime==="vercel"}var eg;(typeof navigator>"u"||!navigator.userAgent?.startsWith?.("Mozilla/5.0 "))&&(eg="jose/v5.10.0");Gt.jwksCache=Symbol();function vJ(e,t){return!(typeof e!="object"||e===null||!("uat"in e)||typeof e.uat!="number"||Date.now()-e.uat>=t||!("jwks"in e)||!(0,cS.default)(e.jwks)||!Array.isArray(e.jwks.keys)||!Array.prototype.every.call(e.jwks.keys,cS.default))}var tg=class{_url;_timeoutDuration;_cooldownDuration;_cacheMaxAge;_jwksTimestamp;_pendingFetch;_options;_local;_cache;constructor(t,n){if(!(t instanceof URL))throw new TypeError("url must be an instance of URL");this._url=new URL(t.href),this._options={agent:n?.agent,headers:n?.headers},this._timeoutDuration=typeof n?.timeoutDuration=="number"?n?.timeoutDuration:5e3,this._cooldownDuration=typeof n?.cooldownDuration=="number"?n?.cooldownDuration:3e4,this._cacheMaxAge=typeof n?.cacheMaxAge=="number"?n?.cacheMaxAge:6e5,n?.[Gt.jwksCache]!==void 0&&(this._cache=n?.[Gt.jwksCache],vJ(n?.[Gt.jwksCache],this._cacheMaxAge)&&(this._jwksTimestamp=this._cache.uat,this._local=(0,sS.createLocalJWKSet)(this._cache.jwks)))}coolingDown(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cooldownDuration:!1}fresh(){return typeof this._jwksTimestamp=="number"?Date.now()<this._jwksTimestamp+this._cacheMaxAge:!1}async getKey(t,n){(!this._local||!this.fresh())&&await this.reload();try{return await this._local(t,n)}catch(r){if(r instanceof wJ.JWKSNoMatchingKey&&this.coolingDown()===!1)return await this.reload(),this._local(t,n);throw r}}async reload(){this._pendingFetch&&EJ()&&(this._pendingFetch=void 0);let t=new Headers(this._options.headers);eg&&!t.has("User-Agent")&&(t.set("User-Agent",eg),this._options.headers=Object.fromEntries(t.entries())),this._pendingFetch||=(0,_J.default)(this._url,this._timeoutDuration,this._options).then(n=>{this._local=(0,sS.createLocalJWKSet)(n),this._cache&&(this._cache.uat=Date.now(),this._cache.jwks=n),this._jwksTimestamp=Date.now(),this._pendingFetch=void 0}).catch(n=>{throw this._pendingFetch=void 0,n}),await this._pendingFetch}};function bJ(e,t){let n=new tg(e,t),r=async(i,o)=>n.getKey(i,o);return Object.defineProperties(r,{coolingDown:{get:()=>n.coolingDown(),enumerable:!0,configurable:!1},fresh:{get:()=>n.fresh(),enumerable:!0,configurable:!1},reload:{value:()=>n.reload(),enumerable:!0,configurable:!1,writable:!1},reloading:{get:()=>!!n._pendingFetch,enumerable:!0,configurable:!1},jwks:{value:()=>n._local?.jwks(),enumerable:!0,configurable:!1,writable:!1}}),r}Gt.experimental_jwksCache=Gt.jwksCache});var lS=y(Al=>{"use strict";Object.defineProperty(Al,"__esModule",{value:!0});Al.UnsecuredJWT=void 0;var bl=Ze(),AJ=Ae(),ng=B(),SJ=ul(),IJ=_l(),rg=class extends IJ.ProduceJWT{encode(){let t=bl.encode(JSON.stringify({alg:"none"})),n=bl.encode(JSON.stringify(this._payload));return`${t}.${n}.`}static decode(t,n){if(typeof t!="string")throw new ng.JWTInvalid("Unsecured JWT must be a string");let{0:r,1:i,2:o,length:a}=t.split(".");if(a!==3||o!=="")throw new ng.JWTInvalid("Invalid Unsecured JWT");let s;try{if(s=JSON.parse(AJ.decoder.decode(bl.decode(r))),s.alg!=="none")throw new Error}catch{throw new ng.JWTInvalid("Invalid Unsecured JWT")}return{payload:(0,SJ.default)(s,bl.decode(i),n),header:s}}};Al.UnsecuredJWT=rg});var Sl=y(fa=>{"use strict";Object.defineProperty(fa,"__esModule",{value:!0});fa.decode=fa.encode=void 0;var uS=Ze();fa.encode=uS.encode;fa.decode=uS.decode});var fS=y(ig=>{"use strict";Object.defineProperty(ig,"__esModule",{value:!0});ig.decodeProtectedHeader=CJ;var TJ=Sl(),PJ=Ae(),kJ=$e();function CJ(e){let t;if(typeof e=="string"){let n=e.split(".");(n.length===3||n.length===5)&&([t]=n)}else if(typeof e=="object"&&e)if("protected"in e)t=e.protected;else throw new TypeError("Token does not contain a Protected Header");try{if(typeof t!="string"||!t)throw new Error;let n=JSON.parse(PJ.decoder.decode((0,TJ.decode)(t)));if(!(0,kJ.default)(n))throw new Error;return n}catch{throw new TypeError("Invalid Token or Protected Header formatting")}}});var pS=y(og=>{"use strict";Object.defineProperty(og,"__esModule",{value:!0});og.decodeJwt=NJ;var RJ=Sl(),xJ=Ae(),OJ=$e(),Wi=B();function NJ(e){if(typeof e!="string")throw new Wi.JWTInvalid("JWTs must use Compact JWS serialization, JWT must be a string");let{1:t,length:n}=e.split(".");if(n===5)throw new Wi.JWTInvalid("Only JWTs using Compact JWS serialization can be decoded");if(n!==3)throw new Wi.JWTInvalid("Invalid JWT");if(!t)throw new Wi.JWTInvalid("JWTs must contain a payload");let r;try{r=(0,RJ.decode)(t)}catch{throw new Wi.JWTInvalid("Failed to base64url decode the payload")}let i;try{i=JSON.parse(xJ.decoder.decode(r))}catch{throw new Wi.JWTInvalid("Failed to parse the decoded payload as JSON")}if(!(0,OJ.default)(i))throw new Wi.JWTInvalid("Invalid JWT Claims Set");return i}});var ag=y(Il=>{"use strict";Object.defineProperty(Il,"__esModule",{value:!0});Il.generateSecret=LJ;Il.generateKeyPair=JJ;var hS=require("node:crypto"),DJ=require("node:util"),MJ=As(),js=B(),Yt=(0,DJ.promisify)(hS.generateKeyPair);async function LJ(e,t){let n;switch(e){case"HS256":case"HS384":case"HS512":case"A128CBC-HS256":case"A192CBC-HS384":case"A256CBC-HS512":n=parseInt(e.slice(-3),10);break;case"A128KW":case"A192KW":case"A256KW":case"A128GCMKW":case"A192GCMKW":case"A256GCMKW":case"A128GCM":case"A192GCM":case"A256GCM":n=parseInt(e.slice(1,4),10);break;default:throw new js.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}return(0,hS.createSecretKey)((0,MJ.default)(new Uint8Array(n>>3)))}async function JJ(e,t){switch(e){case"RS256":case"RS384":case"RS512":case"PS256":case"PS384":case"PS512":case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":case"RSA1_5":{let n=t?.modulusLength??2048;if(typeof n!="number"||n<2048)throw new js.JOSENotSupported("Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used");return await Yt("rsa",{modulusLength:n,publicExponent:65537})}case"ES256":return Yt("ec",{namedCurve:"P-256"});case"ES256K":return Yt("ec",{namedCurve:"secp256k1"});case"ES384":return Yt("ec",{namedCurve:"P-384"});case"ES512":return Yt("ec",{namedCurve:"P-521"});case"Ed25519":return Yt("ed25519");case"EdDSA":switch(t?.crv){case void 0:case"Ed25519":return Yt("ed25519");case"Ed448":return Yt("ed448");default:throw new js.JOSENotSupported("Invalid or unsupported crv option provided, supported values are Ed25519 and Ed448")}case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":{let n=t?.crv??"P-256";switch(n){case void 0:case"P-256":case"P-384":case"P-521":return Yt("ec",{namedCurve:n});case"X25519":return Yt("x25519");case"X448":return Yt("x448");default:throw new js.JOSENotSupported("Invalid or unsupported crv option provided, supported values are P-256, P-384, P-521, X25519, and X448")}}default:throw new js.JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}}});var mS=y(sg=>{"use strict";Object.defineProperty(sg,"__esModule",{value:!0});sg.generateKeyPair=jJ;var UJ=ag();async function jJ(e,t){return(0,UJ.generateKeyPair)(e,t)}});var gS=y(cg=>{"use strict";Object.defineProperty(cg,"__esModule",{value:!0});cg.generateSecret=KJ;var qJ=ag();async function KJ(e,t){return(0,qJ.generateSecret)(e,t)}});var yS=y(dg=>{"use strict";Object.defineProperty(dg,"__esModule",{value:!0});dg.default="node:crypto"});var _S=y(lg=>{"use strict";Object.defineProperty(lg,"__esModule",{value:!0});var HJ=yS();lg.default=HJ.default});var pg=y(T=>{"use strict";Object.defineProperty(T,"__esModule",{value:!0});T.cryptoRuntime=T.base64url=T.generateSecret=T.generateKeyPair=T.errors=T.decodeJwt=T.decodeProtectedHeader=T.importJWK=T.importX509=T.importPKCS8=T.importSPKI=T.exportJWK=T.exportSPKI=T.exportPKCS8=T.UnsecuredJWT=T.experimental_jwksCache=T.jwksCache=T.createRemoteJWKSet=T.createLocalJWKSet=T.EmbeddedJWK=T.calculateJwkThumbprintUri=T.calculateJwkThumbprint=T.EncryptJWT=T.SignJWT=T.GeneralSign=T.FlattenedSign=T.CompactSign=T.FlattenedEncrypt=T.CompactEncrypt=T.jwtDecrypt=T.jwtVerify=T.generalVerify=T.flattenedVerify=T.compactVerify=T.GeneralEncrypt=T.generalDecrypt=T.flattenedDecrypt=T.compactDecrypt=void 0;var VJ=Qh();Object.defineProperty(T,"compactDecrypt",{enumerable:!0,get:function(){return VJ.compactDecrypt}});var $J=rl();Object.defineProperty(T,"flattenedDecrypt",{enumerable:!0,get:function(){return $J.flattenedDecrypt}});var WJ=bA();Object.defineProperty(T,"generalDecrypt",{enumerable:!0,get:function(){return WJ.generalDecrypt}});var FJ=kA();Object.defineProperty(T,"GeneralEncrypt",{enumerable:!0,get:function(){return FJ.GeneralEncrypt}});var BJ=Sm();Object.defineProperty(T,"compactVerify",{enumerable:!0,get:function(){return BJ.compactVerify}});var GJ=ll();Object.defineProperty(T,"flattenedVerify",{enumerable:!0,get:function(){return GJ.flattenedVerify}});var YJ=qA();Object.defineProperty(T,"generalVerify",{enumerable:!0,get:function(){return YJ.generalVerify}});var zJ=WA();Object.defineProperty(T,"jwtVerify",{enumerable:!0,get:function(){return zJ.jwtVerify}});var XJ=FA();Object.defineProperty(T,"jwtDecrypt",{enumerable:!0,get:function(){return XJ.jwtDecrypt}});var ZJ=Jm();Object.defineProperty(T,"CompactEncrypt",{enumerable:!0,get:function(){return ZJ.CompactEncrypt}});var QJ=sl();Object.defineProperty(T,"FlattenedEncrypt",{enumerable:!0,get:function(){return QJ.FlattenedEncrypt}});var eU=Km();Object.defineProperty(T,"CompactSign",{enumerable:!0,get:function(){return eU.CompactSign}});var tU=hl();Object.defineProperty(T,"FlattenedSign",{enumerable:!0,get:function(){return tU.FlattenedSign}});var nU=GA();Object.defineProperty(T,"GeneralSign",{enumerable:!0,get:function(){return nU.GeneralSign}});var rU=YA();Object.defineProperty(T,"SignJWT",{enumerable:!0,get:function(){return rU.SignJWT}});var iU=zA();Object.defineProperty(T,"EncryptJWT",{enumerable:!0,get:function(){return iU.EncryptJWT}});var wS=QA();Object.defineProperty(T,"calculateJwkThumbprint",{enumerable:!0,get:function(){return wS.calculateJwkThumbprint}});Object.defineProperty(T,"calculateJwkThumbprintUri",{enumerable:!0,get:function(){return wS.calculateJwkThumbprintUri}});var oU=tS();Object.defineProperty(T,"EmbeddedJWK",{enumerable:!0,get:function(){return oU.EmbeddedJWK}});var aU=Xm();Object.defineProperty(T,"createLocalJWKSet",{enumerable:!0,get:function(){return aU.createLocalJWKSet}});var ug=dS();Object.defineProperty(T,"createRemoteJWKSet",{enumerable:!0,get:function(){return ug.createRemoteJWKSet}});Object.defineProperty(T,"jwksCache",{enumerable:!0,get:function(){return ug.jwksCache}});Object.defineProperty(T,"experimental_jwksCache",{enumerable:!0,get:function(){return ug.experimental_jwksCache}});var sU=lS();Object.defineProperty(T,"UnsecuredJWT",{enumerable:!0,get:function(){return sU.UnsecuredJWT}});var fg=rm();Object.defineProperty(T,"exportPKCS8",{enumerable:!0,get:function(){return fg.exportPKCS8}});Object.defineProperty(T,"exportSPKI",{enumerable:!0,get:function(){return fg.exportSPKI}});Object.defineProperty(T,"exportJWK",{enumerable:!0,get:function(){return fg.exportJWK}});var Tl=ra();Object.defineProperty(T,"importSPKI",{enumerable:!0,get:function(){return Tl.importSPKI}});Object.defineProperty(T,"importPKCS8",{enumerable:!0,get:function(){return Tl.importPKCS8}});Object.defineProperty(T,"importX509",{enumerable:!0,get:function(){return Tl.importX509}});Object.defineProperty(T,"importJWK",{enumerable:!0,get:function(){return Tl.importJWK}});var cU=fS();Object.defineProperty(T,"decodeProtectedHeader",{enumerable:!0,get:function(){return cU.decodeProtectedHeader}});var dU=pS();Object.defineProperty(T,"decodeJwt",{enumerable:!0,get:function(){return dU.decodeJwt}});T.errors=B();var lU=mS();Object.defineProperty(T,"generateKeyPair",{enumerable:!0,get:function(){return lU.generateKeyPair}});var uU=gS();Object.defineProperty(T,"generateSecret",{enumerable:!0,get:function(){return uU.generateSecret}});T.base64url=Sl();var fU=_S();Object.defineProperty(T,"cryptoRuntime",{enumerable:!0,get:function(){return fU.default}})});var qs=y(pa=>{"use strict";Object.defineProperty(pa,"__esModule",{value:!0});pa.signJwt=pU;pa.decodeJwt=vS;pa.verifyJwtSignature=hU;pa.temporalReason=mU;var Pl=pg();async function pU(e,t,n){let r=await(0,Pl.importJWK)({...e},"EdDSA");return new Pl.SignJWT(n).setProtectedHeader({alg:"EdDSA",kid:t.kid,typ:t.typ}).sign(r)}function ES(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function vS(e){let t=e.split(".");if(t.length!==3)return null;try{let n=JSON.parse(Buffer.from(t[0],"base64url").toString("utf8")),r=JSON.parse(Buffer.from(t[1],"base64url").toString("utf8"));return!ES(n)||!ES(r)?null:{header:n,claims:r}}catch{return null}}async function hU(e,t,n,r=!1){let i=vS(e);if(!i)return{ok:!1,reason:"malformed"};if(i.header.alg!=="EdDSA")return{ok:!1,reason:"bad_alg"};let o=t.keys.find(a=>a.kid===i.header.kid);if(!o)return{ok:!1,reason:"unknown_kid"};if(n!==void 0){if(o.role===void 0){if(r)return{ok:!1,reason:"role_required"}}else if(o.role!==n)return{ok:!1,reason:"role_mismatch"}}try{let a=await(0,Pl.importJWK)({...o},"EdDSA");await(0,Pl.compactVerify)(e,a)}catch{return{ok:!1,reason:"bad_signature"}}return{ok:!0,header:i.header,claims:i.claims}}function mU(e,t){return Number.isFinite(t)?typeof e.iat!="number"||typeof e.exp!="number"?"bad_temporal_claims":e.iat>t?"not_yet_valid":t>=e.exp?"expired":null:"bad_verification_time"}});var kl=y(zt=>{"use strict";var gU=zt&&zt.__createBinding||(Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]})),yU=zt&&zt.__exportStar||function(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&gU(t,e,n)};Object.defineProperty(zt,"__esModule",{value:!0});zt.completeRuntimeCertificate=AS;zt.issueRuntimeCertificate=EU;zt.peekRuntimeCertificate=AU;zt.verifyRuntimeCertificate=SU;var bS=qi(),hg=qs(),_U=Uo();yU(os(),zt);var zn=os(),wU=new Set(zn.RUNTIME_CERTIFICATE_PURPOSES),Ks=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;function AS(e,t){return(0,_U.completeRootSignedJws)(e.signingInput,t,"runtime certificate")}async function EU(e){let t=(0,zn.prepareRuntimeCertificate)({rootKid:e.signer.kid,rootPublicJwk:e.signer.publicJwk,rootJkt:e.rootJkt,agentId:e.agentId,runtimeId:e.runtimeId,runtimePublicJwk:e.runtimePublicJwk,purposes:e.purposes,...e.ttlSeconds===void 0?{}:{ttlSeconds:e.ttlSeconds},...e.nowSec===void 0?{}:{nowSec:e.nowSec},...e.certificateId===void 0?{}:{certificateId:e.certificateId}}),n=await e.signer.sign(new TextEncoder().encode(t.signingInput));return AS(t,n)}function vU(e){if(typeof e!="object"||e===null||Array.isArray(e))return!1;let t=e;return Object.keys(t).length===3&&t.kty==="OKP"&&t.crv==="Ed25519"&&(0,zn.isCanonicalBase64Url32)(t.x)}function bU(e){return Array.isArray(e)&&e.length>0&&e.every(t=>typeof t=="string"?wU.has(t):!1)&&new Set(e).size===e.length&&[...e].sort().every((t,n)=>t===e[n])}function AU(e){let t=(0,hg.decodeJwt)(e);return!t||t.header.typ!==zn.RUNTIME_CERTIFICATE_TYP||typeof t.claims.sub!="string"||!Ks.test(t.claims.sub)||typeof t.claims.iss!="string"||!(0,zn.isCanonicalBase64Url32)(t.claims.iss)||typeof t.claims.runtimeId!="string"||!Ks.test(t.claims.runtimeId)||typeof t.claims.jti!="string"||!Ks.test(t.claims.jti)?null:{agentId:t.claims.sub,rootJkt:t.claims.iss,runtimeId:t.claims.runtimeId,certificateId:t.claims.jti}}async function SU(e,t){if(!Number.isSafeInteger(t.nowSec)||t.nowSec<0)return{ok:!1,reason:"bad_verification_time"};let n=await(0,hg.verifyJwtSignature)(e,t.jwks);if(!n.ok)return n;if(n.header.typ!==zn.RUNTIME_CERTIFICATE_TYP)return{ok:!1,reason:"typ_mismatch"};let r=n.claims;if(r.v!==zn.RUNTIME_CERTIFICATE_VERSION||r.iss!==t.expectedRootJkt||r.sub!==t.expectedAgentId||typeof r.jti!="string"||!Ks.test(r.jti)||typeof r.runtimeId!="string"||!Ks.test(r.runtimeId))return{ok:!1,reason:"claims_mismatch"};if(n.header.kid===void 0)return{ok:!1,reason:"kid_missing"};let i=t.jwks.keys.find(s=>s.kid===n.header.kid);if(!i||(0,bS.computeJkt)(i)!==t.expectedRootJkt)return{ok:!1,reason:"root_key_mismatch"};if(t.expectedRuntimeId!==void 0&&r.runtimeId!==t.expectedRuntimeId)return{ok:!1,reason:"runtime_mismatch"};if(t.expectedCertificateId!==void 0&&r.jti!==t.expectedCertificateId)return{ok:!1,reason:"certificate_mismatch"};if(!r.cnf||!vU(r.cnf.jwk)||!(0,zn.isCanonicalBase64Url32)(r.cnf.jkt))return{ok:!1,reason:"bad_cnf_key"};let o=(0,bS.computeJkt)(r.cnf.jwk);if(r.cnf.jkt!==o||o!==t.expectedRuntimeJkt)return{ok:!1,reason:"runtime_key_mismatch"};if(!bU(r.purposes)||!r.purposes.includes(t.requiredPurpose))return{ok:!1,reason:"purpose_denied"};let a=(0,hg.temporalReason)(r,t.nowSec);return a?{ok:!1,reason:a}:typeof r.nbf!="number"||!Number.isSafeInteger(r.nbf)||r.nbf>t.nowSec||r.nbf!==r.iat?{ok:!1,reason:"not_yet_valid"}:typeof r.iat!="number"||typeof r.exp!="number"||!Number.isSafeInteger(r.iat)||!Number.isSafeInteger(r.exp)||r.exp-r.iat>(0,zn.runtimeCertificateMaxTtl)(r.purposes)?{ok:!1,reason:"ttl_exceeded"}:{ok:!0,claims:r,rootJkt:t.expectedRootJkt,runtimeJkt:o}}});var vg=y(k=>{"use strict";Object.defineProperty(k,"__esModule",{value:!0});k.TEMPO_LEASE_SIGNING_MODE=k.TEMPO_LEASE_NETWORK=k.TEMPO_LEASE_PURPOSE=k.RUNTIME_LEASE_PURPOSE=k.RUNTIME_LEASE_AUDIENCE=k.RUNTIME_LEASE_VERSION=k.RUNTIME_LEASE_TYP=k.RUNTIME_DELEGATION_RAILS=k.RUNTIME_CUSTODIES=k.RUNTIME_DELEGATION_LEGACY_VERSION=k.RUNTIME_DELEGATION_VERSION=k.RUNTIME_AUTHORITY_CLOCK_SKEW_SECONDS=k.RUNTIME_LEASE_MAX_TTL_SECONDS=k.RUNTIME_DELEGATION_MAX_TTL_SECONDS=k.RUNTIME_LEASE_SIGNING_MODES=k.RUNTIME_DELEGATION_TYP=void 0;k.runtimeDelegationScope=Ws;k.prepareRuntimeDelegation=TS;k.completeRuntimeDelegation=PS;k.issueRuntimeDelegation=kU;k.issueRuntimeLease=CU;k.issueTempoRuntimeLease=RU;k.verifyRuntimeDelegation=Fs;k.verifyRuntimeLeaseChain=NU;k.verifyTempoRuntimeLeaseChain=DU;var mg=require("node:crypto"),Vs=qi(),gg=qs(),Hs=Uo(),$s=ss();Object.defineProperty(k,"RUNTIME_DELEGATION_TYP",{enumerable:!0,get:function(){return $s.RUNTIME_DELEGATION_TYP}});Object.defineProperty(k,"RUNTIME_LEASE_SIGNING_MODES",{enumerable:!0,get:function(){return $s.RUNTIME_LEASE_SIGNING_MODES}});Object.defineProperty(k,"RUNTIME_DELEGATION_MAX_TTL_SECONDS",{enumerable:!0,get:function(){return $s.RUNTIME_DELEGATION_MAX_TTL_SECONDS}});Object.defineProperty(k,"RUNTIME_LEASE_MAX_TTL_SECONDS",{enumerable:!0,get:function(){return $s.RUNTIME_LEASE_MAX_TTL_SECONDS}});Object.defineProperty(k,"RUNTIME_AUTHORITY_CLOCK_SKEW_SECONDS",{enumerable:!0,get:function(){return $s.RUNTIME_AUTHORITY_CLOCK_SKEW_SECONDS}});var xe=ss();k.RUNTIME_DELEGATION_VERSION=2;k.RUNTIME_DELEGATION_LEGACY_VERSION=1;k.RUNTIME_CUSTODIES=["device","gate"];k.RUNTIME_DELEGATION_RAILS=["tempo","x402"];k.RUNTIME_LEASE_TYP="visa-agent-runtime-lease+jwt";k.RUNTIME_LEASE_VERSION=1;k.RUNTIME_LEASE_AUDIENCE="urn:visa:tvc:slipgate";k.RUNTIME_LEASE_PURPOSE="wallet:x402";k.TEMPO_LEASE_PURPOSE="wallet:tempo";k.TEMPO_LEASE_NETWORK="eip155:4217";k.TEMPO_LEASE_SIGNING_MODE="tempo:access-key";var Xn=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,IU=/^[A-Za-z0-9_-]{43}$/,yg=/^eip155:[1-9][0-9]{0,15}$/,Fi=/^[A-Za-z0-9._:@/-]{1,256}$/,Cl=new Map(xe.RUNTIME_LEASE_SIGNING_MODES.map((e,t)=>[e,t]));function ft(e){if(typeof e!="string"||!IU.test(e))return!1;let t=Buffer.from(e,"base64url");return t.length===32&&t.toString("base64url")===e}function TU(e){let t=e.toLowerCase();if(!yg.test(t))throw new Error("runtime authority network is invalid");return t}function $r(e,t){if(!Xn.test(t))throw new Error(`${e} must be a canonical UUID`)}function SS(e,t){if(!Fi.test(t))throw new Error(`${e} must be a bounded identifier`)}function Rl(e,t){if(!Number.isSafeInteger(t)||t<0)throw new Error(`${e} must be a non-negative unix-seconds integer`)}function xl(e){if(!Array.isArray(e)||e.length===0)throw new Error("runtime authority requires at least one signing mode");let t=[...new Set(e)];if(t.length!==e.length||t.some(n=>!Cl.has(n)))throw new Error("runtime authority signing modes must be unique supported values");return t.sort((n,r)=>Cl.get(n)-Cl.get(r))}function Ol(e,t){let n=Object.keys(e).sort(),r=[...t].sort();return n.length===r.length&&n.every((i,o)=>i===r[o])}function IS(e){if(!Array.isArray(e)||e.length===0||e.some(n=>typeof n!="string"||!Cl.has(n)))return!1;let t=e;return new Set(t).size===t.length&&xl(t).every((n,r)=>n===t[r])}function Ws(e){let t="custody"in e,n="rails"in e;if(e.v===k.RUNTIME_DELEGATION_LEGACY_VERSION)return t||n?null:{custody:null,tempo:!1};if(e.v!==k.RUNTIME_DELEGATION_VERSION||!t||!n)return null;let{custody:r,rails:i}=e;return!k.RUNTIME_CUSTODIES.includes(r)||!Array.isArray(i)||!PU(i)||r==="gate"&&!(i.length===1&&i[0]==="x402")?null:{custody:r,tempo:i.includes("tempo")}}function PU(e){let t=e.map(n=>k.RUNTIME_DELEGATION_RAILS.indexOf(n));return t.length>0&&t.every((n,r)=>n>=0&&(r===0||n>t[r-1]))&&e.includes("x402")}function TS(e){let t=e.nowSec??Math.floor(Date.now()/1e3),n=e.ttlSeconds??xe.RUNTIME_DELEGATION_MAX_TTL_SECONDS,r=e.maxLeaseTtlSeconds??xe.RUNTIME_LEASE_MAX_TTL_SECONDS,i=e.delegationId??(0,mg.randomUUID)();if(Rl("nowSec",t),!Number.isSafeInteger(n)||n<=0||n>xe.RUNTIME_DELEGATION_MAX_TTL_SECONDS)throw new Error(`runtime delegation ttlSeconds must be in (0, ${xe.RUNTIME_DELEGATION_MAX_TTL_SECONDS}]`);if(!Number.isSafeInteger(r)||r<=0||r>xe.RUNTIME_LEASE_MAX_TTL_SECONDS)throw new Error(`runtime delegation maxLeaseTtlSeconds must be in (0, ${xe.RUNTIME_LEASE_MAX_TTL_SECONDS}]`);if($r("agentId",e.agentId),$r("runtimeId",e.runtimeId),$r("delegationId",i),SS("rootKid",e.rootKid),!ft(e.rootJkt)||(0,Vs.computeJkt)(e.rootPublicJwk)!==e.rootJkt)throw new Error("runtime delegation root public key does not match rootJkt");if(!ft(e.runtimeJkt)||!ft(e.leaseIssuerJkt))throw new Error("runtime delegation runtime/issuer JKT is invalid");if(new Set([e.rootJkt,e.runtimeJkt,e.leaseIssuerJkt]).size!==3)throw new Error("runtime delegation root, runtime, and issuer keys must be distinct");let o=e.custody!==null;if(!o&&e.rails!==void 0)throw new Error("an unmarked (v1) runtime delegation carries no rails");let a=[...e.rails??["x402"]];if(o&&Ws({v:k.RUNTIME_DELEGATION_VERSION,custody:e.custody,rails:a})===null)throw new Error("runtime delegation custody must be device or gate, with sorted rails including x402 (tempo only for device)");let s=t+n;Rl("runtime delegation expiration",s);let c={v:o?k.RUNTIME_DELEGATION_VERSION:k.RUNTIME_DELEGATION_LEGACY_VERSION,iss:e.rootJkt,sub:e.agentId,jti:i,runtimeId:e.runtimeId,runtimeJkt:e.runtimeJkt,leaseIssuerJkt:e.leaseIssuerJkt,purpose:k.RUNTIME_LEASE_PURPOSE,network:TU(e.network),signingModes:xl(e.signingModes),...o?{custody:e.custody,rails:a}:{},maxLeaseTtlSeconds:r,iat:t,nbf:t,exp:s};return{...(0,Hs.prepareRootSignedJws)(xe.RUNTIME_DELEGATION_TYP,e.rootKid,c),claims:c}}function PS(e,t){return(0,Hs.completeRootSignedJws)(e.signingInput,t,"runtime delegation")}async function kU(e){let t=TS({...e,rootKid:e.signer.kid,rootPublicJwk:e.signer.publicJwk}),n=await e.signer.sign(new TextEncoder().encode(t.signingInput));return PS(t,n)}function kS(e){let t=e.nowSec??Math.floor(Date.now()/1e3),n=e.ttlSeconds??e.delegation.maxLeaseTtlSeconds,r=t+n,i=e.leaseId??(0,mg.randomUUID)();if(Rl("nowSec",t),Rl("delegationExpiresAt",e.delegation.exp),!Number.isSafeInteger(e.delegation.maxLeaseTtlSeconds)||e.delegation.maxLeaseTtlSeconds<=0||e.delegation.maxLeaseTtlSeconds>xe.RUNTIME_LEASE_MAX_TTL_SECONDS)throw new Error("runtime lease maximum TTL is invalid");if(!Number.isSafeInteger(n)||n<=0||n>e.delegation.maxLeaseTtlSeconds||!Number.isSafeInteger(r)||r>e.delegation.exp)throw new Error("runtime lease TTL exceeds its delegation");if($r("agentId",e.delegation.sub),$r("runtimeId",e.delegation.runtimeId),$r("delegationId",e.delegation.jti),$r("leaseId",i),$r("grantId",e.grantId),SS("issuerKid",e.issuerKid),!ft(e.delegation.leaseIssuerJkt)||(0,Vs.computeJkt)(e.issuerPublicJwk)!==e.delegation.leaseIssuerJkt)throw new Error("runtime lease issuer public key does not match leaseIssuerJkt");if(!ft(e.delegation.iss)||!ft(e.delegation.runtimeJkt))throw new Error("runtime lease root/runtime JKT is invalid");if(new Set([e.delegation.iss,e.delegation.runtimeJkt,e.delegation.leaseIssuerJkt]).size!==3)throw new Error("runtime lease root, runtime, and issuer keys must be distinct");if(!Number.isSafeInteger(e.generation)||e.generation<1)throw new Error("runtime lease generation must be a positive safe integer");if(!Number.isSafeInteger(e.grantVersion)||e.grantVersion<1)throw new Error("runtime lease grantVersion must be a positive safe integer");if(!ft(e.delegationHash))throw new Error("runtime lease delegationHash is invalid");if(e.tempo){let s=Ws(e.delegation);if(s?.custody!=="device"||!s.tempo)throw new Error("a Tempo lease needs a device delegation that covers tempo");let c={v:k.RUNTIME_LEASE_VERSION,iss:e.delegation.leaseIssuerJkt,sub:e.delegation.sub,aud:k.RUNTIME_LEASE_AUDIENCE,jti:i,delegationId:e.delegation.jti,delegationHash:e.delegationHash,rootJkt:e.delegation.iss,runtimeId:e.delegation.runtimeId,runtimeJkt:e.delegation.runtimeJkt,purpose:k.TEMPO_LEASE_PURPOSE,network:k.TEMPO_LEASE_NETWORK,signingModes:[k.TEMPO_LEASE_SIGNING_MODE],generation:e.generation,grantId:e.grantId,grantVersion:e.grantVersion,iat:t,nbf:t,exp:r};return{...(0,Hs.prepareRootSignedJws)(k.RUNTIME_LEASE_TYP,e.issuerKid,c),claims:c}}let o=xl(e.signingModes);if(!o.every(s=>e.delegation.signingModes.includes(s)))throw new Error("runtime lease signing modes exceed the verified delegation");let a={v:k.RUNTIME_LEASE_VERSION,iss:e.delegation.leaseIssuerJkt,sub:e.delegation.sub,aud:k.RUNTIME_LEASE_AUDIENCE,jti:i,delegationId:e.delegation.jti,delegationHash:e.delegationHash,rootJkt:e.delegation.iss,runtimeId:e.delegation.runtimeId,runtimeJkt:e.delegation.runtimeJkt,purpose:k.RUNTIME_LEASE_PURPOSE,network:e.delegation.network,signingModes:o,generation:e.generation,grantId:e.grantId,grantVersion:e.grantVersion,iat:t,nbf:t,exp:r};return{...(0,Hs.prepareRootSignedJws)(k.RUNTIME_LEASE_TYP,e.issuerKid,a),claims:a}}function CS(e,t){return(0,Hs.completeRootSignedJws)(e.signingInput,t,"runtime lease")}async function CU(e){let t=e.nowSec??Math.floor(Date.now()/1e3),n=await Fs(e.delegationToken,{...e.delegationVerification,nowSec:t});if(!n.ok)throw new Error(`runtime lease delegation refused: ${n.reason}`);let r=kS({delegation:n.delegation,delegationHash:Nl(e.delegationToken),signingModes:e.signingModes,generation:e.generation,grantId:e.grantId,grantVersion:e.grantVersion,ttlSeconds:e.ttlSeconds,nowSec:t,leaseId:e.leaseId,issuerKid:e.signer.kid,issuerPublicJwk:e.signer.publicJwk}),i=await e.signer.sign(new TextEncoder().encode(r.signingInput));return CS(r,i)}async function RU(e){let t=e.nowSec??Math.floor(Date.now()/1e3),n=await Fs(e.delegationToken,{...e.delegationVerification,requiredCustody:"device",nowSec:t});if(!n.ok)throw new Error(`runtime lease delegation refused: ${n.reason}`);let r=kS({delegation:n.delegation,delegationHash:Nl(e.delegationToken),signingModes:[],tempo:!0,generation:e.generation,grantId:e.grantId,grantVersion:e.grantVersion,ttlSeconds:e.ttlSeconds,nowSec:t,leaseId:e.leaseId,issuerKid:e.signer.kid,issuerPublicJwk:e.signer.publicJwk}),i=await e.signer.sign(new TextEncoder().encode(r.signingInput));return CS(r,i)}var RS=["v","iss","sub","jti","runtimeId","runtimeJkt","leaseIssuerJkt","purpose","network","signingModes","maxLeaseTtlSeconds","iat","nbf","exp"],xU=[...RS,"custody","rails"],xS=["v","iss","sub","aud","jti","delegationId","delegationHash","rootJkt","runtimeId","runtimeJkt","purpose","network","signingModes","generation","grantId","grantVersion","iat","nbf","exp"],OU=["alg","kid","typ"];function Nl(e){return(0,mg.createHash)("sha256").update(e,"utf8").digest("base64url")}function OS(e){try{let t=Buffer.from(e,"base64url");if(t.toString("base64url")!==e)return null;let n=new TextDecoder("utf-8",{fatal:!0}).decode(t),r=JSON.parse(n);return typeof r!="object"||r===null||Array.isArray(r)||JSON.stringify(r)!==n?null:r}catch{return null}}function _g(e){let t=e.split(".");return t.length===3&&OS(t[1])!==null}function wg(e){let t=e.split(".");if(t.length!==3)return!1;let n=OS(t[0]),r=Buffer.from(t[2],"base64url");return n!==null&&r.length===64&&r.toString("base64url")===t[2]&&Ol(n,OU)&&typeof n.alg=="string"&&typeof n.kid=="string"&&Fi.test(n.kid)}function Eg(e,t,n){return typeof e.iat!="number"||typeof e.nbf!="number"||typeof e.exp!="number"||!Number.isSafeInteger(e.iat)||!Number.isSafeInteger(e.nbf)||!Number.isSafeInteger(e.exp)||e.iat<0||e.nbf!==e.iat||e.exp<=e.iat||e.exp-e.iat>n?"ttl_exceeded":e.iat>t+xe.RUNTIME_AUTHORITY_CLOCK_SKEW_SECONDS||e.nbf>t+xe.RUNTIME_AUTHORITY_CLOCK_SKEW_SECONDS?"not_yet_valid":t>=e.exp?"expired":null}async function Fs(e,t){if(!Number.isSafeInteger(t.nowSec)||t.nowSec<0||t.nowSec>Number.MAX_SAFE_INTEGER-xe.RUNTIME_AUTHORITY_CLOCK_SKEW_SECONDS||!Fi.test(t.expectedRootKid))return{ok:!1,reason:"bad_verification_context"};if(!wg(e))return{ok:!1,reason:"delegation_header_invalid"};if(!_g(e))return{ok:!1,reason:"delegation_shape_invalid"};let n=await(0,gg.verifyJwtSignature)(e,t.ownerJwks);if(!n.ok)return n;if(n.header.typ!==xe.RUNTIME_DELEGATION_TYP)return{ok:!1,reason:"delegation_typ_mismatch"};let r=n.claims;if(!Ol(r,r.v===k.RUNTIME_DELEGATION_LEGACY_VERSION?RS:xU))return{ok:!1,reason:"delegation_shape_invalid"};let i=t.ownerJwks.keys.find(s=>s.kid===t.expectedRootKid);if(n.header.kid!==t.expectedRootKid||!i||(0,Vs.computeJkt)(i)!==t.expectedRootJkt)return{ok:!1,reason:"root_key_mismatch"};let o=Ws(r);if(o===null||t.requiredCustody!==void 0&&o.custody!==t.requiredCustody||r.iss!==t.expectedRootJkt||r.sub!==t.expectedAgentId||r.jti!==t.expectedDelegationId||r.runtimeId!==t.expectedRuntimeId||r.runtimeJkt!==t.expectedRuntimeJkt||r.leaseIssuerJkt!==t.expectedLeaseIssuerJkt||r.purpose!==k.RUNTIME_LEASE_PURPOSE||r.network!==t.expectedNetwork.toLowerCase()||!Xn.test(r.jti??"")||!Xn.test(r.runtimeId??"")||!ft(r.iss)||!ft(r.runtimeJkt)||!ft(r.leaseIssuerJkt)||new Set([r.iss,r.runtimeJkt,r.leaseIssuerJkt]).size!==3||!yg.test(r.network??"")||!IS(r.signingModes)||!Number.isSafeInteger(r.maxLeaseTtlSeconds)||r.maxLeaseTtlSeconds<=0||r.maxLeaseTtlSeconds>xe.RUNTIME_LEASE_MAX_TTL_SECONDS)return{ok:!1,reason:"delegation_claims_mismatch"};let a=Eg(r,t.nowSec,xe.RUNTIME_DELEGATION_MAX_TTL_SECONDS);return a?{ok:!1,reason:`delegation_${a}`}:{ok:!0,delegation:r}}async function NU(e,t,n){if(!Number.isSafeInteger(n.nowSec)||n.nowSec<0||n.nowSec>Number.MAX_SAFE_INTEGER-xe.RUNTIME_AUTHORITY_CLOCK_SKEW_SECONDS||!Number.isSafeInteger(n.expectedGeneration)||n.expectedGeneration<1||!Number.isSafeInteger(n.expectedGrantVersion)||n.expectedGrantVersion<1||!Fi.test(n.expectedRootKid)||!Fi.test(n.expectedLeaseIssuerKid))return{ok:!1,reason:"bad_verification_context"};let r;try{r=xl(n.allowedSigningModes)}catch{return{ok:!1,reason:"bad_verification_context"}}if(!r.includes(n.requiredSigningMode))return{ok:!1,reason:"current_policy_denied"};let i=await Fs(e,n);if(!i.ok)return i;let o=i.delegation;if(!wg(t))return{ok:!1,reason:"lease_header_invalid"};if(!_g(t))return{ok:!1,reason:"lease_shape_invalid"};let a=await(0,gg.verifyJwtSignature)(t,n.issuerJwks);if(!a.ok)return a;if(a.header.typ!==k.RUNTIME_LEASE_TYP)return{ok:!1,reason:"lease_typ_mismatch"};let s=a.claims;if(!Ol(s,xS))return{ok:!1,reason:"lease_shape_invalid"};let c=n.issuerJwks.keys.find(l=>l.kid===n.expectedLeaseIssuerKid);if(a.header.kid!==n.expectedLeaseIssuerKid||!c||(0,Vs.computeJkt)(c)!==n.expectedLeaseIssuerJkt)return{ok:!1,reason:"lease_issuer_mismatch"};if(s.v!==k.RUNTIME_LEASE_VERSION||s.iss!==n.expectedLeaseIssuerJkt||s.sub!==n.expectedAgentId||s.aud!==k.RUNTIME_LEASE_AUDIENCE||s.delegationId!==n.expectedDelegationId||s.delegationHash!==Nl(e)||s.rootJkt!==n.expectedRootJkt||s.runtimeId!==n.expectedRuntimeId||s.runtimeJkt!==n.expectedRuntimeJkt||s.purpose!==k.RUNTIME_LEASE_PURPOSE||s.network!==n.expectedNetwork.toLowerCase()||s.generation!==n.expectedGeneration||s.grantId!==n.expectedGrantId||s.grantVersion!==n.expectedGrantVersion||!Xn.test(s.jti??"")||!Xn.test(s.delegationId??"")||!ft(s.delegationHash)||!Xn.test(s.runtimeId??"")||!Xn.test(s.grantId??"")||!ft(s.iss)||!ft(s.rootJkt)||!ft(s.runtimeJkt)||new Set([s.iss,s.rootJkt,s.runtimeJkt]).size!==3||!yg.test(s.network??"")||!IS(s.signingModes)||!Number.isSafeInteger(s.generation)||s.generation<1||!Number.isSafeInteger(s.grantVersion)||s.grantVersion<1)return{ok:!1,reason:"lease_claims_mismatch"};let d=Eg(s,n.nowSec,Math.min(o.maxLeaseTtlSeconds,xe.RUNTIME_LEASE_MAX_TTL_SECONDS));return d?{ok:!1,reason:`lease_${d}`}:s.iat<o.iat||s.exp>o.exp||!s.signingModes.every(l=>o.signingModes.includes(l))||!s.signingModes.every(l=>r.includes(l))||!o.signingModes.includes(n.requiredSigningMode)||!s.signingModes.includes(n.requiredSigningMode)?{ok:!1,reason:"lease_scope_exceeded"}:{ok:!0,delegation:o,lease:s}}async function DU(e,t,n){if(!Number.isSafeInteger(n.nowSec)||n.nowSec<0||n.nowSec>Number.MAX_SAFE_INTEGER-xe.RUNTIME_AUTHORITY_CLOCK_SKEW_SECONDS||!Number.isSafeInteger(n.expectedGeneration)||n.expectedGeneration<1||!Number.isSafeInteger(n.expectedGrantVersion)||n.expectedGrantVersion<1||!Fi.test(n.expectedRootKid)||!Fi.test(n.expectedLeaseIssuerKid))return{ok:!1,reason:"bad_verification_context"};let r=await Fs(e,{...n,requiredCustody:"device"});if(!r.ok)return r;let i=r.delegation;if(!Ws(i)?.tempo)return{ok:!1,reason:"delegation_scope_refused"};if(!wg(t))return{ok:!1,reason:"lease_header_invalid"};if(!_g(t))return{ok:!1,reason:"lease_shape_invalid"};let o=await(0,gg.verifyJwtSignature)(t,n.issuerJwks);if(!o.ok)return o;if(o.header.typ!==k.RUNTIME_LEASE_TYP)return{ok:!1,reason:"lease_typ_mismatch"};let a=o.claims;if(!Ol(a,xS))return{ok:!1,reason:"lease_shape_invalid"};let s=n.issuerJwks.keys.find(d=>d.kid===n.expectedLeaseIssuerKid);if(o.header.kid!==n.expectedLeaseIssuerKid||!s||(0,Vs.computeJkt)(s)!==n.expectedLeaseIssuerJkt)return{ok:!1,reason:"lease_issuer_mismatch"};if(a.v!==k.RUNTIME_LEASE_VERSION||a.iss!==n.expectedLeaseIssuerJkt||a.sub!==n.expectedAgentId||a.aud!==k.RUNTIME_LEASE_AUDIENCE||a.delegationId!==n.expectedDelegationId||a.delegationHash!==Nl(e)||a.rootJkt!==n.expectedRootJkt||a.runtimeId!==n.expectedRuntimeId||a.runtimeJkt!==n.expectedRuntimeJkt||a.purpose!==k.TEMPO_LEASE_PURPOSE||a.network!==k.TEMPO_LEASE_NETWORK||a.generation!==n.expectedGeneration||a.grantId!==n.expectedGrantId||a.grantVersion!==n.expectedGrantVersion||!Array.isArray(a.signingModes)||a.signingModes.length!==1||a.signingModes[0]!==k.TEMPO_LEASE_SIGNING_MODE||!Xn.test(a.jti??"")||!Xn.test(a.grantId??""))return{ok:!1,reason:"lease_claims_mismatch"};let c=Eg(a,n.nowSec,Math.min(i.maxLeaseTtlSeconds,xe.RUNTIME_LEASE_MAX_TTL_SECONDS));return c?{ok:!1,reason:`lease_${c}`}:a.iat<i.iat||a.exp>i.exp?{ok:!1,reason:"lease_scope_exceeded"}:{ok:!0,delegation:i,lease:a}}});var Rg=y(zi=>{"use strict";Object.defineProperty(zi,"__esModule",{value:!0});zi.formatCents=HU;zi.formatUsd=VU;zi.formatMicros=$U;zi.formatMoney=FU;zi.formatTime=BU;var Cg=1e6,KU=100;function HU(e,t={}){let n=t.fallback??"\u2014";if(e==null||!Number.isFinite(e))return n;let i=(e/KU).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??2});return t.showPlusSign&&e>0?`+${i}`:i}function VU(e,t={}){let n=t.fallback??"\u2014";if(e==null||!Number.isFinite(e))return n;let r=e.toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??2});return t.showPlusSign&&e>0?`+${r}`:r}function $U(e,t={}){let n=t.fallback??"\u2014",r=typeof e=="string"?e===""?null:Number(e):e;if(r==null||!Number.isFinite(r))return n;let o=(r/Cg).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??6});return t.showPlusSign&&r>0?`+${o}`:o}var WU=/^-?\d+$/;function FU(e,t={}){if(typeof e!="bigint"&&!(typeof e=="string"&&WU.test(e)))throw new TypeError("formatMoney: expected integer micros");let n=BigInt(e),r=n<0n,i=r?-n:n,o=i/BigInt(Cg),a=(i%BigInt(Cg)).toString().padStart(6,"0"),s=t.precision??"cents",c=s==="exact"?a:s==="cents"||i%10000n===0n?a.slice(0,2):a.replace(/0+$/,""),d=r?"-":"",l=t.currency??"USD",u=`${o.toString()}.${c}`;return l==="USD"?`${d}$${u}`:`${d}${u} ${l}`}function BU(e,t={}){let n=t.fallback??"\u2014";if(!e)return n;let r=new Date(e);return Number.isNaN(r.getTime())?n:r.toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit",timeZone:t.timeZone??"UTC"})}});var Og=y(Nt=>{"use strict";Object.defineProperty(Nt,"__esModule",{value:!0});Nt.AGENT_GRANT_MAX_PER_PURCHASE_CENTS=Nt.AGENT_GRANT_MAX_AGGREGATE_CEILING_CENTS=Nt.AGENT_GRANT_MIN_LIMIT_MICROS=Nt.AGENT_GRANT_MAX_PER_PURCHASE_MICROS=Nt.AGENT_GRANT_MAX_AGGREGATE_CEILING_MICROS=void 0;var xg=Ng();Nt.AGENT_GRANT_MAX_AGGREGATE_CEILING_MICROS=(0,xg.micros)(1000000000n);Nt.AGENT_GRANT_MAX_PER_PURCHASE_MICROS=(0,xg.micros)(50000000n);Nt.AGENT_GRANT_MIN_LIMIT_MICROS=(0,xg.micros)(1000n);Nt.AGENT_GRANT_MAX_AGGREGATE_CEILING_CENTS=1e5;Nt.AGENT_GRANT_MAX_PER_PURCHASE_CENTS=5e3});var WS=y(bt=>{"use strict";Object.defineProperty(bt,"__esModule",{value:!0});bt.MAX_BUDGET_DRAWS=void 0;bt.derivePurchaseCountDetail=HS;bt.derivePurchaseCountDetailMicros=VS;bt.derivePurchaseCount=$S;bt.describePurchaseCount=XU;bt.describePurchaseCountMicros=ZU;var ya=Rg(),GU=Og();bt.MAX_BUDGET_DRAWS=20;function KS(e,t){if(!Number.isSafeInteger(t)||t<=0)throw new TypeError(`${e}: expected a positive safe integer of cents, got ${t}`)}function HS(e,t){KS("aggregateCeilingCents",e),KS("perPurchaseCents",t);let n=Math.ceil(e/t),r=Math.max(1,Math.min(bt.MAX_BUDGET_DRAWS,n)),i=n>bt.MAX_BUDGET_DRAWS;return{count:r,clamped:i,unreachableCents:i?e-r*t:0}}function Ys(e,t){if(!/^[1-9]\d{0,18}$/.test(t))throw new TypeError(`${e}: expected canonical positive integer micros, got ${t}`);return BigInt(t)}function VS(e,t){let n=Ys("aggregateCeilingMicros",e),r=Ys("perPurchaseMicros",t),i=(n+r-1n)/r,o=Math.max(1,Math.min(bt.MAX_BUDGET_DRAWS,Number(i))),a=i>BigInt(bt.MAX_BUDGET_DRAWS);return{count:o,clamped:a,unreachableMicros:a?(n-BigInt(o)*r).toString():"0"}}function $S(e,t){return HS(e,t).count}function YU(e){let t=[Math.floor(e/5),Math.floor(e/4),Math.floor(e/2)].filter(n=>n>=1);for(let n of t){let r=$S(e,n);if(r>=2)return{perCents:n,count:r}}return null}function zU(e){let t=Ys("aggregateCeilingMicros",e),n=[t/5n,t/4n,t/2n].filter(r=>r>=GU.AGENT_GRANT_MIN_LIMIT_MICROS);for(let r of n){let i=VS(e,r.toString()).count;if(i>=2)return{perMicros:r.toString(),count:i}}return null}function XU(e,t,n){let r=(0,ya.formatCents)(t);if(e.clamped)return`This budget covers ${e.count} purchases \u2014 the most one budget allows. Each can be up to ${r}. ${(0,ya.formatCents)(e.unreachableCents)} of the total can never be spent. Raise the per-purchase amount to use all of it.`;if(e.count===1){let i=YU(n),o=i?` Lower the per-purchase amount to allow more purchases \u2014 ${(0,ya.formatCents)(i.perCents)} allows ${i.count}.`:" Lower the per-purchase amount to allow more purchases.";return`This budget covers 1 purchase of up to ${r}. A smaller charge still uses that one purchase, and leftover budget sits unused.${o}`}return`This budget covers ${e.count} purchases. Each can be up to ${r}. Smaller charges are fine \u2014 each one still counts as a purchase.`}function ZU(e,t,n){Ys("perPurchaseMicros",t),Ys("aggregateCeilingMicros",n);let r=(0,ya.formatMicros)(t);if(e.clamped)return`This budget covers ${e.count} purchases \u2014 the most one budget allows. Each can be up to ${r}. ${(0,ya.formatMicros)(e.unreachableMicros)} of the total can never be spent. Raise the per-purchase amount to use all of it.`;if(e.count===1){let i=zU(n),o=i?` Lower the per-purchase amount to allow more purchases \u2014 ${(0,ya.formatMicros)(i.perMicros)} allows ${i.count}.`:" Lower the per-purchase amount to allow more purchases.";return`This budget covers 1 purchase of up to ${r}. A smaller charge still uses that one purchase, and leftover budget sits unused.${o}`}return`This budget covers ${e.count} purchases. Each can be up to ${r}. Smaller charges are fine \u2014 each one still counts as a purchase.`}});var Ng=y(q=>{"use strict";Object.defineProperty(q,"__esModule",{value:!0});q.describePurchaseCountMicros=q.describePurchaseCount=q.derivePurchaseCountDetailMicros=q.derivePurchaseCountDetail=q.derivePurchaseCount=q.MAX_BUDGET_DRAWS=q.AGENT_GRANT_MAX_PER_PURCHASE_CENTS=q.AGENT_GRANT_MAX_AGGREGATE_CEILING_CENTS=q.AGENT_GRANT_MIN_LIMIT_MICROS=q.AGENT_GRANT_MAX_PER_PURCHASE_MICROS=q.AGENT_GRANT_MAX_AGGREGATE_CEILING_MICROS=q.formatTime=q.formatMoney=q.formatMicros=q.formatUsd=q.formatCents=void 0;q.micros=QU;q.fromCents=ej;q.fromUsdc=tj;q.fromUsd=nj;q.toCents=rj;q.toCentsForAcquirer=ij;q.toUsdc=oj;q.toWire=aj;q.fromWire=sj;q.toDisplay=cj;q.toUsdRounded2dp=dj;q.toUsdNumber=lj;q.add=uj;q.sub=fj;q.clampNonNegative=pj;q.max=hj;q.min=mj;var Zn=10000n,Jl=1000000n;function QU(e){return e}function ej(e){if(!Number.isFinite(e)||!Number.isInteger(e)||!Number.isSafeInteger(e))throw new TypeError(`fromCents: expected safe integer, got ${e}`);return BigInt(e)*Zn}function tj(e){return e}function nj(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function rj(e){if(e>=0n)return Number(e/Zn);let t=e/Zn,n=e%Zn;return Number(n===0n?t:t-1n)}function ij(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/Zn)}function oj(e){return e}function aj(e){return e.toString()}function sj(e){if(typeof e!="string"||e.length===0)throw new TypeError(`fromWire: expected non-empty string, got ${typeof e} ${JSON.stringify(e)}`);if(!/^-?\d+$/.test(e))throw new TypeError(`fromWire: not a valid micros integer: ${JSON.stringify(e)}`);return BigInt(e)}function cj(e,t={}){let n=t.decimals??2,r=t.symbol??"$",i=e<0n,o=i?-e:e,a=o/Jl,s=o%Jl,c=i?"-":"";if(n===0)return`${c}${r}${a.toString()}`;let d=s.toString().padStart(6,"0").slice(0,n);return`${c}${r}${a.toString()}.${d}`}function dj(e){let t=e<0n,n=t?-e:e,r=n/Zn,o=n%Zn*2n,a;o<Zn?a=r:o>Zn?a=r+1n:a=r%2n===0n?r:r+1n;let s=Number(a)/100;return t?-s:s}function lj(e){let t=e<0n,n=t?-e:e,r=Number(n/Jl)+Number(n%Jl)/1e6;return t?-r:r}function uj(e,t){return e+t}function fj(e,t){return e-t}function pj(e){return e<0n?0n:e}function hj(e,t){return e>t?e:t}function mj(e,t){return e<t?e:t}var zs=Rg();Object.defineProperty(q,"formatCents",{enumerable:!0,get:function(){return zs.formatCents}});Object.defineProperty(q,"formatUsd",{enumerable:!0,get:function(){return zs.formatUsd}});Object.defineProperty(q,"formatMicros",{enumerable:!0,get:function(){return zs.formatMicros}});Object.defineProperty(q,"formatMoney",{enumerable:!0,get:function(){return zs.formatMoney}});Object.defineProperty(q,"formatTime",{enumerable:!0,get:function(){return zs.formatTime}});var Xs=Og();Object.defineProperty(q,"AGENT_GRANT_MAX_AGGREGATE_CEILING_MICROS",{enumerable:!0,get:function(){return Xs.AGENT_GRANT_MAX_AGGREGATE_CEILING_MICROS}});Object.defineProperty(q,"AGENT_GRANT_MAX_PER_PURCHASE_MICROS",{enumerable:!0,get:function(){return Xs.AGENT_GRANT_MAX_PER_PURCHASE_MICROS}});Object.defineProperty(q,"AGENT_GRANT_MIN_LIMIT_MICROS",{enumerable:!0,get:function(){return Xs.AGENT_GRANT_MIN_LIMIT_MICROS}});Object.defineProperty(q,"AGENT_GRANT_MAX_AGGREGATE_CEILING_CENTS",{enumerable:!0,get:function(){return Xs.AGENT_GRANT_MAX_AGGREGATE_CEILING_CENTS}});Object.defineProperty(q,"AGENT_GRANT_MAX_PER_PURCHASE_CENTS",{enumerable:!0,get:function(){return Xs.AGENT_GRANT_MAX_PER_PURCHASE_CENTS}});var _a=WS();Object.defineProperty(q,"MAX_BUDGET_DRAWS",{enumerable:!0,get:function(){return _a.MAX_BUDGET_DRAWS}});Object.defineProperty(q,"derivePurchaseCount",{enumerable:!0,get:function(){return _a.derivePurchaseCount}});Object.defineProperty(q,"derivePurchaseCountDetail",{enumerable:!0,get:function(){return _a.derivePurchaseCountDetail}});Object.defineProperty(q,"derivePurchaseCountDetailMicros",{enumerable:!0,get:function(){return _a.derivePurchaseCountDetailMicros}});Object.defineProperty(q,"describePurchaseCount",{enumerable:!0,get:function(){return _a.describePurchaseCount}});Object.defineProperty(q,"describePurchaseCountMicros",{enumerable:!0,get:function(){return _a.describePurchaseCountMicros}})});var BS=y(We=>{"use strict";Object.defineProperty(We,"__esModule",{value:!0});We.TVC_PROVIDER_WARN_THRESHOLD=We.TURNKEY_SUBORG_RESOURCE_LIMITS=void 0;We.tvcProviderCapacityEvidence=FS;We.parseTvcProviderCapacityEvidence=gj;We.TURNKEY_SUBORG_RESOURCE_LIMITS=Object.freeze({users:100,policies:100,source:"https://docs.turnkey.com/reference/resource-limits",verifiedOn:"2026-08-29"});We.TVC_PROVIDER_WARN_THRESHOLD=70;function FS(e,t){if(!Number.isSafeInteger(e)||e<0)throw new Error("user count is invalid");if(!Number.isSafeInteger(t)||t<0)throw new Error("policy count is invalid");let n=We.TURNKEY_SUBORG_RESOURCE_LIMITS.users-e,r=We.TURNKEY_SUBORG_RESOURCE_LIMITS.policies-t;return{userCount:e,policyCount:t,userLimit:We.TURNKEY_SUBORG_RESOURCE_LIMITS.users,policyLimit:We.TURNKEY_SUBORG_RESOURCE_LIMITS.policies,remainingUsers:n,remainingPolicies:r,pressure:e>We.TVC_PROVIDER_WARN_THRESHOLD||t>We.TVC_PROVIDER_WARN_THRESHOLD,limitsSource:We.TURNKEY_SUBORG_RESOURCE_LIMITS.source,limitsVerifiedOn:We.TURNKEY_SUBORG_RESOURCE_LIMITS.verifiedOn}}function gj(e){if(!e||typeof e!="object"||Array.isArray(e))throw new Error("TVC provider capacity evidence is invalid");let t=e,n=FS(t.userCount??-1,t.policyCount??-1);for(let r of Object.keys(n))if(t[r]!==n[r])throw new Error("TVC provider capacity evidence is invalid");if(Object.keys(t).length!==Object.keys(n).length)throw new Error("TVC provider capacity evidence is invalid");return n}});var GS=y(Ul=>{"use strict";Object.defineProperty(Ul,"__esModule",{value:!0});Ul.TVC_SIGNER_POLICY_CONTRACT_VERSION=void 0;Ul.TVC_SIGNER_POLICY_CONTRACT_VERSION=1});var zS=y(Dg=>{"use strict";Object.defineProperty(Dg,"__esModule",{value:!0});Dg.checkTvcPinParity=bj;var jl=/^[0-9a-f]{64}$/,YS=16*1024,yj=4096,_j="tvc-proof-verifier.railway.internal",ql=class extends Error{};function wj(e,t){return Object.keys(e).sort().join(",")===[...t].sort().join(",")}function Ej(e){try{let t=new URL(e),n=t.protocol==="http:"&&t.hostname===_j&&t.port!=="";return t.protocol!=="https:"&&!n||t.username!==""||t.password!==""||t.search!==""||t.hash!==""?null:(t.pathname="/effective-pins",t)}catch{return null}}async function vj(e){let t=Number(e.headers.get("content-length"));if(Number.isFinite(t)&&t>YS)throw await e.body?.cancel().catch(()=>{}),new Error("response too large");let n=e.body?.getReader();if(!n)throw new Error("response body missing");let r=[],i=0,o=async()=>{try{return await n.read()}catch{throw new ql}};try{for(;;){let c=await o();if(c.done)break;if(i+=c.value.byteLength,i>YS)throw await n.cancel().catch(()=>{}),new Error("response too large");r.push(c.value)}}finally{n.releaseLock()}let a=new Uint8Array(i),s=0;for(let c of r)a.set(c,s),s+=c.byteLength;return JSON.parse(new TextDecoder("utf-8",{fatal:!0}).decode(a))}async function bj(e){let t=e.verifierUrl?.trim()??"",n=e.bearerToken?.trim()??"",r=e.approvedManifestDigest?.trim()??"",i=e.approvedPivotDigest?.trim()??"",o=[t,n,r,i].filter(Boolean).length;if(o===0)return{status:"dark"};let a=t?Ej(t):null;if(o!==4||!a||n.length>yj||!jl.test(r)||!jl.test(i))return{status:"invalid_configuration"};let s;try{s=await(e.fetchImpl??fetch)(a,{method:"GET",redirect:"error",headers:{accept:"application/json",authorization:`Bearer ${n}`},signal:AbortSignal.timeout(Math.min(Math.max(e.timeoutMs??5e3,100),1e4))})}catch{return{status:"verifier_unavailable"}}if(!s.ok)return await s.body?.cancel().catch(()=>{}),s.status===401||s.status===403?{status:"verifier_auth_failed"}:s.status===408||s.status===425||s.status===429||s.status>=500?{status:"verifier_unavailable"}:{status:"verifier_invalid_response"};let c;try{c=await vj(s)}catch(l){return{status:l instanceof ql?"verifier_unavailable":"verifier_invalid_response"}}if(typeof c!="object"||c===null||Array.isArray(c)||!wj(c,["approvedManifestDigest","approvedPivotDigest"]))return{status:"verifier_invalid_response"};let d=c;return typeof d.approvedManifestDigest!="string"||!jl.test(d.approvedManifestDigest)||typeof d.approvedPivotDigest!="string"||!jl.test(d.approvedPivotDigest)?{status:"verifier_invalid_response"}:d.approvedManifestDigest!==r?{status:"manifest_mismatch"}:d.approvedPivotDigest!==i?{status:"pivot_mismatch"}:{status:"ready"}}});var Mg=y(re=>{"use strict";Object.defineProperty(re,"__esModule",{value:!0});re.CARD_PAYMENT_ATTEMPT_STATUSES=re.CARD_PAYMENT_EVENT_REQUIRED_PROVENANCE=re.CARD_PAYMENT_PROCESSOR_TRUTH_EVENT_TYPES=re.CARD_PAYMENT_SOURCE_PROVENANCE=re.CARD_PAYMENT_PROVENANCES=re.OWNER_ATTESTATION_VERDICTS=re.CARD_PAYMENT_EVENT_TYPES=re.CARD_PAYMENT_INTENTS=re.CARD_PAYMENT_SOURCES=re.CARD_PAYMENT_PROCESSORS=void 0;re.isOwnerAttestationVerdict=QS;re.provenanceOfSource=e0;re.requiresProviderProvenance=Aj;re.requiredProvenanceFor=t0;re.reduceCardPaymentEvents=Oj;re.CARD_PAYMENT_PROCESSORS=["cybersource","vgs"];re.CARD_PAYMENT_SOURCES=["auth_request","mpp_gateway","cybersource_tss","cybersource_report","cybersource_webhook","web_vgs","admin","owner_attestation"];re.CARD_PAYMENT_INTENTS=["sale","auth","capture","refund","void","unknown"];re.CARD_PAYMENT_EVENT_TYPES=["charge_requested","charge_ambiguous","sale_accepted","auth_held","capture_pending","captured","voided","refund_pending","refund_succeeded","refund_failed","chargeback_opened","chargeback_lost","chargeback_won","processor_unknown","reconciliation_gap","owner_attested"];re.OWNER_ATTESTATION_VERDICTS=["found_charge","merchant_completed","no_charge_visible"];function QS(e){return typeof e=="string"&&re.OWNER_ATTESTATION_VERDICTS.includes(e)}re.CARD_PAYMENT_PROVENANCES=["provider","platform_caller","owner","operator"];re.CARD_PAYMENT_SOURCE_PROVENANCE={auth_request:"platform_caller",mpp_gateway:"platform_caller",web_vgs:"platform_caller",cybersource_tss:"provider",cybersource_report:"provider",cybersource_webhook:"provider",admin:"operator",owner_attestation:"owner"};function e0(e){return re.CARD_PAYMENT_SOURCE_PROVENANCE[e]??"platform_caller"}re.CARD_PAYMENT_PROCESSOR_TRUTH_EVENT_TYPES=new Set(["auth_held","capture_pending","captured","voided","refund_pending","refund_succeeded","refund_failed","chargeback_opened","chargeback_lost","chargeback_won"]);function Aj(e){return re.CARD_PAYMENT_PROCESSOR_TRUTH_EVENT_TYPES.has(e)}re.CARD_PAYMENT_EVENT_REQUIRED_PROVENANCE={...Object.fromEntries([...re.CARD_PAYMENT_PROCESSOR_TRUTH_EVENT_TYPES].map(e=>[e,"provider"])),owner_attested:"owner"};function t0(e){return re.CARD_PAYMENT_EVENT_REQUIRED_PROVENANCE[e]??null}re.CARD_PAYMENT_ATTEMPT_STATUSES=["pending","needs_reconciliation","auth_held","capture_pending","sale_accepted","captured","voided","refund_pending","partially_refunded","refunded","chargeback_open","chargeback_lost","chargeback_won"];var Sj=-9223372036854775808n,Ij=9223372036854775807n;function XS(e){if(!e)return null;let n=(e instanceof Date?e:new Date(e)).getTime();return Number.isFinite(n)?n:null}function n0(e){if(!/^-?\d+$/.test(e))return null;try{let t=BigInt(e);return t>=Sj&&t<=Ij?t:null}catch{return null}}function Tj(e){return e==null?0n:typeof e=="number"?Number.isSafeInteger(e)?BigInt(e):0n:n0(e)??0n}function Pj(e){let t=XS(e.observedAt)??0;return{event:e,primaryAt:XS(e.occurredAt)??t,observedAt:t,id:Tj(e.id)}}function kj(e,t){let n=e.primaryAt-t.primaryAt;if(n!==0)return n;let r=e.observedAt-t.observedAt;if(r!==0)return r;let i=e.id-t.id;return i<0n?-1:i>0n?1:0}function ZS(e){return e==null?null:typeof e=="bigint"?e:typeof e=="number"?Number.isFinite(e)&&Number.isSafeInteger(e)?BigInt(e):null:n0(e)}function Cj(e,t){return e>0n&&t<e?"partially_refunded":"refunded"}function Rj(e){return e==="charge_requested"||e==="auth_held"||e==="capture_pending"||e==="sale_accepted"||e==="captured"}function xj(e,t){return e===t||t==="needs_reconciliation"?!0:e==="captured"?t==="refund_pending"||t==="partially_refunded"||t==="refunded":e==="sale_accepted"?t==="captured"||t==="refund_pending"||t==="partially_refunded"||t==="refunded"||t==="voided":e==="refund_pending"?t==="partially_refunded"||t==="refunded"||t==="refund_pending":e==="partially_refunded"?t==="partially_refunded"||t==="refunded":e==="refunded"?t==="refunded":e==="voided"?t==="voided":!0}function Qn(e,t,n,r){return xj(e,t)?{status:t,reason:r}:{status:e,reason:n}}function Oj(e,t={}){let n="needs_reconciliation",r="no_processor_events",i=[],o=!1,a=null,s=0n,c=ZS(t.attemptAmountMicros),d=c!==null&&c>0n?c:0n,l=null,u=null,f=!1,h=t.attemptAmountMicros!==null&&t.attemptAmountMicros!==void 0&&(c===null||c<0n)?"invalid_amount":null,p=e.map(Pj).sort(kj).map(({event:m})=>m);for(let m of p){let w=e0(m.source),v=t0(m.eventType);if(v!==null&&w!==v){i.push({eventType:m.eventType,source:m.source,provenance:w,requiredProvenance:v});continue}if(m.eventType==="owner_attested"){o=!0,QS(m.ownerVerdict)&&(a=m.ownerVerdict);continue}let _=ZS(m.amountMicros);if(m.amountMicros!==null&&m.amountMicros!==void 0&&(_===null||_<0n)){h="invalid_amount",n="needs_reconciliation",r="invalid_amount";continue}if((m.amountMicros===null||m.amountMicros===void 0)&&Rj(m.eventType)&&d<=0n){h="missing_amount",n="needs_reconciliation",r="missing_amount";continue}let A=_??d;if(m.eventType==="chargeback_opened"||m.eventType==="chargeback_lost"){l=m.eventType==="chargeback_opened"?"chargeback_open":"chargeback_lost",u=m.eventType,f=!0;continue}if(m.eventType==="chargeback_won"){l=null,u=null,f=!1,n==="needs_reconciliation"&&(n="chargeback_won",r="chargeback_won");continue}switch(m.eventType){case"charge_requested":A>d&&(d=A),{status:n,reason:r}=Qn(n,"pending",r,"charge_requested");break;case"charge_ambiguous":case"processor_unknown":case"reconciliation_gap":({status:n,reason:r}=Qn(n,"needs_reconciliation",r,m.eventType));break;case"auth_held":A>d&&(d=A),{status:n,reason:r}=Qn(n,"auth_held",r,"auth_held");break;case"capture_pending":A>d&&(d=A),{status:n,reason:r}=Qn(n,"capture_pending",r,"capture_pending");break;case"sale_accepted":A>d&&(d=A),{status:n,reason:r}=Qn(n,"sale_accepted",r,"sale_accepted");break;case"captured":A>d&&(d=A),{status:n,reason:r}=Qn(n,"captured",r,"captured");break;case"voided":({status:n,reason:r}=Qn(n,"voided",r,"voided"));break;case"refund_pending":({status:n,reason:r}=Qn(n,"refund_pending",r,"refund_pending"));break;case"refund_succeeded":if(_===null){h="missing_amount",n="needs_reconciliation",r="missing_amount";continue}s+=A,d>0n&&s>d&&(s=d),{status:n,reason:r}=Qn(n,Cj(d,s),r,"refund_succeeded");break;case"refund_failed":r="refund_failed";break}}return l?{status:l,statusReason:u??l,refundMicros:s,hasChargeback:f,rejectedProcessorClaims:i,ownerAttested:o,ownerVerdict:a}:h?{status:"needs_reconciliation",statusReason:h,refundMicros:s,hasChargeback:f,rejectedProcessorClaims:i,ownerAttested:o,ownerVerdict:a}:{status:n,statusReason:r,refundMicros:s,hasChargeback:f,rejectedProcessorClaims:i,ownerAttested:o,ownerVerdict:a}}});var c0=y(er=>{"use strict";Object.defineProperty(er,"__esModule",{value:!0});er.CardPaymentDbValidationError=void 0;er.validateCardPaymentEventInsertRow=i0;er.assertValidCardPaymentAttemptStatus=o0;er.insertCardPaymentLifecycleEvent=Hj;er.insertCardPaymentLifecycleEventWithId=s0;er.refreshCardPaymentAttemptProjection=Vj;var Qs=Mg(),Xi=class extends Error{table;offendingKeys;constructor(t,n,r){super(`[pg:${n}] ${t}`),this.table=n,this.offendingKeys=r,this.name="CardPaymentDbValidationError"}};er.CardPaymentDbValidationError=Xi;function pt(e,t,n){throw new Xi(t,e,Object.keys(n))}function Nj(e,t){if(!t||typeof t!="object"||Array.isArray(t))throw new Xi("row must be a non-array object",e,[]);return t}function Dj(e,t,n){for(let r of Object.keys(t))n.has(r)||pt(e,`unknown column "${r}"`,t)}function Mj(e,t,n){for(let r of n)(t[r]===void 0||t[r]===null)&&pt(e,`required column "${r}" is missing`,t)}function Zs(e,t,n,r={}){let i=t[n];if(i==null){if(r.nullable)return;pt(e,`${n} must be a string`,t)}typeof i!="string"&&pt(e,`${n} must be a string`,t),r.nonEmpty&&i.length===0&&pt(e,`${n} must be non-empty`,t),r.maxLen&&i.length>r.maxLen&&pt(e,`${n} exceeds ${r.maxLen} chars`,t)}function Lg(e,t,n,r){let i=t[n];(typeof i!="string"||!r.has(i))&&pt(e,`${n} must be one of ${[...r].join("|")}`,t)}function Lj(e,t,n){let r=t[n],i=9223372036854775807n,o=typeof r=="bigint"?r:typeof r=="string"&&/^\d+$/.test(r)&&r.length<=19?BigInt(r):null;o===null&&pt(e,`${n} must be a numeric integer string`,t),o<=0n&&pt(e,`${n} must be positive`,t),o>i&&pt(e,`${n} must fit signed 64-bit integer`,t)}var Jj=new Set(["attempt_id","transaction_id","user_login","processor","source","event_type","processor_event_id","processor_transaction_id","amount_micros","currency","processor_status","occurred_at","payload"]),Uj=["user_login","processor","source","event_type","payload"],jj=new Set(Qs.CARD_PAYMENT_PROCESSORS),qj=new Set(Qs.CARD_PAYMENT_SOURCES),Kj=new Set(Qs.CARD_PAYMENT_EVENT_TYPES),r0=new Set(Qs.CARD_PAYMENT_ATTEMPT_STATUSES);function i0(e){let t=Nj("card_payment_events",e);Dj("card_payment_events",t,Jj),Mj("card_payment_events",t,Uj);for(let n of["attempt_id","transaction_id"]){let r=t[n];if(r!=null){let i=typeof r=="string"&&/^\d+$/.test(r)?Number(r):r;(typeof i!="number"||!Number.isInteger(i)||i<=0)&&pt("card_payment_events",`${n} must be a positive integer or null`,t)}}Zs("card_payment_events",t,"user_login",{nonEmpty:!0,maxLen:255}),Lg("card_payment_events",t,"processor",jj),Lg("card_payment_events",t,"source",qj),Lg("card_payment_events",t,"event_type",Kj),t.processor_event_id!==null&&t.processor_event_id!==void 0&&Zs("card_payment_events",t,"processor_event_id",{nonEmpty:!0,maxLen:255,nullable:!0}),t.processor_transaction_id!==null&&t.processor_transaction_id!==void 0&&Zs("card_payment_events",t,"processor_transaction_id",{nonEmpty:!0,maxLen:255,nullable:!0}),t.amount_micros!==null&&t.amount_micros!==void 0&&Lj("card_payment_events",t,"amount_micros"),t.currency!==null&&t.currency!==void 0&&Zs("card_payment_events",t,"currency",{nonEmpty:!0,maxLen:3,nullable:!0}),t.processor_status!==null&&t.processor_status!==void 0&&Zs("card_payment_events",t,"processor_status",{nonEmpty:!0,maxLen:128,nullable:!0}),t.occurred_at!==null&&t.occurred_at!==void 0&&!(t.occurred_at instanceof Date)&&typeof t.occurred_at!="string"&&pt("card_payment_events","occurred_at must be a Date, ISO string, or null",t),typeof t.payload!="string"&&pt("card_payment_events","payload must be a JSON string",t);try{JSON.parse(t.payload)}catch{pt("card_payment_events","payload must be valid JSON",t)}}function o0(e){if(!r0.has(e))throw new Xi(`current_status must be one of ${[...r0].join("|")}`,"card_payment_attempts",["current_status"])}function a0(e){return e===null?null:typeof e=="number"?e:Number(e)}async function Hj(e,t){return(await s0(e,t)).inserted}async function s0(e,t){let n={attempt_id:a0(t.attemptId),transaction_id:t.transactionId,user_login:t.userLogin,processor:t.processor??"cybersource",source:t.source,event_type:t.eventType,processor_event_id:t.processorEventId,processor_transaction_id:t.processorTransactionId,amount_micros:t.amountMicros,currency:t.currency,processor_status:t.processorStatus,occurred_at:t.occurredAt??null,payload:JSON.stringify(t.payload)};i0(n);let i=(await e.query(`INSERT INTO card_payment_events (
|
|
2
|
+
attempt_id, transaction_id, user_login, processor, source, event_type,
|
|
3
|
+
processor_event_id, processor_transaction_id, amount_micros, currency,
|
|
4
|
+
processor_status, occurred_at, payload
|
|
5
|
+
) VALUES ($1,$2,$3,$4,$5,$6,$7,$8,$9::bigint,$10,$11,$12::timestamptz,$13::jsonb)
|
|
6
|
+
ON CONFLICT (processor, processor_event_id)
|
|
7
|
+
WHERE processor_event_id IS NOT NULL
|
|
8
|
+
DO NOTHING
|
|
9
|
+
RETURNING id::text`,[n.attempt_id,n.transaction_id,n.user_login,n.processor,n.source,n.event_type,n.processor_event_id,n.processor_transaction_id,n.amount_micros,n.currency,n.processor_status,n.occurred_at,n.payload])).rows[0]?.id,o=i===void 0?null:Number(i);return{inserted:o!==null,eventId:o}}async function Vj(e,t){let n=a0(t);if(n===null)throw new Xi("attempt_id is required","card_payment_attempts",["attempt_id"]);let i=(await e.query(`SELECT amount_micros::text AS amount_micros
|
|
10
|
+
FROM card_payment_attempts
|
|
11
|
+
WHERE id = $1
|
|
12
|
+
FOR UPDATE`,[n])).rows[0]?.amount_micros;if(!i)return null;let o=await e.query(`SELECT id::text AS id, event_type, source, amount_micros::text AS amount_micros,
|
|
13
|
+
processor_status, payload->>'verdict' AS owner_verdict, occurred_at, observed_at
|
|
14
|
+
FROM card_payment_events
|
|
15
|
+
WHERE attempt_id = $1
|
|
16
|
+
ORDER BY COALESCE(occurred_at, observed_at) ASC, observed_at ASC, id ASC`,[n]),a=o.rows[o.rows.length-1]?.id??null,s=(0,Qs.reduceCardPaymentEvents)(o.rows.map(c=>({id:c.id,eventType:c.event_type,source:c.source,amountMicros:c.amount_micros,processorStatus:c.processor_status,ownerVerdict:c.owner_verdict,occurredAt:c.occurred_at,observedAt:c.observed_at})),{attemptAmountMicros:i});return o0(s.status),await e.query(`UPDATE card_payment_attempts
|
|
17
|
+
SET current_status = $2,
|
|
18
|
+
status_reason = $3,
|
|
19
|
+
last_event_id = $4,
|
|
20
|
+
last_observed_at = NOW(),
|
|
21
|
+
updated_at = NOW()
|
|
22
|
+
WHERE id = $1`,[n,s.status,s.statusReason,a]),{status:s.status,statusReason:s.statusReason,rejectedProcessorClaims:s.rejectedProcessorClaims,ownerAttested:s.ownerAttested,ownerVerdict:s.ownerVerdict}}});var p0=y(An=>{"use strict";Object.defineProperty(An,"__esModule",{value:!0});An.normalizeRailEnvironmentValue=l0;An.isLiveVgsEnvironment=Wj;An.isExplicitProductionRailEnvironment=Kl;An.isPublicPreviewRailEnvironment=Ug;An.clickhouseDatabaseHasStagingMarker=u0;An.resolveClickhouseEnvBinding=Bj;An.resolveDeploymentEnvClass=f0;An.detectDeploymentEnvNodeEnvMismatch=Gj;var $j=new Set(["visacli.sh","app.visacli.sh","auth.visacli.sh","api.visacli.sh"]);function Wr(e){return(e||"").trim().toLowerCase()}function d0(e){let t=Wr(e),n=t;(t.startsWith("http://")||t.startsWith("https://"))&&(n=t.slice(t.indexOf("://")+3));let r=n.indexOf("/");r!==-1&&(n=n.slice(0,r));let i=n.indexOf(":");return i!==-1&&(n=n.slice(0,i)),n.startsWith("www.")?n.slice(4):n}function Jg(e,t){let n="";for(let r of Wr(e)){if(r>="a"&&r<="z"||r>="0"&&r<="9"){n+=r;continue}if(n&&t.has(n))return!0;n=""}return n?t.has(n):!1}function l0(e){return Wr(e)}function Wj(e){return new Set(["live","prod","production"]).has(l0(e))}function Kl(e){let t=d0(e.railwayPublicDomain),n=Wr(e.railwayEnvironment),r=Wr(e.railwayEnvironmentName),i=Wr(e.railwayGitBranch);return $j.has(t)||n==="production"||r==="production"||i==="main"||i==="production"}function Ug(e){if(Kl(e))return!1;let t=d0(e.railwayPublicDomain),n=new Set(["preview","staging","stage"]),r=new Set(["preview"]),i=Wr(e.railwayGitBranch);return Jg(t,r)||Jg(e.railwayEnvironment,n)||Jg(e.railwayEnvironmentName,n)||i==="staging"||i==="preview"||t.endsWith(".up.railway.app")||t.endsWith(".railway.app")}var Fj=new Set(["staging","stage","preview"]);function u0(e){let t=Wr(e);if(!t)return!1;for(let n of t.split(/[^a-z0-9]+/))if(Fj.has(n))return!0;return!1}function Bj(e){let t=(e.clickhouseDatabase||"").trim(),n=u0(t);return Kl(e)?n?{status:"mismatch",environment:"production",database:t,message:`production deploy is pointed at a non-production ClickHouse database (${t||"<empty>"}); production must use an unmarked database such as visa_mcp`}:{status:"ok",environment:"production",database:t}:Ug(e)?n?{status:"ok",environment:"preview",database:t}:{status:"mismatch",environment:"preview",database:t,message:`staging/preview deploy is pointed at the production ClickHouse database (${t||"<empty>"}); staging must use a marked database such as visa_mcp_staging`}:{status:"indeterminate"}}function f0(e){return Kl(e)?"production":Ug(e)?"preview":"unknown"}function Gj(e,t){let n=f0(e),r=(t||"").trim().toLowerCase();return n==="unknown"?{status:"indeterminate",deploymentEnv:n,nodeEnv:r,message:null}:n==="production"?r===""||r==="production"?{status:"ok",deploymentEnv:n,nodeEnv:r,message:null}:{status:"mismatch",deploymentEnv:n,nodeEnv:r,message:`Railway signals classify this deploy as production, but NODE_ENV=${r||"<empty>"}. Dev-only guards keyed on NODE_ENV!=='production' would silently activate. Set NODE_ENV=production on this Railway service.`}:new Set(["","development","test","preview","staging","production"]).has(r)?{status:"ok",deploymentEnv:n,nodeEnv:r,message:null}:{status:"mismatch",deploymentEnv:n,nodeEnv:r,message:`Railway signals classify this deploy as preview/staging, but NODE_ENV=${r||"<empty>"}. Set NODE_ENV=production on deployed Railway preview services.`}}});var h0=y(wa=>{"use strict";Object.defineProperty(wa,"__esModule",{value:!0});wa.DEFAULT_FETCH_TIMEOUT_MS=void 0;wa.fetchWithTimeout=Yj;wa.DEFAULT_FETCH_TIMEOUT_MS=15e3;function Yj(e,t={},n=wa.DEFAULT_FETCH_TIMEOUT_MS){return fetch(e,{...t,signal:t.signal??AbortSignal.timeout(n)})}});var g0=y(ec=>{"use strict";Object.defineProperty(ec,"__esModule",{value:!0});ec.normalizeAgentName=qg;ec.parseAgentSelector=m0;ec.computeAgentSelection=zj;function qg(e){return e.replace(/\.visa$/i,"").toLowerCase()}function m0(e){if(e!==void 0){if(typeof e!="string"||e.trim().length===0)throw new Error("Invalid agent selector. Pass a non-empty agent name or stable id.");return e.trim()}}function jg(e,t){return t?` Available: ${e.map(t).join(", ")}.`:""}function zj(e){let t=m0(e.requested);if(t){let n=qg(t),r=e.candidates.filter(i=>i.exactSelectors.includes(t)||i.names?.some(o=>qg(o)===n));return r.length>1?{kind:"ambiguous",message:`more than one ${e.duplicateAuthorityLabel??e.authorityLabel} is named "${t}".${jg(r,e.describeCandidate)} Select the exact ${e.exactSelectorLabel??"stable id"}. `+e.selectorGuidance,matches:r.map(i=>i.value)}:r.length===1?{kind:"selected",value:r[0].value}:{kind:"not_found",requested:t,message:`no ${e.authorityLabel} matched ${JSON.stringify(t)}.`+jg(e.candidates,e.describeCandidate)+` ${e.selectorGuidance}`}}return e.candidates.length>1?{kind:"ambiguous",message:`more than one ${e.authorityLabel} is available.${jg(e.candidates,e.describeCandidate)} ${e.selectorGuidance}`,matches:e.candidates.map(n=>n.value)}:e.candidates.length===1?{kind:"selected",value:e.candidates[0].value}:{kind:"none"}}});var w0=y(ue=>{"use strict";Object.defineProperty(ue,"__esModule",{value:!0});ue.PgDecryptionFailedError=ue.PgEncryptionWireFormatError=ue.PgEncryptionKeyMissingError=ue.PgEncryptionError=ue.PG_ENCRYPTION_WIRE_VERSIONS=ue.ENCRYPTION_KEY_MIN_BYTES=void 0;ue.isPgcryptoIntegrityError=Qj;ue.validateEncryptionKey=t6;ue.encodeWireFormat=y0;ue.decodeWireFormat=_0;ue.encrypt=n6;ue.decrypt=r6;ue.encryptSqlFragment=i6;ue.decryptSqlFragment=o6;ue.ENCRYPTION_KEY_MIN_BYTES=32;ue.PG_ENCRYPTION_WIRE_VERSIONS=["v1"];var Xj=/^(v[0-9]+):([A-Za-z0-9+/]+={0,2})$/,Dt=class extends Error{constructor(t){super(`[pg-encryption] ${t}`),this.name="PgEncryptionError"}};ue.PgEncryptionError=Dt;var Ea=class extends Dt{constructor(t){super(`${t} is missing or shorter than ${ue.ENCRYPTION_KEY_MIN_BYTES} bytes; merchant credential encryption is disabled`),this.name="PgEncryptionKeyMissingError"}};ue.PgEncryptionKeyMissingError=Ea;var Fr=class extends Dt{constructor(t){super(`malformed ciphertext: ${t}`),this.name="PgEncryptionWireFormatError"}};ue.PgEncryptionWireFormatError=Fr;var tc=class extends Dt{constructor(t){super(`decryption failed: ${t}`),this.name="PgDecryptionFailedError"}};ue.PgDecryptionFailedError=tc;var Zj=new Set(["39000","22023","22P02"]);function Qj(e){return typeof e!="object"||e===null||!("code"in e)?!1:typeof e.code=="string"&&Zj.has(e.code)}var e6=/^[A-Za-z0-9+/]+={0,2}$/;function t6(e,t){if(!e||e.trim()==="")throw new Ea(t);let n=e.trim();if(!e6.test(n))throw new Ea(t);if(Buffer.from(n,"base64").length<ue.ENCRYPTION_KEY_MIN_BYTES)throw new Ea(t);return n}function y0(e,t){if(!ue.PG_ENCRYPTION_WIRE_VERSIONS.includes(e))throw new Fr(`unsupported version "${e}"`);if(!/^[A-Za-z0-9+/]+={0,2}$/.test(t)||t.length===0)throw new Fr("cipher payload is not base64");return`${e}:${t}`}function _0(e){if(typeof e!="string"||e.length===0)throw new Fr("value is empty");let t=Xj.exec(e);if(!t)throw new Fr("does not match v<N>:<base64>");let n=t[1];if(!ue.PG_ENCRYPTION_WIRE_VERSIONS.includes(n))throw new Fr(`unsupported version "${n}"`);return{version:n,cipherBase64:t[2]}}async function n6(e,t,n){if(typeof t!="string"||t.length===0)throw new Dt("plaintext must be a non-empty string");if(typeof n!="string"||n.length===0)throw new Dt("key must be a non-empty string");let i=(await e.query("SELECT encode(pgp_sym_encrypt($1, $2, 'cipher-algo=aes256, compress-algo=2'), 'base64') AS ct",[t,n])).rows[0]?.ct;if(typeof i!="string"||i.length===0)throw new Dt("pgp_sym_encrypt returned no ciphertext");return y0("v1",i.replace(/\s+/g,""))}async function r6(e,t,n){if(typeof n!="string"||n.length===0)throw new Dt("key must be a non-empty string");let r=_0(t),i;try{i=await e.query("SELECT pgp_sym_decrypt(decode($1, 'base64'), $2) AS pt",[r.cipherBase64,n])}catch(a){let s=a instanceof Error?a.message:String(a);throw new tc(s)}let o=i.rows[0]?.pt;if(typeof o!="string")throw new tc("decrypt returned no plaintext");return o}function i6(e,t){return Kg(e,"plaintext"),Kg(t,"key"),`('v1:' || translate(encode(pgp_sym_encrypt(${e}, ${t}, 'cipher-algo=aes256, compress-algo=2'), 'base64'), E'\\n\\r', ''))`}function o6(e,t){return a6(e),Kg(t,"key"),`CASE WHEN ${e} IS NULL THEN NULL
|
|
23
|
+
WHEN SUBSTRING(${e} FROM 1 FOR 3) = 'v1:'
|
|
24
|
+
THEN pgp_sym_decrypt(decode(translate(SUBSTRING(${e} FROM 4), E'\\n\\r ', ''), 'base64'), ${t})
|
|
25
|
+
ELSE NULL END`}function Kg(e,t){if(!/^\$[1-9][0-9]*$/.test(e))throw new Dt(`${t} param ref must look like "$N", got "${e}"`)}function a6(e){if(!/^[a-zA-Z_][a-zA-Z0-9_]*(\.[a-zA-Z_][a-zA-Z0-9_]*){0,2}$/.test(e))throw new Dt(`column ref must be a simple identifier, got "${e}"`)}});var E0=y(Zt=>{"use strict";Object.defineProperty(Zt,"__esModule",{value:!0});Zt.PROTECTED_CARD_MAX_DRAWS=Zt.SETUP_DEFAULT_DAILY_CENTS=Zt.SETUP_DEFAULT_PER_PURCHASE_CENTS=Zt.SETUP_DEFAULT_AGGREGATE_CENTS=void 0;Zt.progressLadder=s6;Zt.SETUP_DEFAULT_AGGREGATE_CENTS=1e4;Zt.SETUP_DEFAULT_PER_PURCHASE_CENTS=2500;Zt.SETUP_DEFAULT_DAILY_CENTS=2500;Zt.PROTECTED_CARD_MAX_DRAWS=1e3;function s6(e,t){let n=!0;return e.map(({key:r,label:i,done:o})=>o?{key:r,label:i,state:"done"}:n?(n=!1,{key:r,label:i,state:t?"stopped":"active"}):{key:r,label:i,state:"pending"})}});var v0=y(Zi=>{"use strict";Object.defineProperty(Zi,"__esModule",{value:!0});Zi.runtimeLabel=d6;Zi.canonicalRuntimeId=Hl;Zi.runtimeMatchAliases=l6;Zi.runtimesMatch=u6;Zi.claimBindingMode=f6;var c6={"claude-code":"Claude Code",claude:"Claude Code",codex:"Codex",openclaw:"OpenClaw",hermes:"Hermes",cursor:"Cursor","custom-mcp":"Custom (MCP)",mcp:"Custom (MCP)",custom:"Custom (MCP)"};function d6(e){let t=e.trim();return c6[t.toLowerCase()]??t}function Hl(e){if(typeof e!="string")return;let t=e.trim().toLowerCase();if(t.length!==0)return t==="claude"||t==="claude-code"?"claude-code":t==="codex"?"codex":t==="openclaw"?"openclaw":t==="hermes"?"hermes":t==="cursor"?"cursor":t==="custom-mcp"||t==="mcp"||t==="custom"?"custom-mcp":t}function l6(e){let t=Hl(e);return t?t==="claude-code"?["claude","claude-code"]:t==="custom-mcp"?["custom","custom-mcp","mcp"]:[t]:[]}function u6(e,t){return!e||e.trim().length===0?!0:!t||t.trim().length===0?!1:Hl(e)===Hl(t)}function f6(e){return e&&e.trim().length>0?"targeted":"unbound"}});var b0=y(Qe=>{"use strict";Object.defineProperty(Qe,"__esModule",{value:!0});Qe.ReleaseManifestValidationError=Qe.PROVIDER_CONFIGURATION_VARIABLE_KEYS=Qe.ACTIVE_RAILWAY_SERVICES=Qe.RELEASE_MANIFEST_SCHEMA_VERSION=void 0;Qe.validateReleaseManifest=h6;var p6=Pr();Qe.RELEASE_MANIFEST_SCHEMA_VERSION="1.0.0";Qe.ACTIVE_RAILWAY_SERVICES=["auth","web"];Qe.PROVIDER_CONFIGURATION_VARIABLE_KEYS=["name","sensitivity","owners","consumer"];var J=class extends Error{field;constructor(t,n){super(`ReleaseManifest validation error: ${t}${n?` (field: ${n})`:""}`),this.field=n,this.name="ReleaseManifestValidationError"}};Qe.ReleaseManifestValidationError=J;function h6(e){if(!e||typeof e!="object"||Array.isArray(e))throw new J("Manifest must be a non-null object");let t=e;if(t.schemaVersion!==Qe.RELEASE_MANIFEST_SCHEMA_VERSION)throw new J(`Unsupported schemaVersion "${t.schemaVersion}"; expected "${Qe.RELEASE_MANIFEST_SCHEMA_VERSION}"`,"schemaVersion");if(typeof t.candidateId!="string"||!t.candidateId.trim())throw new J("candidateId must be a non-empty string","candidateId");if(typeof t.sourceCommit!="string"||!/^[0-9a-f]{7,40}$/i.test(t.sourceCommit))throw new J("sourceCommit must be a valid git commit SHA","sourceCommit");if(typeof t.generatedAt!="string"||!t.generatedAt.trim())throw new J("generatedAt must be a valid timestamp","generatedAt");if(t.environment!=="staging"&&t.environment!=="production")throw new J('environment must be "staging" or "production"',"environment");if(!t.services||typeof t.services!="object"||Array.isArray(t.services))throw new J("services must be an object","services");let n=t.services;for(let p of Qe.ACTIVE_RAILWAY_SERVICES){if(!n[p]||typeof n[p]!="object")throw new J(`Missing required active Railway service "${p}"`,`services.${p}`);let m=n[p];if(m.serviceId!==p)throw new J(`Service ID mismatch for "${p}"`,`services.${p}.serviceId`);if(typeof m.rootPath!="string"||!m.rootPath.trim())throw new J(`Invalid rootPath for service "${p}"`,`services.${p}.rootPath`);if(!Array.isArray(m.watchPaths)||m.watchPaths.length===0)throw new J(`watchPaths must be a non-empty array for service "${p}"`,`services.${p}.watchPaths`);if(!Array.isArray(m.healthEndpoints)||m.healthEndpoints.length===0)throw new J(`healthEndpoints must be a non-empty array for service "${p}"`,`services.${p}.healthEndpoints`)}if(!t.cli||typeof t.cli!="object"||Array.isArray(t.cli))throw new J("cli must be an object","cli");let r=t.cli;if(r.packageName!=="@visa/cli")throw new J('cli.packageName must be "@visa/cli"',"cli.packageName");if(typeof r.version!="string"||!r.version.trim())throw new J("cli.version must be a valid string","cli.version");if(r.channel!=="rc"&&r.channel!=="latest")throw new J('cli.channel must be "rc" or "latest"',"cli.channel");if(typeof r.tarballIntegrity!="string"||!r.tarballIntegrity.trim())throw new J("cli.tarballIntegrity must be a non-empty string","cli.tarballIntegrity");if(typeof r.minimumCompatibleVersion!="string"||!r.minimumCompatibleVersion.trim())throw new J("cli.minimumCompatibleVersion must be a non-empty string","cli.minimumCompatibleVersion");if(!r.capabilityFloors||typeof r.capabilityFloors!="object")throw new J("cli.capabilityFloors must be an object","cli.capabilityFloors");if(!t.database||typeof t.database!="object")throw new J("database must be an object","database");let i=t.database;if(!i.postgres||typeof i.postgres!="object")throw new J("database.postgres must be an object","database.postgres");let o=i.postgres;if(typeof o.schemaChecksum!="string"||!o.schemaChecksum.trim())throw new J("database.postgres.schemaChecksum must be a non-empty string","database.postgres.schemaChecksum");if(!Array.isArray(o.tables)||o.tables.length===0)throw new J("database.postgres.tables must be a non-empty array","database.postgres.tables");if(!i.clickhouse||typeof i.clickhouse!="object")throw new J("database.clickhouse must be an object","database.clickhouse");let a=i.clickhouse;if(typeof a.schemaChecksum!="string"||!a.schemaChecksum.trim())throw new J("database.clickhouse.schemaChecksum must be a non-empty string","database.clickhouse.schemaChecksum");if(!Array.isArray(a.tables)||a.tables.length===0)throw new J("database.clickhouse.tables must be a non-empty array","database.clickhouse.tables");if(!t.capabilities||typeof t.capabilities!="object")throw new J("capabilities must be an object","capabilities");let s=t.capabilities;if(!Array.isArray(s.publicTools)||s.publicTools.length===0)throw new J("capabilities.publicTools must be a non-empty array","capabilities.publicTools");if(!Array.isArray(s.paymentRails)||s.paymentRails.length===0)throw new J("capabilities.paymentRails must be a non-empty array","capabilities.paymentRails");if(!Array.isArray(s.protocols)||s.protocols.length===0)throw new J("capabilities.protocols must be a non-empty array","capabilities.protocols");if(!Array.isArray(s.rolloutFlags)||s.rolloutFlags.length===0)throw new J("capabilities.rolloutFlags must be a non-empty array","capabilities.rolloutFlags");if(!t.providers||typeof t.providers!="object"||Array.isArray(t.providers))throw new J("providers must be an object","providers");let c=t.providers,d=["turnkey","postgres","clickhouse","redis","sentry"];for(let p of d)if(!c[p]||typeof c[p]!="object")throw new J(`Missing required provider assertion "${p}"`,`providers.${p}`);for(let[p,m]of Object.entries(c)){let w=m;if(w.configuration!==void 0){if(!Array.isArray(w.configuration))throw new J(`providers.${p}.configuration must be an array`,`providers.${p}.configuration`);w.configuration.forEach((v,_)=>{let A=`providers.${p}.configuration[${_}]`;if(!v||typeof v!="object"||Array.isArray(v))throw new J(`${A} must be an object`,A);let j=v;for(let Q of Object.keys(j))if(!Qe.PROVIDER_CONFIGURATION_VARIABLE_KEYS.includes(Q))throw new J(`${A} carries unexpected key "${Q}"; only variable names and registry metadata belong in the manifest`,A);if(typeof j.name!="string"||!/^[A-Z][A-Z0-9_]*$/.test(j.name))throw new J(`${A}.name must be an environment variable name`,`${A}.name`);if(typeof j.sensitivity!="string"||!j.sensitivity.trim())throw new J(`${A}.sensitivity must be a non-empty string`,`${A}.sensitivity`);if(!Array.isArray(j.owners)||j.owners.some(Q=>typeof Q!="string"))throw new J(`${A}.owners must be an array of service names`,`${A}.owners`);if(typeof j.consumer!="string"||!j.consumer.trim())throw new J(`${A}.consumer must be a non-empty string`,`${A}.consumer`)})}}if(!t.canaries||typeof t.canaries!="object"||Array.isArray(t.canaries))throw new J("canaries must be an object","canaries");let l=t.canaries;if(!l.ceremonyCanary7590||typeof l.ceremonyCanary7590!="object")throw new J('Missing required canary "ceremonyCanary7590"',"canaries.ceremonyCanary7590");if(!l.serviceHealthProbes||typeof l.serviceHealthProbes!="object")throw new J('Missing required canary "serviceHealthProbes"',"canaries.serviceHealthProbes");if(!t.docs||typeof t.docs!="object")throw new J("docs must be an object","docs");let u=t.docs;if(typeof u.canonicalDocsVersion!="string"||!u.canonicalDocsVersion.trim())throw new J("docs.canonicalDocsVersion must be a non-empty string","docs.canonicalDocsVersion");if(!Array.isArray(t.rollbackClassification)||t.rollbackClassification.length===0)throw new J("rollbackClassification must be a non-empty array","rollbackClassification");let f=new Set(["schema","credentials","provider_effects","money_state"]),h=new Set;for(let p of t.rollbackClassification){if(!p||typeof p!="object")throw new J("rollbackClassification item must be an object","rollbackClassification");let m=p;if(m.classification!=="safe_rollback"&&m.classification!=="forward_fix_required")throw new J(`Invalid classification "${m.classification}" for step "${m.step}"`,"rollbackClassification");typeof m.category=="string"&&h.add(m.category)}for(let p of f)if(!h.has(p))throw new J(`rollbackClassification must cover category "${p}"`,"rollbackClassification");return Hg(t),(0,p6.canonicalJsonValue)(e)}function Hg(e,t=""){if(e!=null){if(typeof e=="string"){if(/Bearer\s+[A-Za-z0-9_-]{20,}/i.test(e))throw new J(`Bearer token detected in manifest at ${t}`);if(/-----BEGIN\s+(?:RSA|EC|PRIVATE)\s+KEY-----/i.test(e))throw new J(`Private key detected in manifest at ${t}`);if(/^(?:postgres|postgresql|redis|mongodb):\/\/[^:]+:[^@]+@/i.test(e))throw new J(`Credential-bearing connection URL detected in manifest at ${t}`);return}if(Array.isArray(e)){for(let n=0;n<e.length;n++)Hg(e[n],`${t}[${n}]`);return}if(typeof e=="object")for(let[n,r]of Object.entries(e))Hg(r,t?`${t}.${n}`:n)}}});var Gr=y(g=>{"use strict";Object.defineProperty(g,"__esModule",{value:!0});g.compareCanonicalKeys=g.assertCanonicalOpaqueId=g.CANONICAL_OPAQUE_ID_PATTERN=g.CANONICAL_OPAQUE_ID_MAX_BYTES=g.canonicalJson=g.parseAgentSelector=g.normalizeAgentName=g.computeAgentSelection=g.fetchWithTimeout=g.DEFAULT_FETCH_TIMEOUT_MS=g.resolveDeploymentEnvClass=g.resolveClickhouseEnvBinding=g.normalizeRailEnvironmentValue=g.isPublicPreviewRailEnvironment=g.isLiveVgsEnvironment=g.isExplicitProductionRailEnvironment=g.detectDeploymentEnvNodeEnvMismatch=g.clickhouseDatabaseHasStagingMarker=g.validateCardPaymentEventInsertRow=g.refreshCardPaymentAttemptProjection=g.insertCardPaymentLifecycleEventWithId=g.insertCardPaymentLifecycleEvent=g.assertValidCardPaymentAttemptStatus=g.CardPaymentDbValidationError=g.requiresProviderProvenance=g.requiredProvenanceFor=g.reduceCardPaymentEvents=g.provenanceOfSource=g.isOwnerAttestationVerdict=g.OWNER_ATTESTATION_VERDICTS=g.CARD_PAYMENT_EVENT_REQUIRED_PROVENANCE=g.CARD_PAYMENT_SOURCE_PROVENANCE=g.CARD_PAYMENT_PROVENANCES=g.CARD_PAYMENT_PROCESSOR_TRUTH_EVENT_TYPES=g.CARD_PAYMENT_SOURCES=g.CARD_PAYMENT_PROCESSORS=g.CARD_PAYMENT_INTENTS=g.CARD_PAYMENT_EVENT_TYPES=g.CARD_PAYMENT_ATTEMPT_STATUSES=g.parseAccountOperationReceipt=g.ACCOUNT_OPERATION_RECEIPT_SCHEMA_VERSION=g.ACCOUNT_OPERATION_PROOF_LEVELS=g.ACCOUNT_OPERATION_OUTCOMES=g.ACCOUNT_OPERATION_EVIDENCE_TYPES=g.checkTvcPinParity=g.TVC_SIGNER_POLICY_CONTRACT_VERSION=g.tvcProviderCapacityEvidence=g.TVC_PROVIDER_WARN_THRESHOLD=g.parseTvcProviderCapacityEvidence=g.TURNKEY_SUBORG_RESOURCE_LIMITS=void 0;g.validateReleaseManifest=g.ReleaseManifestValidationError=g.RELEASE_MANIFEST_SCHEMA_VERSION=g.PROVIDER_CONFIGURATION_VARIABLE_KEYS=g.ACTIVE_RAILWAY_SERVICES=g.claimBindingMode=g.runtimesMatch=g.runtimeMatchAliases=g.canonicalRuntimeId=g.runtimeLabel=g.progressLadder=g.SETUP_DEFAULT_PER_PURCHASE_CENTS=g.SETUP_DEFAULT_DAILY_CENTS=g.SETUP_DEFAULT_AGGREGATE_CENTS=g.PROTECTED_CARD_MAX_DRAWS=g.validateEncryptionKey=g.isPgcryptoIntegrityError=g.encryptSqlFragment=g.encrypt=g.encodeWireFormat=g.decryptSqlFragment=g.decrypt=g.decodeWireFormat=g.PgEncryptionWireFormatError=g.PgEncryptionKeyMissingError=g.PgEncryptionError=g.PgDecryptionFailedError=g.PG_ENCRYPTION_WIRE_VERSIONS=g.ENCRYPTION_KEY_MIN_BYTES=g.utf8ByteLength=g.isCanonicalText=g.isCanonicalOpaqueId=void 0;var Vl=BS();Object.defineProperty(g,"TURNKEY_SUBORG_RESOURCE_LIMITS",{enumerable:!0,get:function(){return Vl.TURNKEY_SUBORG_RESOURCE_LIMITS}});Object.defineProperty(g,"parseTvcProviderCapacityEvidence",{enumerable:!0,get:function(){return Vl.parseTvcProviderCapacityEvidence}});Object.defineProperty(g,"TVC_PROVIDER_WARN_THRESHOLD",{enumerable:!0,get:function(){return Vl.TVC_PROVIDER_WARN_THRESHOLD}});Object.defineProperty(g,"tvcProviderCapacityEvidence",{enumerable:!0,get:function(){return Vl.tvcProviderCapacityEvidence}});var m6=GS();Object.defineProperty(g,"TVC_SIGNER_POLICY_CONTRACT_VERSION",{enumerable:!0,get:function(){return m6.TVC_SIGNER_POLICY_CONTRACT_VERSION}});var g6=zS();Object.defineProperty(g,"checkTvcPinParity",{enumerable:!0,get:function(){return g6.checkTvcPinParity}});var nc=up();Object.defineProperty(g,"ACCOUNT_OPERATION_EVIDENCE_TYPES",{enumerable:!0,get:function(){return nc.ACCOUNT_OPERATION_EVIDENCE_TYPES}});Object.defineProperty(g,"ACCOUNT_OPERATION_OUTCOMES",{enumerable:!0,get:function(){return nc.ACCOUNT_OPERATION_OUTCOMES}});Object.defineProperty(g,"ACCOUNT_OPERATION_PROOF_LEVELS",{enumerable:!0,get:function(){return nc.ACCOUNT_OPERATION_PROOF_LEVELS}});Object.defineProperty(g,"ACCOUNT_OPERATION_RECEIPT_SCHEMA_VERSION",{enumerable:!0,get:function(){return nc.ACCOUNT_OPERATION_RECEIPT_SCHEMA_VERSION}});Object.defineProperty(g,"parseAccountOperationReceipt",{enumerable:!0,get:function(){return nc.parseAccountOperationReceipt}});var et=Mg();Object.defineProperty(g,"CARD_PAYMENT_ATTEMPT_STATUSES",{enumerable:!0,get:function(){return et.CARD_PAYMENT_ATTEMPT_STATUSES}});Object.defineProperty(g,"CARD_PAYMENT_EVENT_TYPES",{enumerable:!0,get:function(){return et.CARD_PAYMENT_EVENT_TYPES}});Object.defineProperty(g,"CARD_PAYMENT_INTENTS",{enumerable:!0,get:function(){return et.CARD_PAYMENT_INTENTS}});Object.defineProperty(g,"CARD_PAYMENT_PROCESSORS",{enumerable:!0,get:function(){return et.CARD_PAYMENT_PROCESSORS}});Object.defineProperty(g,"CARD_PAYMENT_SOURCES",{enumerable:!0,get:function(){return et.CARD_PAYMENT_SOURCES}});Object.defineProperty(g,"CARD_PAYMENT_PROCESSOR_TRUTH_EVENT_TYPES",{enumerable:!0,get:function(){return et.CARD_PAYMENT_PROCESSOR_TRUTH_EVENT_TYPES}});Object.defineProperty(g,"CARD_PAYMENT_PROVENANCES",{enumerable:!0,get:function(){return et.CARD_PAYMENT_PROVENANCES}});Object.defineProperty(g,"CARD_PAYMENT_SOURCE_PROVENANCE",{enumerable:!0,get:function(){return et.CARD_PAYMENT_SOURCE_PROVENANCE}});Object.defineProperty(g,"CARD_PAYMENT_EVENT_REQUIRED_PROVENANCE",{enumerable:!0,get:function(){return et.CARD_PAYMENT_EVENT_REQUIRED_PROVENANCE}});Object.defineProperty(g,"OWNER_ATTESTATION_VERDICTS",{enumerable:!0,get:function(){return et.OWNER_ATTESTATION_VERDICTS}});Object.defineProperty(g,"isOwnerAttestationVerdict",{enumerable:!0,get:function(){return et.isOwnerAttestationVerdict}});Object.defineProperty(g,"provenanceOfSource",{enumerable:!0,get:function(){return et.provenanceOfSource}});Object.defineProperty(g,"reduceCardPaymentEvents",{enumerable:!0,get:function(){return et.reduceCardPaymentEvents}});Object.defineProperty(g,"requiredProvenanceFor",{enumerable:!0,get:function(){return et.requiredProvenanceFor}});Object.defineProperty(g,"requiresProviderProvenance",{enumerable:!0,get:function(){return et.requiresProviderProvenance}});var va=c0();Object.defineProperty(g,"CardPaymentDbValidationError",{enumerable:!0,get:function(){return va.CardPaymentDbValidationError}});Object.defineProperty(g,"assertValidCardPaymentAttemptStatus",{enumerable:!0,get:function(){return va.assertValidCardPaymentAttemptStatus}});Object.defineProperty(g,"insertCardPaymentLifecycleEvent",{enumerable:!0,get:function(){return va.insertCardPaymentLifecycleEvent}});Object.defineProperty(g,"insertCardPaymentLifecycleEventWithId",{enumerable:!0,get:function(){return va.insertCardPaymentLifecycleEventWithId}});Object.defineProperty(g,"refreshCardPaymentAttemptProjection",{enumerable:!0,get:function(){return va.refreshCardPaymentAttemptProjection}});Object.defineProperty(g,"validateCardPaymentEventInsertRow",{enumerable:!0,get:function(){return va.validateCardPaymentEventInsertRow}});var Br=p0();Object.defineProperty(g,"clickhouseDatabaseHasStagingMarker",{enumerable:!0,get:function(){return Br.clickhouseDatabaseHasStagingMarker}});Object.defineProperty(g,"detectDeploymentEnvNodeEnvMismatch",{enumerable:!0,get:function(){return Br.detectDeploymentEnvNodeEnvMismatch}});Object.defineProperty(g,"isExplicitProductionRailEnvironment",{enumerable:!0,get:function(){return Br.isExplicitProductionRailEnvironment}});Object.defineProperty(g,"isLiveVgsEnvironment",{enumerable:!0,get:function(){return Br.isLiveVgsEnvironment}});Object.defineProperty(g,"isPublicPreviewRailEnvironment",{enumerable:!0,get:function(){return Br.isPublicPreviewRailEnvironment}});Object.defineProperty(g,"normalizeRailEnvironmentValue",{enumerable:!0,get:function(){return Br.normalizeRailEnvironmentValue}});Object.defineProperty(g,"resolveClickhouseEnvBinding",{enumerable:!0,get:function(){return Br.resolveClickhouseEnvBinding}});Object.defineProperty(g,"resolveDeploymentEnvClass",{enumerable:!0,get:function(){return Br.resolveDeploymentEnvClass}});var A0=h0();Object.defineProperty(g,"DEFAULT_FETCH_TIMEOUT_MS",{enumerable:!0,get:function(){return A0.DEFAULT_FETCH_TIMEOUT_MS}});Object.defineProperty(g,"fetchWithTimeout",{enumerable:!0,get:function(){return A0.fetchWithTimeout}});var Vg=g0();Object.defineProperty(g,"computeAgentSelection",{enumerable:!0,get:function(){return Vg.computeAgentSelection}});Object.defineProperty(g,"normalizeAgentName",{enumerable:!0,get:function(){return Vg.normalizeAgentName}});Object.defineProperty(g,"parseAgentSelector",{enumerable:!0,get:function(){return Vg.parseAgentSelector}});var y6=Pr();Object.defineProperty(g,"canonicalJson",{enumerable:!0,get:function(){return y6.canonicalJson}});var Qi=xf();Object.defineProperty(g,"CANONICAL_OPAQUE_ID_MAX_BYTES",{enumerable:!0,get:function(){return Qi.CANONICAL_OPAQUE_ID_MAX_BYTES}});Object.defineProperty(g,"CANONICAL_OPAQUE_ID_PATTERN",{enumerable:!0,get:function(){return Qi.CANONICAL_OPAQUE_ID_PATTERN}});Object.defineProperty(g,"assertCanonicalOpaqueId",{enumerable:!0,get:function(){return Qi.assertCanonicalOpaqueId}});Object.defineProperty(g,"compareCanonicalKeys",{enumerable:!0,get:function(){return Qi.compareCanonicalKeys}});Object.defineProperty(g,"isCanonicalOpaqueId",{enumerable:!0,get:function(){return Qi.isCanonicalOpaqueId}});Object.defineProperty(g,"isCanonicalText",{enumerable:!0,get:function(){return Qi.isCanonicalText}});Object.defineProperty(g,"utf8ByteLength",{enumerable:!0,get:function(){return Qi.utf8ByteLength}});var ht=w0();Object.defineProperty(g,"ENCRYPTION_KEY_MIN_BYTES",{enumerable:!0,get:function(){return ht.ENCRYPTION_KEY_MIN_BYTES}});Object.defineProperty(g,"PG_ENCRYPTION_WIRE_VERSIONS",{enumerable:!0,get:function(){return ht.PG_ENCRYPTION_WIRE_VERSIONS}});Object.defineProperty(g,"PgDecryptionFailedError",{enumerable:!0,get:function(){return ht.PgDecryptionFailedError}});Object.defineProperty(g,"PgEncryptionError",{enumerable:!0,get:function(){return ht.PgEncryptionError}});Object.defineProperty(g,"PgEncryptionKeyMissingError",{enumerable:!0,get:function(){return ht.PgEncryptionKeyMissingError}});Object.defineProperty(g,"PgEncryptionWireFormatError",{enumerable:!0,get:function(){return ht.PgEncryptionWireFormatError}});Object.defineProperty(g,"decodeWireFormat",{enumerable:!0,get:function(){return ht.decodeWireFormat}});Object.defineProperty(g,"decrypt",{enumerable:!0,get:function(){return ht.decrypt}});Object.defineProperty(g,"decryptSqlFragment",{enumerable:!0,get:function(){return ht.decryptSqlFragment}});Object.defineProperty(g,"encodeWireFormat",{enumerable:!0,get:function(){return ht.encodeWireFormat}});Object.defineProperty(g,"encrypt",{enumerable:!0,get:function(){return ht.encrypt}});Object.defineProperty(g,"encryptSqlFragment",{enumerable:!0,get:function(){return ht.encryptSqlFragment}});Object.defineProperty(g,"isPgcryptoIntegrityError",{enumerable:!0,get:function(){return ht.isPgcryptoIntegrityError}});Object.defineProperty(g,"validateEncryptionKey",{enumerable:!0,get:function(){return ht.validateEncryptionKey}});var rc=E0();Object.defineProperty(g,"PROTECTED_CARD_MAX_DRAWS",{enumerable:!0,get:function(){return rc.PROTECTED_CARD_MAX_DRAWS}});Object.defineProperty(g,"SETUP_DEFAULT_AGGREGATE_CENTS",{enumerable:!0,get:function(){return rc.SETUP_DEFAULT_AGGREGATE_CENTS}});Object.defineProperty(g,"SETUP_DEFAULT_DAILY_CENTS",{enumerable:!0,get:function(){return rc.SETUP_DEFAULT_DAILY_CENTS}});Object.defineProperty(g,"SETUP_DEFAULT_PER_PURCHASE_CENTS",{enumerable:!0,get:function(){return rc.SETUP_DEFAULT_PER_PURCHASE_CENTS}});Object.defineProperty(g,"progressLadder",{enumerable:!0,get:function(){return rc.progressLadder}});var ic=v0();Object.defineProperty(g,"runtimeLabel",{enumerable:!0,get:function(){return ic.runtimeLabel}});Object.defineProperty(g,"canonicalRuntimeId",{enumerable:!0,get:function(){return ic.canonicalRuntimeId}});Object.defineProperty(g,"runtimeMatchAliases",{enumerable:!0,get:function(){return ic.runtimeMatchAliases}});Object.defineProperty(g,"runtimesMatch",{enumerable:!0,get:function(){return ic.runtimesMatch}});Object.defineProperty(g,"claimBindingMode",{enumerable:!0,get:function(){return ic.claimBindingMode}});var oc=b0();Object.defineProperty(g,"ACTIVE_RAILWAY_SERVICES",{enumerable:!0,get:function(){return oc.ACTIVE_RAILWAY_SERVICES}});Object.defineProperty(g,"PROVIDER_CONFIGURATION_VARIABLE_KEYS",{enumerable:!0,get:function(){return oc.PROVIDER_CONFIGURATION_VARIABLE_KEYS}});Object.defineProperty(g,"RELEASE_MANIFEST_SCHEMA_VERSION",{enumerable:!0,get:function(){return oc.RELEASE_MANIFEST_SCHEMA_VERSION}});Object.defineProperty(g,"ReleaseManifestValidationError",{enumerable:!0,get:function(){return oc.ReleaseManifestValidationError}});Object.defineProperty(g,"validateReleaseManifest",{enumerable:!0,get:function(){return oc.validateReleaseManifest}})});var sc=y(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.VALID_VISA_CLI_PRERELEASE_RE=Qt.DEFAULT_MIN_COMPATIBLE_CLI_VERSION=void 0;Qt.hasUnsupportedVisaCliPrerelease=I6;Qt.isSemverVersion=T6;Qt.isStrictlyNewer=P6;Qt.parseCliVersion=ac;Qt.DEFAULT_MIN_COMPATIBLE_CLI_VERSION="5.0.0-rc.408";var S6=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;Qt.VALID_VISA_CLI_PRERELEASE_RE=/^rc\.\d+$/;function I6(e){let t=ac(e);return t!==null&&t.pre!==null&&!Qt.VALID_VISA_CLI_PRERELEASE_RE.test(t.pre)}function T6(e){return ac(e)!==null}function P6(e,t){let n=ac(e),r=ac(t);if(!n||!r)return!1;for(let i=0;i<3;i++)if(n.main[i]!==r.main[i])return n.main[i]>r.main[i];return n.pre&&!r.pre?!1:!n.pre&&r.pre?!0:!n.pre&&!r.pre?!1:k6(n.pre,r.pre)>0}function ac(e){if(typeof e!="string")return null;let n=e.trim().replace(/^v/,"").match(S6);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function k6(e,t){let n=e.split("."),r=t.split("."),i=Math.max(n.length,r.length);for(let o=0;o<i;o++){if(o>=n.length)return-1;if(o>=r.length)return 1;let a=n[o],s=r[o],c=/^\d+$/.test(a),d=/^\d+$/.test(s);if(c&&d){let l=Number(a)-Number(s);if(l!==0)return l}else{if(c)return-1;if(d)return 1;if(a<s)return-1;if(a>s)return 1}}return 0}});var dy=y(Fe=>{"use strict";Object.defineProperty(Fe,"__esModule",{value:!0});Fe.DEFAULT_POP_MAX_AGE_SEC=Fe.UNIVERSAL_AGENT_OPERATION_AUDIENCE=Fe.POP_JWT_TYP=Fe.createPopProofWithSigner=void 0;Fe.randomPopNonce=i4;Fe.createPopProof=yI;Fe.createAgentOperationPopProof=o4;Fe.verifyAgentOperationPopProof=a4;Fe.verifyPopProof=_I;var n4=require("node:crypto"),fI=pg(),r4=qi(),pI=qs(),hI=jn(),mI=as();Object.defineProperty(Fe,"createPopProofWithSigner",{enumerable:!0,get:function(){return mI.createPopProofWithSigner}});Object.defineProperty(Fe,"POP_JWT_TYP",{enumerable:!0,get:function(){return mI.POP_JWT_TYP}});var gI=as();Fe.UNIVERSAL_AGENT_OPERATION_AUDIENCE="visa-agent-operations:v1";Fe.DEFAULT_POP_MAX_AGE_SEC=hI.POP_MAX_AGE_SECONDS;function i4(){return(0,n4.randomBytes)(32).toString("base64url")}async function yI(e,t){if("createProof"in e)return e.createProof(t);let r={cnf:{jwk:{kty:e.publicJwk.kty,crv:e.publicJwk.crv,x:e.publicJwk.x}},nonce:t.nonce,aud:t.audience,iat:t.nowSec};return t.intentHash!==void 0&&(r.int=t.intentHash),t.runtimeCertificate!==void 0&&(r.rkc=t.runtimeCertificate),(0,pI.signJwt)(e.privateJwk,{kid:e.jkt,typ:gI.POP_JWT_TYP},r)}function o4(e,t){return yI(e,{nonce:t.operationId,audience:t.audience,nowSec:t.nowSec,intentHash:t.intentHash,...t.runtimeCertificate===void 0?{}:{runtimeCertificate:t.runtimeCertificate}})}function a4(e,t){return _I(e,{expectedNonce:t.operationId,audience:t.audience,nowSec:t.nowSec,expectedIntentHash:t.expectedIntentHash,...t.maxAgeSec===void 0?{}:{maxAgeSec:t.maxAgeSec}})}function s4(e){return typeof e=="object"&&e!==null&&typeof e.kty=="string"&&typeof e.crv=="string"&&typeof e.x=="string"}async function _I(e,t){let n=(0,pI.decodeJwt)(e);if(!n)return{ok:!1,reason:"malformed"};if(n.header.alg!=="EdDSA")return{ok:!1,reason:"bad_alg"};if(n.header.typ!==gI.POP_JWT_TYP)return{ok:!1,reason:"typ_mismatch"};let r=n.claims.cnf?.jwk;if(!s4(r)||r.kty!=="OKP"||r.crv!=="Ed25519")return{ok:!1,reason:"bad_cnf_key"};try{let s=await(0,fI.importJWK)({kty:r.kty,crv:r.crv,x:r.x},"EdDSA");await(0,fI.compactVerify)(e,s)}catch{return{ok:!1,reason:"bad_signature"}}let i=(0,r4.computeJkt)(r);if(n.claims.nonce!==t.expectedNonce)return{ok:!1,reason:"nonce_mismatch"};if(n.claims.aud!==t.audience)return{ok:!1,reason:"aud_mismatch"};if(t.expectedIntentHash!==void 0&&n.claims.int!==t.expectedIntentHash)return{ok:!1,reason:"intent_mismatch"};let o=n.claims.iat;if(typeof o!="number"||!Number.isFinite(o))return{ok:!1,reason:"bad_iat"};if(o>t.nowSec+hI.CLOCK_SKEW_SECONDS)return{ok:!1,reason:"not_yet_valid"};let a=t.maxAgeSec??Fe.DEFAULT_POP_MAX_AGE_SEC;return t.nowSec-o>a?{ok:!1,reason:"stale"}:n.claims.rkc!==void 0&&typeof n.claims.rkc!="string"?{ok:!1,reason:"bad_runtime_certificate"}:{ok:!0,jkt:i,...typeof n.claims.rkc=="string"?{runtimeCertificate:n.claims.rkc}:{}}}});var py=y(Ie=>{"use strict";Object.defineProperty(Ie,"__esModule",{value:!0});Ie.IDENTITY_TAP_LEASE_REQUEST_AUDIENCE=Ie.IDENTITY_TAP_LEASE_AUDIENCE=Ie.IDENTITY_TAP_PURPOSE=Ie.IDENTITY_TAP_PROFILE=void 0;Ie.prepareIdentityTapDelegation=AI;Ie.verifyIdentityTapDelegation=SI;Ie.issueIdentityTapLease=f4;Ie.identityTapLeaseRequestIntentHash=fy;Ie.createIdentityTapLeaseRequestProof=h4;Ie.verifyIdentityTapLeaseRequestProof=m4;var wI=require("node:crypto"),c4=Gr(),d4=qi(),EI=qs(),ly=Uo(),vI=dy(),l4=vg();Ie.IDENTITY_TAP_PROFILE="identity-tap-v1";Ie.IDENTITY_TAP_PURPOSE="tap_signature_base";Ie.IDENTITY_TAP_LEASE_AUDIENCE="urn:visa:tvc:identity-gate";Ie.IDENTITY_TAP_LEASE_REQUEST_AUDIENCE="visa-identity-lease-requests:v1";var uy=e=>typeof e=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(e),Xl=e=>Number.isSafeInteger(e)&&Number(e)>0,bI=e=>(0,wI.createHash)("sha256").update(e,"utf8").digest("base64url");function u4(e){if(typeof e!="string"||Buffer.byteLength(e)>32768)throw new Error("identity_tap_token_invalid");let t=e.split(".");if(t.length!==3||t.some(n=>!n||Buffer.from(n,"base64url").toString("base64url")!==n)||Buffer.from(t[2],"base64url").length!==64)throw new Error("identity_tap_token_invalid");return t}function AI(e){let{custody:t,rails:n,...r}=(0,l4.prepareRuntimeDelegation)({...e,signingModes:["eip3009:exact"],custody:"gate"}).claims,i={...r,v:1,purpose:Ie.IDENTITY_TAP_PURPOSE,signingModes:["tap"]};return{...(0,ly.prepareRootSignedJws)("visa-agent-runtime-delegation+jwt",e.rootKid,i),claims:i}}async function SI(e,t){let n=u4(e),r=await(0,EI.verifyJwtSignature)(e,t.ownerJwks);if(!r.ok)throw new Error("identity_tap_delegation_signature_invalid");let i=r.claims,o=t.ownerJwks.keys.find(s=>s.kid===t.expectedRootKid);if(!o||r.header.kid!==t.expectedRootKid||!Number.isSafeInteger(t.nowSec)||t.nowSec<0||!Number.isSafeInteger(i.iat)||!Number.isSafeInteger(i.exp)||i.iat>t.nowSec+30||i.exp<=t.nowSec)throw new Error("identity_tap_delegation_invalid");let a=AI({rootKid:t.expectedRootKid,rootPublicJwk:o,rootJkt:t.expectedRootJkt,agentId:t.expectedAgentId,runtimeId:t.expectedRuntimeId,runtimeJkt:t.expectedRuntimeJkt,leaseIssuerJkt:t.expectedLeaseIssuerJkt,network:t.expectedNetwork,delegationId:t.expectedDelegationId,nowSec:i.iat,ttlSeconds:i.exp-i.iat,maxLeaseTtlSeconds:i.maxLeaseTtlSeconds});if(n[0]+"."+n[1]!==a.signingInput)throw new Error("identity_tap_delegation_mismatch");return a.claims}async function f4(e){let t=await SI(e.delegationToken,e.verification),n=e.verification.nowSec,r=e.ttlSeconds??120,i=e.leaseId??(0,wI.randomUUID)();if(!Xl(e.generation)||!Xl(e.authorizationVersion)||!uy(e.authorizationId)||!uy(i)||!Xl(r)||r>120||!Number.isSafeInteger(e.authorityExpiresAt)||(0,d4.computeJkt)(e.signer.publicJwk)!==t.leaseIssuerJkt)throw new Error("identity_tap_lease_context_invalid");let o=Math.min(n+r,n+t.maxLeaseTtlSeconds,t.exp,e.authorityExpiresAt);if(!Number.isSafeInteger(o)||o<=n)throw new Error("identity_tap_lease_expired");let a={v:1,iss:t.leaseIssuerJkt,sub:t.sub,aud:Ie.IDENTITY_TAP_LEASE_AUDIENCE,jti:i,delegationId:t.jti,delegationHash:bI(e.delegationToken),rootJkt:t.iss,runtimeId:t.runtimeId,runtimeJkt:t.runtimeJkt,purpose:Ie.IDENTITY_TAP_PURPOSE,network:t.network,signingModes:["tap"],generation:e.generation,grantId:e.authorizationId,grantVersion:e.authorizationVersion,iat:n,nbf:n,exp:o},s=(0,ly.prepareRootSignedJws)("visa-agent-runtime-lease+jwt",e.signer.kid,a),c=(0,ly.completeRootSignedJws)(s.signingInput,await e.signer.sign(Buffer.from(s.signingInput)),"identity TAP lease");if(!(await(0,EI.verifyJwtSignature)(c,{keys:[e.signer.publicJwk]})).ok)throw new Error("identity_tap_lease_signer_invalid");return{lease:c,claims:a}}var p4=["v","profile","associationId","associationVersion","agentId","runtimeId","generation","authorizationId","authorizationVersion","requestId","signingMode"].sort();function fy(e){if(!e||typeof e!="object"||Object.keys(e).sort().join(",")!==p4.join(",")||e.v!==1||e.profile!==Ie.IDENTITY_TAP_PROFILE||e.signingMode!=="tap"||![e.associationId,e.agentId,e.runtimeId,e.authorizationId,e.requestId].every(uy)||![e.associationVersion,e.generation,e.authorizationVersion].every(Xl))throw new Error("identity_tap_lease_request_invalid");return bI((0,c4.canonicalJson)(e))}function h4(e,t,n){return(0,vI.createPopProofWithSigner)(e,{nonce:t.requestId,audience:Ie.IDENTITY_TAP_LEASE_REQUEST_AUDIENCE,intentHash:fy(t),nowSec:n})}async function m4(e,t,n,r){let i=await(0,vI.verifyAgentOperationPopProof)(e,{operationId:t.requestId,audience:Ie.IDENTITY_TAP_LEASE_REQUEST_AUDIENCE,expectedIntentHash:fy(t),nowSec:r,maxAgeSec:60});if(!i.ok||i.jkt!==n||i.runtimeCertificate!==void 0)throw new Error("identity_tap_lease_request_proof_invalid")}});var kI=y(ei=>{"use strict";Object.defineProperty(ei,"__esModule",{value:!0});ei.IDENTITY_DEVICE_HANDOFF_AUDIENCE=void 0;ei.identityDeviceProposalSha256=TI;ei.identityDeviceHandoffIntentHash=PI;ei.verifyIdentityDeviceHandoffProof=E4;var g4=require("node:crypto"),y4=Gr(),_4=qi(),w4=dy();ei.IDENTITY_DEVICE_HANDOFF_AUDIENCE="visa-device-handoff:v1";var pc=e=>typeof e=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(e),II=e=>typeof e=="string"&&Buffer.from(e,"base64url").length===32&&Buffer.from(e,"base64url").toString("base64url")===e,ro=(e,t)=>e!==null&&typeof e=="object"&&!Array.isArray(e)&&Object.keys(e).sort().join(",")===t.sort().join(","),hy=e=>(0,g4.createHash)("sha256").update((0,y4.canonicalJson)(e)).digest("base64url");function TI(e){if(!ro(e,["associationId","associationVersion","agentId","rootJkt","runtimeId","runtimePublicJwk","runtimeJkt"])||![e.associationId,e.agentId,e.runtimeId].every(pc)||!Number.isSafeInteger(e.associationVersion)||e.associationVersion<1||![e.rootJkt,e.runtimeJkt].every(II)||e.rootJkt===e.runtimeJkt||!ro(e.runtimePublicJwk,["kty","crv","x"])||e.runtimePublicJwk.kty!=="OKP"||e.runtimePublicJwk.crv!=="Ed25519"||!II(e.runtimePublicJwk.x)||(0,_4.computeJkt)(e.runtimePublicJwk)!==e.runtimeJkt)throw new Error("identity_device_proposal_invalid");return hy(e)}function PI(e){if(!ro(e,["v","operation","requestId","handoffId","proposal","body"])||e.v!==1||!pc(e.requestId)||!pc(e.handoffId))throw new Error("identity_device_handoff_invalid");let t=TI(e.proposal);if(e.operation==="create"){if(e.requestId!==e.handoffId||!ro(e.body,[]))throw new Error("identity_device_handoff_invalid")}else if(e.operation==="read"){if(!ro(e.body,[]))throw new Error("identity_device_handoff_invalid")}else if(e.operation==="cancel"){if(!ro(e.body,["enrollmentRequestId","generation"])||!(e.body.enrollmentRequestId===null&&e.body.generation===null)&&(!pc(e.body.enrollmentRequestId)||!Number.isSafeInteger(e.body.generation)||e.body.generation<1))throw new Error("identity_device_handoff_invalid")}else if(e.operation==="proof"){if(!ro(e.body,["enrollmentRequestId","runtimeProof"])||!pc(e.body.enrollmentRequestId)||typeof e.body.runtimeProof!="string"||e.body.runtimeProof.length!==86||Buffer.from(e.body.runtimeProof,"base64url").length!==64||Buffer.from(e.body.runtimeProof,"base64url").toString("base64url")!==e.body.runtimeProof)throw new Error("identity_device_handoff_invalid")}else throw new Error("identity_device_handoff_invalid");return hy({v:1,operation:e.operation,handoffId:e.handoffId,proposalSha256:t,bodySha256:hy(e.body)})}async function E4(e,t,n){let r=await(0,w4.verifyAgentOperationPopProof)(e,{operationId:t.requestId,audience:ei.IDENTITY_DEVICE_HANDOFF_AUDIENCE,expectedIntentHash:PI(t),nowSec:n,maxAgeSec:60});if(!r.ok||r.jkt!==t.proposal.runtimeJkt||r.runtimeCertificate!==void 0)throw new Error("identity_device_handoff_proof_invalid")}});var XI=y(dr=>{"use strict";Object.defineProperty(dr,"__esModule",{value:!0});dr.IDENTITY_HOSTED_GATE_AUTHORIZATION_PURPOSES=void 0;dr.identityDeviceEnrollmentPreimage=zI;dr.verifyIdentityDeviceEnrollmentProof=R4;dr.prepareIdentityDeviceGateAuthorization=x4;dr.prepareIdentityHostedGateAuthorization=O4;var GI=require("node:crypto"),YI=Uo(),T4=Gr(),P4=qi(),k4=py(),C4=["v","profile","associationId","associationVersion","agentId","runtimeId","generation","requestId","runtimePublicJwk","runtimeJkt","rootJkt","certificateSha256","delegationSha256","gateAuthorizationSha256","iat","exp"].sort().join(","),Ey=e=>typeof e=="string"&&/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(e),vy=e=>Number.isSafeInteger(e)&&Number(e)>0,su=e=>typeof e=="string"&&Buffer.from(e,"base64url").length===32&&Buffer.from(e,"base64url").toString("base64url")===e;function zI(e){if(!e||Object.keys(e).sort().join(",")!==C4||e.v!==1||e.profile!==k4.IDENTITY_TAP_PROFILE||![e.associationId,e.agentId,e.runtimeId,e.requestId].every(Ey)||![e.associationVersion,e.generation].every(vy)||![e.runtimeJkt,e.rootJkt,e.certificateSha256,e.delegationSha256,e.gateAuthorizationSha256].every(su)||!e.runtimePublicJwk||Object.keys(e.runtimePublicJwk).sort().join(",")!=="crv,kty,x"||e.runtimePublicJwk.kty!=="OKP"||e.runtimePublicJwk.crv!=="Ed25519"||!su(e.runtimePublicJwk.x)||(0,P4.computeJkt)(e.runtimePublicJwk)!==e.runtimeJkt||e.runtimeJkt===e.rootJkt||!Number.isSafeInteger(e.iat)||e.iat<0||!Number.isSafeInteger(e.exp)||e.exp<=e.iat||e.exp-e.iat>600)throw new Error("identity_device_challenge_invalid");return Buffer.from("visa:authority:external-runtime-enrollment:v1\0"+(0,T4.canonicalJson)(e),"utf8")}function R4(e,t,n){let r=zI(e);if(!Number.isSafeInteger(n)||n<0||e.iat>n+5||e.exp<=n)throw new Error("identity_device_challenge_expired");if(typeof t!="string"||t.length!==86||Buffer.from(t,"base64url").toString("base64url")!==t||!(0,GI.verify)(null,r,(0,GI.createPublicKey)({key:e.runtimePublicJwk,format:"jwk"}),Buffer.from(t,"base64url")))throw new Error("identity_device_proof_invalid")}function x4(e){if(![e.rootJkt,e.identityPrincipalJkt].every(su)||![e.agentId,e.authorizationId].every(Ey)||!vy(e.generation)||!Number.isSafeInteger(e.nowSec)||e.nowSec<0||!Number.isSafeInteger(e.expiresAt)||e.expiresAt<=e.nowSec||e.expiresAt-e.nowSec>366*86400||![e.rootKid,e.ownerSuborganizationId].every(n=>typeof n=="string"&&/^[\x21-\x7e]{1,256}$/.test(n)))throw new Error("identity_device_standing_authorization_invalid");let t={v:1,iss:e.rootJkt,sub:e.agentId,aud:"urn:visa:tvc:identity-gate",jti:e.authorizationId,ownerSuborganizationId:e.ownerSuborganizationId,turnkeyRootKeyId:e.rootKid,identityPrincipalJkt:e.identityPrincipalJkt,purposes:["tap_signature_base"],generation:e.generation,maxTtlSecondsByPurpose:{tap_signature_base:480},iat:e.nowSec,nbf:e.nowSec,exp:e.expiresAt};return{...(0,YI.prepareRootSignedJws)("visa-agent-identity-gate-authorization+jwt",e.rootKid,t),claims:t}}dr.IDENTITY_HOSTED_GATE_AUTHORIZATION_PURPOSES=["runtime_presence_pop","tap_signature_base"];function O4(e){if(![e.rootJkt,e.identityPrincipalJkt].every(su)||![e.agentId,e.authorizationId].every(Ey)||!vy(e.generation)||!Number.isSafeInteger(e.nowSec)||e.nowSec<0||!Number.isSafeInteger(e.expiresAt)||e.expiresAt<=e.nowSec||e.expiresAt-e.nowSec>366*86400||![e.rootKid,e.ownerSuborganizationId].every(n=>typeof n=="string"&&/^[\x21-\x7e]{1,256}$/.test(n)))throw new Error("identity_hosted_standing_authorization_invalid");let t={v:1,iss:e.rootJkt,sub:e.agentId,aud:"urn:visa:tvc:identity-gate",jti:e.authorizationId,ownerSuborganizationId:e.ownerSuborganizationId,turnkeyRootKeyId:e.rootKid,identityPrincipalJkt:e.identityPrincipalJkt,purposes:[...dr.IDENTITY_HOSTED_GATE_AUTHORIZATION_PURPOSES],generation:e.generation,maxTtlSecondsByPurpose:{runtime_presence_pop:120,tap_signature_base:480},iat:e.nowSec,nbf:e.nowSec,exp:e.expiresAt};return{...(0,YI.prepareRootSignedJws)("visa-agent-identity-gate-authorization+jwt",e.rootKid,t),claims:t}}});var xu=require("node:child_process"),Ou=require("node:crypto"),Ne=require("node:fs"),Ha=require("node:path");var Mc=x(require("fs")),Ju=require("node:net"),r_=x(require("os")),i_=x(require("path"));var Nc=x(require("fs")),Du=x(require("path")),Xy=x(require("os")),Oc=class{static ensureConfigDir(){let t=this.getConfigDir();Nc.existsSync(t)||Nc.mkdirSync(t,{recursive:!0,mode:448})}static getConfigDir(){let t=process.env.VISA_CLI_HOME;return typeof t=="string"&&t.trim().length>0?Du.join(t,".visa-mcp"):Du.join(Xy.homedir(),".visa-mcp")}};var rt=x(require("fs")),Lu=x(require("path")),Zy=x(require("os")),Mu=Lu.join(Zy.homedir(),".visa-mcp"),Va=Lu.join(Mu,"mcp-server.log"),bP=5*1024*1024,$a=null;function AP(){rt.existsSync(Mu)||rt.mkdirSync(Mu,{recursive:!0,mode:448})}function SP(){if(!$a){if(AP(),rt.existsSync(Va)&&rt.statSync(Va).size>bP){let t=Va+".1";rt.existsSync(t)&&rt.unlinkSync(t),rt.renameSync(Va,t)}$a=rt.createWriteStream(Va,{flags:"a"})}return $a}function IP(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"}function Dc(e,...t){let n=new Date().toISOString(),r=t.map(o=>typeof o=="string"?o:JSON.stringify(o,null,2)).join(" "),i=`[${n}] [${e}] ${r}
|
|
26
|
+
`;IP(e)&&process.stderr.write(i),SP().write(i)}var R={debug:(...e)=>Dc("DEBUG",...e),info:(...e)=>Dc("INFO",...e),warn:(...e)=>Dc("WARN",...e),error:(...e)=>Dc("ERROR",...e)};function Qy(e=2e3){let t=$a;return t?($a=null,new Promise(n=>{let r=setTimeout(n,e);r.unref?.(),t.end(()=>{clearTimeout(r),n()})})):Promise.resolve()}function t_(e){let t=r_.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}var PP="settings.json",kP="must use https unless it points at localhost/loopback for local development";function CP(){return i_.join(Oc.getConfigDir(),PP)}function o_(e){if((0,Ju.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function RP(e){let t=e.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(!t)return!1;let n=Number.parseInt(t[1],16),r=Number.parseInt(t[2],16);if(!Number.isFinite(n)||!Number.isFinite(r))return!1;let i=[n>>8&255,n&255,r>>8&255,r&255].join(".");return o_(i)}function xP(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let n=(0,Ju.isIP)(t);return n===4?o_(t):n===6?t==="::1"||RP(t):!1}function n_(e,t="auth.serverUrl"){let n;try{n=new URL(e)}catch{throw new Error(`${t} must be a valid URL (got: ${JSON.stringify(e)})`)}if(n.username||n.password)throw new Error(`${t} must not include username or password credentials`);if(n.protocol!=="https:"&&!(n.protocol==="http:"&&xP(n.hostname)))throw new Error(`${t} ${kP}`)}function OP(){let e=CP();if(!Mc.existsSync(e))return{};try{let t=Mc.readFileSync(e,"utf-8"),n=JSON.parse(t);return!n||typeof n!="object"||Array.isArray(n)?(R.warn("settings:corrupt",{path:t_(e),reason:"not_object"}),{}):n}catch(t){return R.warn("settings:corrupt",{path:t_(e),error:t?.message||String(t)}),{}}}function NP(e){let t=OP()[e];return typeof t=="string"?t:void 0}var a_="https://auth.visacli.sh",s_="https://auth-visa-code-preview.up.railway.app";function DP(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function MP(){try{let e=e_();return DP(e.version)}catch{return!1}}function LP(e){return e.envVar!==void 0&&e.envVar!==""?(n_(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(n_(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?s_:a_}var c_="https://app.visacli.sh",d_="https://web-visa-code-preview.up.railway.app";function Uu(e=process.env){let t=LP({envVar:e.VISA_AUTH_URL,settingValue:NP("auth.serverUrl"),isPrerelease:MP()}),n=new URL(t).origin,i=e.VISA_VERIFY_WEB_URL?.trim()||(n===s_?d_:n===a_?c_:n);for(;i.endsWith("/");)i=i.slice(0,-1);return{authUrl:t,webUrl:i}}function Nn(){return Uu().authUrl}var JP="/agent/enroll";function l_(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function on(e=process.env){return Uu(e).webUrl}function u_(e){return`${l_(e)}${JP}`}var f_="one-code-terminal-sign-in";async function p_(e,t){let n=t?.fetchImpl??fetch,r=t?.maxAttempts??3,i=t?.timeoutMs??5e3,o=t?.sleep??(l=>new Promise(u=>setTimeout(u,l))),a=`${l_(e)}/api/agent-enroll/health`,s=null,c=null;for(let l=1;l<=r;l++){t?.onProgress?.(l,r,a);try{if(c=await n(a,{method:"GET",headers:{accept:"application/json"},signal:AbortSignal.timeout(i)}),c.ok||c.status<500)break;l<r&&await o(l*100)}catch(u){c=null,s=u,l<r&&await o(l*100)}}if(!c){let l=s instanceof Error?s.message:String(s??"network error");return{ready:!1,kind:"network",warning:`Could not reach ${a}: ${l} \u2014 the link may not work yet.`,healthUrl:a}}if(!c.ok)return c.status<500?{ready:!1,kind:"client",warning:`V4 sign-in is unavailable on this deployment (${c.status} at ${a}); refusing to open the retired GitHub flow.`,healthUrl:a}:{ready:!1,kind:"server",warning:`V4 sign-in readiness check failed (${c.status}) at ${a} \u2014 the link may not work yet.`,healthUrl:a};let d=await c.json().catch(()=>null);return d?.clients?.auth!=="turnkey"?{ready:!1,kind:"auth_mode_mismatch",warning:`V4 sign-in is not enabled on this deployment (${e}); refusing to open the retired GitHub flow.`,healthUrl:a}:{ready:!0,healthUrl:a,features:Array.isArray(d.features)?d.features.filter(l=>typeof l=="string"):[]}}var jP=x(m_());var ju={x402_retired:{kind:"caller",fix:null,nextAction:"Read the saved outcome with history. Preserve unresolved evidence and do not pay the same purchase again."},update_required:{kind:"caller",fix:"npm install -g @visa/cli@rc",nextAction:"Upgrade Visa CLI to the minimum compatible version or newer, then retry the command."},session_required:{kind:"caller",fix:"agent_enroll",nextAction:"Run visa connect (shell) or call agent_enroll (MCP) and complete the browser sign-in. Both resume where they left off. Retry the original command after that."},identity_required:{kind:"caller",fix:"agent_enroll (MCP) or visa connect (shell)",nextAction:"Call agent_enroll or run visa connect, open the printed URL, enter the code at /agent/enroll/protected-agent, and have the owner approve the device and its limits. Both entrances use the same protected enrollment implementation."},legacy_door_removed:{kind:"caller",fix:"agent_enroll (MCP) or visa connect (shell)",nextAction:"Call agent_enroll or run visa connect, open the printed URL, enter the code at /agent/enroll/protected-agent, approve the device and its limits, then pay with the pay tool. Do not retry the retired command; nothing was signed, paired, or paid."},agent_selection_required:{kind:"caller",fix:null,nextAction:"Retry the command with one exact agent id from the executable choices in the error."},invalid_argument:{kind:"caller",fix:null,nextAction:"Correct the invalid argument named in the error, then retry the command once. Do not escalate this as a platform incident."},rate_limited:{kind:"caller",fix:"sleep <retry-after-seconds>",nextAction:"Wait the exact Retry-After duration named in the error, then retry the same request once. Do not retry sooner or switch agents to bypass the limit."},activity_entry_not_found:{kind:"caller",fix:"history",nextAction:"Call history for the same agent and find the entry by its exact id in that list, or read the visa://receipt/<id> resource."},wallet_network_mismatch:{kind:"caller",fix:"discover",nextAction:"The unpaid challenge offered no Tempo OUSD payment this wallet can make. Nothing was reserved, signed, or paid. Choose a service that accepts Tempo; do not retry the same challenge unchanged."},agent_operations_cli_upgrade_required:{kind:"caller",fix:null,nextAction:"Use a reviewed CLI build at or above the minimum version named by the server, restart the agent session, and retry once. The payment was not sent."},agent_operation_forbidden:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This owner, agent, runtime, rail, or rollout state is not admitted to the universal payment route. Ask the owner to inspect the selected agent; do not retry through a legacy path."},runtime_context_not_found:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The server cannot find a current managed runtime contract for this exact agent and device. Ask the owner to inspect or renew that runtime before retrying."},product_policy_not_active:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The wallet setup did not install its server-owned spend policy. Resume the owner-approved wallet setup for this agent; do not retry the payment unchanged."},runtime_spend_session_not_active:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The wallet setup has no active runtime spend session. Resume the owner-approved wallet setup for this agent; do not retry the payment unchanged."},runtime_spend_attenuation_not_active:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The wallet runtime spend limits are not bound to the active owner policy. Resume the owner-approved wallet setup for this agent; do not retry the payment unchanged."},runtime_revoked:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This exact runtime has been revoked. Do not reuse it; ask the owner to certify a new runtime for the same agent if access should continue.",remedy:{path:"/agent/enroll/agents",label:"Check the agent in the Console"}},certified_runtime_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This payment requires an owner-certified runtime. Ask the owner to approve the wallet runtime certificate, then retry once."},runtime_certificate_invalid:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The wallet runtime certificate is invalid, expired, or no longer current. Ask the owner to renew it; do not retry unchanged."},runtime_delegation_missing:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This runtime has no active owner delegation for short signing leases. Ask the owner to finish secure wallet setup before retrying.",remedy:{path:"/agent/enroll/agents",label:"Finish the agent's wallet setup"}},runtime_delegation_expired:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This runtime owner delegation has expired. Ask the owner to renew secure wallet authority before retrying.",remedy:{path:"/agent/enroll/agents",label:"Renew the agent's approval"}},runtime_authority_unavailable:{kind:"platform",escalation:"unclassified",fix:null,nextAction:"The server could not verify runtime authority. Surface the outage to an operator and do not retry or fall back until authority health is restored."},universal_required_managed_only:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The universal route requires a fully managed TVC wallet for this agent. Ask the owner to finish managed wallet setup before retrying."},wallet_authority_cli_upgrade_required:{kind:"caller",fix:null,nextAction:"Upgrade the CLI to the minimum version named by the server, restart this agent session, and retry once. Nothing was signed or paid."},tap_signature_required:{kind:"platform",escalation:"unclassified",fix:null,nextAction:"Escalate to a human. A TAP identity signer is available on this runtime but could not sign, so the paid request was not sent unsigned and nothing was paid. Do not retry the payment unsigned. Probe remains unsigned."},wallet_owner_approval_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was paid. Show the owner the approval link in details.approval.url, bare, and ask them to approve this exact payment before details.approval.expiresAt. Then call pay again with the SAME target, max, body and economicIntentId: until they sign, the retry returns this same refusal (safe to repeat every 15-30 seconds); once they sign, the identical authorization resumes. Do not change the payment or start a new one. If the approval expires first, the retry says so and nothing is paid: stop then."},wallet_owner_approval_expired:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was paid. The owner's approval for this exact payment can no longer be used (it expired before the payment completed). Stop: do not call pay again with this economicIntentId, it will keep answering this. Tell the owner; only if they still want it, start a NEW payment with a NEW economicIntentId, which asks them to approve again."},attestation_key_drift:{kind:"caller",fix:"visa connect",nextAction:"This device holds a credential the server does not recognize (machine swap, keychain wipe, restored backup). Clear the stale local credential, enroll a fresh protected agent with visa connect, then retry."},rc_access_required:{kind:"platform",escalation:"awaiting_human",fix:"export VISA_RC_CODE=<access code>",nextAction:"This is a release-candidate build restricted to Visa employees. Set VISA_RC_CODE in this process, then retry. Ask your team lead or Visa Crypto Labs for the code \u2014 do not guess it."},early_access_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Escalate to a human: an admin must enable this tool for the account. Do not retry until they confirm."},card_checkout_not_on_pay:{kind:"caller",fix:"purchase_create",nextAction:"Nothing was probed further, created or charged. This URL answered no payment challenge, so it is an ordinary merchant checkout and `pay` cannot do it: `pay` spends from the agent wallet only. Card checkouts are the `purchase` resource (`purchase_create`, then `purchase_retrieve`), where Visa issues the credential and YOUR runtime drives the browser. Do not retry this target on `pay`."},card_draw_not_live:{kind:"platform",escalation:"surface_dark",fix:null,nextAction:"Escalate to a human now. The card-draw surface is not live on this build (it is opt-in server-side), so no local configuration change makes this command work. Do not retry."},checkout_review_refused:{kind:"caller",fix:null,nextAction:"Nothing was charged. This checkout needs a supported card-field adapter. Choose another supported checkout, or give the merchant and adapter details to the product team; do not retry unchanged."},checkout_action_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was charged and no payment credential was requested. Ask the human to complete the named verification step, then retry the review once."},checkout_mandate_blocked:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was charged. Ask the owner to approve a mandate that covers the exact merchant, amount, and currency, then start a new review. Do not widen authority yourself."},card_mandate_activation_uncertain:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The owner approved the budget but the card network did not confirm its activation. No budget is usable and nothing was charged. Do not start another approval while this one is valid: ask the owner to review the budget in the Visa Console and, once the approval has expired or been revoked there, approve a fresh budget. Quote the request id when reporting it."},ucp_platform_profile_unavailable:{kind:"platform",escalation:"surface_dark",fix:null,nextAction:"Do not retry this checkout. Escalate to the Visa deployment owner: the exact UCP platform profile advertised to merchants must serve a valid HTTPS JSON profile without redirects before checkout handoff can work."},wallet_capability_unavailable:{kind:"platform",escalation:"surface_dark",fix:null,nextAction:"Escalate to a human now. The wallet capability is not served by this build. Do not retry."},surface_disabled:{kind:"platform",escalation:"surface_dark",fix:null,nextAction:"Escalate to a human now. The server reports this surface disabled or not configured (kill switch or missing server config \u2014 see the flag and correlation_id in the error). No retry or local change resolves it."},wallet_grant_required:{kind:"platform",escalation:"awaiting_human",fix:"agent_enroll (MCP) or visa connect (shell)",nextAction:"The Turnkey wallet is delegated by the human owner, not self-minted here. Call agent_enroll or ask the owner to run visa connect and approve the device and its limits at /agent/enroll/protected-agent, then retry.",remedy:{path:"/agent/enroll/agents",label:"Approve this agent in the Console"}},wallet_credential_required:{kind:"platform",escalation:"awaiting_human",fix:"agent_enroll (MCP) or visa connect (shell)",nextAction:"Call agent_enroll or ask the owner to run visa connect for the intended agent and approve the device and its limits at /agent/enroll/protected-agent, then retry. Identity alone does not grant spend authority.",remedy:{path:"/agent/enroll/agents",label:"Approve this agent in the Console"}},grant_expired:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was reserved, signed, or charged. The owner's spending approval for this agent has expired. Ask the owner to renew it in the Visa Console at /agent/enroll/limits?agent=<agent-id> (the same limits are pre-filled), then retry the same payment once. Do not create a new agent or reconnect.",remedy:{path:"/agent/enroll/limits",label:"Renew the agent's approval"}},managed_limits_owner_controlled:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was signed or paid. Managed wallet limits are owner-set on the server. Read them with get_status, then ask the owner to change them in the Visa Console at /agent/enroll/limits?agent=<agent-id>.",remedy:{path:"/agent/enroll/limits",label:"Change the agent's limits"}},agent_paused:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Ask the owner to resume this exact agent in the Visa Console (Agents). Retry only after get_status reports it ready; do not create a replacement credential while the agent is paused.",remedy:{path:"/agent/enroll/agents",label:"Resume the agent in the Console"}},owner_declined:{kind:"caller",fix:null,nextAction:"The owner declined this payment; don't retry it. Nothing was charged. Tell the owner and move on; only if they ask for it again, start a new payment (a new economicIntentId or a new purchase), which asks them again."},setup_declined:{kind:"caller",fix:null,nextAction:"The owner declined this setup, so no agent was connected; don't retry it. Tell the owner, and only if they ask for it again start a new setup (agent_enroll with restart:true, or `visa connect --restart`), which asks them again."},owner_withdrawal_pending:{kind:"caller",fix:null,nextAction:"Nothing was signed or paid. The owner is withdrawing from this wallet and that transfer is still settling (at most about ten minutes). Retry the same payment in a minute; the budget is unchanged."},operator_daily_cap_reached:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The operator\u2019s 24-hour spending limit is reached. This attempt was not signed. Check any earlier attempt using its original reference, then try the same purchase again later only after usage leaves the 24-hour window or the operator changes the limit. A purchase above the entire cap needs a limit change; do not loop or switch agents or rails to bypass the limit."},operator_daily_cap_unavailable:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Visa could not read the operator\u2019s 24-hour spending limit. This attempt was not signed. Check any earlier attempt using its original reference, then tell the operator if the control needs repair; retry the same purchase later only after the control is readable. Do not switch agents or rails."},kill_switch_engaged:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Visa has paused payments on this rail (card, wallet or Tempo), or could not confirm they are open. Nothing was paid. Tell the owner, and try the same purchase again later; do not loop, switch rails to get around it, or create a replacement."},agent_revoked:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This agent is permanently revoked. Do not retry or reuse its credentials; ask the owner whether to pair a new agent identity.",remedy:{path:"/agent/enroll/agents",label:"Connect a new agent in the Console"}},device_key_replaced:{kind:"platform",escalation:"awaiting_human",fix:"agent_enroll (MCP) or visa connect (shell)",nextAction:"Nothing was paid. This computer's keys for the agent were replaced on another computer, which now is the agent. Do not retry here. To use this computer too, call agent_enroll (or have the owner run visa connect) and approve it as a new agent."},agent_stale:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The server cannot prove this agent is currently usable. Ask the owner to inspect its lifecycle and reauthorize it before retrying.",remedy:{path:"/agent/enroll/agents",label:"Check the agent in the Console"}},agent_lifecycle_unknown:{kind:"platform",escalation:"unclassified",fix:null,nextAction:"The lifecycle state is unknown. Surface the full preflight result to a human and do not retry a money operation until the server reports active."},wallet_delivery_required:{kind:"platform",escalation:"awaiting_human",fix:"visa connect",nextAction:"The approved wallet runtime was not delivered completely. Ask the owner to re-run visa connect and re-approve the device and its limits before paying; do not self-mint a mainnet wallet.",remedy:{path:"/agent/enroll/agents",label:"Reconnect this agent in the Console"}},wallet_authority_revoked:{kind:"caller",fix:"get_status",nextAction:"This wallet is preserved for recovery only. Inspect its balance and receipts with get_status or history; do not retry a payment or policy change until the owner approves a new wallet grant."},wallet_authority_replacement_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This compatibility error came from an older single-wallet runtime. Upgrade the CLI and re-run the wallet grant; current builds isolate wallet authority per agent."},wallet_policy_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was signed. Ask the owner to set per-purchase and daily spend caps in the Visa Console at /agent/enroll/limits?agent=<agent-id>, then retry once. Caps are enforced before anything is signed.",remedy:{path:"/agent/enroll/limits",label:"Set spending caps in the Console"}},wallet_funding_required:{kind:"caller",fix:"get_status",nextAction:"Ask the owner to add OUSD on Tempo to their wallet before paying: the Visa Console shows the wallet's address and balance under Payments.",remedy:{path:"/agent/enroll/payments",label:"Add funds to the wallet"}},wallet_unavailable:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Ask the owner to finish wallet setup in the Visa console (their account has no usable wallet yet), then re-run the grant. Do not keep polling: the ceremony cannot complete until the wallet exists.",remedy:{path:"/agent/enroll/payments",label:"Finish wallet setup"}},checkout_agent_access_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Escalate to a human: this account is not enabled for agent checkout, so grant ceremonies are refused server-side. Do not retry until an admin confirms the account has access."},unknown_tool:{kind:"caller",fix:null,nextAction:"Call tools/list and dispatch one of the served names. The tool you asked for is not registered on this runtime."},handoff_not_found:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The Console claim code was not found or was mistyped. Ask the human for a fresh claim code from the Visa Console; do not retry this code."},handoff_expired:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This Console claim code has expired. Ask the human to create a new setup code in the Visa Console."},handoff_already_redeemed:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This Console claim code has already been redeemed. Ask the human to create a new setup code in the Visa Console."},no_paired_agent:{kind:"caller",fix:"agent_enroll (MCP) or visa connect (shell)",nextAction:"No protected agent on this device. Call agent_enroll or run visa connect and complete the owner ceremony at /agent/enroll/protected-agent first."},agent_id_required:{kind:"caller",fix:null,nextAction:"Pass the agentId to identify which agent ceremony to operate on."},already_terminal:{kind:"caller",fix:null,nextAction:"This ceremony is already terminal or cancelled. No further action needed."},purchase_transport_uncertain:{kind:"caller",fix:null,nextAction:"Wait briefly, then repeat the identical Visa purchase call with the same arguments, request key and purchase ID. The original request may have succeeded; its journal recovers the same attempt. Do not cancel, create a replacement or submit Pay at the merchant again. Escalate repeated transport failures."},purchase_refused:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The authority refused this purchase request. Use the recorded upstream status and error to resolve the refusal before trying again. Preserve the original purchase and request key; a refusal is not permission to mint a replacement or repeat merchant payment."},recovery_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Inspect the original purchase and checkout with the owner or support. Preserve the purchase ID and request key. Do not create a replacement, release uncertain liability or submit Pay again."},card_recovery_unconfigured:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Card recovery is not configured. Ask support to restore the protected recovery worker before retrying the same Visa request. Preserve the purchase ID; do not create another purchase or click merchant Pay again."},card_recovery_original_not_expired:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The original credential attempt is still live. Retrieve the same purchase without include:card and follow its continuation; do not force recovery, create another purchase or click merchant Pay again."},card_recovery_liability_present:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The original attempt still has liability. Ask support to reconcile that attempt and inspect the existing checkout. Do not release funds, issue replacement credentials or click merchant Pay again."},card_recovery_issuance_conflict:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Recovery found conflicting issuance evidence. Stop and ask support to reconcile the original purchase and attempt. Do not create another purchase or click merchant Pay again."},card_recovery_proof_invalid:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The recovery proof could not be verified. Ask support to repair recovery for the existing device and purchase; do not replay the invalid proof, replace the identity or click merchant Pay again."},card_purchase_quarantined:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This purchase is quarantined for reconciliation. Ask support to inspect its original attempt and the existing checkout. Do not create another purchase, release its liability or click merchant Pay again."},card_credential_not_available:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Credentials are not available for this purchase state. Retrieve the same purchase without include:card and follow its continuation. Do not recreate the purchase or click merchant Pay again."},purchase_submission_observed:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Submission was already reported for this purchase. Inspect the existing merchant checkout and report its current state on the same purchase. Do not request replacement credentials or click merchant Pay again."},protected_card_request_invalid:{kind:"caller",fix:null,nextAction:"The card executor refused the saved delivery request, usually because its admission has expired. Retrieve the same purchase and follow its continuation; if it reads expired, run purchase create again with the same request file. Do not create a replacement purchase by hand."},protected_card_delivery_conflict:{kind:"caller",fix:null,nextAction:"The saved delivery request differs from the one already in progress for this attempt. Retrieve the same purchase and follow its continuation; do not alter or replay edited request bytes."},protected_card_authority_unavailable:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The card authority did not answer the executor. Nothing was issued. Wait a moment and retrieve the same purchase; recovery continues server-side."},purchase_cancelled:{kind:"caller",fix:null,nextAction:"This purchase was cancelled; it accepts no new credential. Create a new purchase for a fresh checkout if the buyer still wants it. Do not click merchant Pay."},card_intent_unobserved:{kind:"caller",fix:null,nextAction:"The owner's card allowance for this agent is not active yet. Follow next.open_url so the owner finishes card setup, then retry the same checkout."},card_intent_mandate_exists:{kind:"caller",fix:null,nextAction:"The owner's current approval already has a card allowance in progress. Wait for it to finish (or ask the owner to check the limits page), then retry the same checkout."},card_intent_conflict:{kind:"caller",fix:null,nextAction:"A different card allowance request already exists under this id. Retrieve current status instead of resending edited request bytes."},card_vic_provider_refused:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The provider refused credential issuance. Ask the owner or support to inspect the original purchase and provider refusal before retrying; an HTTP error does not prove its reservation was released. Do not create a replacement purchase or click merchant Pay again."},terms_conflict:{kind:"caller",fix:null,nextAction:"The request conflicts with the existing checkout commitment or quote bound. Retrieve the original purchase and compare the exact final terms. Do not change the request key or checkout ID to bypass the conflict; resolve it under the checkout replacement rules."},card_checkout_expired:{kind:"caller",fix:null,nextAction:"The exact checkout quote expired. Inspect the original purchase before obtaining a new final quote. Do not reuse stale terms or bypass checkout replacement rules by changing the request key or checkout ID."},card_mandate_expired:{kind:"caller",fix:null,nextAction:"The owner's card allowance for this agent lapsed (the provider limits each one to 7 days) while the approval itself is still valid; Visa is issuing a replacement under that approval. Wait afterMs and run the same purchase create again. Do not involve the owner or create a replacement purchase."},card_allowance_preparing:{kind:"caller",fix:null,nextAction:"Visa is issuing this agent's card allowance under the owner's existing approval. Wait afterMs and run the same purchase create again; the wait loop does this for you. Do not involve the owner or create a replacement purchase."},protected_card_instrument_inactive:{kind:"platform",escalation:"awaiting_human",fix:"purchase_create",nextAction:"This agent's card connection points at a saved-card record the owner has since replaced (re-verifying the card) or removed. Call purchase_create again with the saved resumeId: it returns one open_url that reconnects this agent to the owner's current saved card. The owner opens it once, then the same saved purchase resumes. Do not ask for card details, create another agent or purchase, or click merchant Pay again."},card_reservation_expired:{kind:"caller",fix:null,nextAction:"Retrieve the same purchase to resolve its expired reservation. Follow its current continuation; do not replay stale admission bytes or create a replacement to hide an unresolved attempt."},card_merchant_country_mismatch:{kind:"caller",fix:null,nextAction:"Use the actual merchant country consistently in the signed checkout terms and settlement envelope. Preserve the existing purchase commitment; do not change keys to bypass a terms conflict."},protected_grant_proof_mismatch:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Ask the owner or support to verify the current grant and runtime proof for this existing agent. Do not retry an unchanged invalid proof or create replacement authority."},purchase_resume_invalid:{kind:"caller",fix:null,nextAction:"Use the exact saved purchase resume reference by itself; do not combine it with a new request. Preserve the original purchase and merchant checkout."},purchase_draft_invalid:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The saved purchase request is damaged or changed. Stop and ask support to recover the original draft; do not overwrite it, invent new terms or click merchant Pay again."},purchase_draft_not_found:{kind:"caller",fix:null,nextAction:"Use the original device and exact saved resume reference. Locate the existing draft before continuing; do not recreate the request or click merchant Pay again."},purchase_draft_agent_invalid:{kind:"caller",fix:null,nextAction:"Select the existing protected agent by its exact UUID and resume the original draft. Do not create a replacement identity or purchase."},purchase_draft_agent_mismatch:{kind:"caller",fix:null,nextAction:"Resume this draft with the same protected agent it already selected. Do not switch agents, replace the draft or click merchant Pay again."},purchase_draft_owner_mismatch:{kind:"caller",fix:null,nextAction:"Sign in as the owner who started this draft on the original device, then resume that same draft. Do not transfer it to another owner or create a replacement purchase."},purchase_draft_owner_required:{kind:"caller",fix:null,nextAction:"Complete the returned owner sign-in step, then resume the same saved draft. Do not start another identity enrollment or purchase."},purchase_draft_busy:{kind:"caller",fix:null,nextAction:"Wait for the current Visa purchase call to finish, then repeat the same resume reference. Do not run concurrent purchase calls, create a replacement or click merchant Pay again."},purchase_not_found:{kind:"caller",fix:null,nextAction:"Check the original purchase ID and selected agent. Recover the existing purchase record; do not mint a replacement merely because a read could not find it."},invalid_contract:{kind:"caller",fix:null,nextAction:"Correct the request using the declared tool schema, then retry only with valid input. Never fabricate facts or change existing payment identifiers to bypass their commitment."},invalid_amount:{kind:"caller",fix:null,nextAction:"Supply a positive canonical amount in the units required by the selected tool. Follow its total and precision constraints; never change identifiers to bypass an existing payment commitment."},invalid_currency:{kind:"caller",fix:null,nextAction:"Use the currency required by the selected payment profile. Do not infer merchant country from currency."},unsupported_version:{kind:"caller",fix:null,nextAction:"Use a supported protocol version and profile. Check the current tool schema or update Visa CLI, then retry the same logical operation without bypassing its existing commitment."},keychain_not_found:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"This Mac user has no default keychain, so no agent key was stored or read and no system dialog was opened. Ask the owner to restore or create their login keychain in Keychain Access, then retry. On a server with no keychain, the owner can choose file custody explicitly with VISA_RUNTIME_CUSTODY_PROFILE=headless."},custody_store_unreadable:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The agent key store on this machine could not be read (its permissions or the disk), so nothing was signed and nothing was changed. Ask the owner to restore read access to Visa CLI's agent-keys directory, then retry. Do not re-enroll: the key may still be there."},keychain_locked_or_unavailable:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The macOS login keychain is locked or refused, so this agent's key could not be read. Nothing was signed or sent, and no new key was made. Ask the owner to unlock the login keychain (log in to the Mac, or open Keychain Access), then retry once."},custody_unavailable:{kind:"platform",escalation:"awaiting_human",fix:"visa connect",nextAction:"This agent's key is not on this computer: it was set up by an older Visa CLI or on another computer. Nothing was signed or sent. Ask the owner to update Visa CLI (npm i -g @visa/cli@rc) and run visa connect on this computer, then approve the new agent in the browser."},protected_card_enrollment_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was signed or paid. The owner must verify a payment card once for this account. Ask the owner to sign in at /agent/enroll and complete the Verify your card step, then retry the original command once.",remedy:{path:"/agent/enroll?enrollCard=1",label:"Verify a payment card"}},financial_rollout_approval_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was signed or paid. The owner account is not approved for protected payments yet. Surface this to the owner; do not retry until they confirm access was granted."},key_purpose_mismatch:{kind:"platform",escalation:"awaiting_human",fix:"npm i -g @visa/cli@rc",nextAction:"The native signer refused to sign because this device key is bound to a different purpose (wallet, card, or identity) than the operation asked of it. Nothing was signed or sent. This is a Visa CLI defect or a CLI/signer version mismatch, not something a retry changes: ask the owner to update Visa CLI, then retry once. If it persists on the latest build, report it."},legacy_custody_profile_required:{kind:"platform",escalation:"awaiting_human",fix:"npm i -g @visa/cli@rc",nextAction:"The native signer refused to sign a wallet or card proof with an identity key. Nothing was signed or sent. This is a Visa CLI defect or a CLI/signer version mismatch: ask the owner to update Visa CLI, then retry once. If it persists on the latest build, report it."},identity_binding_mismatch:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The native signer refused because the request named a different agent or runtime than the device key is bound to. Nothing was signed or sent. Read get_status, then retry once with that agent's id; if it repeats, surface it to the owner rather than retrying."},proof_time_invalid:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The native signer refused a proof whose timestamp is outside its one-minute window, which means this machine's clock is wrong. Nothing was signed or sent. Ask the owner to sync the system clock, then retry once."},secret_service_locked_or_unavailable:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The Linux Secret Service (the desktop keyring) is locked or refused Visa CLI, so the agent's key could not be read. Ask the owner to unlock the login keyring; on a machine without a desktop session (SSH, WSL, a server), set VISA_RUNTIME_CUSTODY_PROFILE=headless and run visa connect instead. Do not retry on your own."},secret_service_unavailable:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"No Linux Secret Service is reachable (no desktop session: SSH, WSL, a container, or a server), so the agent's key could not be read. On such a machine, set VISA_RUNTIME_CUSTODY_PROFILE=headless (an owner-only key file) and run visa connect; in a desktop session, unlock the keyring (gnome-keyring or KWallet). Do not retry on your own."},secret_service_timeout:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"The Linux Secret Service did not answer Visa CLI in time, usually because an unlock prompt is waiting. Ask the owner to answer or unlock the keyring, then retry once."},dpapi_locked_or_unavailable:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Windows data protection (DPAPI) refused to open the agent key, usually because this is a different Windows user or profile than the one that set the agent up. Ask the owner to run Visa CLI as that user; do not retry on your own."},enrollment_device_approval_pending:{kind:"platform",escalation:"awaiting_human",fix:"visa connect",nextAction:"This computer's agent setup is waiting for the owner's device approval, and starting another would strand it. Nothing was changed. Run visa connect (without --restart) to reopen the same approval, ask the owner to approve it, and only then use visa connect --restart if a replacement is still wanted."},enrollment_expired:{kind:"caller",fix:"visa connect --restart",nextAction:"This approval link expired. Run `visa connect --restart` (agent_enroll: restart:true) for a new link, and give the owner the new link and code."},enrollment_owner_mismatch:{kind:"platform",escalation:"awaiting_human",fix:"visa connect --restart (keep the signed-in account) or visa disconnect --all, then visa connect (switch accounts)",nextAction:"The agent approved for this terminal belongs to a different Visa account than the one this terminal is signed in to (the error names it), so nothing was connected. Let the owner choose. To keep the signed-in account: run visa connect --restart and open the new link while signed in to that account. To switch to the other account: visa disconnect --all signs this terminal out, but it also removes the Visa MCP server from every AI client, the spend HUD and any local card-delivery files, so run it only with the owner's say-so; then run visa connect and the owner signs in with the other account. Never approve for them."},wallet_key_setup_pending:{kind:"platform",escalation:"awaiting_human",fix:"visa connect",nextAction:"This agent is connected but cannot pay yet: its key on the owner's Tempo wallet is not set up. The owner's open approval page finishes it on its own (it asks for OUSD first if the wallet has none); if that page was closed, opening the Visa Console finishes it the same way. Then run visa connect (or call get_status) to confirm. Do not run visa connect --restart, and do not try a payment until it reports the key ready.",remedy:{path:"/agent/enroll/payments",label:"Finish the wallet in Payments"}},unspecified_error:{kind:"platform",escalation:"unclassified",fix:null,nextAction:"This failure could not be classified, so it is reported as platform to avoid a silent retry loop. Surface the human-readable error to a human rather than retrying."},tempo_over_max:{kind:"caller",fix:null,nextAction:"Nothing was signed or paid. The charge costs more than max: raise max only if the human agreed to that price, otherwise stop."},tempo_budget_refused:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was signed or paid. The owner's spending budget or per-payment limit does not allow this payment. Ask the human to raise it in the Visa Console; do not retry until they have.",remedy:{path:"/agent/enroll/limits",label:"Change the agent's limits"}},tempo_chain_limit:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was signed or paid. The wallet's weekly on-chain safety limit for this agent is used up; it refills on its weekly schedule, shown with the agent's limits in the Visa Console. Do not retry before then; tell the human if the purchase cannot wait.",remedy:{path:"/agent/enroll/limits",label:"Change the agent's limits"}},tempo_charge_expired:{kind:"caller",fix:"pay",nextAction:"Nothing was paid. The merchant charge expired before it was signed. Call pay again for the same target to get a fresh charge."},tempo_payment_unclear:{kind:"caller",fix:"pay",nextAction:"The payment may have gone through (charged: null). Do not start a new purchase. Call pay again with the SAME economicIntentId in about a minute: it reports whether the earlier payment landed and pays only if it provably did not. history shows it too."},atum_payment_unclear:{kind:"platform",escalation:"unclassified",fix:null,nextAction:"The ATUM payment may have gone through. Do not fund or pay this purchase again on any rail. Ask the human to reconcile the existing ATUM request/payment, and keep the same economicIntentId."},tempo_payment_in_progress:{kind:"caller",fix:"pay",nextAction:"Another call is paying this exact purchase right now. Do not pay again; call pay again with the same economicIntentId in a minute to read its outcome."},tempo_payment_refused:{kind:"platform",escalation:"unclassified",fix:null,nextAction:"Nothing was signed or paid. Visa refused this Tempo payment before signing. Tell the human and stop; do not retry."},tempo_charge_mismatch:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was signed or paid. The merchant's Tempo charge does not match what this payment allows (payee, currency or paying account), checked on this machine. Do not retry; tell the human."},tempo_not_enabled:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:"Nothing was paid. This agent's wallet setup is not finished. Ask the owner to open Payments in the Visa Console (/agent/enroll/payments): the wallet finishes setting up there once it has funds. Then call pay again with the same economicIntentId.",remedy:{path:"/agent/enroll/payments",label:"Finish the wallet in Payments"}},tempo_unavailable:{kind:"platform",escalation:"surface_dark",fix:null,nextAction:"Nothing was paid. Visa has wallet payments switched off right now. Tell the human; do not retry until Visa turns them on, and do not look for another way to pay this merchant."},merchant_not_supported:{kind:"caller",fix:null,nextAction:"Nothing was charged. This merchant does not accept Visa wallet payments (MPP on Tempo). Do not retry it on `pay`; pay a merchant that accepts Tempo, or tell the human."},merchant_unreachable:{kind:"caller",fix:null,nextAction:"Nothing was charged. The merchant URL could not be reached to read its price. Check the URL, then call pay again with the same economicIntentId."},merchant_refused:{kind:"caller",fix:null,nextAction:"Nothing was signed or paid. The merchant refused this request: check the URL, method and body, and do not retry it unchanged."},purchase_on_retired_rail:{kind:"caller",fix:null,nextAction:"Nothing was paid. This purchase was started with the earlier wallet, before Visa moved wallet payments to Tempo. Do not pay it again: check `history` for its outcome, and use a new economicIntentId only for a genuinely new purchase."},tempo_owner_approval_required:{kind:"platform",escalation:"awaiting_human",fix:null,nextAction:`Nothing was paid. The owner chose "Ask me each time" for this agent's wallet payments, and this Tempo payment could not be sent to them for approval. Call pay again with the same economicIntentId: it asks the owner (the answer then carries the approval link). If it keeps failing, ask the human.`}},TK=Object.keys(ju);function Lc(e){return typeof e=="string"&&Object.prototype.hasOwnProperty.call(ju,e)}function qP(e){return e.remedy?{remedyPath:e.remedy.path,remedyLabel:e.remedy.label}:{}}function ci(e,t={}){let n=ju[e],r=t.fix!==void 0?t.fix:n.fix;if(n.kind==="platform"&&n.escalation!=="awaiting_human"&&r!==null)throw new Error(`agent-contract: ${n.escalation} code "${e}" cannot carry a fix \u2014 no command resolves it`);return{code:e,kind:n.kind,fix:r,nextAction:t.nextAction??n.nextAction,...t.agentId?{agentId:t.agentId}:{},...qP(n)}}var ge=class extends Error{diagnostic;details;constructor(t,n,r={}){super(t),this.name="AgentContractError";let i=r.agentId??(typeof r.details?.agentId=="string"?r.details.agentId:void 0);this.diagnostic=ci(n,{...r,...i?{agentId:i}:{}}),this.details=r.details}get code(){return this.diagnostic.code}};function To(e){if(e instanceof ge)return e.diagnostic;if(e&&typeof e=="object"){let t=e,n=typeof t.agentId=="string"?t.agentId:t.details&&typeof t.details=="object"&&typeof t.details.agentId=="string"?t.details.agentId:void 0,r=n?{agentId:n}:{},i=e.underlying;if(i instanceof ge)return i.diagnostic;let o=i?.code;if(o==="agent_paused"||o==="agent_revoked"||o==="device_key_replaced"||o==="grant_expired")return ci(o,r);let a=e.code??e.errorCode;if(Lc(a))return ci(a,r);if(typeof a=="string"){let c=a.toLowerCase();if(Lc(c))return ci(c,r)}let s=e.message;return Lc(s)?ci(s,r):ci("unspecified_error",r)}return ci("unspecified_error")}var No=require("node:crypto"),Ln=x(require("node:fs")),Yu=x(require("node:path"));var fi=require("child_process"),H_=require("util"),Me=x(require("fs")),za=x(require("os")),Oo=x(require("path"));var w_=x(require("crypto"));var g_="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1";var KP="VISA_ALLOW_INSECURE_MOCKS",y_,__;function E_(e){return`${e}-${w_.randomBytes(24).toString("base64url")}`}function HP(e=process.env){return e.NODE_ENV==="test"||e[KP]==="true"}function Kt(e=process.env){return e.VISA_MOCK_KEYCHAIN==="true"&&HP(e)}function v_(){return y_??=E_("mock-session"),y_}function qu(e=process.env){return e.NODE_ENV==="test"?g_:(__??=E_("mock-rc"),__)}var b_=x(require("crypto")),A_=x(require("os")),Jc=x(require("path")),S_="VISA_CLI_HOME";function de(e=process.env){let t=e[S_];return typeof t=="string"&&t.trim().length>0?t:Jc.join(A_.homedir(),".visa-cli")}function I_(e=process.env){let t=e[S_];return typeof t=="string"&&t.trim().length>0}function T_(e=process.env){let t=Jc.resolve(de(e));return b_.createHash("sha256").update(t).digest("hex").slice(0,16)}var jc=require("node:crypto"),vr=x(require("node:fs")),qc=x(require("node:path"));var P_=require("node:crypto"),Ku=x(require("node:fs")),li=x(require("node:path")),k_=require("node:util"),ko=1024*1024,Fa=class extends Error{constructor(t){super(t),this.name="PrivateStateSecurityError"}};function VP(e){return typeof e=="object"&&e!==null&&"code"in e&&e.code==="ENOENT"}function De(e,t){return new Fa(`${e} ${t}`)}function C_(e=process.platform){if(e==="win32")throw new Fa("owner-only identity files are not supported on Windows yet; protocol-v2 pairing is disabled until verified ACL storage is available")}function di(e,t,n,r){try{return n.lstatSync(e)}catch(i){if(r&&VP(i))return null;throw De(t,"could not be inspected safely")}}function R_(e,t){C_(t);let n=e.expectedUid??process.geteuid?.();if(!Number.isSafeInteger(n)||n<0)throw new Fa("private state owner could not be verified against the process effective uid");return n}function Po(e,t,n){return!(n!=="win32"||e.dev!==0||t.dev!==0||e.ino!==0||t.ino!==0)||e.dev===t.dev&&e.ino===t.ino}function Uc(e,t,n,r){if(e.isSymbolicLink()||!e.isDirectory())throw De(t,"must be a real owner-only directory, not a symlink");if(n!=="win32"){if(e.uid!==r)throw De(t,"must be owned by the current effective user");if((e.mode&63)!==0)throw De(t,"must not grant access to group or other users (use mode 0700)")}}function Wa(e,t,n,r){if(e.isSymbolicLink()||!e.isFile())throw De(t,"must be a real owner-only regular file, not a symlink");if(n!=="win32"){if(e.uid!==r)throw De(t,"must be owned by the current effective user");if((e.mode&63)!==0)throw De(t,"must not grant access to group or other users (use mode 0600)")}}function Ye(e,t={}){let n=t.ops??Ku,r=t.platform??process.platform,i=R_(t,r),o=di(e,"private state directory",n,!0);return o?(Uc(o,"private state directory",r,i),!0):!1}function $P(e,t={}){let n=t.ops??Ku,r=t.platform??process.platform,i=t.maxBytes??ko;if(!Number.isSafeInteger(i)||i<1)throw new Error("private state maximum size must be a positive safe integer");let o=R_(t,r),a=li.dirname(e),s=di(a,"private state directory",n,!0);if(!s)return null;Uc(s,"private state directory",r,o);let c=di(e,"private state file",n,!0);if(!c)return null;Wa(c,"private state file",r,o);let d;try{try{d=n.openSync(e,n.constants.O_RDONLY|(n.constants.O_NOFOLLOW??0))}catch{throw De("private state file","changed or could not be opened safely")}let l=n.fstatSync(d);if(Wa(l,"private state file",r,o),!Po(c,l,r))throw De("private state file","changed while it was being opened");if(!Number.isSafeInteger(l.size)||l.size<0||l.size>i)throw De("private state file",`exceeds the ${i}-byte safety limit`);let u=di(e,"private state file",n,!1);if(Wa(u,"private state file",r,o),!Po(l,u,r))throw De("private state file","changed while it was being opened");let f=di(a,"private state directory",n,!1);if(Uc(f,"private state directory",r,o),!Po(s,f,r))throw De("private state directory","changed while private state was being opened");let h=[],p=0;for(;p<=i;){let A=Buffer.allocUnsafe(Math.min(65536,i+1-p)),j=n.readSync(d,A,0,A.length,null);if(j===0)break;if(p+=j,p>i)throw De("private state file",`exceeds the ${i}-byte safety limit`);h.push(A.subarray(0,j))}let m=n.fstatSync(d);if(Wa(m,"private state file",r,o),!Po(l,m,r)||m.size!==l.size||m.mtimeMs!==l.mtimeMs||m.ctimeMs!==l.ctimeMs||p!==m.size)throw De("private state file","changed while it was being read");let w=di(e,"private state file",n,!1);if(Wa(w,"private state file",r,o),!Po(m,w,r))throw De("private state file","changed while it was being read");let v=di(a,"private state directory",n,!1);if(Uc(v,"private state directory",r,o),!Po(s,v,r))throw De("private state directory","changed while private state was being read");let _;try{_=new k_.TextDecoder("utf-8",{fatal:!0}).decode(Buffer.concat(h,p))}catch{throw De("private state file","must contain valid UTF-8")}return{contents:_,mtimeMs:m.mtimeMs}}finally{d!==void 0&&n.closeSync(d)}}function Ue(e,t={}){return $P(e,t)?.contents??null}function ke(e,t,n=Ku,r=process.platform){C_(r);let i=li.dirname(e),o=li.join(i,`.${li.basename(e)}.${process.pid}.${(0,P_.randomBytes)(8).toString("hex")}.tmp`),a=n.constants.O_NOFOLLOW??0,s,c=!1;try{s=n.openSync(o,n.constants.O_WRONLY|n.constants.O_CREAT|n.constants.O_EXCL|a,384),n.writeFileSync(s,t,{encoding:"utf8"}),n.fsyncSync(s),n.closeSync(s),s=void 0,n.renameSync(o,e),c=!0;let d;try{d=n.openSync(e,n.constants.O_RDONLY|a),n.fsyncSync(d)}finally{d!==void 0&&n.closeSync(d)}let l;try{let u=n.constants.O_DIRECTORY??0;l=n.openSync(i,n.constants.O_RDONLY|u|a),n.fsyncSync(l)}finally{l!==void 0&&n.closeSync(l)}}finally{s!==void 0&&n.closeSync(s),c||n.rmSync(o,{force:!0})}}var WP=/^op_[a-f0-9]{24}$/,Hu=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;function Vu(e=process.env){return qc.join(de(e),"owner-profiles")}function $u(e=process.env){return qc.join(Vu(e),"profiles.json")}function O_(e,t){return`op_${(0,jc.createHash)("sha256").update(`${Wu(e)}\0${t}`).digest("hex").slice(0,24)}`}function Wu(e){let t=new URL(e);if(t.username||t.password||t.search||t.hash||t.pathname!==""&&t.pathname!=="/"||t.protocol!=="https:"&&!(t.protocol==="http:"&&["localhost","127.0.0.1","::1"].includes(t.hostname)))throw new Error("owner profile auth origin must be HTTPS (or HTTP loopback)");return t.origin}function N_(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(!WP.test(String(t.profileId??""))||!Hu.test(String(t.ownerPublicId??""))||!Hu.test(String(t.runtimeId??""))||typeof t.loginLabel!="string"||t.loginLabel.length<1||t.loginLabel.length>320||typeof t.createdAt!="string"||!Number.isFinite(Date.parse(t.createdAt)))return!1;try{return Wu(String(t.authOrigin??""))===t.authOrigin&&O_(String(t.authOrigin),String(t.ownerPublicId))===t.profileId}catch{return!1}}function x_(){return{version:1,activeProfileId:null,profiles:[]}}function Ba(e=process.env){let t=$u(e);if(!vr.existsSync(t))return x_();let n=Ue(t,{maxBytes:128*1024});if(n===null)return x_();let r;try{r=JSON.parse(n)}catch{throw new Error(`owner profile registry contains invalid JSON at ${t}. Rename that file out of the directory, then run \`visa connect\` to rebuild it; this signs local profiles out.`)}if(!r||typeof r!="object"||Array.isArray(r))throw new Error(`owner profile registry is invalid at ${t}. Rename that file out of the directory, then run \`visa connect\` to rebuild it; this signs local profiles out.`);let i=r;if(i.version!==1||!Array.isArray(i.profiles)||!i.profiles.every(N_))throw new Error(`owner profile registry is invalid at ${t}. Rename that file out of the directory, then run \`visa connect\` to rebuild it; this signs local profiles out.`);let o=i.profiles,a=new Set(o.map(c=>c.profileId));if(a.size!==o.length)throw new Error(`owner profile registry has duplicate profiles at ${t}. Rename that file out of the directory, then run \`visa connect\` to rebuild it; this signs local profiles out.`);let s=i.activeProfileId;if(s!==null&&(typeof s!="string"||!a.has(s)))throw new Error(`owner profile registry active profile is invalid at ${t}. Rename that file out of the directory, then run \`visa connect\` to rebuild it; this signs local profiles out.`);return{version:1,activeProfileId:s,profiles:o}}function D_(e,t=process.env){let n=Vu(t);vr.mkdirSync(n,{recursive:!0,mode:448}),vr.chmodSync(n,448),Ye(n),ke($u(t),JSON.stringify(e,null,2))}function Co(e=process.env){return[...Ba(e).profiles]}function it(e=process.env){let t=Ba(e);return t.profiles.find(n=>n.profileId===t.activeProfileId)??null}function M_(e){let t=e.env??process.env,n=Wu(e.authOrigin);if(!Hu.test(e.ownerPublicId))throw new Error("owner profile requires a stable owner UUID");let r=e.loginLabel.normalize("NFC").trim();if(!r||r.length>320)throw new Error("owner profile login label is invalid");let i=Ba(t),o=O_(n,e.ownerPublicId),a=i.profiles.find(c=>c.profileId===o);return a?{...a,loginLabel:r}:{profileId:o,authOrigin:n,ownerPublicId:e.ownerPublicId,loginLabel:r,runtimeId:(0,jc.randomUUID)(),createdAt:(e.now??new Date).toISOString()}}function L_(e,t=process.env){if(!N_(e))throw new Error("refusing to activate an invalid owner profile");let n=Ba(t);return D_({version:1,activeProfileId:e.profileId,profiles:[...n.profiles.filter(r=>r.profileId!==e.profileId),e]},t),e}function J_(e,t=process.env){let n=Ba(t),r=n.profiles.filter(i=>i.profileId!==e);D_({version:1,activeProfileId:n.activeProfileId===e?null:n.activeProfileId,profiles:r},t)}function U_(e=process.env){let t=$u(e);try{vr.unlinkSync(t)}catch(n){if(n.code!=="ENOENT")throw n}}function Kc(e){return`session-token:${e.profileId}`}function br(e,t=process.env){return qc.join(Vu(t),e.profileId,"session-token")}function j_(e){return`attestation-key:${e.profileId}:${e.runtimeId}`}var ot=(0,H_.promisify)(fi.execFile);function an(e=process.env){let t=e.VISA_CLI_HOME,n=typeof t=="string"&&t.trim().length>0?t:za.homedir();return Oo.join(n,".visa-mcp","session-token")}function Ro(e=process.env){let t=e.VISA_CLI_HOME,n=typeof t=="string"&&t.trim().length>0?t:za.homedir();return Oo.join(n,".visa-mcp","rc-access")}var at="visa-cli",Mn="session-token",Dn="rc-access";function Hc(e=process.env){return I_(e)?`rc-access:home:${T_(e)}`:Dn}var FP=5e3,$c=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};function BP(e){let t=e;return[t?.message,t?.stderr].filter(n=>typeof n=="string").join(`
|
|
27
|
+
`)}function Fu(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let n=BP(e).toLowerCase();return n.includes("operation not permitted")||n.includes("permission denied")}var q_=null,Ga=null,GP="attestation-key";async function YP(e){try{await ot("security",["delete-generic-password","-s",at,"-a",e],{timeout:5e3})}catch{}}async function zP(e=Co()){if(!await sn())return;let t=new Set([...e.map(j_),GP]);for(let n of t)await YP(n)}function sn(){return process.platform!=="darwin"?Promise.resolve(!1):(q_??=(async()=>{try{return await ot("security",["default-keychain","-d","user"],{timeout:5e3}),!0}catch(e){return Fu(e)}})(),q_)}function XP(){if(process.platform!=="darwin")return!1;if(Ga!==null)return Ga;try{(0,fi.execFileSync)("security",["default-keychain","-d","user"],{timeout:1e3,encoding:"utf8",stdio:["pipe","pipe","ignore"]}),Ga=!0}catch{Ga=!1}return Ga}async function ZP(e=Mn){if(!await sn())return null;try{let{stdout:t}=await ot("security",["find-generic-password","-s",at,"-a",e,"-w"],{timeout:5e3});return t.trim()||null}catch(t){if(Fu(t))throw new $c("Unable to read Visa CLI credentials from macOS Keychain. In sandboxed agents such as Codex, rerun with keychain access or run this command outside the sandbox.");return null}}async function QP(e,t=Mn){if(!await sn())return!1;try{try{await ot("security",["delete-generic-password","-s",at,"-a",t],{timeout:5e3})}catch{}return await ot("security",["add-generic-password","-s",at,"-a",t,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function ek(e=Mn){if(await sn())try{await ot("security",["delete-generic-password","-s",at,"-a",e],{timeout:5e3})}catch{}}async function tk(e=Mn){if(!Bu())return null;try{let{stdout:t}=await ot("secret-tool",["lookup","service",at,"account",e],{timeout:5e3});return t.trim()||null}catch{return null}}async function nk(e,t=Mn){if(!Bu())return!1;try{let n=(0,fi.execFile)("secret-tool",["store","--label",`${at} ${t}`,"service",at,"account",t]);return n.stdin?(n.stdin.write(e),n.stdin.end(),await Promise.race([new Promise((r,i)=>{n.on("exit",o=>o===0?r():i(new Error(`secret-tool exited ${o}`))),n.on("error",i)}),new Promise((r,i)=>setTimeout(()=>{n.kill(),i(new Error("secret-tool timed out"))},FP))]),!0):!1}catch{return!1}}async function rk(e=Mn){if(Bu())try{await ot("secret-tool",["clear","service",at,"account",e],{timeout:5e3})}catch{}}function Bu(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function ik(e=Dn){if(!await sn())return null;try{let{stdout:t}=await ot("security",["find-generic-password","-s",at,"-a",e,"-w"],{timeout:5e3});return t.trim()||null}catch{return null}}async function ok(e,t=Dn){if(await sn())try{try{await ot("security",["delete-generic-password","-s",at,"-a",t],{timeout:5e3})}catch{}await ot("security",["add-generic-password","-s",at,"-a",t,"-w",e],{timeout:5e3})}catch{}}async function K_(e=Dn){if(await sn())try{await ot("security",["delete-generic-password","-s",at,"-a",e],{timeout:5e3})}catch{}}function ak(e=Dn){if(!XP())return null;try{return(0,fi.execFileSync)("security",["find-generic-password","-s",at,"-a",e,"-w"],{timeout:1e3,encoding:"utf8",stdio:["pipe","pipe","ignore"]}).trim()||null}catch{return null}}function xo(e=an()){try{return Me.readFileSync(e,"utf-8").trim()||null}catch(t){if(Fu(t))throw new $c(`Unable to read Visa CLI credentials from ${e}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function Vc(e,t=an()){let n=Oo.dirname(t);Me.mkdirSync(n,{recursive:!0,mode:448}),Me.writeFileSync(t,e,{mode:384}),process.platform==="win32"&&sk(t)}function ui(e=an()){try{Me.unlinkSync(e)}catch{}}function sk(e){try{let t=za.userInfo().username;(0,fi.execFile)("icacls",[e,"/inheritance:r","/grant:r",`${t}:F`],{timeout:5e3},n=>{n&&console.error(`[visa-cli] icacls ACL restriction failed: ${n.message}`)})}catch(t){console.error(`[visa-cli] Failed to invoke icacls: ${t instanceof Error?t.message:String(t)}`)}}function Ya(e=Mn,t=an()){switch(process.platform){case"darwin":return{get:()=>ZP(e),store:n=>QP(n,e),delete:()=>ek(e)};case"linux":return{get:()=>tk(e),store:n=>nk(n,e),delete:()=>rk(e)};default:return{get:async()=>xo(t),store:async n=>{try{return Vc(n,t),!0}catch{return!1}},delete:async()=>ui(t),storesInSessionFile:!0}}}var Ht=class{static profileBackend(t){return Ya(Kc(t),br(t))}static async getSessionToken(t=process.env){if(Kt(t))return Promise.resolve(v_());let n=it(t);if(!n&&Co(t).length>0)return null;let r=n?this.profileBackend(n):Ya(),i=n?br(n,t):an(t),o=await r.get();if(o)return o;let a=xo(i);return a?(await r.store(a),a):null}static async saveSessionToken(t,n={}){let r=n.env??process.env;if(Kt(r))return;let i=it(r);if(i){await this.saveProfileSessionToken(i,t,n);return}let o=Ya(),a=an(r),s=await o.store(t);if(s&&await o.get()===t){o.storesInSessionFile||ui(a);return}if(s&&await o.delete(),Vc(t,a),xo(a)!==t)throw new Error("Failed to persist session token in the unlabeled slot.")}static async saveProfileSessionToken(t,n,r={}){let i=r.env??process.env;if(Kt(i))return;let o=this.profileBackend(t),a=br(t,i);if(await o.store(n)){if(await o.get()===n){o.storesInSessionFile||ui(a),r.preserveLegacy||await this.deleteLegacySessionToken(i);return}await o.delete()}if(Vc(n,a),xo(a)!==n)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${Oo.dirname(a)} is writable.`));r.preserveLegacy||await this.deleteLegacySessionToken(i)}static async retireLegacySessionToken(t=process.env){Kt(t)||await this.deleteLegacySessionToken(t)}static async deleteLegacySessionToken(t=process.env){await Ya().delete(),ui(an(t))}static async getRcAccessRecord(t=process.env){if(Kt(t)){let a=qu(t);return{token:a,source:a?"keychain":null}}let n=Hc(t),r=Ro(t),i=await ik(n);if(i)return{token:i,source:"keychain"};let o=xo(r);return o?{token:o,source:"file"}:{token:null,source:null}}static getRcAccessRecordSync(t=process.env){if(Kt(t)){let a=qu(t);return{token:a,source:a?"keychain":null}}let n=Hc(t),r=Ro(t),i=ak(n);if(i)return{token:i,source:"keychain"};let o=xo(r);return o?{token:o,source:"file"}:{token:null,source:null}}static async getRcAccessToken(t=process.env){return(await this.getRcAccessRecord(t)).token}static getRcAccessTokenSync(t=process.env){return this.getRcAccessRecordSync(t).token}static async saveRcAccessToken(t,n=process.env){if(Kt(n))return;let r=Hc(n),i=Ro(n);await ok(t,r);try{Vc(t,i)}catch{}}static async deleteRcAccessToken(t=process.env){if(Kt(t))return;let n=Hc(t),r=Ro(t);await K_(n),n!==Dn&&await K_(Dn),ui(r)}static async deleteSessionToken(t=process.env){if(Kt(t))return;let n=it(t),r=n?this.profileBackend(n):Ya(),i=n?br(n,t):an(t);await r.delete(),ui(i)}static async deleteProfileSessionToken(t,n=process.env){Kt(n)||(await this.profileBackend(t).delete(),ui(br(t,n)))}static async listKeychainItems(t){if(!await sn())return[];try{let{stdout:n}=await ot("security",["dump-keychain"],{timeout:5e3}),r=n.split(`
|
|
28
|
+
`),i=[],o=null,a=null;for(let s of r){s.includes("keychain:")&&(o===t&&a&&!i.includes(a)&&i.push(a),o=null,a=null);let c=s.match(/"svce"<blob>="([^"]+)"/);c&&(o=c[1]);let d=s.match(/"acct"<blob>="([^"]+)"/);d&&(a=d[1])}return o===t&&a&&!i.includes(a)&&i.push(a),i}catch{return[]}}static async listStoredCredentials(t={}){let n=t.env??process.env,r=[];if(process.platform==="darwin"&&await sn())for(let s of["visa-cli","visa-mcp"]){let c=await this.listKeychainItems(s);for(let d of c)r.push({service:s,account:d,backend:"keychain"})}let i=an(n);Me.existsSync(i)&&r.push({service:"visa-cli",account:Mn,backend:"file",path:i});let o=Co(n);for(let s of o){let c=br(s,n);Me.existsSync(c)&&r.push({service:"visa-cli",account:Kc(s),backend:"file",path:c})}let a=Ro(n);return Me.existsSync(a)&&r.push({service:"visa-cli",account:Dn,backend:"file",path:a}),r}static async purgeAll(t={}){let n=t.env??process.env,r=[];if(process.platform==="darwin"&&await sn())for(let s of["visa-cli","visa-mcp"]){let c=await this.listKeychainItems(s);for(let d of c)try{await ot("security",["delete-generic-password","-s",s,"-a",d],{timeout:5e3}),r.push({service:s,account:d,backend:"keychain"})}catch{}}let i=an(n);if(Me.existsSync(i))try{Me.unlinkSync(i),r.push({service:"visa-cli",account:Mn,backend:"file",path:i})}catch{}let o=Ro(n);if(Me.existsSync(o))try{Me.unlinkSync(o),r.push({service:"visa-cli",account:Dn,backend:"file",path:o})}catch{}let a=Co(n);for(let s of a){let c=br(s,n);if(Me.existsSync(c))try{Me.unlinkSync(c),r.push({service:"visa-cli",account:Kc(s),backend:"file",path:c})}catch{}}try{U_(n)}catch{}return await zP(a),r}static async clearAll(t=process.env){for(let n of Co(t))await this.deleteProfileSessionToken(n,t);await this.deleteLegacySessionToken(t),await this.deleteRcAccessToken(t)}};var ck=15*6e4;function Jn(e=process.env){return Yu.join(de(e),"session-recovery")}var dk="pending.json",Gu=/^[A-Za-z0-9_-]{43}$/,V_="ABCDEFGHJKMNPQRSTUVWXYZ23456789",lk=6,uk=512,fk=2048,W_=2147483647;function pi(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Wc(e,t){let n=new Set(t);return Object.keys(e).every(r=>n.has(r))}function pk(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost"||t==="::1")return!0;let n=t.split(".");return n.length===4&&n[0]==="127"&&n.every(r=>/^\d{1,3}$/.test(r)&&Number(r)<=255)}function ze(e){if(typeof e!="string"||e.length===0||e.length>fk)throw new Error("v4 sign-in URL must be a bounded web origin");let t;try{t=new URL(e)}catch{throw new Error("v4 sign-in URL must be a bounded web origin")}if(t.username.length>0||t.password.length>0||t.search.length>0||t.hash.length>0||t.pathname!==""&&t.pathname!=="/"||t.protocol!=="https:"&&!(t.protocol==="http:"&&pk(t.hostname)))throw new Error("v4 sign-in URL must use an HTTPS origin (or HTTP loopback)");return t.origin}function cn(e){let t=(0,No.createHash)("sha256").update(`${e}:visa-cli-handoff-confirm`,"utf8").digest(),n="";for(let r=0;r<lk;r+=1)n+=V_[t[r]%V_.length];return n}function Za(e=Jn()){return Yu.join(e,dk)}function hk(e){Ln.mkdirSync(e,{recursive:!0,mode:448});let t=Ln.lstatSync(e);if(t.isSymbolicLink()||!t.isDirectory())throw new Error("login recovery directory must be a real directory, not a symlink");Ln.chmodSync(e,448),Ye(e)}function mk(e){if(!pi(e)||!Wc(e,["verifier","challenge","baseUrl","createdAt","expiresAt","serverSkewMs"])||typeof e.verifier!="string"||!Gu.test(e.verifier)||typeof e.challenge!="string"||!Gu.test(e.challenge)||typeof e.baseUrl!="string"||!Number.isSafeInteger(e.createdAt)||e.createdAt<0||e.expiresAt!==void 0&&(!Number.isSafeInteger(e.expiresAt)||e.expiresAt<0)||e.serverSkewMs!==void 0&&!Number.isSafeInteger(e.serverSkewMs))return!1;try{return ze(e.baseUrl)===e.baseUrl&&(0,No.createHash)("sha256").update(e.verifier,"utf8").digest("base64url")===e.challenge}catch{return!1}}function F_(e=Jn()){let t=Ue(Za(e),{maxBytes:8192});if(t===null)return null;let n;try{n=JSON.parse(t)}catch{throw new Error("local login recovery state contains invalid JSON")}if(!mk(n))throw new Error("local login recovery state is invalid");return n}function zu(e){return e.expiresAt!==void 0?{deadline:e.expiresAt,skewMs:e.serverSkewMs??0,source:"server"}:{deadline:e.createdAt+ck,skewMs:0,source:"local"}}function Fc(e=Date.now(),t=Jn()){let n=F_(t);if(!n)return null;let r=cn(n.verifier),{deadline:i,skewMs:o,source:a}=zu(n),s=Math.max(0,i-(e+o)),c=Math.floor(s/1e3),d=z_(n,e);return{verifier:n.verifier,challenge:n.challenge,confirmCode:r,baseUrl:n.baseUrl,createdAt:n.createdAt,expiresAt:new Date(i-o).toISOString(),remainingSeconds:c,likelyExpired:d,expirySource:a}}function $_(e=Jn()){Ye(e)&&Ln.rmSync(Za(e),{force:!0})}var gk="/api/vgs/cli-handoff/announce",B_="This Visa server has no terminal sign-in endpoint, so sign-in cannot finish. This is a server problem, not something you did. Please report it.";function G_(e){return!pi(e)||typeof e.error!="string"&&e.ok===void 0}async function yk(e,t,n,r){try{let i=await n(`${e.baseUrl}${gk}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({challenge:e.challenge}),signal:AbortSignal.timeout(r),redirect:"error"}),o=await i.json().catch(()=>null);if(i.status===404&&G_(o))return"route_missing";if(!i.ok||!pi(o)||o.ok!==!0)return null;let a=typeof o.serverTime=="string"?Date.parse(o.serverTime):NaN,s=o.ttlMs;return!Number.isSafeInteger(a)||a<0||typeof s!="number"||!Number.isSafeInteger(s)||s<=0||s>W_?null:{expiresAt:a+s,skewMs:a-t}}catch{return null}}async function Y_(e,t=Date.now(),n=Jn(),r={}){if(!Number.isSafeInteger(t)||t<0)throw new Error("login handoff time is invalid");let i=ze(e),o=Xa(r.requestTimeoutMs,5e3,"login announce timeout"),a=r.fetchImpl??fetch;if(r.verifier!==void 0&&!Gu.test(r.verifier))throw new Error("login handoff verifier is invalid");let s=r.verifier??(0,No.randomBytes)(32).toString("base64url"),c=(0,No.createHash)("sha256").update(s,"utf8").digest("base64url"),d={verifier:s,challenge:c,baseUrl:i,createdAt:t};hk(n),ke(Za(n),JSON.stringify(d,null,2));let l=await yk(d,t,a,o);if(l==="route_missing")throw Ln.rmSync(Za(n),{force:!0}),new Error(B_);l&&(d.expiresAt=l.expiresAt,d.serverSkewMs=l.skewMs,ke(Za(n),JSON.stringify(d,null,2)));let{deadline:u,skewMs:f,source:h}=zu(d);return{challenge:c,confirmCode:cn(s),expiresAt:new Date(u-f).toISOString(),expirySource:h}}function Xa(e,t,n){let r=e??t;if(!Number.isSafeInteger(r)||r<=0||r>W_)throw new Error(`${n} must be a positive integer within the supported range`);return r}function z_(e,t=Date.now()){let{deadline:n,skewMs:r}=zu(e);return t+r>n}function _k(e){if(!pi(e)||!Wc(e,["payload"])||!pi(e.payload)||!Wc(e.payload,["cliSessionToken","ownerProfile"]))return null;let t=e.payload.cliSessionToken,n=e.payload.ownerProfile;return typeof t!="string"||!t.trim()||t.length>uk||!pi(n)||!Wc(n,["ownerPublicId","loginLabel","authOrigin"])||typeof n.ownerPublicId!="string"||typeof n.loginLabel!="string"||typeof n.authOrigin!="string"?null:{sessionToken:t,ownerProfile:{ownerPublicId:n.ownerPublicId,loginLabel:n.loginLabel,authOrigin:n.authOrigin}}}async function Bc(e,t={}){let n=t.loginDir??Jn(),r;try{r=F_(n)}catch(v){return{status:"error",message:v instanceof Error?v.message:String(v)}}if(!r)return{status:"no_pending"};if(e!==void 0){let v;try{v=ze(e)}catch(_){return{status:"error",message:_ instanceof Error?_.message:String(_)}}if(v!==r.baseUrl)return{status:"error",message:"V4 sign-in origin does not match the pending handoff. Run agent login again."}}let i,o,a,s;try{i=Xa(t.attempts,1,"login claim attempts"),o=Xa(t.delayMs,1e3,"login claim interval"),a=Xa(t.requestTimeoutMs,1e4,"login claim request timeout"),s=t.overallTimeoutMs===void 0?void 0:Xa(t.overallTimeoutMs,1,"login claim overall timeout")}catch(v){return{status:"error",message:v instanceof Error?v.message:String(v)}}let c=t.fetchImpl??fetch,d=t.sleep??(v=>new Promise(_=>setTimeout(_,v))),l=t.now??Date.now,u=s===void 0?void 0:l()+s,f=`${r.baseUrl}/api/vgs/cli-handoff/claim`,h=null,p=r,m=p.expiresAt!==void 0,w=()=>h==="expired"||h==="unknown"&&m?{status:"not_ready",likelyExpired:!0,expirySource:"server"}:h==="pending"?{status:"not_ready",likelyExpired:!1,expirySource:"server"}:{status:"not_ready",likelyExpired:z_(p,l()),expirySource:"local"};for(let v=0;v<i;v+=1){let _=u===void 0?a:u-l();if(_<=0)return w();let A,j=AbortSignal.timeout(Math.max(1,Math.min(a,_)));try{A=await c(f,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({verifier:r.verifier}),signal:j,redirect:"error"})}catch(X){if(j.aborted||pi(X)&&X.name==="TimeoutError"){if(u!==void 0&&l()>=u)return w();if(v+1<i){let H=u===void 0?o:u-l();if(H<=0)return w();await d(Math.min(o,H));continue}return{status:"error",message:"V4 sign-in claim request timed out."}}if(v+1<i){let H=u===void 0?o:u-l();if(H<=0)return w();await d(Math.min(o,H));continue}return{status:"error",message:`Could not reach the v4 sign-in service: ${X instanceof Error?X.message:String(X)}`}}if(A.ok){let X=await A.json().catch(()=>null),H=_k(X);if(!H)return{status:"error",message:"Sign-in response was not a session-only handoff. Restart with visa agent login --restart."};try{let V=M_(H.ownerProfile);await Ht.saveProfileSessionToken(V,H.sessionToken,{preserveLegacy:!0}),L_(V),await Ht.retireLegacySessionToken()}catch{return{status:"error",message:"The session reached this device but could not be saved. Fix local credential storage, then restart with visa agent login --restart."}}return $_(n),{status:"claimed"}}if(A.status===404){let X=await A.json().catch(()=>null);if(G_(X))return{status:"error",message:B_};let H=typeof X?.serverTime=="string"&&typeof X.error=="string"?X.error:null;if(H==="expired"?h="expired":H==="unknown_handoff"?h="unknown":H==="not_ready"&&(h="pending"),h==="expired"||h==="unknown"&&m)return w();if(v+1<i){let V=u===void 0?o:u-l();if(V<=0)return w();await d(Math.min(o,V))}continue}if(A.status===409)return{status:"confirm_mismatch",confirmCode:cn(r.verifier)};if(A.status===422)return $_(n),{status:"error",message:"Sign-in pickup was not login-only. Run agent login again."};if(A.status===429)return w();let Q=await A.json().catch(()=>null);return{status:"error",message:typeof Q?.error=="string"&&Q.error.length<=512?Q.error:`V4 sign-in claim failed (${A.status}).`}}return w()}var Gg=x(Q_()),Yg=x(rw());var Dl=require("node:fs"),Bs=require("node:path"),Bi=require("node:crypto"),Ig=x(qo()),Xt=x(Kn()),Gi=x(lp());var pe=x(require("node:fs")),Nr=x(require("node:path")),uv=require("node:crypto");var lv=x(hp());var dv=x(hp());function fv(e){return e?.code==="ENOENT"}function Le(e){let t=JSON.parse(e),n=!1;function r(i){if(!(!i||typeof i!="object"))for(let[o,a]of Object.entries(i)){if(["networkToken","cryptogramValue","card","privateJwk","private_jwk","seed","secretKey","secret_key","privateKey","d"].includes(o))throw new Error("native_metadata_contains_private_material");if(o==="runtimeKey"&&a&&typeof a=="object"){let s=a;n||=s.v===1&&typeof s.handle=="string"&&/^[0-9a-f]{64}$/.test(s.handle)&&typeof s.binding=="object"}r(a)}}if(r(t),!n)throw new Error("native_metadata_record_required")}function pv(e,t=process.platform){if(t!=="win32")return Ye(e);try{let n=pe.lstatSync(e);if(!n.isDirectory()||n.isSymbolicLink())throw new Error("native_metadata_directory_invalid");return!0}catch(n){if(fv(n))return!1;throw n}}function Bt(e,t=process.platform){return hv(e,t,Le)}function hv(e,t,n){if(t!=="win32")return Ue(e);if(!pv(Nr.dirname(e),t))return null;let r;try{let i=pe.lstatSync(e);if(!i.isFile()||i.isSymbolicLink()||i.size>ko)throw new Error("native_metadata_file_invalid");r=pe.openSync(e,pe.constants.O_RDONLY|(pe.constants.O_NOFOLLOW??0));let o=pe.fstatSync(r);if(!o.isFile()||o.dev!==i.dev||o.ino!==i.ino)throw new Error("native_metadata_file_changed");let a=Buffer.alloc(ko+1),s=0;for(;s<a.length;){let d=pe.readSync(r,a,s,a.length-s,null);if(d===0)break;s+=d}if(s>ko)throw new Error("native_metadata_file_too_large");let c=new TextDecoder("utf-8",{fatal:!0}).decode(a.subarray(0,s));return n(c),c}catch(i){if(fv(i))return null;throw i}finally{r!==void 0&&pe.closeSync(r)}}function lt(e,t,n=process.platform){bO(e,t,n,Le)}function bO(e,t,n,r){if(n!=="win32")return ke(e,t);if(r(t),Buffer.byteLength(t)>ko)throw new Error("native_metadata_file_too_large");if(!pv(Nr.dirname(e),n))throw new Error("native_metadata_directory_missing");let i=Nr.join(Nr.dirname(e),`.${Nr.basename(e)}.${(0,uv.randomUUID)()}.tmp`),o;try{if(o=pe.openSync(i,"wx",384),pe.writeFileSync(o,t,"utf8"),pe.fsyncSync(o),pe.closeSync(o),o=void 0,pe.renameSync(i,e),hv(e,n,r)!==t)throw new Error("native_metadata_readback_failed")}finally{o!==void 0&&pe.closeSync(o),pe.rmSync(i,{force:!0})}}var NS=x(kl()),DS=x(vg());async function bg(e){let{key:t,approved:n,result:r}=e;if(!r.certificate.startsWith(n.preparedCertificate.signingInput+".")||!r.delegation.startsWith(n.preparedDelegation.signingInput+"."))throw new Error("financial_device_owner_result_invalid");let i={keys:[{...e.rootPublicJwk,kid:e.rootKid}]},o=Math.floor((e.nowMs??Date.now())/1e3),a=await(0,NS.verifyRuntimeCertificate)(r.certificate,{jwks:i,nowSec:e.certificateAsOfIssue?n.preparedCertificate.claims.iat:o,expectedAgentId:t.binding.agentId,expectedRootJkt:t.binding.rootJkt,expectedRuntimeId:t.runtimeId,expectedRuntimeJkt:t.jkt,requiredPurpose:"wallet:x402"}),s=await(0,DS.verifyRuntimeDelegation)(r.delegation,{ownerJwks:i,nowSec:o,expectedRootKid:e.rootKid,expectedRootJkt:t.binding.rootJkt,expectedAgentId:t.binding.agentId,expectedRuntimeId:t.runtimeId,expectedRuntimeJkt:t.jkt,expectedNetwork:"eip155:8453",expectedLeaseIssuerJkt:n.preparedDelegation.claims.leaseIssuerJkt,expectedDelegationId:n.preparedDelegation.claims.jti});if(!s.ok&&s.reason==="delegation_expired")throw new Error("runtime_delegation_expired");if(r.v!==1||r.runtimeId!==t.runtimeId||r.childJkt!==t.jkt||!a.ok||!s.ok||s.delegation.custody==="gate")throw new Error("financial_device_owner_result_invalid");return r}function ma(e,t){if(!/^[0-9a-f-]{36}$/.test(e))throw new Error("financial_device_agent_invalid");let n=(0,Bs.join)(de(t),"financial-device");return(0,Dl.mkdirSync)(n,{recursive:!0,mode:448}),(0,Bs.join)(n,e+".pending.json")}function ga(e,t){let n=Bt(ma(e,t));if(n===null)return null;Le(n);let r=JSON.parse(n);if((0,Gi.financialDeviceProposalHash)(r.proposal),r.cardProposal&&(0,Gi.assertFinancialDevicePair)(r.proposal,r.cardProposal),r.v===1&&!Object.prototype.hasOwnProperty.call(r,"ceremony")){let i=ma(e,t),o=i.replace(".pending.json",`.outdated.${r.proposal.requestId}.json`);throw(0,Dl.renameSync)(i,o),new Error(`financial_device_record_outdated: this device's wallet approval was started by an older Visa CLI and cannot be resumed (kept as ${(0,Bs.basename)(o)}). Re-enroll: run \`visa connect\` again.`)}if(r.v!==1||!r.ceremony||typeof r.ceremony!="object"||!/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(r.ceremony.ceremonyId)||!/^[A-Za-z0-9_-]{43}$/.test(r.ceremony.challenge)||!/^[A-Za-z0-9_-]{43}$/.test(r.ceremony.verifier)||(0,Bi.createHash)("sha256").update(r.ceremony.verifier).digest("base64url")!==r.ceremony.challenge||r.proposal.agentId!==e||r.runtimeKey.binding.agentId!==e||r.runtimeKey.runtimeId!==r.proposal.runtimeId||r.runtimeKey.binding.rootJkt!==r.proposal.rootJkt||(0,Ig.computeJkt)(r.rootPublicJwk)!==r.proposal.rootJkt)throw new Error("financial_device_record_invalid");return r}function Ag(e,t){let n=JSON.stringify(e);Le(n),lt(ma(e.proposal.agentId,t),n)}async function Gs(e){let t=ga(e.agentId,e.env);if(t){if((0,Xt.canonicalJson)(t.ceremony)!==(0,Xt.canonicalJson)(e.ceremony))throw new Error("financial_device_ceremony_changed");let a=await e.api.financialRuntimeRequest("device-handoff-create",{requestId:t.proposal.requestId,proposal:t.proposal,ceremony:t.ceremony,...t.cardProposal?{cardProposal:t.cardProposal}:{}}),s=Math.floor(Date.now()/1e3),c=a.prepared?.status==="active",d=h=>{if(typeof h!="string")throw new Error("financial_device_record_invalid");let p=JSON.parse(Buffer.from(h.split(".")[1]??"","base64url").toString()).exp;if(!Number.isSafeInteger(p))throw new Error("financial_device_record_invalid");return p>s},l=c&&d(a.prepared?.certificate)&&d(a.prepared?.delegation),u=!a.prepared||a.prepared.status==="pending"&&a.prepared.challenge.expiresAt>s;if(l||!c&&!a.expired&&u)return t;let f={v:1,ceremony:t.ceremony,proposal:{...t.proposal,requestId:(0,Bi.randomUUID)()},runtimeKey:t.runtimeKey,rootKid:t.rootKid,rootPublicJwk:t.rootPublicJwk,...t.cardProposal?{cardProposal:t.cardProposal}:{}};try{await e.api.financialRuntimeRequest("device-handoff-create",{requestId:f.proposal.requestId,proposal:f.proposal,ceremony:f.ceremony,...f.cardProposal?{cardProposal:f.cardProposal}:{}})}catch(h){let p=MS(h)?await LS(e.agentId,e.env,t.proposal.requestId):null;if(p)return p;throw h}return lt(ma(e.agentId,e.env).replace(".pending.json",`.expired.${t.proposal.requestId}.json`),JSON.stringify(t)),Ag(f,e.env),f}let n=await e.api.financialRuntimeRequest("device-context",{requestId:(0,Bi.randomUUID)(),agentId:e.agentId});if(n.agentId!==e.agentId||(0,Ig.computeJkt)(n.rootPublicJwk)!==n.rootJkt)throw new Error("financial_device_context_invalid");if(e.ownerPublicId!==void 0&&typeof n.ownerPublicId=="string"&&n.ownerPublicId!==e.ownerPublicId)throw new Error("Protected wallet owner differs from the active profile");let r=await e.signer.create({profile:"legacy-root-certified-v1",purpose:"wallet:x402",agentId:e.agentId,rootJkt:n.rootJkt}),i={v:1,purpose:"financial.runtime.device.proposal",requestId:(0,Bi.randomUUID)(),associationId:n.associationId,associationVersion:n.associationVersion,agentId:e.agentId,runtimeId:r.runtimeId,rootJkt:n.rootJkt,publicJwk:r.publicJwk,...e.signer.tempoApprovalStamp?{tempoCosign:"v1"}:{}};(0,Gi.financialDeviceProposalHash)(i),e.cardProposal&&(0,Gi.assertFinancialDevicePair)(i,e.cardProposal);let o={v:1,ceremony:e.ceremony,proposal:i,...e.cardProposal?{cardProposal:e.cardProposal}:{},runtimeKey:r,rootKid:n.rootKid,rootPublicJwk:n.rootPublicJwk};return Ag(o,e.env),await e.api.financialRuntimeRequest("device-handoff-create",{requestId:i.requestId,proposal:i,ceremony:o.ceremony,...o.cardProposal?{cardProposal:o.cardProposal}:{}}),o}var ha=class extends Error{constructor(n=!1){super(n?MU:"This enrollment ceremony expired. Start a fresh enrollment; this expired proposal cannot be approved.");this.stopped=n;this.name="FinancialDeviceExpiredError"}stopped},MU="The owner stopped this device approval (the agent was removed), so visa connect did not renew it. Nothing was connected. Run visa connect again once the owner wants this agent connected.";function MS(e){return e instanceof Error&&e.name==="ProtectedAuthorityRefusedError"&&Number(e.status)<500&&!Sg(e)}async function LS(e,t,n){for(let r=0;;r++){let i=ga(e,t);if(i&&i.proposal.requestId!==n)return i;if(r>=LU)return null;await new Promise(o=>setTimeout(o,JU))}}var LU=20,JU=50;function Sg(e){return e instanceof Error&&e.name==="ProtectedAuthorityRefusedError"&&e.code==="agent_revoked"}async function Ml(e){let t=e.pending,n=t.proposal,r=await e.signer.describe(t.runtimeKey.handle);if((0,Xt.canonicalJson)(r)!==(0,Xt.canonicalJson)(t.runtimeKey)||r.binding.profile!=="legacy-root-certified-v1"||r.binding.purpose!=="wallet:x402")throw new Error("financial_device_handle_changed");let i=async(c,d={})=>e.api.financialRuntimeRequest(c,{requestId:n.requestId,proposal:n,...d}),o=await i("device-handoff-read");if(o.published===!1){if((0,Xt.canonicalJson)(o.proposal)!==(0,Xt.canonicalJson)(n))throw new Error("financial_device_proposal_mismatch");o=await e.api.financialRuntimeRequest("device-handoff-create",{requestId:n.requestId,proposal:n,ceremony:t.ceremony,...t.cardProposal?{cardProposal:t.cardProposal}:{}})}if(o.expired&&o.prepared?.status!=="active")throw new ha(o.prepared?.status==="revoked");if((0,Xt.canonicalJson)(o.proposal)!==(0,Xt.canonicalJson)(n))throw new Error("financial_device_proposal_mismatch");let a=o.evidence?.owner_signatures,s=o.prepared;if(a&&s&&!o.evidence?.device_proof){if(await bg({key:r,rootKid:t.rootKid,rootPublicJwk:t.rootPublicJwk,approved:s.challenge,result:{v:1,runtimeId:n.runtimeId,childJkt:r.jkt,...a}}),t.challenge&&(0,Xt.canonicalJson)(t.challenge)!==(0,Xt.canonicalJson)(s.challenge))throw new Error("financial_device_challenge_changed");t.childPop||(t.challenge=s.challenge,t.childPop=await e.signer.financialEnrollmentProof(r.handle,s.challenge),Ag(t,e.env)),o=await i("device-handoff-proof",{childPop:t.childPop})}return o}function Yi(e,t){let n=Bt(ma(e,t).replace(".pending.json",".active.json"));if(n===null)return null;Le(n);let r=JSON.parse(n);if((0,Gi.financialDeviceProposalHash)(r.proposal),r.v!==1||r.proposal.agentId!==e||r.runtimeKey.binding.agentId!==e||r.runtimeKey.binding.profile!=="legacy-root-certified-v1"||r.runtimeKey.binding.purpose!=="wallet:x402"||!r.challenge||!r.certificate||!r.delegation)throw new Error("financial_device_record_invalid");return r}async function UU(e){let t=await Ml(e);return e.onView?.(t),Tg({...e,view:t})}async function Tg(e){let t=e.pending,n=t.proposal,r=e.view;if(r?.prepared?.status!=="active")return null;let i=await e.signer.describe(t.runtimeKey.handle),o=await bg({key:i,rootKid:t.rootKid,rootPublicJwk:t.rootPublicJwk,approved:r.prepared.challenge,result:{v:1,runtimeId:n.runtimeId,childJkt:i.jkt,certificate:r.prepared.certificate,delegation:r.prepared.delegation}}),a=await e.api.financialRuntimeRequest("device-context",{requestId:(0,Bi.randomUUID)(),agentId:n.agentId});if(a.associationId!==n.associationId||a.associationVersion!==n.associationVersion||a.rootJkt!==n.rootJkt||typeof a.grantId!="string"||!Number.isSafeInteger(a.grantVersion)||a.grantVersion<1||typeof a.ownerPublicId!="string")throw new Error("financial_device_activation_changed");let s={...t,challenge:r.prepared.challenge,certificate:o.certificate,delegation:o.delegation,organizationId:a.organizationId,ownerPublicId:a.ownerPublicId,grantId:a.grantId,grantVersion:a.grantVersion},c=JSON.stringify(s);return Le(c),lt(ma(n.agentId,e.env).replace(".pending.json",".active.json"),c),s}async function JS(e){try{return{active:await UU(e),pending:e.pending,renewed:!1}}catch(t){if(Sg(t))throw new ha(!0);let n=e.pending.ceremony&&MS(t)?await LS(e.pending.proposal.agentId,e.env,e.pending.proposal.requestId):null;if(n)return{active:null,pending:n,renewed:!0};if(!(t instanceof ha)||!e.pending.ceremony||t.stopped)throw t;let r=e.pending.proposal.requestId,i;try{i=await Gs({api:e.api,signer:e.signer,agentId:e.pending.proposal.agentId,ceremony:e.pending.ceremony,env:e.env}),e.onView?.(await Ml({...e,pending:i}))}catch(o){let a=o instanceof Error&&o.name==="ProtectedAuthorityRefusedError"&&o.status<500;throw R.warn("agent:device_approval_renewal_refused",{agentId:e.pending.proposal.agentId,expiredRequestId:r,refused:a,error:o instanceof Error?o.message:String(o)}),Sg(o)?new ha(!0):a?t:o}return R.info("agent:device_approval_renewed",{agentId:i.proposal.agentId,expiredRequestId:r,requestId:i.proposal.requestId}),{active:null,pending:i,renewed:!0}}}var dc=require("node:crypto"),Sn=require("node:fs"),Oe=require("node:path");var US=/^[A-Za-z0-9_-]{43}$/,jU=/^[0-9a-f]{64}$/,qU=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;function Pg(e,t){let n=e;return!!n&&typeof n=="object"&&jU.test(n.handle)&&qU.test(n.runtimeId)&&n.purpose===t&&US.test(n.jkt)&&!!n.publicJwk&&n.publicJwk.kty==="OKP"&&n.publicJwk.crv==="Ed25519"&&US.test(n.publicJwk.x)}function kg(e){let t=e;if(!t||t.v!==2||!Pg(t.wallet,"wallet:x402")||!Pg(t.card,"card:vic")||!Pg(t.tap,"tap")||new Set([t.wallet.jkt,t.card.jkt,t.tap.jkt]).size!==3)throw new Error("device_key_reservation_invalid");return t}async function jS(e){return{v:2,wallet:await e.reserve("wallet:x402"),card:await e.reserve("card:vic"),tap:await e.reserve("tap")}}function Ll(e){return`${e.wallet.jkt}.${e.card.jkt}.${e.tap.jkt}`}function qS(e,t){let n={"wallet:x402":t.wallet,"card:vic":t.card,tap:t.tap};return{create:(r,i)=>e.adopt(n[r.purpose].handle,r,i),describe:r=>e.describe(r),delete:r=>e.delete(r),enrollmentProof:(r,i)=>e.enrollmentProof(r,i),handoffProof:(r,i)=>e.handoffProof(r,i),leaseProof:(r,i)=>e.leaseProof(r,i),tapProof:(r,i,o)=>e.tapProof(r,i,o),financialEnrollmentProof:(r,i)=>e.financialEnrollmentProof(r,i),cardEnrollmentProof:(r,i)=>e.cardEnrollmentProof(r,i),legacyProof:(r,i)=>e.legacyProof(r,i),legacyLeaseProof:(r,i)=>e.legacyLeaseProof(r,i),proofKey:r=>e.proofKey(r),close:()=>e.close()}}var J0=x(qo()),tr=x(Ng()),Bl=x(Gr()),Sa=x(Kn());var S0=x(require("fs")),I0=x(require("os")),ba=x(require("path"));function _6(e){return[["openclaw",ba.join(e,".openclaw")],["hermes",ba.join(e,".hermes")],["claude-code",ba.join(e,".claude")],["codex",ba.join(e,".codex")],["gemini",ba.join(e,".gemini")]]}function T0(e=process.env,t={}){if(e.VISA_CLI_RUNTIME&&e.VISA_CLI_RUNTIME.trim().length>0)return e.VISA_CLI_RUNTIME.trim();if(e.AGENT_RUNTIME&&e.AGENT_RUNTIME.trim().length>0)return e.AGENT_RUNTIME.trim();let n=a=>Object.entries(e).some(([s,c])=>s.startsWith(a)&&typeof c=="string"&&c.trim()!==""),r=new Set;if(n("CODEX_")&&r.add("codex"),(typeof e.CLAUDECODE=="string"&&e.CLAUDECODE.trim()!==""||n("CLAUDE_CODE_")||typeof e.CLAUDE_PROJECT_DIR=="string"&&e.CLAUDE_PROJECT_DIR.trim()!=="")&&r.add("claude-code"),n("OPENCLAW_")&&r.add("openclaw"),n("HERMES_")&&r.add("hermes"),(n("ANTIGRAVITY_")||n("GEMINI_"))&&r.add("gemini"),r.size>0)return r.size===1?r.values().next().value:void 0;let i=t.home??I0.homedir(),o=_6(i).filter(([,a])=>S0.existsSync(a));return o.length===1?o[0][0]:void 0}var k0=require("node:child_process"),C0=x(require("node:os")),w6=64,E6={platform:process.platform,computerName:()=>{try{return(0,k0.execFileSync)("scutil",["--get","ComputerName"],{encoding:"utf8",timeout:1e3,stdio:["ignore","pipe","ignore"]})}catch{return null}},hostname:()=>C0.default.hostname()};function $l(e=E6){let t=e.platform==="darwin"?[e.computerName(),P0(e)]:[P0(e)];for(let n of t){let r=v6(n);if(r)return r}return null}function P0(e){try{return e.hostname().replace(/\.local\.?$/i,"")}catch{return null}}function v6(e){if(typeof e!="string")return null;let t=e.normalize("NFC").replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu," ").replace(/\s+/gu," ").trim();return t&&Array.from(t).slice(0,w6).join("").trim()||null}var x0=require("node:crypto");var $g=null,R0=null,Wg=null;function b6(){return Wg||(Wg=`ms_${(0,x0.randomUUID)().replace(/-/g,"")}`),Wg}function A6(){return $g?R0?`${$g}/${R0}`.slice(0,96):$g:null}function Aa(){let e={"X-Visa-MCP-Session":b6()},t=A6();return t&&(e["X-Visa-MCP-Client"]=t),e}var Wl=x(sc()),O0=x(sc()),Fg=x(sc()),cc=class extends Error{code="update_required";errorCode="update_required";runningVersion;minCompatibleVersion;updateCommand;constructor(t,n,r){let i=`CLI/MCP update required${r?` for ${r}`:""}: running v${t}, minimum compatible version is v${n}. Run: npm install -g @visa/cli@rc`;super(i),this.name="UpdateRequiredError",this.runningVersion=t,this.minCompatibleVersion=n,this.updateCommand="npm install -g @visa/cli@rc"}toJSON(){return{success:!1,error_code:this.errorCode,error:this.message,runningVersion:this.runningVersion,minCompatibleVersion:this.minCompatibleVersion,updateCommand:this.updateCommand}}};function Fl(e,t,n){let r=t&&typeof t=="object"&&!Array.isArray(t)?t:{},i=e<200||e>=300||r.ok===!1||r.success===!1;if(e!==426&&!(i&&[r.error,r.code,r.error_code,r.errorCode].includes("update_required")))return null;let o=(a,s)=>typeof a=="string"&&a.length<=64&&!/[^0-9A-Za-z.+-]/.test(a)&&(0,Wl.isSemverVersion)(a)?a.replace(/^v/,""):s;return new cc(o(r.runningVersion,n),o(r.minCompatibleVersion,O0.DEFAULT_MIN_COMPATIBLE_CLI_VERSION))}var N0="5.0.0-rc.409",C6=(0,tr.toDisplay)((0,tr.fromCents)(Bl.SETUP_DEFAULT_DAILY_CENTS),{decimals:0,symbol:""}),R6=(0,tr.toDisplay)((0,tr.fromCents)(Bl.SETUP_DEFAULT_PER_PURCHASE_CENTS),{decimals:0,symbol:""}),Yr=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,lc=/^[A-Za-z0-9_-]{43}$/,U0=e=>(0,dc.createHash)("sha256").update(e).digest("base64url");function nr(e){let t=ze(e);if(new URL(t).protocol!=="https:")throw new Error("Protected enrollment requires the HTTPS Auth origin");return t}function Xr(e){let t=(0,Oe.join)(de(e),"protected-enrollment");return(0,Sn.mkdirSync)(t,{recursive:!0,mode:448}),Ye(t),t}function zg(e,t,n){if(!e||e.status!=="active"||e.v!==1||!Yr.test(e.ceremonyId)||e.challenge!==t||e.confirmCode!==n||!lc.test(t)||!/^[ABCDEFGHJKMNPQRSTUVWXYZ23456789]{6}$/.test(n)||!Yr.test(e.agentId)||!Yr.test(e.ownerPublicId)||!Yr.test(e.associationId)||!Number.isSafeInteger(e.associationVersion)||e.associationVersion<1||typeof e.rootKid!="string"||!e.rootKid||typeof e.organizationId!="string"||!e.organizationId||(0,J0.computeJkt)(e.rootPublicJwk)!==e.rootJkt)throw new Error("Protected enrollment result does not match this terminal")}function At(e){let t=Ue((0,Oe.join)(Xr(e),"pending.json"));if(t===null)return null;let n=JSON.parse(t);if(n.v!==1||!lc.test(n.verifier)||U0(n.verifier)!==n.challenge||nr(n.authorityOrigin)!==n.authorityOrigin||nr(n.executionOrigin)!==n.executionOrigin||ze(n.webOrigin)!==n.webOrigin||!Number.isSafeInteger(n.createdAt)||!(/^(?:ca_[A-Za-z0-9_-]{24})$/.test(n.ceremonyId)||Yr.test(n.ceremonyId))||n.signIn!==void 0&&n.signIn!==!0||n.restart!==void 0&&n.restart!==!0||n.requestedLimits!==void 0&&!j0(n.requestedLimits))throw new Error("Protected enrollment pending state or transport profile changed");if(n.transportProfileId!==(it(e)?.profileId??null)&&!Zg(n,e))throw new Error("Protected enrollment pending state or transport profile changed");if(n.bindingClaimedAt!==void 0&&(!n.binding||!Number.isSafeInteger(n.bindingClaimedAt)||n.bindingClaimedAt<n.createdAt))throw new Error("Protected enrollment claim receipt changed");if(n.binding&&(zg(n.binding,n.challenge,cn(n.verifier)),n.ceremonyId!==n.binding.ceremonyId))throw new Error("Protected enrollment ceremony changed");if(n.deviceKeys!==void 0&&kg(n.deviceKeys),n.webStartKey!==void 0&&!lc.test(n.webStartKey))throw new Error("Protected enrollment pending state or transport profile changed");return x6(n,e),n}function x6(e,t){let n=Date.now();if(!(!e.binding||e.bindingClaimedAt===void 0||e.bindingClaimedAt<=n)){R.warn("agent:protected_enrollment_claim_receipt_clamped",{ref:e.challenge.slice(0,8),skewMs:e.bindingClaimedAt-n}),e.bindingClaimedAt=n,e.createdAt>n&&(e.createdAt=n);try{ke((0,Oe.join)(Xr(t),"pending.json"),JSON.stringify(e))}catch(r){R.warn("agent:protected_enrollment_claim_receipt_clamp_unsaved",{ref:e.challenge.slice(0,8),errorName:zr(r)})}}}function j0(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e,n=r=>r===void 0||Number.isSafeInteger(r)&&r>0;return Object.keys(t).every(r=>r==="dailyCents"||r==="perPurchaseCents")&&(t.dailyCents!==void 0||t.perPurchaseCents!==void 0)&&n(t.dailyCents)&&n(t.perPurchaseCents)}function uc(e){if(!e)return null;let t={...e.dailyCents!==void 0?{dailyCents:e.dailyCents}:{},...e.perPurchaseCents!==void 0?{perPurchaseCents:e.perPurchaseCents}:{}};return t.dailyCents===void 0&&t.perPurchaseCents===void 0?null:t}function q0(e,t){return e?.dailyCents===t?.dailyCents&&e?.perPurchaseCents===t?.perPurchaseCents}function D0(e){return e?[...e.dailyCents!==void 0?[`${(0,tr.formatCents)(e.dailyCents)} a day`]:[],...e.perPurchaseCents!==void 0?[`${(0,tr.formatCents)(e.perPurchaseCents)} a purchase`]:[]].join(" and "):"no limits"}function Xg(e,t){let n=uc(t),r=uc(e.requestedLimits);if(!(!n||q0(r,n)))throw R.warn("agent:protected_enrollment_limits_mismatch",{ceremonyId:e.ceremonyId,savedDailyCents:r?.dailyCents??null,savedPerPurchaseCents:r?.perPurchaseCents??null,requestedDailyCents:n.dailyCents??null,requestedPerPurchaseCents:n.perPurchaseCents??null}),new ge(`This computer's setup is already waiting for the owner's approval and asked for ${D0(r)}, not ${D0(n)}. Nothing was changed.`,"invalid_argument",{fix:"visa connect --restart",nextAction:"To keep the open approval, run `visa connect` without --ceiling/--per-transaction (agent_enroll: omit ceiling and per_transaction); the owner can still change the limits on the page. To ask for the new limits instead, run `visa connect --restart` with them (agent_enroll: restart:true) and give the owner the new link and code.",details:{savedLimits:r,requestedLimits:n}})}function O6(e,t){let n=uc(t);return!n||q0(uc(e.requestedLimits),n)}var K0=lc;function Zg(e,t){let n=it(t);return e.signIn!==!0||e.binding||e.transportProfileId!==null||!n?!1:(e.transportProfileId=n.profileId,ke((0,Oe.join)(Xr(t),"pending.json"),JSON.stringify(e)),!0)}function Zr(e){return e.signIn===!0&&e.transportProfileId===null&&!e.binding}async function H0(e,t,n){return e.deviceKeys?kg(e.deviceKeys):(e.deviceKeys=await jS(t),ke((0,Oe.join)(Xr(n),"pending.json"),JSON.stringify(e)),e.deviceKeys)}function V0(e,t){let n;try{n=At(t)}catch{return null}return n?.challenge===e&&n.deviceKeys?Ll(n.deviceKeys):null}var Qg=9e5;function to(e,t=Date.now()){return t-(e.binding?e.bindingClaimedAt??e.createdAt:e.createdAt)<Qg}var M0=new Set(["cli_enrollment_claim_refused","enrollment_expired"]),$0="Protected enrollment revalidation changed the accepted binding";async function W0(e,t=fetch){let n;try{n=At(e.env)}catch(o){R.warn("agent:protected_enrollment_revalidate_skipped",{reason:"unreadable",errorName:zr(o)});return}if(!n||to(n)||Zr(n)||Ia(n,e.env)||e.webStartKey!==void 0&&e.webStartKey!==n.webStartKey)return;let r={ref:n.challenge.slice(0,8),bound:!!n.binding};if(n.webOrigin!==ze(e.webOrigin)||n.authorityOrigin!==nr(Nn())||n.executionOrigin!==n.authorityOrigin){R.warn("agent:protected_enrollment_revalidate_skipped",{...r,reason:"origin"});return}if(!O6(n,e.requestedLimits)){n.binding&&Xg(n,e.requestedLimits),R.info("agent:protected_enrollment_revalidate_skipped",{...r,reason:"limits"});return}R.info("agent:protected_enrollment_revalidate_attempt",r);let i;try{i=await ny(n,e.env,t,!0)}catch(o){if(o instanceof tt&&o.status<500){let a={...r,outcome:"refused",status:o.status,code:o.code};if(!n.binding&&o.code!==null&&M0.has(o.code)){R.warn("agent:protected_enrollment_revalidated",{...a,next:"replace"});return}if(o.code!==null&&M0.has(o.code))throw R.warn("agent:protected_enrollment_revalidated",{...a,next:"restart"}),new ge("This computer's earlier setup was approved but did not finish in time, and Visa no longer accepts it. Nothing was changed.","enrollment_expired")}throw R.warn("agent:protected_enrollment_revalidated",{...r,outcome:o instanceof Error&&o.message===$0?"binding_changed":"failed",errorName:zr(o)}),o}if(!i){if(!n.binding){R.info("agent:protected_enrollment_revalidated",{...r,outcome:"still_pending"});return}throw R.warn("agent:protected_enrollment_revalidated",{...r,outcome:"still_pending"}),new Error("The previously accepted setup is not available from the Authority; the saved request was preserved")}R.info("agent:protected_enrollment_revalidated",{...r,outcome:"accepted"})}function Ia(e,t){if(!e.binding)return!1;try{return Yi(e.binding.agentId,t)?.ceremony?.challenge===e.challenge}catch{return!1}}function N6(e){try{return At(e)}catch(t){return R.warn("agent:protected_enrollment_pending_replaced",{reason:t instanceof Error?t.message:"pending record could not be read"}),null}}function F0(e,t){let n,r;try{n=At(t),r=nr(Nn()),e=ze(e)}catch{return!1}return!!(n?.restart===!0&&to(n)&&n.authorityOrigin===r&&n.executionOrigin===r&&n.webOrigin===e&&!Ia(n,t))}function B0(e){let t=uc(e.requestedLimits);if(t&&!j0(t))throw new ge("Requested limits must be whole positive cents.","invalid_argument");let n=nr(Nn()),r=ze(e.webOrigin);if(e.webStartKey!==void 0&&!lc.test(e.webStartKey))throw new ge("That setup key is not one Visa issued. Copy the whole `visa connect --setup` line from the page that started the setup.","invalid_argument");let i=N6(e.env),o=e.restart===!0||e.webStartKey!==void 0&&i?.webStartKey!==e.webStartKey,a=i!==null&&to(i);if(i&&a&&!o){if(i.authorityOrigin!==n||i.webOrigin!==r||i.executionOrigin!==n)throw new Error("Resume requires the original protected authority and browser origins");return Xg(i,t),i}if(i?.binding&&a&&o&&!Ia(i,e.env))throw new ge("This enrollment is already bound. Resume its device approval before starting another agent.","enrollment_device_approval_pending");let s=(0,dc.randomBytes)(32).toString("base64url"),c={v:1,verifier:s,challenge:U0(s),authorityOrigin:n,executionOrigin:n,webOrigin:r,transportProfileId:it(e.env)?.profileId??null,createdAt:Date.now(),ceremonyId:"ca_"+(0,dc.randomBytes)(18).toString("base64url"),...e.webStartKey!==void 0?{webStartKey:e.webStartKey}:{},...e.signIn&&!it(e.env)?{signIn:!0}:{},...e.restart===!0?{restart:!0}:{},...t?{requestedLimits:t}:{}};return ke((0,Oe.join)(Xr(e.env),"pending.json"),JSON.stringify(c)),c}var Bg={"claude-code":"claude",codex:"codex",openclaw:"openclaw",hermes:"hermes",gemini:"gemini",antigravity:"gemini","gemini-cli":"gemini"};function ey(e=process.env,t){let n=(t??"").trim().toLowerCase().replace(/[\s_]+/g,"-");if(n&&Bg[n])return Bg[n];let r=T0(e);return r&&Bg[r]||null}var D6="/api/vgs/cli-handoff/enrollment-code";async function G0(e,t=fetch,n=5e3){if(e.binding)return!1;try{return(await t(`${e.webOrigin}${D6}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({challenge:e.challenge,confirm:cn(e.verifier)}),redirect:"error",signal:AbortSignal.timeout(n)})).ok}catch{return!1}}var M6="/api/vgs/cli-handoff/web-start-pickup";async function Y0(e,t=fetch,n=5e3,r={name:()=>$l(),os:process.platform}){if(!e.webStartKey||!e.deviceKeys||e.binding)return!1;let i=e.challenge.slice(0,8),o=Date.now();try{let a=await t(`${e.webOrigin}${M6}`,{method:"POST",headers:{"content-type":"application/json"},body:JSON.stringify({startKey:e.webStartKey,challenge:e.challenge,confirm:cn(e.verifier),keys:Ll(e.deviceKeys),signIn:Zr(e),device:{name:r.name(),os:r.os},...e.requestedLimits?{limits:e.requestedLimits}:{}}),redirect:"error",signal:AbortSignal.timeout(n)});return R.info("connect:web_start_announce",{ref:i,elapsedMs:Date.now()-o,ok:a.ok,...a.ok?{}:{status:a.status}}),a.ok}catch(a){return R.info("connect:web_start_announce",{ref:i,elapsedMs:Date.now()-o,ok:!1,error:zr(a)||"unknown"}),!1}}var L6=8;function z0(e,t,{heldAgentId:n=null,priorRuntimes:r=[],limits:i=null}={}){let o=new URL("/agent/enroll/protected-agent",e.webOrigin);o.searchParams.set("cliChallenge",e.challenge),n&&Yr.test(n)&&!e.webStartKey&&o.searchParams.set("held",n),e.deviceKeys&&o.searchParams.set("keys",Ll(e.deviceKeys)),e.webStartKey&&o.searchParams.set("start",e.webStartKey),t&&o.searchParams.set("app",t);let a=r.filter(s=>Yr.test(s)).slice(0,L6);return a.length&&!e.webStartKey&&o.searchParams.set("prior",a.join(",")),Zr(e)&&o.searchParams.set("signin","1"),i?.dailyCents!==void 0&&o.searchParams.set("limitDaily",String(i.dailyCents)),i?.perPurchaseCents!==void 0&&o.searchParams.set("limitPer",String(i.perPurchaseCents)),o.toString()}var J6=2e4;var eo=class extends Error{constructor(n,r,i){super(r==="timeout"?`${n} timed out after ${Math.round(i/1e3)} s`:r==="response"?`${n} answered, but the answer could not be read`:`${n} could not be reached`);this.reason=r;this.name="ProtectedAuthorityTransportError"}reason},tt=class extends Error{constructor(n,r,i,o=null,a=null,s=null,c=(0,Yg.decodeRefusal)({code:i,reason:o,purchaseId:a},r)){super(`${n} refused this request (HTTP ${r}${i?`, ${i}`:""})`);this.status=r;this.code=i;this.reason=o;this.purchaseId=a;this.approval=s;this.diagnostic=c;this.name="ProtectedAuthorityRefusedError"}status;code;reason;purchaseId;approval;diagnostic};function zr(e){let t=e&&typeof e=="object"?e.name:void 0;return typeof t=="string"?t:""}function U6(e,t){let n=e&&typeof e=="object"&&!Array.isArray(e)?e:{},r=(0,Yg.decodeRefusal)(e,t);return{code:r.code==="unknown_refusal"?null:r.code,reason:r.reason,diagnostic:r,approval:r.code==="owner_approval_required"?j6(n.approval):null,purchaseId:r.reason==="terms_conflict"?r.purchaseId:null}}function j6(e){if(!e||typeof e!="object"||Array.isArray(e))return null;let{approvalId:t,url:n,expiresAt:r}=e;return typeof t!="string"||t.length>64||typeof n!="string"||n.length>2048||typeof r!="string"||r.length>64?null:{approvalId:t,url:n,expiresAt:r}}function q6(e="Protected authority",t=J6,n={}){return{timeoutMs:t,maxResponseChars:262144,headers:{...n,"content-type":"application/json","X-Source":"cli","X-Visa-CLI-Version":N0,...Aa()},transportError:r=>new eo(e,r,t),refusal:(r,i)=>{let o=Fl(r,i,N0);if(o)return o;let{code:a,reason:s,purchaseId:c,approval:d,diagnostic:l}=U6(i,r);return new tt(e,r,a,s,c,d,l)}}}var K6=e=>()=>(0,Sa.canonicalJson)(JSON.parse(JSON.stringify(e)));function ty(e,t,n,r){return(0,Gg.signedJsonPost)(nr(e)+t,K6(n),q6(),r)}async function X0(e,t=fetch){let n=await ty(e.executionOrigin,"/v1/enrollment/cli-setup",{verifier:e.verifier},t);if(n?.ok!==!0||n.result?.v!==1||!["awaiting_owner","activating","action_required","connected","declined","expired","superseded"].includes(n.result.state)||!["approve","provision_identity","set_limit","add_funds","connect_terminal","wait_for_terminal","approve_device","wait","reconnect","restart","none"].includes(n.result.nextAction)||e.binding&&n.result.agentId!==e.binding.agentId)throw new Error("Protected authority setup response invalid");return n.result}function H6(e,t=fetch){return nr(e),{financialRuntimeRequest:(n,r)=>ty(e,`/v1/financial-runtime/${n}`,r,t)}}function V6(e){return`This agent belongs to a different Visa account than ${e}, the account this terminal is signed in to, so nothing was connected. To use ${e}: run \`visa connect --restart\` and open the new link while signed in to ${e}. To use the other account instead: run \`visa disconnect --all\` to sign this terminal out, then \`visa connect\` and sign in with that account. \`visa disconnect --all\` also removes the Visa MCP server from every AI client, the spend HUD and any local card-delivery files; \`visa connect\` puts the server and HUD back for the client it runs for. Nothing is revoked on the server.`}async function ny(e,t,n=fetch,r=!1){if(e.transportProfileId!==(it(t)?.profileId??null))throw new Error("Protected enrollment transport profile changed");if(e.binding&&!r)return L0(e,e.binding,t),e.binding;if(Zr(e))return null;let i=await ty(e.executionOrigin,"/v1/enrollment/cli-claim",{verifier:e.verifier},n);if(i?.ok!==!0)throw new Error("Protected authority refused enrollment pickup");if(i.result?.status==="pending")return null;let o=i.result;zg(o,e.challenge,cn(e.verifier));let a=it(t);if(a&&o.ownerPublicId!==a.ownerPublicId)throw new ge(V6(a.loginLabel),"enrollment_owner_mismatch");if(e.binding&&["ceremonyId","challenge","confirmCode","associationId","associationVersion","agentId","ownerPublicId","rootJkt","rootKid","organizationId"].some(s=>e.binding[s]!==o[s]))throw new Error($0);return e.bindingClaimedAt=Math.max(Date.now(),e.createdAt),e.ceremonyId=o.ceremonyId,e.binding=o,ke((0,Oe.join)(Xr(t),"pending.json"),JSON.stringify(e)),L0(e,o,t),o}function $6(e,t){let n=de(t);if((0,Sn.existsSync)((0,Oe.join)(n,"financial-device",`${e}.active.json`)))return!0;try{let r=Ue((0,Oe.join)(n,"card-device",`${e}.json`));if(r&&JSON.parse(r)?.certificate)return!0}catch{}return!1}function L0(e,t,n){let r={v:1,authorityOrigin:e.authorityOrigin,executionOrigin:e.executionOrigin,transportProfileId:e.transportProfileId,binding:t},i=(0,Oe.join)(Xr(n),`${t.agentId}.json`),o=Ue(i);if(o!==null&&(0,Sa.canonicalJson)(JSON.parse(o))!==(0,Sa.canonicalJson)(r)){let a=null;try{a=JSON.parse(o)}catch{}if(!(a!==null&&W6(a,r)||!$6(t.agentId,n)))throw new Error("Protected agent selection changed");F6(t.agentId,n)}ke(i,JSON.stringify(r))}function W6(e,t){let n=e?.binding,r=t.binding;return e?.v===1&&!!n&&n.agentId===r.agentId&&n.associationId===r.associationId&&n.ownerPublicId===r.ownerPublicId&&n.organizationId===r.organizationId&&n.rootJkt===r.rootJkt&&e.authorityOrigin===t.authorityOrigin&&e.executionOrigin===t.executionOrigin&&e.transportProfileId===t.transportProfileId&&n.challenge!==r.challenge&&Number.isSafeInteger(n.associationVersion)&&r.associationVersion>=n.associationVersion}function F6(e,t){if(!/^[0-9a-f-]{36}$/.test(e))throw new Error("Protected agent id is invalid");let n=`.replaced-${new Date().toISOString().replace(/[:.]/g,"-")}`,r=de(t),i=o=>(o===`${e}.json`||o.startsWith(`${e}.`))&&o.endsWith(".json")&&!o.includes(".replaced-")&&!o.includes(".bak");for(let o of[(0,Oe.join)(r,"protected-enrollment"),(0,Oe.join)(r,"protected-enrollment","retired"),(0,Oe.join)(r,"card-device"),(0,Oe.join)(r,"financial-device"),(0,Oe.join)(r,"financial-device-presence")])if((0,Sn.existsSync)(o))for(let a of(0,Sn.readdirSync)(o))i(a)&&(0,Sn.renameSync)((0,Oe.join)(o,a),(0,Oe.join)(o,a+n));R.info("protected-enrollment:replaced-agent-records-archived",{agentId:e})}function In(e,t=fetch){let n=H6(e.executionOrigin,t);return{financialRuntimeRequest:async(r,i)=>{let o=await n.financialRuntimeRequest(r,i);if(r==="device-context"){let a=e.binding;if(o.agentId!==a.agentId||o.ownerPublicId!==a.ownerPublicId||o.associationId!==a.associationId||o.associationVersion!==a.associationVersion||o.rootJkt!==a.rootJkt||o.rootKid!==a.rootKid||o.organizationId!==a.organizationId||(0,Sa.canonicalJson)(o.rootPublicJwk)!==(0,Sa.canonicalJson)(a.rootPublicJwk))throw new Error("Protected device context differs from the independently claimed owner")}return o}}}function ry(e){let t=Xr(e);return(0,Sn.readdirSync)(t).filter(n=>Yr.test(n.replace(/\.json$/,""))&&n.endsWith(".json")).flatMap(n=>{let r=Ue((0,Oe.join)(t,n));if(r===null)return[];let i=JSON.parse(r);if(i.v!==1||nr(i.authorityOrigin)!==i.authorityOrigin||nr(i.executionOrigin)!==i.executionOrigin||i.binding.agentId+".json"!==n)throw new Error("Protected selection is invalid");return zg(i.binding,i.binding.challenge,i.binding.confirmCode),[i]})}function Qr(e){let t=it(e)?.profileId??null;return ry(e).filter(n=>n.transportProfileId===t)}function Z0(e,t){let n=Qr(t).find(i=>i.binding.agentId===e.agentId&&i.binding.ownerPublicId===e.ownerPublicId&&i.authorityOrigin===e.authUrl);if(!n||!e.financialDeviceRuntimeId)return;let r=Yi(e.agentId,t);if(!r||r.runtimeKey.runtimeId!==e.financialDeviceRuntimeId||r.ownerPublicId!==n.binding.ownerPublicId||r.proposal.associationId!==n.binding.associationId||r.proposal.associationVersion!==n.binding.associationVersion||r.proposal.rootJkt!==n.binding.rootJkt||r.rootKid!==n.binding.rootKid)throw new Error("Protected wallet installation differs from its independently claimed owner");return n}var zl=x(require("node:fs")),rI=x(require("node:path"));var Mt=x(require("node:fs")),Q0=x(require("node:os")),rr=x(require("node:path"));var eI=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,B6=eI;function Tn(e=process.env){if(e.VISA_V4_HOME)return e.VISA_V4_HOME;let t=e.VISA_CLI_HOME;return typeof t=="string"&&t.trim().length>0?rr.join(t,".visa-v4"):rr.join(Q0.homedir(),".visa-v4")}function tI(e=Tn()){return rr.join(e,"owners")}function iy(e=Tn(),t){if(t!==void 0){if(!B6.test(t))throw new Error("wallet owner id must be a canonical UUID");return rr.join(tI(e),t.toLowerCase(),"agents")}return rr.join(e,"agents")}function fc(e,t=Tn(),n){if(!eI.test(e))throw new Error("wallet agent id must be a canonical UUID");return rr.join(iy(t,n),e.toLowerCase())}function Gl(e){try{let t=Mt.lstatSync(e);if(!t.isDirectory()||t.isSymbolicLink())throw new Error(`wallet runtime path is not a private directory: ${e}`)}catch(t){if(t.code!=="ENOENT")throw t;Mt.mkdirSync(e,{mode:448})}Mt.chmodSync(e,448)}function nI(e,t=Tn(),n){if(Mt.mkdirSync(t,{recursive:!0,mode:448}),n!==void 0){let o=tI(t);Gl(o),Gl(rr.dirname(iy(t,n)))}let r=iy(t,n);Gl(r);let i=fc(e,t,n);return Gl(i),i}var G6=/^0x[0-9a-f]{40}$/i,Y6=/^eip155:[1-9][0-9]{0,18}$/,Yl=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,z6="wallet-authority.json";function oy(e=process.env){return Tn(e)}function ay(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return t.version===1&&(t.financialDeviceRuntimeId===void 0||typeof t.financialDeviceRuntimeId=="string"&&Yl.test(t.financialDeviceRuntimeId))&&(t.executionMode===void 0||t.executionMode==="direct_runtime"||t.executionMode==="managed")&&(t.walletBinding===void 0||/^[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+\.[A-Za-z0-9_-]+$/.test(t.walletBinding)&&t.walletBinding.length<=32*1024)&&(t.managedWallet===void 0||typeof t.managedWallet=="object"&&t.managedWallet!==null&&typeof t.managedWallet.organizationId=="string"&&t.managedWallet.organizationId.length>0&&typeof t.managedWallet.walletId=="string"&&t.managedWallet.walletId.length>0&&typeof t.managedWallet.address=="string"&&G6.test(t.managedWallet.address)&&typeof t.managedWallet.network=="string"&&Y6.test(t.managedWallet.network))&&(t.activationState===void 0||t.activationState==="pending"||t.activationState==="active")&&(t.executionState===void 0||t.executionState==="active"||t.executionState==="recovery_only")&&typeof t.agentId=="string"&&Yl.test(t.agentId)&&typeof t.agentName=="string"&&t.agentName.length>0&&t.agentName.length<=120&&(t.ownerPublicId===void 0||Yl.test(t.ownerPublicId))&&typeof t.grantId=="string"&&Yl.test(t.grantId)&&Number.isSafeInteger(t.grantVersion)&&t.grantVersion>0&&t.rail==="wallet:x402"&&typeof t.authUrl=="string"&&X6(t.authUrl)&&typeof t.activatedAt=="string"&&Number.isFinite(Date.parse(t.activatedAt))}function X6(e){try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:")&&t.username===""&&t.password===""&&t.pathname==="/"&&t.search===""&&t.hash===""&&e===t.origin}catch{return!1}}function iI(e=oy()){return rI.join(e,z6)}function Z6(e,t){if(!ay(e))throw new no("wallet authority binding is invalid");zl.mkdirSync(t,{recursive:!0,mode:448}),zl.chmodSync(t,448),Ye(t),ke(iI(t),`${JSON.stringify(e,null,2)}
|
|
29
|
+
`)}function oI(e=oy()){let t=Ue(iI(e));if(t===null)return null;try{let n=JSON.parse(t);if(!ay(n))throw new no("wallet authority binding is malformed");return n}catch(n){throw n instanceof no?n:new no("wallet authority binding is malformed")}}var no=class extends Error{code="wallet_delivery_required";constructor(t){super(`wallet delivery unusable: ${t}`),this.name="WalletDeliveryRequiredError"}};function aI(e){let t={...e.authorityBinding,executionMode:"managed",activationState:"active"};if(!t.financialDeviceRuntimeId||!ay(t))throw new no("wallet authority binding is invalid");let n=e.homeDir??nI(t.agentId,oy(),t.ownerPublicId);Z6(t,n),R.info("wallet-delivery: device authority binding installed",{agentId:t.agentId,runtimeId:t.financialDeviceRuntimeId})}var Q6=60*6e4,dI=6e4,sy=1e3,sI=15e3,cI=1e3;function e4(e){let t=typeof e?.expiresAt=="string"?Date.parse(e.expiresAt):NaN,n=e?.prepared?.status==="pending"&&typeof e.prepared.challenge?.expiresAt=="number"?e.prepared.challenge.expiresAt*1e3:NaN,r=[t,n].filter(i=>Number.isFinite(i));return r.length?Math.min(...r):null}function t4(e){let t=sy;if(e.now-e.fastSince>=dI){let n=Math.min(sy*2**Math.min(e.slowTicks,10),sI);t=Math.min(Math.round(n*(.8+.4*e.random())),sI)}return e.closesAt!==null&&e.closesAt+cI>e.now&&(t=Math.min(t,e.closesAt+cI-e.now)),Math.max(sy,Math.min(t,e.deadline-e.now))}async function lI(e){let t=e.sleep??(p=>new Promise(m=>setTimeout(m,p))),n=e.now??(()=>Date.now()),r=e.random??Math.random,i=null,o=p=>{i=e4(p)},a=await Gs(e);await e.onProposalPublished?.(a);let s=n(),c=0,d=async()=>{let p=await JS({...e,pending:a,onView:o});return p.renewed&&(a=p.pending,await e.onProposalPublished?.(a)),p.active},l=await d(),u=l?cy(e,l):null,f=l?.grantId,h=a.cardProposal?await e.advanceCompanion?.()===!0:!0;if(await e.advanceTap?.(),!l||!h){let p=n()+Q6;for(;(!l||!h)&&n()<p;){let m=n();m-s>=dI&&c++,await t(t4({now:m,fastSince:s,slowTicks:c,closesAt:i,deadline:p,random:r})),l=await d(),l&&(!u||l.grantId!==f)&&(u=cy(e,l),f=l.grantId),h=a.cardProposal?await e.advanceCompanion?.()===!0:!0,await e.advanceTap?.()}}if(!l||!h||!u)throw new Error("Device approval is still pending. Keep this enrollment command running; the native key and owner request are preserved.");return u}async function uI(e){let t=await Tg(e);return t?cy(e,t):!1}function cy(e,t){if(t.ownerPublicId!==e.ownerPublicId)throw new Error("Protected wallet owner differs from the active profile");return aI({authorityBinding:{version:1,agentId:e.agentId,ownerPublicId:e.ownerPublicId,agentName:e.agentName,grantId:t.grantId,grantVersion:t.grantVersion,rail:"wallet:x402",authUrl:new URL(e.authUrl).origin,activatedAt:new Date().toISOString(),financialDeviceRuntimeId:t.runtimeKey.runtimeId},homeDir:e.walletHomeDir}),!0}var sr=require("node:fs"),nu=require("node:path"),cr=require("node:crypto"),nt=x(Kn()),HI=x(qo()),VI=x(kl()),au=x(lp());var ie=require("node:fs"),ar=require("node:crypto"),mc=require("node:path"),or=x(Gr()),DI=x(kl()),MI=x(py());var hc=require("node:crypto"),io=x(Gr()),CI=x(qo()),RI=x(kI());function xI(e,t){let n=t.tapPublicMaterial;if(!t.gateEnrollment||!n||n.associationId!==e.proposal.associationId||n.associationVersion!==e.proposal.associationVersion||n.agentId!==e.proposal.agentId||n.rootJkt!==e.proposal.rootJkt||!Number.isSafeInteger(n.tapKeyEpoch)||n.tapKeyEpoch<0||(0,CI.computeJkt)(n.tapKey.jwk)!==n.tapKey.jkt||n.custody!==void 0&&!["root-via-gate","runtime"].includes(n.custody)||typeof n.observation!="string"||!Number.isSafeInteger(n.expiresAt)||n.expiresAt<=Math.floor(Date.now()/1e3))throw new Error("identity_device_public_material_invalid");return{...n,custody:n.custody??"root-via-gate"}}function OI(e){if(e?.ok!==!0||!e.result||typeof e.result!="object")throw new Error("identity_device_response_invalid");return e.result}async function my(e){let t=OI(await e.api.identityDeviceRequest("association",{agentId:e.agentId}));if(t.agentId!==e.agentId||t.rootJkt!==e.expectedRootJkt||t.associationId!==e.associationId)throw new Error("identity_device_owner_root_mismatch");let n=await e.native.describe(e.key.handle);if((0,io.canonicalJson)(n)!==(0,io.canonicalJson)(e.key)||n.binding.profile!=="identity-tap-v1"||n.binding.purpose!=="tap"||n.binding.associationId!==t.associationId||n.binding.agentId!==e.agentId||n.binding.rootJkt!==e.expectedRootJkt)throw new Error("identity_device_tap_key_binding_mismatch");let r={v:1,handoffId:(0,hc.randomUUID)(),runtimeKey:n,proposal:{...t,runtimeId:n.runtimeId,runtimeJkt:n.jkt,runtimePublicJwk:n.publicJwk}};return(0,RI.identityDeviceProposalSha256)(r.proposal),await e.persist(r),await ir(e.api,e.native,r,"create"),r}async function ir(e,t,n,r,i,o,a){let s=await t.describe(n.runtimeKey.handle);if((0,io.canonicalJson)(s)!==(0,io.canonicalJson)(n.runtimeKey)||s.jkt!==n.proposal.runtimeJkt||s.runtimeId!==n.proposal.runtimeId)throw new Error("native_runtime_handle_mismatch");let c=r==="cancel"?{v:1,operation:r,requestId:(0,hc.randomUUID)(),handoffId:n.handoffId,proposal:n.proposal,body:{enrollmentRequestId:o??null,generation:a??null}}:r==="proof"?{v:1,operation:r,requestId:(0,hc.randomUUID)(),handoffId:n.handoffId,proposal:n.proposal,body:{enrollmentRequestId:o,runtimeProof:i}}:{v:1,operation:r,requestId:r==="create"?n.handoffId:(0,hc.randomUUID)(),handoffId:n.handoffId,proposal:n.proposal,body:{}},d=await t.handoffProof(s.handle,c),l=OI(await e.identityDeviceRequest("handoff",{request:c,runtimeProof:d}));if(l.handoffId!==n.handoffId||(0,io.canonicalJson)(l.proposal)!==(0,io.canonicalJson)(n.proposal)||!Number.isSafeInteger(l.expiresAt)||!["proposed","pending","active","expired","retired","revoked","cancelled"].includes(l.status))throw new Error("identity_device_response_invalid");return l}async function Zl(e,t,n){let r=await ir(e,t,n,"read");if(r.status==="pending"&&!r.runtimeProof){if(!r.challenge||r.enrollmentRequestId!==r.challenge.requestId)throw new Error("identity_device_response_invalid");let i=await t.enrollmentProof(n.runtimeKey.handle,r.challenge);return ir(e,t,n,"proof",i,r.enrollmentRequestId)}return r}function NI(e,t,n={}){let r=`?device=${encodeURIComponent(t.handoffId)}&association=${encodeURIComponent(t.proposal.associationId)}&tap=${encodeURIComponent(t.proposal.runtimeJkt)}`+(n.revoke?"&deviceAction=revoke":"");return`${e}${n.revoke?"":"/protected-agent"}${r}`}var Ql=e=>/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/.test(e),v4=600*1e3;function LI(e){if(!Number.isSafeInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return!!(t&&typeof t=="object"&&t.code==="EPERM")}}function JI(e){return e&&typeof e=="object"?e.code:void 0}function UI(e,t,n){let r;try{r=(0,ie.openSync)(e,"r")}catch{return!0}try{let i=(0,ie.fstatSync)(r).mtimeMs;try{let o=JSON.parse((0,ie.readFileSync)(r,"utf8")),a=typeof o.createdAt=="string"?Date.parse(o.createdAt):NaN;return o.version===1&&Number.isSafeInteger(o.pid)&&(o.pid??0)>0&&typeof o.token=="string"&&o.token.length>0&&Number.isFinite(a)?!LI(o.pid):t.getTime()-(Number.isFinite(a)?a:i)>=n}catch{return t.getTime()-i>=n}}finally{(0,ie.closeSync)(r)}}function b4(e,t,n){let r=`${e}.${(0,ar.randomUUID)()}`;(0,ie.writeFileSync)(r,JSON.stringify({pid:process.pid,createdAt:t.toISOString()}),{mode:384,flag:"wx"});try{return(0,ie.linkSync)(r,e),!0}catch(a){if(JI(a)!=="EEXIST")throw a}finally{(0,ie.unlinkSync)(r)}let i;try{let a=(0,ie.openSync)(e,"r");try{i=(0,ie.readFileSync)(a,"utf8")}finally{(0,ie.closeSync)(a)}}catch{return!1}let o=!0;try{let a=JSON.parse(i),s=typeof a.createdAt=="string"?Date.parse(a.createdAt):NaN;o=!LI(a.pid??0)||!(t.getTime()-s<n)}catch{}if(o)try{(0,ie.unlinkSync)(e)}catch{}return!1}function A4(e,t,n){let r=`${e}.reclaim`;if(!b4(r,t,n))return!1;try{if(!UI(e,t,n))return!1;try{(0,ie.unlinkSync)(e)}catch(i){if(JI(i)!=="ENOENT")return!1}return!0}finally{try{(0,ie.unlinkSync)(r)}catch{}}}function oo(e){if(!Ql(e.agentId))throw new Error("identity_device_agent_invalid");let t=(0,mc.join)(de(e.env),"identity-runtime-renewal-locks");(0,ie.mkdirSync)(t,{recursive:!0,mode:448}),(0,ie.chmodSync)(t,448);let n=(0,mc.join)(t,`${e.agentId}.${e.purpose??"tap"}.lock`),r=e.now??new Date,i=e.staleMs??v4;for(let o=0;o<2;o+=1){let a=(0,ar.randomUUID)(),s={version:1,pid:process.pid,token:a,createdAt:r.toISOString()};try{let c=(0,ie.openSync)(n,"wx",384);try{(0,ie.writeFileSync)(c,JSON.stringify(s),"utf8"),(0,ie.fsyncSync)(c)}finally{(0,ie.closeSync)(c)}return()=>{try{JSON.parse((0,ie.readFileSync)(n,"utf8")).token===a&&(0,ie.unlinkSync)(n)}catch{}}}catch(c){if(!c||typeof c!="object"||c.code!=="EEXIST")throw c;if(!UI(n,r,i)||!A4(n,r,i))return null}}return null}function gc(e,t){if(!Ql(e))throw new Error("identity_device_agent_invalid");let n=(0,mc.join)(de(t),"financial-device-presence");return(0,ie.mkdirSync)(n,{recursive:!0,mode:448}),(0,mc.join)(n,`${e}.pending.json`)}function Ta(e,t){let n=Bt(gc(e,t));if(n===null)return null;Le(n);let r=JSON.parse(n);if(r.v!==1||r.proposal?.agentId!==e||!Ql(r.handoffId)||!r.runtimeKey?.handle)throw new Error("identity_device_record_invalid");return r}function eu(e,t){Le(JSON.stringify(e));let n=gc(e.proposal.agentId,t),r=Bt(n);if(r){let i=JSON.parse(r);i.handoffId!==e.handoffId&<(n.replace(".pending.json",`.${i.handoffId}.history.json`),r)}lt(n,JSON.stringify(e))}async function yc(e){let{pending:t,view:n}=e,r=Math.floor(Date.now()/1e3);if(n.handoffId!==t.handoffId||n.status!=="active"||!n.authorizationId||!Ql(n.authorizationId)||!Number.isSafeInteger(n.authorizationVersion)||Number(n.authorizationVersion)<1||!n.certificate||!n.delegation||!n.gateAuthorization||(0,or.canonicalJson)(n.proposal)!==(0,or.canonicalJson)(t.proposal))throw new Error("identity_device_activation_invalid");xI(t,n);let i=n.challenge;if(!i||i.runtimeId!==t.proposal.runtimeId||i.runtimeJkt!==t.proposal.runtimeJkt||i.associationId!==t.proposal.associationId||i.associationVersion!==t.proposal.associationVersion)throw new Error("identity_device_challenge_invalid");for(let[u,f]of[[n.certificate,i.certificateSha256],[n.delegation,i.delegationSha256],[n.gateAuthorization,i.gateAuthorizationSha256]])if((0,ar.createHash)("sha256").update(u.split(".").slice(0,2).join(".")).digest("base64url")!==f)throw new Error("identity_device_signed_preparation_mismatch");if(!(await(0,DI.verifyRuntimeCertificate)(n.certificate,{jwks:{keys:[{...e.rootPublicJwk,kid:e.rootKid}]},expectedAgentId:t.proposal.agentId,expectedRootJkt:t.proposal.rootJkt,expectedRuntimeJkt:t.proposal.runtimeJkt,expectedRuntimeId:t.proposal.runtimeId,requiredPurpose:"tap",nowSec:e.collectedRenewal?JSON.parse(Buffer.from(n.certificate.split(".")[1],"base64url").toString("utf8")).iat:r})).ok)throw new Error("identity_device_certificate_invalid");let a=JSON.parse(Buffer.from(n.delegation.split(".")[1],"base64url").toString("utf8"));await(0,MI.verifyIdentityTapDelegation)(n.delegation,{ownerJwks:{keys:[{...e.rootPublicJwk,kid:e.rootKid}]},expectedRootKid:e.rootKid,expectedRootJkt:t.proposal.rootJkt,expectedAgentId:t.proposal.agentId,expectedRuntimeId:t.proposal.runtimeId,expectedRuntimeJkt:t.proposal.runtimeJkt,expectedLeaseIssuerJkt:a.leaseIssuerJkt,expectedNetwork:a.network,expectedDelegationId:a.jti,nowSec:r});let s=n.gateAuthorization.split("."),c={ok:s.length===3&&(0,ar.verify)(null,Buffer.from(s.slice(0,2).join(".")),(0,ar.createPublicKey)({key:{...e.rootPublicJwk},format:"jwk"}),Buffer.from(s[2],"base64url")),header:JSON.parse(Buffer.from(s[0],"base64url").toString("utf8")),claims:JSON.parse(Buffer.from(s[1],"base64url").toString("utf8"))};if(!c.ok||c.header.alg!=="EdDSA"||c.header.kid!==e.rootKid||c.header.typ!=="visa-agent-identity-gate-authorization+jwt"||c.claims.iss!==t.proposal.rootJkt||c.claims.sub!==t.proposal.agentId||c.claims.aud!=="urn:visa:tvc:identity-gate"||c.claims.generation!==n.challenge?.generation||!Number.isSafeInteger(c.claims.exp)||Number(c.claims.exp)<=r||!Number.isSafeInteger(c.claims.nbf)||Number(c.claims.nbf)>r||(0,or.canonicalJson)(c.claims.purposes)!==(0,or.canonicalJson)(["tap_signature_base"]))throw new Error("identity_device_gate_authorization_invalid");let d=await e.native.describe(t.runtimeKey.handle);if((0,or.canonicalJson)(d)!==(0,or.canonicalJson)(t.runtimeKey))throw new Error("native_runtime_handle_mismatch");let l={...t,active:n,rootPublicJwk:e.rootPublicJwk,rootKid:e.rootKid};return Le(JSON.stringify(l)),lt(gc(t.proposal.agentId,e.env).replace(".pending.json",`.${t.proposal.runtimeId}.active.json`),JSON.stringify(l)),lt(gc(t.proposal.agentId,e.env).replace(".pending.json",".selected.json"),JSON.stringify(l)),R.info("identity_device_selected",{agentId:t.proposal.agentId,handoffId:t.handoffId}),l}function S4(e){let t=e.runtimeKey?.binding;return t?t.profile==="identity-tap-v1"?t.purpose==="tap"&&t.associationId===e.proposal?.associationId:t.profile==="legacy-root-certified-v1"&&t.purpose==="wallet:x402":!1}function gy(e){return e.runtimeKey.binding.profile==="legacy-root-certified-v1"}function en(e,t){let n=Bt(gc(e,t).replace(".pending.json",".selected.json"));if(n===null)return null;Le(n);let r=JSON.parse(n);if(r.v!==1||r.revoked!==void 0&&r.revoked!==!0||r.proposal?.agentId!==e||!S4(r)||r.active?.status!=="active"||r.active.handoffId!==r.handoffId||!r.rootKid||!r.rootPublicJwk||(0,or.canonicalJson)(r.active.proposal)!==(0,or.canonicalJson)(r.proposal))throw new Error("identity_device_selected_invalid");return r}function I4(e,t){return e?e.ceremonyId===t.binding.ceremonyId&&e.challenge===t.binding.challenge&&/^[A-Za-z0-9_-]{43}$/.test(e.verifier)&&(0,cr.createHash)("sha256").update(e.verifier).digest("base64url")===e.challenge:!0}function _y(e,t){if(e&&(e.ceremonyId!==t.binding.ceremonyId||e.challenge!==t.binding.challenge||!/^[A-Za-z0-9_-]{43}$/.test(e.verifier)||(0,cr.createHash)("sha256").update(e.verifier).digest("base64url")!==e.challenge))throw new Error("card_device_ceremony_changed")}function _c(e,t){if(!/^[0-9a-f-]{36}$/.test(e))throw new Error("card_device_agent_invalid");let n=(0,nu.join)(de(t),"card-device");return(0,sr.mkdirSync)(n,{recursive:!0,mode:448}),(0,nu.join)(n,`${e}.json`)}function tu(e,t){let n=JSON.stringify(e);Le(n),lt(_c(e.proposal.agentId,t),n)}function ru(e,t){return _c(e,t).replace(/\.json$/,".renewal.json")}function jI(e,t){let n=JSON.stringify(e);Le(n),lt(ru(e.proposal.agentId,t),n)}function $I(e,t){let n=Bt(e);if(n===null)return null;Le(n);let r=JSON.parse(n),i=r.proposal,o=t.binding,a=r.runtimeKey;if((0,au.financialDeviceProposalHash)(i),!r.certificate&&(!I4(r.ceremony,t)||i.associationId!==o.associationId||i.associationVersion!==o.associationVersion||i.rootJkt!==o.rootJkt)){let c=e.replace(".json",`.${i?.requestId??(0,cr.randomUUID)()}.superseded.json`);return(0,sr.renameSync)(e,c),null}if(_y(r.ceremony,t),r.v!==1||r.initialConnection!==void 0&&r.initialConnection!==!0||i.v!==2||i.agentId!==o.agentId||i.associationId!==o.associationId||i.associationVersion!==o.associationVersion||i.rootJkt!==o.rootJkt||a.binding.profile!=="legacy-root-certified-v1"||a.binding.purpose!=="card:vic"||a.binding.agentId!==o.agentId||a.binding.rootJkt!==o.rootJkt||a.runtimeId!==i.runtimeId||a.jkt!==(0,HI.computeJkt)(i.publicJwk)||(0,nt.canonicalJson)(a.publicJwk)!==(0,nt.canonicalJson)(i.publicJwk))throw new Error("card_device_record_invalid");return r}function ti(e,t){return $I(_c(e.binding.agentId,t),e)}function yy(e,t,n){let r=$I(ru(e.binding.agentId,n),e);if(r&&(r.ceremony||r.initialConnection))throw new Error("card_device_record_invalid");return r&&(0,nt.canonicalJson)(r.runtimeKey)===(0,nt.canonicalJson)(t.runtimeKey)?r:null}function WI(e,t,n,r){let i=ze(e);if(new URL(i).protocol!=="https:")throw new Error("card_connection_https_required");(0,au.financialDeviceProposalHash)(t.proposal);let o=new URL("/agent/enroll/protected-agent",i);if(t.ceremony){o.searchParams.set("cliChallenge",t.ceremony.challenge);let a=V0(t.ceremony.challenge,r);a&&o.searchParams.set("keys",a)}else o.searchParams.set("cardDevice",Buffer.from((0,nt.canonicalJson)(t.proposal)).toString("base64url"));return n&&o.searchParams.set("app",n),o.toString()}async function iu(e,t,n,r=Math.floor(Date.now()/1e3)){let i=e.challenge,o=e.proposal;if(!i||i.v!==1||i.audience!=="visa:financial:card-actor-enrollment:v1"||i.requestId!==o.requestId||i.associationId!==o.associationId||i.associationVersion!==o.associationVersion||i.runtimeId!==o.runtimeId||i.childJkt!==e.runtimeKey.jkt||i.generation!==1||!Number.isSafeInteger(i.expiresAt)||!n.startsWith(i.preparedCertificate.signingInput+"."))throw new Error("card_device_certificate_changed");let a=await(0,VI.verifyRuntimeCertificate)(n,{jwks:{keys:[{...t.binding.rootPublicJwk,kid:t.binding.rootKid}]},nowSec:r,expectedAgentId:e.proposal.agentId,expectedRootJkt:e.proposal.rootJkt,expectedRuntimeId:e.proposal.runtimeId,expectedRuntimeJkt:e.runtimeKey.jkt,requiredPurpose:"card:vic"});if(!a.ok||(0,nt.canonicalJson)(a.claims.purposes)!=='["card:vic"]')throw new Error("card_device_certificate_invalid");return a.claims}async function FI(e){let{selection:t,signer:n,env:r}=e,i=ti(t,r);if(!i){let o=await n.create({profile:"legacy-root-certified-v1",purpose:"card:vic",agentId:t.binding.agentId,rootJkt:t.binding.rootJkt});i={v:1,runtimeKey:o,ceremony:e.ceremony,...e.initialConnection?{initialConnection:!0}:{},proposal:{v:2,rail:"card:vic",purpose:"financial.runtime.device.proposal",requestId:(0,cr.randomUUID)(),agentId:t.binding.agentId,associationId:t.binding.associationId,associationVersion:t.binding.associationVersion,rootJkt:t.binding.rootJkt,runtimeId:o.runtimeId,publicJwk:o.publicJwk}},tu(i,r)}return i}async function BI(e){_y(e.ceremony,e.selection);let t=oo({agentId:e.selection.binding.agentId,purpose:"card",env:e.env});if(!t)throw new Error("card_device_busy");try{let n=await FI(e);if((0,nt.canonicalJson)(await e.signer.describe(n.runtimeKey.handle))!==(0,nt.canonicalJson)(n.runtimeKey))throw new Error("card_device_handle_changed");return n}finally{t()}}async function qI(e,t,n,r){let{selection:i,signer:o,api:a,env:s}=n,c=e.proposal,d;try{d=await a.financialRuntimeRequest("device-handoff-read",{requestId:c.requestId,proposal:c})}catch(f){if(!(f instanceof tt)||f.status!==400||f.code!=="financial_runtime_refused")throw f;d={proposal:c,published:!1,prepared:null,expired:!1,evidence:{}}}if(d.published===!1&&e.ceremony)try{d=await a.financialRuntimeRequest("device-handoff-create",{requestId:c.requestId,proposal:c,ceremony:e.ceremony})}catch(f){if(!(f instanceof tt)||f.status!==400||f.code!=="financial_runtime_refused")throw f;delete e.ceremony,r(e)}if((0,nt.canonicalJson)(d.proposal)!==(0,nt.canonicalJson)(c))throw new Error("card_device_proposal_changed");let l=d.prepared?.challenge,u=d.evidence?.owner_signatures?.certificate;if(d.prepared?.status==="revoked"||d.prepared?.status==="expired")throw new Error("card_device_connection_revoked");if(d.expired&&d.prepared?.status!=="active"){lt(_c(c.agentId,s).replace(".json",`.${c.requestId}.expired.json`),JSON.stringify(e));let f=e.ceremony||d.prepared?.kind==="enroll"?await o.create(t.binding):t;return r({v:1,runtimeKey:f,ceremony:e.ceremony,proposal:{...c,requestId:(0,cr.randomUUID)(),runtimeId:f.runtimeId,publicJwk:f.publicJwk}}),{status:"retry"}}if(l&&typeof u=="string"){if(e.challenge&&(0,nt.canonicalJson)(e.challenge)!==(0,nt.canonicalJson)(l))throw new Error("card_device_challenge_changed");e.challenge=l;let f=await iu(e,i,u,d.prepared?.status==="active"?l.preparedCertificate.claims.iat:void 0);if(!d.evidence?.device_proof&&d.prepared?.status!=="active"&&(e.childPop||(e.childPop=await o.cardEnrollmentProof(t.handle,l),r(e)),d=await a.financialRuntimeRequest("device-handoff-proof",{requestId:c.requestId,proposal:c,childPop:e.childPop})),d.prepared?.status==="active"){if(d.prepared.certificate!==u)throw new Error("card_device_certificate_changed");return e.certificate=u,r(e),f.exp<=Math.floor(Date.now()/1e3)+30?{status:"retry"}:{status:"active",record:e}}}if(d.expired)throw new Error("card_device_preparation_expired");return{status:"awaiting_owner",proposal:c,hash:(0,au.financialDeviceProposalHash)(c),published:d.published!==!1}}function KI(e,t){lt(_c(e.proposal.agentId,t).replace(".json",`.${e.proposal.requestId}.completed.json`),JSON.stringify(e))}async function wc(e){let{selection:t,signer:n,env:r}=e;_y(e.ceremony,t);let i=oo({agentId:t.binding.agentId,purpose:"card",env:r});if(!i)return{status:"busy"};try{let o=await FI(e),a=await n.describe(o.runtimeKey.handle);if((0,nt.canonicalJson)(a)!==(0,nt.canonicalJson)(o.runtimeKey))throw new Error("card_device_handle_changed");if(o.certificate){let s=JSON.parse(Buffer.from(o.certificate.split(".")[1]??"","base64url").toString());await iu(o,t,o.certificate,s.iat);let c=Math.floor(Date.now()/1e3);if(s.exp>c+30){await iu(o,t,o.certificate);let l=e.renewWithinSeconds===void 0?null:yy(t,o,r);if(!l&&s.exp>c+(e.renewWithinSeconds??0))return{status:"active",record:o};let u=l??{v:1,proposal:{...o.proposal,requestId:(0,cr.randomUUID)()},runtimeKey:o.runtimeKey};l||jI(u,r);let f=await qI(u,a,e,h=>jI(h,r));return f.status!=="active"||(KI(o,r),tu(f.record,r),(0,sr.rmSync)(ru(t.binding.agentId,r),{force:!0})),f}KI(o,r);let d=yy(t,o,r);o=d??{v:1,proposal:{...o.proposal,requestId:(0,cr.randomUUID)()},runtimeKey:o.runtimeKey},tu(o,r),d&&(0,sr.rmSync)(ru(t.binding.agentId,r),{force:!0})}return await qI(o,a,e,s=>tu(s,r))}finally{i()}}var ou=720*60*60;async function wy(e,t,n=Math.floor(Date.now()/1e3)){let r={state:"none",renew:!1},i=e.binding.agentId,o;try{o=ti(e,t)}catch{return r}if(!o)return r;if(!o.certificate){let s=!1;try{s=(0,sr.readdirSync)((0,nu.join)(de(t),"card-device")).some(c=>c.startsWith(`${i}.`)&&c.endsWith(".completed.json"))}catch{s=!1}return s&&!o.ceremony&&!o.initialConnection?{state:"renewing",renew:!0}:r}let a;try{a=JSON.parse(Buffer.from(o.certificate.split(".")[1]??"","base64url").toString()),await iu(o,e,o.certificate,a.iat)}catch{return r}try{if(yy(e,o,t))return{state:"renewing",renew:!0}}catch{}return a.exp<=n+30?{state:"expired",renew:!0}:a.exp-n<ou?{state:"renew_due",renew:a.exp-a.iat>=ou}:{state:"live",renew:!1}}var Ke=require("node:crypto"),tn=x(Gr()),tT=x(qo()),nT=x(XI()),N4={"wallet:x402":["visa-agent-operations:v1","visa-wallet-authority:local-v1","visa:financial:wallet-device-handoff:v1","visa:financial:device-operations:v1","visa-tempo-mpp-payment:v1","visa-tempo-mpp-report:v1","visa-tempo-mpp-history:v1"],"card:vic":["visa-agent-operations:v1","visa-auth-card-draw","visa:purchase-resource:v1","visa:financial:card-device-handoff:v1","visa:card-admission-recovery:v1"]},rT=Number.MAX_SAFE_INTEGER,D4=Buffer.from("302e020100300506032b657004220420","hex");function I(e){throw new Error(e)}var M4=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,we=e=>typeof e=="string"&&M4.test(e);function bc(e){if(!/^[A-Za-z0-9_-]*$/.test(e))return null;let t=Buffer.from(e,"base64url");return t.toString("base64url")===e?t:null}var ni=e=>typeof e=="string"&&bc(e)?.length===32,lr=e=>(0,Ke.createHash)("sha256").update(e).digest("base64url");function ri(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Re(e,t){return ri(e)||I("request_invalid"),(Object.keys(e).filter(r=>e[r]!==void 0).length!==t.length||t.some(r=>!Object.hasOwn(e,r)))&&I("request_invalid"),e}function S(e,t){let n=e[t];return typeof n!="string"&&I("request_invalid"),n}function te(e,t){let n=e[t];return(typeof n!="number"||!Number.isSafeInteger(n)||n<0||n>rT)&&I("request_invalid"),n}function Pn(e,t){try{return(0,tn.canonicalJson)(e)===(0,tn.canonicalJson)(t)}catch{return!1}}function ZI(e){let t=bc(e);t||I("request_invalid");try{return JSON.parse(t.toString("utf8"))}catch{I("request_invalid")}}var Pa=class{constructor(t,n,r){this.binding=n;this.runtimeId=r;let i=Buffer.concat([D4,t]);try{this.#e=(0,Ke.createPrivateKey)({key:i,format:"der",type:"pkcs8"})}finally{i.fill(0)}let o=(0,Ke.createPublicKey)(this.#e).export({format:"jwk"}).x;typeof o!="string"&&I("custody_record_invalid"),this.publicJwk={kty:"OKP",crv:"Ed25519",x:o},this.jkt=lr((0,tn.canonicalJson)(this.publicJwk))}binding;runtimeId;publicJwk;jkt;#e;signature(t){return(0,Ke.sign)(null,Buffer.from(t),this.#e)}signer(){return{kid:this.jkt,publicJwk:this.publicJwk,sign:async t=>new Uint8Array(this.signature(t))}}};function by(e){ri(e)||I("identity_binding_invalid");let t=["profile","associationId","agentId","rootJkt","purpose"];Object.keys(e).some(d=>!t.includes(d))&&I("identity_binding_invalid");let{profile:n,associationId:r,agentId:i,rootJkt:o,purpose:a}=e,s=n==="identity-tap-v1"&&a==="tap"&&we(r),c=n==="legacy-root-certified-v1"&&r===void 0&&(a==="wallet:x402"||a==="card:vic");return(!we(i)||!ni(o)||!(s||c))&&I("identity_binding_invalid"),s?{profile:"identity-tap-v1",associationId:r,agentId:i,rootJkt:o,purpose:"tap"}:{profile:"legacy-root-certified-v1",agentId:i,rootJkt:o,purpose:a}}function L4(e){let t={agentId:"00000000-0000-4000-8000-000000000000",rootJkt:"A".repeat(43)};return e==="tap"?{profile:"identity-tap-v1",associationId:"00000000-0000-4000-8000-000000000000",...t,purpose:e}:{profile:"legacy-root-certified-v1",...t,purpose:e}}function vc(e){return e.binding.profile==="identity-tap-v1"&&e.binding.purpose==="tap"||e.binding.profile==="legacy-root-certified-v1"&&e.binding.purpose==="wallet:x402"}function cu(e,t){e.binding.purpose!==t&&I("key_purpose_mismatch")}function Ec(e){e.binding.profile!=="legacy-root-certified-v1"&&I("legacy_custody_profile_required")}function QI(e,t){let n=S(t,"associationId"),r=e.binding.profile==="identity-tap-v1"?e.binding.associationId:void 0;(!(r!==void 0?r===n:vc(e)&&we(n))||S(t,"agentId")!==e.binding.agentId||S(t,"runtimeId")!==e.runtimeId)&&I("identity_binding_mismatch"),(te(t,"associationVersion")===0||te(t,"generation")===0)&&I("request_invalid")}function Ay(e,t){let n=Re(e,["claims","signingInput"]),r=S(n,"signingInput");r.length>16384&&I("request_invalid");let i=r.split(".");i.length!==2&&I("request_invalid");let o=Re(ZI(i[0]),["alg","kid","typ"]),a=S(o,"kid");return(S(o,"alg")!=="EdDSA"||S(o,"typ")!==t||a.length===0||a.length>256||!/^[A-Za-z0-9._:@/-]+$/.test(a)||!Pn(ZI(i[1]),n.claims))&&I("request_invalid"),ri(n.claims)||I("request_invalid"),{claims:n.claims,kid:a}}var iT=["v","iss","sub","jti","runtimeId","runtimeJkt","leaseIssuerJkt","purpose","network","signingModes","maxLeaseTtlSeconds","iat","nbf","exp"],J4=[...iT,"custody","rails"],eT=["v","iss","sub","jti","runtimeId","cnf","purposes","iat","nbf","exp"],du=class{#e;#t;constructor(t,n={}){this.#e=t,this.#t=n.nowSec??(()=>Math.floor(Date.now()/1e3))}async holds(t){try{return await this.load(t),"held"}catch(n){return n.message==="custody_unavailable"?"missing":"unknown"}}async load(t){/^[0-9a-f]{64}$/.test(t)||I("custody_handle_invalid");let n=await this.#e.read(t),r;try{r=JSON.parse(Buffer.from(n).toString("utf8"))}catch{I("custody_record_invalid")}finally{n.fill(0)}(!ri(r)||r.v!==1||typeof r.seed!="string")&&I("custody_record_invalid"),r.reservation!==void 0&&I("custody_record_unbound");let i=bc(r.seed);(!i||i.length!==32||!we(r.runtimeId))&&I("custody_record_invalid");let o;try{o=by(r.binding)}catch{I("custody_record_invalid")}try{return new Pa(i,o,r.runtimeId)}finally{i.fill(0)}}describeKey(t,n){return{v:1,handle:t,runtimeId:n.runtimeId,binding:n.binding,publicJwk:n.publicJwk,jkt:n.jkt}}async create(t,n){let r=by(t);(n!==void 0&&!we(n)||r.profile==="identity-tap-v1"&&n!==void 0)&&I("identity_binding_invalid");let i=(0,Ke.randomBytes)(32),o=(0,Ke.randomBytes)(32).toString("hex"),a={v:1,seed:i.toString("base64url"),binding:r,runtimeId:n??(0,Ke.randomUUID)()},s=Buffer.from(JSON.stringify(a),"utf8");try{await this.#e.create(o,s);let c=await this.#e.read(o);try{Buffer.from(c).equals(s)||I("custody_readback_failed")}finally{c.fill(0)}let d=new Pa(i,r,a.runtimeId);return this.describeKey(o,d)}finally{i.fill(0),s.fill(0)}}async reserve(t){t!=="wallet:x402"&&t!=="card:vic"&&t!=="tap"&&I("identity_binding_invalid");let n=(0,Ke.randomBytes)(32),r=(0,Ke.randomBytes)(32).toString("hex"),i={v:1,seed:n.toString("base64url"),runtimeId:(0,Ke.randomUUID)(),reservation:t==="tap"?{profile:"identity-tap-v1",purpose:t}:{profile:"legacy-root-certified-v1",purpose:t}},o=Buffer.from(JSON.stringify(i),"utf8");try{await this.#e.create(r,o);let a=await this.#e.read(r);Buffer.from(a).equals(o)||I("custody_readback_failed");let s=new Pa(n,L4(t),i.runtimeId);return{handle:r,runtimeId:i.runtimeId,purpose:t,publicJwk:s.publicJwk,jkt:s.jkt}}finally{n.fill(0),o.fill(0)}}async adopt(t,n,r){/^[0-9a-f]{64}$/.test(t)||I("custody_handle_invalid");let i=by(n),o=(0,Ke.createHash)("sha256").update("visa-agent-key-adopt:v1\0").update(t).update("\0").update((0,tn.canonicalJson)(i)).digest("hex"),a=null;try{a=JSON.parse(Buffer.from(await this.#e.read(t)).toString("utf8"))}catch(l){if(l.message!=="custody_unavailable")throw l;let u=await this.describe(o);return r!==void 0&&u.runtimeId!==r&&I("identity_binding_invalid"),u}(!ri(a)||a.v!==1||!ri(a.reservation)||a.reservation.profile!==i.profile||a.reservation.purpose!==i.purpose||!we(a.runtimeId)||r!==void 0&&r!==a.runtimeId)&&I("identity_binding_invalid");let s=bc(a.seed);(!s||s.length!==32)&&I("custody_record_invalid");let c={v:1,seed:a.seed,binding:i,runtimeId:a.runtimeId},d=Buffer.from(JSON.stringify(c),"utf8");try{try{await this.#e.create(o,d)}catch(f){if(f.message!=="custody_handle_exists")throw f}let l=await this.#e.read(o);Buffer.from(l).equals(d)||I("custody_readback_failed");let u=new Pa(s,i,c.runtimeId);return await this.#e.delete(t),this.describeKey(o,u)}finally{s.fill(0),d.fill(0)}}async describe(t){return this.describeKey(t,await this.load(t))}async delete(t){/^[0-9a-f]{64}$/.test(t)||I("custody_handle_invalid"),await this.#e.delete(t)}pop(t,n,r,i,o,a){(!(we(n)||ni(n))||!ni(i))&&I("request_invalid");let s={nonce:n,audience:r,nowSec:o,intentHash:i,...a===void 0?{}:{runtimeCertificate:a}};return(0,tT.createPopProofWithSigner)(t.signer(),s)}async enrollmentProof(t,n){let r=await this.load(t);vc(r)||I("protected_association_required");let i=Re(n,["v","profile","associationId","associationVersion","agentId","runtimeId","generation","requestId","runtimePublicJwk","runtimeJkt","rootJkt","certificateSha256","delegationSha256","gateAuthorizationSha256","iat","exp"]);QI(r,i),(te(i,"v")!==1||S(i,"profile")!=="identity-tap-v1"||!we(S(i,"requestId"))||!Pn(i.runtimePublicJwk,r.publicJwk)||S(i,"runtimeJkt")!==r.jkt||S(i,"rootJkt")!==r.binding.rootJkt||!ni(S(i,"certificateSha256"))||!ni(S(i,"delegationSha256"))||!ni(S(i,"gateAuthorizationSha256")))&&I("identity_binding_mismatch");let o=te(i,"iat"),a=te(i,"exp"),s=this.#t();return(o>s+5||a<=s||a<=o||a-o>600)&&I("challenge_expired"),r.signature((0,nT.identityDeviceEnrollmentPreimage)(n)).toString("base64url")}async handoffProof(t,n){let r=await this.load(t);vc(r)||I("protected_association_required");let i=Re(n,["v","operation","requestId","handoffId","proposal","body"]),o=Re(i.proposal,["associationId","associationVersion","agentId","rootJkt","runtimeId","runtimePublicJwk","runtimeJkt"]),a=r.binding.profile==="identity-tap-v1"?r.binding.associationId:void 0;(te(i,"v")!==1||!we(S(i,"requestId"))||!we(S(i,"handoffId"))||(a!==void 0?S(o,"associationId")!==a:!we(S(o,"associationId")))||S(o,"agentId")!==r.binding.agentId||S(o,"rootJkt")!==r.binding.rootJkt||S(o,"runtimeId")!==r.runtimeId||te(o,"associationVersion")===0||!Pn(o.runtimePublicJwk,r.publicJwk)||S(o,"runtimeJkt")!==r.jkt)&&I("identity_binding_mismatch");let s=i.body,c=S(i,"operation");if(c==="create")Re(s,[]),S(i,"requestId")!==S(i,"handoffId")&&I("request_invalid");else if(c==="read")Re(s,[]);else if(c==="cancel"){let u=Re(s,["enrollmentRequestId","generation"]);!(u.enrollmentRequestId===null&&u.generation===null)&&(!we(S(u,"enrollmentRequestId"))||te(u,"generation")===0||te(u,"generation")>rT)&&I("request_invalid")}else if(c==="proof"){let u=Re(s,["enrollmentRequestId","runtimeProof"]),f=S(u,"runtimeProof");(!we(S(u,"enrollmentRequestId"))||f.length!==86||bc(f)?.length!==64)&&I("request_invalid")}else I("request_invalid");let d=lr((0,tn.canonicalJson)({v:1,operation:c,handoffId:S(i,"handoffId"),proposalSha256:lr((0,tn.canonicalJson)(o)),bodySha256:lr((0,tn.canonicalJson)(s))})),l=S(i,"requestId");return we(l)||I("request_invalid"),this.pop(r,l,"visa-device-handoff:v1",d,this.#t())}async leaseProof(t,n){let r=await this.load(t);vc(r)||I("protected_association_required");let i=Re(n,["v","profile","associationId","associationVersion","agentId","runtimeId","generation","authorizationId","authorizationVersion","requestId","signingMode"]);QI(r,i),(te(i,"v")!==1||S(i,"profile")!=="identity-tap-v1"||S(i,"signingMode")!=="tap"||!we(S(i,"authorizationId"))||te(i,"authorizationVersion")===0)&&I("request_invalid");let o=S(i,"requestId");return we(o)||I("request_invalid"),this.pop(r,o,"visa-identity-lease-requests:v1",lr((0,tn.canonicalJson)(i)),this.#t())}async tapProof(t,n,r){let i=await this.load(t);vc(i)||I("protected_association_required"),ri(r)||I("request_invalid");let o=["kind","method","authority","path","coveredComponents","paymentHeaderName","paymentHeaderValue","created","expires","keyId","nonce","tag","signatureBase"];r.contentDigest!==void 0&&o.push("contentDigest");let a=Re(r,o);(S(a,"kind")!=="tap_signature_base"||S(a,"tag")!=="agent-payer-auth"||!ni(S(a,"keyId")))&&I("request_invalid");let s=te(a,"created"),c=te(a,"expires"),d=this.#t();(s>d+30||c<=d||c<=s||c-s>480)&&I("tap_expired");let l=S(a,"method"),u=S(a,"authority"),f=S(a,"path"),h=S(a,"paymentHeaderName"),p=S(a,"paymentHeaderValue"),m=V=>V.length>0&&Buffer.byteLength(V)<=8192&&!/[\0\r\n]/.test(V);(l.length===0||l.length>16||!/^[A-Z]+$/.test(l)||!m(u)||!m(f)||!f.startsWith("/")||!m(p)||!["payment-signature","x-payment","authorization"].includes(h)||h==="authorization"&&!/^payment \S/i.test(p))&&I("tap_payload_invalid");let w=S(a,"nonce"),v=/^[A-Za-z0-9+/]*={0,2}$/.test(w)?Buffer.from(w,"base64"):null;(!v||v.length!==32||v.toString("base64")!==w)&&I("tap_payload_invalid");let _=a.coveredComponents;(!Array.isArray(_)||_.length<4||_.length>5)&&I("tap_payload_invalid");let A=new Set,j=[],Q=[];for(let V of _){(typeof V!="string"||A.has(V))&&I("tap_payload_invalid"),A.add(V);let Ee;if(V==="@method")Ee=l;else if(V==="@authority")Ee=u;else if(V==="@path")Ee=f;else if(V==="content-digest"){let Ge=S(a,"contentDigest");(!m(Ge)||!Ge.startsWith("sha-256=:"))&&I("tap_payload_invalid"),Ee=Ge}else V===h?Ee=p:I("tap_payload_invalid");Q.push(`"${V}"`),j.push(`"${V}": ${Ee}`)}(!["@method","@authority","@path",h].every(V=>A.has(V))||A.has("content-digest")!==(a.contentDigest!==void 0))&&I("tap_payload_invalid");let X=`(${Q.join(" ")});created=${s};expires=${c};keyid="${S(a,"keyId")}";alg="Ed25519";nonce="${w}";tag="agent-payer-auth"`;j.push(`"@signature-params": ${X}`);let H=S(a,"signatureBase");return j.join(`
|
|
30
|
+
`)!==H&&I("tap_payload_invalid"),we(n)||I("request_invalid"),this.pop(i,n,"urn:visa:tvc:identity-gate",lr(H),d)}async financialEnrollmentProof(t,n){let r=await this.load(t);Ec(r),cu(r,"wallet:x402");let i=Re(n,["v","purpose","requestId","associationId","associationVersion","runtimeId","runtimeGeneration","childJkt","preparedCertificate","preparedDelegation","expiresAt"]);(te(i,"v")!==1||S(i,"purpose")!=="financial.runtime.device.enroll"||!we(S(i,"requestId"))||!we(S(i,"associationId"))||te(i,"associationVersion")===0||te(i,"runtimeGeneration")===0)&&I("request_invalid"),(S(i,"runtimeId")!==r.runtimeId||S(i,"childJkt")!==r.jkt||r.binding.rootJkt===r.jkt)&&I("identity_binding_mismatch");let o=Ay(i.preparedCertificate,"visa-agent-runtime-cert+jwt"),a=Ay(i.preparedDelegation,"visa-agent-runtime-delegation+jwt");Re(o.claims,eT);let s=Re(o.claims.cnf,["jwk","jkt"]),c="custody"in a.claims||"rails"in a.claims;Re(a.claims,c?J4:iT);let d=c?2:1;(te(a.claims,"v")!==d||c&&(S(a.claims,"custody")!=="device"||!(Pn(a.claims.rails,["tempo","x402"])||Pn(a.claims.rails,["x402"]))))&&I("identity_binding_mismatch");let l=S(a.claims,"leaseIssuerJkt");(o.kid!==a.kid||!Pn(s.jwk,r.publicJwk)||S(s,"jkt")!==r.jkt||!Pn(o.claims.purposes,["wallet:x402"])||S(a.claims,"runtimeJkt")!==r.jkt||S(a.claims,"purpose")!=="wallet:x402"||S(a.claims,"network")!=="eip155:8453"||!Pn(a.claims.signingModes,["eip3009:exact"])||te(a.claims,"maxLeaseTtlSeconds")!==300||!ni(l)||l===r.jkt||l===r.binding.rootJkt)&&I("identity_binding_mismatch");let u=this.#t(),f=te(o.claims,"iat"),h=te(i,"expiresAt");(h!==f+300||h<=u||h>u+330)&&I("challenge_expired");for(let[p,m,w]of[[o.claims,86400,1],[a.claims,366*86400,d]]){(te(p,"v")!==w||S(p,"iss")!==r.binding.rootJkt||S(p,"sub")!==r.binding.agentId||S(p,"runtimeId")!==r.runtimeId||!we(S(p,"jti")))&&I("identity_binding_mismatch");let v=te(p,"exp");(te(p,"iat")!==f||te(p,"nbf")!==f||v<h||v<=f||v-f>m)&&I("challenge_expired")}return this.pop(r,S(i,"requestId"),"visa:financial:device-enrollment:v1",lr((0,tn.canonicalJson)(i)),u)}async cardEnrollmentProof(t,n){let r=await this.load(t);Ec(r),cu(r,"card:vic");let i=Re(n,["v","audience","requestId","associationId","associationVersion","instrumentId","runtimeId","generation","childJkt","preparedCertificate","expiresAt"]);(te(i,"v")!==1||S(i,"audience")!=="visa:financial:card-actor-enrollment:v1"||!we(S(i,"requestId"))||!we(S(i,"associationId"))||!we(S(i,"instrumentId"))||te(i,"associationVersion")===0||te(i,"generation")===0)&&I("request_invalid");let o=Ay(i.preparedCertificate,"visa-agent-runtime-cert+jwt");Re(o.claims,eT);let a=Re(o.claims.cnf,["jwk","jkt"]);(S(i,"runtimeId")!==r.runtimeId||S(i,"childJkt")!==r.jkt||r.binding.rootJkt===r.jkt||te(o.claims,"v")!==1||S(o.claims,"iss")!==r.binding.rootJkt||S(o.claims,"sub")!==r.binding.agentId||S(o.claims,"runtimeId")!==r.runtimeId||!we(S(o.claims,"jti"))||!Pn(a.jwk,r.publicJwk)||S(a,"jkt")!==r.jkt||!Pn(o.claims.purposes,["card:vic"]))&&I("identity_binding_mismatch");let s=this.#t(),c=te(o.claims,"iat"),d=te(i,"expiresAt"),l=te(o.claims,"exp");return(d!==c+300||d<=s||d>s+330||te(o.claims,"nbf")!==c||l<d||l<=c||l-c>366*86400)&&I("challenge_expired"),this.pop(r,S(i,"requestId"),S(i,"audience"),lr((0,tn.canonicalJson)(i)),s)}async legacyProof(t,n){let r=await this.load(t);Ec(r);let i=["nonce","audience","nowSec","intentHash"];ri(n)&&n.runtimeCertificate!==void 0&&i.push("runtimeCertificate");let o=Re(n,i),a=S(o,"audience");(N4[r.binding.purpose]??[]).includes(a)||I("key_purpose_mismatch");let s=o.runtimeCertificate===void 0?void 0:S(o,"runtimeCertificate");return s!==void 0&&(s.length>16384||s.split(".").length!==3)&&I("runtime_certificate_invalid"),this.pop(r,S(o,"nonce"),a,S(o,"intentHash"),this.proofTime(o),s)}async legacyLeaseProof(t,n){let r=await this.load(t);Ec(r),cu(r,"wallet:x402");let i=Re(n,["agentId","runtimeId","requestId","signingMode","nowSec"]);(S(i,"agentId")!==r.binding.agentId||S(i,"runtimeId")!==r.runtimeId)&&I("identity_binding_mismatch");let o=S(i,"signingMode");o!=="eip3009:exact"&&o!=="permit2:upto"&&I("key_purpose_mismatch");let a=S(i,"requestId"),s=lr(JSON.stringify({v:1,agentId:r.binding.agentId,runtimeId:r.runtimeId,requestId:a,signingMode:o}));return this.pop(r,a,"visa-runtime-lease-requests:v1",s,this.proofTime(i))}proofTime(t){let n=te(t,"nowSec"),r=this.#t();return(n>r+30||n+60<r)&&I("proof_time_invalid"),n}async proofKey(t){let n=await this.describe(t);return(n.binding.profile!=="legacy-root-certified-v1"||!["wallet:x402","card:vic"].includes(n.binding.purpose))&&I("key_purpose_mismatch"),{jkt:n.jkt,publicJwk:n.publicJwk,createProof:r=>this.legacyProof(t,r)}}async tempoApprovalStamp(t,n){let r=await this.load(t);Ec(r),cu(r,"wallet:x402"),(!/^[A-Za-z0-9_-]{1,128}$/.test(n.organizationId)||!/^[A-Za-z0-9_-]{1,256}$/.test(n.value))&&I("request_invalid");let i;n.action==="get_activity"?i={organizationId:n.organizationId,activityId:n.value}:n.action==="approve_activity"?i={type:"ACTIVITY_TYPE_APPROVE_ACTIVITY",timestampMs:String(this.#t()*1e3),organizationId:n.organizationId,parameters:{fingerprint:n.value}}:I("request_invalid");let o=JSON.stringify(i),a=Buffer.from(JSON.stringify({publicKey:Buffer.from(r.publicJwk.x,"base64url").toString("hex"),signature:r.signature(Buffer.from(o)).toString("hex"),scheme:"SIGNATURE_SCHEME_TK_API_ED25519"})).toString("base64url");return{body:o,stamp:a}}close(){}};var cT=require("node:child_process"),ce=require("node:fs"),pu=require("node:path");var uu="com.visacli.agent-key.v2",ka=16384,U4=/^[0-9a-f]{64}$/;function ur(e){if(!U4.test(e))throw new Error("custody_handle_invalid")}function hu(e){if(e.length===0||e.length>ka)throw new Error("custody_record_too_large")}var oT=null;var Cy=(e,t,n,r)=>oT!==null?Promise.reject(new Error(oT)):j4(e,t,n,r),j4=(e,t,n,r)=>new Promise(i=>{let o="",a="",s=!1,c=(0,cT.spawn)(e,[...t],{stdio:["pipe","pipe","pipe"],windowsHide:!0}),d=u=>{s||(s=!0,clearTimeout(l),i(u))},l=setTimeout(()=>{c.kill(),d({status:null,stdout:o,stderr:a,error:"timeout"})},r);l.unref(),c.stdout.setEncoding("utf8").on("data",u=>{o+=u}),c.stderr.setEncoding("utf8").on("data",u=>{a+=u}),c.on("error",u=>d({status:null,stdout:o,stderr:a,error:u.code==="ENOENT"?"missing":"failed"})),c.on("close",u=>d({status:u,stdout:o,stderr:a})),c.stdin.on("error",()=>{}),c.stdin.end(n)}),lu="/usr/bin/security",aT=44,q4=45,Iy=class{#e;#t;#n=!1;constructor(t={}){if(t.keychain!==void 0&&/["\n\r]/.test(t.keychain))throw new Error("custody_directory_invalid");this.#e=t.keychain,this.#t=t.run??Cy}target(){return this.#e===void 0?[]:[this.#e]}refused(){return new Error("keychain_locked_or_unavailable")}async requireKeychain(){if(this.#n)return;let t=this.#e;if(t===void 0){let n=await this.#t(lu,["default-keychain","-d","user"],"",5e3);if(t=n.stdout.trim().replace(/^"(.*)"$/,"$1"),n.status!==0||n.error||!t)throw new Error("keychain_not_found")}if(!(0,ce.existsSync)(t))throw new Error("keychain_not_found");this.#n=!0}async create(t,n){ur(t),hu(n),await this.requireKeychain();let r=this.#e===void 0?"":` "${this.#e}"`,i=Buffer.from(n).toString("base64"),o=await this.#t(lu,["-i"],`add-generic-password -s ${uu} -a ${t} -l visa-cli-agent-key -w ${i}${r}
|
|
31
|
+
`,1e4);if(!(o.status===0&&!o.error))throw o.status===q4?new Error("custody_handle_exists"):this.refused()}async read(t){ur(t),await this.requireKeychain();let n=await this.#t(lu,["find-generic-password","-s",uu,"-a",t,"-w",...this.target()],"",1e4);if(n.status===aT)throw new Error("custody_unavailable");if(n.status!==0||n.error)throw this.refused();let r=n.stdout.trim(),i=/^[A-Za-z0-9+/]+={0,2}$/.test(r)?Buffer.from(r,"base64"):null;if(!i||i.toString("base64")!==r||i.length>ka)throw new Error("custody_record_invalid");return i}async delete(t){ur(t),await this.requireKeychain();let n=await this.#t(lu,["delete-generic-password","-s",uu,"-a",t,...this.target()],"",1e4);if(!(n.status===0||n.status===aT))throw this.refused()}},Sy="secret-tool",Ty=class{#e;constructor(t={}){this.#e=t.run??Cy}attributes(t){return["service",uu,"handle",t]}refused(t){return t.error==="missing"?new Error("secret_service_unavailable"):/d-?bus|DBUS_SESSION_BUS_ADDRESS|\$DISPLAY|Could not connect/i.test(t.stderr)?new Error("secret_service_unavailable"):t.error==="timeout"?new Error("secret_service_timeout"):new Error("secret_service_locked_or_unavailable")}async lookup(t){let n=await this.#e(Sy,["lookup",...this.attributes(t)],"",1e4);if(n.status===0&&!n.error)return n.stdout;if(n.status===1&&!n.error&&n.stderr.trim()==="")return null;throw this.refused(n)}async create(t,n){if(ur(t),hu(n),await this.lookup(t)!==null)throw new Error("custody_handle_exists");let r=await this.#e(Sy,["store","--label=Visa CLI agent key",...this.attributes(t)],Buffer.from(n).toString("base64"),1e4);if(r.status!==0||r.error)throw this.refused(r)}async read(t){ur(t);let n=await this.lookup(t);if(n===null)throw new Error("custody_unavailable");let r=n.trim(),i=/^[A-Za-z0-9+/]+={0,2}$/.test(r)?Buffer.from(r,"base64"):null;if(!i||i.toString("base64")!==r||i.length>ka)throw new Error("custody_record_invalid");return i}async delete(t){ur(t);let n=await this.#e(Sy,["clear",...this.attributes(t)],"",1e4);if(!(n.status===1&&!n.error&&n.stderr.trim()==="")&&(n.status!==0||n.error))throw this.refused(n)}};function dT(e){if(!(0,ce.existsSync)(e)){(0,ce.mkdirSync)(e,{recursive:!0,mode:448}),process.platform!=="win32"&&(0,ce.chmodSync)(e,448);return}let t=(0,ce.lstatSync)(e);if(!t.isDirectory())throw new Error("custody_directory_invalid");if(process.platform!=="win32"&&(t.mode&63)!==0)throw new Error("custody_directory_not_private")}function lT(e,t){let n;try{n=(0,ce.openSync)(e,"wx",384)}catch(i){throw i.code==="EEXIST"?new Error("custody_handle_exists"):new Error("custody_create_failed")}let r=0;try{for(;r<t.length;)r+=(0,ce.writeSync)(n,t,r)}catch{throw(0,ce.closeSync)(n),(0,ce.rmSync)(e,{force:!0}),new Error("custody_create_failed")}(0,ce.closeSync)(n)}function sT(e){return new Error(e?.code==="ENOENT"?"custody_unavailable":"custody_store_unreadable")}function uT(e){let t;try{t=(0,ce.lstatSync)(e)}catch(n){throw sT(n)}if(!t.isFile()||t.size>ka*2)throw new Error("custody_file_invalid");try{return(0,ce.readFileSync)(e)}catch(n){throw sT(n)}}var Py=class{constructor(t){this.directory=t}directory;path(t){return ur(t),(0,pu.join)(this.directory,`${t}.key`)}async create(t,n){let r=this.path(t);hu(n),dT(this.directory),lT(r,n)}async read(t){let n=this.path(t);if(process.platform!=="win32"&&(0,ce.existsSync)(this.directory)){let i=(0,ce.lstatSync)(this.directory);if(!i.isDirectory()||(i.mode&63)!==0)throw new Error("custody_directory_not_private")}let r=uT(n);if(process.platform!=="win32"&&((0,ce.lstatSync)(n).mode&63)!==0)throw new Error("custody_file_invalid");if(r.length===0||r.length>ka)throw new Error("custody_file_invalid");return r}async delete(t){(0,ce.rmSync)(this.path(t),{force:!0})}},K4="powershell.exe";function H4(e,t){return ur(t),["$ErrorActionPreference = 'Stop'","Add-Type -AssemblyName System.Security","$payload = [Convert]::FromBase64String([Console]::In.ReadToEnd().Trim())",`$entropy = [Text.Encoding]::UTF8.GetBytes('visa-agent-key:${t}')`,`$result = [System.Security.Cryptography.ProtectedData]::${e}($payload, $entropy, [System.Security.Cryptography.DataProtectionScope]::CurrentUser)`,"[Console]::Out.Write([Convert]::ToBase64String($result))"].join("; ")}var ky=class{constructor(t,n={}){this.directory=t;this.#e=n.run??Cy}directory;#e;path(t){return ur(t),(0,pu.join)(this.directory,`${t}.dpapi`)}async call(t,n,r){let i=await this.#e(K4,["-NoProfile","-NonInteractive","-Command",H4(t,n)],Buffer.from(r).toString("base64"),3e4),o=i.stdout.trim();if(i.status!==0||i.error||!/^[A-Za-z0-9+/]+={0,2}$/.test(o))throw new Error("dpapi_locked_or_unavailable");return Buffer.from(o,"base64")}async create(t,n){let r=this.path(t);if(hu(n),dT(this.directory),(0,ce.existsSync)(r))throw new Error("custody_handle_exists");lT(r,await this.call("Protect",t,n))}async read(t){let n=uT(this.path(t)),r=await this.call("Unprotect",t,n);if(r.length===0||r.length>ka)throw new Error("custody_record_invalid");return r}async delete(t){(0,ce.rmSync)(this.path(t),{force:!0})}};function fu(e=process.env){return(0,pu.join)(de(e),"agent-keys")}function fT(e=process.env,t=process.platform){let n=e.VISA_RUNTIME_CUSTODY_PROFILE??"os";if(n==="headless")return new Py(fu(e));if(n!=="os")throw new Error("native_runtime_custody_profile_invalid");if(t==="darwin")return new Iy;if(t==="win32")return new ky(fu(e));if(t==="linux")return new Ty;throw new Error("custody_platform_unsupported")}var mu=new Map;function ao(e=process.env){let t=`${e.VISA_RUNTIME_CUSTODY_PROFILE??"os"}\0${fu(e)}`,n=mu.get(t);return n||(n=new du(fT(e)),mu.set(t,n)),n}function V4(){for(let e of mu.values())e.close();mu.clear()}process.once("exit",V4);var Cc=require("node:crypto");var W={};EP(W,{BRAND:()=>m5,DIRTY:()=>so,EMPTY_PATH:()=>B4,INVALID:()=>K,NEVER:()=>Q5,OK:()=>Be,ParseStatus:()=>He,Schema:()=>Y,ZodAny:()=>ai,ZodArray:()=>mr,ZodBigInt:()=>lo,ZodBoolean:()=>uo,ZodBranded:()=>Sc,ZodCatch:()=>bo,ZodDate:()=>fo,ZodDefault:()=>vo,ZodDiscriminatedUnion:()=>_u,ZodEffects:()=>Ut,ZodEnum:()=>wo,ZodError:()=>mt,ZodFirstPartyTypeKind:()=>$,ZodFunction:()=>Eu,ZodIntersection:()=>go,ZodIssueCode:()=>b,ZodLazy:()=>yo,ZodLiteral:()=>_o,ZodMap:()=>Da,ZodNaN:()=>La,ZodNativeEnum:()=>Eo,ZodNever:()=>nn,ZodNull:()=>ho,ZodNullable:()=>Rn,ZodNumber:()=>co,ZodObject:()=>gt,ZodOptional:()=>Lt,ZodParsedType:()=>C,ZodPipeline:()=>Ic,ZodPromise:()=>si,ZodReadonly:()=>Ao,ZodRecord:()=>wu,ZodSchema:()=>Y,ZodSet:()=>Ma,ZodString:()=>oi,ZodSymbol:()=>Oa,ZodTransformer:()=>Ut,ZodTuple:()=>Cn,ZodType:()=>Y,ZodUndefined:()=>po,ZodUnion:()=>mo,ZodUnknown:()=>hr,ZodVoid:()=>Na,addIssueToContext:()=>P,any:()=>S5,array:()=>k5,bigint:()=>w5,boolean:()=>AT,coerce:()=>Z5,custom:()=>ET,date:()=>E5,datetimeRegex:()=>_T,defaultErrorMap:()=>fr,discriminatedUnion:()=>O5,effect:()=>$5,enum:()=>K5,function:()=>U5,getErrorMap:()=>Ca,getParsedType:()=>kn,instanceof:()=>y5,intersection:()=>N5,isAborted:()=>gu,isAsync:()=>Ra,isDirty:()=>yu,isValid:()=>ii,late:()=>g5,lazy:()=>j5,literal:()=>q5,makeIssue:()=>Ac,map:()=>L5,nan:()=>_5,nativeEnum:()=>H5,never:()=>T5,null:()=>A5,nullable:()=>F5,number:()=>bT,object:()=>C5,objectUtil:()=>Ry,oboolean:()=>X5,onumber:()=>z5,optional:()=>W5,ostring:()=>Y5,pipeline:()=>G5,preprocess:()=>B5,promise:()=>V5,quotelessJson:()=>$4,record:()=>M5,set:()=>J5,setErrorMap:()=>F4,strictObject:()=>R5,string:()=>vT,symbol:()=>v5,transformer:()=>$5,tuple:()=>D5,undefined:()=>b5,union:()=>x5,unknown:()=>I5,util:()=>Z,void:()=>P5});var Z;(function(e){e.assertEqual=i=>{};function t(i){}e.assertIs=t;function n(i){throw new Error}e.assertNever=n,e.arrayToEnum=i=>{let o={};for(let a of i)o[a]=a;return o},e.getValidEnumValues=i=>{let o=e.objectKeys(i).filter(s=>typeof i[i[s]]!="number"),a={};for(let s of o)a[s]=i[s];return e.objectValues(a)},e.objectValues=i=>e.objectKeys(i).map(function(o){return i[o]}),e.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let a in i)Object.prototype.hasOwnProperty.call(i,a)&&o.push(a);return o},e.find=(i,o)=>{for(let a of i)if(o(a))return a},e.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function r(i,o=" | "){return i.map(a=>typeof a=="string"?`'${a}'`:a).join(o)}e.joinValues=r,e.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(Z||(Z={}));var Ry;(function(e){e.mergeShapes=(t,n)=>({...t,...n})})(Ry||(Ry={}));var C=Z.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),kn=e=>{switch(typeof e){case"undefined":return C.undefined;case"string":return C.string;case"number":return Number.isNaN(e)?C.nan:C.number;case"boolean":return C.boolean;case"function":return C.function;case"bigint":return C.bigint;case"symbol":return C.symbol;case"object":return Array.isArray(e)?C.array:e===null?C.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?C.promise:typeof Map<"u"&&e instanceof Map?C.map:typeof Set<"u"&&e instanceof Set?C.set:typeof Date<"u"&&e instanceof Date?C.date:C.object;default:return C.unknown}};var b=Z.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),$4=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),mt=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=r=>{this.issues=[...this.issues,r]},this.addIssues=(r=[])=>{this.issues=[...this.issues,...r]};let n=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,n):this.__proto__=n,this.name="ZodError",this.issues=t}format(t){let n=t||function(o){return o.message},r={_errors:[]},i=o=>{for(let a of o.issues)if(a.code==="invalid_union")a.unionErrors.map(i);else if(a.code==="invalid_return_type")i(a.returnTypeError);else if(a.code==="invalid_arguments")i(a.argumentsError);else if(a.path.length===0)r._errors.push(n(a));else{let s=r,c=0;for(;c<a.path.length;){let d=a.path[c];c===a.path.length-1?(s[d]=s[d]||{_errors:[]},s[d]._errors.push(n(a))):s[d]=s[d]||{_errors:[]},s=s[d],c++}}};return i(this),r}static assert(t){if(!(t instanceof e))throw new Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,Z.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=n=>n.message){let n={},r=[];for(let i of this.issues)if(i.path.length>0){let o=i.path[0];n[o]=n[o]||[],n[o].push(t(i))}else r.push(t(i));return{formErrors:r,fieldErrors:n}}get formErrors(){return this.flatten()}};mt.create=e=>new mt(e);var W4=(e,t)=>{let n;switch(e.code){case b.invalid_type:e.received===C.undefined?n="Required":n=`Expected ${e.expected}, received ${e.received}`;break;case b.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,Z.jsonStringifyReplacer)}`;break;case b.unrecognized_keys:n=`Unrecognized key(s) in object: ${Z.joinValues(e.keys,", ")}`;break;case b.invalid_union:n="Invalid input";break;case b.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${Z.joinValues(e.options)}`;break;case b.invalid_enum_value:n=`Invalid enum value. Expected ${Z.joinValues(e.options)}, received '${e.received}'`;break;case b.invalid_arguments:n="Invalid function arguments";break;case b.invalid_return_type:n="Invalid function return type";break;case b.invalid_date:n="Invalid date";break;case b.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:Z.assertNever(e.validation):e.validation!=="regex"?n=`Invalid ${e.validation}`:n="Invalid";break;case b.too_small:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?n=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:n="Invalid input";break;case b.too_big:e.type==="array"?n=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?n=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?n=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?n=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?n=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:n="Invalid input";break;case b.custom:n="Invalid input";break;case b.invalid_intersection_types:n="Intersection results could not be merged";break;case b.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case b.not_finite:n="Number must be finite";break;default:n=t.defaultError,Z.assertNever(e)}return{message:n}},fr=W4;var pT=fr;function F4(e){pT=e}function Ca(){return pT}var Ac=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,o=[...n,...i.path||[]],a={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let s="",c=r.filter(d=>!!d).slice().reverse();for(let d of c)s=d(a,{data:t,defaultError:s}).message;return{...i,path:o,message:s}},B4=[];function P(e,t){let n=Ca(),r=Ac({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===fr?void 0:fr].filter(i=>!!i)});e.common.issues.push(r)}var He=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,n){let r=[];for(let i of n){if(i.status==="aborted")return K;i.status==="dirty"&&t.dirty(),r.push(i.value)}return{status:t.value,value:r}}static async mergeObjectAsync(t,n){let r=[];for(let i of n){let o=await i.key,a=await i.value;r.push({key:o,value:a})}return e.mergeObjectSync(t,r)}static mergeObjectSync(t,n){let r={};for(let i of n){let{key:o,value:a}=i;if(o.status==="aborted"||a.status==="aborted")return K;o.status==="dirty"&&t.dirty(),a.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof a.value<"u"||i.alwaysSet)&&(r[o.value]=a.value)}return{status:t.value,value:r}}},K=Object.freeze({status:"aborted"}),so=e=>({status:"dirty",value:e}),Be=e=>({status:"valid",value:e}),gu=e=>e.status==="aborted",yu=e=>e.status==="dirty",ii=e=>e.status==="valid",Ra=e=>typeof Promise<"u"&&e instanceof Promise;var L;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(L||(L={}));var Jt=class{constructor(t,n,r,i){this._cachedPath=[],this.parent=t,this.data=n,this._path=r,this._key=i}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},hT=(e,t)=>{if(ii(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let n=new mt(e.common.issues);return this._error=n,this._error}}};function G(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(a,s)=>{let{message:c}=e;return a.code==="invalid_enum_value"?{message:c??s.defaultError}:typeof s.data>"u"?{message:c??r??s.defaultError}:a.code!=="invalid_type"?{message:s.defaultError}:{message:c??n??s.defaultError}},description:i}}var Y=class{get description(){return this._def.description}_getType(t){return kn(t.data)}_getOrReturnCtx(t,n){return n||{common:t.parent.common,data:t.data,parsedType:kn(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new He,ctx:{common:t.parent.common,data:t.data,parsedType:kn(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let n=this._parse(t);if(Ra(n))throw new Error("Synchronous parse encountered promise.");return n}_parseAsync(t){let n=this._parse(t);return Promise.resolve(n)}parse(t,n){let r=this.safeParse(t,n);if(r.success)return r.data;throw r.error}safeParse(t,n){let r={common:{issues:[],async:n?.async??!1,contextualErrorMap:n?.errorMap},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:kn(t)},i=this._parseSync({data:t,path:r.path,parent:r});return hT(r,i)}"~validate"(t){let n={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:kn(t)};if(!this["~standard"].async)try{let r=this._parseSync({data:t,path:[],parent:n});return ii(r)?{value:r.value}:{issues:n.common.issues}}catch(r){r?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),n.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:n}).then(r=>ii(r)?{value:r.value}:{issues:n.common.issues})}async parseAsync(t,n){let r=await this.safeParseAsync(t,n);if(r.success)return r.data;throw r.error}async safeParseAsync(t,n){let r={common:{issues:[],contextualErrorMap:n?.errorMap,async:!0},path:n?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:kn(t)},i=this._parse({data:t,path:r.path,parent:r}),o=await(Ra(i)?i:Promise.resolve(i));return hT(r,o)}refine(t,n){let r=i=>typeof n=="string"||typeof n>"u"?{message:n}:typeof n=="function"?n(i):n;return this._refinement((i,o)=>{let a=t(i),s=()=>o.addIssue({code:b.custom,...r(i)});return typeof Promise<"u"&&a instanceof Promise?a.then(c=>c?!0:(s(),!1)):a?!0:(s(),!1)})}refinement(t,n){return this._refinement((r,i)=>t(r)?!0:(i.addIssue(typeof n=="function"?n(r,i):n),!1))}_refinement(t){return new Ut({schema:this,typeName:$.ZodEffects,effect:{type:"refinement",refinement:t}})}superRefine(t){return this._refinement(t)}constructor(t){this.spa=this.safeParseAsync,this._def=t,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:n=>this["~validate"](n)}}optional(){return Lt.create(this,this._def)}nullable(){return Rn.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return mr.create(this)}promise(){return si.create(this,this._def)}or(t){return mo.create([this,t],this._def)}and(t){return go.create(this,t,this._def)}transform(t){return new Ut({...G(this._def),schema:this,typeName:$.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let n=typeof t=="function"?t:()=>t;return new vo({...G(this._def),innerType:this,defaultValue:n,typeName:$.ZodDefault})}brand(){return new Sc({typeName:$.ZodBranded,type:this,...G(this._def)})}catch(t){let n=typeof t=="function"?t:()=>t;return new bo({...G(this._def),innerType:this,catchValue:n,typeName:$.ZodCatch})}describe(t){let n=this.constructor;return new n({...this._def,description:t})}pipe(t){return Ic.create(this,t)}readonly(){return Ao.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},G4=/^c[^\s-]{8,}$/i,Y4=/^[0-9a-z]+$/,z4=/^[0-9A-HJKMNP-TV-Z]{26}$/i,X4=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,Z4=/^[a-z0-9_-]{21}$/i,Q4=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,e5=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,t5=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,n5="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",xy,r5=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,i5=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,o5=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,a5=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,s5=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,c5=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,gT="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",d5=new RegExp(`^${gT}$`);function yT(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let n=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function l5(e){return new RegExp(`^${yT(e)}$`)}function _T(e){let t=`${gT}T${yT(e)}`,n=[];return n.push(e.local?"Z?":"Z"),e.offset&&n.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${n.join("|")})`,new RegExp(`^${t}$`)}function u5(e,t){return!!((t==="v4"||!t)&&r5.test(e)||(t==="v6"||!t)&&o5.test(e))}function f5(e,t){if(!Q4.test(e))return!1;try{let[n]=e.split(".");if(!n)return!1;let r=n.replace(/-/g,"+").replace(/_/g,"/").padEnd(n.length+(4-n.length%4)%4,"="),i=JSON.parse(atob(r));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||t&&i.alg!==t)}catch{return!1}}function p5(e,t){return!!((t==="v4"||!t)&&i5.test(e)||(t==="v6"||!t)&&a5.test(e))}var oi=class e extends Y{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==C.string){let o=this._getOrReturnCtx(t);return P(o,{code:b.invalid_type,expected:C.string,received:o.parsedType}),K}let r=new He,i;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(i=this._getOrReturnCtx(t,i),P(i,{code:b.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="max")t.data.length>o.value&&(i=this._getOrReturnCtx(t,i),P(i,{code:b.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),r.dirty());else if(o.kind==="length"){let a=t.data.length>o.value,s=t.data.length<o.value;(a||s)&&(i=this._getOrReturnCtx(t,i),a?P(i,{code:b.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):s&&P(i,{code:b.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),r.dirty())}else if(o.kind==="email")t5.test(t.data)||(i=this._getOrReturnCtx(t,i),P(i,{validation:"email",code:b.invalid_string,message:o.message}),r.dirty());else if(o.kind==="emoji")xy||(xy=new RegExp(n5,"u")),xy.test(t.data)||(i=this._getOrReturnCtx(t,i),P(i,{validation:"emoji",code:b.invalid_string,message:o.message}),r.dirty());else if(o.kind==="uuid")X4.test(t.data)||(i=this._getOrReturnCtx(t,i),P(i,{validation:"uuid",code:b.invalid_string,message:o.message}),r.dirty());else if(o.kind==="nanoid")Z4.test(t.data)||(i=this._getOrReturnCtx(t,i),P(i,{validation:"nanoid",code:b.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid")G4.test(t.data)||(i=this._getOrReturnCtx(t,i),P(i,{validation:"cuid",code:b.invalid_string,message:o.message}),r.dirty());else if(o.kind==="cuid2")Y4.test(t.data)||(i=this._getOrReturnCtx(t,i),P(i,{validation:"cuid2",code:b.invalid_string,message:o.message}),r.dirty());else if(o.kind==="ulid")z4.test(t.data)||(i=this._getOrReturnCtx(t,i),P(i,{validation:"ulid",code:b.invalid_string,message:o.message}),r.dirty());else if(o.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),P(i,{validation:"url",code:b.invalid_string,message:o.message}),r.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(t.data)||(i=this._getOrReturnCtx(t,i),P(i,{validation:"regex",code:b.invalid_string,message:o.message}),r.dirty())):o.kind==="trim"?t.data=t.data.trim():o.kind==="includes"?t.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(t,i),P(i,{code:b.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),r.dirty()):o.kind==="toLowerCase"?t.data=t.data.toLowerCase():o.kind==="toUpperCase"?t.data=t.data.toUpperCase():o.kind==="startsWith"?t.data.startsWith(o.value)||(i=this._getOrReturnCtx(t,i),P(i,{code:b.invalid_string,validation:{startsWith:o.value},message:o.message}),r.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(i=this._getOrReturnCtx(t,i),P(i,{code:b.invalid_string,validation:{endsWith:o.value},message:o.message}),r.dirty()):o.kind==="datetime"?_T(o).test(t.data)||(i=this._getOrReturnCtx(t,i),P(i,{code:b.invalid_string,validation:"datetime",message:o.message}),r.dirty()):o.kind==="date"?d5.test(t.data)||(i=this._getOrReturnCtx(t,i),P(i,{code:b.invalid_string,validation:"date",message:o.message}),r.dirty()):o.kind==="time"?l5(o).test(t.data)||(i=this._getOrReturnCtx(t,i),P(i,{code:b.invalid_string,validation:"time",message:o.message}),r.dirty()):o.kind==="duration"?e5.test(t.data)||(i=this._getOrReturnCtx(t,i),P(i,{validation:"duration",code:b.invalid_string,message:o.message}),r.dirty()):o.kind==="ip"?u5(t.data,o.version)||(i=this._getOrReturnCtx(t,i),P(i,{validation:"ip",code:b.invalid_string,message:o.message}),r.dirty()):o.kind==="jwt"?f5(t.data,o.alg)||(i=this._getOrReturnCtx(t,i),P(i,{validation:"jwt",code:b.invalid_string,message:o.message}),r.dirty()):o.kind==="cidr"?p5(t.data,o.version)||(i=this._getOrReturnCtx(t,i),P(i,{validation:"cidr",code:b.invalid_string,message:o.message}),r.dirty()):o.kind==="base64"?s5.test(t.data)||(i=this._getOrReturnCtx(t,i),P(i,{validation:"base64",code:b.invalid_string,message:o.message}),r.dirty()):o.kind==="base64url"?c5.test(t.data)||(i=this._getOrReturnCtx(t,i),P(i,{validation:"base64url",code:b.invalid_string,message:o.message}),r.dirty()):Z.assertNever(o);return{status:r.value,value:t.data}}_regex(t,n,r){return this.refinement(i=>t.test(i),{validation:n,code:b.invalid_string,...L.errToObj(r)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...L.errToObj(t)})}url(t){return this._addCheck({kind:"url",...L.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...L.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...L.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...L.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...L.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...L.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...L.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...L.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...L.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...L.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...L.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...L.errToObj(t)})}datetime(t){return typeof t=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:t}):this._addCheck({kind:"datetime",precision:typeof t?.precision>"u"?null:t?.precision,offset:t?.offset??!1,local:t?.local??!1,...L.errToObj(t?.message)})}date(t){return this._addCheck({kind:"date",message:t})}time(t){return typeof t=="string"?this._addCheck({kind:"time",precision:null,message:t}):this._addCheck({kind:"time",precision:typeof t?.precision>"u"?null:t?.precision,...L.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...L.errToObj(t)})}regex(t,n){return this._addCheck({kind:"regex",regex:t,...L.errToObj(n)})}includes(t,n){return this._addCheck({kind:"includes",value:t,position:n?.position,...L.errToObj(n?.message)})}startsWith(t,n){return this._addCheck({kind:"startsWith",value:t,...L.errToObj(n)})}endsWith(t,n){return this._addCheck({kind:"endsWith",value:t,...L.errToObj(n)})}min(t,n){return this._addCheck({kind:"min",value:t,...L.errToObj(n)})}max(t,n){return this._addCheck({kind:"max",value:t,...L.errToObj(n)})}length(t,n){return this._addCheck({kind:"length",value:t,...L.errToObj(n)})}nonempty(t){return this.min(1,L.errToObj(t))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(t=>t.kind==="datetime")}get isDate(){return!!this._def.checks.find(t=>t.kind==="date")}get isTime(){return!!this._def.checks.find(t=>t.kind==="time")}get isDuration(){return!!this._def.checks.find(t=>t.kind==="duration")}get isEmail(){return!!this._def.checks.find(t=>t.kind==="email")}get isURL(){return!!this._def.checks.find(t=>t.kind==="url")}get isEmoji(){return!!this._def.checks.find(t=>t.kind==="emoji")}get isUUID(){return!!this._def.checks.find(t=>t.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(t=>t.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(t=>t.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(t=>t.kind==="cuid2")}get isULID(){return!!this._def.checks.find(t=>t.kind==="ulid")}get isIP(){return!!this._def.checks.find(t=>t.kind==="ip")}get isCIDR(){return!!this._def.checks.find(t=>t.kind==="cidr")}get isBase64(){return!!this._def.checks.find(t=>t.kind==="base64")}get isBase64url(){return!!this._def.checks.find(t=>t.kind==="base64url")}get minLength(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxLength(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};oi.create=e=>new oi({checks:[],typeName:$.ZodString,coerce:e?.coerce??!1,...G(e)});function h5(e,t){let n=(e.toString().split(".")[1]||"").length,r=(t.toString().split(".")[1]||"").length,i=n>r?n:r,o=Number.parseInt(e.toFixed(i).replace(".","")),a=Number.parseInt(t.toFixed(i).replace(".",""));return o%a/10**i}var co=class e extends Y{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(t){if(this._def.coerce&&(t.data=Number(t.data)),this._getType(t)!==C.number){let o=this._getOrReturnCtx(t);return P(o,{code:b.invalid_type,expected:C.number,received:o.parsedType}),K}let r,i=new He;for(let o of this._def.checks)o.kind==="int"?Z.isInteger(t.data)||(r=this._getOrReturnCtx(t,r),P(r,{code:b.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(r=this._getOrReturnCtx(t,r),P(r,{code:b.too_small,minimum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),P(r,{code:b.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?h5(t.data,o.value)!==0&&(r=this._getOrReturnCtx(t,r),P(r,{code:b.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(r=this._getOrReturnCtx(t,r),P(r,{code:b.not_finite,message:o.message}),i.dirty()):Z.assertNever(o);return{status:i.value,value:t.data}}gte(t,n){return this.setLimit("min",t,!0,L.toString(n))}gt(t,n){return this.setLimit("min",t,!1,L.toString(n))}lte(t,n){return this.setLimit("max",t,!0,L.toString(n))}lt(t,n){return this.setLimit("max",t,!1,L.toString(n))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:L.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:L.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:L.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:L.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:L.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:L.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:L.toString(n)})}finite(t){return this._addCheck({kind:"finite",message:L.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:L.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:L.toString(t)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&Z.isInteger(t.value))}get isFinite(){let t=null,n=null;for(let r of this._def.checks){if(r.kind==="finite"||r.kind==="int"||r.kind==="multipleOf")return!0;r.kind==="min"?(n===null||r.value>n)&&(n=r.value):r.kind==="max"&&(t===null||r.value<t)&&(t=r.value)}return Number.isFinite(n)&&Number.isFinite(t)}};co.create=e=>new co({checks:[],typeName:$.ZodNumber,coerce:e?.coerce||!1,...G(e)});var lo=class e extends Y{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(t){if(this._def.coerce)try{t.data=BigInt(t.data)}catch{return this._getInvalidInput(t)}if(this._getType(t)!==C.bigint)return this._getInvalidInput(t);let r,i=new He;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(r=this._getOrReturnCtx(t,r),P(r,{code:b.too_small,type:"bigint",minimum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="max"?(o.inclusive?t.data>o.value:t.data>=o.value)&&(r=this._getOrReturnCtx(t,r),P(r,{code:b.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(r=this._getOrReturnCtx(t,r),P(r,{code:b.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):Z.assertNever(o);return{status:i.value,value:t.data}}_getInvalidInput(t){let n=this._getOrReturnCtx(t);return P(n,{code:b.invalid_type,expected:C.bigint,received:n.parsedType}),K}gte(t,n){return this.setLimit("min",t,!0,L.toString(n))}gt(t,n){return this.setLimit("min",t,!1,L.toString(n))}lte(t,n){return this.setLimit("max",t,!0,L.toString(n))}lt(t,n){return this.setLimit("max",t,!1,L.toString(n))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:L.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:L.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:L.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:L.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:L.toString(t)})}multipleOf(t,n){return this._addCheck({kind:"multipleOf",value:t,message:L.toString(n)})}get minValue(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t}get maxValue(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t}};lo.create=e=>new lo({checks:[],typeName:$.ZodBigInt,coerce:e?.coerce??!1,...G(e)});var uo=class extends Y{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==C.boolean){let r=this._getOrReturnCtx(t);return P(r,{code:b.invalid_type,expected:C.boolean,received:r.parsedType}),K}return Be(t.data)}};uo.create=e=>new uo({typeName:$.ZodBoolean,coerce:e?.coerce||!1,...G(e)});var fo=class e extends Y{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==C.date){let o=this._getOrReturnCtx(t);return P(o,{code:b.invalid_type,expected:C.date,received:o.parsedType}),K}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return P(o,{code:b.invalid_date}),K}let r=new He,i;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(i=this._getOrReturnCtx(t,i),P(i,{code:b.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),r.dirty()):o.kind==="max"?t.data.getTime()>o.value&&(i=this._getOrReturnCtx(t,i),P(i,{code:b.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),r.dirty()):Z.assertNever(o);return{status:r.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,n){return this._addCheck({kind:"min",value:t.getTime(),message:L.toString(n)})}max(t,n){return this._addCheck({kind:"max",value:t.getTime(),message:L.toString(n)})}get minDate(){let t=null;for(let n of this._def.checks)n.kind==="min"&&(t===null||n.value>t)&&(t=n.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let n of this._def.checks)n.kind==="max"&&(t===null||n.value<t)&&(t=n.value);return t!=null?new Date(t):null}};fo.create=e=>new fo({checks:[],coerce:e?.coerce||!1,typeName:$.ZodDate,...G(e)});var Oa=class extends Y{_parse(t){if(this._getType(t)!==C.symbol){let r=this._getOrReturnCtx(t);return P(r,{code:b.invalid_type,expected:C.symbol,received:r.parsedType}),K}return Be(t.data)}};Oa.create=e=>new Oa({typeName:$.ZodSymbol,...G(e)});var po=class extends Y{_parse(t){if(this._getType(t)!==C.undefined){let r=this._getOrReturnCtx(t);return P(r,{code:b.invalid_type,expected:C.undefined,received:r.parsedType}),K}return Be(t.data)}};po.create=e=>new po({typeName:$.ZodUndefined,...G(e)});var ho=class extends Y{_parse(t){if(this._getType(t)!==C.null){let r=this._getOrReturnCtx(t);return P(r,{code:b.invalid_type,expected:C.null,received:r.parsedType}),K}return Be(t.data)}};ho.create=e=>new ho({typeName:$.ZodNull,...G(e)});var ai=class extends Y{constructor(){super(...arguments),this._any=!0}_parse(t){return Be(t.data)}};ai.create=e=>new ai({typeName:$.ZodAny,...G(e)});var hr=class extends Y{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Be(t.data)}};hr.create=e=>new hr({typeName:$.ZodUnknown,...G(e)});var nn=class extends Y{_parse(t){let n=this._getOrReturnCtx(t);return P(n,{code:b.invalid_type,expected:C.never,received:n.parsedType}),K}};nn.create=e=>new nn({typeName:$.ZodNever,...G(e)});var Na=class extends Y{_parse(t){if(this._getType(t)!==C.undefined){let r=this._getOrReturnCtx(t);return P(r,{code:b.invalid_type,expected:C.void,received:r.parsedType}),K}return Be(t.data)}};Na.create=e=>new Na({typeName:$.ZodVoid,...G(e)});var mr=class e extends Y{_parse(t){let{ctx:n,status:r}=this._processInputParams(t),i=this._def;if(n.parsedType!==C.array)return P(n,{code:b.invalid_type,expected:C.array,received:n.parsedType}),K;if(i.exactLength!==null){let a=n.data.length>i.exactLength.value,s=n.data.length<i.exactLength.value;(a||s)&&(P(n,{code:a?b.too_big:b.too_small,minimum:s?i.exactLength.value:void 0,maximum:a?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),r.dirty())}if(i.minLength!==null&&n.data.length<i.minLength.value&&(P(n,{code:b.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),r.dirty()),i.maxLength!==null&&n.data.length>i.maxLength.value&&(P(n,{code:b.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),r.dirty()),n.common.async)return Promise.all([...n.data].map((a,s)=>i.type._parseAsync(new Jt(n,a,n.path,s)))).then(a=>He.mergeArray(r,a));let o=[...n.data].map((a,s)=>i.type._parseSync(new Jt(n,a,n.path,s)));return He.mergeArray(r,o)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:L.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:L.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:L.toString(n)}})}nonempty(t){return this.min(1,t)}};mr.create=(e,t)=>new mr({type:e,minLength:null,maxLength:null,exactLength:null,typeName:$.ZodArray,...G(t)});function xa(e){if(e instanceof gt){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=Lt.create(xa(r))}return new gt({...e._def,shape:()=>t})}else return e instanceof mr?new mr({...e._def,type:xa(e.element)}):e instanceof Lt?Lt.create(xa(e.unwrap())):e instanceof Rn?Rn.create(xa(e.unwrap())):e instanceof Cn?Cn.create(e.items.map(t=>xa(t))):e}var gt=class e extends Y{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let t=this._def.shape(),n=Z.objectKeys(t);return this._cached={shape:t,keys:n},this._cached}_parse(t){if(this._getType(t)!==C.object){let d=this._getOrReturnCtx(t);return P(d,{code:b.invalid_type,expected:C.object,received:d.parsedType}),K}let{status:r,ctx:i}=this._processInputParams(t),{shape:o,keys:a}=this._getCached(),s=[];if(!(this._def.catchall instanceof nn&&this._def.unknownKeys==="strip"))for(let d in i.data)a.includes(d)||s.push(d);let c=[];for(let d of a){let l=o[d],u=i.data[d];c.push({key:{status:"valid",value:d},value:l._parse(new Jt(i,u,i.path,d)),alwaysSet:d in i.data})}if(this._def.catchall instanceof nn){let d=this._def.unknownKeys;if(d==="passthrough")for(let l of s)c.push({key:{status:"valid",value:l},value:{status:"valid",value:i.data[l]}});else if(d==="strict")s.length>0&&(P(i,{code:b.unrecognized_keys,keys:s}),r.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let d=this._def.catchall;for(let l of s){let u=i.data[l];c.push({key:{status:"valid",value:l},value:d._parse(new Jt(i,u,i.path,l)),alwaysSet:l in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let d=[];for(let l of c){let u=await l.key,f=await l.value;d.push({key:u,value:f,alwaysSet:l.alwaysSet})}return d}).then(d=>He.mergeObjectSync(r,d)):He.mergeObjectSync(r,c)}get shape(){return this._def.shape()}strict(t){return L.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(n,r)=>{let i=this._def.errorMap?.(n,r).message??r.defaultError;return n.code==="unrecognized_keys"?{message:L.errToObj(t).message??i}:{message:i}}}:{}})}strip(){return new e({...this._def,unknownKeys:"strip"})}passthrough(){return new e({...this._def,unknownKeys:"passthrough"})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:$.ZodObject})}setKey(t,n){return this.augment({[t]:n})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let r of Z.objectKeys(t))t[r]&&this.shape[r]&&(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let r of Z.objectKeys(this.shape))t[r]||(n[r]=this.shape[r]);return new e({...this._def,shape:()=>n})}deepPartial(){return xa(this)}partial(t){let n={};for(let r of Z.objectKeys(this.shape)){let i=this.shape[r];t&&!t[r]?n[r]=i:n[r]=i.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let r of Z.objectKeys(this.shape))if(t&&!t[r])n[r]=this.shape[r];else{let o=this.shape[r];for(;o instanceof Lt;)o=o._def.innerType;n[r]=o}return new e({...this._def,shape:()=>n})}keyof(){return wT(Z.objectKeys(this.shape))}};gt.create=(e,t)=>new gt({shape:()=>e,unknownKeys:"strip",catchall:nn.create(),typeName:$.ZodObject,...G(t)});gt.strictCreate=(e,t)=>new gt({shape:()=>e,unknownKeys:"strict",catchall:nn.create(),typeName:$.ZodObject,...G(t)});gt.lazycreate=(e,t)=>new gt({shape:e,unknownKeys:"strip",catchall:nn.create(),typeName:$.ZodObject,...G(t)});var mo=class extends Y{_parse(t){let{ctx:n}=this._processInputParams(t),r=this._def.options;function i(o){for(let s of o)if(s.result.status==="valid")return s.result;for(let s of o)if(s.result.status==="dirty")return n.common.issues.push(...s.ctx.common.issues),s.result;let a=o.map(s=>new mt(s.ctx.common.issues));return P(n,{code:b.invalid_union,unionErrors:a}),K}if(n.common.async)return Promise.all(r.map(async o=>{let a={...n,common:{...n.common,issues:[]},parent:null};return{result:await o._parseAsync({data:n.data,path:n.path,parent:a}),ctx:a}})).then(i);{let o,a=[];for(let c of r){let d={...n,common:{...n.common,issues:[]},parent:null},l=c._parseSync({data:n.data,path:n.path,parent:d});if(l.status==="valid")return l;l.status==="dirty"&&!o&&(o={result:l,ctx:d}),d.common.issues.length&&a.push(d.common.issues)}if(o)return n.common.issues.push(...o.ctx.common.issues),o.result;let s=a.map(c=>new mt(c));return P(n,{code:b.invalid_union,unionErrors:s}),K}}get options(){return this._def.options}};mo.create=(e,t)=>new mo({options:e,typeName:$.ZodUnion,...G(t)});var pr=e=>e instanceof yo?pr(e.schema):e instanceof Ut?pr(e.innerType()):e instanceof _o?[e.value]:e instanceof wo?e.options:e instanceof Eo?Z.objectValues(e.enum):e instanceof vo?pr(e._def.innerType):e instanceof po?[void 0]:e instanceof ho?[null]:e instanceof Lt?[void 0,...pr(e.unwrap())]:e instanceof Rn?[null,...pr(e.unwrap())]:e instanceof Sc||e instanceof Ao?pr(e.unwrap()):e instanceof bo?pr(e._def.innerType):[],_u=class e extends Y{_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==C.object)return P(n,{code:b.invalid_type,expected:C.object,received:n.parsedType}),K;let r=this.discriminator,i=n.data[r],o=this.optionsMap.get(i);return o?n.common.async?o._parseAsync({data:n.data,path:n.path,parent:n}):o._parseSync({data:n.data,path:n.path,parent:n}):(P(n,{code:b.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[r]}),K)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=new Map;for(let o of n){let a=pr(o.shape[t]);if(!a.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let s of a){if(i.has(s))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(s)}`);i.set(s,o)}}return new e({typeName:$.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...G(r)})}};function Oy(e,t){let n=kn(e),r=kn(t);if(e===t)return{valid:!0,data:e};if(n===C.object&&r===C.object){let i=Z.objectKeys(t),o=Z.objectKeys(e).filter(s=>i.indexOf(s)!==-1),a={...e,...t};for(let s of o){let c=Oy(e[s],t[s]);if(!c.valid)return{valid:!1};a[s]=c.data}return{valid:!0,data:a}}else if(n===C.array&&r===C.array){if(e.length!==t.length)return{valid:!1};let i=[];for(let o=0;o<e.length;o++){let a=e[o],s=t[o],c=Oy(a,s);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else return n===C.date&&r===C.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var go=class extends Y{_parse(t){let{status:n,ctx:r}=this._processInputParams(t),i=(o,a)=>{if(gu(o)||gu(a))return K;let s=Oy(o.value,a.value);return s.valid?((yu(o)||yu(a))&&n.dirty(),{status:n.value,value:s.data}):(P(r,{code:b.invalid_intersection_types}),K)};return r.common.async?Promise.all([this._def.left._parseAsync({data:r.data,path:r.path,parent:r}),this._def.right._parseAsync({data:r.data,path:r.path,parent:r})]).then(([o,a])=>i(o,a)):i(this._def.left._parseSync({data:r.data,path:r.path,parent:r}),this._def.right._parseSync({data:r.data,path:r.path,parent:r}))}};go.create=(e,t,n)=>new go({left:e,right:t,typeName:$.ZodIntersection,...G(n)});var Cn=class e extends Y{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==C.array)return P(r,{code:b.invalid_type,expected:C.array,received:r.parsedType}),K;if(r.data.length<this._def.items.length)return P(r,{code:b.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),K;!this._def.rest&&r.data.length>this._def.items.length&&(P(r,{code:b.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),n.dirty());let o=[...r.data].map((a,s)=>{let c=this._def.items[s]||this._def.rest;return c?c._parse(new Jt(r,a,r.path,s)):null}).filter(a=>!!a);return r.common.async?Promise.all(o).then(a=>He.mergeArray(n,a)):He.mergeArray(n,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Cn.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Cn({items:e,typeName:$.ZodTuple,rest:null,...G(t)})};var wu=class e extends Y{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==C.object)return P(r,{code:b.invalid_type,expected:C.object,received:r.parsedType}),K;let i=[],o=this._def.keyType,a=this._def.valueType;for(let s in r.data)i.push({key:o._parse(new Jt(r,s,r.path,s)),value:a._parse(new Jt(r,r.data[s],r.path,s)),alwaysSet:s in r.data});return r.common.async?He.mergeObjectAsync(n,i):He.mergeObjectSync(n,i)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof Y?new e({keyType:t,valueType:n,typeName:$.ZodRecord,...G(r)}):new e({keyType:oi.create(),valueType:t,typeName:$.ZodRecord,...G(n)})}},Da=class extends Y{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==C.map)return P(r,{code:b.invalid_type,expected:C.map,received:r.parsedType}),K;let i=this._def.keyType,o=this._def.valueType,a=[...r.data.entries()].map(([s,c],d)=>({key:i._parse(new Jt(r,s,r.path,[d,"key"])),value:o._parse(new Jt(r,c,r.path,[d,"value"]))}));if(r.common.async){let s=new Map;return Promise.resolve().then(async()=>{for(let c of a){let d=await c.key,l=await c.value;if(d.status==="aborted"||l.status==="aborted")return K;(d.status==="dirty"||l.status==="dirty")&&n.dirty(),s.set(d.value,l.value)}return{status:n.value,value:s}})}else{let s=new Map;for(let c of a){let d=c.key,l=c.value;if(d.status==="aborted"||l.status==="aborted")return K;(d.status==="dirty"||l.status==="dirty")&&n.dirty(),s.set(d.value,l.value)}return{status:n.value,value:s}}}};Da.create=(e,t,n)=>new Da({valueType:t,keyType:e,typeName:$.ZodMap,...G(n)});var Ma=class e extends Y{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.parsedType!==C.set)return P(r,{code:b.invalid_type,expected:C.set,received:r.parsedType}),K;let i=this._def;i.minSize!==null&&r.data.size<i.minSize.value&&(P(r,{code:b.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),n.dirty()),i.maxSize!==null&&r.data.size>i.maxSize.value&&(P(r,{code:b.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),n.dirty());let o=this._def.valueType;function a(c){let d=new Set;for(let l of c){if(l.status==="aborted")return K;l.status==="dirty"&&n.dirty(),d.add(l.value)}return{status:n.value,value:d}}let s=[...r.data.values()].map((c,d)=>o._parse(new Jt(r,c,r.path,d)));return r.common.async?Promise.all(s).then(c=>a(c)):a(s)}min(t,n){return new e({...this._def,minSize:{value:t,message:L.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:L.toString(n)}})}size(t,n){return this.min(t,n).max(t,n)}nonempty(t){return this.min(1,t)}};Ma.create=(e,t)=>new Ma({valueType:e,minSize:null,maxSize:null,typeName:$.ZodSet,...G(t)});var Eu=class e extends Y{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==C.function)return P(n,{code:b.invalid_type,expected:C.function,received:n.parsedType}),K;function r(s,c){return Ac({data:s,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Ca(),fr].filter(d=>!!d),issueData:{code:b.invalid_arguments,argumentsError:c}})}function i(s,c){return Ac({data:s,path:n.path,errorMaps:[n.common.contextualErrorMap,n.schemaErrorMap,Ca(),fr].filter(d=>!!d),issueData:{code:b.invalid_return_type,returnTypeError:c}})}let o={errorMap:n.common.contextualErrorMap},a=n.data;if(this._def.returns instanceof si){let s=this;return Be(async function(...c){let d=new mt([]),l=await s._def.args.parseAsync(c,o).catch(h=>{throw d.addIssue(r(c,h)),d}),u=await Reflect.apply(a,this,l);return await s._def.returns._def.type.parseAsync(u,o).catch(h=>{throw d.addIssue(i(u,h)),d})})}else{let s=this;return Be(function(...c){let d=s._def.args.safeParse(c,o);if(!d.success)throw new mt([r(c,d.error)]);let l=Reflect.apply(a,this,d.data),u=s._def.returns.safeParse(l,o);if(!u.success)throw new mt([i(l,u.error)]);return u.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Cn.create(t).rest(hr.create())})}returns(t){return new e({...this._def,returns:t})}implement(t){return this.parse(t)}strictImplement(t){return this.parse(t)}static create(t,n,r){return new e({args:t||Cn.create([]).rest(hr.create()),returns:n||hr.create(),typeName:$.ZodFunction,...G(r)})}},yo=class extends Y{get schema(){return this._def.getter()}_parse(t){let{ctx:n}=this._processInputParams(t);return this._def.getter()._parse({data:n.data,path:n.path,parent:n})}};yo.create=(e,t)=>new yo({getter:e,typeName:$.ZodLazy,...G(t)});var _o=class extends Y{_parse(t){if(t.data!==this._def.value){let n=this._getOrReturnCtx(t);return P(n,{received:n.data,code:b.invalid_literal,expected:this._def.value}),K}return{status:"valid",value:t.data}}get value(){return this._def.value}};_o.create=(e,t)=>new _o({value:e,typeName:$.ZodLiteral,...G(t)});function wT(e,t){return new wo({values:e,typeName:$.ZodEnum,...G(t)})}var wo=class e extends Y{_parse(t){if(typeof t.data!="string"){let n=this._getOrReturnCtx(t),r=this._def.values;return P(n,{expected:Z.joinValues(r),received:n.parsedType,code:b.invalid_type}),K}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let n=this._getOrReturnCtx(t),r=this._def.values;return P(n,{received:n.data,code:b.invalid_enum_value,options:r}),K}return Be(t.data)}get options(){return this._def.values}get enum(){let t={};for(let n of this._def.values)t[n]=n;return t}get Values(){let t={};for(let n of this._def.values)t[n]=n;return t}get Enum(){let t={};for(let n of this._def.values)t[n]=n;return t}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(r=>!t.includes(r)),{...this._def,...n})}};wo.create=wT;var Eo=class extends Y{_parse(t){let n=Z.getValidEnumValues(this._def.values),r=this._getOrReturnCtx(t);if(r.parsedType!==C.string&&r.parsedType!==C.number){let i=Z.objectValues(n);return P(r,{expected:Z.joinValues(i),received:r.parsedType,code:b.invalid_type}),K}if(this._cache||(this._cache=new Set(Z.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=Z.objectValues(n);return P(r,{received:r.data,code:b.invalid_enum_value,options:i}),K}return Be(t.data)}get enum(){return this._def.values}};Eo.create=(e,t)=>new Eo({values:e,typeName:$.ZodNativeEnum,...G(t)});var si=class extends Y{unwrap(){return this._def.type}_parse(t){let{ctx:n}=this._processInputParams(t);if(n.parsedType!==C.promise&&n.common.async===!1)return P(n,{code:b.invalid_type,expected:C.promise,received:n.parsedType}),K;let r=n.parsedType===C.promise?n.data:Promise.resolve(n.data);return Be(r.then(i=>this._def.type.parseAsync(i,{path:n.path,errorMap:n.common.contextualErrorMap})))}};si.create=(e,t)=>new si({type:e,typeName:$.ZodPromise,...G(t)});var Ut=class extends Y{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===$.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:n,ctx:r}=this._processInputParams(t),i=this._def.effect||null,o={addIssue:a=>{P(r,a),a.fatal?n.abort():n.dirty()},get path(){return r.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let a=i.transform(r.data,o);if(r.common.async)return Promise.resolve(a).then(async s=>{if(n.value==="aborted")return K;let c=await this._def.schema._parseAsync({data:s,path:r.path,parent:r});return c.status==="aborted"?K:c.status==="dirty"?so(c.value):n.value==="dirty"?so(c.value):c});{if(n.value==="aborted")return K;let s=this._def.schema._parseSync({data:a,path:r.path,parent:r});return s.status==="aborted"?K:s.status==="dirty"?so(s.value):n.value==="dirty"?so(s.value):s}}if(i.type==="refinement"){let a=s=>{let c=i.refinement(s,o);if(r.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return s};if(r.common.async===!1){let s=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});return s.status==="aborted"?K:(s.status==="dirty"&&n.dirty(),a(s.value),{status:n.value,value:s.value})}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(s=>s.status==="aborted"?K:(s.status==="dirty"&&n.dirty(),a(s.value).then(()=>({status:n.value,value:s.value}))))}if(i.type==="transform")if(r.common.async===!1){let a=this._def.schema._parseSync({data:r.data,path:r.path,parent:r});if(!ii(a))return K;let s=i.transform(a.value,o);if(s instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:n.value,value:s}}else return this._def.schema._parseAsync({data:r.data,path:r.path,parent:r}).then(a=>ii(a)?Promise.resolve(i.transform(a.value,o)).then(s=>({status:n.value,value:s})):K);Z.assertNever(i)}};Ut.create=(e,t,n)=>new Ut({schema:e,typeName:$.ZodEffects,effect:t,...G(n)});Ut.createWithPreprocess=(e,t,n)=>new Ut({schema:t,effect:{type:"preprocess",transform:e},typeName:$.ZodEffects,...G(n)});var Lt=class extends Y{_parse(t){return this._getType(t)===C.undefined?Be(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Lt.create=(e,t)=>new Lt({innerType:e,typeName:$.ZodOptional,...G(t)});var Rn=class extends Y{_parse(t){return this._getType(t)===C.null?Be(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Rn.create=(e,t)=>new Rn({innerType:e,typeName:$.ZodNullable,...G(t)});var vo=class extends Y{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return n.parsedType===C.undefined&&(r=this._def.defaultValue()),this._def.innerType._parse({data:r,path:n.path,parent:n})}removeDefault(){return this._def.innerType}};vo.create=(e,t)=>new vo({innerType:e,typeName:$.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...G(t)});var bo=class extends Y{_parse(t){let{ctx:n}=this._processInputParams(t),r={...n,common:{...n.common,issues:[]}},i=this._def.innerType._parse({data:r.data,path:r.path,parent:{...r}});return Ra(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new mt(r.common.issues)},input:r.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new mt(r.common.issues)},input:r.data})}}removeCatch(){return this._def.innerType}};bo.create=(e,t)=>new bo({innerType:e,typeName:$.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...G(t)});var La=class extends Y{_parse(t){if(this._getType(t)!==C.nan){let r=this._getOrReturnCtx(t);return P(r,{code:b.invalid_type,expected:C.nan,received:r.parsedType}),K}return{status:"valid",value:t.data}}};La.create=e=>new La({typeName:$.ZodNaN,...G(e)});var m5=Symbol("zod_brand"),Sc=class extends Y{_parse(t){let{ctx:n}=this._processInputParams(t),r=n.data;return this._def.type._parse({data:r,path:n.path,parent:n})}unwrap(){return this._def.type}},Ic=class e extends Y{_parse(t){let{status:n,ctx:r}=this._processInputParams(t);if(r.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:r.data,path:r.path,parent:r});return o.status==="aborted"?K:o.status==="dirty"?(n.dirty(),so(o.value)):this._def.out._parseAsync({data:o.value,path:r.path,parent:r})})();{let i=this._def.in._parseSync({data:r.data,path:r.path,parent:r});return i.status==="aborted"?K:i.status==="dirty"?(n.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:r.path,parent:r})}}static create(t,n){return new e({in:t,out:n,typeName:$.ZodPipeline})}},Ao=class extends Y{_parse(t){let n=this._def.innerType._parse(t),r=i=>(ii(i)&&(i.value=Object.freeze(i.value)),i);return Ra(n)?n.then(i=>r(i)):r(n)}unwrap(){return this._def.innerType}};Ao.create=(e,t)=>new Ao({innerType:e,typeName:$.ZodReadonly,...G(t)});function mT(e,t){let n=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof n=="string"?{message:n}:n}function ET(e,t={},n){return e?ai.create().superRefine((r,i)=>{let o=e(r);if(o instanceof Promise)return o.then(a=>{if(!a){let s=mT(t,r),c=s.fatal??n??!0;i.addIssue({code:"custom",...s,fatal:c})}});if(!o){let a=mT(t,r),s=a.fatal??n??!0;i.addIssue({code:"custom",...a,fatal:s})}}):ai.create()}var g5={object:gt.lazycreate},$;(function(e){e.ZodString="ZodString",e.ZodNumber="ZodNumber",e.ZodNaN="ZodNaN",e.ZodBigInt="ZodBigInt",e.ZodBoolean="ZodBoolean",e.ZodDate="ZodDate",e.ZodSymbol="ZodSymbol",e.ZodUndefined="ZodUndefined",e.ZodNull="ZodNull",e.ZodAny="ZodAny",e.ZodUnknown="ZodUnknown",e.ZodNever="ZodNever",e.ZodVoid="ZodVoid",e.ZodArray="ZodArray",e.ZodObject="ZodObject",e.ZodUnion="ZodUnion",e.ZodDiscriminatedUnion="ZodDiscriminatedUnion",e.ZodIntersection="ZodIntersection",e.ZodTuple="ZodTuple",e.ZodRecord="ZodRecord",e.ZodMap="ZodMap",e.ZodSet="ZodSet",e.ZodFunction="ZodFunction",e.ZodLazy="ZodLazy",e.ZodLiteral="ZodLiteral",e.ZodEnum="ZodEnum",e.ZodEffects="ZodEffects",e.ZodNativeEnum="ZodNativeEnum",e.ZodOptional="ZodOptional",e.ZodNullable="ZodNullable",e.ZodDefault="ZodDefault",e.ZodCatch="ZodCatch",e.ZodPromise="ZodPromise",e.ZodBranded="ZodBranded",e.ZodPipeline="ZodPipeline",e.ZodReadonly="ZodReadonly"})($||($={}));var y5=(e,t={message:`Input not instance of ${e.name}`})=>ET(n=>n instanceof e,t),vT=oi.create,bT=co.create,_5=La.create,w5=lo.create,AT=uo.create,E5=fo.create,v5=Oa.create,b5=po.create,A5=ho.create,S5=ai.create,I5=hr.create,T5=nn.create,P5=Na.create,k5=mr.create,C5=gt.create,R5=gt.strictCreate,x5=mo.create,O5=_u.create,N5=go.create,D5=Cn.create,M5=wu.create,L5=Da.create,J5=Ma.create,U5=Eu.create,j5=yo.create,q5=_o.create,K5=wo.create,H5=Eo.create,V5=si.create,$5=Ut.create,W5=Lt.create,F5=Rn.create,B5=Ut.createWithPreprocess,G5=Ic.create,Y5=()=>vT().optional(),z5=()=>bT().optional(),X5=()=>AT().optional(),Z5={string:(e=>oi.create({...e,coerce:!0})),number:(e=>co.create({...e,coerce:!0})),boolean:(e=>uo.create({...e,coerce:!0})),bigint:(e=>lo.create({...e,coerce:!0})),date:(e=>fo.create({...e,coerce:!0}))};var Q5=K;var Ve=e=>W.string().transform(t=>e.find(n=>n===t)??"unknown"),Ja=W.string().uuid(),gr=W.string().refine(e=>Number.isFinite(Date.parse(e))),vu=W.string().regex(/^(0|[1-9][0-9]{0,24})$/),Tc=W.object({status:Ve(["available","needs_reauthorization"]),reason:Ve(["agent_inactive","current_grant_missing","current_grant_replaced","current_grant_expired","current_grant_inactive","required_scope_missing","managed_wallet_authority_unverified","authority_projection_unknown","authorization_version_unsupported","owner_eligibility_required"]).optional()}),eq=W.object({grantId:Ja,approvalId:Ja,expiresAt:gr,totalMicros:vu,perTransactionMicros:vu,spentMicros:vu,reservedMicros:vu,scopes:W.array(Ve(["card:vic","wallet:x402"]))}),tq=W.object({agentId:Ja,associationId:Ja,associationVersion:W.string().regex(/^[1-9][0-9]*$/),authorizationVersion:W.number().int(),lifecycle:Ve(["setting_up","active","paused","revoked"]),managementPlane:Ve(["protected"]),agentJkt:W.string().regex(/^[A-Za-z0-9_-]{43}$/),agentRootJkt:W.string().regex(/^[A-Za-z0-9_-]{43}$/),name:W.string().min(1).transform(e=>e.slice(0,120)),grant:W.union([W.object({condition:W.literal("absent")}),eq.extend({condition:Ve(["current","ended","replaced","revoked","not_yet_effective"]),version:W.number().int().positive(),effectiveAt:gr})]),mode:Ve(["identity_only","card","wallet","both"]),capabilities:W.array(Ve(["card","wallet"])),cardVerified:W.boolean(),tapStatus:Ve(["registered","pending","contact_required","not_requested","deactivated","unavailable"]),tapBlockedReason:W.string().nullable(),tapRegisteredAt:gr.nullable(),registrable:W.boolean(),createdAt:gr,revoked:W.boolean(),paused:W.boolean(),executionStatus:Tc.shape.status,executionStatusReason:Tc.shape.reason,executionReadiness:W.object({shared:Tc,card:Tc.optional(),wallet:Tc.optional()}),identityKeyCustody:Ve(["turnkey"]),identityKeyStatus:Ve(["active","revoked"]),mandates:W.array(W.unknown()),wallet:W.object({walletAddress:W.string().nullable(),network:Ve(["eip155:4217"]).nullable(),provisioned:W.boolean()}).nullable(),runtimes:W.array(W.object({runtimeId:Ja,agentId:Ja,generation:W.string().regex(/^[1-9][0-9]*$/),custody:Ve(["device","tkms","signer"]),source:Ve(["financial","card"]),kind:Ve(["local_cli","remote_mcp","mobile","automation","compatibility"]),label:W.string(),status:Ve(["active","pending","revoked"]),credentialAudience:W.string(),credentialPurpose:W.string(),createdAt:gr,lastSeenAt:gr.nullable(),revokedAt:gr.nullable(),approval:W.object({status:Ve(["healthy","renew_soon","expired","inactive"]),expiresAt:gr.nullable()}).optional()}))}),ST=W.object({v:W.literal(2),read:W.object({status:W.literal("available"),observedAt:gr}),agents:W.array(tq),truncated:W.boolean()});async function IT(e,t,n){let{timeoutMs:r=3e4,...i}=t??{},o=i.signal===void 0&&e instanceof Request?e.signal:i.signal;o?.throwIfAborted();let a=new AbortController,{signal:s}=a,c=()=>a.abort(o?.reason);o?.addEventListener("abort",c,{once:!0});let d,l=new Promise((f,h)=>{d=()=>h(s.reason),s.addEventListener("abort",d,{once:!0})}),u=setTimeout(()=>a.abort(),r);try{return await Promise.race([(async()=>{let f=await fetch(e,{...i,signal:s});s.throwIfAborted();let h=await n(f,s);return s.throwIfAborted(),h})(),l])}finally{clearTimeout(u),o?.removeEventListener("abort",c),s.removeEventListener("abort",d)}}var bu=class extends Error{code="ATTESTATION_KEY_DRIFT";kind="attestation";nextAction="visa disconnect --all";fix="Run `visa disconnect --all` to clear the stale device credential, then `visa connect` to enroll again.";hint;constructor(t,n){super(t),this.name="AttestationDriftError",this.hint=n}},Pc=class extends Error{code="session_required";kind="session";nextAction="visa connect";fix="visa connect";status;constructor(t,n){super(t),this.name="SessionRequiredError",this.status=n}},Au=class extends Error{code="server_unavailable";kind="server";nextAction=void 0;fix;status;retryable;constructor(t,n=503,r=!0){super(t),this.name="ServerUnavailableError",this.status=n,this.retryable=r,this.fix=r?"Wait a moment and retry. If the outage persists check https://visacli.sh for status.":"Do not retry this request automatically; inspect the server error and reconcile the existing attempt."}},Su=class extends Error{code="surface_disabled";kind="server";nextAction=void 0;fix="This surface is disabled or not configured on the server (kill switch or missing config). Escalate to a human \u2014 retrying will not help.";status;disabledSurface;flag;correlationId;constructor(t,n={}){super(t),this.name="SurfaceDisabledError",this.status=n.status??503,this.disabledSurface=n.disabledSurface,this.flag=n.flag,this.correlationId=n.correlationId}},Iu=class extends Error{constructor(n,r){super(n);this.retryAfterSeconds=r;this.name="RateLimitError",this.nextAction=void 0,this.fix=`Wait ${r}s before retrying.`}retryAfterSeconds;code="rate_limited";kind="rate_limit";fix;status=429;nextAction=void 0};var nq=["UNABLE_TO_GET_ISSUER_CERT","UNABLE_TO_GET_ISSUER_CERT_LOCALLY","UNABLE_TO_VERIFY_LEAF_SIGNATURE","SELF_SIGNED_CERT_IN_CHAIN","DEPTH_ZERO_SELF_SIGNED_CERT","CERT_UNTRUSTED"],rq="This machine does not trust the certificate offered for the Visa CLI server, so the request never left it. The server is not down, and neither retrying nor signing in again can help. A network that inspects TLS traffic does this: point Node at its root certificate with NODE_EXTRA_CA_CERTS=/path/to/root.pem, or use a network that does not inspect. Do not disable certificate verification.";function iq(){return Object.fromEntries(nq.map(e=>[e,rq]))}var TT={ENOTFOUND:"Cannot resolve the Visa CLI server hostname (DNS error). Check your internet connection or the auth.serverUrl setting.",EAI_AGAIN:"DNS lookup for the Visa CLI server failed temporarily. Check your internet connection and try again.",ECONNREFUSED:"The Visa CLI server refused the connection. The service may be down \u2014 check https://visacli.sh for status.",ECONNRESET:"The connection to the Visa CLI server was reset mid-request. Try again in a moment.",EHOSTUNREACH:"The Visa CLI server is unreachable from this network. Check your internet connection.",ETIMEDOUT:"The connection to the Visa CLI server timed out. Try again or check https://visacli.sh for status.",CERT_HAS_EXPIRED:"The Visa CLI server's TLS certificate is expired. Check https://visacli.sh for status; do not bypass the cert.",...iq(),ERR_TLS_CERT_ALTNAME_INVALID:"The certificate offered for the Visa CLI server is for a different hostname. Check the auth.serverUrl setting. Do not disable certificate verification.",UND_ERR_CONNECT_TIMEOUT:"The connection to the Visa CLI server timed out before it could be established. Try again in a moment.",UND_ERR_SOCKET:"The connection to the Visa CLI server was interrupted. Try again in a moment."};function Ny(e){if(!e||typeof e!="object")return null;let t=e,r=(t.cause&&typeof t.cause=="object"?t.cause.code:void 0)??(typeof t.code=="string"?t.code:void 0);return typeof r=="string"&&r.length>0?r:null}function Tu(e){let t=e&&typeof e=="object"?e:{};if(t.name==="AbortError"||typeof t.message=="string"&&t.message.includes("aborted"))return"The request timed out. The server may be under heavy load. Please try again.";let n=Ny(e);return n&&TT[n]?TT[n]:`Network error contacting the Visa CLI server (${n?`${n}: ${typeof t.message=="string"?t.message:"unknown"}`:typeof t.message=="string"&&t.message.length>0?t.message:"unknown error"}). Check https://visacli.sh for status.`}var oq="visa connect",aq="agent_enroll",sq="/agent/enroll/protected-agent",IV=Object.freeze(["setup_start","setup_status","setup_resume","setup_cancel","setup_agent","enroll_agent","agent_pairing_cancel","agent_handoff_claim","agent_connect","agent_connect_cancel","agent_connect_poll","feedback","ucp_checkout_preflight","ucp_checkout_handoff","ucp_checkout_reconcile","ucp_discover","webmcp_discover"]),TV=Object.freeze(["create","verify","enroll-claim","pair","claim","pairing-resume","cancel","handoff-claim","connect","grant-wallet","grant-card","grant-activate","grant-claim","grants","grant-cancel","grant-batch"]),PV=Object.freeze(["setup","agent","wallet","find","inspect","receipt","connections","keys","security","checkout","mandate","logout","capabilities","feedback","status","pay","purchase","limits","fund","activity"]);function PT(){return`Run ${oq} or call ${aq}, open the printed URL, enter the code at ${sq}, approve the device and its limits, then pay with the pay tool. Do not retry the retired command; nothing was signed, paired, or paid.`}var RT=x(sc());function CT(){return!!(kT(process.env.VISA_CLI_NO_UPDATE_CHECK)||kT(process.env.CI)||process.env.NODE_ENV==="test")}function kT(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}var kc="5.0.0-rc.409",cq="1",dq=/^vk_(?:live|test)_[A-Za-z0-9_-]{16,128}$/,lq=5e3,Pe=class extends Error{constructor(n,r,i,o,a,s){super(n);this.status=r;this.code=i;this.detail=o;this.serverRetryable=a;this.details=s;this.name="ApiHttpError"}status;code;detail;serverRetryable;details;get retryable(){return this.serverRetryable??(this.status>=500||this.status===408||this.status===425||this.status===429)}};function uq(e){if(e===null||!/^\d{1,4}$/.test(e))return 3;let t=Number(e);return Number.isSafeInteger(t)&&t>=1&&t<=3600?t:3}var fq=new Set(["agent_paused","agent_revoked","device_key_replaced","grant_expired","owner_withdrawal_pending"]);function pq(e,t){if(e===410&&(t?.code==="route_retired"||t?.error==="route_retired"))return new ge(typeof t?.message=="string"&&t.message.length>0?t.message:"This legacy agent setup route was removed.","legacy_door_removed",{nextAction:PT(),details:{stage:"retired_door",...typeof t?.replacement=="string"?{replacement:t.replacement}:{}}});if((t?.reason==="policy_step_up_required"||t?.error==="spend_policy_step_up_required")&&typeof t?.stepUp?.reviewUrl=="string")return new Pe(`Owner confirmation required before this payment. Ask the owner to review it at ${t.stepUp.reviewUrl}. Nothing was paid.`,e,typeof t?.error=="string"?t.error:void 0,"policy_step_up_required",!1);if(t?.error==="owner_approval_required"&&t?.approval&&typeof t.approval=="object"&&!Array.isArray(t.approval))return new Pe(typeof t?.message=="string"&&t.message?t.message:"owner_approval_required",e,"owner_approval_required",void 0,!1,{approval:t.approval});let n=typeof t?.error=="string"?t.error:typeof t?.code=="string"&&fq.has(t.code)?t.code:void 0,r=typeof t?.reason=="string"?t.reason:void 0,i=typeof t?.retryable=="boolean"?t.retryable:void 0,o=typeof t?.message=="string"&&t.message||r||n||"";if(o)return new Pe(o,e,n,r,i);let a=e>=500||e===408||e===425||e===429;return i??a?new Pe(`Request failed (${e}). Try again.`,e,void 0,void 0,i):e===404?new Pe(`Request failed (${e}) \u2014 not found; check the identifier or slug.`,e,void 0,void 0,i):new Pe(`Request failed (${e}).`,e,void 0,void 0,i)}var hq="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";function rn(e){return typeof e=="string"?e.trim():""}function mq(e){let t=rn(e.error_code)||rn(e.error);return t?t==="SURFACE_DISABLED"||/(_disabled|_not_configured)$/.test(t):!1}function gq(e){let t=e&&typeof e=="object"?e:{},n=rn(t.error)||rn(t.message);if(!n)return hq;let r=rn(t.error_code),i=[["surface",rn(t.disabled_surface)],["flag",rn(t.flag)],["correlation_id",rn(t.correlation_id)]].filter(([,a])=>a).map(([a,s])=>`${a}=${s}`),o=i.length?` (${i.join(" ")})`:"";return r?`503 [${r}] ${n}${o}`:`503 ${n}${o}`}function yq(e=process.env,t=process.stdin.isTTY){let n=["Not logged in. No local Visa CLI session credentials were found."],r=e.VISA_CLI_API_KEY?.trim();return r&&(dq.test(r)?n.push("VISA_CLI_API_KEY is set, but this operation requires an enrolled device session."):n.push("VISA_CLI_API_KEY is set but has invalid format (expected vk_live_<...> or vk_test_<...>).")),n.push("Run `visa connect` to sign in and connect this device session."),t===!1&&n.push("Complete sign-in in a normal terminal with `visa connect`, then restart the MCP client."),n.join(`
|
|
32
|
+
`)}function wr(e){return!!e&&typeof e=="object"&&!Array.isArray(e)}function yr(e){return e===null||typeof e=="string"}function _r(e,t){let n=e[t];return typeof n=="string"&&n.length>0?n:void 0}function _q(e){if(!wr(e))throw new Error("account activity returned a malformed entry");let t=e.rail;if(t!=="card"&&t!=="x402")throw new Error("account activity entry is missing a valid rail label");let n=e.amountUsd,r={id:e.id,operationId:e.operationId,merchant:e.merchant,description:e.description,currency:e.currency,status:e.status,createdAt:e.createdAt};for(let[i,o]of Object.entries(r))if(typeof o!="string"||o.length===0)throw new Error(`account activity entry is missing ${i}`);if(typeof n!="number"||!Number.isFinite(n))throw new Error("account activity entry is missing a numeric amount");return{id:r.id,operationId:r.operationId,merchant:r.merchant,description:r.description,amountUsd:n,currency:r.currency,status:r.status,rail:t,createdAt:r.createdAt,..._r(e,"failurePhase")?{failurePhase:e.failurePhase}:{},..._r(e,"finalizesBy")?{finalizesBy:e.finalizesBy}:{},..._r(e,"agentId")?{agentId:e.agentId}:{},..._r(e,"agentName")?{agentName:e.agentName}:{},..._r(e,"grantId")?{grantId:e.grantId}:{},..._r(e,"mandateId")?{mandateId:e.mandateId}:{},..._r(e,"drawId")?{drawId:e.drawId}:{},..._r(e,"transactionHash")?{transactionHash:e.transactionHash}:{},..._r(e,"transactionNetwork")?{transactionNetwork:e.transactionNetwork}:{}}}function wq(e){if(!wr(e))return null;let{payment:t,route:n,party:r,authority:i,outcome:o}=e;return e.schemaVersion!==1||typeof e.operationId!="string"||typeof e.activityId!="string"||!wr(t)||typeof t.amountAtomic!="string"||typeof t.decimals!="number"||!Number.isSafeInteger(t.decimals)||t.decimals<0||typeof t.currency!="string"||typeof t.merchant!="string"||typeof t.description!="string"||typeof t.createdAt!="string"||!wr(n)||n.rail!=="wallet"&&n.rail!=="card"||!yr(n.protocol)||!yr(n.network)||!yr(n.cardLast4)||!wr(r)||!yr(r.agentId)||!yr(r.agentName)||!wr(i)||!yr(i.grantId)||!yr(i.mandateId)||!yr(i.drawId)||!wr(o)||typeof o.status!="string"||typeof o.proofLevel!="string"||typeof o.final!="boolean"||typeof o.updatedAt!="string"||!yr(o.finalizesBy)||!Array.isArray(e.evidence)||!e.evidence.every(wr)||!Array.isArray(e.timeline)||!e.timeline.every(wr)||e.dataCompleteness!=="complete"&&e.dataCompleteness!=="partial"?null:e}var Ua=class{constructor(t){this.getSessionToken=t;this.baseUrl=Nn()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!CT()){let n=t.headers.get("X-Latest-Version");n&&(0,RT.isStrictlyNewer)(n,kc)&&(this.lastSignals.updateAvailable={currentVersion:kc,latestVersion:n})}}getClientVersion(){return kc}getAuthServerOrigin(){return this.baseUrl}throwIfAttestationDrift(t){if(t?.error_code==="ATTESTATION_KEY_DRIFT")throw new bu(t.error||"Your biometric key is out of sync with the server.",typeof t.hint=="string"?t.hint:void 0)}async throwServerUnavailable(t,n){let r=null;try{r=await t.json()}catch{n.throwIfAborted()}let i=gq(r),o=r&&typeof r=="object"?r:{};throw mq(o)?new Su(i,{status:t.status,disabledSurface:rn(o.disabled_surface)||void 0,flag:rn(o.flag)||void 0,correlationId:rn(o.correlation_id)||void 0}):new Au(i,t.status,typeof o.retryable=="boolean"?o.retryable:!0)}async financialRuntimeRequest(t,n){return this.request("POST",`/v1/financial-runtime/${t}`,n,2e4)}async identityDeviceRequest(t,n){return this.request("POST",`/v1/identity-device/${t}`,n,2e4)}async request(t,n,r,i,o){let a=await this.getSessionToken();if(!a)throw new Pc(yq());let s={Authorization:`Bearer ${a}`};o&&(t==="GET"?s["X-User-Context"]=encodeURIComponent(o.replace(/[\r\n\0]/g," ").slice(0,1e3)):r={...r||{},user_context:o}),r&&(s["Content-Type"]="application/json");let c;try{return await IT(`${this.baseUrl}${n}`,{method:t,headers:{...s,"X-Visa-CLI-Version":kc,"X-Visa-Agent-Operations-Version":cq,"X-Source":"cli",...Aa()},body:r?JSON.stringify(r):void 0,timeoutMs:i},(d,l)=>(c=l,this.consumeResponse(d,l,t,n)))}catch(d){if(c&&!c.aborted)throw d;let l=new Error(Tu(d)),u=Ny(d);throw u&&(l.code=u),l}}async consumeResponse(t,n,r,i){if(this.parseServerSignals(t),t.status===401)throw new Pc("Your device session has expired. Run `visa connect` to refresh it (the device is already enrolled).",t.status);if(t.status===429){let a=uq(t.headers.get("Retry-After"));throw new Iu(`Rate limited \u2014 wait ${a}s, then retry.`,a)}t.status===503&&await this.throwServerUnavailable(t,n);let o;try{o=await t.json()}catch{if(n.throwIfAborted(),t.status===500)throw new Pe(`Server error on ${i}. Try again or check https://visacli.sh for status.`,t.status);if(!t.ok){let a=t.status>=500||t.status===429||r==="GET"&&(t.status===408||t.status===425);throw new Pe(a?`Unexpected response from ${i}. Try again.`:`Unexpected response from ${i} (${t.status}).`,t.status,void 0,void 0,a)}throw new Error(`Unexpected response from ${i}.`)}if(!t.ok){if(t.status===426||o?.error==="update_required"||o?.error_code==="update_required"||o?.errorCode==="update_required"){let a=typeof o?.runningVersion=="string"?o.runningVersion:kc,s=typeof o?.minCompatibleVersion=="string"?o.minCompatibleVersion:Fg.DEFAULT_MIN_COMPATIBLE_CLI_VERSION;throw new cc(a,s,i)}if(t.status===500){let a=typeof o?.retryable=="boolean"?o.retryable:void 0;throw new Pe(a===!1?`Server error on ${i}. Inspect the server error and reconcile the existing attempt.`:`Server error on ${i}. Try again or check https://visacli.sh for status.`,t.status,typeof o?.error=="string"?o.error:void 0,typeof o?.reason=="string"?o.reason:void 0,a)}throw this.throwIfAttestationDrift(o),pq(t.status,o)}return o}async emitTelemetry(t){return this.request("POST","/v1/telemetry",{rows:t},lq)}async merchantDirectorySearch(t,n){let r=new URLSearchParams;return t.provider&&r.set("provider",t.provider),t.q&&r.set("q",t.q),t.protocol&&r.set("protocol",t.protocol),t.maxPriceUsd&&r.set("max_price_usd",t.maxPriceUsd),t.verify&&r.set("verify",t.verify),r.set("limit",String(t.limit)),r.set("offset",String(t.offset)),this.request("GET",`/v1/merchant-directory/search?${r.toString()}`,void 0,void 0,n)}async merchantDirectoryCertified(t){return this.request("GET","/v1/merchant-directory/certified",void 0,void 0,t)}async getAccountActivity(t,n,r){let i=new URLSearchParams;t!==void 0&&i.set("limit",String(t)),n!==void 0&&i.set("agentId",n),r!==void 0&&i.set("cursor",r);let o=i.size>0?`?${i.toString()}`:"",a=await this.request("GET",`/v4/account/activity${o}`);if(!a||!Array.isArray(a.activity))throw new Error("account activity service returned an invalid response");let s=typeof a.next_cursor=="string"&&a.next_cursor.length>0?a.next_cursor:null;return{activity:a.activity.map(_q),nextCursor:s}}async getAccountActivityReceipt(t){let n;try{n=await this.request("GET",`/v4/account/activity/${encodeURIComponent(t)}`)}catch(i){throw i instanceof Pe&&i.status===404?new ge(`account activity entry not found: ${t}`,"activity_entry_not_found"):i}let r=wq(n);if(!r)throw new Error("account receipt service returned an invalid or unsupported response");return r}async getStatus(t){return this.request("GET","/v1/status",void 0,void 0,t)}async listAccountAgents(t){try{let n=await this.readAccountAgents(t);return n.truncated?null:n.agents}catch{return null}}async readAccountAgents(t){let n=[],r=0,i=!0;for(;;){let o=new URLSearchParams;t&&o.set("agentId",t),r&&o.set("offset",String(r));try{let a=ST.parse(await this.request("GET",`/v4/account/agents${o.size?`?${o}`:""}`));if(n.push(...a.agents),!a.truncated){i=!1;break}if(!a.agents.length)break;r+=a.agents.length}catch(a){if(r===0)throw a;break}}return{truncated:i,agents:n.map(o=>({...o,executionReadiness:{shared:o.executionReadiness.shared.status,...o.executionReadiness.card?{card:o.executionReadiness.card.status}:{},...o.executionReadiness.wallet?{wallet:o.executionReadiness.wallet.status}:{}}}))}}async getFeatureFlags(){return this.request("GET","/v1/feature-flags")}async claimAgentForApp(t,n,r){return{claimed:(await this.request("POST","/v4/account/agent-apps",{agentId:t,harnessId:n,...r?{deviceName:r}:{}}))?.claimed===!0}}};var xT=x(jn());var Dy=new Set(["retired","revoked"]);async function OT(e){let{binding:t,signer:n,api:r,env:i}=e,o=en(t.agentId,i);if(o&&!o.revoked)return"connected";let a=oo({agentId:t.agentId,env:i});if(!a)return"pending";try{let s=await n.create({profile:"identity-tap-v1",associationId:t.associationId,agentId:t.agentId,rootJkt:t.rootJkt,purpose:"tap"}),c=Ta(t.agentId,i),d=async h=>eu(h,i),l=c&&c.runtimeKey.handle===s.handle?c:await my({api:r,native:n,key:s,agentId:t.agentId,associationId:t.associationId,expectedRootJkt:t.rootJkt,persist:d}),u=async()=>(l={...l,handoffId:(0,Cc.randomUUID)()},await d(l),await ir(r,n,l,"create"),"pending"),f;try{f=await Zl(r,n,l)}catch(h){if(h instanceof Pe&&h.code==="device_handoff_expired")return u();throw h}return f.status==="active"?(await yc({pending:l,view:f,native:n,rootPublicJwk:t.rootPublicJwk,rootKid:t.rootKid,env:i}),"connected"):Dy.has(f.status)?"stopped":f.status==="expired"||f.status==="cancelled"?u():"pending"}finally{a()}}async function NT(e){let{binding:t,native:n,api:r,env:i}=e,o=en(t.agentId,i);if(o&&!o.revoked)return"connected";let a=Ta(t.agentId,i);if(!a||a.runtimeKey.binding.profile!=="identity-tap-v1"||a.proposal.associationId!==t.associationId||a.proposal.rootJkt!==t.rootJkt)return"absent";let s=oo({agentId:t.agentId,env:i});if(!s)return"pending";try{let c=async()=>{let l={...a,handoffId:(0,Cc.randomUUID)()};return eu(l,i),await ir(r,n,l,"create"),"pending"},d;try{d=await Zl(r,n,a)}catch(l){if(l instanceof Pe&&l.code==="device_handoff_expired")return c();throw l}return d.status==="active"?(await yc({pending:a,view:d,native:n,rootPublicJwk:t.rootPublicJwk,rootKid:t.rootKid,env:i}),"connected"):Dy.has(d.status)?"stopped":d.status==="expired"||d.status==="cancelled"?c():"pending"}finally{s()}}function Eq(e){if(typeof e!="string"||e.split(".").length!==3)return null;try{let t=JSON.parse(Buffer.from(e.split(".")[1],"base64url").toString("utf8")).exp;return Number.isSafeInteger(t)?t:null}catch{return null}}function Rc(e,t,n=Math.floor(Date.now()/1e3)){let r;try{r=en(e,t)}catch{return"missing"}if(!r||r.revoked||r.runtimeKey.binding.profile!=="identity-tap-v1")return"missing";let i=[r.active.delegation,r.active.gateAuthorization].map(Eq);if(i.some(a=>a===null))return"missing";let o=Math.min(...i);return o<=n?"expired":(0,xT.renewalDue)({endSec:o,grantEndSec:null,nowSec:n})?"renew_due":"live"}async function vq(e){let{binding:t,native:n,api:r,env:i}=e,o;try{o=en(t.agentId,i)}catch{return!1}if(!o||o.revoked||o.runtimeKey.binding.profile!=="identity-tap-v1")return!1;let a=await ir(r,n,o,"read"),s=Number(o.active.challenge?.generation??0);return a.status!=="active"||!(Number(a.challenge?.generation??0)>s)?!1:(await yc({pending:o,view:a,native:n,rootPublicJwk:t.rootPublicJwk,rootKid:t.rootKid,env:i,collectedRenewal:!0}),R.info("identity_device_tap_renewal_collected",{agentId:t.agentId,generation:a.challenge?.generation}),!0)}async function My(e){let{binding:t,native:n,api:r,env:i}=e,o=Rc(t.agentId,i,e.nowSec);if(o==="live")return{state:"connected"};if(o!=="missing")return await vq({binding:t,native:n,api:r,env:i})?{state:"renewed"}:{state:"owner_renews"};let a=oo({agentId:t.agentId,env:i});if(!a){let s=Ta(t.agentId,i);return s?{state:"pending",pending:s}:{state:"connected"}}try{let s=Ta(t.agentId,i),c=async u=>eu(u,i),d=s&&s.runtimeKey.binding.profile==="identity-tap-v1"&&s.proposal.associationId===t.associationId&&s.proposal.rootJkt===t.rootJkt?s:null;if(!d){let u=await n.create({profile:"identity-tap-v1",associationId:t.associationId,agentId:t.agentId,rootJkt:t.rootJkt,purpose:"tap"});return d=await my({api:r,native:n,key:u,agentId:t.agentId,associationId:t.associationId,expectedRootJkt:t.rootJkt,persist:c}),R.info("identity_device_tap_key_proposed",{agentId:t.agentId}),{state:"pending",pending:d}}let l;try{l=await Zl(r,n,d)}catch(u){if(!(u instanceof Pe)||u.code!=="device_handoff_expired")throw u;return d={...d,handoffId:(0,Cc.randomUUID)()},await c(d),await ir(r,n,d,"create"),{state:"pending",pending:d}}return l.status==="active"?(await yc({pending:d,view:l,native:n,rootPublicJwk:t.rootPublicJwk,rootKid:t.rootKid,env:i}),R.info("identity_device_tap_connected",{agentId:t.agentId}),{state:"connected"}):Dy.has(l.status)?{state:"stopped"}:((l.status==="expired"||l.status==="cancelled")&&(d={...d,handoffId:(0,Cc.randomUUID)()},await c(d),await ir(r,n,d,"create")),{state:"pending",pending:d})}finally{a()}}function DT(e,t){try{let n=Ta(e,t);if(!n||n.runtimeKey.binding.profile!=="identity-tap-v1")return!1;let r;try{r=en(e,t)}catch{r=null}return n.handoffId!==r?.handoffId}catch{return!1}}var MT="5.0.0-rc.409",bq=["association","handoff","lease","tap-sign"],LT=262144,Aq=2e4;function ja(e={}){let t=(e.origin??Nn()).replace(/\/+$/,""),n=e.fetch;return{async identityDeviceRequest(r,i){if(!bq.includes(r))throw new Error("identity_device_action_invalid");let o=JSON.stringify(i);if(Buffer.byteLength(o)>LT)throw new Error("identity_device_request_too_large");let a=`${t}/v1/identity-device/${r}`,s={method:"POST",headers:{"Content-Type":"application/json","X-Visa-CLI-Version":MT,"X-Source":"cli",...Aa()},body:o},c;try{c=await(n??fetch)(a,{...s,signal:AbortSignal.timeout(Aq)})}catch(u){throw new Error(Tu(u))}let d;try{let u=Buffer.from(await c.arrayBuffer());if(u.byteLength>LT)throw new Error("response_too_large");d=JSON.parse(u.toString("utf8"))}catch{d=void 0}let l=Fl(c.status,d,MT);if(l)throw l;if(typeof d?.ok!="boolean")throw new Pe(`Identity device relay returned an invalid response for ${r} (${c.status}).`,c.status,"identity_device_response_invalid",void 0,!1);if(!c.ok||d.ok!==!0){let u=typeof d.code=="string"?d.code:void 0,f=typeof d.retryable=="boolean"?d.retryable:void 0;throw new Pe(`Identity device ${r} refused (${c.status}${u?` ${u}`:""}).`,c.status,u,void 0,f)}return d}}}var JT=require("node:crypto");var t$=30*1e3,Sq=new Map;function Iq(){Sq.clear()}function Tq(e){let t=oI(e.homeDir),n=t?.financialDeviceRuntimeId;if(!t||t.agentId!==e.agentId||!n)return null;let r=Yi(e.agentId,e.env);if(!r||r.runtimeKey.runtimeId!==n)return null;let i=Z0(t,e.env),o=i?In(i):e.api;return{runtimeId:n,active:r,api:o}}async function Pq(e,t,n){return await e.financialRuntimeRequest("tempo-context",{requestId:(0,JT.randomUUID)(),agentId:t,runtimeId:n})}function UT(e){let t=e?.code;return t==="agent_revoked"||t==="device_key_replaced"}async function Pu(e){let t;try{t=Tq(e)}catch{return"unknown"}if(!t)return"unknown";let n;try{n=await Pq(t.api,e.agentId,t.runtimeId)}catch(r){if(UT(r))throw r;return"unknown"}return n?.v!==1||typeof n.enrolled!="boolean"?"unknown":n.available===!1?"switched_off":(n.enrolled&&Iq(),n.enrolled?"enrolled":"setup_pending")}var Ly={begin:async(e,t,n)=>{let r=Jn(n),i=Fc(Date.now(),r);i&&i.verifier===t&&!i.likelyExpired||await Y_(e,Date.now(),r,{verifier:t})},claim:(e,t)=>Bc(e,{loginDir:Jn(t),attempts:1}),revert:async(e=process.env)=>{let t=it(e);if(t)try{await Ht.deleteProfileSessionToken(t,e)}finally{J_(t.profileId,e)}}};async function jT(e=process.env,t=p_){try{if(ry(e).length!==0)return null}catch{return null}let n=ze(on(e));try{let i=At(e);if(i&&Zr(i))return{baseUrl:n}}catch{}let r=await t(n);return r.ready&&r.features.includes(f_)?{baseUrl:n}:null}var qT={start:B0,claim:ny,readSetup:X0,bindApi:In,custody:ao,beginDevice:Gs,advanceDevice:Ml,connectDevice:lI,finishDevice:uI,beginCard:BI,advanceCard:wc,advanceTap:OT,identityDevice:ja,walletHomeForAgent:fc,walletStateRoot:Tn,claimApp:(e,t,n)=>new Ua(()=>Ht.getSessionToken()).claimAgentForApp(e,t,n),deviceName:()=>$l(),tempoKey:Pu,sleep:e=>new Promise(t=>setTimeout(t,e)),now:()=>Date.now(),signIn:Ly,announceCode:e=>G0(e),announcePickup:e=>Y0(e)},kq=new Set(["identity_authority_not_configured"]);function Jy(e){return e instanceof eo?!0:e instanceof tt?!(e.code!==null&&kq.has(e.code))&&(e.status>=500||e.status===429):zr(e)==="ProtectedAuthorityTransportError"}var Cq=12e4,Uy=12e4,Rq=3,jy=1e3,xq=15e3,qy=1800*1e3;function Oq(e){return Math.min(jy*2**Math.max(0,e-1),xq)}async function Nq(e,t,n){let r=t.app??ey(t.env);if(!r)return;let i=null;try{i=e.deviceName?e.deviceName():null}catch{i=null}try{let o=await e.claimApp(n,r,i);R.info("agent:protected_enrollment_app_stamped",{agentId:n,harnessId:r,claimed:o.claimed,deviceReported:i!==null})}catch(o){R.warn("agent:protected_enrollment_app_stamp_failed",{agentId:n,harnessId:r,error:o instanceof Error?o.message:"request refused"})}}async function Dq(e,t=qT){if(!Number.isSafeInteger(e.attempts)||e.attempts<1||e.attempts>900)throw new Error("Attempts must be between 1 and 900");let n=t.start({webOrigin:e.webOrigin,restart:e.restart,env:e.env,...e.webStartKey!==void 0?{webStartKey:e.webStartKey}:{},...e.signIn?{signIn:!0}:{},requestedLimits:e.requestedLimits??null});await H0(n,t.custody(e.env),e.env);let r=e.signIn&&Zr(n)?e.signIn:null,i=r?t.signIn??Ly:null;r&&i&&await i.begin(r.baseUrl,n.verifier,e.env),await t.announceCode?.(n),n.webStartKey&&await t.announcePickup?.(n);let o=z0(n,e.app??ey(e.env),{heldAgentId:e.heldAgentId,priorRuntimes:e.priorRuntimes,limits:n.requestedLimits??null});n.requestedLimits&&R.info("agent:protected_enrollment_requested_limits",{ceremonyId:n.ceremonyId,dailyCents:n.requestedLimits.dailyCents??null,perPurchaseCents:n.requestedLimits.perPurchaseCents??null}),!n.binding&&!n.webStartKey&&R.info("agent:protected_enrollment_prior_runtimes",{ceremonyId:n.ceremonyId,challenge:n.challenge.slice(0,8),heldAgent:!!e.heldAgentId,priorRuntimes:e.priorRuntimes?.length??0});let a=cn(n.verifier);n.binding||await e.announce({kind:"owner_enrollment",url:o,confirmCode:a});let s=null,c=0,d=null,l=t.now??(()=>Date.now()),u=l();for(let f=0;f<e.attempts;f++){if(l()-u>=qy){R.warn("agent:protected_enrollment_pickup_deadline",{attempt:f+1,waitedMs:l()-u});break}f>0&&await t.sleep(c>0?Oq(c):jy);try{if(r&&i&&Zr(n)){let h=await i.claim(r.baseUrl,e.env);if(h.status==="confirm_mismatch")throw new Error("The code entered in the browser does not match this terminal, so it was not signed in. Run `visa connect --restart` and enter the code this terminal shows.");if(h.status==="error")throw new eo("Visa sign-in","network",0);if(h.status!=="claimed"||!Zg(n,e.env))continue}try{s=await t.claim(n,e.env)}catch(h){if(n.signIn===!0&&h instanceof ge&&h.code==="enrollment_owner_mismatch")try{await(t.signIn??Ly).revert(e.env)}catch(p){R.warn("agent:protected_enrollment_sign_in_revert_failed",{reason:p instanceof Error?p.name:typeof p})}throw h}}catch(h){if(!Jy(h))throw h;c++,d=h,R.warn("agent:protected_enrollment_pickup_retry",{attempt:f+1,consecutiveFailures:c,status:h instanceof tt?h.status:null,reason:h instanceof eo?h.reason:null});continue}if(c=0,d=null,s)break}return s?{status:"identity_active",pending:n,binding:s,enrollmentUrl:o}:{status:"awaiting_owner_enrollment",browserUrl:o,confirmCode:a,...d?{lastPickupFailure:d instanceof Error?d.message:"Authority unavailable"}:{}}}async function KT(e,t=qT){if(e.perTransactionLimitCents>e.dailyLimitCents)throw new ge("Per-purchase limit exceeds daily limit","invalid_argument");if(!Number.isSafeInteger(e.attempts)||e.attempts<1||e.attempts>900)throw new ge("Attempts must be between 1 and 900","invalid_argument");let n=await Dq(e,t);if(n.status!=="identity_active")return n;let{pending:r,binding:i,enrollmentUrl:o}=n,a={v:1,authorityOrigin:r.authorityOrigin,executionOrigin:r.executionOrigin,transportProfileId:r.transportProfileId,binding:i},s=t.bindApi(a),c=qS(t.custody(e.env),r.deviceKeys),d={api:s,signer:c,selection:a,env:e.env,ceremony:{ceremonyId:i.ceremonyId,challenge:r.challenge,verifier:r.verifier}},l=t.identityDevice({origin:r.executionOrigin}),u="pending",f,h,p=!1,m=async()=>{if(!(u==="connected"||u==="stopped"||p))try{u=await t.advanceTap({binding:i,signer:c,api:l,env:e.env}),f=void 0,h=void 0}catch(ee){u="failed",p=!Jy(ee),f=ee instanceof Error?ee.message:"TAP connection refused",h=To(ee),R.warn("agent:protected_enrollment_tap_pending",{agentId:i.agentId,errorName:zr(ee),code:h.code,...ee instanceof tt?{status:ee.status}:{}})}},w=await t.beginCard({...d,initialConnection:!0});await m();let v=async()=>{try{return(await t.advanceCard(d)).status==="active"}catch(ee){if(!Jy(ee))throw ee;return R.warn("agent:protected_card_connection_pending",{agentId:i.agentId,errorName:zr(ee),...ee instanceof tt?{status:ee.status}:{}}),!1}},_=()=>t.walletHomeForAgent(i.agentId,t.walletStateRoot(e.env),i.ownerPublicId),A=async ee=>t.tempoKey?t.tempoKey({api:s,agentId:i.agentId,homeDir:ee,env:e.env}):"enrolled",j=async ee=>(ee!=="enrolled"&&R.warn("agent:protected_enrollment_wallet_key_owed",{agentId:i.agentId,walletKey:ee}),R.info("agent:protected_enrollment_connected",{agentId:i.agentId,tap:u,walletKey:ee,wait:e.wait}),await Nq(t,e,i.agentId),{status:"connected",agentId:i.agentId,tap:u,...u==="failed"&&f?{tapError:f}:{},...u==="failed"&&h?{tapDiagnostic:h}:{},walletKey:ee});if(!e.wait){let ee=await t.beginDevice({api:s,signer:c,agentId:i.agentId,ownerPublicId:i.ownerPublicId,cardProposal:w.proposal,ceremony:{ceremonyId:i.ceremonyId,challenge:r.challenge,verifier:r.verifier},env:e.env}),On=await t.advanceDevice({api:s,signer:c,pending:ee,env:e.env}),qt=ee.cardProposal?await v():!0;await m();let Yy=u==="failed"?{tap:u,tapError:f,tapDiagnostic:h}:{},Io=await t.readSetup(r);if(Io.state==="declined")throw new ge("The owner declined this setup","setup_declined");if(Io.state==="expired")throw new ge("This setup expired","enrollment_expired");if(Io.state==="superseded")throw new Error("setup_superseded");if(["approve","approve_device","set_limit"].includes(Io.nextAction))return{status:"awaiting_owner_device_approval",setupNextAction:Io.nextAction,browserUrl:o,agentId:i.agentId,...Yy};let zy=_();return qt&&await t.finishDevice({api:s,signer:c,agentId:i.agentId,ownerPublicId:i.ownerPublicId,agentName:"Protected agent",authUrl:r.authorityOrigin,walletHomeDir:zy,pending:ee,view:On,env:e.env})?j(await A(zy)):(R.info("agent:protected_enrollment_device_finishing",{agentId:i.agentId,active:On?.prepared?.status==="active",companionReady:qt}),{status:"finishing_device_setup",setupNextAction:Io.nextAction,browserUrl:o,agentId:i.agentId,...Yy})}let Q=_();await t.connectDevice({api:s,signer:c,agentId:i.agentId,ownerPublicId:i.ownerPublicId,cardProposal:w.proposal,advanceCompanion:v,advanceTap:async()=>{u==="failed"&&!p&&(u="pending"),await m()},ceremony:{ceremonyId:i.ceremonyId,challenge:r.challenge,verifier:r.verifier},agentName:"Protected agent",authUrl:r.authorityOrigin,walletHomeDir:Q,env:e.env});let X=t.now??(()=>Date.now()),H=X()+Cq,V=X()+Uy,Ee=await A(Q),Ge=()=>(u==="pending"||u==="failed")&&!p,jt=()=>Ee==="setup_pending"||Ee==="unknown";for(let ee=1;;ee++){let On=Ge()&&X()<H,qt=jt()&&X()<V;if(!On&&!qt)break;await t.sleep(jy),On&&(u==="failed"&&(u="pending"),await m()),qt&&ee%Rq===0&&(Ee=await A(Q))}return j(Ee)}var HT=require("node:path");function Mq(e,t){return en(e,t),(0,HT.join)(de(t),"financial-device-presence",`${e}.revocation.json`)}function ku(e,t){let n=Bt(Mq(e,t));if(n===null)return null;Le(n);let r=JSON.parse(n);if(r.v!==1||r.selected?.proposal.agentId!==e||!Array.isArray(r.keys)||!r.keys.length||!["awaiting_owner","revocation_verified","complete"].includes(r.phase)||r.keys.some(({record:o})=>o.proposal.agentId!==e||o.proposal.runtimeId!==r.selected.proposal.runtimeId||o.proposal.associationId!==r.selected.proposal.associationId))throw new Error("identity_device_revocation_invalid");if(en(e,t)?.handoffId!==r.selected.handoffId){if(r.phase==="complete")return null;throw new Error("identity_device_selection_changed")}return r}var So=require("node:fs"),qa=require("node:path"),FT=require("node:crypto");var $T=require("node:crypto");var VT=e=>e instanceof Error&&e.message?e.message:String(e);function xn(e,t){try{let n=ku(e,t);if(n&&n.phase!=="complete"&&gy(n.selected))return{state:"revoking"};let r=en(e,t);if(r?.revoked&&gy(r))return{state:"revoked"}}catch(n){return{state:"unreadable",detail:`presence: ${VT(n)}`}}try{let n=Yi(e,t);if(n)return{state:"installed",runtimeId:n.runtimeKey.runtimeId,record:n};let r=ga(e,t);if(r)return{state:"wallet_setup_pending",runtimeId:r.runtimeKey.runtimeId}}catch(n){return{state:"unreadable",detail:VT(n)}}return{state:"missing"}}function Lq(e){let t=e?.deviceWalletAuthority;return t==="live"||t==="expired"||t==="absent"?t:"unreachable"}function Jq(e){let t=e?.code;if(t==="agent_revoked")return"revoked";if(t==="device_key_replaced")return"replaced";let n=e?.status;return typeof n=="number"&&n>=400&&n<500&&n!==408&&n!==429?"refused":"unreachable"}async function WT(e,t=(r,i)=>In(e).financialRuntimeRequest(r,i),n){try{return Lq(await t("device-context",{requestId:(0,$T.randomUUID)(),agentId:e.binding.agentId,...n?{runtimeId:n}:{}}))}catch(r){if(Ky(r))throw r;return Jq(r)}}function Ky(e){return e instanceof Error&&/independently claimed owner/.test(e.message)}var Uq=["revoked","key_not_held","replaced","superseded"],Cu=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;function xc(e){let t=(0,qa.join)(de(e),"protected-enrollment","retired");return(0,So.mkdirSync)(t,{recursive:!0,mode:448}),Ye(t),t}function Hy(e,t,n,r=()=>new Date){if(!Cu.test(e))throw new Error("retired_agent_id_invalid");let i=(0,qa.join)(xc(n),`${e}.json`),o=BT(i);if(o)return o;let a={v:1,agentId:e,reason:t,retiredAt:r().toISOString()};return ke(i,JSON.stringify(a)),a}function BT(e){let t=Ue(e);if(t===null)return null;let n=JSON.parse(t);if(n?.v!==1||!Cu.test(n.agentId)||!Uq.includes(n.reason)||typeof n.retiredAt!="string")throw new Error("retired_agent_record_invalid");return n}function Vy(e){let t=new Map,n;try{n=(0,So.readdirSync)(xc(e))}catch{return t}for(let r of n)if(!(!r.endsWith(".json")||!Cu.test(r.slice(0,-5))))try{let i=BT((0,qa.join)(xc(e),r));i&&`${i.agentId}.json`===r&&t.set(i.agentId,i)}catch{}return t}function Ka(e){let t=Vy(e);return Qr(e).filter(n=>!t.has(n.binding.agentId))}async function GT(e,t){let n=e.binding.agentId,r=[],i=null,o=xn(n,t.env);o.state==="installed"&&(r.push(o.record.runtimeKey.handle),i=o.record.runtimeKey.runtimeId);try{let a=ti(e,t.env);a?.certificate&&r.push(a.runtimeKey.handle)}catch{}if(r.length>0&&(await Promise.all(r.map(s=>t.holds(s)))).every(s=>s==="missing")&&R.warn("agent:held_agent_keys_not_in_this_store",{agentId:n}),i)try{await t.api(e).financialRuntimeRequest("tempo-context",{requestId:(0,FT.randomUUID)(),agentId:n,runtimeId:i})}catch(a){if(a instanceof tt&&a.code==="agent_revoked")return{agentId:n,verdict:"retire",reason:"revoked"};if(a instanceof tt&&a.code==="device_key_replaced")return{agentId:n,verdict:"retire",reason:"replaced"}}if((t.resumable??Ru)(e,t.env))return{agentId:n,verdict:"usable"};try{if(await t.association?.(e)==="revoked")return{agentId:n,verdict:"retire",reason:"revoked"}}catch{}return{agentId:n,verdict:"usable"}}async function jq(e){let t=[],n,r;try{n=Vy(e.env),r=Qr(e.env)}catch{return t}for(let i of r){let o=i.binding.agentId;if(n.get(o)?.reason==="key_not_held")try{if((await GT(i,e)).verdict==="retire"){(0,So.rmSync)((0,qa.join)(xc(e.env),`${o}.json`),{force:!0}),Hy(o,"revoked",e.env);continue}(0,So.rmSync)((0,qa.join)(xc(e.env),`${o}.json`),{force:!0}),R.info("agent:held_agent_restored",{agentId:o}),t.push(o)}catch(a){R.warn("agent:held_agent_restore_failed",{agentId:o,error:a instanceof Error?a.message:String(a)})}}return t}async function YT(e){let t;try{t=Ka(e.env)}catch{return[]}await jq(e);try{t=Ka(e.env)}catch{return[]}let n=[];for(let r of t)try{let i=await GT(r,e);if(i.verdict!=="retire")continue;let o=Hy(i.agentId,i.reason,e.env);R.warn("agent:held_agent_retired",{agentId:o.agentId,reason:o.reason}),n.push(o)}catch(i){R.warn("agent:held_agent_judge_failed",{agentId:r.binding.agentId,error:i instanceof Error?i.message:String(i)})}return n}function $y(e){let t;try{t=Ka(e)}catch{return[]}let n=new Map(t.map(i=>{try{return[i.binding.agentId,Wy(i,e)]}catch{return[i.binding.agentId,null]}}));if(![...n.values()].includes("installed"))return[];let r=[];for(let i of t){let o=i.binding.agentId;if(n.get(o)!=="unfinished"||Ru(i,e))continue;let a=xn(o,e);if(a.state!=="wallet_setup_pending"&&a.state!=="missing"){a.state==="unreadable"&&R.warn("agent:held_agent_setup_unreadable",{agentId:o,detail:a.detail});continue}try{if(ti(i,e)?.certificate)continue}catch{R.warn("agent:held_agent_setup_unreadable",{agentId:o,detail:"card record"});continue}try{let s=Hy(o,"superseded",e);R.warn("agent:held_agent_retired",{agentId:o,reason:s.reason}),r.push(s)}catch(s){R.warn("agent:held_agent_retire_failed",{agentId:o,error:s instanceof Error?s.message:String(s)})}}return r}async function zT(e){try{return await ja({origin:e.executionOrigin}).identityDeviceRequest("association",{agentId:e.binding.agentId}),"active"}catch(t){return t instanceof Pe&&(t.code==="association_inactive"||t.code==="agent_revoked")?"revoked":"unknown"}}function Wy(e,t){if(xn(e.binding.agentId,t).state!=="installed")return"unfinished";try{let n=ti(e,t);if(n&&!n.certificate)return"unfinished"}catch{}return"installed"}function Ru(e,t){let n;try{n=At(t)}catch{return!1}return!!(n?.binding&&n.binding.agentId===e.binding.agentId&&n.binding.associationId===e.binding.associationId&&to(n))}async function XT(e,t,n){let r=[],i=xn(e.binding.agentId,n);i.state==="installed"&&r.push(i.record.runtimeKey.handle);try{let a=ti(e,n);a?.certificate&&r.push(a.runtimeKey.handle)}catch{}return r.length===0?"readable":(await Promise.all(r.map(a=>t(a).catch(()=>"unknown")))).every(a=>a==="missing")?"unreadable":"readable"}function qq(e,t,n){return e===null||n||e.state==="installed"||t?.certificate||e.state!=="wallet_setup_pending"&&e.state!=="missing"&&e.state!=="revoked"?!1:e.state==="wallet_setup_pending"||!!t}function ZT(e){let t,n;try{t=Qr(e),n=Vy(e)}catch{return[]}let r=new Set;for(let i of t){let o=i.binding.agentId,a=n.get(o)?.reason;if(a==="replaced"||a==="revoked")continue;let s=null;try{s=xn(o,e)}catch{}let c=null,d=!1;try{c=ti(i,e)}catch{d=!0}a===void 0&&!qq(s,c,d)||((s?.state==="installed"||s?.state==="wallet_setup_pending")&&r.add(s.runtimeId),c&&r.add(c.runtimeKey.runtimeId))}return[...r].filter(i=>Cu.test(i))}function QT(e,t,n){return(t?e?.find(r=>r.agentId===t):void 0)??(n?e?.find(r=>r.agentJkt===n||r.agentRootJkt===n):void 0)}var Kq=new Set(["registered","removal_pending","pending","blocked","not_requested","deactivated","contact_required","unavailable"]);function Hq(e){return typeof e=="string"&&Kq.has(e)?e:"unknown"}function Vq(e){let t=Hq(e?.tapStatus),n=typeof e?.tapBlockedReason=="string"?e.tapBlockedReason:"";return t==="pending"&&n?{directory:"blocked",blockedReason:n}:{directory:t}}function $q(e,t,n,r){return{key:Rc(e,n),...Vq(QT(t,e,r))}}async function eP(e,t,n,r){let i=null;try{i=await t()}catch{i=null}return $q(e,i,n,r)}function tP(e,t){let n=t??Qr().find(r=>r.binding.agentId===e)?.binding.rootJkt;return eP(e,()=>new Ua(()=>Ht.getSessionToken()).listAccountAgents(e),void 0,n)}async function Wq(e){try{if(await Ht.getSessionToken())return"already"}catch{}try{if(!Fc()||e===!0)return null;let n=ze(on()),r=await Bc(n,{attempts:1});return r.status==="confirm_mismatch"?r:r.status==="claimed"?"claimed":null}catch{return null}}var nP=e=>e==="setup_pending"?"finish_wallet_key":e==="switched_off"?"wallet_switched_off":e==="unknown"?"confirm_wallet_key":"none";async function Fq(e){try{return await Pu({api:In(e),agentId:e.binding.agentId,homeDir:fc(e.binding.agentId,Tn(),e.binding.ownerPublicId)})}catch{return"unknown"}}async function Bq(e){let t=e.binding,n=xn(t.agentId);if(n.state==="installed"){try{await WT(e)}catch(a){if(Ky(a))throw a}let o=n.record;if(o.ownerPublicId!==t.ownerPublicId||o.organizationId!==t.organizationId||o.proposal.associationId!==t.associationId||o.proposal.associationVersion!==t.associationVersion||o.proposal.rootJkt!==t.rootJkt||o.rootKid!==t.rootKid)throw new Error("Protected wallet installation differs from its independently claimed owner");return}let r;try{r=ga(t.agentId)}catch{return}if(!r)return;let i=At();if(i?.binding?.agentId!==t.agentId||i.binding.ceremonyId!==t.ceremonyId||i.executionOrigin!==e.executionOrigin||i.authorityOrigin!==e.authorityOrigin||!to(i)||r.ceremony.ceremonyId!==i.ceremonyId||r.ceremony.challenge!==i.challenge||r.ceremony.verifier!==i.verifier||r.proposal.associationId!==t.associationId||r.proposal.associationVersion!==t.associationVersion||r.proposal.rootJkt!==t.rootJkt)throw new Error("Existing wallet setup cannot resume this identity; call get_status before restarting enrollment")}async function Gq(e,t,n){let r=e.binding.agentId,i=xn(r).state,o=i==="revoking"||i==="revoked";try{let s=ku(r);o||=!!(s&&s.phase!=="complete")}catch{}if(o)return{state:"revoking"};let a={binding:e.binding,native:ao(),api:ja({origin:e.executionOrigin})};try{let s=await NT(a);if(s==="stopped")return{state:"stopped"};let c=s==="pending";if(!c)try{c=DT(r)||Rc(r)!=="live"}catch{c=!0}if(!c)return{state:"live"};let d=Date.now()+Math.max(1,n)*1e3,l=await My(a);for(;l.state==="pending"&&t&&Date.now()<d;)await new Promise(u=>setTimeout(u,1e3)),l=await My(a);return l.state!=="pending"?{state:l.state}:{state:"awaiting_owner",url:NI(u_(on()),l.pending),fingerprint:l.pending.proposal.runtimeJkt}}catch(s){return{state:"failed",error:s}}}async function Yq(e,t,n){let r=await wy(e);if(!t||!r.renew)return{card:{state:"untouched"},cardKey:r.state};try{let i={api:In(e),signer:ao(),selection:e,renewWithinSeconds:ou},o=await wc(i);return o.status==="retry"&&(o=await wc(i)),o.status==="active"?{card:{state:"renewed"},cardKey:(await wy(e)).state}:o.status==="awaiting_owner"?{card:{state:"awaiting_owner",url:WI(on({...process.env,VISA_AUTH_URL:e.authorityOrigin}),{proposal:o.proposal},n)},cardKey:"renewing"}:{card:{state:"busy"},cardKey:"renewing"}}catch(i){return{card:{state:"failed",error:i},cardKey:r.state}}}function zq(e){if(e!==void 0&&!K0.test(e))throw new ge("That setup key is not one Visa issued. Copy the whole `visa connect --setup` line from the page that started the setup.","invalid_argument")}async function rP(e){zq(e.webStartKey);let t=[],n=[],r=await Wq(e.restart),i=typeof r=="object"?r:null,o=typeof r=="string"?r:null;o==="already"&&e.verifySession&&await e.verifySession()===!1&&(o=null);let a=o||i?null:await jT();if(a&&(o="one_code"),!o){let m=await e.signIn(i);if(!m.done)return{leg:"signin",pending:m.pending,signIn:"pending",retired:t,superseded:n,nextAction:"sign_in"};o="interactive"}o!=="one_code"&&e.restart!==!0&&await W0({webOrigin:on(),webStartKey:e.webStartKey,requestedLimits:e.requestedLimits??null});let s={signIn:o,retired:t,superseded:n},c=null,d=null;if(!e.restart){t.push(...await YT({holds:async w=>ao().holds(w),api:w=>In(w),association:zT}),...$y());let m=e.webStartKey===void 0?Ka()[0]:void 0;if(m){let w=m.binding.agentId;await Bq(m);let v=Wy(m)==="unfinished";if(v&&Ru(m))c=w;else if(F0(on()))d={heldAgentId:w};else{if(v)return{...s,leg:"unfinished_expired",agentId:w,nextAction:"restart_to_replace"};if(await XT(m,async _=>ao().holds(_))==="unreadable")return{...s,leg:"unreadable_keys",agentId:w,nextAction:"restart_new_agent"};{let _=await Gq(m,e.tapWait,e.tapAttempts??e.attempts),A=_.state==="awaiting_owner"?null:await Fq(m),j;try{j=xn(w).state!=="missing"}catch{j=!0}let Q=nP(A),X=Q!=="none"&&(j||Q!=="confirm_wallet_key"),H=_.state==="awaiting_owner"?"approve_device":_.state==="failed"?To(_.error).code==="update_required"?"update_cli":"retry_tap":X?Q:_.state==="owner_renews"?"owner_renews_tap":"none",{card:V,cardKey:Ee}=await Yq(m,H==="none",e.app),Ge=H!=="none"?H:V.state==="awaiting_owner"?"approve_card":V.state==="failed"||V.state==="busy"?"retry_card":Q;return{...s,leg:"held",agentId:w,tap:_,walletKey:A,tapStatus:await tP(w,m.binding.rootJkt),card:V,cardKey:Ee,nextAction:Ge}}}}}let l=null,u;try{u=e.webStartKey===void 0?Ka()[0]?.binding.agentId:void 0}catch{u=void 0}let f=await KT({webOrigin:on(),...u!==void 0?{heldAgentId:u}:{},...a?{signIn:a}:{},...e.app!==void 0?{app:e.app}:{},restart:e.restart,...e.webStartKey!==void 0?{webStartKey:e.webStartKey}:{},...e.webStartKey===void 0&&c===null?{priorRuntimes:ZT()}:{},wait:e.wait,attempts:e.attempts,dailyLimitCents:e.dailyLimitCents,perTransactionLimitCents:e.perTransactionLimitCents,requestedLimits:e.requestedLimits??null,announce:async m=>{l=m,await e.announce?.(m,a!==null)}});f.status!=="awaiting_owner_enrollment"&&n.push(...$y());let h=f.status==="awaiting_owner_enrollment"?"approve":f.status==="awaiting_owner_device_approval"?f.setupNextAction==="set_limit"?"set_limit":"approve_device":f.status==="finishing_device_setup"?"finish_device":nP(f.walletKey),p=f.status==="awaiting_owner_enrollment"?null:await tP(f.agentId);return{...s,leg:"enroll",resumed:c,result:f,announcement:l,tapStatus:p,restartPickup:d,nextAction:h}}var Xq=1e3,Zq=900,sP=qy+Uy+6e4;var wW=60*6e4,cP=sP+6e4;function Fy(e){return"enr_"+(0,Ou.createHash)("sha256").update(e).digest("base64url").slice(0,16)}function dP(e){let t=(0,Ha.join)(de(e),"protected-enrollment");return(0,Ne.mkdirSync)(t,{recursive:!0,mode:448}),Ye(t),t}var lP=e=>(0,Ha.join)(dP(e),"finisher.json"),uP=e=>(0,Ha.join)(dP(e),"finisher.lock");function Qq(e){let t=Ue(lP(e));if(t===null)return null;let n=JSON.parse(t);if(n?.v!==1||typeof n.ref!="string"||!["finishing","connected","failed","expired","stopped"].includes(n.state)||!Number.isFinite(n.startedAt)||!Number.isFinite(n.updatedAt))throw new Error("Enrollment finisher record is malformed");return n}function eK(e,t){ke(lP(t),JSON.stringify(e))}function iP(e,t,n,r,i={}){let o=null;try{o=Qq(r)}catch{o=null}if(i.keepOtherRef&&o&&o.ref!==e)return null;let s={...o&&o.ref===e?o:{v:1,ref:e,state:"finishing",startedAt:n,updatedAt:n,pid:null},...t,v:1,ref:e,updatedAt:n};return eK(s,r),s}function tK(e){if(!Number.isSafeInteger(e)||e<=0)return!1;try{return process.kill(e,0),!0}catch(t){return t?.code==="EPERM"}}function oP(e){try{let t=JSON.parse((0,Ne.readFileSync)(uP(e),"utf8"));return t.version===1&&Number.isSafeInteger(t.pid)&&typeof t.token=="string"&&Number.isFinite(t.createdAt)&&(t.pidStart===void 0||t.pidStart===null||typeof t.pidStart=="string")&&(t.holder===void 0||t.holder==="finisher"||t.holder==="connect")?t:null}catch{return null}}function nK(e){if(process.platform==="win32"||!Number.isSafeInteger(e)||e<=0)return null;try{return(0,xu.execFileSync)("ps",["-o","lstart=","-p",String(e)],{encoding:"utf8",stdio:["ignore","pipe","ignore"],timeout:2e3}).trim()||null}catch{return null}}function rK(e,t){if(!tK(e.pid))return!1;let n=null;try{n=By.processStart(e.pid)}catch{n=null}return e.pidStart&&n?n===e.pidStart:t-e.createdAt<cP}function iK(e,t=Date.now(),n=process.pid,r="finisher"){let i=uP(e),o=null;try{o=By.processStart(n)}catch{o=null}for(let a=0;a<2;a++){let s=(0,Ou.randomUUID)();try{let c=(0,Ne.openSync)(i,"wx",384);try{(0,Ne.writeFileSync)(c,JSON.stringify({version:1,pid:n,token:s,createdAt:t,pidStart:o,holder:r}),"utf8"),(0,Ne.fsyncSync)(c)}finally{(0,Ne.closeSync)(c)}let d=()=>oP(e)?.token===s;return Object.assign(()=>{if(d())try{(0,Ne.unlinkSync)(i)}catch{}},{held:d})}catch(c){if(c?.code!=="EEXIST")throw c;let d=oP(e),l;if(d)l=!rK(d,t);else try{l=t-(0,Ne.statSync)(i).mtimeMs>=cP}catch{l=!0}if(!l)return null;try{(0,Ne.unlinkSync)(i)}catch(u){if(u?.code!=="ENOENT")throw u}}}return null}function oK(e=__dirname){for(let t of[(0,Ha.join)(e,"enrollment-finisher.js"),(0,Ha.join)(e,"..","enrollment-finisher.js")])if((0,Ne.existsSync)(t))return t;return null}var aK=(e,t)=>{if(t.JEST_WORKER_ID!==void 0||t.VITEST!==void 0||t.NODE_ENV==="test")return{spawned:!1,reason:"test_runner"};let n=oK();if(!n)return{spawned:!1,reason:"finisher_entry_missing"};let r=(0,xu.spawn)(process.execPath,[n,...e],{detached:!0,stdio:"ignore",env:t,windowsHide:!0});return r.on("error",i=>R.warn("agent:enrollment_finisher_spawn_failed",{errorName:i.name})),r.unref(),{spawned:!0}},By={spawn:aK,sleep:e=>new Promise(t=>setTimeout(t,e)),now:()=>Date.now(),processStart:nK};var sK={setup:rP,readPending:At,now:()=>By.now(),pid:process.pid,deadlineMs:sP,approvalFinished:Ia},aP=e=>e instanceof Error?e.message:String(e);function cK(e,t){let n=t.after&&Fy(t.after.challenge)===t.ref;if(e.leg==="held"){let i=t.after;return n&&i!==null&&i.binding?.agentId===e.agentId&&t.approvalFinished(i)?{state:"connected",leg:"held",agentId:e.agentId,nextAction:e.nextAction,...e.walletKey?{walletKey:e.walletKey}:{},tap:e.tap.state,...e.tap.state==="awaiting_owner"?{tapUrl:e.tap.url,tapFingerprint:e.tap.fingerprint}:{},...e.tap.state==="failed"?{tapError:aP(e.tap.error)}:{},card:e.card.state,...e.card.state==="awaiting_owner"?{cardUrl:e.card.url}:{},...e.card.state==="failed"?{cardError:aP(e.card.error)}:{}}:{state:"failed",code:"setup_not_picked_up",reason:`This computer answered with agent ${e.agentId}, which it already held, instead of picking up this setup's approval.`}}if(e.leg==="signin")return{state:"failed",code:"session_required",reason:"This computer is signed out."};if(e.leg==="unfinished_expired"||e.leg==="unreadable_keys")return{state:"failed",agentId:e.agentId,code:e.leg,reason:e.nextAction};let r=e.result;if(r.status==="connected"){let i=t.after?.binding?.agentId;return!n||i!==void 0&&i!==r.agentId?{state:"stopped",reason:"The setup request changed."}:{state:"connected",leg:"enroll",agentId:r.agentId,walletKey:r.walletKey,tap:r.tap,...r.tapError?{tapError:r.tapError}:{},nextAction:e.nextAction}}return r.status==="awaiting_owner_enrollment"?{state:"expired",reason:r.lastPickupFailure?`Visa was unavailable while waiting (${r.lastPickupFailure}).`:"The owner did not approve within the setup window."}:{state:"expired",agentId:r.agentId,reason:r.status}}async function fP(e,t=sK){let n=e.env??process.env,r=iK(n,t.now(),t.pid);if(!r)return R.info("agent:enrollment_finisher_already_running",{ref:e.ref}),"already_running";let i=t.now(),o,a;try{let d=null;try{d=t.readPending(n)}catch{d=null}if(!d||Fy(d.challenge)!==e.ref)o={state:"stopped",reason:"The setup request changed."};else if(t.now()-d.createdAt>=Qg&&!d.binding)o={state:"expired",reason:"The setup request expired before it was approved."};else{iP(e.ref,{state:"finishing",pid:t.pid},t.now(),n,{keepOtherRef:!0}),R.info("agent:enrollment_finisher_start",{ref:e.ref,pid:t.pid,phase:d.binding?"device":"owner_approval"});let l=new Promise(p=>{a=setTimeout(()=>p({state:"expired",reason:"The background setup reached its time limit."}),t.deadlineMs),a.unref?.()}),u=d.webStartKey,f=t.approvalFinished??Ia,h=t.setup({...u!==void 0?{webStartKey:u}:{},wait:!0,attempts:Zq,tapWait:!1,dailyLimitCents:e.dailyLimitCents,perTransactionLimitCents:e.perTransactionLimitCents,...e.app!==void 0?{app:e.app}:{},signIn:async()=>({done:!1,pending:null})}).then(p=>{let m;try{m=t.readPending(n)}catch{m=null}return cK(p,{ref:e.ref,after:m,approvalFinished:w=>f(w,n)})});o=await Promise.race([h,l])}}catch(d){o={state:"failed",code:To(d).code,reason:d instanceof Error?d.message:String(d)}}finally{a&&clearTimeout(a)}let s=!r.held();try{s||iP(e.ref,{...o,pid:t.pid},t.now(),n,{keepOtherRef:!0})}finally{r()}return s&&R.info("agent:enrollment_finisher_superseded_exit",{ref:e.ref,outcome:o.state}),(o.state==="connected"?R.info:R.warn)("agent:enrollment_finisher_exit",{ref:e.ref,outcome:o.state,...o.agentId?{agentId:o.agentId}:{},...o.code?{code:o.code}:{},...o.walletKey?{walletKey:o.walletKey}:{},...o.nextAction?{nextAction:o.nextAction}:{},...o.leg?{leg:o.leg}:{},durationMs:t.now()-i}),o.state}function dK(e,t,n=At,r=Xq){let i=!1,o=()=>{if(!i)try{let s=n(t);s&&s.binding&&Fy(s.challenge)===e&&(i=!0)}catch{}};o();let a=setInterval(o,r);return a.unref?.(),{safeToExit:()=>(o(),!i),dispose:()=>clearInterval(a)}}function pP(e){let t=dK(e.ref,e.env,e.readPending),n=e.on??((i,o)=>process.on(i,o)),r=!1;return n("SIGTERM",()=>{r||(r=!0,t.safeToExit()?(R.info("agent:enrollment_finisher_signal_exit",{ref:e.ref}),e.exit(143)):R.info("agent:enrollment_finisher_signal_deferred",{ref:e.ref,reason:"device_legs"}))}),{stopRequested:()=>r,dispose:t.dispose}}function hP(e){let t=a=>{let s=e.indexOf(a);return s>=0?e[s+1]:void 0},n=t("--ref"),r=Number(t("--daily-cents")),i=Number(t("--per-transaction-cents"));if(!n||!/^enr_[A-Za-z0-9_-]{16}$/.test(n))throw new Error("finisher_ref_invalid");if(!Number.isSafeInteger(r)||r<=0||!Number.isSafeInteger(i)||i<=0)throw new Error("finisher_limits_invalid");let o=t("--app");return{ref:n,dailyLimitCents:r,perTransactionLimitCents:i,app:o??null}}function Gy(e){Qy().finally(()=>process.exit(e))}async function lK(){let e;try{e=hP(process.argv.slice(2))}catch(n){return R.warn("agent:enrollment_finisher_bad_args",{reason:n instanceof Error?n.message:"invalid"}),2}let t=pP({ref:e.ref,exit:Gy});try{let n=await fP(e);return t.stopRequested()?143:n==="connected"||n==="already_running"?0:1}finally{t.dispose()}}lK().then(Gy,e=>{R.error("agent:enrollment_finisher_crashed",{errorName:e instanceof Error?e.name:typeof e}),Gy(1)});
|
|
33
|
+
/*! Bundled license information:
|
|
34
|
+
|
|
35
|
+
@noble/ed25519/index.js:
|
|
36
|
+
(*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) *)
|
|
37
|
+
*/
|