@visa/cli 4.1.0-rc.50 → 4.1.0-rc.51
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/dist/cli.js
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
1
|
"use strict";var p6t=Object.create;var uj=Object.defineProperty;var f6t=Object.getOwnPropertyDescriptor;var m6t=Object.getOwnPropertyNames;var h6t=Object.getPrototypeOf,y6t=Object.prototype.hasOwnProperty;var k=(e,t,r)=>()=>{if(r)throw r[0];try{return e&&(t=e(e=0)),t}catch(n){throw r=[n],n}};var g=(e,t)=>()=>{try{return t||e((t={exports:{}}).exports,t),t.exports}catch(r){throw t=0,r}},Pi=(e,t)=>{for(var r in t)uj(e,r,{get:t[r],enumerable:!0})},H9e=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of m6t(t))!y6t.call(e,i)&&i!==r&&uj(e,i,{get:()=>t[i],enumerable:!(n=f6t(t,i))||n.enumerable});return e};var _e=(e,t,r)=>(r=e!=null?p6t(h6t(e)):{},H9e(t||!e||!e.__esModule?uj(r,"default",{value:e,enumerable:!0}):r,e)),ie=e=>H9e(uj({},"__esModule",{value:!0}),e);var v0,pee=k(()=>{"use strict";v0="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1"});function fee(e){return`${e}-${K9e.randomBytes(24).toString("base64url")}`}function G9e(e=process.env){return e.NODE_ENV==="test"||e[W9e]==="true"}function ty(e=process.env){return e.VISA_MOCK_KEYCHAIN==="true"&&G9e(e)}function IT(e=process.env){return e.VISA_MOCK_TOUCHID==="true"&&G9e(e)}function mee(){return`Set ${W9e}=true only for local debugging; it enables insecure mock credential hooks outside NODE_ENV=test.`}function J9e(){return $9e??=fee("mock-session"),$9e}function Y9e(e=process.env){return e.NODE_ENV==="test"?v0:(F9e??=fee("mock-rc"),F9e)}function Z9e(){return V9e??=fee("mock-signature"),V9e}var K9e,W9e,$9e,F9e,V9e,dj=k(()=>{"use strict";K9e=_e(require("crypto"));pee();W9e="VISA_ALLOW_INSECURE_MOCKS"});function b6t(e){let t=e;return[t?.message,t?.stderr].filter(r=>typeof r=="string").join(`
|
|
2
|
-
`)}function vee(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let r=b6t(e).toLowerCase();return r.includes("operation not permitted")||r.includes("permission denied")}function sf(){return process.platform!=="darwin"?Promise.resolve(!1):(X9e??=(async()=>{try{return await jl("security",["default-keychain","-d","user"],{timeout:5e3}),!0}catch(e){return vee(e)}})(),X9e)}async function _6t(){if(!await sf())return null;try{let{stdout:e}=await jl("security",["find-generic-password","-s",ld,"-a",ry,"-w"],{timeout:5e3});return e.trim()||null}catch(e){if(vee(e))throw new pj("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 v6t(e){if(!await sf())return!1;try{try{await jl("security",["delete-generic-password","-s",ld,"-a",ry],{timeout:5e3})}catch{}return await jl("security",["add-generic-password","-s",ld,"-a",ry,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function w6t(){if(await sf())try{await jl("security",["delete-generic-password","-s",ld,"-a",ry],{timeout:5e3})}catch{}}async function E6t(){if(!wee())return null;try{let{stdout:e}=await jl("secret-tool",["lookup","service",ld,"account",ry],{timeout:5e3});return e.trim()||null}catch{return null}}async function A6t(e){if(!wee())return!1;try{let t=(0,fj.execFile)("secret-tool",["store","--label",`${ld} ${ry}`,"service",ld,"account",ry]);return t.stdin?(t.stdin.write(e),t.stdin.end(),await Promise.race([new Promise((r,n)=>{t.on("exit",i=>i===0?r():n(new Error(`secret-tool exited ${i}`))),t.on("error",n)}),new Promise((r,n)=>setTimeout(()=>{t.kill(),n(new Error("secret-tool timed out"))},g6t))]),!0):!1}catch{return!1}}async function x6t(){if(wee())try{await jl("secret-tool",["clear","service",ld,"account",ry],{timeout:5e3})}catch{}}function wee(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function S6t(){if(!await sf())return null;try{let{stdout:e}=await jl("security",["find-generic-password","-s",ld,"-a",lj,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function T6t(e){if(await sf())try{try{await jl("security",["delete-generic-password","-s",ld,"-a",lj],{timeout:5e3})}catch{}await jl("security",["add-generic-password","-s",ld,"-a",lj,"-w",e],{timeout:5e3})}catch{}}async function I6t(){if(await sf())try{await jl("security",["delete-generic-password","-s",ld,"-a",lj],{timeout:5e3})}catch{}}function yee(){try{return ny.readFileSync(PT,"utf-8").trim()||null}catch(e){if(vee(e))throw new pj(`Unable to read Visa CLI credentials from ${PT}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function eSe(e){ny.mkdirSync(_ee,{recursive:!0,mode:448}),ny.writeFileSync(PT,e,{mode:384}),process.platform==="win32"&&P6t(PT)}function gee(){try{ny.unlinkSync(PT)}catch{}}function P6t(e){try{let t=mj.userInfo().username;(0,fj.execFile)("icacls",[e,"/inheritance:r","/grant:r",`${t}:F`],{timeout:5e3},r=>{r&&console.error(`[visa-cli] icacls ACL restriction failed: ${r.message}`)})}catch(t){console.error(`[visa-cli] Failed to invoke icacls: ${t instanceof Error?t.message:String(t)}`)}}function hee(){switch(process.platform){case"darwin":return{get:_6t,store:v6t,delete:w6t};case"linux":return{get:E6t,store:A6t,delete:x6t};default:return{get:async()=>yee(),store:async e=>{try{return eSe(e),!0}catch{return!1}},delete:async()=>gee(),storesInSessionFile:!0}}}var fj,Q9e,ny,mj,bee,jl,_ee,PT,ld,ry,lj,g6t,pj,X9e,An,w0=k(()=>{"use strict";fj=require("child_process"),Q9e=require("util"),ny=_e(require("fs")),mj=_e(require("os")),bee=_e(require("path"));dj();jl=(0,Q9e.promisify)(fj.execFile),_ee=bee.join(mj.homedir(),".visa-mcp"),PT=bee.join(_ee,"session-token"),ld="visa-cli",ry="session-token",lj="rc-access",g6t=5e3,pj=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};X9e=null;An=class{static async getSessionToken(){if(ty())return Promise.resolve(J9e());let t=hee(),r=await t.get();if(r)return r;let n=yee();return n?(await t.store(n),n):null}static async saveSessionToken(t){if(ty())return;let r=hee();if(await r.store(t)){if(await r.get()===t){r.storesInSessionFile||gee();return}await r.delete()}if(eSe(t),yee()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${_ee} is writable.`))}static async getRcAccessToken(){return ty()?Y9e():S6t()}static async saveRcAccessToken(t){ty()||await T6t(t)}static async deleteSessionToken(){if(ty())return;await hee().delete(),gee()}static async clearAll(){await this.deleteSessionToken(),await I6t()}}});var hj=g((JBr,C6t)=>{C6t.exports={name:"@visa/cli",version:"4.1.0-rc.
|
|
2
|
+
`)}function vee(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let r=b6t(e).toLowerCase();return r.includes("operation not permitted")||r.includes("permission denied")}function sf(){return process.platform!=="darwin"?Promise.resolve(!1):(X9e??=(async()=>{try{return await jl("security",["default-keychain","-d","user"],{timeout:5e3}),!0}catch(e){return vee(e)}})(),X9e)}async function _6t(){if(!await sf())return null;try{let{stdout:e}=await jl("security",["find-generic-password","-s",ld,"-a",ry,"-w"],{timeout:5e3});return e.trim()||null}catch(e){if(vee(e))throw new pj("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 v6t(e){if(!await sf())return!1;try{try{await jl("security",["delete-generic-password","-s",ld,"-a",ry],{timeout:5e3})}catch{}return await jl("security",["add-generic-password","-s",ld,"-a",ry,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function w6t(){if(await sf())try{await jl("security",["delete-generic-password","-s",ld,"-a",ry],{timeout:5e3})}catch{}}async function E6t(){if(!wee())return null;try{let{stdout:e}=await jl("secret-tool",["lookup","service",ld,"account",ry],{timeout:5e3});return e.trim()||null}catch{return null}}async function A6t(e){if(!wee())return!1;try{let t=(0,fj.execFile)("secret-tool",["store","--label",`${ld} ${ry}`,"service",ld,"account",ry]);return t.stdin?(t.stdin.write(e),t.stdin.end(),await Promise.race([new Promise((r,n)=>{t.on("exit",i=>i===0?r():n(new Error(`secret-tool exited ${i}`))),t.on("error",n)}),new Promise((r,n)=>setTimeout(()=>{t.kill(),n(new Error("secret-tool timed out"))},g6t))]),!0):!1}catch{return!1}}async function x6t(){if(wee())try{await jl("secret-tool",["clear","service",ld,"account",ry],{timeout:5e3})}catch{}}function wee(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function S6t(){if(!await sf())return null;try{let{stdout:e}=await jl("security",["find-generic-password","-s",ld,"-a",lj,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function T6t(e){if(await sf())try{try{await jl("security",["delete-generic-password","-s",ld,"-a",lj],{timeout:5e3})}catch{}await jl("security",["add-generic-password","-s",ld,"-a",lj,"-w",e],{timeout:5e3})}catch{}}async function I6t(){if(await sf())try{await jl("security",["delete-generic-password","-s",ld,"-a",lj],{timeout:5e3})}catch{}}function yee(){try{return ny.readFileSync(PT,"utf-8").trim()||null}catch(e){if(vee(e))throw new pj(`Unable to read Visa CLI credentials from ${PT}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function eSe(e){ny.mkdirSync(_ee,{recursive:!0,mode:448}),ny.writeFileSync(PT,e,{mode:384}),process.platform==="win32"&&P6t(PT)}function gee(){try{ny.unlinkSync(PT)}catch{}}function P6t(e){try{let t=mj.userInfo().username;(0,fj.execFile)("icacls",[e,"/inheritance:r","/grant:r",`${t}:F`],{timeout:5e3},r=>{r&&console.error(`[visa-cli] icacls ACL restriction failed: ${r.message}`)})}catch(t){console.error(`[visa-cli] Failed to invoke icacls: ${t instanceof Error?t.message:String(t)}`)}}function hee(){switch(process.platform){case"darwin":return{get:_6t,store:v6t,delete:w6t};case"linux":return{get:E6t,store:A6t,delete:x6t};default:return{get:async()=>yee(),store:async e=>{try{return eSe(e),!0}catch{return!1}},delete:async()=>gee(),storesInSessionFile:!0}}}var fj,Q9e,ny,mj,bee,jl,_ee,PT,ld,ry,lj,g6t,pj,X9e,An,w0=k(()=>{"use strict";fj=require("child_process"),Q9e=require("util"),ny=_e(require("fs")),mj=_e(require("os")),bee=_e(require("path"));dj();jl=(0,Q9e.promisify)(fj.execFile),_ee=bee.join(mj.homedir(),".visa-mcp"),PT=bee.join(_ee,"session-token"),ld="visa-cli",ry="session-token",lj="rc-access",g6t=5e3,pj=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};X9e=null;An=class{static async getSessionToken(){if(ty())return Promise.resolve(J9e());let t=hee(),r=await t.get();if(r)return r;let n=yee();return n?(await t.store(n),n):null}static async saveSessionToken(t){if(ty())return;let r=hee();if(await r.store(t)){if(await r.get()===t){r.storesInSessionFile||gee();return}await r.delete()}if(eSe(t),yee()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${_ee} is writable.`))}static async getRcAccessToken(){return ty()?Y9e():S6t()}static async saveRcAccessToken(t){ty()||await T6t(t)}static async deleteSessionToken(){if(ty())return;await hee().delete(),gee()}static async clearAll(){await this.deleteSessionToken(),await I6t()}}});var hj=g((JBr,C6t)=>{C6t.exports={name:"@visa/cli",version:"4.1.0-rc.51",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"},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 && pnpm --filter @visa/money build && pnpm --filter @visa/crypto build && pnpm --filter subway-sdk build && pnpm --filter @visa-cli/tools build && pnpm --filter @visa/identity build && pnpm --filter @visa/wallet build && pnpm --filter @visa/agent-mail build && pnpm --filter @visa/wallet-tools build && pnpm --filter @visa/checkout-engine build",build:"tsc --noEmit && 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:unit":"jest --config jest.config.js","test:unit:watch":"jest --config jest.config.js --watch","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:integration":"jest --config jest.integration.config.js","test:e2e":"jest --config jest.e2e.config.js","test:all":"npm run test:unit && npm run test:integration && 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/sdk":"^1.0.0","@ucp-js/sdk":"0.4.1",commander:"^12.1.0",zod:"^3.23.0"},optionalDependencies:{libp2p:"^3.3.4","@libp2p/tcp":"^11.0.22","@libp2p/crypto":"^5.1.20","@chainsafe/libp2p-noise":"^17.0.0","@chainsafe/libp2p-yamux":"^8.0.1","@multiformats/multiaddr":"^13.0.3",uint8arrays:"^6.1.1","playwright-core":"^1.48.2"},devDependencies:{"@visa/checkout-engine":"workspace:*","@visa/crypto":"workspace:*","@visa/identity":"workspace:*","subway-sdk":"workspace:*","@visa/money":"workspace:*","@visa/wallet":"workspace:*","@visa/wallet-tools":"workspace:*","@visa/observability":"workspace:*","@visa-cli/tools":"workspace:*","@changesets/changelog-git":"^0.2.1","@changesets/cli":"^2.31.0","@types/jest":"^30.0.0","@types/node":"^26.1.0","@typescript-eslint/eslint-plugin":"^8.65.0","@typescript-eslint/parser":"^8.65.0","@types/express":"^5.0.0",esbuild:"^0.28.1",express:"^4.21.0",eslint:"^10.0.2","eslint-config-prettier":"^10.1.8",jest:"^29.7.0",prettier:"^3.9.4","ts-jest":"^29.4.11",typescript:"^5.7.0"},engines:{node:">=18.0.0"},mcpName:"io.github.visa-crypto-labs/visa-cli",files:["bin/visa-cli.js","dist/","install.ps1","install.sh","native/visa-keychain.m","native/visa-keychain-win.cpp","native/build-win.bat","native/bin/win32-x64/visa-keychain-win.exe","server.json","README.md","LICENSE"]}});function CT(e=process.env,t=process.platform){return e.VISA_CLI_NO_BROWSER==="1"||e.VISA_CLI_NO_BROWSER==="true"?{headless:!0,reason:"VISA_CLI_NO_BROWSER is set"}:e.CI==="true"||e.CI==="1"?{headless:!0,reason:"CI environment detected"}:e.SSH_CONNECTION||e.SSH_TTY?{headless:!0,reason:"SSH session detected"}:t==="linux"&&!e.DISPLAY&&!e.WAYLAND_DISPLAY?{headless:!0,reason:"Linux with no $DISPLAY or $WAYLAND_DISPLAY"}:{headless:!1}}function z6t(e){let r=e.length+4;return[`\u250C${"\u2500".repeat(r)}\u2510`,`\u2502${" ".repeat(2)}${e}${" ".repeat(2)}\u2502`,`\u2514${"\u2500".repeat(r)}\u2518`].join(`
|
|
3
3
|
`)}function OT(e){if(typeof e!="string"||e.length===0)return null;let t;try{t=new URL(e)}catch{return null}return t.protocol!=="https:"&&t.protocol!=="http:"?null:t.toString()}function cSe(e,t){let r=OT(e);if(!r)return null;let n,i;try{n=new URL(r),i=new URL(t)}catch{return null}return n.origin===i.origin?r:null}function uSe(e,t){return t==="darwin"?{cmd:"open",args:[e]}:t==="win32"?{cmd:"rundll32.exe",args:["url.dll,FileProtocolHandler",e]}:t==="linux"?{cmd:"xdg-open",args:[e]}:null}function dSe(e,t=process.platform){let r=OT(e);return r?uSe(r,t):null}function sSe(e,t){e(` Could not open browser automatically (${t.message}).`),e(" Open the URL above manually to continue."),e("")}async function P_(e,t={}){let r=t.log??(u=>console.log(u)),n=t.env??process.env,i=t.platform??process.platform,o=OT(e),s=t.spawn??((u,d,l)=>{(0,aSe.execFile)(u,d,p=>l(p))});r(""),r(" Sign in to Visa CLI by opening this URL in your browser:"),r("");for(let u of z6t(o??e).split(`
|
|
4
4
|
`))r(` ${u}`);if(r(""),!o){r(" (Auth URL is not a valid absolute http(s) URL \u2014 skipping browser auto-open.)"),r(" Open the URL above manually to continue."),r("");return}let a=CT(n,i);if(a.headless){r(` (${a.reason} \u2014 skipping browser auto-open.)`),r(" Open the URL above on any device with a browser. The CLI will"),r(" continue waiting for you to complete sign-in."),r("");return}let c=uSe(o,i);if(!c){r(` No known browser-open command for platform "${i}".`),r(" Open the URL above manually to continue."),r("");return}await new Promise(u=>{let d=l=>{l?sSe(r,l):(r(" Opened browser. Waiting for you to sign in..."),r("")),u()};try{s(c.cmd,c.args,d)}catch(l){sSe(r,l instanceof Error?l:new Error(String(l))),u()}})}var aSe,_j=k(()=>{"use strict";aSe=require("child_process")});async function JSe(e,t){let r=t?.timeoutMs??3e4,n=new AbortController,i=setTimeout(()=>n.abort(),r);try{let{timeoutMs:o,...s}=t??{};return await fetch(e,{...s,signal:n.signal})}finally{clearTimeout(i)}}var YSe=k(()=>{"use strict"});var Nj,ZSe=k(()=>{"use strict";Nj=class extends Error{code="ATTESTATION_KEY_DRIFT";hint;constructor(t,r){super(t),this.name="AttestationDriftError",this.hint=r}}});function QSe(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 r=(t.cause&&typeof t.cause=="object"?t.cause.code:void 0)??(typeof t.code=="string"?t.code:void 0);return r&&XSe[r]?XSe[r]:`Network error contacting the Visa CLI server (${r?`${r}: ${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 XSe,eTe=k(()=>{"use strict";XSe={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.",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 rTe(e,t){let r=tTe(e),n=tTe(t);if(!r||!n)return!1;for(let i=0;i<3;i++)if(r.main[i]!==n.main[i])return r.main[i]>n.main[i];return r.pre&&!n.pre?!1:!r.pre&&n.pre?!0:!r.pre&&!n.pre?!1:Ivt(r.pre,n.pre)>0}function tTe(e){if(typeof e!="string")return null;let r=e.trim().replace(/^v/,"").match(Tvt);return r?{main:[Number(r[1]),Number(r[2]),Number(r[3])],pre:r[4]??null}:null}function Ivt(e,t){let r=e.split("."),n=t.split("."),i=Math.max(r.length,n.length);for(let o=0;o<i;o++){if(o>=r.length)return-1;if(o>=n.length)return 1;let s=r[o],a=n[o],c=/^\d+$/.test(s),u=/^\d+$/.test(a);if(c&&u){let d=Number(s)-Number(a);if(d!==0)return d}else{if(c)return-1;if(u)return 1;if(s<a)return-1;if(s>a)return 1}}return 0}var Tvt,nTe=k(()=>{"use strict";Tvt=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/});function oy(){return!!(iTe(process.env.VISA_CLI_NO_UPDATE_CHECK)||iTe(process.env.CI)||process.env.NODE_ENV==="test")}function iTe(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}var MT=k(()=>{"use strict"});var Bj,oTe,sTe,Mee,qT,aTe=k(()=>{"use strict";Bj=_e(require("fs")),oTe=_e(require("path")),sTe=_e(require("os")),Mee=oTe.join(sTe.homedir(),".visa-mcp"),qT=class{static ensureConfigDir(){Bj.existsSync(Mee)||Bj.mkdirSync(Mee,{recursive:!0,mode:448})}static getConfigDir(){return Mee}}});function Cvt(){sc.existsSync(Dee)||sc.mkdirSync(Dee,{recursive:!0,mode:448})}function Ovt(){if(!qee){if(Cvt(),sc.existsSync(DT)&&sc.statSync(DT).size>Pvt){let t=DT+".1";sc.existsSync(t)&&sc.unlinkSync(t),sc.renameSync(DT,t)}qee=sc.createWriteStream(DT,{flags:"a"})}return qee}function kvt(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"}function jj(e,...t){let r=new Date().toISOString(),n=t.map(o=>typeof o=="string"?o:JSON.stringify(o,null,2)).join(" "),i=`[${r}] [${e}] ${n}
|
|
5
5
|
`;kvt(e)&&process.stderr.write(i),Ovt().write(i)}var sc,Lee,cTe,Dee,DT,Pvt,qee,Ce,pd=k(()=>{"use strict";sc=_e(require("fs")),Lee=_e(require("path")),cTe=_e(require("os")),Dee=Lee.join(cTe.homedir(),".visa-mcp"),DT=Lee.join(Dee,"mcp-server.log"),Pvt=5*1024*1024,qee=null;Ce={debug:(...e)=>jj("DEBUG",...e),info:(...e)=>jj("INFO",...e),warn:(...e)=>jj("WARN",...e),error:(...e)=>jj("ERROR",...e)}});function uTe(e){let t=dTe.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function Uj(){return lTe.join(qT.getConfigDir(),Rvt)}function pTe(e){if((0,Hee.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function Bvt(e){let t=e.match(/^::ffff:([0-9a-f]{1,4}):([0-9a-f]{1,4})$/i);if(!t)return!1;let r=Number.parseInt(t[1],16),n=Number.parseInt(t[2],16);if(!Number.isFinite(r)||!Number.isFinite(n))return!1;let i=[r>>8&255,r&255,n>>8&255,n&255].join(".");return pTe(i)}function jvt(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let r=(0,Hee.isIP)(t);return r===4?pTe(t):r===6?t==="::1"||Bvt(t):!1}function zee(e,t="auth.serverUrl"){let r;try{r=new URL(e)}catch{throw new Error(`${t} must be a valid URL (got: ${JSON.stringify(e)})`)}if(r.username||r.password)throw new Error(`${t} must not include username or password credentials`);if(r.protocol!=="https:"&&!(r.protocol==="http:"&&jvt(r.hostname)))throw new Error(`${t} ${Nvt}`)}function Mj(){let e=Uj();if(!sy.existsSync(e))return{};try{let t=sy.readFileSync(e,"utf-8"),r=JSON.parse(t);return!r||typeof r!="object"||Array.isArray(r)?(Ce.warn("settings:corrupt",{path:uTe(e),reason:"not_object"}),{}):r}catch(t){return Ce.warn("settings:corrupt",{path:uTe(e),error:t?.message||String(t)}),{}}}function fTe(e){qT.ensureConfigDir();let t=Uj(),r=`${t}.tmp`,n=JSON.stringify(e,null,2)+`
|
|
6
6
|
`;sy.writeFileSync(r,n,{mode:384}),sy.renameSync(r,t)}function $ee(e){let t=Mj()[e];return typeof t=="string"?t:void 0}function Fee(e){let t=Mj()[e];return typeof t=="boolean"?t:void 0}function qj(e,t){let r=j_[e];if(!r)throw new Ul(e);let n;if(r.type==="boolean")if(typeof t=="boolean")n=t;else if(typeof t=="string"){let o=t.toLowerCase();if(o==="true")n=!0;else if(o==="false")n=!1;else throw new Error(`${e} expects true or false (got: ${JSON.stringify(t)})`)}else throw new Error(`${e} expects a boolean (got: ${typeof t})`);else if(r.type==="number")if(typeof t=="number")n=t;else if(typeof t=="string"&&t.trim().length>0){let o=Number(t);if(!Number.isFinite(o))throw new Error(`${e} expects a number (got: ${JSON.stringify(t)})`);n=o}else throw new Error(`${e} expects a number (got: ${typeof t})`);else{if(typeof t!="string"||t.length===0)throw new Error(`${e} expects a non-empty string`);n=t}r.validate&&r.validate(n);let i=Mj();return i[e]=n,fTe(i),{key:e,value:n,requiresRestart:!!r.requiresRestart,path:Uj()}}function Dj(e){let t=j_[e];if(!t)throw new Ul(e);let r=Mj(),n=e in r;return n&&(delete r[e],fTe(r)),{key:e,removed:n,requiresRestart:n&&!!t.requiresRestart,path:Uj()}}function qvt(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function Dvt(){try{let e=hj();return qvt(e.version)}catch{return!1}}function Lvt(e){return e.envVar!==void 0&&e.envVar!==""?(zee(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(zee(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?Mvt:Uvt}function Sa(){return Lvt({envVar:process.env.VISA_AUTH_URL,settingValue:$ee("auth.serverUrl"),isPrerelease:Dvt()})}function mTe(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":Fee("ui.suppressBrowser")??!1}var sy,Hee,dTe,lTe,Rvt,Nvt,j_,Ul,Uvt,Mvt,ay=k(()=>{"use strict";sy=_e(require("fs")),Hee=require("node:net"),dTe=_e(require("os")),lTe=_e(require("path"));aTe();pd();Rvt="settings.json",Nvt="must use https unless it points at localhost/loopback for local development";j_={"auth.serverUrl":{type:"string",description:"Auth server base URL. Override for staging / self-hosted backends.",requiresRestart:!0,validate:e=>{if(typeof e!="string")throw new Error("auth.serverUrl must be a string");zee(e)}},"ui.suppressBrowser":{type:"boolean",description:"When true, the CLI/MCP server stops auto-opening result URLs in your browser."}};Ul=class extends Error{constructor(t){let r=Object.keys(j_).sort().join(", ");super(`Unknown setting "${t}". Settable keys: ${r}.`),this.name="UnknownSettingKeyError"}};Uvt="https://auth.visacli.sh",Mvt="https://auth-visa-code-preview.up.railway.app"});function Hvt(e,t){let r=typeof t?.error=="string"&&t.error||typeof t?.message=="string"&&t.message||"";return r?new Error(r):e>=500||e===408||e===425||e===429?new Error(`Request failed (${e}). Try again.`):e===404?new Error(`Request failed (${e}) \u2014 not found; check the identifier or slug.`):new Error(`Request failed (${e}).`)}function W4(e){return typeof e=="string"?e.trim():""}function Fvt(e){let t=e&&typeof e=="object"?e:{},r=W4(t.error)||W4(t.message);if(!r)return $vt;let n=W4(t.error_code),i=[["surface",W4(t.disabled_surface)],["flag",W4(t.flag)],["correlation_id",W4(t.correlation_id)]].filter(([,s])=>s).map(([s,a])=>`${s}=${a}`),o=i.length?` (${i.join(" ")})`:"";return n?`503 [${n}] ${r}${o}`:`503 ${r}${o}`}function Vvt(e=process.env,t=process.stdin.isTTY){let r=["Not logged in. No local Visa CLI session credentials were found."],n=e.VISA_CLI_API_KEY?.trim();return n?zvt.test(n)?(r.push("VISA_CLI_API_KEY is set, but this operation requires an enrolled device session."),r.push("Use the Visa Key with X-Api-Key on the /v2/harness/* surface.")):(r.push("VISA_CLI_API_KEY is set but has invalid format (expected vk_live_<...> or vk_test_<...>)."),r.push("Create a new Visa Key with: visa-cli keys create <app-name>")):r.push("Ask your agent to call `enroll_agent` to connect this device."),t===!1&&r.push("Complete enrollment in a normal terminal, then restart the MCP client."),r.join(`
|
|
7
|
-
`)}var Lj,zvt,$vt,fd,G4=k(()=>{"use strict";YSe();ZSe();eTe();nTe();MT();ay();Lj="4.1.0-rc.50",zvt=/^vk_(?:live|test)_[A-Za-z0-9_-]{16,128}$/;$vt="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";fd=class{constructor(t){this.getSessionToken=t;this.baseUrl=Sa()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!oy()){let n=t.headers.get("X-Latest-Version");n&&rTe(n,Lj)&&(this.lastSignals.updateAvailable={currentVersion:Lj,latestVersion:n})}let r=t.headers.get("X-Feedback-Prompt");if(r)try{this.lastSignals.feedbackPrompt=JSON.parse(r)}catch{}}getClientVersion(){return Lj}throwIfAttestationDrift(t){if(t?.error_code==="ATTESTATION_KEY_DRIFT")throw new Nj(t.error||"Your biometric key is out of sync with the server.",typeof t.hint=="string"?t.hint:void 0)}async throwServerUnavailable(t){let r=null;try{r=await t.json()}catch{}throw new Error(Fvt(r))}async request(t,r,n,i,o){let s=await this.getSessionToken();if(!s)throw new Error(Vvt());let a={Authorization:`Bearer ${s}`};o&&(t==="GET"?a["X-User-Context"]=encodeURIComponent(o.replace(/[\r\n\0]/g," ").slice(0,1e3)):n={...n||{},user_context:o}),n&&(a["Content-Type"]="application/json");let c;try{c=await JSe(`${this.baseUrl}${r}`,{method:t,headers:{...a,"X-Visa-CLI-Version":Lj,"X-Source":"cli"},body:n?JSON.stringify(n):void 0,timeoutMs:i})}catch(d){throw new Error(QSe(d))}if(this.parseServerSignals(c),c.status===401)throw new Error("Your device session has expired. Ask your agent to call `enroll_agent` to reconnect.");if(c.status===429){let d=c.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${d}s, then retry.`)}c.status===503&&await this.throwServerUnavailable(c);let u;try{u=await c.json()}catch{throw c.status===500?new Error(`Server error on ${r}. Try again or check https://visacli.sh for status.`):new Error(`Unexpected response from ${r}. Try again.`)}if(!c.ok)throw c.status===500?new Error(`Server error on ${r}. Try again or check https://visacli.sh for status.`):(this.throwIfAttestationDrift(u),Hvt(c.status,u));return u}async emitTelemetry(t){return this.request("POST","/v1/telemetry",{rows:t})}async merchantDirectorySearch(t,r){let n=new URLSearchParams;return t.provider&&n.set("provider",t.provider),t.q&&n.set("q",t.q),t.protocol&&n.set("protocol",t.protocol),t.maxPriceUsd&&n.set("max_price_usd",t.maxPriceUsd),n.set("limit",String(t.limit)),n.set("offset",String(t.offset)),this.request("GET",`/v1/merchant-directory/search?${n.toString()}`,void 0,void 0,r)}async getStatus(t){return this.request("GET","/v1/status",void 0,void 0,t)}async getAgentTapStatus(t){try{return await this.request("GET",`/v4/agent-bindings/${encodeURIComponent(t)}/tap-status`)}catch{return null}}async getFeatureFlags(){return this.request("GET","/v1/feature-flags")}async getAttestationChallenge(){return this.request("GET","/v1/attestation-challenge")}async registerAttestationKey(t,r){return this.request("POST","/v1/attestation-key",{publicKey:t,...r?{attestation:r}:{}})}async startAttestationRecovery(t,r){return this.request("POST","/v1/attestation-key/recovery/start",{state:t},void 0,r)}async setBiometricPreference(t,r){return this.request("POST","/v1/biometric-preference",{...t,confirm:!0},void 0,r)}async getPendingWebAuthenticators(t){return this.request("GET","/v1/webauthn/pending",void 0,void 0,t)}async authorizeWebAuthenticator(t,r){return this.request("POST","/v1/webauthn/authorize",t,void 0,r)}async logout(t,r){return this.request("POST","/v4/logout",t,void 0,r)}async feedback(t,r,n){return this.request("POST","/v1/feedback",{message:t,...r&&{transaction_id:r}},void 0,n)}async createAppApiKey(t){return this.request("POST","/v1/api/keys",t)}async listAppApiKeys(t){let r=new URLSearchParams;t?.limit!=null&&r.set("limit",String(t.limit)),t?.startingAfter!=null&&r.set("starting_after",String(t.startingAfter)),t?.endingBefore!=null&&r.set("ending_before",String(t.endingBefore));let n=r.toString();return this.request("GET",n?`/v1/api/keys?${n}`:"/v1/api/keys")}async listAllAppApiKeys(){let t=[],r=new Set,n,i=null,o=0;for(;;){let s=await this.listAppApiKeys({limit:100,...n!==void 0?{startingAfter:n}:{}});if(o+=1,i=s,t.push(...s.keys??[]),!s.has_more)break;if(s.next_cursor==null)throw new Error("API key pagination response did not include next_cursor.");if(r.has(s.next_cursor))throw new Error("API key pagination cursor did not advance.");r.add(s.next_cursor),n=s.next_cursor}return{...i??{success:!0,keys:[]},keys:t,limit:100,has_more:!1,next_cursor:null,previous_cursor:null,pages:o}}async revokeAppApiKey(t){return this.request("DELETE",`/v1/api/keys/${encodeURIComponent(String(t))}`)}async submitFeedback(t,r,n){return this.request("POST","/v1/feedback",{message:t,...r&&{transaction_id:r}},void 0,n)}async getFeedback(t,r){let n=new URLSearchParams;t&&n.set("limit",String(t));let i=n.toString();return this.request("GET",`/v1/feedback${i?"?"+i:""}`,void 0,void 0,r)}async submitRatedFeedback(t){return this.request("POST","/v1/feedback",t)}async createCapabilityAttach(t,r){return this.request("POST",`/v4/agents/${encodeURIComponent(t)}/capability-attach`,{protocolVersion:2,capability:r.capability,aggregateCeilingCents:r.aggregateCeilingCents,perPurchaseCents:r.perPurchaseCents})}}});function Vee(e=hTe){return/^\d+\.\d+\.\d+$/.test(e)&&e!=="0.0.0"}function yTe(e=hTe){return/-(?:rc|alpha|beta)\./i.test(e)}function Kee(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function cy(e=process.env){let t=e.VISA_VERIFY_WEB_URL?.trim();return t?Kee(t):yTe()?Wvt:Kvt}function gTe(e){return`${Kee(e)}${Gvt}`}function Jvt(e=process.env){return!!e.VISA_VERIFY_WEB_URL?.trim()||yTe()}function Wee(e,t=process.env){if(!e||!Jvt(t))return e;try{let r=new URL(cy(t)),n=new URL(e);return n.protocol=r.protocol,n.host=r.host,n.toString()}catch{return e}}async function bTe(e,t=fetch){let r=`${Kee(e)}/api/agent-enroll/health`,n;try{n=await t(r,{method:"GET",headers:{accept:"application/json"},signal:AbortSignal.timeout(1e4)})}catch{throw new Error("Could not verify the v4 sign-in service. Try again shortly.")}if(!n.ok)throw new Error(`V4 sign-in readiness check failed (${n.status}).`);if((await n.json().catch(()=>null))?.clients?.auth!=="turnkey")throw new Error("V4 sign-in is not enabled on this deployment; refusing to open the retired GitHub flow.")}var hTe,Kvt,Wvt,Gvt,zj=k(()=>{"use strict";hTe="4.1.0-rc.50",Kvt="https://app.visacli.sh",Wvt="https://web-visa-code-preview.up.railway.app",Gvt="/agent/enroll"});function S5t(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function g7e(e,t,r=""){let n=S5t(e),i=e?.length,o=t!==void 0;if(!n||o&&i!==t){let s=r&&`"${r}" `,a=o?` of length ${t}`:"",c=n?`length=${i}`:`type=${typeof e}`,u=s+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(u):new TypeError(u)}return e}function FTe(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function T5t(e,t){g7e(e,void 0,"digestInto() output");let r=t.outputLen;if(e.length<r)throw new RangeError('"digestInto() output" expected to be of length >='+r)}function ate(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Qee(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function I5t(e,t={}){let r=(i,o)=>e(o).update(i).digest(),n=e(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=i=>e(i),Object.assign(r,t),Object.freeze(r)}function O5t(e,t=!1){return t?{h:Number(e&Wj),l:Number(e>>VTe&Wj)}:{h:Number(e>>VTe&Wj)|0,l:Number(e&Wj)|0}}function k5t(e,t=!1){let r=e.length,n=new Uint32Array(r),i=new Uint32Array(r);for(let o=0;o<r;o++){let{h:s,l:a}=O5t(e[o],t);[n[o],i[o]]=[s,a]}return[n,i]}function I0(e,t,r,n){let i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:i|0}}function $5t(){return w5t.randomSecretKey()}function z_(e){return y5t(e)}function _7e(){let e=$5t();return{secretKey:e,publicKey:z_(e)}}function v7e(e){if(e.length!==JTe)throw new Error(`Ed25519 seed must be ${JTe} bytes, got ${e.length}`);return{secretKey:e,publicKey:z_(e)}}function t8(e,t){return _5t(t,e)}function F5t(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function V5t(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function rU(e){return F5t(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function E7e(e){let t=e.length%4===0?0:4-e.length%4,r=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat(t);return V5t(r)}function K5t(e){if(e.kty!=="OKP"||e.crv!=="Ed25519")throw new Error("not an Ed25519 OKP JWK")}function H_(e){let t=z_(e);return{kty:"OKP",crv:"Ed25519",x:rU(t),d:rU(e)}}function my(e){return{kty:"OKP",crv:"Ed25519",x:rU(e)}}function r8(e){if(K5t(e),!e.d)throw new Error("Ed25519 JWK has no private component (d)");return E7e(e.d)}function ZTe(e,t){return e<t?-1:e>t?1:0}function tte(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Cr(e){if(typeof e!="string"||!J5t.test(e))return!1;try{let t=E7e(e);return t.byteLength===32&&rU(t)===e}catch{return!1}}function rte(e,t,r){let n=Object.keys(t).filter(i=>!r.has(i));if(n.length>0)throw new Error(`${e} contains unknown field(s): ${n.sort().join(", ")}`)}function rwt(e,t){if(typeof t!="string"||!G5t.test(t))throw new Error(`${e} must be a UUID`)}function zT(e,t){return rwt(e,t),t.toLowerCase()}function XTe(e,t){if(typeof t!="string")throw new Error(`${e} must be an ISO timestamp with an explicit time-zone offset`);let r=Z5t.exec(t);if(!r)throw new Error(`${e} must be an ISO timestamp with an explicit time-zone offset`);let[,n,i,o,s,a,c]=r,u=Number(n),d=Number(i),l=Number(o),p=Number(s),f=Number(a),m=Number(c),h=new Date(0);if(h.setUTCFullYear(u,d-1,l),h.setUTCHours(p,f,m,0),u===0||h.getUTCFullYear()!==u||h.getUTCMonth()!==d-1||h.getUTCDate()!==l||h.getUTCHours()!==p||h.getUTCMinutes()!==f||h.getUTCSeconds()!==m)throw new Error(`${e} must be a valid calendar timestamp`);let y=Date.parse(t);if(!Number.isFinite(y))throw new Error(`${e} must be a valid ISO timestamp`);return new Date(y).toISOString()}function Yj(e,t,r=!1){if(typeof t!="string"||!Y5t.test(t))throw new Error(`${e} must be a canonical non-negative integer micros string`);if(!r&&t==="0")throw new Error(`${e} must be positive`);if(BigInt(t)>Q5t)throw new Error(`${e} exceeds the PostgreSQL BIGINT range`);return t}function nwt(e,t){if(typeof t!="number"||!Number.isInteger(t)||t<=0||t>X5t)throw new Error(`${e} must be a positive PostgreSQL INTEGER`);return t}function QTe(e,t){if(typeof t!="string")throw new Error(`${e} must be a string`);if(A7e.test(t))throw new Error(`${e} must be a bounded non-empty payee without control characters`);let r=t.normalize("NFC").trim();if(r.length===0||r.length>ewt)throw new Error(`${e} must be a bounded non-empty payee without control characters`);return r}function iwt(e,t,r){if(typeof t!="string")throw new Error(`${e} must be a string`);if(A7e.test(t))throw new Error(`${e} must be bounded, non-empty text without control characters`);let n=t.normalize("NFC").trim();if(n.length===0||n.length>r)throw new Error(`${e} must be bounded, non-empty text without control characters`);return n}function nte(e,t){return typeof e=="string"&&t.includes(e)}function owt(e){if(!tte(e))throw new Error("agent authority grant must be an object");if(rte("agent authority grant",e,new Set(["v","grantId","agentId","version","budgetEpochId","budgetEpochMode","status","currency","valuationPolicy","totalMicros","perTransactionMicros","scopes","payeeConstraints","effectiveAt","expiresAt","supersedesGrantId"])),e.v!==X4)throw new Error("grant.v must be 2");let t=zT("grantId",e.grantId),r=zT("agentId",e.agentId),n=nwt("version",e.version),i=zT("budgetEpochId",e.budgetEpochId);if(!nte(e.budgetEpochMode,W5t))throw new Error("budgetEpochMode must be new or continue");if(!nte(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!==ete)throw new Error(`valuationPolicy must be '${ete}'`);let o=Yj("totalMicros",e.totalMicros),s=Yj("perTransactionMicros",e.perTransactionMicros);if(BigInt(s)>BigInt(o))throw new Error("perTransactionMicros cannot exceed totalMicros");if(!Array.isArray(e.scopes)||e.scopes.length===0)throw new Error("scopes must be a non-empty array");let a=e.scopes.map(l=>{if(!tte(l))throw new Error("grant scope must be an object");if(rte("grant scope",l,new Set(["scope","totalMicros","perTransactionMicros","instrumentRef"])),!nte(l.scope,py))throw new Error("invalid authorization scope");let p=l.totalMicros===void 0?void 0:Yj("scope.totalMicros",l.totalMicros),f=l.perTransactionMicros===void 0?void 0:Yj("scope.perTransactionMicros",l.perTransactionMicros);if(p!==void 0&&BigInt(p)>BigInt(o))throw new Error("scope.totalMicros cannot exceed the aggregate totalMicros");if(f!==void 0&&BigInt(f)>BigInt(s))throw new Error("scope.perTransactionMicros cannot exceed the aggregate perTransactionMicros");if(p!==void 0&&f!==void 0&&BigInt(f)>BigInt(p))throw new Error("scope.perTransactionMicros cannot exceed scope.totalMicros");let m=iwt("scope.instrumentRef",l.instrumentRef,255);return{scope:l.scope,...p!==void 0?{totalMicros:p}:{},...f!==void 0?{perTransactionMicros:f}:{},instrumentRef:m}});if(new Set(a.map(({scope:l})=>l)).size!==a.length)throw new Error("scopes must not repeat");let c;if(e.payeeConstraints!==void 0){if(!Array.isArray(e.payeeConstraints)||e.payeeConstraints.length===0||e.payeeConstraints.length>YTe)throw new Error(`payeeConstraints must contain between 1 and ${YTe} entries`);if(c=e.payeeConstraints.map(p=>{if(!tte(p))throw new Error("payee constraint must be an object");if(rte("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:QTe("payee constraint canonicalId",p.canonicalId)};if(p.scope==="wallet:x402"&&p.kind==="evm_address"){let f=QTe("payee constraint canonicalId",p.canonicalId).toLowerCase();if(!twt.test(f))throw new Error("wallet payee constraint canonicalId must be an EVM address");return{scope:p.scope,kind:p.kind,canonicalId:f}}throw new Error("payee constraint scope/kind combination is invalid")}),c.some(p=>!a.some(({scope:f})=>f===p.scope)))throw new Error("payee constraint scope must be present in grant scopes");let l=c.map(({scope:p,kind:f,canonicalId:m})=>`${p}:${f}:${m}`);if(new Set(l).size!==l.length)throw new Error("payeeConstraints must not repeat after normalization")}let u=XTe("effectiveAt",e.effectiveAt),d=XTe("expiresAt",e.expiresAt);if(Date.parse(d)<=Date.parse(u))throw new Error("expiresAt must be after effectiveAt");if(e.supersedesGrantId!==void 0&&zT("supersedesGrantId",e.supersedesGrantId)===t)throw new Error("a grant cannot supersede itself");return{v:X4,grantId:t,agentId:r,version:n,budgetEpochId:i,budgetEpochMode:e.budgetEpochMode,status:e.status,currency:"USD",valuationPolicy:ete,totalMicros:o,perTransactionMicros:s,scopes:[...a].sort((l,p)=>ZTe(l.scope,p.scope)),...c!==void 0?{payeeConstraints:[...c].sort((l,p)=>ZTe(`${l.scope}:${l.kind}:${l.canonicalId}`,`${p.scope}:${p.kind}:${p.canonicalId}`))}:{},effectiveAt:u,expiresAt:d,...e.supersedesGrantId!==void 0?{supersedesGrantId:zT("supersedesGrantId",e.supersedesGrantId)}:{}}}function I7e(e,t){return e<t?-1:e>t?1:0}function md(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ml(e,t,r){let n=new Set(r),i=Object.keys(t).filter(o=>!n.has(o));if(i.length>0)throw new Error(`${e} contains unknown field(s): ${i.sort().join(", ")}`)}function mwt(e){if(typeof e!="string")throw new Error("displayName must be a string");if(iU.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>cwt)throw new Error("displayName must be bounded, non-empty text without control characters");return t}function hwt(e){if(typeof e!="string")throw new Error("dotVisaAddress must be a string");if(iU.test(e))throw new Error("dotVisaAddress must be a valid .visa address");let t=e.trim().toLowerCase();if(!awt.test(t))throw new Error("dotVisaAddress must be a valid .visa address");return t}function Zj(e,t,r){if(typeof t!="string")throw new Error(`${e} must be a string`);if(iU.test(t)||T7e.test(t))throw new Error(`${e} must be bounded, non-empty text without control characters`);let n=t.normalize("NFC").trim();if(n.length===0||n.length>r)throw new Error(`${e} must be bounded, non-empty text without control characters`);return n}function ywt(e){if(!md(e))throw new Error("runtime context v2 must be an object");Ml("runtime context v2",e,["runtime","contextLabel","cliVersion","platform"]);let t=Zj("runtime",e.runtime,dwt),r=Zj("contextLabel",e.contextLabel,lwt),n=e.cliVersion===void 0?void 0:Zj("cliVersion",e.cliVersion,pwt),i=e.platform===void 0?void 0:Zj("platform",e.platform,fwt);return{runtime:t,contextLabel:r,...n!==void 0?{cliVersion:n}:{},...i!==void 0?{platform:i}:{}}}function yte(e){if(typeof e!="string"||!S7e.test(e))throw new Error("pairingId must be a server-generated pairing id")}function oU(e){if(e!==jt)throw new Error("protocolVersion must be 2")}function fy(e,t){if(typeof t!="string"||!uwt.test(t))throw new Error(`${e} must be a canonical lowercase UUID`)}function Co(e,t){if(!Cr(t))throw new Error(`${e} must be 32 canonical unpadded base64url bytes`)}function P7e(e){if(typeof e!="string"||!gwt.test(e))throw new Error("attachId must be a server-generated capability-attach id")}function bwt(e){if(typeof e!="string"||!e7e.includes(e))throw new Error(`capability must be one of ${e7e.join(", ")}`)}function _wt(e){if(typeof e!="string"||!py.includes(e))throw new Error(`rail must be one of ${py.join(", ")}`)}function n7e(e,t){if(typeof t!="string"||t.length===0||t.length>r7e||iU.test(t)||T7e.test(t))throw new Error(`${e} must be a bounded absolute HTTP(S) URL`);let r;try{r=new URL(t)}catch{throw new Error(`${e} must be a bounded absolute HTTP(S) URL`)}if(r.protocol!=="https:"&&r.protocol!=="http:"||r.hostname.length===0||r.username.length>0||r.password.length>0||r.hash.length>0)throw new Error(`${e} must be a bounded absolute HTTP(S) URL`);let n=r.toString();if(n.length>r7e)throw new Error(`${e} must be a bounded absolute HTTP(S) URL`);return n}function C7e(){return $T.default.randomBytes(32).toString("base64url")}function O7e(e){if(!Cr(e))throw new Error("pairing verifier must be 32 unpadded base64url bytes");return VT(e)}function vwt(e){return e.toUpperCase().replace(/[^A-Z0-9]/g,"")}function wwt(e){let t=vwt(e);return`${t.slice(0,4)}-${t.slice(4)}`}function sU(){return $T.default.randomBytes(32).toString("base64url")}function P0(e){if(!Cr(e))throw new Error("claim token must be 32 unpadded base64url bytes");return VT(`visa-agent-pairing-claim-token:v1:${e}`)}function aU(e,t){P0(t);let r=$T.default.createHash("sha256").update(`visa-agent-pairing-derived-code:v1:${e}:${t}`,"utf8").digest(),n="";for(let i=0;i<swt;i+=1)n+=hte[r[i]&x7e];return wwt(n)}function k7e(e){if(!md(e))throw new Error("pairing terms v2 must be an object");if(Ml("pairing terms v2",e,["v","pairingId","agentId","agentSelection","identityKeyJkt","ownerPublicId","displayName","dotVisaAddress","authority"]),e.v!==X4)throw new Error("pairing terms v2 must carry v=2");if(typeof e.pairingId!="string"||!S7e.test(e.pairingId))throw new Error("pairingId must be a server-issued pairing id");if(typeof e.agentId!="string"||!t7e.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(!Cr(e.identityKeyJkt))throw new Error("identityKeyJkt must be a canonical 32-byte base64url thumbprint");if(typeof e.ownerPublicId!="string"||!t7e.test(e.ownerPublicId))throw new Error("ownerPublicId must be a UUID");let t=e.agentId.toLowerCase(),r=e.ownerPublicId.toLowerCase(),n=mwt(e.displayName),i=e.dotVisaAddress===void 0?void 0:hwt(e.dotVisaAddress);if(e.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:n,identityKeyJkt:e.identityKeyJkt,...i!==void 0?{dotVisaAddress:i}:{},ownerPublicId:r,pairingId:e.pairingId,v:X4})}if(!md(e.authority))throw new Error("pairing authority must be an object or null");if(Ml("pairing authority",e.authority,["grantId","grantVersion","supersedesGrantId","budgetEpochId","budgetEpochMode","currency","valuationPolicy","totalMicros","perTransactionMicros","scopes","payeeConstraints","effectiveAt","expiresAt"]),!Array.isArray(e.authority.scopes)||e.authority.scopes.length===0||e.authority.scopes.length>py.length)throw new Error(`pairing authority scopes must contain between 1 and ${py.length} entries`);let o=new Map,s=e.authority.scopes.map(c=>{if(!md(c))throw new Error("pairing authority scope must be an object");if(Object.prototype.hasOwnProperty.call(c,"instrumentRef"))throw new Error("pairing authority scopes may not supply instrumentRef; auth resolves it");if(Ml("pairing authority scope",c,["scope","totalMicros","perTransactionMicros","instrumentCommitment"]),!py.includes(c.scope))throw new Error("invalid authorization scope");let u=c.scope;if(!Cr(c.instrumentCommitment))throw new Error("every approved scope requires a 32-byte instrumentCommitment");return o.set(u,c.instrumentCommitment),{scope:u,instrumentRef:c.instrumentCommitment,...c.totalMicros!==void 0?{totalMicros:c.totalMicros}:{},...c.perTransactionMicros!==void 0?{perTransactionMicros:c.perTransactionMicros}:{}}}),a=owt({v:X4,grantId:e.authority.grantId,agentId:t,version:e.authority.grantVersion,budgetEpochId:e.authority.budgetEpochId,budgetEpochMode:e.authority.budgetEpochMode,status:"active",currency:e.authority.currency,valuationPolicy:e.authority.valuationPolicy,totalMicros:e.authority.totalMicros,perTransactionMicros:e.authority.perTransactionMicros,scopes:s,...e.authority.payeeConstraints!==void 0?{payeeConstraints:e.authority.payeeConstraints}:{},effectiveAt:e.authority.effectiveAt,expiresAt:e.authority.expiresAt,...e.authority.supersedesGrantId!==void 0?{supersedesGrantId:e.authority.supersedesGrantId}:{}});if(e.agentSelection==="new"&&(a.version>1||a.supersedesGrantId!==void 0))throw new Error("a new-agent pairing cannot replace or supersede an existing grant; replacement authority belongs to an existing agent");if(a.version===1&&(a.budgetEpochMode!=="new"||a.supersedesGrantId!==void 0))throw new Error("an initial pairing grant must start a new budget epoch and supersede nothing");if(a.version>1&&a.supersedesGrantId===void 0)throw new Error("a replacement pairing grant must name its direct predecessor");return JSON.stringify({agentId:t,agentSelection:e.agentSelection,authority:{...a.payeeConstraints!==void 0?{payeeConstraints:a.payeeConstraints}:{},currency:a.currency,effectiveAt:a.effectiveAt,expiresAt:a.expiresAt,grantId:a.grantId,grantVersion:a.version,budgetEpochId:a.budgetEpochId,budgetEpochMode:a.budgetEpochMode,...a.supersedesGrantId!==void 0?{supersedesGrantId:a.supersedesGrantId}:{},perTransactionMicros:a.perTransactionMicros,scopes:a.scopes.map(({scope:c,totalMicros:u,perTransactionMicros:d})=>{let l=o.get(c);if(l===void 0)throw new Error("canonical scope lost its approved instrument commitment");return{instrumentCommitment:l,...d!==void 0?{perTransactionMicros:d}:{},scope:c,...u!==void 0?{totalMicros:u}:{}}}),totalMicros:a.totalMicros,valuationPolicy:a.valuationPolicy},displayName:n,identityKeyJkt:e.identityKeyJkt,...i!==void 0?{dotVisaAddress:i}:{},ownerPublicId:r,pairingId:e.pairingId,v:X4})}function Ewt(e){return VT(`visa-agent-pairing-terms:v2:${k7e(e)}`)}function gte(e){if(!md(e))throw new Error("pairing claim v2 must be an object");Ml("pairing claim v2",e,["protocolVersion","pairingId","agentId","serverNonce","claimTokenHash","identityKeyJkt","runtime"]),oU(e.protocolVersion),yte(e.pairingId),fy("agentId",e.agentId),Co("serverNonce",e.serverNonce),Co("claimTokenHash",e.claimTokenHash),Co("identityKeyJkt",e.identityKeyJkt);let t=ywt(e.runtime);return cU("visa-agent-pairing-claim:v2",{agentId:e.agentId,claimTokenHash:e.claimTokenHash,cliVersion:t.cliVersion??"",contextLabel:t.contextLabel,identityKeyJkt:e.identityKeyJkt,pairingId:e.pairingId,platform:t.platform??"",protocolVersion:String(e.protocolVersion),runtime:t.runtime,serverNonce:e.serverNonce})}function R7e(e){if(!md(e))throw new Error("pairing activation v2 must be an object");return Ml("pairing activation v2",e,["protocolVersion","pairingId","agentId","ownerPublicId","claimTokenHash","identityKeyJkt","ceremonyHash","deliveryArtifactHash"]),oU(e.protocolVersion),yte(e.pairingId),fy("agentId",e.agentId),fy("ownerPublicId",e.ownerPublicId),Co("claimTokenHash",e.claimTokenHash),Co("identityKeyJkt",e.identityKeyJkt),Co("ceremonyHash",e.ceremonyHash),Co("deliveryArtifactHash",e.deliveryArtifactHash),cU("visa-agent-pairing-activation:v2",{agentId:e.agentId,ceremonyHash:e.ceremonyHash,claimTokenHash:e.claimTokenHash,deliveryArtifactHash:e.deliveryArtifactHash,identityKeyJkt:e.identityKeyJkt,ownerPublicId:e.ownerPublicId,pairingId:e.pairingId,protocolVersion:String(e.protocolVersion)})}function N7e(e){if(!md(e))throw new Error("capability attach claim v2 must be an object");return Ml("capability attach claim v2",e,["protocolVersion","attachId","agentId","capability","serverNonce","claimTokenHash","identityKeyJkt"]),oU(e.protocolVersion),P7e(e.attachId),fy("agentId",e.agentId),bwt(e.capability),Co("serverNonce",e.serverNonce),Co("claimTokenHash",e.claimTokenHash),Co("identityKeyJkt",e.identityKeyJkt),cU("visa-agent-capability-attach-claim:v2",{agentId:e.agentId,attachId:e.attachId,capability:e.capability,claimTokenHash:e.claimTokenHash,identityKeyJkt:e.identityKeyJkt,protocolVersion:String(e.protocolVersion),serverNonce:e.serverNonce})}function bte(e){if(!md(e))throw new Error("capability attach activation v2 must be an object");return Ml("capability attach activation v2",e,["protocolVersion","attachId","agentId","ownerPublicId","identityKeyJkt","claimTokenHash","grantHash","ceremonyHash","deliveryArtifactHash","rail"]),oU(e.protocolVersion),P7e(e.attachId),fy("agentId",e.agentId),fy("ownerPublicId",e.ownerPublicId),Co("identityKeyJkt",e.identityKeyJkt),Co("claimTokenHash",e.claimTokenHash),Co("grantHash",e.grantHash),Co("ceremonyHash",e.ceremonyHash),Co("deliveryArtifactHash",e.deliveryArtifactHash),_wt(e.rail),cU("visa-agent-capability-attach-activation:v2",{agentId:e.agentId,attachId:e.attachId,ceremonyHash:e.ceremonyHash,claimTokenHash:e.claimTokenHash,deliveryArtifactHash:e.deliveryArtifactHash,grantHash:e.grantHash,identityKeyJkt:e.identityKeyJkt,ownerPublicId:e.ownerPublicId,protocolVersion:String(e.protocolVersion),rail:e.rail})}function FT(e){if(!md(e))throw new Error("pairing delivery artifact v2 must be an object");if(Ml("pairing delivery artifact v2",e,["v","kind","pairingId","agentId","ownerPublicId","identityKey","terms","ceremonyHash","issuer","activationAudience"]),e.v!==jt)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(yte(e.pairingId),fy("agentId",e.agentId),fy("ownerPublicId",e.ownerPublicId),Co("ceremonyHash",e.ceremonyHash),!md(e.identityKey))throw new Error("pairing delivery identityKey must be an object");if(Ml("pairing delivery identityKey",e.identityKey,["jkt","publicJwk"]),Co("identityKey.jkt",e.identityKey.jkt),!md(e.identityKey.publicJwk))throw new Error("pairing delivery identityKey.publicJwk must be an object");let t=e.identityKey.publicJwk;if(Ml("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");Co("identityKey.publicJwk.x",t.x);let r=VT(JSON.stringify({crv:"Ed25519",kty:"OKP",x:t.x}));if(e.identityKey.jkt!==r)throw new Error("identityKey.jkt must equal the RFC 7638 thumbprint of publicJwk");if(!md(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 n=k7e(e.terms);if(Ewt(e.terms)!==e.ceremonyHash)throw new Error("ceremonyHash must equal the hash of the exact canonical v2 terms");let i=n7e("issuer",e.issuer),o=n7e("activationAudience",e.activationAudience);return cte({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(n),v:jt})}function B7e(e){return VT(`visa-agent-pairing-delivery-artifact:v2:${FT(e)}`)}function VT(e){return $T.default.createHash("sha256").update(e,"utf8").digest("base64url")}function cU(e,t){return`${e}
|
|
7
|
+
`)}var Lj,zvt,$vt,fd,G4=k(()=>{"use strict";YSe();ZSe();eTe();nTe();MT();ay();Lj="4.1.0-rc.51",zvt=/^vk_(?:live|test)_[A-Za-z0-9_-]{16,128}$/;$vt="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";fd=class{constructor(t){this.getSessionToken=t;this.baseUrl=Sa()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!oy()){let n=t.headers.get("X-Latest-Version");n&&rTe(n,Lj)&&(this.lastSignals.updateAvailable={currentVersion:Lj,latestVersion:n})}let r=t.headers.get("X-Feedback-Prompt");if(r)try{this.lastSignals.feedbackPrompt=JSON.parse(r)}catch{}}getClientVersion(){return Lj}throwIfAttestationDrift(t){if(t?.error_code==="ATTESTATION_KEY_DRIFT")throw new Nj(t.error||"Your biometric key is out of sync with the server.",typeof t.hint=="string"?t.hint:void 0)}async throwServerUnavailable(t){let r=null;try{r=await t.json()}catch{}throw new Error(Fvt(r))}async request(t,r,n,i,o){let s=await this.getSessionToken();if(!s)throw new Error(Vvt());let a={Authorization:`Bearer ${s}`};o&&(t==="GET"?a["X-User-Context"]=encodeURIComponent(o.replace(/[\r\n\0]/g," ").slice(0,1e3)):n={...n||{},user_context:o}),n&&(a["Content-Type"]="application/json");let c;try{c=await JSe(`${this.baseUrl}${r}`,{method:t,headers:{...a,"X-Visa-CLI-Version":Lj,"X-Source":"cli"},body:n?JSON.stringify(n):void 0,timeoutMs:i})}catch(d){throw new Error(QSe(d))}if(this.parseServerSignals(c),c.status===401)throw new Error("Your device session has expired. Ask your agent to call `enroll_agent` to reconnect.");if(c.status===429){let d=c.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${d}s, then retry.`)}c.status===503&&await this.throwServerUnavailable(c);let u;try{u=await c.json()}catch{throw c.status===500?new Error(`Server error on ${r}. Try again or check https://visacli.sh for status.`):new Error(`Unexpected response from ${r}. Try again.`)}if(!c.ok)throw c.status===500?new Error(`Server error on ${r}. Try again or check https://visacli.sh for status.`):(this.throwIfAttestationDrift(u),Hvt(c.status,u));return u}async emitTelemetry(t){return this.request("POST","/v1/telemetry",{rows:t})}async merchantDirectorySearch(t,r){let n=new URLSearchParams;return t.provider&&n.set("provider",t.provider),t.q&&n.set("q",t.q),t.protocol&&n.set("protocol",t.protocol),t.maxPriceUsd&&n.set("max_price_usd",t.maxPriceUsd),n.set("limit",String(t.limit)),n.set("offset",String(t.offset)),this.request("GET",`/v1/merchant-directory/search?${n.toString()}`,void 0,void 0,r)}async getStatus(t){return this.request("GET","/v1/status",void 0,void 0,t)}async getAgentTapStatus(t){try{return await this.request("GET",`/v4/agent-bindings/${encodeURIComponent(t)}/tap-status`)}catch{return null}}async getFeatureFlags(){return this.request("GET","/v1/feature-flags")}async getAttestationChallenge(){return this.request("GET","/v1/attestation-challenge")}async registerAttestationKey(t,r){return this.request("POST","/v1/attestation-key",{publicKey:t,...r?{attestation:r}:{}})}async startAttestationRecovery(t,r){return this.request("POST","/v1/attestation-key/recovery/start",{state:t},void 0,r)}async setBiometricPreference(t,r){return this.request("POST","/v1/biometric-preference",{...t,confirm:!0},void 0,r)}async getPendingWebAuthenticators(t){return this.request("GET","/v1/webauthn/pending",void 0,void 0,t)}async authorizeWebAuthenticator(t,r){return this.request("POST","/v1/webauthn/authorize",t,void 0,r)}async logout(t,r){return this.request("POST","/v4/logout",t,void 0,r)}async feedback(t,r,n){return this.request("POST","/v1/feedback",{message:t,...r&&{transaction_id:r}},void 0,n)}async createAppApiKey(t){return this.request("POST","/v1/api/keys",t)}async listAppApiKeys(t){let r=new URLSearchParams;t?.limit!=null&&r.set("limit",String(t.limit)),t?.startingAfter!=null&&r.set("starting_after",String(t.startingAfter)),t?.endingBefore!=null&&r.set("ending_before",String(t.endingBefore));let n=r.toString();return this.request("GET",n?`/v1/api/keys?${n}`:"/v1/api/keys")}async listAllAppApiKeys(){let t=[],r=new Set,n,i=null,o=0;for(;;){let s=await this.listAppApiKeys({limit:100,...n!==void 0?{startingAfter:n}:{}});if(o+=1,i=s,t.push(...s.keys??[]),!s.has_more)break;if(s.next_cursor==null)throw new Error("API key pagination response did not include next_cursor.");if(r.has(s.next_cursor))throw new Error("API key pagination cursor did not advance.");r.add(s.next_cursor),n=s.next_cursor}return{...i??{success:!0,keys:[]},keys:t,limit:100,has_more:!1,next_cursor:null,previous_cursor:null,pages:o}}async revokeAppApiKey(t){return this.request("DELETE",`/v1/api/keys/${encodeURIComponent(String(t))}`)}async submitFeedback(t,r,n){return this.request("POST","/v1/feedback",{message:t,...r&&{transaction_id:r}},void 0,n)}async getFeedback(t,r){let n=new URLSearchParams;t&&n.set("limit",String(t));let i=n.toString();return this.request("GET",`/v1/feedback${i?"?"+i:""}`,void 0,void 0,r)}async submitRatedFeedback(t){return this.request("POST","/v1/feedback",t)}async createCapabilityAttach(t,r){return this.request("POST",`/v4/agents/${encodeURIComponent(t)}/capability-attach`,{protocolVersion:2,capability:r.capability,aggregateCeilingCents:r.aggregateCeilingCents,perPurchaseCents:r.perPurchaseCents})}}});function Vee(e=hTe){return/^\d+\.\d+\.\d+$/.test(e)&&e!=="0.0.0"}function yTe(e=hTe){return/-(?:rc|alpha|beta)\./i.test(e)}function Kee(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function cy(e=process.env){let t=e.VISA_VERIFY_WEB_URL?.trim();return t?Kee(t):yTe()?Wvt:Kvt}function gTe(e){return`${Kee(e)}${Gvt}`}function Jvt(e=process.env){return!!e.VISA_VERIFY_WEB_URL?.trim()||yTe()}function Wee(e,t=process.env){if(!e||!Jvt(t))return e;try{let r=new URL(cy(t)),n=new URL(e);return n.protocol=r.protocol,n.host=r.host,n.toString()}catch{return e}}async function bTe(e,t=fetch){let r=`${Kee(e)}/api/agent-enroll/health`,n;try{n=await t(r,{method:"GET",headers:{accept:"application/json"},signal:AbortSignal.timeout(1e4)})}catch{throw new Error("Could not verify the v4 sign-in service. Try again shortly.")}if(!n.ok)throw new Error(`V4 sign-in readiness check failed (${n.status}).`);if((await n.json().catch(()=>null))?.clients?.auth!=="turnkey")throw new Error("V4 sign-in is not enabled on this deployment; refusing to open the retired GitHub flow.")}var hTe,Kvt,Wvt,Gvt,zj=k(()=>{"use strict";hTe="4.1.0-rc.51",Kvt="https://app.visacli.sh",Wvt="https://web-visa-code-preview.up.railway.app",Gvt="/agent/enroll"});function S5t(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function g7e(e,t,r=""){let n=S5t(e),i=e?.length,o=t!==void 0;if(!n||o&&i!==t){let s=r&&`"${r}" `,a=o?` of length ${t}`:"",c=n?`length=${i}`:`type=${typeof e}`,u=s+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(u):new TypeError(u)}return e}function FTe(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function T5t(e,t){g7e(e,void 0,"digestInto() output");let r=t.outputLen;if(e.length<r)throw new RangeError('"digestInto() output" expected to be of length >='+r)}function ate(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Qee(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function I5t(e,t={}){let r=(i,o)=>e(o).update(i).digest(),n=e(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=i=>e(i),Object.assign(r,t),Object.freeze(r)}function O5t(e,t=!1){return t?{h:Number(e&Wj),l:Number(e>>VTe&Wj)}:{h:Number(e>>VTe&Wj)|0,l:Number(e&Wj)|0}}function k5t(e,t=!1){let r=e.length,n=new Uint32Array(r),i=new Uint32Array(r);for(let o=0;o<r;o++){let{h:s,l:a}=O5t(e[o],t);[n[o],i[o]]=[s,a]}return[n,i]}function I0(e,t,r,n){let i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:i|0}}function $5t(){return w5t.randomSecretKey()}function z_(e){return y5t(e)}function _7e(){let e=$5t();return{secretKey:e,publicKey:z_(e)}}function v7e(e){if(e.length!==JTe)throw new Error(`Ed25519 seed must be ${JTe} bytes, got ${e.length}`);return{secretKey:e,publicKey:z_(e)}}function t8(e,t){return _5t(t,e)}function F5t(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function V5t(e){let t=atob(e),r=new Uint8Array(t.length);for(let n=0;n<t.length;n++)r[n]=t.charCodeAt(n);return r}function rU(e){return F5t(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function E7e(e){let t=e.length%4===0?0:4-e.length%4,r=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat(t);return V5t(r)}function K5t(e){if(e.kty!=="OKP"||e.crv!=="Ed25519")throw new Error("not an Ed25519 OKP JWK")}function H_(e){let t=z_(e);return{kty:"OKP",crv:"Ed25519",x:rU(t),d:rU(e)}}function my(e){return{kty:"OKP",crv:"Ed25519",x:rU(e)}}function r8(e){if(K5t(e),!e.d)throw new Error("Ed25519 JWK has no private component (d)");return E7e(e.d)}function ZTe(e,t){return e<t?-1:e>t?1:0}function tte(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Cr(e){if(typeof e!="string"||!J5t.test(e))return!1;try{let t=E7e(e);return t.byteLength===32&&rU(t)===e}catch{return!1}}function rte(e,t,r){let n=Object.keys(t).filter(i=>!r.has(i));if(n.length>0)throw new Error(`${e} contains unknown field(s): ${n.sort().join(", ")}`)}function rwt(e,t){if(typeof t!="string"||!G5t.test(t))throw new Error(`${e} must be a UUID`)}function zT(e,t){return rwt(e,t),t.toLowerCase()}function XTe(e,t){if(typeof t!="string")throw new Error(`${e} must be an ISO timestamp with an explicit time-zone offset`);let r=Z5t.exec(t);if(!r)throw new Error(`${e} must be an ISO timestamp with an explicit time-zone offset`);let[,n,i,o,s,a,c]=r,u=Number(n),d=Number(i),l=Number(o),p=Number(s),f=Number(a),m=Number(c),h=new Date(0);if(h.setUTCFullYear(u,d-1,l),h.setUTCHours(p,f,m,0),u===0||h.getUTCFullYear()!==u||h.getUTCMonth()!==d-1||h.getUTCDate()!==l||h.getUTCHours()!==p||h.getUTCMinutes()!==f||h.getUTCSeconds()!==m)throw new Error(`${e} must be a valid calendar timestamp`);let y=Date.parse(t);if(!Number.isFinite(y))throw new Error(`${e} must be a valid ISO timestamp`);return new Date(y).toISOString()}function Yj(e,t,r=!1){if(typeof t!="string"||!Y5t.test(t))throw new Error(`${e} must be a canonical non-negative integer micros string`);if(!r&&t==="0")throw new Error(`${e} must be positive`);if(BigInt(t)>Q5t)throw new Error(`${e} exceeds the PostgreSQL BIGINT range`);return t}function nwt(e,t){if(typeof t!="number"||!Number.isInteger(t)||t<=0||t>X5t)throw new Error(`${e} must be a positive PostgreSQL INTEGER`);return t}function QTe(e,t){if(typeof t!="string")throw new Error(`${e} must be a string`);if(A7e.test(t))throw new Error(`${e} must be a bounded non-empty payee without control characters`);let r=t.normalize("NFC").trim();if(r.length===0||r.length>ewt)throw new Error(`${e} must be a bounded non-empty payee without control characters`);return r}function iwt(e,t,r){if(typeof t!="string")throw new Error(`${e} must be a string`);if(A7e.test(t))throw new Error(`${e} must be bounded, non-empty text without control characters`);let n=t.normalize("NFC").trim();if(n.length===0||n.length>r)throw new Error(`${e} must be bounded, non-empty text without control characters`);return n}function nte(e,t){return typeof e=="string"&&t.includes(e)}function owt(e){if(!tte(e))throw new Error("agent authority grant must be an object");if(rte("agent authority grant",e,new Set(["v","grantId","agentId","version","budgetEpochId","budgetEpochMode","status","currency","valuationPolicy","totalMicros","perTransactionMicros","scopes","payeeConstraints","effectiveAt","expiresAt","supersedesGrantId"])),e.v!==X4)throw new Error("grant.v must be 2");let t=zT("grantId",e.grantId),r=zT("agentId",e.agentId),n=nwt("version",e.version),i=zT("budgetEpochId",e.budgetEpochId);if(!nte(e.budgetEpochMode,W5t))throw new Error("budgetEpochMode must be new or continue");if(!nte(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!==ete)throw new Error(`valuationPolicy must be '${ete}'`);let o=Yj("totalMicros",e.totalMicros),s=Yj("perTransactionMicros",e.perTransactionMicros);if(BigInt(s)>BigInt(o))throw new Error("perTransactionMicros cannot exceed totalMicros");if(!Array.isArray(e.scopes)||e.scopes.length===0)throw new Error("scopes must be a non-empty array");let a=e.scopes.map(l=>{if(!tte(l))throw new Error("grant scope must be an object");if(rte("grant scope",l,new Set(["scope","totalMicros","perTransactionMicros","instrumentRef"])),!nte(l.scope,py))throw new Error("invalid authorization scope");let p=l.totalMicros===void 0?void 0:Yj("scope.totalMicros",l.totalMicros),f=l.perTransactionMicros===void 0?void 0:Yj("scope.perTransactionMicros",l.perTransactionMicros);if(p!==void 0&&BigInt(p)>BigInt(o))throw new Error("scope.totalMicros cannot exceed the aggregate totalMicros");if(f!==void 0&&BigInt(f)>BigInt(s))throw new Error("scope.perTransactionMicros cannot exceed the aggregate perTransactionMicros");if(p!==void 0&&f!==void 0&&BigInt(f)>BigInt(p))throw new Error("scope.perTransactionMicros cannot exceed scope.totalMicros");let m=iwt("scope.instrumentRef",l.instrumentRef,255);return{scope:l.scope,...p!==void 0?{totalMicros:p}:{},...f!==void 0?{perTransactionMicros:f}:{},instrumentRef:m}});if(new Set(a.map(({scope:l})=>l)).size!==a.length)throw new Error("scopes must not repeat");let c;if(e.payeeConstraints!==void 0){if(!Array.isArray(e.payeeConstraints)||e.payeeConstraints.length===0||e.payeeConstraints.length>YTe)throw new Error(`payeeConstraints must contain between 1 and ${YTe} entries`);if(c=e.payeeConstraints.map(p=>{if(!tte(p))throw new Error("payee constraint must be an object");if(rte("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:QTe("payee constraint canonicalId",p.canonicalId)};if(p.scope==="wallet:x402"&&p.kind==="evm_address"){let f=QTe("payee constraint canonicalId",p.canonicalId).toLowerCase();if(!twt.test(f))throw new Error("wallet payee constraint canonicalId must be an EVM address");return{scope:p.scope,kind:p.kind,canonicalId:f}}throw new Error("payee constraint scope/kind combination is invalid")}),c.some(p=>!a.some(({scope:f})=>f===p.scope)))throw new Error("payee constraint scope must be present in grant scopes");let l=c.map(({scope:p,kind:f,canonicalId:m})=>`${p}:${f}:${m}`);if(new Set(l).size!==l.length)throw new Error("payeeConstraints must not repeat after normalization")}let u=XTe("effectiveAt",e.effectiveAt),d=XTe("expiresAt",e.expiresAt);if(Date.parse(d)<=Date.parse(u))throw new Error("expiresAt must be after effectiveAt");if(e.supersedesGrantId!==void 0&&zT("supersedesGrantId",e.supersedesGrantId)===t)throw new Error("a grant cannot supersede itself");return{v:X4,grantId:t,agentId:r,version:n,budgetEpochId:i,budgetEpochMode:e.budgetEpochMode,status:e.status,currency:"USD",valuationPolicy:ete,totalMicros:o,perTransactionMicros:s,scopes:[...a].sort((l,p)=>ZTe(l.scope,p.scope)),...c!==void 0?{payeeConstraints:[...c].sort((l,p)=>ZTe(`${l.scope}:${l.kind}:${l.canonicalId}`,`${p.scope}:${p.kind}:${p.canonicalId}`))}:{},effectiveAt:u,expiresAt:d,...e.supersedesGrantId!==void 0?{supersedesGrantId:zT("supersedesGrantId",e.supersedesGrantId)}:{}}}function I7e(e,t){return e<t?-1:e>t?1:0}function md(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Ml(e,t,r){let n=new Set(r),i=Object.keys(t).filter(o=>!n.has(o));if(i.length>0)throw new Error(`${e} contains unknown field(s): ${i.sort().join(", ")}`)}function mwt(e){if(typeof e!="string")throw new Error("displayName must be a string");if(iU.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>cwt)throw new Error("displayName must be bounded, non-empty text without control characters");return t}function hwt(e){if(typeof e!="string")throw new Error("dotVisaAddress must be a string");if(iU.test(e))throw new Error("dotVisaAddress must be a valid .visa address");let t=e.trim().toLowerCase();if(!awt.test(t))throw new Error("dotVisaAddress must be a valid .visa address");return t}function Zj(e,t,r){if(typeof t!="string")throw new Error(`${e} must be a string`);if(iU.test(t)||T7e.test(t))throw new Error(`${e} must be bounded, non-empty text without control characters`);let n=t.normalize("NFC").trim();if(n.length===0||n.length>r)throw new Error(`${e} must be bounded, non-empty text without control characters`);return n}function ywt(e){if(!md(e))throw new Error("runtime context v2 must be an object");Ml("runtime context v2",e,["runtime","contextLabel","cliVersion","platform"]);let t=Zj("runtime",e.runtime,dwt),r=Zj("contextLabel",e.contextLabel,lwt),n=e.cliVersion===void 0?void 0:Zj("cliVersion",e.cliVersion,pwt),i=e.platform===void 0?void 0:Zj("platform",e.platform,fwt);return{runtime:t,contextLabel:r,...n!==void 0?{cliVersion:n}:{},...i!==void 0?{platform:i}:{}}}function yte(e){if(typeof e!="string"||!S7e.test(e))throw new Error("pairingId must be a server-generated pairing id")}function oU(e){if(e!==jt)throw new Error("protocolVersion must be 2")}function fy(e,t){if(typeof t!="string"||!uwt.test(t))throw new Error(`${e} must be a canonical lowercase UUID`)}function Co(e,t){if(!Cr(t))throw new Error(`${e} must be 32 canonical unpadded base64url bytes`)}function P7e(e){if(typeof e!="string"||!gwt.test(e))throw new Error("attachId must be a server-generated capability-attach id")}function bwt(e){if(typeof e!="string"||!e7e.includes(e))throw new Error(`capability must be one of ${e7e.join(", ")}`)}function _wt(e){if(typeof e!="string"||!py.includes(e))throw new Error(`rail must be one of ${py.join(", ")}`)}function n7e(e,t){if(typeof t!="string"||t.length===0||t.length>r7e||iU.test(t)||T7e.test(t))throw new Error(`${e} must be a bounded absolute HTTP(S) URL`);let r;try{r=new URL(t)}catch{throw new Error(`${e} must be a bounded absolute HTTP(S) URL`)}if(r.protocol!=="https:"&&r.protocol!=="http:"||r.hostname.length===0||r.username.length>0||r.password.length>0||r.hash.length>0)throw new Error(`${e} must be a bounded absolute HTTP(S) URL`);let n=r.toString();if(n.length>r7e)throw new Error(`${e} must be a bounded absolute HTTP(S) URL`);return n}function C7e(){return $T.default.randomBytes(32).toString("base64url")}function O7e(e){if(!Cr(e))throw new Error("pairing verifier must be 32 unpadded base64url bytes");return VT(e)}function vwt(e){return e.toUpperCase().replace(/[^A-Z0-9]/g,"")}function wwt(e){let t=vwt(e);return`${t.slice(0,4)}-${t.slice(4)}`}function sU(){return $T.default.randomBytes(32).toString("base64url")}function P0(e){if(!Cr(e))throw new Error("claim token must be 32 unpadded base64url bytes");return VT(`visa-agent-pairing-claim-token:v1:${e}`)}function aU(e,t){P0(t);let r=$T.default.createHash("sha256").update(`visa-agent-pairing-derived-code:v1:${e}:${t}`,"utf8").digest(),n="";for(let i=0;i<swt;i+=1)n+=hte[r[i]&x7e];return wwt(n)}function k7e(e){if(!md(e))throw new Error("pairing terms v2 must be an object");if(Ml("pairing terms v2",e,["v","pairingId","agentId","agentSelection","identityKeyJkt","ownerPublicId","displayName","dotVisaAddress","authority"]),e.v!==X4)throw new Error("pairing terms v2 must carry v=2");if(typeof e.pairingId!="string"||!S7e.test(e.pairingId))throw new Error("pairingId must be a server-issued pairing id");if(typeof e.agentId!="string"||!t7e.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(!Cr(e.identityKeyJkt))throw new Error("identityKeyJkt must be a canonical 32-byte base64url thumbprint");if(typeof e.ownerPublicId!="string"||!t7e.test(e.ownerPublicId))throw new Error("ownerPublicId must be a UUID");let t=e.agentId.toLowerCase(),r=e.ownerPublicId.toLowerCase(),n=mwt(e.displayName),i=e.dotVisaAddress===void 0?void 0:hwt(e.dotVisaAddress);if(e.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:n,identityKeyJkt:e.identityKeyJkt,...i!==void 0?{dotVisaAddress:i}:{},ownerPublicId:r,pairingId:e.pairingId,v:X4})}if(!md(e.authority))throw new Error("pairing authority must be an object or null");if(Ml("pairing authority",e.authority,["grantId","grantVersion","supersedesGrantId","budgetEpochId","budgetEpochMode","currency","valuationPolicy","totalMicros","perTransactionMicros","scopes","payeeConstraints","effectiveAt","expiresAt"]),!Array.isArray(e.authority.scopes)||e.authority.scopes.length===0||e.authority.scopes.length>py.length)throw new Error(`pairing authority scopes must contain between 1 and ${py.length} entries`);let o=new Map,s=e.authority.scopes.map(c=>{if(!md(c))throw new Error("pairing authority scope must be an object");if(Object.prototype.hasOwnProperty.call(c,"instrumentRef"))throw new Error("pairing authority scopes may not supply instrumentRef; auth resolves it");if(Ml("pairing authority scope",c,["scope","totalMicros","perTransactionMicros","instrumentCommitment"]),!py.includes(c.scope))throw new Error("invalid authorization scope");let u=c.scope;if(!Cr(c.instrumentCommitment))throw new Error("every approved scope requires a 32-byte instrumentCommitment");return o.set(u,c.instrumentCommitment),{scope:u,instrumentRef:c.instrumentCommitment,...c.totalMicros!==void 0?{totalMicros:c.totalMicros}:{},...c.perTransactionMicros!==void 0?{perTransactionMicros:c.perTransactionMicros}:{}}}),a=owt({v:X4,grantId:e.authority.grantId,agentId:t,version:e.authority.grantVersion,budgetEpochId:e.authority.budgetEpochId,budgetEpochMode:e.authority.budgetEpochMode,status:"active",currency:e.authority.currency,valuationPolicy:e.authority.valuationPolicy,totalMicros:e.authority.totalMicros,perTransactionMicros:e.authority.perTransactionMicros,scopes:s,...e.authority.payeeConstraints!==void 0?{payeeConstraints:e.authority.payeeConstraints}:{},effectiveAt:e.authority.effectiveAt,expiresAt:e.authority.expiresAt,...e.authority.supersedesGrantId!==void 0?{supersedesGrantId:e.authority.supersedesGrantId}:{}});if(e.agentSelection==="new"&&(a.version>1||a.supersedesGrantId!==void 0))throw new Error("a new-agent pairing cannot replace or supersede an existing grant; replacement authority belongs to an existing agent");if(a.version===1&&(a.budgetEpochMode!=="new"||a.supersedesGrantId!==void 0))throw new Error("an initial pairing grant must start a new budget epoch and supersede nothing");if(a.version>1&&a.supersedesGrantId===void 0)throw new Error("a replacement pairing grant must name its direct predecessor");return JSON.stringify({agentId:t,agentSelection:e.agentSelection,authority:{...a.payeeConstraints!==void 0?{payeeConstraints:a.payeeConstraints}:{},currency:a.currency,effectiveAt:a.effectiveAt,expiresAt:a.expiresAt,grantId:a.grantId,grantVersion:a.version,budgetEpochId:a.budgetEpochId,budgetEpochMode:a.budgetEpochMode,...a.supersedesGrantId!==void 0?{supersedesGrantId:a.supersedesGrantId}:{},perTransactionMicros:a.perTransactionMicros,scopes:a.scopes.map(({scope:c,totalMicros:u,perTransactionMicros:d})=>{let l=o.get(c);if(l===void 0)throw new Error("canonical scope lost its approved instrument commitment");return{instrumentCommitment:l,...d!==void 0?{perTransactionMicros:d}:{},scope:c,...u!==void 0?{totalMicros:u}:{}}}),totalMicros:a.totalMicros,valuationPolicy:a.valuationPolicy},displayName:n,identityKeyJkt:e.identityKeyJkt,...i!==void 0?{dotVisaAddress:i}:{},ownerPublicId:r,pairingId:e.pairingId,v:X4})}function Ewt(e){return VT(`visa-agent-pairing-terms:v2:${k7e(e)}`)}function gte(e){if(!md(e))throw new Error("pairing claim v2 must be an object");Ml("pairing claim v2",e,["protocolVersion","pairingId","agentId","serverNonce","claimTokenHash","identityKeyJkt","runtime"]),oU(e.protocolVersion),yte(e.pairingId),fy("agentId",e.agentId),Co("serverNonce",e.serverNonce),Co("claimTokenHash",e.claimTokenHash),Co("identityKeyJkt",e.identityKeyJkt);let t=ywt(e.runtime);return cU("visa-agent-pairing-claim:v2",{agentId:e.agentId,claimTokenHash:e.claimTokenHash,cliVersion:t.cliVersion??"",contextLabel:t.contextLabel,identityKeyJkt:e.identityKeyJkt,pairingId:e.pairingId,platform:t.platform??"",protocolVersion:String(e.protocolVersion),runtime:t.runtime,serverNonce:e.serverNonce})}function R7e(e){if(!md(e))throw new Error("pairing activation v2 must be an object");return Ml("pairing activation v2",e,["protocolVersion","pairingId","agentId","ownerPublicId","claimTokenHash","identityKeyJkt","ceremonyHash","deliveryArtifactHash"]),oU(e.protocolVersion),yte(e.pairingId),fy("agentId",e.agentId),fy("ownerPublicId",e.ownerPublicId),Co("claimTokenHash",e.claimTokenHash),Co("identityKeyJkt",e.identityKeyJkt),Co("ceremonyHash",e.ceremonyHash),Co("deliveryArtifactHash",e.deliveryArtifactHash),cU("visa-agent-pairing-activation:v2",{agentId:e.agentId,ceremonyHash:e.ceremonyHash,claimTokenHash:e.claimTokenHash,deliveryArtifactHash:e.deliveryArtifactHash,identityKeyJkt:e.identityKeyJkt,ownerPublicId:e.ownerPublicId,pairingId:e.pairingId,protocolVersion:String(e.protocolVersion)})}function N7e(e){if(!md(e))throw new Error("capability attach claim v2 must be an object");return Ml("capability attach claim v2",e,["protocolVersion","attachId","agentId","capability","serverNonce","claimTokenHash","identityKeyJkt"]),oU(e.protocolVersion),P7e(e.attachId),fy("agentId",e.agentId),bwt(e.capability),Co("serverNonce",e.serverNonce),Co("claimTokenHash",e.claimTokenHash),Co("identityKeyJkt",e.identityKeyJkt),cU("visa-agent-capability-attach-claim:v2",{agentId:e.agentId,attachId:e.attachId,capability:e.capability,claimTokenHash:e.claimTokenHash,identityKeyJkt:e.identityKeyJkt,protocolVersion:String(e.protocolVersion),serverNonce:e.serverNonce})}function bte(e){if(!md(e))throw new Error("capability attach activation v2 must be an object");return Ml("capability attach activation v2",e,["protocolVersion","attachId","agentId","ownerPublicId","identityKeyJkt","claimTokenHash","grantHash","ceremonyHash","deliveryArtifactHash","rail"]),oU(e.protocolVersion),P7e(e.attachId),fy("agentId",e.agentId),fy("ownerPublicId",e.ownerPublicId),Co("identityKeyJkt",e.identityKeyJkt),Co("claimTokenHash",e.claimTokenHash),Co("grantHash",e.grantHash),Co("ceremonyHash",e.ceremonyHash),Co("deliveryArtifactHash",e.deliveryArtifactHash),_wt(e.rail),cU("visa-agent-capability-attach-activation:v2",{agentId:e.agentId,attachId:e.attachId,ceremonyHash:e.ceremonyHash,claimTokenHash:e.claimTokenHash,deliveryArtifactHash:e.deliveryArtifactHash,grantHash:e.grantHash,identityKeyJkt:e.identityKeyJkt,ownerPublicId:e.ownerPublicId,protocolVersion:String(e.protocolVersion),rail:e.rail})}function FT(e){if(!md(e))throw new Error("pairing delivery artifact v2 must be an object");if(Ml("pairing delivery artifact v2",e,["v","kind","pairingId","agentId","ownerPublicId","identityKey","terms","ceremonyHash","issuer","activationAudience"]),e.v!==jt)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(yte(e.pairingId),fy("agentId",e.agentId),fy("ownerPublicId",e.ownerPublicId),Co("ceremonyHash",e.ceremonyHash),!md(e.identityKey))throw new Error("pairing delivery identityKey must be an object");if(Ml("pairing delivery identityKey",e.identityKey,["jkt","publicJwk"]),Co("identityKey.jkt",e.identityKey.jkt),!md(e.identityKey.publicJwk))throw new Error("pairing delivery identityKey.publicJwk must be an object");let t=e.identityKey.publicJwk;if(Ml("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");Co("identityKey.publicJwk.x",t.x);let r=VT(JSON.stringify({crv:"Ed25519",kty:"OKP",x:t.x}));if(e.identityKey.jkt!==r)throw new Error("identityKey.jkt must equal the RFC 7638 thumbprint of publicJwk");if(!md(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 n=k7e(e.terms);if(Ewt(e.terms)!==e.ceremonyHash)throw new Error("ceremonyHash must equal the hash of the exact canonical v2 terms");let i=n7e("issuer",e.issuer),o=n7e("activationAudience",e.activationAudience);return cte({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(n),v:jt})}function B7e(e){return VT(`visa-agent-pairing-delivery-artifact:v2:${FT(e)}`)}function VT(e){return $T.default.createHash("sha256").update(e,"utf8").digest("base64url")}function cU(e,t){return`${e}
|
|
8
8
|
${Object.entries(t).sort(([r],[n])=>I7e(r,n)).map(([r,n])=>`${r}=${n}`).join(`
|
|
9
9
|
`)}`}function cte(e){if(e===null||typeof e!="object")return JSON.stringify(e);if(Array.isArray(e))return`[${e.map(cte).join(",")}]`;let t=e;return`{${Object.keys(t).sort(I7e).map(r=>`${JSON.stringify(r)}:${cte(t[r])}`).join(",")}}`}var $T,i7e,Qj,Xj,MTe,qTe,Yee,Zee,s5t,Q4,a5t,as,c5t,u5t,d5t,cf,nU,ute,o7e,dte,T0,DTe,lte,s7e,l5t,e8,a7e,eU,M_,xn,LTe,Ve,c7e,u7e,d7e,l7e,Xee,ite,HT,L_,D_,p7e,f7e,af,p5t,zTe,f5t,ote,m5t,pte,m7e,h5t,fte,y5t,g5t,b5t,_5t,mte,h7e,v5t,w5t,tU,E5t,y7e,ste,A5t,HTe,$Te,x5t,P5t,C5t,Hs,Wj,VTe,KTe,WTe,Y4,Z4,Gj,Jj,R5t,N5t,B5t,j5t,U5t,M5t,b7e,q5t,D5t,dy,ly,L5t,z5t,H5t,GTe,JTe,Njr,w7e,Bjr,jjr,Ujr,Mjr,X4,W5t,ete,py,G5t,J5t,Y5t,Z5t,A7e,X5t,Q5t,YTe,ewt,twt,qjr,e7e,jt,hte,swt,x7e,S7e,t7e,iU,awt,cwt,uwt,dwt,lwt,pwt,fwt,r7e,T7e,gwt,$_=k(()=>{"use strict";$T=_e(require("node:crypto"),1),i7e=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:Qj,n:Xj,Gx:MTe,Gy:qTe,a:Yee,d:Zee,h:s5t}=i7e,Q4=32,a5t=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},as=(e="")=>{let t=new Error(e);throw a5t(t,as),t},c5t=e=>typeof e=="bigint",u5t=e=>typeof e=="string",d5t=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,cf=(e,t,r="")=>{let n=d5t(e),i=e?.length,o=t!==void 0;if(!n||o&&i!==t){let s=r&&`"${r}" `,a=o?` of length ${t}`:"",c=n?`length=${i}`:`type=${typeof e}`,u=s+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(u):new TypeError(u)}return e},nU=e=>new Uint8Array(e),ute=e=>Uint8Array.from(e),o7e=(e,t)=>e.toString(16).padStart(t,"0"),dte=e=>Array.from(cf(e)).map(t=>o7e(t,2)).join(""),T0={_0:48,_9:57,A:65,F:70,a:97,f:102},DTe=e=>{if(e>=T0._0&&e<=T0._9)return e-T0._0;if(e>=T0.A&&e<=T0.F)return e-(T0.A-10);if(e>=T0.a&&e<=T0.f)return e-(T0.a-10)},lte=e=>{let t="hex invalid";if(!u5t(e))return as(t);let r=e.length,n=r/2;if(r%2)return as(t);let i=nU(n);for(let o=0,s=0;o<n;o++,s+=2){let a=DTe(e.charCodeAt(s)),c=DTe(e.charCodeAt(s+1));if(a===void 0||c===void 0)return as(t);i[o]=a*16+c}return i},s7e=()=>globalThis?.crypto,l5t=()=>s7e()?.subtle??as("crypto.subtle must be defined, consider polyfill"),e8=(...e)=>{let t=0;for(let i of e)t+=cf(i).length;let r=nU(t),n=0;return e.forEach(i=>{r.set(i,n),n+=i.length}),r},a7e=(e=Q4)=>s7e().getRandomValues(nU(e)),eU=BigInt,M_=(e,t,r,n="bad number: out of range")=>{if(!c5t(e))throw new TypeError(n);if(t<=e&&e<r)return e;throw new RangeError(n)},xn=(e,t=Qj)=>{let r=e%t;return r>=0n?r:t+r},LTe=(1n<<255n)-1n,Ve=e=>{e<0n&&as("negative coordinate");let t=(e>>255n)*19n+(e<e);return t=(t>>255n)*19n+(t<e),t%Qj},c7e=e=>xn(e,Xj),u7e=(e,t)=>{(e===0n||t<=0n)&&as("no inverse n="+e+" mod="+t);let r=xn(e,t),n=t,i=0n,o=1n,s=1n,a=0n;for(;r!==0n;){let c=n/r,u=n%r,d=i-s*c,l=o-a*c;n=r,r=u,i=s,o=a,s=d,a=l}return n===1n?xn(i,t):as("no inverse")},d7e=e=>{let t=h7e[e];return typeof t!="function"&&as("hashes."+e+" not set"),t},l7e=e=>cf(e,64,"digest"),Xee=e=>e instanceof HT?e:as("Point expected"),ite=2n**256n,HT=class q_{static BASE;static ZERO;X;Y;Z;T;constructor(t,r,n,i){let o=ite;this.X=M_(t,0n,o),this.Y=M_(r,0n,o),this.Z=M_(n,1n,o),this.T=M_(i,0n,o),Object.freeze(this)}static CURVE(){return i7e}static fromAffine(t){return new q_(t.x,t.y,1n,Ve(t.x*t.y))}static fromBytes(t,r=!1){let n=Zee,i=ute(cf(t,Q4)),o=t[31];i[31]=o&-129;let s=f7e(i);M_(s,0n,r?ite:Qj);let c=Ve(s*s),u=xn(c-1n),d=Ve(n*c+1n),{isValid:l,value:p}=f5t(u,d);l||as("bad point: y not sqrt");let f=(p&1n)===1n,m=(o&128)!==0;return!r&&p===0n&&m&&as("bad point: x==0, isLastByteOdd"),m!==f&&(p=xn(-p)),new q_(p,s,1n,Ve(p*s))}static fromHex(t,r){return q_.fromBytes(lte(t),r)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=Yee,r=Zee,n=this;if(n.is0())return as("bad point: ZERO");let{X:i,Y:o,Z:s,T:a}=n,c=Ve(i*i),u=Ve(o*o),d=Ve(s*s),l=Ve(d*d),p=Ve(c*t),f=Ve(d*(p+u)),m=xn(l+Ve(r*Ve(c*u)));if(f!==m)return as("bad point: equation left != right (1)");let h=Ve(i*o),y=Ve(s*a);return h!==y?as("bad point: equation left != right (2)"):this}equals(t){let{X:r,Y:n,Z:i}=this,{X:o,Y:s,Z:a}=Xee(t),c=Ve(r*a),u=Ve(o*i),d=Ve(n*a),l=Ve(s*i);return c===u&&d===l}is0(){return this.equals(D_)}negate(){return new q_(xn(-this.X),this.Y,this.Z,xn(-this.T))}double(){let{X:t,Y:r,Z:n}=this,i=Yee,o=Ve(t*t),s=Ve(r*r),a=Ve(2n*n*n),c=Ve(i*o),u=xn(t+r),d=xn(Ve(u*u)-o-s),l=xn(c+s),p=xn(l-a),f=xn(c-s),m=Ve(d*p),h=Ve(l*f),y=Ve(d*f),v=Ve(p*l);return new q_(m,h,v,y)}add(t){let{X:r,Y:n,Z:i,T:o}=this,{X:s,Y:a,Z:c,T:u}=Xee(t),d=Yee,l=Zee,p=Ve(r*s),f=Ve(n*a),m=Ve(Ve(o*l)*u),h=Ve(i*c),y=xn(Ve(xn(r+n)*xn(s+a))-p-f),v=xn(h-m),E=xn(h+m),_=xn(f-Ve(d*p)),w=Ve(y*v),A=Ve(E*_),x=Ve(y*_),S=Ve(v*E);return new q_(w,A,S,x)}subtract(t){return this.add(Xee(t).negate())}multiply(t,r=!0){if(!r&&t===0n||(M_(t,1n,Xj),!r&&this.is0()))return D_;if(t===1n)return this;if(this.equals(L_))return x5t(t).p;let n=D_,i=L_;for(let o=this;t>0n;o=o.double(),t>>=1n)t&1n?n=n.add(o):r&&(i=i.add(o));return n}multiplyUnsafe(t){return this.multiply(t,!1)}toAffine(){let{X:t,Y:r,Z:n}=this;if(this.equals(D_))return{x:0n,y:1n};let i=u7e(n,Qj);Ve(n*i)!==1n&&as("invalid inverse");let o=Ve(t*i),s=Ve(r*i);return{x:o,y:s}}toBytes(){let{x:t,y:r}=this.toAffine(),n=p7e(r);return n[31]|=t&1n?128:0,n}toHex(){return dte(this.toBytes())}clearCofactor(){return this.multiply(eU(s5t),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(Xj/2n,!1).double();return Xj%2n&&(t=t.add(this)),t.is0()}},L_=new HT(MTe,qTe,1n,xn(MTe*qTe)),D_=new HT(0n,1n,1n,0n);HT.BASE=L_;HT.ZERO=D_;p7e=e=>lte(o7e(M_(e,0n,ite),64)).reverse(),f7e=e=>eU("0x"+dte(ute(cf(e)).reverse())),af=(e,t)=>{let r=e;for(;t-- >0n;)r=Ve(r*r);return r},p5t=e=>{let t=Ve(e*e),r=Ve(t*e),n=Ve(af(r,2n)*r),i=Ve(af(n,1n)*e),o=Ve(af(i,5n)*i),s=Ve(af(o,10n)*o),a=Ve(af(s,20n)*s),c=Ve(af(a,40n)*a),u=Ve(af(c,80n)*c),d=Ve(af(u,80n)*c),l=Ve(af(d,10n)*o);return{pow_p_5_8:Ve(af(l,2n)*e),b2:r}},zTe=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,f5t=(e,t)=>{let r=Ve(t*Ve(t*t)),n=Ve(Ve(r*r)*t),i=p5t(Ve(e*n)).pow_p_5_8,o=Ve(e*Ve(r*i)),s=Ve(t*Ve(o*o)),a=o,c=Ve(o*zTe),u=s===e,d=s===xn(-e),l=s===xn(-e*zTe);return u&&(o=a),(d||l)&&(o=c),(xn(o)&1n)===1n&&(o=xn(-o)),{isValid:u||d,value:o}},ote=e=>c7e(f7e(e)),m5t=(...e)=>Promise.resolve(d7e("sha512Async")(e8(...e))).then(l7e),pte=(...e)=>l7e(d7e("sha512")(e8(...e))),m7e=e=>{let t=ute(e),r=t.slice(0,32);r[0]&=248,r[31]&=127,r[31]|=64;let n=t.slice(32,64),i=ote(r),o=L_.multiply(i),s=o.toBytes();return{head:r,prefix:n,scalar:i,point:o,pointBytes:s}},h5t=e=>m5t(cf(e,Q4)).then(m7e),fte=e=>m7e(pte(cf(e,Q4))),y5t=e=>fte(e).pointBytes,g5t=e=>e.finish(pte(e.hashable)),b5t=(e,t,r)=>{let{pointBytes:n,scalar:i}=e,o=ote(t),s=L_.multiply(o).toBytes();return{hashable:e8(s,n,r),finish:u=>{let d=c7e(o+ote(u)*i);return cf(e8(s,p7e(d)),64)}}},_5t=(e,t)=>{let r=cf(e),n=fte(t),i=pte(n.prefix,r);return g5t(b5t(n,i,r))},mte=Object.freeze({bytesToHex:dte,hexToBytes:lte,concatBytes:e8,mod:xn,invert:u7e,randomBytes:a7e}),h7e={sha512Async:async e=>{let t=l5t(),r=e8(e);return nU(await t.digest("SHA-512",r.buffer))},sha512:void 0},v5t=e=>(e=e===void 0?a7e(Q4):e,cf(e,Q4)),w5t=Object.freeze({getExtendedPublicKeyAsync:h5t,getExtendedPublicKey:fte,randomSecretKey:v5t}),tU=8,E5t=256,y7e=Math.ceil(E5t/tU)+1,ste=2**(tU-1),A5t=()=>{let e=[],t=L_,r=t;for(let n=0;n<y7e;n++){r=t,e.push(r);for(let i=1;i<ste;i++)r=r.add(t),e.push(r);t=r.double()}return e},HTe=void 0,$Te=(e,t)=>{let r=t.negate();return e?r:t},x5t=e=>{let t=HTe||(HTe=A5t()),r=D_,n=L_,i=2**tU,o=i,s=eU(i-1),a=eU(tU);for(let c=0;c<y7e;c++){let u=Number(e&s);e>>=a,u>ste&&(u-=o,e+=1n);let d=c*ste,l=d,p=d+Math.abs(u)-1,f=c%2!==0,m=u<0;u===0?n=n.add($Te(f,t[l])):r=r.add($Te(m,t[p]))}return e!==0n&&as("invalid wnaf"),{p:r,f:n}};P5t=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}),C5t=class{blockLen;outputLen;canXOF=!1;padOffset;isLE;buffer;view;finished=!1;length=0;pos=0;destroyed=!1;constructor(e,t,r,n){this.blockLen=e,this.outputLen=t,this.padOffset=r,this.isLE=n,this.buffer=new Uint8Array(e),this.view=Qee(this.buffer)}update(e){FTe(this),g7e(e);let{view:t,buffer:r,blockLen:n}=this,i=e.length;for(let o=0;o<i;){let s=Math.min(n-this.pos,i-o);if(s===n){let a=Qee(e);for(;n<=i-o;o+=n)this.process(a,o);continue}r.set(e.subarray(o,o+s),this.pos),this.pos+=s,o+=s,this.pos===n&&(this.process(t,0),this.pos=0)}return this.length+=e.length,this.roundClean(),this}digestInto(e){FTe(this),T5t(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:i}=this,{pos:o}=this;t[o++]=128,ate(this.buffer.subarray(o)),this.padOffset>n-o&&(this.process(r,0),o=0);for(let d=o;d<n;d++)t[d]=0;r.setBigUint64(n-8,BigInt(this.length*8),i),this.process(r,0);let s=Qee(e),a=this.outputLen;if(a%4)throw new Error("_sha2: outputLen must be aligned to 32bit");let c=a/4,u=this.get();if(c>u.length)throw new Error("_sha2: outputLen bigger than state");for(let d=0;d<c;d++)s.setUint32(4*d,u[d],i)}digest(){let{buffer:e,outputLen:t}=this;this.digestInto(e);let r=e.slice(0,t);return this.destroy(),r}_cloneInto(e){e||=new this.constructor,e.set(...this.get());let{blockLen:t,buffer:r,length:n,finished:i,destroyed:o,pos:s}=this;return e.destroyed=o,e.finished=i,e.length=n,e.pos=s,n%t&&e.buffer.set(r),e}clone(){return this._cloneInto()}},Hs=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),Wj=BigInt(2**32-1),VTe=BigInt(32);KTe=(e,t,r)=>e>>>r,WTe=(e,t,r)=>e<<32-r|t>>>r,Y4=(e,t,r)=>e>>>r|t<<32-r,Z4=(e,t,r)=>e<<32-r|t>>>r,Gj=(e,t,r)=>e<<64-r|t>>>r-32,Jj=(e,t,r)=>e>>>r-32|t<<64-r;R5t=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),N5t=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,B5t=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),j5t=(e,t,r,n,i)=>t+r+n+i+(e/2**32|0)|0,U5t=(e,t,r,n,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(i>>>0),M5t=(e,t,r,n,i,o)=>t+r+n+i+o+(e/2**32|0)|0,b7e=k5t(["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))),q5t=b7e[0],D5t=b7e[1],dy=new Uint32Array(80),ly=new Uint32Array(80),L5t=class extends C5t{constructor(e){super(128,e,16,!1)}get(){let{Ah:e,Al:t,Bh:r,Bl:n,Ch:i,Cl:o,Dh:s,Dl:a,Eh:c,El:u,Fh:d,Fl:l,Gh:p,Gl:f,Hh:m,Hl:h}=this;return[e,t,r,n,i,o,s,a,c,u,d,l,p,f,m,h]}set(e,t,r,n,i,o,s,a,c,u,d,l,p,f,m,h){this.Ah=e|0,this.Al=t|0,this.Bh=r|0,this.Bl=n|0,this.Ch=i|0,this.Cl=o|0,this.Dh=s|0,this.Dl=a|0,this.Eh=c|0,this.El=u|0,this.Fh=d|0,this.Fl=l|0,this.Gh=p|0,this.Gl=f|0,this.Hh=m|0,this.Hl=h|0}process(e,t){for(let E=0;E<16;E++,t+=4)dy[E]=e.getUint32(t),ly[E]=e.getUint32(t+=4);for(let E=16;E<80;E++){let _=dy[E-15]|0,w=ly[E-15]|0,A=Y4(_,w,1)^Y4(_,w,8)^KTe(_,w,7),x=Z4(_,w,1)^Z4(_,w,8)^WTe(_,w,7),S=dy[E-2]|0,I=ly[E-2]|0,T=Y4(S,I,19)^Gj(S,I,61)^KTe(S,I,6),C=Z4(S,I,19)^Jj(S,I,61)^WTe(S,I,6),j=B5t(x,C,ly[E-7],ly[E-16]),M=j5t(j,A,T,dy[E-7],dy[E-16]);dy[E]=M|0,ly[E]=j|0}let{Ah:r,Al:n,Bh:i,Bl:o,Ch:s,Cl:a,Dh:c,Dl:u,Eh:d,El:l,Fh:p,Fl:f,Gh:m,Gl:h,Hh:y,Hl:v}=this;for(let E=0;E<80;E++){let _=Y4(d,l,14)^Y4(d,l,18)^Gj(d,l,41),w=Z4(d,l,14)^Z4(d,l,18)^Jj(d,l,41),A=d&p^~d&m,x=l&f^~l&h,S=U5t(v,w,x,D5t[E],ly[E]),I=M5t(S,y,_,A,q5t[E],dy[E]),T=S|0,C=Y4(r,n,28)^Gj(r,n,34)^Gj(r,n,39),j=Z4(r,n,28)^Jj(r,n,34)^Jj(r,n,39),M=r&i^r&s^i&s,U=n&o^n&a^o&a;y=m|0,v=h|0,m=p|0,h=f|0,p=d|0,f=l|0,{h:d,l}=I0(c|0,u|0,I|0,T|0),c=s|0,u=a|0,s=i|0,a=o|0,i=r|0,o=n|0;let R=R5t(T,j,U);r=N5t(R,I,C,M),n=R|0}({h:r,l:n}=I0(this.Ah|0,this.Al|0,r|0,n|0)),{h:i,l:o}=I0(this.Bh|0,this.Bl|0,i|0,o|0),{h:s,l:a}=I0(this.Ch|0,this.Cl|0,s|0,a|0),{h:c,l:u}=I0(this.Dh|0,this.Dl|0,c|0,u|0),{h:d,l}=I0(this.Eh|0,this.El|0,d|0,l|0),{h:p,l:f}=I0(this.Fh|0,this.Fl|0,p|0,f|0),{h:m,l:h}=I0(this.Gh|0,this.Gl|0,m|0,h|0),{h:y,l:v}=I0(this.Hh|0,this.Hl|0,y|0,v|0),this.set(r,n,i,o,s,a,c,u,d,l,p,f,m,h,y,v)}roundClean(){ate(dy,ly)}destroy(){this.destroyed=!0,ate(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},z5t=class extends L5t{Ah=Hs[0]|0;Al=Hs[1]|0;Bh=Hs[2]|0;Bl=Hs[3]|0;Ch=Hs[4]|0;Cl=Hs[5]|0;Dh=Hs[6]|0;Dl=Hs[7]|0;Eh=Hs[8]|0;El=Hs[9]|0;Fh=Hs[10]|0;Fl=Hs[11]|0;Gh=Hs[12]|0;Gl=Hs[13]|0;Hh=Hs[14]|0;Hl=Hs[15]|0;constructor(){super(64)}},H5t=I5t(()=>new z5t,P5t(3)),GTe=h7e;GTe.sha512||(GTe.sha512=e=>H5t(e));JTe=32;Njr=mte.bytesToHex,w7e=mte.hexToBytes,Bjr=mte.concatBytes;jjr=new TextEncoder;Ujr=w7e("302e020100300506032b657004220420"),Mjr=w7e("302a300506032b6570032100"),X4=2,W5t=["new","continue"],ete="nominal_usd_usdc_parity",py=["card:vic","wallet:x402"],G5t=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,J5t=/^[A-Za-z0-9_-]{43}$/,Y5t=/^(?:0|[1-9][0-9]*)$/,Z5t=/^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.\d{1,6})?(?:Z|[+-]\d{2}:\d{2})$/,A7e=/[\u0000-\u001f\u007f]/,X5t=2147483647,Q5t=9223372036854775807n,YTe=100,ewt=512,twt=/^0x[0-9a-f]{40}$/,qjr=new TextEncoder;e7e=["card","wallet"],jt=2,hte="ABCDEFGHJKLMNPQRSTUVWXYZ23456789",swt=8,x7e=hte.length-1;if((hte.length&x7e)!==0)throw new Error("agent pairing code alphabet must contain a power-of-two number of symbols");S7e=/^ap_[A-Za-z0-9_-]{24}$/,t7e=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i,iU=/[\p{Cc}\p{Cf}]/u,awt=/^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?\.visa$/,cwt=255,uwt=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,dwt=100,lwt=200,pwt=64,fwt=100,r7e=2048,T7e=/[\u0080-\u009f\u2028\u2029]/;gwt=/^ca_[A-Za-z0-9_-]{24}$/;});var M7e={};Pi(M7e,{VisaBindingRequiredError:()=>uf,jkt:()=>df,readSeed:()=>KT});function df(e){let t=JSON.stringify({crv:e.crv,kty:e.kty,x:e.x});return j7e.createHash("sha256").update(t,"utf8").digest("base64url")}function KT(e){let t=new Uint8Array(U7e.readFileSync(e));if(t.length!==32)throw new Error("Subway identity key must be a 32-byte Ed25519 seed");return t}var j7e,U7e,uf,WT=k(()=>{"use strict";j7e=_e(require("node:crypto")),U7e=_e(require("node:fs"));uf=class extends Error{reason;constructor(t="No active .visa mesh admission binding is stored. Identity pairing does not grant a .visa name or TAP/channel binding; configure that capability separately when its approval flow is available."){super(t),this.name="VisaBindingRequiredError",this.reason="missing_or_incompatible"}}});function _te(e,t){switch(e){case"name_not_found":return new q7e(t);case"delivery_failed":return new D7e(t);case"timeout":return new GT(t);case"not_registered":return new L7e;case"register_failed":return new uU(t);case"invalid_message":return new z7e(t);case"rate_limited":return new H7e(t);default:return new lf(e,t)}}var lf,q7e,D7e,GT,L7e,$s,z7e,uU,H7e,vte=k(()=>{"use strict";lf=class extends Error{code;constructor(e,t){super(t),this.name="SubwayError",this.code=e}},q7e=class extends lf{constructor(e){super("name_not_found",`Agent not registered: ${e}`),this.name="NameNotFoundError"}},D7e=class extends lf{constructor(e){super("delivery_failed",e),this.name="DeliveryFailedError"}},GT=class extends lf{constructor(e="RPC call timed out"){super("timeout",e),this.name="TimeoutError"}},L7e=class extends lf{constructor(){super("not_registered","Client has not registered with the bridge"),this.name="NotRegisteredError"}},$s=class extends lf{constructor(e){super("connection_failed",e),this.name="ConnectionError"}},z7e=class extends lf{constructor(e){super("invalid_message",e),this.name="InvalidMessageError"}},uU=class extends lf{constructor(e){super("register_failed",e),this.name="RegisterFailedError"}},H7e=class extends lf{constructor(e="Rate limited"){super("rate_limited",e),this.name="RateLimitedError"}}});var $7e,wte=k(()=>{"use strict";$7e=(e=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(e,{get:(t,r)=>(typeof require<"u"?require:t)[r]}):e)(function(e){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+e+'" is not supported')})});function G_(e){return e.includes(".")?e:`${e}.relay`}function Ete(){return typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,e=>{let t=Math.random()*16|0;return(e==="x"?t:t&3|8).toString(16)})}function Awt(){if(typeof WebSocket<"u")return WebSocket;try{let e=$7e("ws");return e.default??e}catch{return}}function xwt(e,t,r){return Math.min(Math.max(e,t),r)}function Jwt(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function PIe(e,t,r=""){let n=Jwt(e),i=e?.length;if(!n||t!==void 0){let s=r&&`"${r}" `,a="",c=n?`length=${i}`:`type=${typeof e}`,u=s+"expected Uint8Array"+a+", got "+c;throw n?new RangeError(u):new TypeError(u)}return e}function Z7e(e,t=!0){if(e.destroyed)throw new Error("Hash instance has been destroyed");if(t&&e.finished)throw new Error("Hash#digest() has already been called")}function Ywt(e,t){PIe(e,void 0,"digestInto() output");let r=t.outputLen;if(e.length<r)throw new RangeError('"digestInto() output" expected to be of length >='+r)}function JT(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function Tte(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function ff(e,t){return e<<32-t|e>>>t}function CIe(e,t={}){let r=(i,o)=>e(o).update(i).digest(),n=e(void 0);return r.outputLen=n.outputLen,r.blockLen=n.blockLen,r.canXOF=n.canXOF,r.create=i=>e(i),Object.assign(r,t),Object.freeze(r)}function Zwt(e,t,r){return e&t^~e&r}function Xwt(e,t,r){return e&t^e&r^t&r}function Qwt(e,t=!1){return t?{h:Number(e&dU),l:Number(e>>X7e&dU)}:{h:Number(e>>X7e&dU)|0,l:Number(e&dU)|0}}function e4t(e,t=!1){let r=e.length,n=new Uint32Array(r),i=new Uint32Array(r);for(let o=0;o<r;o++){let{h:s,l:a}=Qwt(e[o],t);[n[o],i[o]]=[s,a]}return[n,i]}function O0(e,t,r,n){let i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:i|0}}function y4t(e){return Hwt(e)}function g4t(e,t){return Vwt(t,e)}function _4t(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function E4t(e){let t=b4t(m4t(e.payload)),r=`${e.messageId}
|
|
10
10
|
${e.senderPeerId}
|
|
@@ -44,7 +44,7 @@ ${e.nonce}`;return v4t.encode(r)}function A4t(e,t,r,n,i,o,s){return E4t({message
|
|
|
44
44
|
`)}}catch(n){throw R8t(n)?new ere(e,r,n):n}return{installed:!0,configPath:r,message:e.postInstallHint}}function L8t(e){for(let t of e.split(`
|
|
45
45
|
`)){if(t.trim()===""||NU(t)>0)continue;let r=t.trim();if(!(r.startsWith("#")||r==="---"||r==="..."||r.startsWith("- "))&&!/^[^\s:#][^:]*:(\s|$)/.test(r))return!1}return!0}function Qte(e,t){return e?e.command===t.command&&Array.isArray(e.args)&&e.args.length===t.args.length&&t.args.every((r,n)=>e.args[n]===r):!1}function vPe(e,t,r=UU()){let n=e.configFormat??"json";try{let i=Yt.existsSync(t),o=i?Yt.readFileSync(t,"utf-8"):"",s;if(n==="toml"){if(Qte(sre(o,"visa-cli"),r))return{status:"already-mounted",configPath:t};s=yPe(o,"visa-cli",r)}else if(n==="yaml"){if(i&&!L8t(o))return{status:"error",configPath:t,error:`existing config at ${t} does not look like editable YAML \u2014 fix or remove it, then re-run`};if(Qte(cre(o,"visa-cli"),r))return{status:"already-mounted",configPath:t};s=bPe(o,"visa-cli",r)}else{let a={};if(i){try{a=JSON.parse(o)}catch{return{status:"error",configPath:t,error:`existing config at ${t} is not valid JSON \u2014 fix or remove it, then re-run`}}if(!a||typeof a!="object"||Array.isArray(a))return{status:"error",configPath:t,error:`existing config at ${t} is not a JSON object \u2014 fix or remove it, then re-run`}}if(Qte(nre(a,e.configKey)?.["visa-cli"],r))return{status:"already-mounted",configPath:t};mPe(a,e.configKey)["visa-cli"]=e.buildEntry?e.buildEntry(r):r,s=JSON.stringify(a,null,2)+`
|
|
46
46
|
`}return Yt.mkdirSync(Nt.dirname(t),{recursive:!0}),Yt.writeFileSync(t,s),{status:"mounted",configPath:t}}catch(i){return{status:"error",configPath:t,error:i instanceof Error?i.message:String(i)}}}function wPe(e,t="global"){let r=t==="project"?Nt.join(process.cwd(),".mcp.json"):tre(e);if(!Yt.existsSync(r))return{removed:!1,configPath:r};let n=ire(e,t);if(n==="toml"){let s=Yt.readFileSync(r,"utf-8");return sre(s,"visa-cli")?(Yt.writeFileSync(r,U8t(s,"visa-cli")),{removed:!0,configPath:r}):{removed:!1,configPath:r}}if(n==="yaml"){let s=Yt.readFileSync(r,"utf-8");return cre(s,"visa-cli")?(Yt.writeFileSync(r,D8t(s,"visa-cli")),{removed:!0,configPath:r}):{removed:!1,configPath:r}}let i;try{i=JSON.parse(Yt.readFileSync(r,"utf-8"))}catch{return{removed:!1,configPath:r}}let o=nre(i,e.configKey);return!o||!o["visa-cli"]?{removed:!1,configPath:r}:(delete o["visa-cli"],Yt.writeFileSync(r,JSON.stringify(i,null,2)+`
|
|
47
|
-
`),{removed:!0,configPath:r})}function ure(e,t="global"){let r=t==="project"?Nt.join(process.cwd(),".mcp.json"):tre(e);if(!Yt.existsSync(r))return!1;let n=ire(e,t);if(n==="toml")try{let i=Yt.readFileSync(r,"utf-8");return!!sre(i,"visa-cli")}catch{return!1}if(n==="yaml")try{let i=Yt.readFileSync(r,"utf-8");return!!cre(i,"visa-cli")}catch{return!1}try{let i=JSON.parse(Yt.readFileSync(r,"utf-8"));return!!nre(i,e.configKey)?.["visa-cli"]}catch{return!1}}var Yt,Nt,uPe,Tn,k8t,ere,jU,gPe,dre=k(()=>{"use strict";Yt=_e(require("fs")),Nt=_e(require("path")),uPe=_e(require("os")),Tn=uPe.homedir(),k8t=["Claude_","Anthropic.ClaudeDesktop_"],ere=class extends Error{constructor(r,n,i){super(N8t(r,n,i));this.client=r;this.configPath=n;this.name="McpConfigAccessError"}client;configPath};jU=[{id:"claude",displayName:"Claude Code",globalConfigPath:Nt.join(Tn,".claude.json"),configKey:"mcpServers",detectPaths:[Nt.join(Tn,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:pPe(),configKey:"mcpServers",detectPaths:fPe(),postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:Nt.join(Tn,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[Nt.join(Tn,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:Nt.join(Tn,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[Nt.join(Tn,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:Nt.join(Tn,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[Nt.join(Tn,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:Xte({win32:Nt.join(r7(),"Roo","mcp_settings.json"),posix:Nt.join(Tn,".config","Roo","mcp_settings.json")}),configKey:"mcpServers",detectPaths:[Nt.join(Tn,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:Nt.join(Tn,".vscode","mcp.json"),configKey:"servers",detectPaths:[Nt.join(Tn,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:Xte({win32:Nt.join(r7(),"Zed","settings.json"),posix:Nt.join(Tn,".config","zed","settings.json")}),configKey:"context_servers",detectPaths:Xte({win32:[Nt.join(r7(),"Zed")],posix:[Nt.join(Tn,".config","zed")]}),postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})},{id:"codex",displayName:"Codex",globalConfigPath:Nt.join(Tn,".codex","config.toml"),configKey:"mcp_servers",configFormat:"toml",detectPaths:[Nt.join(Tn,".codex")],postInstallHint:"Restart Codex to connect."},{id:"openclaw",displayName:"OpenClaw",globalConfigPath:Nt.join(Tn,".openclaw","openclaw.json"),configKey:"mcp.servers",detectPaths:[Nt.join(Tn,".openclaw")],postInstallHint:"Restart OpenClaw (or reload its config) to connect."},{id:"hermes",displayName:"Hermes",globalConfigPath:Nt.join(Tn,".hermes","config.yaml"),configKey:"mcp_servers",configFormat:"yaml",detectPaths:[Nt.join(Tn,".hermes")],postInstallHint:"Restart Hermes to connect."}];gPe="mcp_servers"});function lre(e,t={}){let r=t.home??MU.homedir(),n=t.cwd??process.cwd();switch(e){case"openclaw":return ri.join(r,".openclaw","skills");case"hermes":return ri.join(r,".hermes","skills");case"claude-code":case"claude":return ri.join(r,".claude","skills");case"default":case"agentskills":return ri.join(n,".agents","skills");default:return null}}function z8t(e={}){let t=e.home??MU.homedir(),r=[["openclaw",ri.join(t,".openclaw")],["hermes",ri.join(t,".hermes")],["claude-code",ri.join(t,".claude")]];for(let[n,i]of r)if(Ks.existsSync(i))return{runtime:n,base:lre(n,e)};return{runtime:"default",base:lre("default",e)}}function EPe(e){let t=[ri.join(e,"skills",j0),ri.join(e,"..","skills",j0),ri.join(e,"..","..","visa-cli-openclaw","skills",j0),ri.join(e,"..","..","..","visa-cli-openclaw","skills",j0)];for(let r of t)if(Ks.existsSync(ri.join(r,"SKILL.md")))return r;return null}function H8t(e){let{bundledDir:t,base:r,force:n}=e;if(!Ks.existsSync(ri.join(t,"SKILL.md")))throw new Error(`bundled skill not found at ${t} (no SKILL.md)`);let i=ri.join(r,j0),o=Ks.existsSync(i)&&Ks.readdirSync(i).length>0;if(o&&!n)throw new Error(`${i} already exists \u2014 re-run with --force to overwrite, or --print to view the skill.`);return Ks.mkdirSync(r,{recursive:!0}),o&&Ks.rmSync(i,{recursive:!0,force:!0}),Ks.cpSync(t,i,{recursive:!0}),{installedDir:i,files:$8t(i),overwrote:o}}function $8t(e){let t=[],r=(n,i)=>{for(let o of Ks.readdirSync(n,{withFileTypes:!0})){let s=i?ri.join(i,o.name):o.name;o.isDirectory()?r(ri.join(n,o.name),s):t.push(s)}};return r(e,""),t.sort()}function APe(e){return Ks.readFileSync(ri.join(e,"SKILL.md"),"utf8")}function V8t(e){let{runtime:t}=e;if(!F8t.includes(t))return{runtime:t,status:"skipped",path:null,note:t==="claude-code"||t==="claude"?"Claude Code mounts MCP servers via its own config \u2014 run `visa-cli connect claude` to have the CLI write it.":"no known MCP config for this target \u2014 the skill can drive the raw `visa` CLI instead."};let r=n7(t),n=e.home?ri.join(e.home,ri.relative(MU.homedir(),r.globalConfigPath)):r.globalConfigPath,i=vPe(r,n,UU());return i.status==="error"?{runtime:t,status:"error",path:i.configPath,note:i.error}:{runtime:t,status:i.status,path:i.configPath}}function xPe(e){let t,r;if(e.dir)t=ri.resolve(e.dir),r="custom";else if(e.runtime){let o=lre(e.runtime,e);if(!o)throw new Error(`unknown runtime "${e.runtime}" \u2014 use openclaw | hermes | claude-code | default, or pass --dir.`);t=o,r=e.runtime}else{let o=z8t(e);t=o.base,r=o.runtime}let n=H8t({bundledDir:e.bundledDir,base:t,force:e.force}),i=e.mount===!1?{runtime:r,status:"skipped",path:null,note:"mount disabled with --no-mount"}:V8t({runtime:r,home:e.home});return{skill:j0,runtime:r,installedDir:n.installedDir,files:n.files,overwrote:n.overwrote,mount:i}}var Ks,MU,ri,j0,F8t,SPe=k(()=>{"use strict";Ks=_e(require("fs")),MU=_e(require("os")),ri=_e(require("path"));dre();j0="pair-visa-agent";F8t=["openclaw","hermes"]});function K8t(e,t={}){let r=t.execPath??process.execPath,n=t.cliEntry??process.argv[1],i=String(t.intervalSec??5),o=String(t.timeoutSec??840),s=["agent","enroll-claim",...e?["--url",e]:[],"--interval",i,"--timeout",o,"--format","json"];return n?{cmd:r,args:[n,...s]}:{cmd:"visa",args:s}}async function IPe(e,t=TPe.spawn){try{let{cmd:r,args:n}=K8t(e),i=t(r,n,{detached:!0,stdio:"ignore"});return typeof i.once!="function"?i.pid===void 0?{started:!1,error:"background process did not report a pid"}:(i.unref(),{started:!0,pid:i.pid}):await new Promise(o=>{let s=!1,a=c=>{s||(s=!0,o(c))};i.once?.("error",c=>{a({started:!1,error:c.message||"background process failed to start"})}),i.once?.("spawn",()=>{if(i.pid===void 0){a({started:!1,error:"background process did not report a pid"});return}i.unref(),a({started:!0,pid:i.pid})})})}catch(r){return{started:!1,error:r instanceof Error?r.message:"background process failed to start"}}}var TPe,PPe=k(()=>{"use strict";TPe=require("node:child_process")});function RPe(e=process.env){return e[G8t]==="true"}function t6(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function LU(e){return typeof e=="string"&&J8t.test(e)}function mre(e){return typeof e=="string"&&Y8t.test(e)}function qU(e){return typeof e=="string"&&Z8t.test(e)}function zU(e){return typeof e=="string"&&py.includes(e)}function NPe(e){return e===null||typeof e=="string"&&e.length>0&&e.length<=Q8t&&!e3t.test(e)}function n3t(e){if(typeof e!="string")return!1;let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}function i3t(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost"||t==="::1")return!0;let r=t.split(".");return r.length===4&&r[0]==="127"&&r.every(n=>/^\d{1,3}$/.test(n)&&Number(n)<=255)}function BPe(e){if(e.length===0||e.length>X8t)throw new Error("auth URL must be a bounded absolute URL");let t;try{t=new URL(e)}catch{throw new Error("auth URL must be a bounded absolute URL")}if(t.username.length>0||t.password.length>0||t.search.length>0||t.hash.length>0||t.protocol!=="https:"&&!(t.protocol==="http:"&&i3t(t.hostname)))throw new Error("auth URL must use HTTPS (or HTTP on a loopback host) without credentials");let r=t.pathname.replace(/\/+$/,"");return`${t.origin}${r===""||r==="/"?"":r}`}function o3t(e){if(typeof e!="string")return!1;try{return BPe(e)===e}catch{return!1}}function jPe(e){return t6(e)&&e.protocolVersion===jt&&LU(e.attachId)&&mre(e.agentId)&&o3t(e.authUrl)&&e.capability===p8&&zU(e.rail)&&e.currency==="USD"&&qU(e.aggregateCeilingMicros)&&qU(e.perTransactionMicros)&&NPe(e.instrumentLabel)&&Cr(e.serverNonce)&&Cr(e.identityKeyJkt)&&Cr(e.claimToken)&&n3t(e.createdAt)}function hre(e,t=i7){if(!LU(e))throw new Error("attach id must use the canonical ca_ + 24 base64url form");return fre.join(t,`${e}.json`)}function s3t(e){xy.mkdirSync(e,{recursive:!0,mode:448});let t=xy.lstatSync(e);if(t.isSymbolicLink()||!t.isDirectory())throw new Error("capability-attach directory must be a real directory, not a symlink");xy.chmodSync(e,448),ac(e)}function a3t(e,t=i7){if(!jPe(e))throw new Error("refusing to write an invalid capability-attach ceremony record");s3t(t),B0(hre(e.attachId,t),JSON.stringify(e,null,2))}function yre(e,t=i7){if(!LU(e))return null;let r=e6(hre(e,t));if(r===null)return null;let n;try{n=JSON.parse(r)}catch{throw new Error(`local capability-attach state for ${e} contains invalid JSON`)}if(!jPe(n)||n.attachId!==e)throw new Error(`local capability-attach state for ${e} is invalid or misbound`);return n}function CPe(e,t=i7){yre(e,t)&&ac(t)&&xy.rmSync(hre(e,t),{force:!0})}function DU(e,t="capability-attach operation aborted"){return e.reason instanceof Error?e.reason:new Error(t)}function pre(e,t){return t?t.aborted?Promise.reject(DU(t)):new Promise((r,n)=>{let i=()=>n(DU(t));t.addEventListener("abort",i,{once:!0}),e.then(o=>{t.removeEventListener("abort",i),r(o)},o=>{t.removeEventListener("abort",i),n(o)})}):e}async function gre(e,t,r,n={}){let i=new AbortController,o=()=>{let a=n.signal?.reason;i.abort(a instanceof Error?a:new Error("capability-attach operation aborted"))};n.signal?.aborted?o():n.signal?.addEventListener("abort",o,{once:!0});let s=setTimeout(()=>i.abort(new Error(`capability-attach request timed out after ${OPe}ms`)),OPe);s.unref?.();try{if(i.signal.aborted)throw DU(i.signal);let a=await pre(r(e,{...t,headers:{"X-Source":"cli","X-Visa-CLI-Version":W8t,...t.headers??{}},redirect:"error",signal:i.signal}),i.signal),c;try{c=await pre(a.json(),i.signal)}catch{if(i.signal.aborted)throw DU(i.signal);c={}}if(!a.ok&&a.status!==202){let u=t6(c)?c:{},d=typeof u.error=="string"?u.error:void 0,l=typeof u.detail=="string"?u.detail:void 0;throw new Error(d??l??`capability-attach server returned ${a.status}`)}return{status:a.status,body:c}}finally{clearTimeout(s),n.signal?.removeEventListener("abort",o)}}function UPe(e,t){return Buffer.from(t8(e,Buffer.from(t,"utf8"))).toString("base64url")}function MPe(e,t,r){let n=o7(e,r);if(!n||!hf(n))throw new Error(`no paired identity for agent ${e} on this machine \u2014 run \`visa agent pair\` first`);if(n.identity_key.jkt!==t||df(n.identity_key.public_jwk)!==t)throw new Error("the paired agent key rotated since this ceremony was created; start over");return{seed:Buffer.from(n.identity_key.private_jwk.d,"base64url"),publicJwk:n.identity_key.public_jwk,jkt:n.identity_key.jkt}}async function qPe(e){let t=e.attachDir??i7,r=o7(e.agentId,e.agentDir);if(!r||!hf(r))throw new Error(`no paired identity for agent ${e.agentId} on this machine \u2014 run \`visa agent pair\` first`);let n=BPe(e.authUrl??r.auth_url??Sa());if(!Number.isSafeInteger(e.aggregateCeilingCents)||e.aggregateCeilingCents<=0||!Number.isSafeInteger(e.perPurchaseCents)||e.perPurchaseCents<=0||e.perPurchaseCents>e.aggregateCeilingCents)throw new Error("ceiling and per-transaction caps must be positive, with per-transaction \u2264 ceiling");let i=await e.createCall(e.agentId,{protocolVersion:jt,capability:p8,aggregateCeilingCents:e.aggregateCeilingCents,perPurchaseCents:e.perPurchaseCents});if(!t6(i)||i.protocolVersion!==jt||!LU(i.attachId)||i.agentId!==e.agentId||i.state!=="attach_initiated"||i.capability!==p8||!zU(i.rail)||i.currency!=="USD"||!qU(i.aggregateCeilingMicros)||!qU(i.perTransactionMicros)||!NPe(i.instrumentLabel??null)||!Cr(i.serverNonce))throw new Error("capability-attach server returned an invalid create response");let o={protocolVersion:jt,attachId:i.attachId,agentId:e.agentId,authUrl:n,capability:p8,rail:i.rail,currency:"USD",aggregateCeilingMicros:i.aggregateCeilingMicros,perTransactionMicros:i.perTransactionMicros,instrumentLabel:i.instrumentLabel??null,serverNonce:i.serverNonce,identityKeyJkt:r.identity_key.jkt,claimToken:sU(),createdAt:new Date().toISOString()};return a3t(o,t),o}function c3t(e,t,r){let n=UPe(r,N7e({protocolVersion:jt,attachId:e.attachId,agentId:e.agentId,capability:e.capability,serverNonce:e.serverNonce,claimTokenHash:P0(e.claimToken),identityKeyJkt:e.identityKeyJkt}));return{protocolVersion:jt,agentId:e.agentId,identityPublicJwk:t,signature:n,claimToken:e.claimToken}}async function DPe(e){let{pending:t}=e,r=e.fetchImpl??fetch,n=MPe(t.agentId,t.identityKeyJkt,e.agentDir),{body:i}=await gre(`${t.authUrl}/v4/agents/${encodeURIComponent(t.agentId)}/capability-attach/${encodeURIComponent(t.attachId)}/claim`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c3t(t,n.publicJwk,n.seed))},r,{signal:e.signal});if(!t6(i)||i.protocolVersion!==jt||i.attachId!==t.attachId||i.agentId!==t.agentId||i.state!=="attach_claimed"||i.capabilityToken!==t.claimToken)throw new Error("capability-attach server returned an invalid claim response");return t}function u3t(e,t){if(!t6(e)||e.protocolVersion!==jt||e.attachId!==t.attachId||e.agentId!==t.agentId||!zU(e.rail)||e.rail!==t.rail||e.identityKeyJkt!==t.identityKeyJkt||e.claimTokenHash!==P0(t.claimToken)||!mre(e.ownerPublicId)||!Cr(e.grantHash)||!Cr(e.ceremonyHash)||!Cr(e.deliveryArtifactHash))throw new Error("capability-attach server returned an invalid activation-delivery artifact");let r={protocolVersion:jt,attachId:t.attachId,agentId:t.agentId,ownerPublicId:e.ownerPublicId,identityKeyJkt:t.identityKeyJkt,claimTokenHash:P0(t.claimToken),grantHash:e.grantHash,ceremonyHash:e.ceremonyHash,deliveryArtifactHash:e.deliveryArtifactHash,rail:t.rail};return bte(r),r}async function d3t(e,t,r,n){let{status:i,body:o}=await gre(`${e.authUrl}/v4/agents/${encodeURIComponent(e.agentId)}/capability-attach/${encodeURIComponent(e.attachId)}/delivery`,{method:"GET",cache:"no-store",headers:{"x-agent-capability-token":e.claimToken}},t,{signal:r});if(!t6(o)||o.attachId!==e.attachId||o.agentId!==e.agentId)throw new Error("capability-attach server returned an invalid delivery response");let s=typeof o.state=="string"?o.state:"";if(!t3t.has(s))throw new Error("capability-attach server returned an invalid delivery response");if(n?.(s),r3t.has(s))throw new Error(`capability-attach ceremony ended in state ${s}`);if(i===202||s!=="human_authorized"&&s!=="grant_activated")return null;let a=u3t(o.artifact,e);if(o.deliveryArtifactHash!==a.deliveryArtifactHash)throw new Error("capability-attach delivery hash does not match its artifact");return a}async function l3t(e){let{pending:t}=e,r=e.fetchImpl??fetch,n;try{n=await d3t(t,r,e.signal,e.onState)}catch(a){throw a instanceof Error&&/ceremony ended in state (failed|expired)/.test(a.message)&&CPe(t.attachId,e.attachDir),a}if(!n)return null;let i=MPe(t.agentId,t.identityKeyJkt,e.agentDir),o=UPe(i.seed,bte(n)),{body:s}=await gre(`${t.authUrl}/v4/agents/${encodeURIComponent(t.agentId)}/capability-attach/${encodeURIComponent(t.attachId)}/activate`,{method:"POST",headers:{"Content-Type":"application/json","x-agent-capability-token":t.claimToken},body:JSON.stringify({protocolVersion:jt,agentId:t.agentId,signature:o})},r,{signal:e.signal});if(!t6(s)||s.protocolVersion!==jt||s.attachId!==t.attachId||s.agentId!==t.agentId||s.state!=="grant_activated"||!zU(s.rail)||s.rail!==t.rail||!mre(s.grantId)||!Number.isSafeInteger(s.grantVersion)||typeof s.replay!="boolean")throw new Error("capability-attach server returned an invalid activation response");return CPe(t.attachId,e.attachDir),{attachId:t.attachId,agentId:t.agentId,rail:t.rail,aggregateCeilingMicros:t.aggregateCeilingMicros,perTransactionMicros:t.perTransactionMicros,grantId:s.grantId,grantVersion:s.grantVersion,replay:s.replay}}async function bre(e){let t=e.wait??(i=>new Promise(o=>setTimeout(o,i))),r=e.maxPolls??450,n="";for(let i=0;i<r;i+=1){let o=await l3t({...e,onState:s=>{s!==n&&(n=s,e.onState?.(s))}});if(o)return o;i+1<r&&await pre(t(e.pollIntervalMs??2e3),e.signal)}throw new Error("timed out waiting for human authorization of the spending grant")}var xy,kPe,fre,W8t,i7,G8t,J8t,Y8t,Z8t,X8t,Q8t,e3t,p8,t3t,r3t,OPe,LPe=k(()=>{"use strict";xy=_e(require("node:fs")),kPe=_e(require("node:os")),fre=_e(require("node:path"));$_();ay();WT();e7();r6();W8t="4.1.0-rc.50",i7=fre.join(kPe.homedir(),".visa-cli","capability-attach"),G8t="VISA_V4_CAPABILITY_ATTACH_ENABLED";J8t=/^ca_[A-Za-z0-9_-]{24}$/,Y8t=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,Z8t=/^(0|[1-9][0-9]{0,17})$/,X8t=2048,Q8t=255,e3t=/[\p{Cc}\p{Cf}\u2028\u2029]/u,p8="card",t3t=new Set(["attach_initiated","attach_claimed","human_authorized","grant_activated","failed","expired"]),r3t=new Set(["failed","expired"]);OPe=3e4});var rCe={};Pi(rCe,{agentFilePath:()=>m8,agentFormatIsJson:()=>n6,attachAgentCommand:()=>Pre,attachPollOptsFromFlags:()=>Are,claimOptsFromFlags:()=>f8,decodeBindingClaims:()=>y8,enrollClaimEnvelope:()=>QPe,formatUsdMicros:()=>a7,isAgentCommandEnabled:()=>XPe,isAgentRecord:()=>Sre,isAgentRecordV2:()=>hf,isStoredAgentRecord:()=>Tre,listAgentFiles:()=>VU,listLegacyAgentRecords:()=>GU,loginClaimEnvelope:()=>eCe,loginClaimOptsFromFlags:()=>tCe,newestAgentRecord:()=>WU,newestAgentRecordV2:()=>h8,parseUsdToCents:()=>Ere,readAgent:()=>o7,renderGrantActivated:()=>xre,writeAgent:()=>Ire});function Sre(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.agent_jkt=="string"&&typeof t.name=="string"&&t.public_key_jwk?.kty==="OKP"&&t.public_key_jwk.crv==="Ed25519"&&typeof t.public_key_jwk.x=="string"&&t.private_key_jwk?.kty==="OKP"&&t.private_key_jwk.crv==="Ed25519"&&typeof t.private_key_jwk.x=="string"&&typeof t.private_key_jwk.d=="string"&&typeof t.binding_jwt=="string"&&typeof t.registration_jwt=="string"&&typeof t.wallet_public_key=="string"&&typeof t.pairing_id=="string"&&(t.pairing_status==="activated"||t.pairing_status==="revoked")&&t.artifacts!==null&&typeof t.artifacts=="object"&&!Array.isArray(t.artifacts)&&typeof t.auth_url=="string"&&typeof t.created_at=="string"}function f3t(e){if(typeof e!="string")return!1;let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}function m3t(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost"||t==="::1")return!0;let r=t.split(".");return r.length===4&&r[0]==="127"&&r.every(n=>/^\d{1,3}$/.test(n)&&Number(n)<=255)}function h3t(e){if(typeof e!="string"||e.length===0||e.length>2048)return!1;try{let t=new URL(e);if(t.username.length>0||t.password.length>0||t.search.length>0||t.hash.length>0||t.protocol!=="https:"&&!(t.protocol==="http:"&&m3t(t.hostname)))return!1;let r=t.pathname.replace(/\/+$/,""),n=`${t.origin}${r===""||r==="/"?"":r}`;return e===n}catch{return!1}}function y3t(e){return typeof e=="string"&&e.length>0&&e.length<=255&&!p3t.test(e)&&e===e.normalize("NFC").trim().replace(/ {2,}/g," ")}function g3t(e,t){try{let r=H_(Buffer.from(e.d,"base64url"));return r.d===e.d&&r.x===t.x}catch{return!1}}function zPe(e){if(e.length===0||e.length>wre)return null;let t=e.split(".");if(t.length!==3||t.some(r=>!/^[A-Za-z0-9_-]+$/.test(r)))return null;try{let r=JSON.parse(Buffer.from(t[1],"base64url").toString("utf8"));return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}function HPe(e){return Number.isSafeInteger(e.iat)&&Number.isSafeInteger(e.exp)&&e.iat>=0&&e.exp>e.iat}function b3t(e){let t=zPe(e.activation_credentials.binding_jwt),r=zPe(e.activation_credentials.registration_jwt);return!t||!r||!HPe(t)||!HPe(r)?!1:t.v===jt&&t.sub===e.agent_id&&t.owner_public_id===e.owner_public_id&&t.name===e.display_name&&t.jkt===e.identity_key.jkt&&t.mesh==="visa"&&t.mode==="identity_only"&&t.card_verified===!1&&r.sub===e.identity_key.jkt&&r.name===e.display_name&&r.pol==="visa-agent-identity-only-v2"&&!!r.cnf&&typeof r.cnf=="object"&&!Array.isArray(r.cnf)&&r.cnf.jkt===e.identity_key.jkt}function ZPe(e){return typeof e=="string"&&(vre.test(e)||Cr(e))}function s7(e,t){let r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function hf(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(!s7(e,["v","agent_id","owner_public_id","display_name","identity_key","pairing_id","pairing_status","activation_credentials","delivery_artifact","auth_url","created_at"])||t.v!==jt||typeof t.agent_id!="string"||!vre.test(t.agent_id)||typeof t.owner_public_id!="string"||!vre.test(t.owner_public_id)||!y3t(t.display_name)||!t.identity_key||!s7(t.identity_key,["jkt","public_jwk","private_jwk","custody"])||t.identity_key.custody!=="runtime"||!s7(t.identity_key.public_jwk??{},["kty","crv","x"])||!s7(t.identity_key.private_jwk??{},["kty","crv","x","d"])||!Cr(t.identity_key.jkt)||t.identity_key.public_jwk?.kty!=="OKP"||t.identity_key.public_jwk.crv!=="Ed25519"||!Cr(t.identity_key.public_jwk.x)||t.identity_key.private_jwk?.kty!=="OKP"||t.identity_key.private_jwk.crv!=="Ed25519"||!Cr(t.identity_key.private_jwk.x)||!Cr(t.identity_key.private_jwk.d)||t.identity_key.public_jwk.x!==t.identity_key.private_jwk.x||!g3t(t.identity_key.private_jwk,t.identity_key.public_jwk)||typeof t.pairing_id!="string"||t.pairing_status!=="activated"||!t.activation_credentials||!s7(t.activation_credentials,["binding_jwt","registration_jwt"])||typeof t.activation_credentials.binding_jwt!="string"||t.activation_credentials.binding_jwt.length===0||t.activation_credentials.binding_jwt.length>wre||typeof t.activation_credentials.registration_jwt!="string"||t.activation_credentials.registration_jwt.length===0||t.activation_credentials.registration_jwt.length>wre||!t.delivery_artifact||!h3t(t.auth_url)||!f3t(t.created_at)||!b3t(t))return!1;try{let r=JSON.parse(FT(t.delivery_artifact));return r.agentId===t.agent_id&&r.pairingId===t.pairing_id&&r.ownerPublicId===t.owner_public_id&&r.terms.displayName===t.display_name&&r.identityKey.jkt===t.identity_key.jkt&&r.identityKey.publicJwk.x===t.identity_key.public_jwk.x}catch{return!1}}function Tre(e){return hf(e)||Sre(e)}function XPe(){return!0}function n6(e){return e==="json"}function QPe(e){switch(e.status){case"activated":return{json:{status:"activated",protocolVersion:e.protocolVersion,pairingId:e.pairingId,agentId:e.agentId,displayName:e.displayName,identityKeyJkt:e.identityKeyJkt},exitCode:0};case"not_ready":return{json:{status:"not_ready",protocolVersion:e.protocolVersion,pairingId:e.pairingId,agentId:e.agentId,likelyExpired:e.likelyExpired,error:e.likelyExpired?"the pairing authorization window has expired":"not ready yet \u2014 finish the human authorization in the browser"},exitCode:3};case"no_pending":return{json:{status:"no_pending",error:"no agent pairing in progress"},exitCode:1};case"error":return{json:{status:"error",error:e.message},exitCode:1}}}function eCe(e){switch(e.status){case"claimed":return{json:{status:"claimed",sessionSaved:!0},exitCode:0};case"not_ready":return{json:{status:"not_ready",likelyExpired:e.likelyExpired,error:e.likelyExpired?"the 15-minute v4 sign-in window has likely expired":"not ready yet \u2014 finish browser sign-in and terminal-code confirmation"},exitCode:3};case"no_pending":return{json:{status:"no_pending",error:"no v4 sign-in handoff is in progress"},exitCode:1};case"confirm_mismatch":return{json:{status:"confirm_mismatch",confirmCode:e.confirmCode,error:"this v4 sign-in handoff did not match this terminal"},exitCode:1};case"error":return{json:{status:"error",error:e.message},exitCode:1}}}function f8(e){let t=e.interval&&e.interval>0?e.interval:3,r=e.attempts&&e.attempts>0?e.attempts:5;return e.timeout&&e.timeout>0&&(r=Math.max(1,Math.ceil(e.timeout/t))),{attempts:r,delayMs:t*1e3}}function Ere(e){let t=e.trim().replace(/^\$/,"");if(!/^\d{1,15}(\.\d{1,2})?$/.test(t))throw new Error(`invalid USD amount "${e}" \u2014 use dollars like 25 or 25.50`);let[r,n=""]=t.split("."),i=Number(r)*100+Number(n.padEnd(2,"0"));if(!Number.isSafeInteger(i)||i<=0)throw new Error(`invalid USD amount "${e}" \u2014 must be greater than zero`);return i}function a7(e){let t=Number(e);return Number.isFinite(t)?`$${(t/1e6).toFixed(2)}`:`${e} micros`}function Are(e){if(!(e.attempts!==void 0&&e.attempts>0||e.interval!==void 0&&e.interval>0||e.timeout!==void 0&&e.timeout>0))return{maxPolls:450,pollIntervalMs:2e3};let r=f8(e);return{maxPolls:r.attempts,pollIntervalMs:r.delayMs}}function xre(e){return`\u2713 Spending authority active for agent ${e.agentId} \u2014 ${a7(e.aggregateCeilingMicros)} ceiling.
|
|
47
|
+
`),{removed:!0,configPath:r})}function ure(e,t="global"){let r=t==="project"?Nt.join(process.cwd(),".mcp.json"):tre(e);if(!Yt.existsSync(r))return!1;let n=ire(e,t);if(n==="toml")try{let i=Yt.readFileSync(r,"utf-8");return!!sre(i,"visa-cli")}catch{return!1}if(n==="yaml")try{let i=Yt.readFileSync(r,"utf-8");return!!cre(i,"visa-cli")}catch{return!1}try{let i=JSON.parse(Yt.readFileSync(r,"utf-8"));return!!nre(i,e.configKey)?.["visa-cli"]}catch{return!1}}var Yt,Nt,uPe,Tn,k8t,ere,jU,gPe,dre=k(()=>{"use strict";Yt=_e(require("fs")),Nt=_e(require("path")),uPe=_e(require("os")),Tn=uPe.homedir(),k8t=["Claude_","Anthropic.ClaudeDesktop_"],ere=class extends Error{constructor(r,n,i){super(N8t(r,n,i));this.client=r;this.configPath=n;this.name="McpConfigAccessError"}client;configPath};jU=[{id:"claude",displayName:"Claude Code",globalConfigPath:Nt.join(Tn,".claude.json"),configKey:"mcpServers",detectPaths:[Nt.join(Tn,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:pPe(),configKey:"mcpServers",detectPaths:fPe(),postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:Nt.join(Tn,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[Nt.join(Tn,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:Nt.join(Tn,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[Nt.join(Tn,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:Nt.join(Tn,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[Nt.join(Tn,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:Xte({win32:Nt.join(r7(),"Roo","mcp_settings.json"),posix:Nt.join(Tn,".config","Roo","mcp_settings.json")}),configKey:"mcpServers",detectPaths:[Nt.join(Tn,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:Nt.join(Tn,".vscode","mcp.json"),configKey:"servers",detectPaths:[Nt.join(Tn,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:Xte({win32:Nt.join(r7(),"Zed","settings.json"),posix:Nt.join(Tn,".config","zed","settings.json")}),configKey:"context_servers",detectPaths:Xte({win32:[Nt.join(r7(),"Zed")],posix:[Nt.join(Tn,".config","zed")]}),postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})},{id:"codex",displayName:"Codex",globalConfigPath:Nt.join(Tn,".codex","config.toml"),configKey:"mcp_servers",configFormat:"toml",detectPaths:[Nt.join(Tn,".codex")],postInstallHint:"Restart Codex to connect."},{id:"openclaw",displayName:"OpenClaw",globalConfigPath:Nt.join(Tn,".openclaw","openclaw.json"),configKey:"mcp.servers",detectPaths:[Nt.join(Tn,".openclaw")],postInstallHint:"Restart OpenClaw (or reload its config) to connect."},{id:"hermes",displayName:"Hermes",globalConfigPath:Nt.join(Tn,".hermes","config.yaml"),configKey:"mcp_servers",configFormat:"yaml",detectPaths:[Nt.join(Tn,".hermes")],postInstallHint:"Restart Hermes to connect."}];gPe="mcp_servers"});function lre(e,t={}){let r=t.home??MU.homedir(),n=t.cwd??process.cwd();switch(e){case"openclaw":return ri.join(r,".openclaw","skills");case"hermes":return ri.join(r,".hermes","skills");case"claude-code":case"claude":return ri.join(r,".claude","skills");case"default":case"agentskills":return ri.join(n,".agents","skills");default:return null}}function z8t(e={}){let t=e.home??MU.homedir(),r=[["openclaw",ri.join(t,".openclaw")],["hermes",ri.join(t,".hermes")],["claude-code",ri.join(t,".claude")]];for(let[n,i]of r)if(Ks.existsSync(i))return{runtime:n,base:lre(n,e)};return{runtime:"default",base:lre("default",e)}}function EPe(e){let t=[ri.join(e,"skills",j0),ri.join(e,"..","skills",j0),ri.join(e,"..","..","visa-cli-openclaw","skills",j0),ri.join(e,"..","..","..","visa-cli-openclaw","skills",j0)];for(let r of t)if(Ks.existsSync(ri.join(r,"SKILL.md")))return r;return null}function H8t(e){let{bundledDir:t,base:r,force:n}=e;if(!Ks.existsSync(ri.join(t,"SKILL.md")))throw new Error(`bundled skill not found at ${t} (no SKILL.md)`);let i=ri.join(r,j0),o=Ks.existsSync(i)&&Ks.readdirSync(i).length>0;if(o&&!n)throw new Error(`${i} already exists \u2014 re-run with --force to overwrite, or --print to view the skill.`);return Ks.mkdirSync(r,{recursive:!0}),o&&Ks.rmSync(i,{recursive:!0,force:!0}),Ks.cpSync(t,i,{recursive:!0}),{installedDir:i,files:$8t(i),overwrote:o}}function $8t(e){let t=[],r=(n,i)=>{for(let o of Ks.readdirSync(n,{withFileTypes:!0})){let s=i?ri.join(i,o.name):o.name;o.isDirectory()?r(ri.join(n,o.name),s):t.push(s)}};return r(e,""),t.sort()}function APe(e){return Ks.readFileSync(ri.join(e,"SKILL.md"),"utf8")}function V8t(e){let{runtime:t}=e;if(!F8t.includes(t))return{runtime:t,status:"skipped",path:null,note:t==="claude-code"||t==="claude"?"Claude Code mounts MCP servers via its own config \u2014 run `visa-cli connect claude` to have the CLI write it.":"no known MCP config for this target \u2014 the skill can drive the raw `visa` CLI instead."};let r=n7(t),n=e.home?ri.join(e.home,ri.relative(MU.homedir(),r.globalConfigPath)):r.globalConfigPath,i=vPe(r,n,UU());return i.status==="error"?{runtime:t,status:"error",path:i.configPath,note:i.error}:{runtime:t,status:i.status,path:i.configPath}}function xPe(e){let t,r;if(e.dir)t=ri.resolve(e.dir),r="custom";else if(e.runtime){let o=lre(e.runtime,e);if(!o)throw new Error(`unknown runtime "${e.runtime}" \u2014 use openclaw | hermes | claude-code | default, or pass --dir.`);t=o,r=e.runtime}else{let o=z8t(e);t=o.base,r=o.runtime}let n=H8t({bundledDir:e.bundledDir,base:t,force:e.force}),i=e.mount===!1?{runtime:r,status:"skipped",path:null,note:"mount disabled with --no-mount"}:V8t({runtime:r,home:e.home});return{skill:j0,runtime:r,installedDir:n.installedDir,files:n.files,overwrote:n.overwrote,mount:i}}var Ks,MU,ri,j0,F8t,SPe=k(()=>{"use strict";Ks=_e(require("fs")),MU=_e(require("os")),ri=_e(require("path"));dre();j0="pair-visa-agent";F8t=["openclaw","hermes"]});function K8t(e,t={}){let r=t.execPath??process.execPath,n=t.cliEntry??process.argv[1],i=String(t.intervalSec??5),o=String(t.timeoutSec??840),s=["agent","enroll-claim",...e?["--url",e]:[],"--interval",i,"--timeout",o,"--format","json"];return n?{cmd:r,args:[n,...s]}:{cmd:"visa",args:s}}async function IPe(e,t=TPe.spawn){try{let{cmd:r,args:n}=K8t(e),i=t(r,n,{detached:!0,stdio:"ignore"});return typeof i.once!="function"?i.pid===void 0?{started:!1,error:"background process did not report a pid"}:(i.unref(),{started:!0,pid:i.pid}):await new Promise(o=>{let s=!1,a=c=>{s||(s=!0,o(c))};i.once?.("error",c=>{a({started:!1,error:c.message||"background process failed to start"})}),i.once?.("spawn",()=>{if(i.pid===void 0){a({started:!1,error:"background process did not report a pid"});return}i.unref(),a({started:!0,pid:i.pid})})})}catch(r){return{started:!1,error:r instanceof Error?r.message:"background process failed to start"}}}var TPe,PPe=k(()=>{"use strict";TPe=require("node:child_process")});function RPe(e=process.env){return e[G8t]==="true"}function t6(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function LU(e){return typeof e=="string"&&J8t.test(e)}function mre(e){return typeof e=="string"&&Y8t.test(e)}function qU(e){return typeof e=="string"&&Z8t.test(e)}function zU(e){return typeof e=="string"&&py.includes(e)}function NPe(e){return e===null||typeof e=="string"&&e.length>0&&e.length<=Q8t&&!e3t.test(e)}function n3t(e){if(typeof e!="string")return!1;let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}function i3t(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost"||t==="::1")return!0;let r=t.split(".");return r.length===4&&r[0]==="127"&&r.every(n=>/^\d{1,3}$/.test(n)&&Number(n)<=255)}function BPe(e){if(e.length===0||e.length>X8t)throw new Error("auth URL must be a bounded absolute URL");let t;try{t=new URL(e)}catch{throw new Error("auth URL must be a bounded absolute URL")}if(t.username.length>0||t.password.length>0||t.search.length>0||t.hash.length>0||t.protocol!=="https:"&&!(t.protocol==="http:"&&i3t(t.hostname)))throw new Error("auth URL must use HTTPS (or HTTP on a loopback host) without credentials");let r=t.pathname.replace(/\/+$/,"");return`${t.origin}${r===""||r==="/"?"":r}`}function o3t(e){if(typeof e!="string")return!1;try{return BPe(e)===e}catch{return!1}}function jPe(e){return t6(e)&&e.protocolVersion===jt&&LU(e.attachId)&&mre(e.agentId)&&o3t(e.authUrl)&&e.capability===p8&&zU(e.rail)&&e.currency==="USD"&&qU(e.aggregateCeilingMicros)&&qU(e.perTransactionMicros)&&NPe(e.instrumentLabel)&&Cr(e.serverNonce)&&Cr(e.identityKeyJkt)&&Cr(e.claimToken)&&n3t(e.createdAt)}function hre(e,t=i7){if(!LU(e))throw new Error("attach id must use the canonical ca_ + 24 base64url form");return fre.join(t,`${e}.json`)}function s3t(e){xy.mkdirSync(e,{recursive:!0,mode:448});let t=xy.lstatSync(e);if(t.isSymbolicLink()||!t.isDirectory())throw new Error("capability-attach directory must be a real directory, not a symlink");xy.chmodSync(e,448),ac(e)}function a3t(e,t=i7){if(!jPe(e))throw new Error("refusing to write an invalid capability-attach ceremony record");s3t(t),B0(hre(e.attachId,t),JSON.stringify(e,null,2))}function yre(e,t=i7){if(!LU(e))return null;let r=e6(hre(e,t));if(r===null)return null;let n;try{n=JSON.parse(r)}catch{throw new Error(`local capability-attach state for ${e} contains invalid JSON`)}if(!jPe(n)||n.attachId!==e)throw new Error(`local capability-attach state for ${e} is invalid or misbound`);return n}function CPe(e,t=i7){yre(e,t)&&ac(t)&&xy.rmSync(hre(e,t),{force:!0})}function DU(e,t="capability-attach operation aborted"){return e.reason instanceof Error?e.reason:new Error(t)}function pre(e,t){return t?t.aborted?Promise.reject(DU(t)):new Promise((r,n)=>{let i=()=>n(DU(t));t.addEventListener("abort",i,{once:!0}),e.then(o=>{t.removeEventListener("abort",i),r(o)},o=>{t.removeEventListener("abort",i),n(o)})}):e}async function gre(e,t,r,n={}){let i=new AbortController,o=()=>{let a=n.signal?.reason;i.abort(a instanceof Error?a:new Error("capability-attach operation aborted"))};n.signal?.aborted?o():n.signal?.addEventListener("abort",o,{once:!0});let s=setTimeout(()=>i.abort(new Error(`capability-attach request timed out after ${OPe}ms`)),OPe);s.unref?.();try{if(i.signal.aborted)throw DU(i.signal);let a=await pre(r(e,{...t,headers:{"X-Source":"cli","X-Visa-CLI-Version":W8t,...t.headers??{}},redirect:"error",signal:i.signal}),i.signal),c;try{c=await pre(a.json(),i.signal)}catch{if(i.signal.aborted)throw DU(i.signal);c={}}if(!a.ok&&a.status!==202){let u=t6(c)?c:{},d=typeof u.error=="string"?u.error:void 0,l=typeof u.detail=="string"?u.detail:void 0;throw new Error(d??l??`capability-attach server returned ${a.status}`)}return{status:a.status,body:c}}finally{clearTimeout(s),n.signal?.removeEventListener("abort",o)}}function UPe(e,t){return Buffer.from(t8(e,Buffer.from(t,"utf8"))).toString("base64url")}function MPe(e,t,r){let n=o7(e,r);if(!n||!hf(n))throw new Error(`no paired identity for agent ${e} on this machine \u2014 run \`visa agent pair\` first`);if(n.identity_key.jkt!==t||df(n.identity_key.public_jwk)!==t)throw new Error("the paired agent key rotated since this ceremony was created; start over");return{seed:Buffer.from(n.identity_key.private_jwk.d,"base64url"),publicJwk:n.identity_key.public_jwk,jkt:n.identity_key.jkt}}async function qPe(e){let t=e.attachDir??i7,r=o7(e.agentId,e.agentDir);if(!r||!hf(r))throw new Error(`no paired identity for agent ${e.agentId} on this machine \u2014 run \`visa agent pair\` first`);let n=BPe(e.authUrl??r.auth_url??Sa());if(!Number.isSafeInteger(e.aggregateCeilingCents)||e.aggregateCeilingCents<=0||!Number.isSafeInteger(e.perPurchaseCents)||e.perPurchaseCents<=0||e.perPurchaseCents>e.aggregateCeilingCents)throw new Error("ceiling and per-transaction caps must be positive, with per-transaction \u2264 ceiling");let i=await e.createCall(e.agentId,{protocolVersion:jt,capability:p8,aggregateCeilingCents:e.aggregateCeilingCents,perPurchaseCents:e.perPurchaseCents});if(!t6(i)||i.protocolVersion!==jt||!LU(i.attachId)||i.agentId!==e.agentId||i.state!=="attach_initiated"||i.capability!==p8||!zU(i.rail)||i.currency!=="USD"||!qU(i.aggregateCeilingMicros)||!qU(i.perTransactionMicros)||!NPe(i.instrumentLabel??null)||!Cr(i.serverNonce))throw new Error("capability-attach server returned an invalid create response");let o={protocolVersion:jt,attachId:i.attachId,agentId:e.agentId,authUrl:n,capability:p8,rail:i.rail,currency:"USD",aggregateCeilingMicros:i.aggregateCeilingMicros,perTransactionMicros:i.perTransactionMicros,instrumentLabel:i.instrumentLabel??null,serverNonce:i.serverNonce,identityKeyJkt:r.identity_key.jkt,claimToken:sU(),createdAt:new Date().toISOString()};return a3t(o,t),o}function c3t(e,t,r){let n=UPe(r,N7e({protocolVersion:jt,attachId:e.attachId,agentId:e.agentId,capability:e.capability,serverNonce:e.serverNonce,claimTokenHash:P0(e.claimToken),identityKeyJkt:e.identityKeyJkt}));return{protocolVersion:jt,agentId:e.agentId,identityPublicJwk:t,signature:n,claimToken:e.claimToken}}async function DPe(e){let{pending:t}=e,r=e.fetchImpl??fetch,n=MPe(t.agentId,t.identityKeyJkt,e.agentDir),{body:i}=await gre(`${t.authUrl}/v4/agents/${encodeURIComponent(t.agentId)}/capability-attach/${encodeURIComponent(t.attachId)}/claim`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(c3t(t,n.publicJwk,n.seed))},r,{signal:e.signal});if(!t6(i)||i.protocolVersion!==jt||i.attachId!==t.attachId||i.agentId!==t.agentId||i.state!=="attach_claimed"||i.capabilityToken!==t.claimToken)throw new Error("capability-attach server returned an invalid claim response");return t}function u3t(e,t){if(!t6(e)||e.protocolVersion!==jt||e.attachId!==t.attachId||e.agentId!==t.agentId||!zU(e.rail)||e.rail!==t.rail||e.identityKeyJkt!==t.identityKeyJkt||e.claimTokenHash!==P0(t.claimToken)||!mre(e.ownerPublicId)||!Cr(e.grantHash)||!Cr(e.ceremonyHash)||!Cr(e.deliveryArtifactHash))throw new Error("capability-attach server returned an invalid activation-delivery artifact");let r={protocolVersion:jt,attachId:t.attachId,agentId:t.agentId,ownerPublicId:e.ownerPublicId,identityKeyJkt:t.identityKeyJkt,claimTokenHash:P0(t.claimToken),grantHash:e.grantHash,ceremonyHash:e.ceremonyHash,deliveryArtifactHash:e.deliveryArtifactHash,rail:t.rail};return bte(r),r}async function d3t(e,t,r,n){let{status:i,body:o}=await gre(`${e.authUrl}/v4/agents/${encodeURIComponent(e.agentId)}/capability-attach/${encodeURIComponent(e.attachId)}/delivery`,{method:"GET",cache:"no-store",headers:{"x-agent-capability-token":e.claimToken}},t,{signal:r});if(!t6(o)||o.attachId!==e.attachId||o.agentId!==e.agentId)throw new Error("capability-attach server returned an invalid delivery response");let s=typeof o.state=="string"?o.state:"";if(!t3t.has(s))throw new Error("capability-attach server returned an invalid delivery response");if(n?.(s),r3t.has(s))throw new Error(`capability-attach ceremony ended in state ${s}`);if(i===202||s!=="human_authorized"&&s!=="grant_activated")return null;let a=u3t(o.artifact,e);if(o.deliveryArtifactHash!==a.deliveryArtifactHash)throw new Error("capability-attach delivery hash does not match its artifact");return a}async function l3t(e){let{pending:t}=e,r=e.fetchImpl??fetch,n;try{n=await d3t(t,r,e.signal,e.onState)}catch(a){throw a instanceof Error&&/ceremony ended in state (failed|expired)/.test(a.message)&&CPe(t.attachId,e.attachDir),a}if(!n)return null;let i=MPe(t.agentId,t.identityKeyJkt,e.agentDir),o=UPe(i.seed,bte(n)),{body:s}=await gre(`${t.authUrl}/v4/agents/${encodeURIComponent(t.agentId)}/capability-attach/${encodeURIComponent(t.attachId)}/activate`,{method:"POST",headers:{"Content-Type":"application/json","x-agent-capability-token":t.claimToken},body:JSON.stringify({protocolVersion:jt,agentId:t.agentId,signature:o})},r,{signal:e.signal});if(!t6(s)||s.protocolVersion!==jt||s.attachId!==t.attachId||s.agentId!==t.agentId||s.state!=="grant_activated"||!zU(s.rail)||s.rail!==t.rail||!mre(s.grantId)||!Number.isSafeInteger(s.grantVersion)||typeof s.replay!="boolean")throw new Error("capability-attach server returned an invalid activation response");return CPe(t.attachId,e.attachDir),{attachId:t.attachId,agentId:t.agentId,rail:t.rail,aggregateCeilingMicros:t.aggregateCeilingMicros,perTransactionMicros:t.perTransactionMicros,grantId:s.grantId,grantVersion:s.grantVersion,replay:s.replay}}async function bre(e){let t=e.wait??(i=>new Promise(o=>setTimeout(o,i))),r=e.maxPolls??450,n="";for(let i=0;i<r;i+=1){let o=await l3t({...e,onState:s=>{s!==n&&(n=s,e.onState?.(s))}});if(o)return o;i+1<r&&await pre(t(e.pollIntervalMs??2e3),e.signal)}throw new Error("timed out waiting for human authorization of the spending grant")}var xy,kPe,fre,W8t,i7,G8t,J8t,Y8t,Z8t,X8t,Q8t,e3t,p8,t3t,r3t,OPe,LPe=k(()=>{"use strict";xy=_e(require("node:fs")),kPe=_e(require("node:os")),fre=_e(require("node:path"));$_();ay();WT();e7();r6();W8t="4.1.0-rc.51",i7=fre.join(kPe.homedir(),".visa-cli","capability-attach"),G8t="VISA_V4_CAPABILITY_ATTACH_ENABLED";J8t=/^ca_[A-Za-z0-9_-]{24}$/,Y8t=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,Z8t=/^(0|[1-9][0-9]{0,17})$/,X8t=2048,Q8t=255,e3t=/[\p{Cc}\p{Cf}\u2028\u2029]/u,p8="card",t3t=new Set(["attach_initiated","attach_claimed","human_authorized","grant_activated","failed","expired"]),r3t=new Set(["failed","expired"]);OPe=3e4});var rCe={};Pi(rCe,{agentFilePath:()=>m8,agentFormatIsJson:()=>n6,attachAgentCommand:()=>Pre,attachPollOptsFromFlags:()=>Are,claimOptsFromFlags:()=>f8,decodeBindingClaims:()=>y8,enrollClaimEnvelope:()=>QPe,formatUsdMicros:()=>a7,isAgentCommandEnabled:()=>XPe,isAgentRecord:()=>Sre,isAgentRecordV2:()=>hf,isStoredAgentRecord:()=>Tre,listAgentFiles:()=>VU,listLegacyAgentRecords:()=>GU,loginClaimEnvelope:()=>eCe,loginClaimOptsFromFlags:()=>tCe,newestAgentRecord:()=>WU,newestAgentRecordV2:()=>h8,parseUsdToCents:()=>Ere,readAgent:()=>o7,renderGrantActivated:()=>xre,writeAgent:()=>Ire});function Sre(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;return typeof t.agent_jkt=="string"&&typeof t.name=="string"&&t.public_key_jwk?.kty==="OKP"&&t.public_key_jwk.crv==="Ed25519"&&typeof t.public_key_jwk.x=="string"&&t.private_key_jwk?.kty==="OKP"&&t.private_key_jwk.crv==="Ed25519"&&typeof t.private_key_jwk.x=="string"&&typeof t.private_key_jwk.d=="string"&&typeof t.binding_jwt=="string"&&typeof t.registration_jwt=="string"&&typeof t.wallet_public_key=="string"&&typeof t.pairing_id=="string"&&(t.pairing_status==="activated"||t.pairing_status==="revoked")&&t.artifacts!==null&&typeof t.artifacts=="object"&&!Array.isArray(t.artifacts)&&typeof t.auth_url=="string"&&typeof t.created_at=="string"}function f3t(e){if(typeof e!="string")return!1;let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}function m3t(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost"||t==="::1")return!0;let r=t.split(".");return r.length===4&&r[0]==="127"&&r.every(n=>/^\d{1,3}$/.test(n)&&Number(n)<=255)}function h3t(e){if(typeof e!="string"||e.length===0||e.length>2048)return!1;try{let t=new URL(e);if(t.username.length>0||t.password.length>0||t.search.length>0||t.hash.length>0||t.protocol!=="https:"&&!(t.protocol==="http:"&&m3t(t.hostname)))return!1;let r=t.pathname.replace(/\/+$/,""),n=`${t.origin}${r===""||r==="/"?"":r}`;return e===n}catch{return!1}}function y3t(e){return typeof e=="string"&&e.length>0&&e.length<=255&&!p3t.test(e)&&e===e.normalize("NFC").trim().replace(/ {2,}/g," ")}function g3t(e,t){try{let r=H_(Buffer.from(e.d,"base64url"));return r.d===e.d&&r.x===t.x}catch{return!1}}function zPe(e){if(e.length===0||e.length>wre)return null;let t=e.split(".");if(t.length!==3||t.some(r=>!/^[A-Za-z0-9_-]+$/.test(r)))return null;try{let r=JSON.parse(Buffer.from(t[1],"base64url").toString("utf8"));return r&&typeof r=="object"&&!Array.isArray(r)?r:null}catch{return null}}function HPe(e){return Number.isSafeInteger(e.iat)&&Number.isSafeInteger(e.exp)&&e.iat>=0&&e.exp>e.iat}function b3t(e){let t=zPe(e.activation_credentials.binding_jwt),r=zPe(e.activation_credentials.registration_jwt);return!t||!r||!HPe(t)||!HPe(r)?!1:t.v===jt&&t.sub===e.agent_id&&t.owner_public_id===e.owner_public_id&&t.name===e.display_name&&t.jkt===e.identity_key.jkt&&t.mesh==="visa"&&t.mode==="identity_only"&&t.card_verified===!1&&r.sub===e.identity_key.jkt&&r.name===e.display_name&&r.pol==="visa-agent-identity-only-v2"&&!!r.cnf&&typeof r.cnf=="object"&&!Array.isArray(r.cnf)&&r.cnf.jkt===e.identity_key.jkt}function ZPe(e){return typeof e=="string"&&(vre.test(e)||Cr(e))}function s7(e,t){let r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function hf(e){if(!e||typeof e!="object"||Array.isArray(e))return!1;let t=e;if(!s7(e,["v","agent_id","owner_public_id","display_name","identity_key","pairing_id","pairing_status","activation_credentials","delivery_artifact","auth_url","created_at"])||t.v!==jt||typeof t.agent_id!="string"||!vre.test(t.agent_id)||typeof t.owner_public_id!="string"||!vre.test(t.owner_public_id)||!y3t(t.display_name)||!t.identity_key||!s7(t.identity_key,["jkt","public_jwk","private_jwk","custody"])||t.identity_key.custody!=="runtime"||!s7(t.identity_key.public_jwk??{},["kty","crv","x"])||!s7(t.identity_key.private_jwk??{},["kty","crv","x","d"])||!Cr(t.identity_key.jkt)||t.identity_key.public_jwk?.kty!=="OKP"||t.identity_key.public_jwk.crv!=="Ed25519"||!Cr(t.identity_key.public_jwk.x)||t.identity_key.private_jwk?.kty!=="OKP"||t.identity_key.private_jwk.crv!=="Ed25519"||!Cr(t.identity_key.private_jwk.x)||!Cr(t.identity_key.private_jwk.d)||t.identity_key.public_jwk.x!==t.identity_key.private_jwk.x||!g3t(t.identity_key.private_jwk,t.identity_key.public_jwk)||typeof t.pairing_id!="string"||t.pairing_status!=="activated"||!t.activation_credentials||!s7(t.activation_credentials,["binding_jwt","registration_jwt"])||typeof t.activation_credentials.binding_jwt!="string"||t.activation_credentials.binding_jwt.length===0||t.activation_credentials.binding_jwt.length>wre||typeof t.activation_credentials.registration_jwt!="string"||t.activation_credentials.registration_jwt.length===0||t.activation_credentials.registration_jwt.length>wre||!t.delivery_artifact||!h3t(t.auth_url)||!f3t(t.created_at)||!b3t(t))return!1;try{let r=JSON.parse(FT(t.delivery_artifact));return r.agentId===t.agent_id&&r.pairingId===t.pairing_id&&r.ownerPublicId===t.owner_public_id&&r.terms.displayName===t.display_name&&r.identityKey.jkt===t.identity_key.jkt&&r.identityKey.publicJwk.x===t.identity_key.public_jwk.x}catch{return!1}}function Tre(e){return hf(e)||Sre(e)}function XPe(){return!0}function n6(e){return e==="json"}function QPe(e){switch(e.status){case"activated":return{json:{status:"activated",protocolVersion:e.protocolVersion,pairingId:e.pairingId,agentId:e.agentId,displayName:e.displayName,identityKeyJkt:e.identityKeyJkt},exitCode:0};case"not_ready":return{json:{status:"not_ready",protocolVersion:e.protocolVersion,pairingId:e.pairingId,agentId:e.agentId,likelyExpired:e.likelyExpired,error:e.likelyExpired?"the pairing authorization window has expired":"not ready yet \u2014 finish the human authorization in the browser"},exitCode:3};case"no_pending":return{json:{status:"no_pending",error:"no agent pairing in progress"},exitCode:1};case"error":return{json:{status:"error",error:e.message},exitCode:1}}}function eCe(e){switch(e.status){case"claimed":return{json:{status:"claimed",sessionSaved:!0},exitCode:0};case"not_ready":return{json:{status:"not_ready",likelyExpired:e.likelyExpired,error:e.likelyExpired?"the 15-minute v4 sign-in window has likely expired":"not ready yet \u2014 finish browser sign-in and terminal-code confirmation"},exitCode:3};case"no_pending":return{json:{status:"no_pending",error:"no v4 sign-in handoff is in progress"},exitCode:1};case"confirm_mismatch":return{json:{status:"confirm_mismatch",confirmCode:e.confirmCode,error:"this v4 sign-in handoff did not match this terminal"},exitCode:1};case"error":return{json:{status:"error",error:e.message},exitCode:1}}}function f8(e){let t=e.interval&&e.interval>0?e.interval:3,r=e.attempts&&e.attempts>0?e.attempts:5;return e.timeout&&e.timeout>0&&(r=Math.max(1,Math.ceil(e.timeout/t))),{attempts:r,delayMs:t*1e3}}function Ere(e){let t=e.trim().replace(/^\$/,"");if(!/^\d{1,15}(\.\d{1,2})?$/.test(t))throw new Error(`invalid USD amount "${e}" \u2014 use dollars like 25 or 25.50`);let[r,n=""]=t.split("."),i=Number(r)*100+Number(n.padEnd(2,"0"));if(!Number.isSafeInteger(i)||i<=0)throw new Error(`invalid USD amount "${e}" \u2014 must be greater than zero`);return i}function a7(e){let t=Number(e);return Number.isFinite(t)?`$${(t/1e6).toFixed(2)}`:`${e} micros`}function Are(e){if(!(e.attempts!==void 0&&e.attempts>0||e.interval!==void 0&&e.interval>0||e.timeout!==void 0&&e.timeout>0))return{maxPolls:450,pollIntervalMs:2e3};let r=f8({...e,interval:e.interval&&e.interval>0?e.interval:2});return{maxPolls:r.attempts,pollIntervalMs:r.delayMs}}function xre(e){return`\u2713 Spending authority active for agent ${e.agentId} \u2014 ${a7(e.aggregateCeilingMicros)} ceiling.
|
|
48
48
|
Rail: ${e.rail}
|
|
49
49
|
Per transaction: ${a7(e.perTransactionMicros)}
|
|
50
50
|
Grant: ${e.grantId} (v${e.grantVersion})
|
|
@@ -188,7 +188,7 @@ Full request-key fingerprint to compare exactly: ${n.identityKeyJkt}
|
|
|
188
188
|
`:`Agent not found: ${r}
|
|
189
189
|
`),process.exitCode=1;return}if(hf(n)){let o=y8(n.activation_credentials.binding_jwt);process.stdout.write([`agent id: ${n.agent_id}`,`name: ${n.display_name}`,`owner id: ${n.owner_public_id}`,`key fingerprint: ${n.identity_key.jkt} (Ed25519, runtime custody)`,`created: ${n.created_at}`,`auth server: ${n.auth_url}`,`pairing: ${n.pairing_id}`,`status: ${n.pairing_status}`,`key file: ${m8(n.agent_id)}`,"key custody: exportable owner-only runtime file (mode 0600; macOS/Linux)","key recovery: unavailable; copying transfers identity proof and loss blocks new proofs","binding claims (decoded locally, NOT verified):",o?JSON.stringify(o,null,2):" (stored binding is malformed)",""].join(`
|
|
190
190
|
`));return}let i=n.binding_jwt?y8(n.binding_jwt):null;process.stdout.write(["record: legacy v1 (key-addressed; no stable agent id)",`key jkt: ${n.agent_jkt}`,`name: ${n.name}`,`created: ${n.created_at}`,`auth server: ${n.auth_url}`,`pairing: ${n.pairing_id}`,`status: ${n.pairing_status}`,`public key: ${n.public_key_jwk.x} (Ed25519, OKP)`,"registration: stored",`key file: ${m8(n.agent_jkt)}`,"binding claims (decoded locally, NOT verified):",i?JSON.stringify(i,null,2):" (no binding stored or malformed JWT)",""].join(`
|
|
191
|
-
`))})}var yf,YPe,Sy,_re,Iy,vre,wre,p3t,r6=k(()=>{"use strict";yf=_e(require("fs")),YPe=_e(require("os")),Sy=_e(require("path")),_re=require("node:readline/promises");$_();_j();zj();e7();RU();aPe();SPe();PPe();ZU();LPe();G4();w0();Iy=Sy.join(YPe.homedir(),".visa-cli","agents");vre=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,wre=32768,p3t=/[\p{Cc}\p{Cf}\u2028\u2029]/u});var Ure={};Pi(Ure,{SUBWAY_PROTOCOL:()=>fCe,registerDirect:()=>q3t,resolveDirect:()=>D3t});function Rre(e,t){let r=typeof t=="bigint"?t:BigInt(t);for(;r>0x7fn;)e.push(Number(r&0x7fn|0x80n)),r>>=7n;e.push(Number(r))}function yd(e,t){let r=0n,n=0n,i=t;for(;;){let o=e[i++];if(r|=BigInt(o&127)<<n,(o&128)===0)break;n+=7n}return[r,i]}function Nre(e,t){return e<<3|t}function p7(e,t,r){e.push(Nre(t,2)),Rre(e,r.length);for(let n of r)e.push(n)}function T3t(e,t){let r=[];return p7(r,1,kre.encode(e)),t&&t.length>0&&p7(r,2,kre.encode(t)),Uint8Array.from(r)}function I3t(e,t,r){let n=[];return r!==0n&&(n.push(Nre(1,0)),Rre(n,r)),p7(n,2,T3t(e,t)),Uint8Array.from(n)}function P3t(e){let t=[];return p7(t,1,kre.encode(e)),Uint8Array.from(t)}function C3t(e,t){let r=[];return t!==0n&&(r.push(Nre(1,0)),Rre(r,t)),p7(r,3,P3t(e)),Uint8Array.from(r)}function O3t(e){let t=0,r={success:!1,error:""};for(;t<e.length;){let[n,i]=yd(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===0){let[a,c]=yd(e,t);t=c,r.success=a!==0n}else if(o===2&&s===2){let[a,c]=yd(e,t),u=c,d=u+Number(a);r.error=lCe.decode(e.subarray(u,d)),t=d}else t=Bre(e,t,s)}return r}function k3t(e){let t=0,r={peerId:new Uint8Array(0),error:""};for(;t<e.length;){let[n,i]=yd(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===2){let[a,c]=yd(e,t),u=c,d=u+Number(a);r.peerId=e.subarray(u,d),t=d}else if(o===2&&s===2){let[a,c]=yd(e,t),u=c,d=u+Number(a);r.error=lCe.decode(e.subarray(u,d)),t=d}else t=Bre(e,t,s)}return r}function Bre(e,t,r){if(r===0)return yd(e,t)[1];if(r===2){let[n,i]=yd(e,t);return i+Number(n)}if(r===5)return t+4;if(r===1)return t+8;throw new Error(`unsupported wire type ${r}`)}function pCe(e){let t=0,r={requestId:0n};for(;t<e.length;){let[n,i]=yd(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===0){let[a,c]=yd(e,t);t=c,r.requestId=a}else if(o===13&&s===2){let[a,c]=yd(e,t),u=c,d=u+Number(a);r.registerNameResponse=O3t(e.subarray(u,d)),t=d}else if(o===14&&s===2){let[a,c]=yd(e,t),u=c,d=u+Number(a);r.resolveNameResponse=k3t(e.subarray(u,d)),t=d}else t=Bre(e,t,s)}return r}function R3t(e){let t=new Uint8Array(4+e.length);return new DataView(t.buffer).setUint32(0,e.length,!1),t.set(e,4),t}function jre(e){return new DataView(e.buffer,e.byteOffset,4).getUint32(0,!1)}function N3t(e){if(e.length<4)return{success:!1,error:"short reply (no length prefix)"};let t=jre(e.subarray(0,4));return e.length<4+t?{success:!1,error:`truncated frame (have ${e.length-4}, need ${t})`}:pCe(e.subarray(4,4+t)).registerNameResponse??{success:!1,error:"reply carried no register_name_response"}}function B3t(e){if(e.length<4)return{peerId:new Uint8Array(0),error:"short reply (no length prefix)"};let t=jre(e.subarray(0,4));return e.length<4+t?{peerId:new Uint8Array(0),error:`truncated frame (have ${e.length-4}, need ${t})`}:pCe(e.subarray(4,4+t)).resolveNameResponse??{peerId:new Uint8Array(0),error:"reply carried no resolve_name_response"}}function Ore(e){let t=e.reduce((i,o)=>i+o.length,0),r=new Uint8Array(t),n=0;for(let i of e)r.set(i,n),n+=i.length;return r}async function M3t(e){let t=[],r=0,n=-1;for await(let i of e){let o=i instanceof Uint8Array?i:i.subarray();if(t.push(o),r+=o.length,r>nCe)throw new Error("subway: reply exceeded max size");if(n<0&&r>=4&&(n=4+jre(Ore(t).subarray(0,4)),n>nCe))throw new Error("subway: declared frame exceeds max size");if(n>=0&&r>=n)return Ore(t).subarray(0,n)}return Ore(t)}async function mCe(e){return(0,iCe.createLibp2p)({...e?{privateKey:await(0,cCe.generateKeyPairFromSeed)("Ed25519",e)}:{},transports:[(0,oCe.tcp)()],connectionEncrypters:[(0,sCe.noise)()],streamMuxers:[(0,aCe.yamux)()],connectionGater:{denyDialMultiaddr:async()=>!1}})}async function hCe(e,t,r){let n=await e.dialProtocol((0,uCe.multiaddr)(t),fCe,{signal:AbortSignal.timeout(j3t)});n.send(R3t(r));let i;return Promise.race([M3t(n),new Promise((o,s)=>{i=setTimeout(()=>s(new Error("subway: request timed out")),U3t)})]).finally(()=>clearTimeout(i))}async function q3t(e){let t=await mCe(e.seed);try{let r=await hCe(t,e.relayMultiaddr,I3t(e.name,e.binding,e.requestId??1n)),n=N3t(r);return{success:n.success,error:n.error,peerId:t.peerId.toString()}}finally{await t.stop()}}async function D3t(e){let t=await mCe(e.seed);try{let r=await hCe(t,e.relayMultiaddr,C3t(e.name,e.requestId??1n)),n=B3t(r);return n.peerId.length===0?{found:!1,peerId:"",error:n.error||"name not found"}:{found:!0,peerId:(0,dCe.toString)(n.peerId,"base58btc"),error:""}}finally{await t.stop()}}var iCe,oCe,sCe,aCe,cCe,uCe,dCe,kre,lCe,fCe,j3t,U3t,nCe,Mre=k(()=>{"use strict";wte();iCe=require("libp2p"),oCe=require("@libp2p/tcp"),sCe=require("@chainsafe/libp2p-noise"),aCe=require("@chainsafe/libp2p-yamux"),cCe=require("@libp2p/crypto/keys"),uCe=require("@multiformats/multiaddr"),dCe=require("uint8arrays/to-string"),kre=new TextEncoder,lCe=new TextDecoder;fCe="/subway/p2p/1.0.0",j3t=15e3,U3t=15e3,nCe=1<<20});var y7={};Pi(y7,{DEFAULT_VISA_RELAY_MULTIADDR:()=>yCe,MESH:()=>Ci,RELAY_URL:()=>m7,connectOrThrow:()=>_8,ensureMailbox:()=>Zre,hydrateInbox:()=>ACe,isSubwayEnabled:()=>Hre,listRegistered:()=>Gre,loadBindingFor:()=>Vre,loadRegistry:()=>o6,makeClient:()=>b8,meshName:()=>gf,pairedVisaBinding:()=>vCe,pairedVisaBindingForIdentity:()=>wCe,persistInbox:()=>Yre,readInbox:()=>F3t,registerName:()=>h7,resolveActingName:()=>eM,resolveMeshName:()=>Kre,seedSubwayKeyFromExactIdentity:()=>_Ce,seedSubwayKeyFromTapAgent:()=>bCe,sendMessage:()=>Wre,sendVia:()=>V3t,subwayKeyPath:()=>Fre,visaRelayMultiaddr:()=>zre});function zre(e=process.env){return e.SUBWAY_RELAY_MULTIADDR??yCe}function gf(e){return e.includes(".")?e:`${e}.${Ci}`}function Hre(e){if(process.env.VISA_DEV==="1")return!0;let t=e??"0.0.0";return t==="0.0.0"||t.startsWith("0.0.")?!0:/-rc\.|-beta\./.test(t)}function $re(){Ws.mkdirSync(g8,{recursive:!0,mode:448})}function gCe(e){return e.replace(/[^a-zA-Z0-9_.-]/g,"_")}function Fre(e){return f7.join(g8,`${gCe(e)}.key`)}function o6(){if(!Ws.existsSync(Lre))return{};try{return JSON.parse(Ws.readFileSync(Lre,"utf8"))}catch{return{}}}function qre(e){$re(),Ws.writeFileSync(Lre,JSON.stringify(e,null,2),{mode:384})}function Dre(){try{return QU.userInfo().username}catch{return"local"}}function bCe(e){if(Ws.existsSync(e))return null;let t=WU();if(!t)return null;try{let r=r8(t.private_key_jwk);return $re(),Ws.writeFileSync(e,Buffer.from(r),{mode:384}),t.agent_jkt}catch{return null}}function _Ce(e,t){let r=r8(t.identityPrivateJwk);if(df(my(z_(r)))!==t.identityKeyJkt)throw new uf("The selected agent identity key does not match its stable record. Refusing .visa registration.");if(Ws.existsSync(e)){if(df(my(z_(KT(e))))!==t.identityKeyJkt)throw new uf("The existing Subway key belongs to a different agent. Refusing to replace it implicitly.");return t.stableAgentId}return $re(),Ws.writeFileSync(e,Buffer.from(r),{mode:384}),t.stableAgentId}function b8(e,t={}){return new YIe({name:gf(e),url:m7,keyPath:Fre(e),autoReconnect:t.autoReconnect??!1,binding:t.binding})}function Vre(e){if(Ci!=="visa")return;let t=o6()[e];if(t?.binding&&!(t.bindingExpiresAt&&Date.parse(t.bindingExpiresAt)<=Date.now()))return t.binding}async function _8(e,t=15e3){await Promise.race([e.connect(),new Promise((r,n)=>setTimeout(()=>n(new Error(`Subway relay connect timed out after ${t}ms (${m7})`)),t))])}function eM(e){if(e)return e;let t=Object.keys(o6());if(t.length===1)return t[0];throw t.length===0?new Error("No Subway names registered yet. Run `visa register <name>` first."):new Error(`Multiple names registered (${t.join(", ")}). Pass --as <name>.`)}function vCe(e,t=Date.now()){let r=WU();if(!r?.binding_jwt)return null;let n=y8(r.binding_jwt);if(!n||n.mesh!=="visa"||n.name!==e||n.jkt!==r.agent_jkt)return null;let i=typeof n.exp=="number"?n.exp:NaN;return!Number.isFinite(i)||i*1e3<=t?null:{binding:r.binding_jwt,bindingExpiresAt:new Date(i*1e3).toISOString(),identityKeyJkt:r.agent_jkt}}function wCe(e,t,r=Date.now()){for(let n of GU()){if(n.agent_jkt!==t)continue;let i=y8(n.binding_jwt);if(!i||i.mesh!=="visa"||i.name!==e||i.jkt!==t)continue;let o=typeof i.exp=="number"?i.exp:NaN;if(!(!Number.isFinite(o)||o*1e3<=r))return{binding:n.binding_jwt,bindingExpiresAt:new Date(o*1e3).toISOString(),identityKeyJkt:t}}return null}async function h7(e,t={}){let r=Fre(e),n=gf(e),i,o;if(t.exactIdentity){if(o=Ci==="visa"?wCe(n,t.exactIdentity.identityKeyJkt):null,Ci==="visa"&&!o)throw new uf;i=_Ce(r,t.exactIdentity)}else i=bCe(r),o=Ci==="visa"?vCe(n):null;let s,a={};if(o){if(!Ws.existsSync(r))throw new uf("A stored .visa binding exists, but its runtime-held identity key is unavailable. A new identity pairing cannot recreate this separate channel binding.");if(df(my(z_(KT(r))))!==o.identityKeyJkt)throw new uf("The stored .visa binding does not match this Subway identity key. Refusing to present a mismatched legacy admission artifact.");s=o.binding,a={binding:o.binding,bindingExpiresAt:o.bindingExpiresAt}}else if(Ci==="visa")throw new uf;let c=Ci==="visa"?zre():process.env.SUBWAY_RELAY_MULTIADDR;if(Ci==="visa"&&c){let{registerDirect:d}=await Promise.resolve().then(()=>(Mre(),Ure)),l=await d({relayMultiaddr:c,seed:KT(r),name:n,binding:s});if(!l.success)throw new Error(`.visa relay admission failed: ${l.error||"unknown"}`);let p=o6();return p[e]={relayName:n,mesh:Ci,peerId:l.peerId,owner:Dre(),tapAgentId:i,registeredAt:new Date().toISOString(),...a},qre(p),{relayName:n,mesh:Ci,peerId:l.peerId,tapAgentId:i,...s?{binding:s}:{}}}if(Ci==="visa"&&!process.env.SUBWAY_RELAY){let d=o6();return d[e]={relayName:n,mesh:Ci,peerId:null,owner:Dre(),tapAgentId:i,registeredAt:new Date().toISOString(),...a},qre(d),{relayName:n,mesh:Ci,peerId:null,tapAgentId:i,...s?{binding:s}:{},note:s?"Visa binding ready; relay admission pending a .visa relay (set SUBWAY_RELAY).":"No Visa directory/TAP admission binding is stored. Identity pairing does not issue one; use a separately approved directory capability when available."}}let u=b8(e,{autoReconnect:!1,binding:s});try{await _8(u);let d=o6();return d[e]={relayName:n,mesh:Ci,peerId:u.peerId,owner:Dre(),tapAgentId:i,registeredAt:new Date().toISOString(),...a},qre(d),{relayName:n,mesh:Ci,peerId:u.peerId,tapAgentId:i,...s?{binding:s}:{}}}finally{u.disconnect()}}async function Kre(e){let t=gf(e),r=Ci==="visa"?zre():process.env.SUBWAY_RELAY_MULTIADDR;if(Ci==="visa"&&r){let{resolveDirect:n}=await Promise.resolve().then(()=>(Mre(),Ure)),i=await n({relayMultiaddr:r,name:t});return{relayName:t,found:i.found,peerId:i.peerId,error:i.error}}throw new Error("subway find needs the .visa mesh with a dedicated relay \u2014 set SUBWAY_MESH=visa and SUBWAY_RELAY_MULTIADDR.")}async function Wre(e,t,r){let n=b8(e,{autoReconnect:!1,binding:Vre(e)});try{await _8(n);let i=gf(t);return await n.sendSigned(i,"chat",r),{to:i,as:gf(e)}}finally{n.disconnect()}}function Gre(){let e=o6();return Object.entries(e).map(([t,r])=>({name:t,...r}))}function ECe(e,t=g8){return f7.join(t,`${gCe(e)}.inbox.json`)}function z3t(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.from=="string"&&typeof t.text=="string"&&typeof t.ts=="number"&&typeof t.verified=="boolean"}function ACe(e,t=g8){try{let r=JSON.parse(Ws.readFileSync(ECe(e,t),"utf8"));return Array.isArray(r)?r.filter(z3t).slice(-Jre):[]}catch{return[]}}function Yre(e,t,r=g8){try{Ws.mkdirSync(r,{recursive:!0,mode:448}),Ws.writeFileSync(ECe(e,r),JSON.stringify(t.slice(-Jre),null,2),{mode:384})}catch{}}function H3t(e,t){if(t.dirty=!0,t.flushTimer)return;let r=setTimeout(()=>{t.flushTimer=null,t.dirty&&(t.dirty=!1,Yre(e,t.buffer))},L3t);typeof r.unref=="function"&&r.unref(),t.flushTimer=r}function $3t(e,t){t.flushTimer&&(clearTimeout(t.flushTimer),t.flushTimer=null),t.dirty=!1,Yre(e,t.buffer)}async function Zre(e){let t=XU.get(e);if(t)return{relayName:gf(e),peerId:t.client.peerId};let r=b8(e,{autoReconnect:!0,binding:Vre(e)}),n=ACe(e),i={client:r,buffer:n,flushTimer:null,dirty:!1};return r.onMessage(o=>{n.push({from:o.fromName,text:o.payload,ts:o.timestampMs,verified:!!o.verified}),n.length>Jre&&n.shift(),H3t(e,i)}),XU.set(e,i),await _8(r),{relayName:gf(e),peerId:r.peerId}}async function F3t(e,t=20,r=!1){await Zre(e);let n=XU.get(e);if(!n)return[];let i=n.buffer.slice(-t);return r&&(n.buffer.length=0,$3t(e,n)),i}async function V3t(e,t,r){await Zre(e);let n=XU.get(e);if(!n)throw new Error(`mailbox for ${e} unavailable`);let i=gf(t);return await n.client.sendSigned(i,"chat",r),{to:i,as:gf(e)}}var Ws,QU,f7,Ci,yCe,m7,g8,Lre,XU,Jre,L3t,s6=k(()=>{"use strict";Fte();$_();Ws=_e(require("fs")),QU=_e(require("os")),f7=_e(require("path"));WT();r6();Ci=process.env.SUBWAY_MESH??"relay",yCe="/dns4/subway-relay-visa.fly.dev/tcp/9100/p2p/12D3KooWM2q6SXgKFxj5wvnJ7gTD4XPjhvc5tHVVjDBrZRnJ3CKU";m7=process.env.SUBWAY_RELAY??"wss://relay.subway.dev/ws";g8=f7.join(QU.homedir(),".visa-cli","subway"),Lre=f7.join(g8,"registry.json");XU=new Map,Jre=200,L3t=100});var DCe={};Pi(DCe,{PAIRING_DIR:()=>_f,cancelPairing:()=>Cre,claimPairing:()=>i6,getPairingStatus:()=>YU,initiatePairing:()=>l7,latestPendingHumanPairing:()=>$U,latestPendingRuntimePairing:()=>aM,pairingFilePath:()=>sM,pollAndActivatePairing:()=>FU,readPendingPairing:()=>hd,registerOnVisaMeshIfEnabled:()=>JU,removePendingPairing:()=>d7,tryActivatePairing:()=>sne,verifyPairing:()=>Ty,writePendingPairing:()=>one});async function JU(e){if(process.env.SUBWAY_MESH!=="visa")return!1;try{return await h7(e),!0}catch(t){return Ce.warn("subway:pairing-auto-register-failed",{name:e,mesh:"visa",error:t instanceof Error?t.message:String(t)}),!1}}function cc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function bf(e,t){let r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function ene(e){return typeof e=="string"&&G3t.test(e)}function v8(e){return typeof e=="string"&&J3t.test(e)}function g7(e){if(typeof e!="string")return!1;let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}function OCe(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost"||t==="::1")return!0;let r=t.split(".");return r.length===4&&r[0]==="127"&&r.every(n=>/^\d{1,3}$/.test(n)&&Number(n)<=255)}function rM(e){if(typeof e!="string"||e.length===0||e.length>CCe)return!1;try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:"&&OCe(t.hostname))&&t.username.length===0&&t.password.length===0}catch{return!1}}function oM(e){if(e.length===0||e.length>CCe)throw new Error("auth URL must be a bounded absolute URL");let t;try{t=new URL(e)}catch{throw new Error("auth URL must be a bounded absolute URL")}if(t.username.length>0||t.password.length>0||t.search.length>0||t.hash.length>0||t.protocol!=="https:"&&!(t.protocol==="http:"&&OCe(t.hostname)))throw new Error("auth URL must use HTTPS (or HTTP on a loopback host) without credentials");let r=t.pathname.replace(/\/+$/,"");return`${t.origin}${r===""||r==="/"?"":r}`}function tne(e){if(typeof e!="string")return!1;try{return oM(e)===e}catch{return!1}}function X3t(e){return cc(e)&&bf(e,["kty","crv","x"])&&e.kty==="OKP"&&e.crv==="Ed25519"&&Cr(e.x)}function Q3t(e){return cc(e)&&bf(e,["kty","crv","x","d"])&&e.kty==="OKP"&&e.crv==="Ed25519"&&Cr(e.x)&&Cr(e.d)}function eEt(e,t){try{let r=H_(Buffer.from(e.d,"base64url"));return r.x===t.x&&r.d===e.d}catch{return!1}}function tM(e,t){if(typeof e!="string"||Y3t.test(e))return null;let r=e.normalize("NFC").trim();return r.length>0&&r.length<=t?r:null}function kCe(e){if(!cc(e)||!bf(e,["runtime","contextLabel","cliVersion","platform"]))return null;let t=tM(e.runtime,100),r=tM(e.contextLabel,200),n=e.cliVersion===void 0?void 0:tM(e.cliVersion,64),i=e.platform===void 0?void 0:tM(e.platform,100);return!t||!r||e.cliVersion!==void 0&&!n||e.platform!==void 0&&!i?null:{runtime:t,contextLabel:r,...n?{cliVersion:n}:{},...i?{platform:i}:{}}}function tEt(e){if(!cc(e))return!1;let t=kCe(e);return t?t.runtime===e.runtime&&t.contextLabel===e.contextLabel&&t.cliVersion===e.cliVersion&&t.platform===e.platform:!1}function RCe(e){return cc(e)?bf(e,["role","protocolVersion","pairingId","agentId","verifier","authUrl","skillUrl","expiresAt","createdAt"])&&e.role==="human"&&e.protocolVersion===jt&&v8(e.pairingId)&&ene(e.agentId)&&Cr(e.verifier)&&tne(e.authUrl)&&rM(e.skillUrl)&&g7(e.expiresAt)&&g7(e.createdAt):!1}function NCe(e){return!cc(e)||!bf(e,["role","protocolVersion","pairingId","agentId","authUrl","claimToken","serverNonce","identityKeyJkt","identityPublicJwk","identityPrivateJwk","runtime","createdAt"])||e.role!=="runtime"||e.protocolVersion!==jt||!v8(e.pairingId)||!ene(e.agentId)||!tne(e.authUrl)||!Cr(e.claimToken)||!Cr(e.serverNonce)||!Cr(e.identityKeyJkt)||!X3t(e.identityPublicJwk)||!Q3t(e.identityPrivateJwk)||!tEt(e.runtime)||!g7(e.createdAt)?!1:e.identityPublicJwk.x===e.identityPrivateJwk.x&&df(e.identityPublicJwk)===e.identityKeyJkt&&eEt(e.identityPrivateJwk,e.identityPublicJwk)}function rEt(e){return cc(e)&&bf(e,["protocolVersion","verifier","authUrl","createdAt"])&&e.protocolVersion===jt&&Cr(e.verifier)&&tne(e.authUrl)&&g7(e.createdAt)}function b7(e,t,r){if(!cc(e)||e.protocolVersion!==jt||!v8(e.pairingId)||!ene(e.agentId)||typeof e.state!="string"||!Z3t.has(e.state)||!g7(e.expiresAt)||e.skillUrl!==void 0&&!rM(e.skillUrl)||e.authorizationUrl!==void 0&&!rM(e.authorizationUrl)||e.serverNonce!==void 0&&!Cr(e.serverNonce)||e.authApiUrl!==void 0&&!rM(e.authApiUrl)||e.failureCode!==void 0&&typeof e.failureCode!="string"||t!==void 0&&e.pairingId!==t||r!==void 0&&e.agentId!==r)throw new Error("pairing server returned an invalid v2 status response")}function sM(e,t,r=_f){if(!v8(e))throw new Error("pairing id must use the canonical ap_ + 24 base64url form");return iM.join(r,`${e}.${t}.json`)}function BCe(e){ql.mkdirSync(e,{recursive:!0,mode:448});let t=ql.lstatSync(e);if(t.isSymbolicLink()||!t.isDirectory())throw new Error("pairing directory must be a real directory, not a symlink");ql.chmodSync(e,448),ac(e)}function rne(e){return iM.join(e,K3t)}function nne(e){let t=e6(rne(e));if(t===null)return null;let r;try{r=JSON.parse(t)}catch{throw new Error("local pairing initiation state contains invalid JSON")}if(!rEt(r))throw new Error("local pairing initiation state is invalid");return r}function nEt(e,t){BCe(t),B0(rne(t),JSON.stringify(e,null,2))}function xCe(e,t){let r=nne(t);if(!r)return;let n=hd(e,"human",t);n&&n.verifier===r.verifier&&n.authUrl===r.authUrl&&ine(t)}function ine(e){nne(e)&&ac(e)&&ql.rmSync(rne(e),{force:!0})}function one(e,t=_f){if(!(e.role==="human"?RCe(e):NCe(e)))throw new Error("refusing to write invalid protocol-v2 pending pairing state");BCe(t);let n=sM(e.pairingId,e.role,t);B0(n,JSON.stringify(e,null,2))}function d7(e,t,r=_f){hd(e,t,r)&&ac(r)&&ql.rmSync(sM(e,t,r),{force:!0})}function Xre(e,t=_f){d7(e,"human",t),d7(e,"runtime",t),ine(t)}function hd(e,t,r=_f){if(!v8(e))return null;let n=e6(sM(e,t,r));if(n===null)return null;let i;try{i=JSON.parse(n)}catch{throw new Error(`local ${t} pairing state for ${e} contains invalid JSON`)}if(t==="human"){if(!RCe(i)||i.pairingId!==e)throw new Error(`local human pairing state for ${e} is invalid or misbound`);return i}if(!NCe(i)||i.pairingId!==e)throw new Error(`local runtime pairing state for ${e} is invalid or misbound`);return i}function jCe(e,t){return ac(t)?ql.readdirSync(t).filter(n=>n.endsWith(`.${e}.json`)).map(n=>{let i=n.slice(0,-`.${e}.json`.length);if(!v8(i))throw new Error(`local ${e} pairing filename ${n} is invalid`);return hd(i,e,t)}).filter(n=>n!==null).sort((n,i)=>i.createdAt.localeCompare(n.createdAt))[0]??null:null}function $U(e=_f){return jCe("human",e)}function aM(e=_f){return jCe("runtime",e)}function nM(e,t="pairing operation aborted"){return e.reason instanceof Error?e.reason:new Error(t)}function Qre(e,t){return t?t.aborted?Promise.reject(nM(t)):new Promise((r,n)=>{let i=()=>n(nM(t));t.addEventListener("abort",i,{once:!0}),e.then(o=>{t.removeEventListener("abort",i),r(o)},o=>{t.removeEventListener("abort",i),n(o)})}):e}async function a6(e,t,r,n={}){let i=new AbortController,o=()=>{let a=n.signal?.reason;i.abort(a instanceof Error?a:new Error("pairing operation aborted"))};n.signal?.aborted?o():n.signal?.addEventListener("abort",o,{once:!0});let s=setTimeout(()=>i.abort(new Error(`pairing request timed out after ${SCe}ms`)),SCe);s.unref?.();try{if(i.signal.aborted)throw nM(i.signal);let a=await Qre(r(e,{...t,headers:{"X-Source":"cli","X-Visa-CLI-Version":PCe,...t.headers??{}},redirect:"error",signal:i.signal}),i.signal),c;try{c=await Qre(a.json(),i.signal)}catch{if(i.signal.aborted)throw nM(i.signal);c={}}if(!a.ok&&a.status!==202){let u=cc(c)?c:{},d=typeof u.error=="string"?u.error:void 0,l=typeof u.detail=="string"?u.detail:void 0;throw new Error(d??l??`pairing server returned ${a.status}`)}return{status:a.status,body:c}}finally{clearTimeout(s),n.signal?.removeEventListener("abort",o)}}async function l7(e={}){let t=oM(e.authUrl??Sa()),r=e.pairingDir??_f,n=nne(r),i=n?Date.parse(n.createdAt):Number.NaN,o=n!==null&&Number.isFinite(i)&&Date.now()-i<W3t;if(o&&n.authUrl!==t)throw new Error("a pairing initiation is pending for a different auth origin; retry it first");let s=o?n:{protocolVersion:jt,verifier:C7e(),authUrl:t,createdAt:new Date().toISOString()};o||nEt(s,r);let a=s.verifier,{body:c}=await a6(`${t}/v4/agent-pairings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({protocolVersion:jt,cliChallenge:O7e(a)})},e.fetchImpl??fetch,{signal:e.signal});if(b7(c),c.state!=="awaiting_agent"||!c.skillUrl)throw new Error("pairing server returned an incomplete v2 initiation response");let u={role:"human",protocolVersion:jt,pairingId:c.pairingId,agentId:c.agentId,verifier:a,authUrl:t,skillUrl:Wee(c.skillUrl),expiresAt:c.expiresAt,createdAt:new Date().toISOString()};return one(u,r),e.retainInitiationDraft||ine(r),u}function UCe(e){return e.authorizationUrl?{...e,authorizationUrl:Wee(e.authorizationUrl)}:e}async function Ty(e){let{pairing:t}=e,{body:r}=await a6(`${t.authUrl}/v4/agent-pairings/${encodeURIComponent(t.pairingId)}/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({protocolVersion:jt,verifier:t.verifier,code:e.code})},e.fetchImpl??fetch,{signal:e.signal});return b7(r,t.pairingId,t.agentId),UCe(r)}async function YU(e){let t=oM(e.authUrl??Sa()),{body:r}=await a6(`${t}/v4/agent-pairings/${encodeURIComponent(e.pairingId)}`,{method:"GET",cache:"no-store"},e.fetchImpl??fetch,{signal:e.signal});return b7(r,e.pairingId,e.expectedAgentId),UCe(r)}function MCe(e,t){return Buffer.from(t8(e,Buffer.from(t,"utf8"))).toString("base64url")}function iEt(e){let t=MCe(Buffer.from(e.identityPrivateJwk.d,"base64url"),gte({protocolVersion:jt,pairingId:e.pairingId,agentId:e.agentId,serverNonce:e.serverNonce,claimTokenHash:P0(e.claimToken),identityKeyJkt:e.identityKeyJkt,runtime:e.runtime}));return{protocolVersion:jt,agentId:e.agentId,identityPublicJwk:e.identityPublicJwk,runtime:e.runtime,signature:t,claimToken:e.claimToken}}async function TCe(e,t,r){let{body:n}=await a6(`${e.authUrl}/v4/agent-pairings/${encodeURIComponent(e.pairingId)}/claim`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(iEt(e))},t,{signal:r}),i=n;if(!cc(i)||!bf(i,["protocolVersion","pairingId","agentId","state","verificationCode","claimToken"])||i.protocolVersion!==jt||i.pairingId!==e.pairingId||i.agentId!==e.agentId||typeof i.state!="string"||!["agent_claimed","code_verified","awaiting_human","authorized","delivered","activated"].includes(i.state)||i.claimToken!==e.claimToken||typeof i.verificationCode!="string"||i.verificationCode!==aU(e.pairingId,e.claimToken))throw new Error("pairing server returned an invalid v2 claim response");return{pending:e,verificationCode:i.verificationCode}}async function i6(e){let t=oM(e.authUrl??Sa()),r=e.fetchImpl??fetch,n=e.pairingDir??_f,i=kCe({runtime:e.runtime,contextLabel:e.contextLabel,platform:`${process.platform}/${process.arch}`,cliVersion:PCe});if(!i)throw new Error("runtime metadata must be canonical, bounded, non-empty text");let o=hd(e.pairingId,"runtime",n);if(o){if(o.authUrl!==t||o.runtime.runtime!==i.runtime||o.runtime.contextLabel!==i.contextLabel)throw new Error("this pairing already has a different pending runtime claim; resume it");return xCe(o.pairingId,n),TCe(o,r,e.signal)}let s=await YU({pairingId:e.pairingId,authUrl:t,fetchImpl:r,signal:e.signal});if(s.state!=="awaiting_agent"||!Cr(s.serverNonce))throw new Error(`pairing cannot be claimed from state ${s.state}`);let a=_7e(),c=H_(a.secretKey),u=my(a.publicKey),d=df(u),l=i,p=sU();gte({protocolVersion:jt,pairingId:e.pairingId,agentId:s.agentId,serverNonce:s.serverNonce,claimTokenHash:P0(p),identityKeyJkt:d,runtime:l});let f={role:"runtime",protocolVersion:jt,pairingId:e.pairingId,agentId:s.agentId,authUrl:t,claimToken:p,serverNonce:s.serverNonce,identityKeyJkt:d,identityPublicJwk:u,identityPrivateJwk:c,runtime:l,createdAt:new Date().toISOString()};return one(f,n),xCe(f.pairingId,n),TCe(f,r,e.signal)}async function qCe(e){let t=e.fetchImpl??fetch,{body:r,status:n}=await a6(`${e.pending.authUrl}/v4/agent-pairings/${encodeURIComponent(e.pending.pairingId)}/delivery`,{method:"GET",headers:{"X-Agent-Pairing-Token":e.pending.claimToken},cache:"no-store"},t,{signal:e.signal});if(n===202){if(b7(r,e.pending.pairingId,e.pending.agentId),e.onState?.(r.state),["expired","cancelled","failed","revoked"].includes(r.state))throw Xre(e.pending.pairingId,e.pairingDir),new Error(`pairing ended in state ${r.state}`);return null}if(!cc(r)||!bf(r,["protocolVersion","pairingId","agentId","state","artifact","deliveryArtifactHash"])||r.protocolVersion!==jt||r.pairingId!==e.pending.pairingId||r.agentId!==e.pending.agentId||r.state!=="delivered"&&r.state!=="activated"||!cc(r.artifact)||!Cr(r.deliveryArtifactHash))throw new Error("pairing delivery omitted the canonical v2 identity artifact");e.onState?.(r.state);let i=FT(r.artifact),o=JSON.parse(i),s=B7e(o);if(s!==r.deliveryArtifactHash||o.pairingId!==e.pending.pairingId||o.agentId!==e.pending.agentId||o.identityKey.jkt!==e.pending.identityKeyJkt||o.identityKey.publicJwk.x!==e.pending.identityPublicJwk.x)throw new Error("pairing v2 delivery artifact did not match this pending identity claim");let a=MCe(Buffer.from(e.pending.identityPrivateJwk.d,"base64url"),R7e({protocolVersion:jt,pairingId:e.pending.pairingId,agentId:e.pending.agentId,ownerPublicId:o.ownerPublicId,claimTokenHash:P0(e.pending.claimToken),identityKeyJkt:e.pending.identityKeyJkt,ceremonyHash:o.ceremonyHash,deliveryArtifactHash:s})),c=await a6(`${e.pending.authUrl}/v4/agent-pairings/${encodeURIComponent(e.pending.pairingId)}/activate`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Pairing-Token":e.pending.claimToken},body:JSON.stringify({protocolVersion:jt,agentId:e.pending.agentId,signature:a})},t,{signal:e.signal}),u=o.terms,d=c.body;if(!cc(d)||!bf(d,["protocolVersion","state","pairingId","agentId","ownerPublicId","identityKeyJkt","displayName","credentials"])||d.protocolVersion!==jt||d.state!=="activated"||d.pairingId!==e.pending.pairingId||d.agentId!==e.pending.agentId||d.ownerPublicId!==o.ownerPublicId||d.identityKeyJkt!==e.pending.identityKeyJkt||d.displayName!==u.displayName||!cc(d.credentials)||!bf(d.credentials,["bindingJwt","registrationJwt"])||typeof d.credentials.bindingJwt!="string"||d.credentials.bindingJwt.length===0||typeof d.credentials.registrationJwt!="string"||d.credentials.registrationJwt.length===0)throw new Error("pairing server returned an invalid v2 activation response");let l={v:jt,agent_id:e.pending.agentId,owner_public_id:o.ownerPublicId,display_name:c.body.displayName,identity_key:{jkt:e.pending.identityKeyJkt,public_jwk:e.pending.identityPublicJwk,private_jwk:e.pending.identityPrivateJwk,custody:"runtime"},pairing_id:e.pending.pairingId,pairing_status:"activated",activation_credentials:{binding_jwt:d.credentials.bindingJwt,registration_jwt:d.credentials.registrationJwt},delivery_artifact:o,auth_url:e.pending.authUrl,created_at:new Date().toISOString()};(e.writeAgentRecord??Ire)(l,e.agentDir),Xre(e.pending.pairingId,e.pairingDir);let p=await JU(l.display_name);return process.env.SUBWAY_MESH==="visa"&&Ce.info("agent:fresh_activate_mesh",{name:l.display_name,meshRegistered:p}),{record:l,name:l.display_name,agentId:l.agent_id,identityKeyJkt:l.identity_key.jkt}}async function sne(e){return qCe(e)}async function FU(e){let t=e.wait??(i=>new Promise(o=>setTimeout(o,i))),r=e.maxPolls??450,n="";for(let i=0;i<r;i+=1){let o=await qCe({...e,onState:s=>{s!==n&&(n=s,e.onState?.(s))}});if(o)return o;i+1<r&&await Qre(t(e.pollIntervalMs??2e3),e.signal)}throw new Error("timed out waiting for human authorization")}async function Cre(e){let{pairing:t}=e,{body:r}=await a6(`${t.authUrl}/v4/agent-pairings/${encodeURIComponent(t.pairingId)}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({protocolVersion:jt,verifier:t.verifier})},e.fetchImpl??fetch,{signal:e.signal});return b7(r,t.pairingId,t.agentId),r.state==="cancelled"&&Xre(t.pairingId,e.pairingDir),r}var ql,ICe,iM,PCe,_f,K3t,W3t,G3t,J3t,Y3t,Z3t,CCe,SCe,ZU=k(()=>{"use strict";ql=_e(require("node:fs")),ICe=_e(require("node:os")),iM=_e(require("node:path"));$_();ay();zj();pd();WT();s6();e7();r6();PCe="4.1.0-rc.50",_f=iM.join(ICe.homedir(),".visa-cli","pairings"),K3t=".initiation.v2.json",W3t=15*6e4,G3t=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,J3t=/^ap_[A-Za-z0-9_-]{24}$/,Y3t=/[\p{Cc}\p{Cf}\u2028\u2029]/u,Z3t=new Set(["awaiting_agent","agent_claimed","code_verified","awaiting_human","authorized","delivered","activated","expired","cancelled","failed","revoked"]),CCe=2048;SCe=3e4});function LCe(e){return e.reason instanceof Error?e.reason:new Error("agent pairing timed out")}function oEt(e,t){return t?t.aborted?Promise.reject(LCe(t)):new Promise((r,n)=>{let i=()=>n(LCe(t));t.addEventListener("abort",i,{once:!0}),e.then(o=>{t.removeEventListener("abort",i),r(o)},o=>{t.removeEventListener("abort",i),n(o)})}):e}function sEt(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return t===e.length?e:e.slice(0,t)}function zCe(e,t){if(t!==void 0&&sEt(t)!==e)throw new Error("auth URL does not match the pending pairing; resume with the original origin")}function aEt(e){return{status:"activated",protocolVersion:jt,pairingId:e.record.pairing_id,agentId:e.agentId,displayName:e.name,identityKeyJkt:e.identityKeyJkt}}async function c7(e={}){let t=aM(e.pairingDir);if(t){zCe(t.authUrl,e.authUrl);let s=hd(t.pairingId,"human",e.pairingDir);if(!s||s.agentId!==t.agentId)throw new Error("a runtime pairing is already pending without its local human proof; resume or cancel it before starting another");let a=await i6({pairingId:t.pairingId,runtime:t.runtime.runtime,contextLabel:t.runtime.contextLabel,authUrl:t.authUrl,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,...e.signal?{signal:e.signal}:{}}),c=await Ty({pairing:s,code:a.verificationCode,fetchImpl:e.fetchImpl,...e.signal?{signal:e.signal}:{}});if(!c.authorizationUrl)throw new Error("authorization URL missing after v2 pairing verification");return{protocolVersion:jt,pairingId:t.pairingId,agentId:t.agentId,requestKeyFingerprint:t.identityKeyJkt,authorizationUrl:c.authorizationUrl,expiresAt:s.expiresAt}}let r=await l7({authUrl:e.authUrl,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,...e.signal?{signal:e.signal}:{},retainInitiationDraft:!0}),{pending:n,verificationCode:i}=await i6({pairingId:r.pairingId,runtime:e.runtime??"visa-cli",contextLabel:e.contextLabel??"Pair this runtime",authUrl:r.authUrl,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,...e.signal?{signal:e.signal}:{}});if(n.agentId!==r.agentId)throw new Error("pairing claim returned a different stable agent id");let o=await Ty({pairing:r,code:i,fetchImpl:e.fetchImpl,...e.signal?{signal:e.signal}:{}});if(!o.authorizationUrl)throw new Error("authorization URL missing after v2 pairing verification");return{protocolVersion:jt,pairingId:r.pairingId,agentId:r.agentId,requestKeyFingerprint:n.identityKeyJkt,authorizationUrl:o.authorizationUrl,expiresAt:r.expiresAt}}function cEt(e,t){if(!e)return!1;let r=Date.parse(e.expiresAt);return Number.isFinite(r)&&t>=r}async function u7(e={}){let t=aM(e.pairingDir);if(!t)return{status:"no_pending"};let r=hd(t.pairingId,"human",e.pairingDir);try{zCe(t.authUrl,e.authUrl);let n=Math.max(1,e.attempts??1),i=e.sleep??(o=>new Promise(s=>setTimeout(s,o)));for(let o=0;o<n;o+=1){let s="",a=await sne({pending:t,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,agentDir:e.agentDir,...e.signal?{signal:e.signal}:{},onState:c=>{s=c}});if(a)return aEt(a);if(o===0&&["awaiting_agent","agent_claimed","code_verified"].includes(s)){if(!r)throw new Error("pending pairing is missing its local human verification proof");let c=await i6({pairingId:t.pairingId,runtime:t.runtime.runtime,contextLabel:t.runtime.contextLabel,authUrl:t.authUrl,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,...e.signal?{signal:e.signal}:{}});await Ty({pairing:r,code:c.verificationCode,fetchImpl:e.fetchImpl,...e.signal?{signal:e.signal}:{}})}o+1<n&&await oEt(i(e.delayMs??3e3),e.signal)}return{status:"not_ready",protocolVersion:jt,pairingId:t.pairingId,agentId:t.agentId,likelyExpired:cEt(r,(e.now??Date.now)())}}catch(n){return{status:"error",message:n instanceof Error?n.message:String(n)}}}async function cPe(e){if(typeof e!="string"||e.trim().length===0)return!1;try{return await An.saveSessionToken(e),!0}catch{return!1}}var RU=k(()=>{"use strict";$_();w0();ZU()});var lne={};Pi(lne,{CardDrawRefusedError:()=>c6,cardDrawIntentHash:()=>XCe,decimalUsdToCents:()=>dne,fetchCardDrawVerdict:()=>EEt,loadCardMandateCapability:()=>wEt,registerCardMandate:()=>AEt});function yEt(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(0,une.createHash)("sha256").update(t,"utf8").digest().toString("base64url")}function gEt(e){let{secretKey:t,publicKey:r}=v7e(e),n=H_(t),i=my(r);return{privateJwk:n,publicJwk:i,jkt:yEt(i)}}async function YCe(e,t){let n={cnf:{jwk:{kty:e.publicJwk.kty,crv:e.publicJwk.crv,x:e.publicJwk.x}},nonce:t.nonce,aud:t.audience,iat:t.nowSec};t.intentHash!==void 0&&(n.int=t.intentHash);let i={alg:"EdDSA",kid:e.jkt,typ:hEt},o=`${GCe(i)}.${GCe(n)}`,s=r8(e.privateJwk),a=t8(s,Buffer.from(o,"utf8"));return`${o}.${Buffer.from(a).toString("base64url")}`}function ZCe(e){let{amount:t,currency:r,payee:n,intentId:i}=e;if(!Number.isSafeInteger(t)||t<=0)throw new Error(`intent.amount must be a positive safe integer in minor units (cents); got ${String(t)}`);let o=typeof r=="string"?r.toUpperCase():"";if(!bEt.has(o))throw new Error(`intent.currency must be a supported ISO 4217 code; got ${JSON.stringify(r)}`);if(typeof n!="string"||n.length===0)throw new Error("intent.payee must be a non-empty string");if(i!==void 0&&(typeof i!="string"||i.length===0))throw new Error("intent.intentId, when present, must be a non-empty string");let s=JSON.stringify({v:_Et,amount:t,currency:o,payee:n,intentId:i??null,settlementHash:null});return(0,une.createHash)("sha256").update(s,"utf8").digest().toString("base64url")}function vEt(e){let t=e.split(".");if(t.length!==3)return null;try{let r=JSON.parse(Buffer.from(t[1],"base64url").toString("utf8"));return typeof r.mode=="string"?r.mode:null}catch{return null}}function dne(e){let t=/^([0-9]+)(?:\.([0-9]{1,2}))?$/.exec(e);if(!t)return null;let r=Number(t[1]),n=Number(((t[2]??"")+"00").slice(0,2)),i=r*100+n;return Number.isSafeInteger(i)?i:null}function XCe(e,t){let r=dne(e.amount);return r===null?null:ZCe({amount:r,currency:e.currency,payee:e.merchantUrl,intentId:t})}function wEt(e={}){let r=(e.record!==void 0?e.record?[e.record]:[]:e.records??(r6(),ie(rCe)).listLegacyAgentRecords()).flatMap(i=>{if(!i.binding_jwt||!i.auth_url)return[];let o=vEt(i.binding_jwt);if(o!=="card"&&o!=="both")return[];let s;try{s=gEt(r8(i.private_key_jwk))}catch{return[]}return s.jkt!==i.agent_jkt?[]:[{record:i,capability:{agentKey:s,agentJkt:i.agent_jkt,authBaseUrl:i.auth_url}}]}),n=e.agentRef?.trim();if(n){let i=n.replace(/\.visa$/i,"").toLowerCase(),o=r.filter(({record:s})=>s.agent_jkt===n||s.name.replace(/\.visa$/i,"").toLowerCase()===i);if(o.length>1)throw new Error(`more than one card capability is named "${n}"; select the exact request-key JKT`);return o[0]?.capability??null}if(r.length>1)throw new Error("more than one card-capable agent is available; select one explicitly with --agent (name or request-key JKT)");return r[0]?.capability??null}async function uM(e,t,r){let n=new AbortController,i=setTimeout(()=>n.abort(new Error(`card authority request timed out after ${JCe}ms`)),JCe);i.unref?.();try{return await e(t,{...r,redirect:"error",signal:n.signal})}finally{clearTimeout(i)}}function QCe(e){return e.replace(/\/+$/,"")}async function EEt(e){let t=e.fetchImpl??fetch,r=e.now??(()=>Math.floor(Date.now()/1e3)),n=QCe(e.authBaseUrl),i=XCe(e.draw,e.drawId);if(i===null)throw new c6(400,["invalid_amount"]);let o=await uM(t,`${n}/v4/card/draw/challenge`,{method:"POST",headers:{"content-type":"application/json","x-source":"cli"}});if(!o.ok)throw new c6(o.status,["challenge_failed"]);let s=await o.json();if(!s.nonce||!s.audience)throw new c6(502,["challenge_malformed"]);let a=await YCe(e.agentKey,{nonce:s.nonce,audience:s.audience,nowSec:r(),intentHash:i}),c=await uM(t,`${n}/v4/card/draw-verdict`,{method:"POST",headers:{"content-type":"application/json","x-source":"cli"},body:JSON.stringify({nonce:s.nonce,popJwt:a,mandateId:e.mandateId,drawId:e.drawId,draw:e.draw})}),u=await c.json().catch(()=>null);if(!c.ok||!u?.ok||typeof u.verdict!="string")throw new c6(c.status,u?.reasons??["verdict_refused"]);return{verdict:u.verdict,remainingCents:Number(u.remainingCents??0)}}async function AEt(e){try{let t=e.fetchImpl??fetch,r=e.now??(()=>Math.floor(Date.now()/1e3)),n=QCe(e.authBaseUrl),i=dne(e.ceiling);if(i===null)return{ok:!1,reason:"invalid_amount"};let o=ZCe({amount:i,currency:e.currency,payee:"card-mandate-register",intentId:e.mandateId}),s=await uM(t,`${n}/v4/card/draw/challenge`,{method:"POST",headers:{"content-type":"application/json","x-source":"cli"}});if(!s.ok)return{ok:!1,reason:"challenge_failed"};let a=await s.json();if(!a.nonce||!a.audience)return{ok:!1,reason:"challenge_malformed"};let c=await YCe(e.agentKey,{nonce:a.nonce,audience:a.audience,nowSec:r(),intentHash:o}),u=await uM(t,`${n}/v4/card/mandate/register`,{method:"POST",headers:{"content-type":"application/json","x-source":"cli"},body:JSON.stringify({nonce:a.nonce,popJwt:c,mandateId:e.mandateId,mintToken:e.mintToken})}),d=await u.json().catch(()=>null);return!u.ok||!d?.ok?{ok:!1,reason:d?.reasons?.[0]??"register_refused"}:{ok:!0}}catch(t){return{ok:!1,reason:t instanceof Error?t.message:String(t)}}}var une,hEt,GCe,bEt,_Et,c6,JCe,pne=k(()=>{"use strict";une=require("node:crypto");$_();hEt="visa-agent-pop+jwt",GCe=e=>Buffer.from(JSON.stringify(e),"utf8").toString("base64url");bEt=new Set(["USD","EUR","GBP","CAD","AUD","JPY","CHF","CNY","HKD","SGD","INR","MXN","BRL","NZD","SEK","NOK","DKK","ZAR","AED"]),_Et=1;c6=class extends Error{constructor(r,n){super(`card draw refused (${r}): ${n.join(", ")||"unknown"}`);this.status=r;this.reasons=n;this.name="CardDrawRefusedError"}status;reasons},JCe=3e4});var Pke=g(Hl=>{"use strict";Object.defineProperty(Hl,"__esModule",{value:!0});Hl.formatCents=Ike;Hl.formatUsd=J9t;Hl.formatMicros=OM;Hl.formatMicrosWire=Y9t;Hl.formatTxAmount=Z9t;Hl.formatDate=X9t;Hl.formatRelativeTime=Q9t;Hl.formatTime=eSt;Hl.formatAge=tSt;var Tke=1e6,G9t=100;function Ike(e,t={}){let r=t.fallback??"\u2014";if(e==null||!Number.isFinite(e))return r;let i=(e/G9t).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??2});return t.showPlusSign&&e>0?`+${i}`:i}function J9t(e,t={}){let r=t.fallback??"\u2014";if(e==null||!Number.isFinite(e))return r;let n=e.toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??2});return t.showPlusSign&&e>0?`+${n}`:n}function OM(e,t={}){let r=t.fallback??"\u2014",n=typeof e=="string"?e===""?null:Number(e):e;if(n==null||!Number.isFinite(n))return r;let o=(n/Tke).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??6});return t.showPlusSign&&n>0?`+${o}`:o}function Y9t(e,t,r={}){return e&&/^-?\d+$/.test(e)?OM(e,r):t!=null&&Number.isFinite(t)?Ike(t,r):r.fallback??"\u2014"}function Z9t(e,t={}){let r=Number(e.amount_micros);if(Number.isFinite(r)&&e.amount_micros!=null&&e.amount_micros!=="")return OM(r,t);let n=Number(String(e.amount).replace(/^\$/,""));return Number.isFinite(n)?OM(n*Tke,t):t.fallback??"\u2014"}function X9t(e,t={}){let r=t.fallback??"\u2014";if(!e)return r;let n=new Date(e);return Number.isNaN(n.getTime())?r:n.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:t.timeZone??"UTC"})}function Q9t(e,t=Date.now()){if(!e)return"\u2014";let r=Date.parse(e);if(Number.isNaN(r))return"\u2014";let n=t-r,i=n>=0,o=Math.abs(n),s=Math.floor(o/1e3),a=Math.floor(s/60),c=Math.floor(a/60),u=Math.floor(c/24),d=Math.floor(u/7),l=Math.floor(u/30),p=Math.floor(u/365);return s<45?"just now":a<1?i?"a minute ago":"in a minute":a<60?L8(n,i,a,"minute"):c<24?L8(n,i,c,"hour"):u===1?i?"yesterday":"tomorrow":u<7?L8(n,i,u,"day"):d<4?L8(n,i,d,"week"):l<12?L8(n,i,l,"month"):L8(n,i,p,"year")}function L8(e,t,r,n){let i=r!==1?"s":"";return t?`${r} ${n}${i} ago`:`in ${r} ${n}${i}`}function eSt(e,t={}){let r=t.fallback??"\u2014";if(!e)return r;let n=new Date(e);return Number.isNaN(n.getTime())?r:n.toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit",timeZone:t.timeZone??"UTC"})}function tSt(e,t){if(!e)return"";let r=Date.parse(e);if(Number.isNaN(r))return"";let n=Math.max(0,t-r),i=Math.floor(n/1e3);if(i<45)return"just now";let o=Math.floor(i/60);if(o<60)return`${o}m ago`;let s=Math.floor(o/60);if(s<24)return`${s}h ago`;let a=Math.floor(s/24);if(a<30)return`${a}d ago`;let c=Math.floor(a/30);return c<12?`${c}mo ago`:`${Math.floor(a/365)}y ago`}});var z8=g(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.formatAge=Qt.formatTime=Qt.formatRelativeTime=Qt.formatDate=Qt.formatTxAmount=Qt.formatMicrosWire=Qt.formatMicros=Qt.formatUsd=Qt.formatCents=void 0;Qt.micros=rSt;Qt.fromCents=nSt;Qt.fromUsdc=iSt;Qt.fromUsd=oSt;Qt.toCents=sSt;Qt.toCentsForAcquirer=aSt;Qt.toUsdc=cSt;Qt.toWire=uSt;Qt.fromWire=dSt;Qt.toDisplay=lSt;Qt.toUsdRounded2dp=pSt;Qt.add=fSt;Qt.sub=mSt;Qt.clampNonNegative=hSt;Qt.isNonNegative=ySt;Qt.max=gSt;Qt.min=bSt;var H0=10000n,Cke=1000000n;function rSt(e){return e}function nSt(e){if(!Number.isFinite(e)||!Number.isInteger(e)||!Number.isSafeInteger(e))throw new TypeError(`fromCents: expected safe integer, got ${e}`);return BigInt(e)*H0}function iSt(e){return e}function oSt(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function sSt(e){if(e>=0n)return Number(e/H0);let t=e/H0,r=e%H0;return Number(r===0n?t:t-1n)}function aSt(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/H0)}function cSt(e){return e}function uSt(e){return e.toString()}function dSt(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 lSt(e,t={}){let r=t.decimals??2,n=t.symbol??"$",i=e<0n,o=i?-e:e,s=o/Cke,a=o%Cke,c=i?"-":"";if(r===0)return`${c}${n}${s.toString()}`;let u=a.toString().padStart(6,"0").slice(0,r);return`${c}${n}${s.toString()}.${u}`}function pSt(e){let t=e<0n,r=t?-e:e,n=r/H0,o=r%H0*2n,s;o<H0?s=n:o>H0?s=n+1n:s=n%2n===0n?n:n+1n;let a=Number(s)/100;return t?-a:a}function fSt(e,t){return e+t}function mSt(e,t){return e-t}function hSt(e){return e<0n?0n:e}function ySt(e){return e>=0n}function gSt(e,t){return e>t?e:t}function bSt(e,t){return e<t?e:t}var $0=Pke();Object.defineProperty(Qt,"formatCents",{enumerable:!0,get:function(){return $0.formatCents}});Object.defineProperty(Qt,"formatUsd",{enumerable:!0,get:function(){return $0.formatUsd}});Object.defineProperty(Qt,"formatMicros",{enumerable:!0,get:function(){return $0.formatMicros}});Object.defineProperty(Qt,"formatMicrosWire",{enumerable:!0,get:function(){return $0.formatMicrosWire}});Object.defineProperty(Qt,"formatTxAmount",{enumerable:!0,get:function(){return $0.formatTxAmount}});Object.defineProperty(Qt,"formatDate",{enumerable:!0,get:function(){return $0.formatDate}});Object.defineProperty(Qt,"formatRelativeTime",{enumerable:!0,get:function(){return $0.formatRelativeTime}});Object.defineProperty(Qt,"formatTime",{enumerable:!0,get:function(){return $0.formatTime}});Object.defineProperty(Qt,"formatAge",{enumerable:!0,get:function(){return $0.formatAge}})});var qne=g(lc=>{"use strict";var _St=lc&&lc.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),vSt=lc&&lc.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),kke=lc&&lc.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(r){var n=[];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(n[n.length]=i);return n},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(t!=null)for(var n=e(t),i=0;i<n.length;i++)n[i]!=="default"&&_St(r,t,n[i]);return vSt(r,t),r}})();Object.defineProperty(lc,"__esModule",{value:!0});lc.pruneResponsesDir=Mne;lc.isTextualContentType=kM;lc.isValidUtf8=Nke;lc.spillFilename=Bke;lc.describePaidBody=jne;lc.capturePaidResponse=TSt;var xf=kke(require("fs")),D7=kke(require("path")),wSt=require("node:crypto"),Rke=16*1024,Bne=2*1024,ESt=64*1024*1024,ASt=3e4,Une=256*1024*1024;function Mne(e,t=Une,r){try{let n=r?D7.basename(r):null,i=xf.readdirSync(e).map(s=>{if(s.includes(".part-"))return null;try{let a=xf.statSync(D7.join(e,s));return a.isFile()?{name:s,size:a.size,mtime:a.mtimeMs}:null}catch{return null}}).filter(s=>s!==null).sort((s,a)=>s.name===n?-1:a.name===n?1:a.mtime-s.mtime),o=0;for(let s of i)if(o+=s.size,o>t&&s.name!==n)try{xf.rmSync(D7.join(e,s.name),{force:!0})}catch{}}catch{}}var xSt=new Set(["application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/csv"]);function kM(e){if(!e)return!1;let t=e.split(";",1)[0].trim().toLowerCase();return t.startsWith("text/")||t.endsWith("+json")||t.endsWith("+xml")||xSt.has(t)}function Nke(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(e),!0}catch{return!1}}var SSt={"application/json":".json","application/pdf":".pdf","audio/mpeg":".mp3","image/gif":".gif","image/jpeg":".jpg","image/png":".png","image/svg+xml":".svg","image/webp":".webp","text/csv":".csv","text/html":".html","text/plain":".txt","video/mp4":".mp4"};function Bke(e,t,r){let n="unknown-host";try{n=new URL(e).hostname.toLowerCase()}catch{}let i=n.replace(/[^a-z0-9.-]/g,"_").slice(0,80),o=(t??"").split(";",1)[0].trim().toLowerCase(),s=SSt[o]??(kM(t)?".txt":".bin");return`${r.toISOString().replace(/[:.]/g,"-")}-${i}${s}`}function jke(e,t,r){let n=Bke(t,r,new Date),i=D7.extname(n),o=n.slice(0,n.length-i.length);return D7.join(e,`${o}-${(0,wSt.randomBytes)(8).toString("hex")}${i}`)}function Uke(e){xf.mkdirSync(e,{recursive:!0,mode:448})}function Oke(e,t){let r=0;for(;r<t.length;){let n=xf.writeSync(e,t,r,t.length-r,null);if(n<=0)throw new Error("Paid response file write made no progress.");r+=n}}function jne(e,t,r,n,i){let o=r?kM(r):Nke(n),s={status:t,contentType:r??"unknown",bodyBytes:n.length};if(n.length===0)return{...s,body:""};if(o&&n.length<=Rke)return{...s,body:n.toString("utf-8")};Uke(i);let a=jke(i,e,r);return xf.writeFileSync(a,n,{flag:"wx",mode:384}),Mne(i,Une,a),{...s,bodyFile:a,...o?{bodyPreview:n.subarray(0,Bne).toString("utf-8")}:{},note:"Body too large or binary to inline \u2014 full paid response written to bodyFile."}}async function TSt(e,t,r,n={}){let i=n.maxBytes??ESt,o=n.timeoutMs??ASt;if(!Number.isSafeInteger(i)||i<=0)throw new Error("Paid response capture maxBytes must be a positive safe integer.");if(!Number.isFinite(o)||o<=0)throw new Error("Paid response capture timeoutMs must be positive.");let s=t.headers.get("content-length");if(s&&/^\d+$/.test(s.trim())){let _=Number(s);if(Number.isSafeInteger(_)&&_>i)throw t.body?.cancel("paid response exceeds capture limit").catch(()=>{}),new Error(`Merchant response body exceeds the ${i}-byte capture limit (declared ${_} bytes).`)}if(!t.body)return jne(e,t.status,t.headers.get("content-type"),Buffer.alloc(0),r);let a=t.body.getReader(),c=Date.now(),u=[],d=0,l=0,p=null,f=null,m=null,h=[],y=0,v=()=>{p!==null&&(xf.closeSync(p),p=null)},E=()=>{if(v(),m)try{xf.rmSync(m,{force:!0})}catch{}};try{for(;;){let A=o-(Date.now()-c);if(A<=0)throw new Error(`Merchant response body timed out after ${o}ms.`);let x,S=new Promise((C,j)=>{x=setTimeout(()=>j(new Error(`Merchant response body timed out after ${o}ms.`)),A)}),I;try{I=await Promise.race([a.read(),S])}finally{x&&clearTimeout(x)}if(I.done)break;let T=Buffer.from(I.value);if(l+=T.length,l>i)throw new Error(`Merchant response body exceeded the ${i}-byte capture limit.`);if(y<Bne){let C=T.subarray(0,Math.min(T.length,Bne-y));h.push(Buffer.from(C)),y+=C.length}if(p===null){if(u.push(T),d+=T.length,d<=Rke)continue;Uke(r),f=jke(r,e,t.headers.get("content-type")),m=`${f}.part-${process.pid}-${Math.random().toString(16).slice(2)}`,p=xf.openSync(m,"wx",384);for(let C of u)Oke(p,C);u.length=0,d=0}else Oke(p,T)}if(p===null){let A=Buffer.concat(u,d);return jne(e,t.status,t.headers.get("content-type"),A,r)}v(),xf.renameSync(m,f),m=null,Mne(r,Une,f);let _=t.headers.get("content-type"),w=_?kM(_):!1;return{status:t.status,contentType:_??"unknown",bodyBytes:l,bodyFile:f,...w?{bodyPreview:Buffer.concat(h).toString("utf-8")}:{},note:"Body too large or binary to inline \u2014 full paid response written to bodyFile."}}catch(_){throw a.cancel("paid response capture failed").catch(()=>{}),E(),_}finally{try{a.releaseLock()}catch{}}}});var jy=g(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.TURNKEY_API_BASE_URL_ENV=mo.CIRCLE_TESTNET_FAUCET_URL=mo.NETWORK_ENV=mo.NETWORKS=void 0;mo.resolveNetwork=ISt;mo.turnkeyApiBaseUrl=CSt;mo.explorerTxUrl=OSt;mo.explorerAddressUrl=kSt;mo.NETWORKS={"base-mainnet":{id:"base-mainnet",caip2:"eip155:8453",chainId:8453,usdc:{address:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",eip712Domain:{name:"USD Coin",version:"2"}},rpcUrl:"https://mainnet.base.org",explorerBaseUrl:"https://basescan.org",isTestnet:!1},"base-sepolia":{id:"base-sepolia",caip2:"eip155:84532",chainId:84532,usdc:{address:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",eip712Domain:{name:"USDC",version:"2"}},rpcUrl:"https://sepolia.base.org",explorerBaseUrl:"https://sepolia.basescan.org",isTestnet:!0}};mo.NETWORK_ENV="VISA_V4_NETWORK";mo.CIRCLE_TESTNET_FAUCET_URL="https://faucet.circle.com";var Mke={"base-mainnet":"base-mainnet","base-sepolia":"base-sepolia","eip155:8453":"base-mainnet","eip155:84532":"base-sepolia"};function ISt(e=process.env){let t=(e[mo.NETWORK_ENV]??"").trim();if(t==="")return mo.NETWORKS["base-mainnet"];let r=Mke[t.toLowerCase()];if(!r)throw new Error(`unknown ${mo.NETWORK_ENV} value ${JSON.stringify(t)} \u2014 valid values: `+Object.keys(Mke).join(", "));return mo.NETWORKS[r]}mo.TURNKEY_API_BASE_URL_ENV="TURNKEY_API_BASE_URL";var PSt="https://api.turnkey.com";function CSt(e=process.env){let t=(e[mo.TURNKEY_API_BASE_URL_ENV]??"").trim();return t===""?PSt:t}function OSt(e,t){return`${e.explorerBaseUrl}/tx/${t}`}function kSt(e,t){return`${e.explorerBaseUrl}/address/${t}`}});var qke=g(RM=>{"use strict";Object.defineProperty(RM,"__esModule",{value:!0});RM.version=void 0;RM.version="1.2.3"});var T6=g(NM=>{"use strict";Object.defineProperty(NM,"__esModule",{value:!0});NM.BaseError=void 0;var RSt=qke(),Dne=class e extends Error{constructor(t,r={}){let n=r.cause instanceof e?r.cause.details:r.cause?.message?r.cause.message:r.details,i=r.cause instanceof e&&r.cause.docsPath||r.docsPath,o=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...i?[`Docs: https://abitype.dev${i}`]:[],...n?[`Details: ${n}`]:[],`Version: abitype@${RSt.version}`].join(`
|
|
191
|
+
`))})}var yf,YPe,Sy,_re,Iy,vre,wre,p3t,r6=k(()=>{"use strict";yf=_e(require("fs")),YPe=_e(require("os")),Sy=_e(require("path")),_re=require("node:readline/promises");$_();_j();zj();e7();RU();aPe();SPe();PPe();ZU();LPe();G4();w0();Iy=Sy.join(YPe.homedir(),".visa-cli","agents");vre=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,wre=32768,p3t=/[\p{Cc}\p{Cf}\u2028\u2029]/u});var Ure={};Pi(Ure,{SUBWAY_PROTOCOL:()=>fCe,registerDirect:()=>q3t,resolveDirect:()=>D3t});function Rre(e,t){let r=typeof t=="bigint"?t:BigInt(t);for(;r>0x7fn;)e.push(Number(r&0x7fn|0x80n)),r>>=7n;e.push(Number(r))}function yd(e,t){let r=0n,n=0n,i=t;for(;;){let o=e[i++];if(r|=BigInt(o&127)<<n,(o&128)===0)break;n+=7n}return[r,i]}function Nre(e,t){return e<<3|t}function p7(e,t,r){e.push(Nre(t,2)),Rre(e,r.length);for(let n of r)e.push(n)}function T3t(e,t){let r=[];return p7(r,1,kre.encode(e)),t&&t.length>0&&p7(r,2,kre.encode(t)),Uint8Array.from(r)}function I3t(e,t,r){let n=[];return r!==0n&&(n.push(Nre(1,0)),Rre(n,r)),p7(n,2,T3t(e,t)),Uint8Array.from(n)}function P3t(e){let t=[];return p7(t,1,kre.encode(e)),Uint8Array.from(t)}function C3t(e,t){let r=[];return t!==0n&&(r.push(Nre(1,0)),Rre(r,t)),p7(r,3,P3t(e)),Uint8Array.from(r)}function O3t(e){let t=0,r={success:!1,error:""};for(;t<e.length;){let[n,i]=yd(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===0){let[a,c]=yd(e,t);t=c,r.success=a!==0n}else if(o===2&&s===2){let[a,c]=yd(e,t),u=c,d=u+Number(a);r.error=lCe.decode(e.subarray(u,d)),t=d}else t=Bre(e,t,s)}return r}function k3t(e){let t=0,r={peerId:new Uint8Array(0),error:""};for(;t<e.length;){let[n,i]=yd(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===2){let[a,c]=yd(e,t),u=c,d=u+Number(a);r.peerId=e.subarray(u,d),t=d}else if(o===2&&s===2){let[a,c]=yd(e,t),u=c,d=u+Number(a);r.error=lCe.decode(e.subarray(u,d)),t=d}else t=Bre(e,t,s)}return r}function Bre(e,t,r){if(r===0)return yd(e,t)[1];if(r===2){let[n,i]=yd(e,t);return i+Number(n)}if(r===5)return t+4;if(r===1)return t+8;throw new Error(`unsupported wire type ${r}`)}function pCe(e){let t=0,r={requestId:0n};for(;t<e.length;){let[n,i]=yd(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===0){let[a,c]=yd(e,t);t=c,r.requestId=a}else if(o===13&&s===2){let[a,c]=yd(e,t),u=c,d=u+Number(a);r.registerNameResponse=O3t(e.subarray(u,d)),t=d}else if(o===14&&s===2){let[a,c]=yd(e,t),u=c,d=u+Number(a);r.resolveNameResponse=k3t(e.subarray(u,d)),t=d}else t=Bre(e,t,s)}return r}function R3t(e){let t=new Uint8Array(4+e.length);return new DataView(t.buffer).setUint32(0,e.length,!1),t.set(e,4),t}function jre(e){return new DataView(e.buffer,e.byteOffset,4).getUint32(0,!1)}function N3t(e){if(e.length<4)return{success:!1,error:"short reply (no length prefix)"};let t=jre(e.subarray(0,4));return e.length<4+t?{success:!1,error:`truncated frame (have ${e.length-4}, need ${t})`}:pCe(e.subarray(4,4+t)).registerNameResponse??{success:!1,error:"reply carried no register_name_response"}}function B3t(e){if(e.length<4)return{peerId:new Uint8Array(0),error:"short reply (no length prefix)"};let t=jre(e.subarray(0,4));return e.length<4+t?{peerId:new Uint8Array(0),error:`truncated frame (have ${e.length-4}, need ${t})`}:pCe(e.subarray(4,4+t)).resolveNameResponse??{peerId:new Uint8Array(0),error:"reply carried no resolve_name_response"}}function Ore(e){let t=e.reduce((i,o)=>i+o.length,0),r=new Uint8Array(t),n=0;for(let i of e)r.set(i,n),n+=i.length;return r}async function M3t(e){let t=[],r=0,n=-1;for await(let i of e){let o=i instanceof Uint8Array?i:i.subarray();if(t.push(o),r+=o.length,r>nCe)throw new Error("subway: reply exceeded max size");if(n<0&&r>=4&&(n=4+jre(Ore(t).subarray(0,4)),n>nCe))throw new Error("subway: declared frame exceeds max size");if(n>=0&&r>=n)return Ore(t).subarray(0,n)}return Ore(t)}async function mCe(e){return(0,iCe.createLibp2p)({...e?{privateKey:await(0,cCe.generateKeyPairFromSeed)("Ed25519",e)}:{},transports:[(0,oCe.tcp)()],connectionEncrypters:[(0,sCe.noise)()],streamMuxers:[(0,aCe.yamux)()],connectionGater:{denyDialMultiaddr:async()=>!1}})}async function hCe(e,t,r){let n=await e.dialProtocol((0,uCe.multiaddr)(t),fCe,{signal:AbortSignal.timeout(j3t)});n.send(R3t(r));let i;return Promise.race([M3t(n),new Promise((o,s)=>{i=setTimeout(()=>s(new Error("subway: request timed out")),U3t)})]).finally(()=>clearTimeout(i))}async function q3t(e){let t=await mCe(e.seed);try{let r=await hCe(t,e.relayMultiaddr,I3t(e.name,e.binding,e.requestId??1n)),n=N3t(r);return{success:n.success,error:n.error,peerId:t.peerId.toString()}}finally{await t.stop()}}async function D3t(e){let t=await mCe(e.seed);try{let r=await hCe(t,e.relayMultiaddr,C3t(e.name,e.requestId??1n)),n=B3t(r);return n.peerId.length===0?{found:!1,peerId:"",error:n.error||"name not found"}:{found:!0,peerId:(0,dCe.toString)(n.peerId,"base58btc"),error:""}}finally{await t.stop()}}var iCe,oCe,sCe,aCe,cCe,uCe,dCe,kre,lCe,fCe,j3t,U3t,nCe,Mre=k(()=>{"use strict";wte();iCe=require("libp2p"),oCe=require("@libp2p/tcp"),sCe=require("@chainsafe/libp2p-noise"),aCe=require("@chainsafe/libp2p-yamux"),cCe=require("@libp2p/crypto/keys"),uCe=require("@multiformats/multiaddr"),dCe=require("uint8arrays/to-string"),kre=new TextEncoder,lCe=new TextDecoder;fCe="/subway/p2p/1.0.0",j3t=15e3,U3t=15e3,nCe=1<<20});var y7={};Pi(y7,{DEFAULT_VISA_RELAY_MULTIADDR:()=>yCe,MESH:()=>Ci,RELAY_URL:()=>m7,connectOrThrow:()=>_8,ensureMailbox:()=>Zre,hydrateInbox:()=>ACe,isSubwayEnabled:()=>Hre,listRegistered:()=>Gre,loadBindingFor:()=>Vre,loadRegistry:()=>o6,makeClient:()=>b8,meshName:()=>gf,pairedVisaBinding:()=>vCe,pairedVisaBindingForIdentity:()=>wCe,persistInbox:()=>Yre,readInbox:()=>F3t,registerName:()=>h7,resolveActingName:()=>eM,resolveMeshName:()=>Kre,seedSubwayKeyFromExactIdentity:()=>_Ce,seedSubwayKeyFromTapAgent:()=>bCe,sendMessage:()=>Wre,sendVia:()=>V3t,subwayKeyPath:()=>Fre,visaRelayMultiaddr:()=>zre});function zre(e=process.env){return e.SUBWAY_RELAY_MULTIADDR??yCe}function gf(e){return e.includes(".")?e:`${e}.${Ci}`}function Hre(e){if(process.env.VISA_DEV==="1")return!0;let t=e??"0.0.0";return t==="0.0.0"||t.startsWith("0.0.")?!0:/-rc\.|-beta\./.test(t)}function $re(){Ws.mkdirSync(g8,{recursive:!0,mode:448})}function gCe(e){return e.replace(/[^a-zA-Z0-9_.-]/g,"_")}function Fre(e){return f7.join(g8,`${gCe(e)}.key`)}function o6(){if(!Ws.existsSync(Lre))return{};try{return JSON.parse(Ws.readFileSync(Lre,"utf8"))}catch{return{}}}function qre(e){$re(),Ws.writeFileSync(Lre,JSON.stringify(e,null,2),{mode:384})}function Dre(){try{return QU.userInfo().username}catch{return"local"}}function bCe(e){if(Ws.existsSync(e))return null;let t=WU();if(!t)return null;try{let r=r8(t.private_key_jwk);return $re(),Ws.writeFileSync(e,Buffer.from(r),{mode:384}),t.agent_jkt}catch{return null}}function _Ce(e,t){let r=r8(t.identityPrivateJwk);if(df(my(z_(r)))!==t.identityKeyJkt)throw new uf("The selected agent identity key does not match its stable record. Refusing .visa registration.");if(Ws.existsSync(e)){if(df(my(z_(KT(e))))!==t.identityKeyJkt)throw new uf("The existing Subway key belongs to a different agent. Refusing to replace it implicitly.");return t.stableAgentId}return $re(),Ws.writeFileSync(e,Buffer.from(r),{mode:384}),t.stableAgentId}function b8(e,t={}){return new YIe({name:gf(e),url:m7,keyPath:Fre(e),autoReconnect:t.autoReconnect??!1,binding:t.binding})}function Vre(e){if(Ci!=="visa")return;let t=o6()[e];if(t?.binding&&!(t.bindingExpiresAt&&Date.parse(t.bindingExpiresAt)<=Date.now()))return t.binding}async function _8(e,t=15e3){await Promise.race([e.connect(),new Promise((r,n)=>setTimeout(()=>n(new Error(`Subway relay connect timed out after ${t}ms (${m7})`)),t))])}function eM(e){if(e)return e;let t=Object.keys(o6());if(t.length===1)return t[0];throw t.length===0?new Error("No Subway names registered yet. Run `visa register <name>` first."):new Error(`Multiple names registered (${t.join(", ")}). Pass --as <name>.`)}function vCe(e,t=Date.now()){let r=WU();if(!r?.binding_jwt)return null;let n=y8(r.binding_jwt);if(!n||n.mesh!=="visa"||n.name!==e||n.jkt!==r.agent_jkt)return null;let i=typeof n.exp=="number"?n.exp:NaN;return!Number.isFinite(i)||i*1e3<=t?null:{binding:r.binding_jwt,bindingExpiresAt:new Date(i*1e3).toISOString(),identityKeyJkt:r.agent_jkt}}function wCe(e,t,r=Date.now()){for(let n of GU()){if(n.agent_jkt!==t)continue;let i=y8(n.binding_jwt);if(!i||i.mesh!=="visa"||i.name!==e||i.jkt!==t)continue;let o=typeof i.exp=="number"?i.exp:NaN;if(!(!Number.isFinite(o)||o*1e3<=r))return{binding:n.binding_jwt,bindingExpiresAt:new Date(o*1e3).toISOString(),identityKeyJkt:t}}return null}async function h7(e,t={}){let r=Fre(e),n=gf(e),i,o;if(t.exactIdentity){if(o=Ci==="visa"?wCe(n,t.exactIdentity.identityKeyJkt):null,Ci==="visa"&&!o)throw new uf;i=_Ce(r,t.exactIdentity)}else i=bCe(r),o=Ci==="visa"?vCe(n):null;let s,a={};if(o){if(!Ws.existsSync(r))throw new uf("A stored .visa binding exists, but its runtime-held identity key is unavailable. A new identity pairing cannot recreate this separate channel binding.");if(df(my(z_(KT(r))))!==o.identityKeyJkt)throw new uf("The stored .visa binding does not match this Subway identity key. Refusing to present a mismatched legacy admission artifact.");s=o.binding,a={binding:o.binding,bindingExpiresAt:o.bindingExpiresAt}}else if(Ci==="visa")throw new uf;let c=Ci==="visa"?zre():process.env.SUBWAY_RELAY_MULTIADDR;if(Ci==="visa"&&c){let{registerDirect:d}=await Promise.resolve().then(()=>(Mre(),Ure)),l=await d({relayMultiaddr:c,seed:KT(r),name:n,binding:s});if(!l.success)throw new Error(`.visa relay admission failed: ${l.error||"unknown"}`);let p=o6();return p[e]={relayName:n,mesh:Ci,peerId:l.peerId,owner:Dre(),tapAgentId:i,registeredAt:new Date().toISOString(),...a},qre(p),{relayName:n,mesh:Ci,peerId:l.peerId,tapAgentId:i,...s?{binding:s}:{}}}if(Ci==="visa"&&!process.env.SUBWAY_RELAY){let d=o6();return d[e]={relayName:n,mesh:Ci,peerId:null,owner:Dre(),tapAgentId:i,registeredAt:new Date().toISOString(),...a},qre(d),{relayName:n,mesh:Ci,peerId:null,tapAgentId:i,...s?{binding:s}:{},note:s?"Visa binding ready; relay admission pending a .visa relay (set SUBWAY_RELAY).":"No Visa directory/TAP admission binding is stored. Identity pairing does not issue one; use a separately approved directory capability when available."}}let u=b8(e,{autoReconnect:!1,binding:s});try{await _8(u);let d=o6();return d[e]={relayName:n,mesh:Ci,peerId:u.peerId,owner:Dre(),tapAgentId:i,registeredAt:new Date().toISOString(),...a},qre(d),{relayName:n,mesh:Ci,peerId:u.peerId,tapAgentId:i,...s?{binding:s}:{}}}finally{u.disconnect()}}async function Kre(e){let t=gf(e),r=Ci==="visa"?zre():process.env.SUBWAY_RELAY_MULTIADDR;if(Ci==="visa"&&r){let{resolveDirect:n}=await Promise.resolve().then(()=>(Mre(),Ure)),i=await n({relayMultiaddr:r,name:t});return{relayName:t,found:i.found,peerId:i.peerId,error:i.error}}throw new Error("subway find needs the .visa mesh with a dedicated relay \u2014 set SUBWAY_MESH=visa and SUBWAY_RELAY_MULTIADDR.")}async function Wre(e,t,r){let n=b8(e,{autoReconnect:!1,binding:Vre(e)});try{await _8(n);let i=gf(t);return await n.sendSigned(i,"chat",r),{to:i,as:gf(e)}}finally{n.disconnect()}}function Gre(){let e=o6();return Object.entries(e).map(([t,r])=>({name:t,...r}))}function ECe(e,t=g8){return f7.join(t,`${gCe(e)}.inbox.json`)}function z3t(e){if(!e||typeof e!="object")return!1;let t=e;return typeof t.from=="string"&&typeof t.text=="string"&&typeof t.ts=="number"&&typeof t.verified=="boolean"}function ACe(e,t=g8){try{let r=JSON.parse(Ws.readFileSync(ECe(e,t),"utf8"));return Array.isArray(r)?r.filter(z3t).slice(-Jre):[]}catch{return[]}}function Yre(e,t,r=g8){try{Ws.mkdirSync(r,{recursive:!0,mode:448}),Ws.writeFileSync(ECe(e,r),JSON.stringify(t.slice(-Jre),null,2),{mode:384})}catch{}}function H3t(e,t){if(t.dirty=!0,t.flushTimer)return;let r=setTimeout(()=>{t.flushTimer=null,t.dirty&&(t.dirty=!1,Yre(e,t.buffer))},L3t);typeof r.unref=="function"&&r.unref(),t.flushTimer=r}function $3t(e,t){t.flushTimer&&(clearTimeout(t.flushTimer),t.flushTimer=null),t.dirty=!1,Yre(e,t.buffer)}async function Zre(e){let t=XU.get(e);if(t)return{relayName:gf(e),peerId:t.client.peerId};let r=b8(e,{autoReconnect:!0,binding:Vre(e)}),n=ACe(e),i={client:r,buffer:n,flushTimer:null,dirty:!1};return r.onMessage(o=>{n.push({from:o.fromName,text:o.payload,ts:o.timestampMs,verified:!!o.verified}),n.length>Jre&&n.shift(),H3t(e,i)}),XU.set(e,i),await _8(r),{relayName:gf(e),peerId:r.peerId}}async function F3t(e,t=20,r=!1){await Zre(e);let n=XU.get(e);if(!n)return[];let i=n.buffer.slice(-t);return r&&(n.buffer.length=0,$3t(e,n)),i}async function V3t(e,t,r){await Zre(e);let n=XU.get(e);if(!n)throw new Error(`mailbox for ${e} unavailable`);let i=gf(t);return await n.client.sendSigned(i,"chat",r),{to:i,as:gf(e)}}var Ws,QU,f7,Ci,yCe,m7,g8,Lre,XU,Jre,L3t,s6=k(()=>{"use strict";Fte();$_();Ws=_e(require("fs")),QU=_e(require("os")),f7=_e(require("path"));WT();r6();Ci=process.env.SUBWAY_MESH??"relay",yCe="/dns4/subway-relay-visa.fly.dev/tcp/9100/p2p/12D3KooWM2q6SXgKFxj5wvnJ7gTD4XPjhvc5tHVVjDBrZRnJ3CKU";m7=process.env.SUBWAY_RELAY??"wss://relay.subway.dev/ws";g8=f7.join(QU.homedir(),".visa-cli","subway"),Lre=f7.join(g8,"registry.json");XU=new Map,Jre=200,L3t=100});var DCe={};Pi(DCe,{PAIRING_DIR:()=>_f,cancelPairing:()=>Cre,claimPairing:()=>i6,getPairingStatus:()=>YU,initiatePairing:()=>l7,latestPendingHumanPairing:()=>$U,latestPendingRuntimePairing:()=>aM,pairingFilePath:()=>sM,pollAndActivatePairing:()=>FU,readPendingPairing:()=>hd,registerOnVisaMeshIfEnabled:()=>JU,removePendingPairing:()=>d7,tryActivatePairing:()=>sne,verifyPairing:()=>Ty,writePendingPairing:()=>one});async function JU(e){if(process.env.SUBWAY_MESH!=="visa")return!1;try{return await h7(e),!0}catch(t){return Ce.warn("subway:pairing-auto-register-failed",{name:e,mesh:"visa",error:t instanceof Error?t.message:String(t)}),!1}}function cc(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function bf(e,t){let r=new Set(t);return Object.keys(e).every(n=>r.has(n))}function ene(e){return typeof e=="string"&&G3t.test(e)}function v8(e){return typeof e=="string"&&J3t.test(e)}function g7(e){if(typeof e!="string")return!1;let t=Date.parse(e);return Number.isFinite(t)&&new Date(t).toISOString()===e}function OCe(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost"||t==="::1")return!0;let r=t.split(".");return r.length===4&&r[0]==="127"&&r.every(n=>/^\d{1,3}$/.test(n)&&Number(n)<=255)}function rM(e){if(typeof e!="string"||e.length===0||e.length>CCe)return!1;try{let t=new URL(e);return(t.protocol==="https:"||t.protocol==="http:"&&OCe(t.hostname))&&t.username.length===0&&t.password.length===0}catch{return!1}}function oM(e){if(e.length===0||e.length>CCe)throw new Error("auth URL must be a bounded absolute URL");let t;try{t=new URL(e)}catch{throw new Error("auth URL must be a bounded absolute URL")}if(t.username.length>0||t.password.length>0||t.search.length>0||t.hash.length>0||t.protocol!=="https:"&&!(t.protocol==="http:"&&OCe(t.hostname)))throw new Error("auth URL must use HTTPS (or HTTP on a loopback host) without credentials");let r=t.pathname.replace(/\/+$/,"");return`${t.origin}${r===""||r==="/"?"":r}`}function tne(e){if(typeof e!="string")return!1;try{return oM(e)===e}catch{return!1}}function X3t(e){return cc(e)&&bf(e,["kty","crv","x"])&&e.kty==="OKP"&&e.crv==="Ed25519"&&Cr(e.x)}function Q3t(e){return cc(e)&&bf(e,["kty","crv","x","d"])&&e.kty==="OKP"&&e.crv==="Ed25519"&&Cr(e.x)&&Cr(e.d)}function eEt(e,t){try{let r=H_(Buffer.from(e.d,"base64url"));return r.x===t.x&&r.d===e.d}catch{return!1}}function tM(e,t){if(typeof e!="string"||Y3t.test(e))return null;let r=e.normalize("NFC").trim();return r.length>0&&r.length<=t?r:null}function kCe(e){if(!cc(e)||!bf(e,["runtime","contextLabel","cliVersion","platform"]))return null;let t=tM(e.runtime,100),r=tM(e.contextLabel,200),n=e.cliVersion===void 0?void 0:tM(e.cliVersion,64),i=e.platform===void 0?void 0:tM(e.platform,100);return!t||!r||e.cliVersion!==void 0&&!n||e.platform!==void 0&&!i?null:{runtime:t,contextLabel:r,...n?{cliVersion:n}:{},...i?{platform:i}:{}}}function tEt(e){if(!cc(e))return!1;let t=kCe(e);return t?t.runtime===e.runtime&&t.contextLabel===e.contextLabel&&t.cliVersion===e.cliVersion&&t.platform===e.platform:!1}function RCe(e){return cc(e)?bf(e,["role","protocolVersion","pairingId","agentId","verifier","authUrl","skillUrl","expiresAt","createdAt"])&&e.role==="human"&&e.protocolVersion===jt&&v8(e.pairingId)&&ene(e.agentId)&&Cr(e.verifier)&&tne(e.authUrl)&&rM(e.skillUrl)&&g7(e.expiresAt)&&g7(e.createdAt):!1}function NCe(e){return!cc(e)||!bf(e,["role","protocolVersion","pairingId","agentId","authUrl","claimToken","serverNonce","identityKeyJkt","identityPublicJwk","identityPrivateJwk","runtime","createdAt"])||e.role!=="runtime"||e.protocolVersion!==jt||!v8(e.pairingId)||!ene(e.agentId)||!tne(e.authUrl)||!Cr(e.claimToken)||!Cr(e.serverNonce)||!Cr(e.identityKeyJkt)||!X3t(e.identityPublicJwk)||!Q3t(e.identityPrivateJwk)||!tEt(e.runtime)||!g7(e.createdAt)?!1:e.identityPublicJwk.x===e.identityPrivateJwk.x&&df(e.identityPublicJwk)===e.identityKeyJkt&&eEt(e.identityPrivateJwk,e.identityPublicJwk)}function rEt(e){return cc(e)&&bf(e,["protocolVersion","verifier","authUrl","createdAt"])&&e.protocolVersion===jt&&Cr(e.verifier)&&tne(e.authUrl)&&g7(e.createdAt)}function b7(e,t,r){if(!cc(e)||e.protocolVersion!==jt||!v8(e.pairingId)||!ene(e.agentId)||typeof e.state!="string"||!Z3t.has(e.state)||!g7(e.expiresAt)||e.skillUrl!==void 0&&!rM(e.skillUrl)||e.authorizationUrl!==void 0&&!rM(e.authorizationUrl)||e.serverNonce!==void 0&&!Cr(e.serverNonce)||e.authApiUrl!==void 0&&!rM(e.authApiUrl)||e.failureCode!==void 0&&typeof e.failureCode!="string"||t!==void 0&&e.pairingId!==t||r!==void 0&&e.agentId!==r)throw new Error("pairing server returned an invalid v2 status response")}function sM(e,t,r=_f){if(!v8(e))throw new Error("pairing id must use the canonical ap_ + 24 base64url form");return iM.join(r,`${e}.${t}.json`)}function BCe(e){ql.mkdirSync(e,{recursive:!0,mode:448});let t=ql.lstatSync(e);if(t.isSymbolicLink()||!t.isDirectory())throw new Error("pairing directory must be a real directory, not a symlink");ql.chmodSync(e,448),ac(e)}function rne(e){return iM.join(e,K3t)}function nne(e){let t=e6(rne(e));if(t===null)return null;let r;try{r=JSON.parse(t)}catch{throw new Error("local pairing initiation state contains invalid JSON")}if(!rEt(r))throw new Error("local pairing initiation state is invalid");return r}function nEt(e,t){BCe(t),B0(rne(t),JSON.stringify(e,null,2))}function xCe(e,t){let r=nne(t);if(!r)return;let n=hd(e,"human",t);n&&n.verifier===r.verifier&&n.authUrl===r.authUrl&&ine(t)}function ine(e){nne(e)&&ac(e)&&ql.rmSync(rne(e),{force:!0})}function one(e,t=_f){if(!(e.role==="human"?RCe(e):NCe(e)))throw new Error("refusing to write invalid protocol-v2 pending pairing state");BCe(t);let n=sM(e.pairingId,e.role,t);B0(n,JSON.stringify(e,null,2))}function d7(e,t,r=_f){hd(e,t,r)&&ac(r)&&ql.rmSync(sM(e,t,r),{force:!0})}function Xre(e,t=_f){d7(e,"human",t),d7(e,"runtime",t),ine(t)}function hd(e,t,r=_f){if(!v8(e))return null;let n=e6(sM(e,t,r));if(n===null)return null;let i;try{i=JSON.parse(n)}catch{throw new Error(`local ${t} pairing state for ${e} contains invalid JSON`)}if(t==="human"){if(!RCe(i)||i.pairingId!==e)throw new Error(`local human pairing state for ${e} is invalid or misbound`);return i}if(!NCe(i)||i.pairingId!==e)throw new Error(`local runtime pairing state for ${e} is invalid or misbound`);return i}function jCe(e,t){return ac(t)?ql.readdirSync(t).filter(n=>n.endsWith(`.${e}.json`)).map(n=>{let i=n.slice(0,-`.${e}.json`.length);if(!v8(i))throw new Error(`local ${e} pairing filename ${n} is invalid`);return hd(i,e,t)}).filter(n=>n!==null).sort((n,i)=>i.createdAt.localeCompare(n.createdAt))[0]??null:null}function $U(e=_f){return jCe("human",e)}function aM(e=_f){return jCe("runtime",e)}function nM(e,t="pairing operation aborted"){return e.reason instanceof Error?e.reason:new Error(t)}function Qre(e,t){return t?t.aborted?Promise.reject(nM(t)):new Promise((r,n)=>{let i=()=>n(nM(t));t.addEventListener("abort",i,{once:!0}),e.then(o=>{t.removeEventListener("abort",i),r(o)},o=>{t.removeEventListener("abort",i),n(o)})}):e}async function a6(e,t,r,n={}){let i=new AbortController,o=()=>{let a=n.signal?.reason;i.abort(a instanceof Error?a:new Error("pairing operation aborted"))};n.signal?.aborted?o():n.signal?.addEventListener("abort",o,{once:!0});let s=setTimeout(()=>i.abort(new Error(`pairing request timed out after ${SCe}ms`)),SCe);s.unref?.();try{if(i.signal.aborted)throw nM(i.signal);let a=await Qre(r(e,{...t,headers:{"X-Source":"cli","X-Visa-CLI-Version":PCe,...t.headers??{}},redirect:"error",signal:i.signal}),i.signal),c;try{c=await Qre(a.json(),i.signal)}catch{if(i.signal.aborted)throw nM(i.signal);c={}}if(!a.ok&&a.status!==202){let u=cc(c)?c:{},d=typeof u.error=="string"?u.error:void 0,l=typeof u.detail=="string"?u.detail:void 0;throw new Error(d??l??`pairing server returned ${a.status}`)}return{status:a.status,body:c}}finally{clearTimeout(s),n.signal?.removeEventListener("abort",o)}}async function l7(e={}){let t=oM(e.authUrl??Sa()),r=e.pairingDir??_f,n=nne(r),i=n?Date.parse(n.createdAt):Number.NaN,o=n!==null&&Number.isFinite(i)&&Date.now()-i<W3t;if(o&&n.authUrl!==t)throw new Error("a pairing initiation is pending for a different auth origin; retry it first");let s=o?n:{protocolVersion:jt,verifier:C7e(),authUrl:t,createdAt:new Date().toISOString()};o||nEt(s,r);let a=s.verifier,{body:c}=await a6(`${t}/v4/agent-pairings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({protocolVersion:jt,cliChallenge:O7e(a)})},e.fetchImpl??fetch,{signal:e.signal});if(b7(c),c.state!=="awaiting_agent"||!c.skillUrl)throw new Error("pairing server returned an incomplete v2 initiation response");let u={role:"human",protocolVersion:jt,pairingId:c.pairingId,agentId:c.agentId,verifier:a,authUrl:t,skillUrl:Wee(c.skillUrl),expiresAt:c.expiresAt,createdAt:new Date().toISOString()};return one(u,r),e.retainInitiationDraft||ine(r),u}function UCe(e){return e.authorizationUrl?{...e,authorizationUrl:Wee(e.authorizationUrl)}:e}async function Ty(e){let{pairing:t}=e,{body:r}=await a6(`${t.authUrl}/v4/agent-pairings/${encodeURIComponent(t.pairingId)}/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({protocolVersion:jt,verifier:t.verifier,code:e.code})},e.fetchImpl??fetch,{signal:e.signal});return b7(r,t.pairingId,t.agentId),UCe(r)}async function YU(e){let t=oM(e.authUrl??Sa()),{body:r}=await a6(`${t}/v4/agent-pairings/${encodeURIComponent(e.pairingId)}`,{method:"GET",cache:"no-store"},e.fetchImpl??fetch,{signal:e.signal});return b7(r,e.pairingId,e.expectedAgentId),UCe(r)}function MCe(e,t){return Buffer.from(t8(e,Buffer.from(t,"utf8"))).toString("base64url")}function iEt(e){let t=MCe(Buffer.from(e.identityPrivateJwk.d,"base64url"),gte({protocolVersion:jt,pairingId:e.pairingId,agentId:e.agentId,serverNonce:e.serverNonce,claimTokenHash:P0(e.claimToken),identityKeyJkt:e.identityKeyJkt,runtime:e.runtime}));return{protocolVersion:jt,agentId:e.agentId,identityPublicJwk:e.identityPublicJwk,runtime:e.runtime,signature:t,claimToken:e.claimToken}}async function TCe(e,t,r){let{body:n}=await a6(`${e.authUrl}/v4/agent-pairings/${encodeURIComponent(e.pairingId)}/claim`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(iEt(e))},t,{signal:r}),i=n;if(!cc(i)||!bf(i,["protocolVersion","pairingId","agentId","state","verificationCode","claimToken"])||i.protocolVersion!==jt||i.pairingId!==e.pairingId||i.agentId!==e.agentId||typeof i.state!="string"||!["agent_claimed","code_verified","awaiting_human","authorized","delivered","activated"].includes(i.state)||i.claimToken!==e.claimToken||typeof i.verificationCode!="string"||i.verificationCode!==aU(e.pairingId,e.claimToken))throw new Error("pairing server returned an invalid v2 claim response");return{pending:e,verificationCode:i.verificationCode}}async function i6(e){let t=oM(e.authUrl??Sa()),r=e.fetchImpl??fetch,n=e.pairingDir??_f,i=kCe({runtime:e.runtime,contextLabel:e.contextLabel,platform:`${process.platform}/${process.arch}`,cliVersion:PCe});if(!i)throw new Error("runtime metadata must be canonical, bounded, non-empty text");let o=hd(e.pairingId,"runtime",n);if(o){if(o.authUrl!==t||o.runtime.runtime!==i.runtime||o.runtime.contextLabel!==i.contextLabel)throw new Error("this pairing already has a different pending runtime claim; resume it");return xCe(o.pairingId,n),TCe(o,r,e.signal)}let s=await YU({pairingId:e.pairingId,authUrl:t,fetchImpl:r,signal:e.signal});if(s.state!=="awaiting_agent"||!Cr(s.serverNonce))throw new Error(`pairing cannot be claimed from state ${s.state}`);let a=_7e(),c=H_(a.secretKey),u=my(a.publicKey),d=df(u),l=i,p=sU();gte({protocolVersion:jt,pairingId:e.pairingId,agentId:s.agentId,serverNonce:s.serverNonce,claimTokenHash:P0(p),identityKeyJkt:d,runtime:l});let f={role:"runtime",protocolVersion:jt,pairingId:e.pairingId,agentId:s.agentId,authUrl:t,claimToken:p,serverNonce:s.serverNonce,identityKeyJkt:d,identityPublicJwk:u,identityPrivateJwk:c,runtime:l,createdAt:new Date().toISOString()};return one(f,n),xCe(f.pairingId,n),TCe(f,r,e.signal)}async function qCe(e){let t=e.fetchImpl??fetch,{body:r,status:n}=await a6(`${e.pending.authUrl}/v4/agent-pairings/${encodeURIComponent(e.pending.pairingId)}/delivery`,{method:"GET",headers:{"X-Agent-Pairing-Token":e.pending.claimToken},cache:"no-store"},t,{signal:e.signal});if(n===202){if(b7(r,e.pending.pairingId,e.pending.agentId),e.onState?.(r.state),["expired","cancelled","failed","revoked"].includes(r.state))throw Xre(e.pending.pairingId,e.pairingDir),new Error(`pairing ended in state ${r.state}`);return null}if(!cc(r)||!bf(r,["protocolVersion","pairingId","agentId","state","artifact","deliveryArtifactHash"])||r.protocolVersion!==jt||r.pairingId!==e.pending.pairingId||r.agentId!==e.pending.agentId||r.state!=="delivered"&&r.state!=="activated"||!cc(r.artifact)||!Cr(r.deliveryArtifactHash))throw new Error("pairing delivery omitted the canonical v2 identity artifact");e.onState?.(r.state);let i=FT(r.artifact),o=JSON.parse(i),s=B7e(o);if(s!==r.deliveryArtifactHash||o.pairingId!==e.pending.pairingId||o.agentId!==e.pending.agentId||o.identityKey.jkt!==e.pending.identityKeyJkt||o.identityKey.publicJwk.x!==e.pending.identityPublicJwk.x)throw new Error("pairing v2 delivery artifact did not match this pending identity claim");let a=MCe(Buffer.from(e.pending.identityPrivateJwk.d,"base64url"),R7e({protocolVersion:jt,pairingId:e.pending.pairingId,agentId:e.pending.agentId,ownerPublicId:o.ownerPublicId,claimTokenHash:P0(e.pending.claimToken),identityKeyJkt:e.pending.identityKeyJkt,ceremonyHash:o.ceremonyHash,deliveryArtifactHash:s})),c=await a6(`${e.pending.authUrl}/v4/agent-pairings/${encodeURIComponent(e.pending.pairingId)}/activate`,{method:"POST",headers:{"Content-Type":"application/json","X-Agent-Pairing-Token":e.pending.claimToken},body:JSON.stringify({protocolVersion:jt,agentId:e.pending.agentId,signature:a})},t,{signal:e.signal}),u=o.terms,d=c.body;if(!cc(d)||!bf(d,["protocolVersion","state","pairingId","agentId","ownerPublicId","identityKeyJkt","displayName","credentials"])||d.protocolVersion!==jt||d.state!=="activated"||d.pairingId!==e.pending.pairingId||d.agentId!==e.pending.agentId||d.ownerPublicId!==o.ownerPublicId||d.identityKeyJkt!==e.pending.identityKeyJkt||d.displayName!==u.displayName||!cc(d.credentials)||!bf(d.credentials,["bindingJwt","registrationJwt"])||typeof d.credentials.bindingJwt!="string"||d.credentials.bindingJwt.length===0||typeof d.credentials.registrationJwt!="string"||d.credentials.registrationJwt.length===0)throw new Error("pairing server returned an invalid v2 activation response");let l={v:jt,agent_id:e.pending.agentId,owner_public_id:o.ownerPublicId,display_name:c.body.displayName,identity_key:{jkt:e.pending.identityKeyJkt,public_jwk:e.pending.identityPublicJwk,private_jwk:e.pending.identityPrivateJwk,custody:"runtime"},pairing_id:e.pending.pairingId,pairing_status:"activated",activation_credentials:{binding_jwt:d.credentials.bindingJwt,registration_jwt:d.credentials.registrationJwt},delivery_artifact:o,auth_url:e.pending.authUrl,created_at:new Date().toISOString()};(e.writeAgentRecord??Ire)(l,e.agentDir),Xre(e.pending.pairingId,e.pairingDir);let p=await JU(l.display_name);return process.env.SUBWAY_MESH==="visa"&&Ce.info("agent:fresh_activate_mesh",{name:l.display_name,meshRegistered:p}),{record:l,name:l.display_name,agentId:l.agent_id,identityKeyJkt:l.identity_key.jkt}}async function sne(e){return qCe(e)}async function FU(e){let t=e.wait??(i=>new Promise(o=>setTimeout(o,i))),r=e.maxPolls??450,n="";for(let i=0;i<r;i+=1){let o=await qCe({...e,onState:s=>{s!==n&&(n=s,e.onState?.(s))}});if(o)return o;i+1<r&&await Qre(t(e.pollIntervalMs??2e3),e.signal)}throw new Error("timed out waiting for human authorization")}async function Cre(e){let{pairing:t}=e,{body:r}=await a6(`${t.authUrl}/v4/agent-pairings/${encodeURIComponent(t.pairingId)}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({protocolVersion:jt,verifier:t.verifier})},e.fetchImpl??fetch,{signal:e.signal});return b7(r,t.pairingId,t.agentId),r.state==="cancelled"&&Xre(t.pairingId,e.pairingDir),r}var ql,ICe,iM,PCe,_f,K3t,W3t,G3t,J3t,Y3t,Z3t,CCe,SCe,ZU=k(()=>{"use strict";ql=_e(require("node:fs")),ICe=_e(require("node:os")),iM=_e(require("node:path"));$_();ay();zj();pd();WT();s6();e7();r6();PCe="4.1.0-rc.51",_f=iM.join(ICe.homedir(),".visa-cli","pairings"),K3t=".initiation.v2.json",W3t=15*6e4,G3t=/^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/,J3t=/^ap_[A-Za-z0-9_-]{24}$/,Y3t=/[\p{Cc}\p{Cf}\u2028\u2029]/u,Z3t=new Set(["awaiting_agent","agent_claimed","code_verified","awaiting_human","authorized","delivered","activated","expired","cancelled","failed","revoked"]),CCe=2048;SCe=3e4});function LCe(e){return e.reason instanceof Error?e.reason:new Error("agent pairing timed out")}function oEt(e,t){return t?t.aborted?Promise.reject(LCe(t)):new Promise((r,n)=>{let i=()=>n(LCe(t));t.addEventListener("abort",i,{once:!0}),e.then(o=>{t.removeEventListener("abort",i),r(o)},o=>{t.removeEventListener("abort",i),n(o)})}):e}function sEt(e){let t=e.length;for(;t>0&&e[t-1]==="/";)t-=1;return t===e.length?e:e.slice(0,t)}function zCe(e,t){if(t!==void 0&&sEt(t)!==e)throw new Error("auth URL does not match the pending pairing; resume with the original origin")}function aEt(e){return{status:"activated",protocolVersion:jt,pairingId:e.record.pairing_id,agentId:e.agentId,displayName:e.name,identityKeyJkt:e.identityKeyJkt}}async function c7(e={}){let t=aM(e.pairingDir);if(t){zCe(t.authUrl,e.authUrl);let s=hd(t.pairingId,"human",e.pairingDir);if(!s||s.agentId!==t.agentId)throw new Error("a runtime pairing is already pending without its local human proof; resume or cancel it before starting another");let a=await i6({pairingId:t.pairingId,runtime:t.runtime.runtime,contextLabel:t.runtime.contextLabel,authUrl:t.authUrl,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,...e.signal?{signal:e.signal}:{}}),c=await Ty({pairing:s,code:a.verificationCode,fetchImpl:e.fetchImpl,...e.signal?{signal:e.signal}:{}});if(!c.authorizationUrl)throw new Error("authorization URL missing after v2 pairing verification");return{protocolVersion:jt,pairingId:t.pairingId,agentId:t.agentId,requestKeyFingerprint:t.identityKeyJkt,authorizationUrl:c.authorizationUrl,expiresAt:s.expiresAt}}let r=await l7({authUrl:e.authUrl,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,...e.signal?{signal:e.signal}:{},retainInitiationDraft:!0}),{pending:n,verificationCode:i}=await i6({pairingId:r.pairingId,runtime:e.runtime??"visa-cli",contextLabel:e.contextLabel??"Pair this runtime",authUrl:r.authUrl,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,...e.signal?{signal:e.signal}:{}});if(n.agentId!==r.agentId)throw new Error("pairing claim returned a different stable agent id");let o=await Ty({pairing:r,code:i,fetchImpl:e.fetchImpl,...e.signal?{signal:e.signal}:{}});if(!o.authorizationUrl)throw new Error("authorization URL missing after v2 pairing verification");return{protocolVersion:jt,pairingId:r.pairingId,agentId:r.agentId,requestKeyFingerprint:n.identityKeyJkt,authorizationUrl:o.authorizationUrl,expiresAt:r.expiresAt}}function cEt(e,t){if(!e)return!1;let r=Date.parse(e.expiresAt);return Number.isFinite(r)&&t>=r}async function u7(e={}){let t=aM(e.pairingDir);if(!t)return{status:"no_pending"};let r=hd(t.pairingId,"human",e.pairingDir);try{zCe(t.authUrl,e.authUrl);let n=Math.max(1,e.attempts??1),i=e.sleep??(o=>new Promise(s=>setTimeout(s,o)));for(let o=0;o<n;o+=1){let s="",a=await sne({pending:t,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,agentDir:e.agentDir,...e.signal?{signal:e.signal}:{},onState:c=>{s=c}});if(a)return aEt(a);if(o===0&&["awaiting_agent","agent_claimed","code_verified"].includes(s)){if(!r)throw new Error("pending pairing is missing its local human verification proof");let c=await i6({pairingId:t.pairingId,runtime:t.runtime.runtime,contextLabel:t.runtime.contextLabel,authUrl:t.authUrl,fetchImpl:e.fetchImpl,pairingDir:e.pairingDir,...e.signal?{signal:e.signal}:{}});await Ty({pairing:r,code:c.verificationCode,fetchImpl:e.fetchImpl,...e.signal?{signal:e.signal}:{}})}o+1<n&&await oEt(i(e.delayMs??3e3),e.signal)}return{status:"not_ready",protocolVersion:jt,pairingId:t.pairingId,agentId:t.agentId,likelyExpired:cEt(r,(e.now??Date.now)())}}catch(n){return{status:"error",message:n instanceof Error?n.message:String(n)}}}async function cPe(e){if(typeof e!="string"||e.trim().length===0)return!1;try{return await An.saveSessionToken(e),!0}catch{return!1}}var RU=k(()=>{"use strict";$_();w0();ZU()});var lne={};Pi(lne,{CardDrawRefusedError:()=>c6,cardDrawIntentHash:()=>XCe,decimalUsdToCents:()=>dne,fetchCardDrawVerdict:()=>EEt,loadCardMandateCapability:()=>wEt,registerCardMandate:()=>AEt});function yEt(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(0,une.createHash)("sha256").update(t,"utf8").digest().toString("base64url")}function gEt(e){let{secretKey:t,publicKey:r}=v7e(e),n=H_(t),i=my(r);return{privateJwk:n,publicJwk:i,jkt:yEt(i)}}async function YCe(e,t){let n={cnf:{jwk:{kty:e.publicJwk.kty,crv:e.publicJwk.crv,x:e.publicJwk.x}},nonce:t.nonce,aud:t.audience,iat:t.nowSec};t.intentHash!==void 0&&(n.int=t.intentHash);let i={alg:"EdDSA",kid:e.jkt,typ:hEt},o=`${GCe(i)}.${GCe(n)}`,s=r8(e.privateJwk),a=t8(s,Buffer.from(o,"utf8"));return`${o}.${Buffer.from(a).toString("base64url")}`}function ZCe(e){let{amount:t,currency:r,payee:n,intentId:i}=e;if(!Number.isSafeInteger(t)||t<=0)throw new Error(`intent.amount must be a positive safe integer in minor units (cents); got ${String(t)}`);let o=typeof r=="string"?r.toUpperCase():"";if(!bEt.has(o))throw new Error(`intent.currency must be a supported ISO 4217 code; got ${JSON.stringify(r)}`);if(typeof n!="string"||n.length===0)throw new Error("intent.payee must be a non-empty string");if(i!==void 0&&(typeof i!="string"||i.length===0))throw new Error("intent.intentId, when present, must be a non-empty string");let s=JSON.stringify({v:_Et,amount:t,currency:o,payee:n,intentId:i??null,settlementHash:null});return(0,une.createHash)("sha256").update(s,"utf8").digest().toString("base64url")}function vEt(e){let t=e.split(".");if(t.length!==3)return null;try{let r=JSON.parse(Buffer.from(t[1],"base64url").toString("utf8"));return typeof r.mode=="string"?r.mode:null}catch{return null}}function dne(e){let t=/^([0-9]+)(?:\.([0-9]{1,2}))?$/.exec(e);if(!t)return null;let r=Number(t[1]),n=Number(((t[2]??"")+"00").slice(0,2)),i=r*100+n;return Number.isSafeInteger(i)?i:null}function XCe(e,t){let r=dne(e.amount);return r===null?null:ZCe({amount:r,currency:e.currency,payee:e.merchantUrl,intentId:t})}function wEt(e={}){let r=(e.record!==void 0?e.record?[e.record]:[]:e.records??(r6(),ie(rCe)).listLegacyAgentRecords()).flatMap(i=>{if(!i.binding_jwt||!i.auth_url)return[];let o=vEt(i.binding_jwt);if(o!=="card"&&o!=="both")return[];let s;try{s=gEt(r8(i.private_key_jwk))}catch{return[]}return s.jkt!==i.agent_jkt?[]:[{record:i,capability:{agentKey:s,agentJkt:i.agent_jkt,authBaseUrl:i.auth_url}}]}),n=e.agentRef?.trim();if(n){let i=n.replace(/\.visa$/i,"").toLowerCase(),o=r.filter(({record:s})=>s.agent_jkt===n||s.name.replace(/\.visa$/i,"").toLowerCase()===i);if(o.length>1)throw new Error(`more than one card capability is named "${n}"; select the exact request-key JKT`);return o[0]?.capability??null}if(r.length>1)throw new Error("more than one card-capable agent is available; select one explicitly with --agent (name or request-key JKT)");return r[0]?.capability??null}async function uM(e,t,r){let n=new AbortController,i=setTimeout(()=>n.abort(new Error(`card authority request timed out after ${JCe}ms`)),JCe);i.unref?.();try{return await e(t,{...r,redirect:"error",signal:n.signal})}finally{clearTimeout(i)}}function QCe(e){return e.replace(/\/+$/,"")}async function EEt(e){let t=e.fetchImpl??fetch,r=e.now??(()=>Math.floor(Date.now()/1e3)),n=QCe(e.authBaseUrl),i=XCe(e.draw,e.drawId);if(i===null)throw new c6(400,["invalid_amount"]);let o=await uM(t,`${n}/v4/card/draw/challenge`,{method:"POST",headers:{"content-type":"application/json","x-source":"cli"}});if(!o.ok)throw new c6(o.status,["challenge_failed"]);let s=await o.json();if(!s.nonce||!s.audience)throw new c6(502,["challenge_malformed"]);let a=await YCe(e.agentKey,{nonce:s.nonce,audience:s.audience,nowSec:r(),intentHash:i}),c=await uM(t,`${n}/v4/card/draw-verdict`,{method:"POST",headers:{"content-type":"application/json","x-source":"cli"},body:JSON.stringify({nonce:s.nonce,popJwt:a,mandateId:e.mandateId,drawId:e.drawId,draw:e.draw})}),u=await c.json().catch(()=>null);if(!c.ok||!u?.ok||typeof u.verdict!="string")throw new c6(c.status,u?.reasons??["verdict_refused"]);return{verdict:u.verdict,remainingCents:Number(u.remainingCents??0)}}async function AEt(e){try{let t=e.fetchImpl??fetch,r=e.now??(()=>Math.floor(Date.now()/1e3)),n=QCe(e.authBaseUrl),i=dne(e.ceiling);if(i===null)return{ok:!1,reason:"invalid_amount"};let o=ZCe({amount:i,currency:e.currency,payee:"card-mandate-register",intentId:e.mandateId}),s=await uM(t,`${n}/v4/card/draw/challenge`,{method:"POST",headers:{"content-type":"application/json","x-source":"cli"}});if(!s.ok)return{ok:!1,reason:"challenge_failed"};let a=await s.json();if(!a.nonce||!a.audience)return{ok:!1,reason:"challenge_malformed"};let c=await YCe(e.agentKey,{nonce:a.nonce,audience:a.audience,nowSec:r(),intentHash:o}),u=await uM(t,`${n}/v4/card/mandate/register`,{method:"POST",headers:{"content-type":"application/json","x-source":"cli"},body:JSON.stringify({nonce:a.nonce,popJwt:c,mandateId:e.mandateId,mintToken:e.mintToken})}),d=await u.json().catch(()=>null);return!u.ok||!d?.ok?{ok:!1,reason:d?.reasons?.[0]??"register_refused"}:{ok:!0}}catch(t){return{ok:!1,reason:t instanceof Error?t.message:String(t)}}}var une,hEt,GCe,bEt,_Et,c6,JCe,pne=k(()=>{"use strict";une=require("node:crypto");$_();hEt="visa-agent-pop+jwt",GCe=e=>Buffer.from(JSON.stringify(e),"utf8").toString("base64url");bEt=new Set(["USD","EUR","GBP","CAD","AUD","JPY","CHF","CNY","HKD","SGD","INR","MXN","BRL","NZD","SEK","NOK","DKK","ZAR","AED"]),_Et=1;c6=class extends Error{constructor(r,n){super(`card draw refused (${r}): ${n.join(", ")||"unknown"}`);this.status=r;this.reasons=n;this.name="CardDrawRefusedError"}status;reasons},JCe=3e4});var Pke=g(Hl=>{"use strict";Object.defineProperty(Hl,"__esModule",{value:!0});Hl.formatCents=Ike;Hl.formatUsd=J9t;Hl.formatMicros=OM;Hl.formatMicrosWire=Y9t;Hl.formatTxAmount=Z9t;Hl.formatDate=X9t;Hl.formatRelativeTime=Q9t;Hl.formatTime=eSt;Hl.formatAge=tSt;var Tke=1e6,G9t=100;function Ike(e,t={}){let r=t.fallback??"\u2014";if(e==null||!Number.isFinite(e))return r;let i=(e/G9t).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??2});return t.showPlusSign&&e>0?`+${i}`:i}function J9t(e,t={}){let r=t.fallback??"\u2014";if(e==null||!Number.isFinite(e))return r;let n=e.toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??2});return t.showPlusSign&&e>0?`+${n}`:n}function OM(e,t={}){let r=t.fallback??"\u2014",n=typeof e=="string"?e===""?null:Number(e):e;if(n==null||!Number.isFinite(n))return r;let o=(n/Tke).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??6});return t.showPlusSign&&n>0?`+${o}`:o}function Y9t(e,t,r={}){return e&&/^-?\d+$/.test(e)?OM(e,r):t!=null&&Number.isFinite(t)?Ike(t,r):r.fallback??"\u2014"}function Z9t(e,t={}){let r=Number(e.amount_micros);if(Number.isFinite(r)&&e.amount_micros!=null&&e.amount_micros!=="")return OM(r,t);let n=Number(String(e.amount).replace(/^\$/,""));return Number.isFinite(n)?OM(n*Tke,t):t.fallback??"\u2014"}function X9t(e,t={}){let r=t.fallback??"\u2014";if(!e)return r;let n=new Date(e);return Number.isNaN(n.getTime())?r:n.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:t.timeZone??"UTC"})}function Q9t(e,t=Date.now()){if(!e)return"\u2014";let r=Date.parse(e);if(Number.isNaN(r))return"\u2014";let n=t-r,i=n>=0,o=Math.abs(n),s=Math.floor(o/1e3),a=Math.floor(s/60),c=Math.floor(a/60),u=Math.floor(c/24),d=Math.floor(u/7),l=Math.floor(u/30),p=Math.floor(u/365);return s<45?"just now":a<1?i?"a minute ago":"in a minute":a<60?L8(n,i,a,"minute"):c<24?L8(n,i,c,"hour"):u===1?i?"yesterday":"tomorrow":u<7?L8(n,i,u,"day"):d<4?L8(n,i,d,"week"):l<12?L8(n,i,l,"month"):L8(n,i,p,"year")}function L8(e,t,r,n){let i=r!==1?"s":"";return t?`${r} ${n}${i} ago`:`in ${r} ${n}${i}`}function eSt(e,t={}){let r=t.fallback??"\u2014";if(!e)return r;let n=new Date(e);return Number.isNaN(n.getTime())?r:n.toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit",timeZone:t.timeZone??"UTC"})}function tSt(e,t){if(!e)return"";let r=Date.parse(e);if(Number.isNaN(r))return"";let n=Math.max(0,t-r),i=Math.floor(n/1e3);if(i<45)return"just now";let o=Math.floor(i/60);if(o<60)return`${o}m ago`;let s=Math.floor(o/60);if(s<24)return`${s}h ago`;let a=Math.floor(s/24);if(a<30)return`${a}d ago`;let c=Math.floor(a/30);return c<12?`${c}mo ago`:`${Math.floor(a/365)}y ago`}});var z8=g(Qt=>{"use strict";Object.defineProperty(Qt,"__esModule",{value:!0});Qt.formatAge=Qt.formatTime=Qt.formatRelativeTime=Qt.formatDate=Qt.formatTxAmount=Qt.formatMicrosWire=Qt.formatMicros=Qt.formatUsd=Qt.formatCents=void 0;Qt.micros=rSt;Qt.fromCents=nSt;Qt.fromUsdc=iSt;Qt.fromUsd=oSt;Qt.toCents=sSt;Qt.toCentsForAcquirer=aSt;Qt.toUsdc=cSt;Qt.toWire=uSt;Qt.fromWire=dSt;Qt.toDisplay=lSt;Qt.toUsdRounded2dp=pSt;Qt.add=fSt;Qt.sub=mSt;Qt.clampNonNegative=hSt;Qt.isNonNegative=ySt;Qt.max=gSt;Qt.min=bSt;var H0=10000n,Cke=1000000n;function rSt(e){return e}function nSt(e){if(!Number.isFinite(e)||!Number.isInteger(e)||!Number.isSafeInteger(e))throw new TypeError(`fromCents: expected safe integer, got ${e}`);return BigInt(e)*H0}function iSt(e){return e}function oSt(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function sSt(e){if(e>=0n)return Number(e/H0);let t=e/H0,r=e%H0;return Number(r===0n?t:t-1n)}function aSt(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/H0)}function cSt(e){return e}function uSt(e){return e.toString()}function dSt(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 lSt(e,t={}){let r=t.decimals??2,n=t.symbol??"$",i=e<0n,o=i?-e:e,s=o/Cke,a=o%Cke,c=i?"-":"";if(r===0)return`${c}${n}${s.toString()}`;let u=a.toString().padStart(6,"0").slice(0,r);return`${c}${n}${s.toString()}.${u}`}function pSt(e){let t=e<0n,r=t?-e:e,n=r/H0,o=r%H0*2n,s;o<H0?s=n:o>H0?s=n+1n:s=n%2n===0n?n:n+1n;let a=Number(s)/100;return t?-a:a}function fSt(e,t){return e+t}function mSt(e,t){return e-t}function hSt(e){return e<0n?0n:e}function ySt(e){return e>=0n}function gSt(e,t){return e>t?e:t}function bSt(e,t){return e<t?e:t}var $0=Pke();Object.defineProperty(Qt,"formatCents",{enumerable:!0,get:function(){return $0.formatCents}});Object.defineProperty(Qt,"formatUsd",{enumerable:!0,get:function(){return $0.formatUsd}});Object.defineProperty(Qt,"formatMicros",{enumerable:!0,get:function(){return $0.formatMicros}});Object.defineProperty(Qt,"formatMicrosWire",{enumerable:!0,get:function(){return $0.formatMicrosWire}});Object.defineProperty(Qt,"formatTxAmount",{enumerable:!0,get:function(){return $0.formatTxAmount}});Object.defineProperty(Qt,"formatDate",{enumerable:!0,get:function(){return $0.formatDate}});Object.defineProperty(Qt,"formatRelativeTime",{enumerable:!0,get:function(){return $0.formatRelativeTime}});Object.defineProperty(Qt,"formatTime",{enumerable:!0,get:function(){return $0.formatTime}});Object.defineProperty(Qt,"formatAge",{enumerable:!0,get:function(){return $0.formatAge}})});var qne=g(lc=>{"use strict";var _St=lc&&lc.__createBinding||(Object.create?(function(e,t,r,n){n===void 0&&(n=r);var i=Object.getOwnPropertyDescriptor(t,r);(!i||("get"in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[r]}}),Object.defineProperty(e,n,i)}):(function(e,t,r,n){n===void 0&&(n=r),e[n]=t[r]})),vSt=lc&&lc.__setModuleDefault||(Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t}),kke=lc&&lc.__importStar||(function(){var e=function(t){return e=Object.getOwnPropertyNames||function(r){var n=[];for(var i in r)Object.prototype.hasOwnProperty.call(r,i)&&(n[n.length]=i);return n},e(t)};return function(t){if(t&&t.__esModule)return t;var r={};if(t!=null)for(var n=e(t),i=0;i<n.length;i++)n[i]!=="default"&&_St(r,t,n[i]);return vSt(r,t),r}})();Object.defineProperty(lc,"__esModule",{value:!0});lc.pruneResponsesDir=Mne;lc.isTextualContentType=kM;lc.isValidUtf8=Nke;lc.spillFilename=Bke;lc.describePaidBody=jne;lc.capturePaidResponse=TSt;var xf=kke(require("fs")),D7=kke(require("path")),wSt=require("node:crypto"),Rke=16*1024,Bne=2*1024,ESt=64*1024*1024,ASt=3e4,Une=256*1024*1024;function Mne(e,t=Une,r){try{let n=r?D7.basename(r):null,i=xf.readdirSync(e).map(s=>{if(s.includes(".part-"))return null;try{let a=xf.statSync(D7.join(e,s));return a.isFile()?{name:s,size:a.size,mtime:a.mtimeMs}:null}catch{return null}}).filter(s=>s!==null).sort((s,a)=>s.name===n?-1:a.name===n?1:a.mtime-s.mtime),o=0;for(let s of i)if(o+=s.size,o>t&&s.name!==n)try{xf.rmSync(D7.join(e,s.name),{force:!0})}catch{}}catch{}}var xSt=new Set(["application/json","application/xml","application/javascript","application/x-www-form-urlencoded","application/csv"]);function kM(e){if(!e)return!1;let t=e.split(";",1)[0].trim().toLowerCase();return t.startsWith("text/")||t.endsWith("+json")||t.endsWith("+xml")||xSt.has(t)}function Nke(e){try{return new TextDecoder("utf-8",{fatal:!0}).decode(e),!0}catch{return!1}}var SSt={"application/json":".json","application/pdf":".pdf","audio/mpeg":".mp3","image/gif":".gif","image/jpeg":".jpg","image/png":".png","image/svg+xml":".svg","image/webp":".webp","text/csv":".csv","text/html":".html","text/plain":".txt","video/mp4":".mp4"};function Bke(e,t,r){let n="unknown-host";try{n=new URL(e).hostname.toLowerCase()}catch{}let i=n.replace(/[^a-z0-9.-]/g,"_").slice(0,80),o=(t??"").split(";",1)[0].trim().toLowerCase(),s=SSt[o]??(kM(t)?".txt":".bin");return`${r.toISOString().replace(/[:.]/g,"-")}-${i}${s}`}function jke(e,t,r){let n=Bke(t,r,new Date),i=D7.extname(n),o=n.slice(0,n.length-i.length);return D7.join(e,`${o}-${(0,wSt.randomBytes)(8).toString("hex")}${i}`)}function Uke(e){xf.mkdirSync(e,{recursive:!0,mode:448})}function Oke(e,t){let r=0;for(;r<t.length;){let n=xf.writeSync(e,t,r,t.length-r,null);if(n<=0)throw new Error("Paid response file write made no progress.");r+=n}}function jne(e,t,r,n,i){let o=r?kM(r):Nke(n),s={status:t,contentType:r??"unknown",bodyBytes:n.length};if(n.length===0)return{...s,body:""};if(o&&n.length<=Rke)return{...s,body:n.toString("utf-8")};Uke(i);let a=jke(i,e,r);return xf.writeFileSync(a,n,{flag:"wx",mode:384}),Mne(i,Une,a),{...s,bodyFile:a,...o?{bodyPreview:n.subarray(0,Bne).toString("utf-8")}:{},note:"Body too large or binary to inline \u2014 full paid response written to bodyFile."}}async function TSt(e,t,r,n={}){let i=n.maxBytes??ESt,o=n.timeoutMs??ASt;if(!Number.isSafeInteger(i)||i<=0)throw new Error("Paid response capture maxBytes must be a positive safe integer.");if(!Number.isFinite(o)||o<=0)throw new Error("Paid response capture timeoutMs must be positive.");let s=t.headers.get("content-length");if(s&&/^\d+$/.test(s.trim())){let _=Number(s);if(Number.isSafeInteger(_)&&_>i)throw t.body?.cancel("paid response exceeds capture limit").catch(()=>{}),new Error(`Merchant response body exceeds the ${i}-byte capture limit (declared ${_} bytes).`)}if(!t.body)return jne(e,t.status,t.headers.get("content-type"),Buffer.alloc(0),r);let a=t.body.getReader(),c=Date.now(),u=[],d=0,l=0,p=null,f=null,m=null,h=[],y=0,v=()=>{p!==null&&(xf.closeSync(p),p=null)},E=()=>{if(v(),m)try{xf.rmSync(m,{force:!0})}catch{}};try{for(;;){let A=o-(Date.now()-c);if(A<=0)throw new Error(`Merchant response body timed out after ${o}ms.`);let x,S=new Promise((C,j)=>{x=setTimeout(()=>j(new Error(`Merchant response body timed out after ${o}ms.`)),A)}),I;try{I=await Promise.race([a.read(),S])}finally{x&&clearTimeout(x)}if(I.done)break;let T=Buffer.from(I.value);if(l+=T.length,l>i)throw new Error(`Merchant response body exceeded the ${i}-byte capture limit.`);if(y<Bne){let C=T.subarray(0,Math.min(T.length,Bne-y));h.push(Buffer.from(C)),y+=C.length}if(p===null){if(u.push(T),d+=T.length,d<=Rke)continue;Uke(r),f=jke(r,e,t.headers.get("content-type")),m=`${f}.part-${process.pid}-${Math.random().toString(16).slice(2)}`,p=xf.openSync(m,"wx",384);for(let C of u)Oke(p,C);u.length=0,d=0}else Oke(p,T)}if(p===null){let A=Buffer.concat(u,d);return jne(e,t.status,t.headers.get("content-type"),A,r)}v(),xf.renameSync(m,f),m=null,Mne(r,Une,f);let _=t.headers.get("content-type"),w=_?kM(_):!1;return{status:t.status,contentType:_??"unknown",bodyBytes:l,bodyFile:f,...w?{bodyPreview:Buffer.concat(h).toString("utf-8")}:{},note:"Body too large or binary to inline \u2014 full paid response written to bodyFile."}}catch(_){throw a.cancel("paid response capture failed").catch(()=>{}),E(),_}finally{try{a.releaseLock()}catch{}}}});var jy=g(mo=>{"use strict";Object.defineProperty(mo,"__esModule",{value:!0});mo.TURNKEY_API_BASE_URL_ENV=mo.CIRCLE_TESTNET_FAUCET_URL=mo.NETWORK_ENV=mo.NETWORKS=void 0;mo.resolveNetwork=ISt;mo.turnkeyApiBaseUrl=CSt;mo.explorerTxUrl=OSt;mo.explorerAddressUrl=kSt;mo.NETWORKS={"base-mainnet":{id:"base-mainnet",caip2:"eip155:8453",chainId:8453,usdc:{address:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",eip712Domain:{name:"USD Coin",version:"2"}},rpcUrl:"https://mainnet.base.org",explorerBaseUrl:"https://basescan.org",isTestnet:!1},"base-sepolia":{id:"base-sepolia",caip2:"eip155:84532",chainId:84532,usdc:{address:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",eip712Domain:{name:"USDC",version:"2"}},rpcUrl:"https://sepolia.base.org",explorerBaseUrl:"https://sepolia.basescan.org",isTestnet:!0}};mo.NETWORK_ENV="VISA_V4_NETWORK";mo.CIRCLE_TESTNET_FAUCET_URL="https://faucet.circle.com";var Mke={"base-mainnet":"base-mainnet","base-sepolia":"base-sepolia","eip155:8453":"base-mainnet","eip155:84532":"base-sepolia"};function ISt(e=process.env){let t=(e[mo.NETWORK_ENV]??"").trim();if(t==="")return mo.NETWORKS["base-mainnet"];let r=Mke[t.toLowerCase()];if(!r)throw new Error(`unknown ${mo.NETWORK_ENV} value ${JSON.stringify(t)} \u2014 valid values: `+Object.keys(Mke).join(", "));return mo.NETWORKS[r]}mo.TURNKEY_API_BASE_URL_ENV="TURNKEY_API_BASE_URL";var PSt="https://api.turnkey.com";function CSt(e=process.env){let t=(e[mo.TURNKEY_API_BASE_URL_ENV]??"").trim();return t===""?PSt:t}function OSt(e,t){return`${e.explorerBaseUrl}/tx/${t}`}function kSt(e,t){return`${e.explorerBaseUrl}/address/${t}`}});var qke=g(RM=>{"use strict";Object.defineProperty(RM,"__esModule",{value:!0});RM.version=void 0;RM.version="1.2.3"});var T6=g(NM=>{"use strict";Object.defineProperty(NM,"__esModule",{value:!0});NM.BaseError=void 0;var RSt=qke(),Dne=class e extends Error{constructor(t,r={}){let n=r.cause instanceof e?r.cause.details:r.cause?.message?r.cause.message:r.details,i=r.cause instanceof e&&r.cause.docsPath||r.docsPath,o=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...i?[`Docs: https://abitype.dev${i}`]:[],...n?[`Details: ${n}`]:[],`Version: abitype@${RSt.version}`].join(`
|
|
192
192
|
`);super(o),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiTypeError"}),r.cause&&(this.cause=r.cause),this.details=n,this.docsPath=i,this.metaMessages=r.metaMessages,this.shortMessage=t}};NM.BaseError=Dne});var Dke=g(Lne=>{"use strict";Object.defineProperty(Lne,"__esModule",{value:!0});Lne.narrow=NSt;function NSt(e){return e}});var L7=g(F0=>{"use strict";Object.defineProperty(F0,"__esModule",{value:!0});F0.isTupleRegex=F0.integerRegex=F0.bytesRegex=void 0;F0.execTyped=BSt;function BSt(e,t){return e.exec(t)?.groups}F0.bytesRegex=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/;F0.integerRegex=/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/;F0.isTupleRegex=/^\(.+?\).*?$/});var $ne=g(Hne=>{"use strict";Object.defineProperty(Hne,"__esModule",{value:!0});Hne.formatAbiParameter=zne;var jSt=L7(),Lke=/^tuple(?<array>(\[(\d*)\])*)$/;function zne(e){let t=e.type;if(Lke.test(e.type)&&"components"in e){t="(";let r=e.components.length;for(let i=0;i<r;i++){let o=e.components[i];t+=zne(o),i<r-1&&(t+=", ")}let n=(0,jSt.execTyped)(Lke,e.type);return t+=`)${n?.array||""}`,zne({...e,type:t})}return"indexed"in e&&e.indexed&&(t=`${t} indexed`),e.name?`${t} ${e.name}`:t}});var Vne=g(Fne=>{"use strict";Object.defineProperty(Fne,"__esModule",{value:!0});Fne.formatAbiParameters=MSt;var USt=$ne();function MSt(e){let t="",r=e.length;for(let n=0;n<r;n++){let i=e[n];t+=(0,USt.formatAbiParameter)(i),n!==r-1&&(t+=", ")}return t}});var Wne=g(Kne=>{"use strict";Object.defineProperty(Kne,"__esModule",{value:!0});Kne.formatAbiItem=qSt;var z7=Vne();function qSt(e){return e.type==="function"?`function ${e.name}(${(0,z7.formatAbiParameters)(e.inputs)})${e.stateMutability&&e.stateMutability!=="nonpayable"?` ${e.stateMutability}`:""}${e.outputs?.length?` returns (${(0,z7.formatAbiParameters)(e.outputs)})`:""}`:e.type==="event"?`event ${e.name}(${(0,z7.formatAbiParameters)(e.inputs)})`:e.type==="error"?`error ${e.name}(${(0,z7.formatAbiParameters)(e.inputs)})`:e.type==="constructor"?`constructor(${(0,z7.formatAbiParameters)(e.inputs)})${e.stateMutability==="payable"?" payable":""}`:e.type==="fallback"?`fallback() external${e.stateMutability==="payable"?" payable":""}`:"receive() external payable"}});var zke=g(Gne=>{"use strict";Object.defineProperty(Gne,"__esModule",{value:!0});Gne.formatAbi=LSt;var DSt=Wne();function LSt(e){let t=[],r=e.length;for(let n=0;n<r;n++){let i=e[n],o=(0,DSt.formatAbiItem)(i);t.push(o)}return t}});var I6=g(Oi=>{"use strict";Object.defineProperty(Oi,"__esModule",{value:!0});Oi.functionModifiers=Oi.eventModifiers=Oi.modifiers=void 0;Oi.isErrorSignature=zSt;Oi.execErrorSignature=HSt;Oi.isEventSignature=$St;Oi.execEventSignature=FSt;Oi.isFunctionSignature=VSt;Oi.execFunctionSignature=KSt;Oi.isStructSignature=WSt;Oi.execStructSignature=GSt;Oi.isConstructorSignature=JSt;Oi.execConstructorSignature=YSt;Oi.isFallbackSignature=ZSt;Oi.execFallbackSignature=XSt;Oi.isReceiveSignature=eTt;var H8=L7(),Hke=/^error (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function zSt(e){return Hke.test(e)}function HSt(e){return(0,H8.execTyped)(Hke,e)}var $ke=/^event (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function $St(e){return $ke.test(e)}function FSt(e){return(0,H8.execTyped)($ke,e)}var Fke=/^function (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\s?\((?<returns>.*?)\))?$/;function VSt(e){return Fke.test(e)}function KSt(e){return(0,H8.execTyped)(Fke,e)}var Vke=/^struct (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?<properties>.*?)\}$/;function WSt(e){return Vke.test(e)}function GSt(e){return(0,H8.execTyped)(Vke,e)}var Kke=/^constructor\((?<parameters>.*?)\)(?:\s(?<stateMutability>payable{1}))?$/;function JSt(e){return Kke.test(e)}function YSt(e){return(0,H8.execTyped)(Kke,e)}var Wke=/^fallback\(\) external(?:\s(?<stateMutability>payable{1}))?$/;function ZSt(e){return Wke.test(e)}function XSt(e){return(0,H8.execTyped)(Wke,e)}var QSt=/^receive\(\) external payable$/;function eTt(e){return QSt.test(e)}Oi.modifiers=new Set(["memory","indexed","storage","calldata"]);Oi.eventModifiers=new Set(["indexed"]);Oi.functionModifiers=new Set(["calldata","memory","storage"])});var H7=g(Uy=>{"use strict";Object.defineProperty(Uy,"__esModule",{value:!0});Uy.UnknownSolidityTypeError=Uy.UnknownTypeError=Uy.InvalidAbiItemError=void 0;var Xne=T6(),Jne=class extends Xne.BaseError{constructor({signature:t}){super("Failed to parse ABI item.",{details:`parseAbiItem(${JSON.stringify(t,null,2)})`,docsPath:"/api/human#parseabiitem-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiItemError"})}};Uy.InvalidAbiItemError=Jne;var Yne=class extends Xne.BaseError{constructor({type:t}){super("Unknown type.",{metaMessages:[`Type "${t}" is not a valid ABI type. Perhaps you forgot to include a struct signature?`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownTypeError"})}};Uy.UnknownTypeError=Yne;var Zne=class extends Xne.BaseError{constructor({type:t}){super("Unknown type.",{metaMessages:[`Type "${t}" is not a valid ABI type.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSolidityTypeError"})}};Uy.UnknownSolidityTypeError=Zne});var $8=g(Js=>{"use strict";Object.defineProperty(Js,"__esModule",{value:!0});Js.InvalidAbiTypeParameterError=Js.InvalidFunctionModifierError=Js.InvalidModifierError=Js.SolidityProtectedKeywordError=Js.InvalidParameterError=Js.InvalidAbiParametersError=Js.InvalidAbiParameterError=void 0;var P6=T6(),Qne=class extends P6.BaseError{constructor({param:t}){super("Failed to parse ABI parameter.",{details:`parseAbiParameter(${JSON.stringify(t,null,2)})`,docsPath:"/api/human#parseabiparameter-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiParameterError"})}};Js.InvalidAbiParameterError=Qne;var eie=class extends P6.BaseError{constructor({params:t}){super("Failed to parse ABI parameters.",{details:`parseAbiParameters(${JSON.stringify(t,null,2)})`,docsPath:"/api/human#parseabiparameters-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiParametersError"})}};Js.InvalidAbiParametersError=eie;var tie=class extends P6.BaseError{constructor({param:t}){super("Invalid ABI parameter.",{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParameterError"})}};Js.InvalidParameterError=tie;var rie=class extends P6.BaseError{constructor({param:t,name:r}){super("Invalid ABI parameter.",{details:t,metaMessages:[`"${r}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SolidityProtectedKeywordError"})}};Js.SolidityProtectedKeywordError=rie;var nie=class extends P6.BaseError{constructor({param:t,type:r,modifier:n}){super("Invalid ABI parameter.",{details:t,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidModifierError"})}};Js.InvalidModifierError=nie;var iie=class extends P6.BaseError{constructor({param:t,type:r,modifier:n}){super("Invalid ABI parameter.",{details:t,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`,`Data location can only be specified for array, struct, or mapping types, but "${n}" was given.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidFunctionModifierError"})}};Js.InvalidFunctionModifierError=iie;var oie=class extends P6.BaseError{constructor({abiParameter:t}){super("Invalid ABI parameter.",{details:JSON.stringify(t,null,2),metaMessages:["ABI parameter type is invalid."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiTypeParameterError"})}};Js.InvalidAbiTypeParameterError=oie});var BM=g(My=>{"use strict";Object.defineProperty(My,"__esModule",{value:!0});My.InvalidStructSignatureError=My.UnknownSignatureError=My.InvalidSignatureError=void 0;var uie=T6(),sie=class extends uie.BaseError{constructor({signature:t,type:r}){super(`Invalid ${r} signature.`,{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidSignatureError"})}};My.InvalidSignatureError=sie;var aie=class extends uie.BaseError{constructor({signature:t}){super("Unknown signature.",{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSignatureError"})}};My.UnknownSignatureError=aie;var cie=class extends uie.BaseError{constructor({signature:t}){super("Invalid struct signature.",{details:t,metaMessages:["No properties exist."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidStructSignatureError"})}};My.InvalidStructSignatureError=cie});var lie=g(jM=>{"use strict";Object.defineProperty(jM,"__esModule",{value:!0});jM.CircularReferenceError=void 0;var tTt=T6(),die=class extends tTt.BaseError{constructor({type:t}){super("Circular reference detected.",{metaMessages:[`Struct "${t}" is a circular reference.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"CircularReferenceError"})}};jM.CircularReferenceError=die});var fie=g(UM=>{"use strict";Object.defineProperty(UM,"__esModule",{value:!0});UM.InvalidParenthesisError=void 0;var rTt=T6(),pie=class extends rTt.BaseError{constructor({current:t,depth:r}){super("Unbalanced parentheses.",{metaMessages:[`"${t.trim()}" has too many ${r>0?"opening":"closing"} parentheses.`],details:`Depth "${r}"`}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParenthesisError"})}};UM.InvalidParenthesisError=pie});var Gke=g($7=>{"use strict";Object.defineProperty($7,"__esModule",{value:!0});$7.parameterCache=void 0;$7.getParameterCacheKey=nTt;function nTt(e,t,r){let n="";if(r)for(let i of Object.entries(r)){if(!i)continue;let o="";for(let s of i[1])o+=`[${s.type}${s.name?`:${s.name}`:""}]`;n+=`(${i[0]}{${o}})`}return t?`${t}:${e}${n}`:`${e}${n}`}$7.parameterCache=new Map([["address",{type:"address"}],["bool",{type:"bool"}],["bytes",{type:"bytes"}],["bytes32",{type:"bytes32"}],["int",{type:"int256"}],["int256",{type:"int256"}],["string",{type:"string"}],["uint",{type:"uint256"}],["uint8",{type:"uint8"}],["uint16",{type:"uint16"}],["uint24",{type:"uint24"}],["uint32",{type:"uint32"}],["uint64",{type:"uint64"}],["uint96",{type:"uint96"}],["uint112",{type:"uint112"}],["uint160",{type:"uint160"}],["uint192",{type:"uint192"}],["uint256",{type:"uint256"}],["address owner",{type:"address",name:"owner"}],["address to",{type:"address",name:"to"}],["bool approved",{type:"bool",name:"approved"}],["bytes _data",{type:"bytes",name:"_data"}],["bytes data",{type:"bytes",name:"data"}],["bytes signature",{type:"bytes",name:"signature"}],["bytes32 hash",{type:"bytes32",name:"hash"}],["bytes32 r",{type:"bytes32",name:"r"}],["bytes32 root",{type:"bytes32",name:"root"}],["bytes32 s",{type:"bytes32",name:"s"}],["string name",{type:"string",name:"name"}],["string symbol",{type:"string",name:"symbol"}],["string tokenURI",{type:"string",name:"tokenURI"}],["uint tokenId",{type:"uint256",name:"tokenId"}],["uint8 v",{type:"uint8",name:"v"}],["uint256 balance",{type:"uint256",name:"balance"}],["uint256 tokenId",{type:"uint256",name:"tokenId"}],["uint256 value",{type:"uint256",name:"value"}],["event:address indexed from",{type:"address",name:"from",indexed:!0}],["event:address indexed to",{type:"address",name:"to",indexed:!0}],["event:uint indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}],["event:uint256 indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}]])});var O6=g(yu=>{"use strict";Object.defineProperty(yu,"__esModule",{value:!0});yu.parseSignature=sTt;yu.parseFunctionSignature=Jke;yu.parseEventSignature=Yke;yu.parseErrorSignature=Zke;yu.parseConstructorSignature=Xke;yu.parseFallbackSignature=Qke;yu.parseAbiParameter=C6;yu.splitParameters=xd;yu.isSolidityType=eRe;yu.isSolidityKeyword=tRe;yu.isValidDataLocation=rRe;var F8=L7(),iTt=H7(),MM=$8(),V8=BM(),oTt=fie(),qM=Gke(),Ia=I6();function sTt(e,t={}){if((0,Ia.isFunctionSignature)(e))return Jke(e,t);if((0,Ia.isEventSignature)(e))return Yke(e,t);if((0,Ia.isErrorSignature)(e))return Zke(e,t);if((0,Ia.isConstructorSignature)(e))return Xke(e,t);if((0,Ia.isFallbackSignature)(e))return Qke(e);if((0,Ia.isReceiveSignature)(e))return{type:"receive",stateMutability:"payable"};throw new V8.UnknownSignatureError({signature:e})}function Jke(e,t={}){let r=(0,Ia.execFunctionSignature)(e);if(!r)throw new V8.InvalidSignatureError({signature:e,type:"function"});let n=xd(r.parameters),i=[],o=n.length;for(let a=0;a<o;a++)i.push(C6(n[a],{modifiers:Ia.functionModifiers,structs:t,type:"function"}));let s=[];if(r.returns){let a=xd(r.returns),c=a.length;for(let u=0;u<c;u++)s.push(C6(a[u],{modifiers:Ia.functionModifiers,structs:t,type:"function"}))}return{name:r.name,type:"function",stateMutability:r.stateMutability??"nonpayable",inputs:i,outputs:s}}function Yke(e,t={}){let r=(0,Ia.execEventSignature)(e);if(!r)throw new V8.InvalidSignatureError({signature:e,type:"event"});let n=xd(r.parameters),i=[],o=n.length;for(let s=0;s<o;s++)i.push(C6(n[s],{modifiers:Ia.eventModifiers,structs:t,type:"event"}));return{name:r.name,type:"event",inputs:i}}function Zke(e,t={}){let r=(0,Ia.execErrorSignature)(e);if(!r)throw new V8.InvalidSignatureError({signature:e,type:"error"});let n=xd(r.parameters),i=[],o=n.length;for(let s=0;s<o;s++)i.push(C6(n[s],{structs:t,type:"error"}));return{name:r.name,type:"error",inputs:i}}function Xke(e,t={}){let r=(0,Ia.execConstructorSignature)(e);if(!r)throw new V8.InvalidSignatureError({signature:e,type:"constructor"});let n=xd(r.parameters),i=[],o=n.length;for(let s=0;s<o;s++)i.push(C6(n[s],{structs:t,type:"constructor"}));return{type:"constructor",stateMutability:r.stateMutability??"nonpayable",inputs:i}}function Qke(e){let t=(0,Ia.execFallbackSignature)(e);if(!t)throw new V8.InvalidSignatureError({signature:e,type:"fallback"});return{type:"fallback",stateMutability:t.stateMutability??"nonpayable"}}var aTt=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*(?:\spayable)?)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,cTt=/^\((?<type>.+?)\)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,uTt=/^u?int$/;function C6(e,t){let r=(0,qM.getParameterCacheKey)(e,t?.type,t?.structs);if(qM.parameterCache.has(r))return qM.parameterCache.get(r);let n=F8.isTupleRegex.test(e),i=(0,F8.execTyped)(n?cTt:aTt,e);if(!i)throw new MM.InvalidParameterError({param:e});if(i.name&&tRe(i.name))throw new MM.SolidityProtectedKeywordError({param:e,name:i.name});let o=i.name?{name:i.name}:{},s=i.modifier==="indexed"?{indexed:!0}:{},a=t?.structs??{},c,u={};if(n){c="tuple";let l=xd(i.type),p=[],f=l.length;for(let m=0;m<f;m++)p.push(C6(l[m],{structs:a}));u={components:p}}else if(i.type in a)c="tuple",u={components:a[i.type]};else if(uTt.test(i.type))c=`${i.type}256`;else if(i.type==="address payable")c="address";else if(c=i.type,t?.type!=="struct"&&!eRe(c))throw new iTt.UnknownSolidityTypeError({type:c});if(i.modifier){if(!t?.modifiers?.has?.(i.modifier))throw new MM.InvalidModifierError({param:e,type:t?.type,modifier:i.modifier});if(Ia.functionModifiers.has(i.modifier)&&!rRe(c,!!i.array))throw new MM.InvalidFunctionModifierError({param:e,type:t?.type,modifier:i.modifier})}let d={type:`${c}${i.array??""}`,...o,...s,...u};return qM.parameterCache.set(r,d),d}function xd(e,t=[],r="",n=0){let i=e.trim().length;for(let o=0;o<i;o++){let s=e[o],a=e.slice(o+1);switch(s){case",":return n===0?xd(a,[...t,r.trim()]):xd(a,t,`${r}${s}`,n);case"(":return xd(a,t,`${r}${s}`,n+1);case")":return xd(a,t,`${r}${s}`,n-1);default:return xd(a,t,`${r}${s}`,n)}}if(r==="")return t;if(n!==0)throw new oTt.InvalidParenthesisError({current:r,depth:n});return t.push(r.trim()),t}function eRe(e){return e==="address"||e==="bool"||e==="function"||e==="string"||F8.bytesRegex.test(e)||F8.integerRegex.test(e)}var dTt=/^(?:after|alias|anonymous|apply|auto|byte|calldata|case|catch|constant|copyof|default|defined|error|event|external|false|final|function|immutable|implements|in|indexed|inline|internal|let|mapping|match|memory|mutable|null|of|override|partial|private|promise|public|pure|reference|relocatable|return|returns|sizeof|static|storage|struct|super|supports|switch|this|true|try|typedef|typeof|var|view|virtual)$/;function tRe(e){return e==="address"||e==="bool"||e==="function"||e==="string"||e==="tuple"||F8.bytesRegex.test(e)||F8.integerRegex.test(e)||dTt.test(e)}function rRe(e,t){return t||e==="bytes"||e==="string"||e==="tuple"}});var F7=g(mie=>{"use strict";Object.defineProperty(mie,"__esModule",{value:!0});mie.parseStructs=mTt;var nRe=L7(),lTt=H7(),pTt=$8(),iRe=BM(),fTt=lie(),oRe=I6(),sRe=O6();function mTt(e){let t={},r=e.length;for(let s=0;s<r;s++){let a=e[s];if(!(0,oRe.isStructSignature)(a))continue;let c=(0,oRe.execStructSignature)(a);if(!c)throw new iRe.InvalidSignatureError({signature:a,type:"struct"});let u=c.properties.split(";"),d=[],l=u.length;for(let p=0;p<l;p++){let m=u[p].trim();if(!m)continue;let h=(0,sRe.parseAbiParameter)(m,{type:"struct"});d.push(h)}if(!d.length)throw new iRe.InvalidStructSignatureError({signature:a});t[c.name]=d}let n={},i=Object.entries(t),o=i.length;for(let s=0;s<o;s++){let[a,c]=i[s];n[a]=aRe(c,t)}return n}var hTt=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\[\d*?\])+?)?$/;function aRe(e=[],t={},r=new Set){let n=[],i=e.length;for(let o=0;o<i;o++){let s=e[o];if(nRe.isTupleRegex.test(s.type))n.push(s);else{let c=(0,nRe.execTyped)(hTt,s.type);if(!c?.type)throw new pTt.InvalidAbiTypeParameterError({abiParameter:s});let{array:u,type:d}=c;if(d in t){if(r.has(d))throw new fTt.CircularReferenceError({type:d});n.push({...s,type:`tuple${u??""}`,components:aRe(t[d],t,new Set([...r,d]))})}else if((0,sRe.isSolidityType)(d))n.push(s);else throw new lTt.UnknownTypeError({type:d})}}return n}});var cRe=g(hie=>{"use strict";Object.defineProperty(hie,"__esModule",{value:!0});hie.parseAbi=_Tt;var yTt=I6(),gTt=F7(),bTt=O6();function _Tt(e){let t=(0,gTt.parseStructs)(e),r=[],n=e.length;for(let i=0;i<n;i++){let o=e[i];(0,yTt.isStructSignature)(o)||r.push((0,bTt.parseSignature)(o,t))}return r}});var dRe=g(yie=>{"use strict";Object.defineProperty(yie,"__esModule",{value:!0});yie.parseAbiItem=ATt;var vTt=H7(),wTt=I6(),ETt=F7(),uRe=O6();function ATt(e){let t;if(typeof e=="string")t=(0,uRe.parseSignature)(e);else{let r=(0,ETt.parseStructs)(e),n=e.length;for(let i=0;i<n;i++){let o=e[i];if(!(0,wTt.isStructSignature)(o)){t=(0,uRe.parseSignature)(o,r);break}}}if(!t)throw new vTt.InvalidAbiItemError({signature:e});return t}});var pRe=g(bie=>{"use strict";Object.defineProperty(bie,"__esModule",{value:!0});bie.parseAbiParameter=TTt;var xTt=$8(),gie=I6(),STt=F7(),lRe=O6();function TTt(e){let t;if(typeof e=="string")t=(0,lRe.parseAbiParameter)(e,{modifiers:gie.modifiers});else{let r=(0,STt.parseStructs)(e),n=e.length;for(let i=0;i<n;i++){let o=e[i];if(!(0,gie.isStructSignature)(o)){t=(0,lRe.parseAbiParameter)(o,{modifiers:gie.modifiers,structs:r});break}}}if(!t)throw new xTt.InvalidAbiParameterError({param:e});return t}});var hRe=g(vie=>{"use strict";Object.defineProperty(vie,"__esModule",{value:!0});vie.parseAbiParameters=CTt;var ITt=$8(),_ie=I6(),PTt=F7(),fRe=O6(),mRe=O6();function CTt(e){let t=[];if(typeof e=="string"){let r=(0,fRe.splitParameters)(e),n=r.length;for(let i=0;i<n;i++)t.push((0,mRe.parseAbiParameter)(r[i],{modifiers:_ie.modifiers}))}else{let r=(0,PTt.parseStructs)(e),n=e.length;for(let i=0;i<n;i++){let o=e[i];if((0,_ie.isStructSignature)(o))continue;let s=(0,fRe.splitParameters)(o),a=s.length;for(let c=0;c<a;c++)t.push((0,mRe.parseAbiParameter)(s[c],{modifiers:_ie.modifiers,structs:r}))}}if(t.length===0)throw new ITt.InvalidAbiParametersError({params:e});return t}});var V7=g(ft=>{"use strict";Object.defineProperty(ft,"__esModule",{value:!0});ft.CircularReferenceError=ft.InvalidParenthesisError=ft.UnknownSignatureError=ft.InvalidSignatureError=ft.InvalidStructSignatureError=ft.InvalidAbiParameterError=ft.InvalidAbiParametersError=ft.InvalidParameterError=ft.SolidityProtectedKeywordError=ft.InvalidModifierError=ft.InvalidFunctionModifierError=ft.InvalidAbiTypeParameterError=ft.UnknownSolidityTypeError=ft.InvalidAbiItemError=ft.UnknownTypeError=ft.parseAbiParameters=ft.parseAbiParameter=ft.parseAbiItem=ft.parseAbi=ft.formatAbiParameters=ft.formatAbiParameter=ft.formatAbiItem=ft.formatAbi=ft.narrow=ft.BaseError=void 0;var OTt=T6();Object.defineProperty(ft,"BaseError",{enumerable:!0,get:function(){return OTt.BaseError}});var kTt=Dke();Object.defineProperty(ft,"narrow",{enumerable:!0,get:function(){return kTt.narrow}});var RTt=zke();Object.defineProperty(ft,"formatAbi",{enumerable:!0,get:function(){return RTt.formatAbi}});var NTt=Wne();Object.defineProperty(ft,"formatAbiItem",{enumerable:!0,get:function(){return NTt.formatAbiItem}});var BTt=$ne();Object.defineProperty(ft,"formatAbiParameter",{enumerable:!0,get:function(){return BTt.formatAbiParameter}});var jTt=Vne();Object.defineProperty(ft,"formatAbiParameters",{enumerable:!0,get:function(){return jTt.formatAbiParameters}});var UTt=cRe();Object.defineProperty(ft,"parseAbi",{enumerable:!0,get:function(){return UTt.parseAbi}});var MTt=dRe();Object.defineProperty(ft,"parseAbiItem",{enumerable:!0,get:function(){return MTt.parseAbiItem}});var qTt=pRe();Object.defineProperty(ft,"parseAbiParameter",{enumerable:!0,get:function(){return qTt.parseAbiParameter}});var DTt=hRe();Object.defineProperty(ft,"parseAbiParameters",{enumerable:!0,get:function(){return DTt.parseAbiParameters}});var wie=H7();Object.defineProperty(ft,"UnknownTypeError",{enumerable:!0,get:function(){return wie.UnknownTypeError}});Object.defineProperty(ft,"InvalidAbiItemError",{enumerable:!0,get:function(){return wie.InvalidAbiItemError}});Object.defineProperty(ft,"UnknownSolidityTypeError",{enumerable:!0,get:function(){return wie.UnknownSolidityTypeError}});var k6=$8();Object.defineProperty(ft,"InvalidAbiTypeParameterError",{enumerable:!0,get:function(){return k6.InvalidAbiTypeParameterError}});Object.defineProperty(ft,"InvalidFunctionModifierError",{enumerable:!0,get:function(){return k6.InvalidFunctionModifierError}});Object.defineProperty(ft,"InvalidModifierError",{enumerable:!0,get:function(){return k6.InvalidModifierError}});Object.defineProperty(ft,"SolidityProtectedKeywordError",{enumerable:!0,get:function(){return k6.SolidityProtectedKeywordError}});Object.defineProperty(ft,"InvalidParameterError",{enumerable:!0,get:function(){return k6.InvalidParameterError}});Object.defineProperty(ft,"InvalidAbiParametersError",{enumerable:!0,get:function(){return k6.InvalidAbiParametersError}});Object.defineProperty(ft,"InvalidAbiParameterError",{enumerable:!0,get:function(){return k6.InvalidAbiParameterError}});var Eie=BM();Object.defineProperty(ft,"InvalidStructSignatureError",{enumerable:!0,get:function(){return Eie.InvalidStructSignatureError}});Object.defineProperty(ft,"InvalidSignatureError",{enumerable:!0,get:function(){return Eie.InvalidSignatureError}});Object.defineProperty(ft,"UnknownSignatureError",{enumerable:!0,get:function(){return Eie.UnknownSignatureError}});var LTt=fie();Object.defineProperty(ft,"InvalidParenthesisError",{enumerable:!0,get:function(){return LTt.InvalidParenthesisError}});var zTt=lie();Object.defineProperty(ft,"CircularReferenceError",{enumerable:!0,get:function(){return zTt.CircularReferenceError}})});var or=g(Aie=>{"use strict";Object.defineProperty(Aie,"__esModule",{value:!0});Aie.getAction=HTt;function HTt(e,t,r){let n=e[t.name];if(typeof n=="function")return n;let i=e[r];return typeof i=="function"?i:o=>t(e,o)}});var Sf=g(DM=>{"use strict";Object.defineProperty(DM,"__esModule",{value:!0});DM.formatAbiItem=FTt;DM.formatAbiParams=xie;var $Tt=zn();function FTt(e,{includeName:t=!1}={}){if(e.type!=="function"&&e.type!=="event"&&e.type!=="error")throw new $Tt.InvalidDefinitionTypeError(e.type);return`${e.name}(${xie(e.inputs,{includeName:t})})`}function xie(e,{includeName:t=!1}={}){return e?e.map(r=>VTt(r,{includeName:t})).join(t?", ":","):""}function VTt(e,{includeName:t}){return e.type.startsWith("tuple")?`(${xie(e.components,{includeName:t})})${e.type.slice(5)}`:e.type+(t&&e.name?` ${e.name}`:"")}});var ls=g(Sie=>{"use strict";Object.defineProperty(Sie,"__esModule",{value:!0});Sie.isHex=KTt;function KTt(e,{strict:t=!0}={}){return!e||typeof e!="string"?!1:t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x")}});var ps=g(Tie=>{"use strict";Object.defineProperty(Tie,"__esModule",{value:!0});Tie.size=GTt;var WTt=ls();function GTt(e){return(0,WTt.isHex)(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}});var yRe=g(LM=>{"use strict";Object.defineProperty(LM,"__esModule",{value:!0});LM.version=void 0;LM.version="2.54.6"});var Ct=g(K7=>{"use strict";Object.defineProperty(K7,"__esModule",{value:!0});K7.BaseError=void 0;K7.setErrorConfig=JTt;var gRe=yRe(),zM={getDocsUrl:({docsBaseUrl:e,docsPath:t="",docsSlug:r})=>t?`${e??"https://viem.sh"}${t}${r?`#${r}`:""}`:void 0,version:`viem@${gRe.version}`};function JTt(e){zM=e}var Iie=class e extends Error{constructor(t,r={}){let n=r.cause instanceof e?r.cause.details:r.cause?.message?r.cause.message:r.details,i=r.cause instanceof e&&r.cause.docsPath||r.docsPath,o=zM.getDocsUrl?.({...r,docsPath:i}),s=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...o?[`Docs: ${o}`]:[],...n?[`Details: ${n}`]:[],...zM.version?[`Version: ${zM.version}`]:[]].join(`
|
|
193
193
|
`);super(s,r.cause?{cause:r.cause}:void 0),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"version",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"BaseError"}),this.details=n,this.docsPath=i,this.metaMessages=r.metaMessages,this.name=r.name??this.name,this.shortMessage=t,this.version=gRe.version}walk(t){return bRe(this,t)}};K7.BaseError=Iie;function bRe(e,t){return t?.(e)?e:e&&typeof e=="object"&&"cause"in e&&e.cause!==void 0?bRe(e.cause,t):t?null:e}});var zn=g(lt=>{"use strict";Object.defineProperty(lt,"__esModule",{value:!0});lt.UnsupportedPackedAbiType=lt.InvalidDefinitionTypeError=lt.InvalidArrayError=lt.InvalidAbiDecodingTypeError=lt.InvalidAbiEncodingTypeError=lt.DecodeLogTopicsMismatch=lt.DecodeLogDataMismatch=lt.BytesSizeMismatchError=lt.AbiItemAmbiguityError=lt.AbiFunctionSignatureNotFoundError=lt.AbiFunctionOutputsNotFoundError=lt.AbiFunctionNotFoundError=lt.AbiEventNotFoundError=lt.AbiEventSignatureNotFoundError=lt.AbiEventSignatureEmptyTopicsError=lt.AbiErrorSignatureNotFoundError=lt.AbiErrorNotFoundError=lt.AbiErrorInputsNotFoundError=lt.AbiEncodingLengthMismatchError=lt.AbiEncodingBytesSizeMismatchError=lt.AbiEncodingArrayLengthMismatchError=lt.AbiDecodingZeroDataError=lt.AbiDecodingDataSizeTooSmallError=lt.AbiDecodingDataSizeInvalidError=lt.AbiConstructorParamsNotFoundError=lt.AbiConstructorNotFoundError=void 0;var W7=Sf(),YTt=ps(),pn=Ct(),Pie=class extends pn.BaseError{constructor({docsPath:t}){super(["A constructor was not found on the ABI.","Make sure you are using the correct ABI and that the constructor exists on it."].join(`
|
|
194
194
|
`),{docsPath:t,name:"AbiConstructorNotFoundError"})}};lt.AbiConstructorNotFoundError=Pie;var Cie=class extends pn.BaseError{constructor({docsPath:t}){super(["Constructor arguments were provided (`args`), but a constructor parameters (`inputs`) were not found on the ABI.","Make sure you are using the correct ABI, and that the `inputs` attribute on the constructor exists."].join(`
|
|
@@ -20920,7 +20920,7 @@ ${n}
|
|
|
20920
20920
|
`),NT(BT(),n+`
|
|
20921
20921
|
`)}catch{}}function PSe(e){try{let t=Tj();if(!t)return;let r=Math.max(Date.now(),t.renderedAt+1),n={...t,refreshFailedAt:r,refreshErrorReason:RT(e).slice(0,200)};NT(k_(),JSON.stringify(n)+`
|
|
20922
20922
|
`)}catch{}}function O_(){try{Er.unlinkSync(wSe())}catch{}}function Tj(){let e=k_();if(!Er.existsSync(e))return null;try{return JSON.parse(Er.readFileSync(e,"utf-8"))}catch{return null}}function CSe(){return Tj()?.status??null}function dvt(){if(process.env.JEST_WORKER_ID)return;let e=wSe();try{if(Er.mkdirSync(Kr.dirname(e),{recursive:!0}),!hvt(e))return;let t=process.argv[1]?Kr.resolve(process.argv[1]):"";if(!t){O_();return}let r=wj(),n=(process.env.VISA_CLI_HUD_THEME??"").toLowerCase().trim(),i=r==="no-color"||n==="light"||n==="dark"?{}:{VISA_CLI_HUD_THEME:r},o=(0,_Se.spawn)(process.execPath,[t,"shell-hud","refresh"],{detached:!0,stdio:"ignore",env:{...process.env,...i,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});o.once("error",O_),o.unref()}catch{O_()}}function RT(e){return e.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g,"").replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/\u001B[P_^][^\u001B]*(?:\u001B\\|\u0007)/g,"").replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g,"").replace(/\s+/g," ").trim()}var lvt=/^\u001B\[(?:0|38;2;\d{1,3};\d{1,3};\d{1,3}|38;5;\d{1,3})m$/;function pvt(e){let t=[],r=`__VISA_CLI_HUD_SGR_${(0,Iee.randomBytes)(8).toString("hex")}_`,n=e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,o=>{if(!lvt.test(o))return"";let s=`${r}${t.length}__`;return t.push(o),s}),i=new RegExp(`${r}(\\d+)__`,"g");return RT(n).replace(i,(o,s)=>t[Number(s)]??"")}var oc={get reset(){return Ls().reset},get visaBlue(){return Ls().visaBlue},get visaBlueSoft(){return Ls().visaBlueSoft},get visaGold(){return Ls().visaGold},get green(){return Ls().green},get muted(){return Ls().muted},get chrome(){return Ls().chrome}};function mu(e,t){return e.length===0||process.env.NO_COLOR||Ej()?e:`${t}${e}${oc.reset}`}function bSe(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function kee(){let e=R_.homedir();if(!e||!Kr.isAbsolute(e))throw new Error("unable to determine a valid home directory");return Kr.resolve(e)}function fvt(e){return e==="powershell"?"& visa-cli config shell-hud refresh":"visa-cli config shell-hud refresh"}function mvt(e){return e==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function hvt(e){for(let t=0;t<2;t+=1){let r;try{return r=Er.openSync(e,"wx"),Er.writeFileSync(r,String(Date.now())),!0}catch(n){if(n?.code!=="EEXIST")return!1;try{let i=Er.statSync(e);if(Date.now()-i.mtimeMs<=evt)return!1;Er.unlinkSync(e)}catch{}}finally{r!==void 0&&Er.closeSync(r)}}return!1}function Tee(e){return e instanceof Error?e.message:"unknown file system error"}function NT(e,t){Er.mkdirSync(Kr.dirname(e),{recursive:!0});let r=`${e}.${process.pid}.${(0,Iee.randomBytes)(8).toString("hex")}.tmp`;try{Er.writeFileSync(r,t),Er.renameSync(r,e)}catch(n){try{Er.unlinkSync(r)}catch{}throw n}}var yvt=1440*60*1e3;function Pj(e,t){Po.mkdirSync(xa.dirname(e),{recursive:!0});let r=`${e}.${process.pid}.${RSe.randomBytes(8).toString("hex")}.tmp`;try{Po.writeFileSync(r,JSON.stringify(t,null,2)+`
|
|
20923
|
-
`),Po.renameSync(r,e)}catch(n){try{Po.unlinkSync(r)}catch{}throw n}}function OSe(e){return`'${e.replace(/'/g,"'\\''")}'`}var Nee="# visa-cli-hud-v1";function Cj(e,t){if(!e&&!t&&gvt())return`visa-cli config statusline ${Nee}`;let r=e??process.execPath,n=t??process.argv[1]??"",i=n?xa.resolve(n):"";return`${i?`${OSe(r)} ${OSe(i)} config statusline`:"visa-cli config statusline"} ${Nee}`}function gvt(){try{return(0,NSe.execSync)("command -v visa-cli",{stdio:"ignore",timeout:1e3}),!0}catch{return!1}}function iy(e){return typeof e!="string"?!1:e.includes(Nee)?!0:e.includes("visa-cli")&&e.includes("statusline")}function bvt(){return"4.1.0-rc.
|
|
20923
|
+
`),Po.renameSync(r,e)}catch(n){try{Po.unlinkSync(r)}catch{}throw n}}function OSe(e){return`'${e.replace(/'/g,"'\\''")}'`}var Nee="# visa-cli-hud-v1";function Cj(e,t){if(!e&&!t&&gvt())return`visa-cli config statusline ${Nee}`;let r=e??process.execPath,n=t??process.argv[1]??"",i=n?xa.resolve(n):"";return`${i?`${OSe(r)} ${OSe(i)} config statusline`:"visa-cli config statusline"} ${Nee}`}function gvt(){try{return(0,NSe.execSync)("command -v visa-cli",{stdio:"ignore",timeout:1e3}),!0}catch{return!1}}function iy(e){return typeof e!="string"?!1:e.includes(Nee)?!0:e.includes("visa-cli")&&e.includes("statusline")}function bvt(){return"4.1.0-rc.51"}function Oj(e){let t=xa.dirname(xa.resolve(e));return xa.basename(t)===".claude"?xa.dirname(t):BSe.homedir()}function Ij(e,t){let r=xa.relative(t,e);return!r.startsWith("..")&&!xa.isAbsolute(r)?`~/${r}`:e}function _vt(e){return xa.join(Oj(e),".visa-cli","hud-self-heal.json")}function vvt(e,t,r,n){try{if(!Po.existsSync(e))return!1;let i=JSON.parse(Po.readFileSync(e,"utf-8"));return i.version===t&&typeof i.checkedAt=="number"&&r-i.checkedAt<n}catch{return!1}}function Ree(e,t,r){try{Pj(e,{version:t,checkedAt:r})}catch{}}function wvt(e,t){return e&&typeof e=="object"&&!Array.isArray(e)?{...e,type:"command",command:t}:{type:"command",command:t}}function kj(e,t={}){let r=t.now??Date.now(),n=t.version??bvt(),i=t.stampPath??_vt(e),o=t.minIntervalMs??yvt,s=[],a=!1,c=!1;if(!t.force&&vvt(i,n,r,o))return{checked:!1,statusLineRepaired:!1,shellHudRemoved:!1,messages:s,skippedReason:"recently checked"};try{if(!Po.existsSync(e))return Ree(i,n,r),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:s};let u=JSON.parse(Po.readFileSync(e,"utf-8")),d=u.statusLine,l=d&&typeof d=="object"&&!Array.isArray(d)?d.command:"";if(!iy(l))return Ree(i,n,r),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:s};let p=(t.getCommand??Cj)();if(l!==p&&(u.statusLine=wvt(d,p),Pj(e,u),a=!0,s.push("Repaired Claude Code statusLine command to use the current Visa CLI.")),!Rj()){let f=Oj(e);if(N_(f).length>0){let h=E0(null,f);if(h.removed&&h.rcPaths&&h.rcPaths.length>0){let y=h.rcPaths.map(v=>Ij(v,f)).join(", ");c=!0,s.push(`Cleaned legacy shell-prompt HUD block from ${y}.`)}}}return Ree(i,n,r),{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:s}}catch(u){if(t.force){let d=u instanceof Error?u.message:"unknown error";try{process.stderr.write(`visa-cli: HUD self-heal skipped \u2014 ${d}. Run: visa-cli config hud doctor
|
|
20924
20924
|
`)}catch{}}return{checked:!0,statusLineRepaired:a,shellHudRemoved:c,messages:s}}}function Evt(e,t){let r=Oj(t),n=N_(r);if(n.length===0)return e;let i=n.map(o=>Ij(o,r)).join(", ");return`${e}
|
|
20925
20925
|
Note: a shell-prompt HUD block was detected in ${i}. If it is unintended, remove it with: visa-cli config hud disable shell`}function Rj(e=process.env.VISA_HUD_KEEP_SHELL){if(e===void 0)return!1;let t=e.trim().toLowerCase();return t==="1"||t==="true"||t==="yes"||t==="on"}function kSe(e,t){let r=Oj(t),n=N_(r);if(n.length===0)return e;let i=n.map(s=>Ij(s,r)).join(", ");if(Rj())return`${e}
|
|
20926
20926
|
Note: a legacy shell-prompt HUD block was detected in ${i}. VISA_HUD_KEEP_SHELL set \u2014 leaving it in place. Remove it any time with: visa-cli config hud disable shell`;let o=E0(null,r);if(o.removed&&o.rcPaths&&o.rcPaths.length>0){let s=o.rcPaths.map(a=>Ij(a,r)).join(", ");return`${e}
|
|
@@ -20930,8 +20930,8 @@ Note: a legacy shell-prompt HUD block was detected in ${i} but could not be auto
|
|
|
20930
20930
|
`),"","Visa Key active","Scoped agent spend credential ready for apps and agents","",...Svt([["Key",e.key],["Label",e.label],["Owner",e.owner],["Daily cap",`${Bee(e.daily_cap_cents)}/day`],["Total cap",HSe(e.total_cap_cents)],["Allowed tools",$Se(e.allowed_tools)]]),"","Guardrails",`- Spend: ${Bee(e.daily_cap_cents)}/day, ${HSe(e.total_cap_cents)} total`,`- Tools: ${$Se(e.allowed_tools)}`,"- Auth: X-Api-Key header for supported v4 services","Save this key now - it won't be shown again."];return e.biometric_warning?r.push("",FSe,`Server warning: ${e.biometric_warning}`):e.biometric_enabled&&r.push("",FSe),`${r.join(`
|
|
20931
20931
|
`)}
|
|
20932
20932
|
`}function KSe(e){return e.json===!0||e.isTTY!==!0}function jee(e){if(!e)return;let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new Error("--daily-cap must be a positive USD amount.");let r=Math.round(t*100);if(r<100||r>1e4)throw new Error("--daily-cap must be between 1 and 100 USD.");return r}function Uee(e){if(e===!1)return null;if(!e)return;let t=Number(e);if(!Number.isFinite(t)||t<=0)throw new Error("--total-cap must be a positive USD amount.");let r=Math.round(t*100);if(r<100||r>1e6)throw new Error("--total-cap must be between 1 and 10000 USD.");return r}function WSe(e,t){let r=jee(e);if(r!==void 0)return r;if(KSe(t))return 500}function GSe(e,t){let r=Uee(e);if(r!==void 0)return r;if(KSe(t)||t.recommendedCapsAccepted===!0)return 2500}G4();G4();zj();var Gee=require("child_process"),PTe=require("util"),CTe=_e(require("crypto")),tn=_e(require("fs")),OTe=_e(require("os")),zs=_e(require("path"));pd();dj();w0();var x0=(0,PTe.promisify)(Gee.execFile),Yvt=6e4,Zvt=()=>process.platform==="darwin",J4=()=>process.platform==="win32",uy=zs.join(OTe.homedir(),".visa-mcp","bin"),U_=zs.join(uy,"Visa CLI"),A0=zs.join(uy,"visa-keychain-win.exe"),kTe=zs.join(__dirname,"..","native"),_Te="6",vTe=zs.join(uy,"visa-keychain.version"),wTe=zs.join(uy,"visa-keychain.sha256"),ETe="1",ATe=zs.join(uy,"visa-keychain-win.version"),xTe=zs.join(uy,"visa-keychain-win.sha256"),RTe=[zs.join(kTe,"bin","win32-x64","visa-keychain-win.exe"),zs.resolve(__dirname,"..","..","native","bin","win32-x64","visa-keychain-win.exe"),zs.resolve(__dirname,"..","native","bin","win32-x64","visa-keychain-win.exe")];function Hj(e){let t=tn.readFileSync(e);return CTe.createHash("sha256").update(t).digest("hex")}function Xvt(e){let t=e.trim();if(t.startsWith("OK:"))return t.slice(3);if(t==="OK")return;let r=t.startsWith("ERROR:")?t.slice(6):"Unknown error";throw new Error(r)}function STe(e){let t=typeof e?.message=="string"?e.message:"";return e?.code==="ETIMEDOUT"||e?.killed===!0||/timed out|timeout/i.test(t)}function TTe(e){let t=Math.max(1,Math.round(e/1e3));return new Error(`Timed out waiting for Touch ID/device approval after ${t}s.`)}async function NTe(){try{if(tn.readFileSync(vTe,"utf-8").trim()===_Te&&tn.existsSync(U_)){let n=tn.readFileSync(wTe,"utf-8").trim();if(Hj(U_)!==n)Ce.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),tn.unlinkSync(U_);else return U_}}catch{}let e=zs.join(kTe,"visa-keychain.m");if(tn.existsSync(e)||(e=zs.resolve(__dirname,"..","..","native","visa-keychain.m")),tn.existsSync(e)||(e=zs.resolve(__dirname,"..","native","visa-keychain.m")),!tn.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");tn.mkdirSync(uy,{recursive:!0,mode:448});try{await x0("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",U_,e],{timeout:3e4})}catch(r){throw r.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):r}let t=Hj(U_);return tn.writeFileSync(wTe,t,{mode:384}),tn.writeFileSync(vTe,_Te,{mode:384}),U_}function BTe(){for(let e of RTe)if(tn.existsSync(e))return e;return null}async function Vj(){try{if(tn.readFileSync(ATe,"utf-8").trim()===ETe&&tn.existsSync(A0)){let n=tn.readFileSync(xTe,"utf-8").trim();if(Hj(A0)!==n)Ce.warn("binary:hash-mismatch:win32",{message:"Windows binary hash mismatch. Redeploying."}),tn.unlinkSync(A0);else return A0}}catch{}let e=BTe();if(!e)throw new Error(`visa-keychain-win.exe not found in package. Reinstall @visa/cli.
|
|
20933
|
-
If building from source, run native/build-win.bat first.`);tn.mkdirSync(uy,{recursive:!0}),tn.copyFileSync(e,A0);let t=Hj(A0);return tn.writeFileSync(xTe,t,{mode:384}),tn.writeFileSync(ATe,ETe,{mode:384}),A0}async function Qvt(){return J4()?Vj():NTe()}var $j="visa-cli",Fj="attestation-key";async function e5t(e){if(!await sf())throw new Error("macOS Keychain is unavailable in this environment (no default keychain), so the Touch ID key cannot be stored. Run this command in a regular user session.");try{await x0("security",["delete-generic-password","-s",$j,"-a",Fj],{timeout:5e3})}catch{}try{await x0("security",["add-generic-password","-s",$j,"-a",Fj,"-w",e],{timeout:5e3})}catch(t){throw new Error(`Could not store the Touch ID key in the macOS Keychain (${t5t(t)}).`)}}function t5t(e){let t=e,r=[t?.stderr,t?.message].filter(n=>typeof n=="string").join(" ").toLowerCase();return/canceled|cancelled/.test(r)?"the Keychain authorization was canceled":/locked/.test(r)?"the Keychain is locked":/not permitted|permission denied|not authorized/.test(r)?"Keychain access was denied":/could not be found|no default keychain/.test(r)?"no default keychain was found":"the security tool reported an error"}function r5t(e){let t=typeof e?.code=="number"?e.code:void 0,r=typeof e?.stderr=="string"?e.stderr:"",n=typeof e?.stdout=="string"?e.stdout:"",i=[r,n,e?.message].filter(Boolean).join(" ").trim();return t===44||/could not be found|item(?: was)? not found|no such keychain item|not found/i.test(i)?{state:"absent",usable:!1,message:"No local attestation key was found."}:/user interaction is not allowed|user canceled|user cancelled|authorization failed|interaction not allowed|keychain.*locked|denied|not authorized/i.test(i)?{state:"denied",usable:!1,message:"The local attestation key exists but Keychain access was denied or unavailable."}:{state:"error",usable:!1,message:i||"Could not read the local attestation key from Keychain."}}async function n5t(){if(!await sf())return{key:null,status:{state:"denied",usable:!1,message:"macOS Keychain is unavailable in this environment (no default keychain)."}};try{let{stdout:e}=await x0("security",["find-generic-password","-s",$j,"-a",Fj,"-w"],{timeout:5e3}),t=e.trim();return t?{key:t,status:{state:"present",usable:!0}}:{key:null,status:{state:"absent",usable:!1,message:"No local attestation key was found."}}}catch(e){return{key:null,status:r5t(e)}}}async function i5t(){let e=await n5t();if(e.key)return e.key;if(e.status.state==="absent")return null;throw new Error(e.status.message||"Could not read the local attestation key from Keychain.")}async function jTe(e){let t=await Qvt(),r;try{r=(await x0(t,e,{timeout:6e4})).stdout}catch(n){r=n.stdout||"";let i=r.trim();throw i.startsWith("ERROR:")?new Error(i.slice(6)):new Error(n.stderr?.toString().trim()||n.message||"Unknown error")}return Xvt(r)}var ITe=!1;function o5t(){if(!J4())return!1;try{return tn.existsSync(A0)||BTe()!==null?!0:(ITe||(ITe=!0,Ce.warn("binary:missing:win32",{message:"visa-keychain-win.exe not found; Windows Hello attestation unavailable on this install.",binPath:A0,searchedPrebuiltPaths:RTe})),!1)}catch{return!1}}function S0(){return IT()||Zvt()?!0:J4()?o5t():!1}async function UTe(){if(J4()){let i=await Vj(),{stdout:o}=await x0(i,["generate-key"],{timeout:3e4}),s=o.trim();if(s.startsWith("OK:"))return s.slice(3);throw new Error(s.startsWith("ERROR:")?s.slice(6):"Key generation failed")}let e=await jTe(["generate-key"]);if(!e)throw new Error("Key generation returned no output");let t=e.indexOf(":");if(t<0)throw new Error("Unexpected generate-key output format");let r=e.slice(0,t),n=e.slice(t+1);return await e5t(r),n}async function Jee(e,t,r={}){if(IT())return Promise.resolve(Z9e());let n=r.timeoutMs??Yvt;if(J4()){let a=await Vj(),c=["sign",e];t&&c.push(t);let u;try{u=(await x0(a,c,{timeout:n})).stdout}catch(l){throw STe(l)?TTe(n):l}let d=u.trim();if(d.startsWith("OK:"))return d.slice(3);throw new Error(d.startsWith("ERROR:")?d.slice(6):"Unknown error")}let i=await i5t();if(!i)throw new Error("Attestation key not found. Run setup to generate a new key.");let o=await NTe(),s=["sign",e];return t&&s.push(t),new Promise((a,c)=>{let u=(0,Gee.execFile)(o,s,{timeout:n},(d,l)=>{let p=(l||"").trim();if(d){p.startsWith("ERROR:")?c(new Error(p.slice(6))):STe(d)?c(TTe(n)):c(new Error(d.stderr?.toString().trim()||d.message||"Unknown error"));return}p.startsWith("OK:")?a(p.slice(3)):c(new Error(p.startsWith("ERROR:")?p.slice(6):"Unknown error"))});u.stdin.write(i),u.stdin.end()})}async function Kj(){if(J4()){try{let e=await Vj();await x0(e,["delete-key"],{timeout:1e4})}catch{}return}if(await sf())try{await x0("security",["delete-generic-password","-s",$j,"-a",Fj],{timeout:5e3})}catch{}try{await jTe(["delete-key"])}catch{}}w0();pd();_j();RU();r6();var lke=require("child_process"),TM=_e(require("fs")),IM=_e(require("os")),pke=_e(require("path"));MT();ay();dj();var HCe="4.1.0-rc.
|
|
20934
|
-
`)}function FCe(e){return JSON.stringify({config:e.entries.map(t=>({key:t.key,value:t.value,source:t.source,hint:t.hint})),statusError:e.statusError},null,2)}var mne=require("node:os"),A7=require("node:path"),x7=require("node:fs/promises"),tOe=require("node:fs"),rOe=require("node:url"),nOe=require("node:crypto");pd();var lEt=new Set(["USD","USDC","EUR","GBP","CAD","AUD"]);function E8(e,t){let r=t.toUpperCase();return!Number.isFinite(e)||!lEt.has(r)?`${e} ${r} (minor units)`:`${(e/100).toFixed(2)} ${r}`}var U0=class extends Error{constructor(t){super(t),this.name="PayValidationError"}};function VCe(e){let t;try{t=new URL(e)}catch{throw new U0(`Invalid URL: ${e}. Expected a fully-qualified http(s) URL.`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new U0(`Unsupported URL scheme "${t.protocol}". Only http and https are allowed.`);return t}pd();var pEt={ucp_checkout_handoff:"checkout_agent_access",ucp_checkout_reconcile:"checkout_agent_access",pay_merchant:"checkout_agent_access",pay_merchant_status:"checkout_agent_access",start_card_mandate:"checkout_agent_access"},fEt=300*1e3,cne={},KCe=0,v7=null;function mEt(){return v7||(v7=(async()=>{try{let e=await gd.getFeatureFlags();cne=e&&e.flags||{},KCe=Date.now()}catch(e){cne={},Ce.warn("feature-flags:fetch-failed",{error:e instanceof Error?e.message:String(e)})}finally{v7=null}})(),v7)}async function w7(){Date.now()-KCe<fEt||await mEt()}function Py(e){let t=pEt[e];return t?cne[t]!==!0:!1}var WCe=require("node:crypto"),E7=class extends Error{constructor(r){super(`Approval handoff already exists with different inputs for review ${r}`);this.reviewId=r;this.name="PayMerchantApprovalConflictError"}reviewId},cM=class{constructor(t={}){this.options=t}options;jobsByOperation=new Map;operationByReview=new Map;now(){return(this.options.now??Date.now)()}activeTtlMs(){return this.options.activeTtlMs??300*1e3}terminalTtlMs(){return this.options.terminalTtlMs??300*1e3}async waitUntilQueryable(t){let r;try{await Promise.race([t,new Promise(n=>{r=setTimeout(n,Math.max(0,this.options.initialWaitMs??1e3)),r.unref?.()})])}finally{r&&clearTimeout(r)}}finish(t,r){t.inFlight=!1,t.status=r,t.expiresAtMs=this.now()+this.terminalTtlMs(),t.resolveReady()}pruneExpired(){let t=this.now();for(let[r,n]of this.jobsByOperation)if(!(n.expiresAtMs>t)){if(n.inFlight){(n.status==="starting"||n.status==="awaiting_passkey")&&(n.status="reconciling",n.error="Approval handoff expired while the checkout was in progress; reconcile with the merchant before retrying",n.resolveReady()),n.expiresAtMs=t+this.terminalTtlMs();continue}this.jobsByOperation.delete(r),this.operationByReview.get(n.reviewId)===r&&this.operationByReview.delete(n.reviewId)}}snapshot(t){return{operationId:t.operationId,reviewId:t.reviewId,status:t.status,approvalUrl:t.approvalUrl,result:t.result,error:t.error,expiresAt:new Date(t.expiresAtMs).toISOString()}}get(t){this.pruneExpired();let r=this.jobsByOperation.get(t);return r?this.snapshot(r):null}async start(t){this.pruneExpired();let r=this.operationByReview.get(t.reviewId),n=r?this.jobsByOperation.get(r):void 0;if(n){if(n.fingerprint!==t.fingerprint)throw new E7(t.reviewId);return await this.waitUntilQueryable(n.ready),this.snapshot(n)}let i=()=>{},o=new Promise(u=>{i=u}),s=(this.options.idFactory??WCe.randomUUID)(),a={operationId:s,reviewId:t.reviewId,fingerprint:t.fingerprint,status:"starting",approvalUrl:null,result:null,error:null,expiresAtMs:this.now()+this.activeTtlMs(),inFlight:!0,ready:o,resolveReady:i};this.jobsByOperation.set(s,a),this.operationByReview.set(t.reviewId,s);let c=u=>{a.status==="starting"&&(a.approvalUrl=u,a.status="awaiting_passkey",a.resolveReady())};return Promise.resolve().then(()=>t.run(c)).then(u=>{a.result=u,a.error=null,this.finish(a,"completed")}).catch(u=>{a.error=u instanceof Error?u.message:String(u),this.finish(a,"failed")}),await this.waitUntilQueryable(o),this.snapshot(a)}};function iOe(e){return[(0,A7.join)(e,"checkout-engine","index.js"),(0,A7.join)(e,"..","checkout-engine","index.js")]}function xEt(e,t=tOe.existsSync){return iOe(e).find(r=>t(r))??null}var dM=null,oOe=async()=>{if(dM)return dM;let e=xEt(__dirname);if(!e)throw new Error(`Cannot find module: the checkout engine was not packaged (looked in ${iOe(__dirname).join(" and ")}).`);return dM=(await import((0,rOe.pathToFileURL)(e).href)).createCliCheckoutEngine({cardDrawVerdict:await SEt(),cardMandateRegister:await TEt()}),dM};async function SEt(){let e=await Promise.resolve().then(()=>(pne(),lne));return{loadCapability:t=>e.loadCardMandateCapability({agentRef:t}),fetchVerdict:t=>e.fetchCardDrawVerdict(t)}}async function TEt(){let e=await Promise.resolve().then(()=>(pne(),lne));return{loadCapability:t=>e.loadCardMandateCapability({agentRef:t}),register:t=>e.registerCardMandate(t)}}async function hne(){return Py("pay_merchant")?(await w7(),Py("pay_merchant")):!1}var sOe=(0,A7.join)((0,mne.homedir)(),".visa-mcp","agent-credential.json"),aOe=(0,A7.join)((0,mne.homedir)(),".visa-mcp","contact.json"),cOe=new cM;function S7(e){return e.replace(/https?:\/\/[^\s"')\]]+/gi,t=>{try{return new URL(t).origin}catch{return"[url]"}}).slice(0,300)}var IEt=new Set(["USD","USDC","EUR","GBP","CAD","AUD"]);function uOe(e){return IEt.has(e)?e:null}async function lM(e){try{await e.emitTelemetry([{timestamp:new Date().toISOString(),tool_name:"pay_merchant",user_prompt:"",tool_params:JSON.stringify({action:e.action,rail:"card",merchant_host:e.merchantHost,amount_minor:e.amountMinor,payment_amount_unit:"major",currency:e.currency,...e.submit===void 0?{}:{submit:e.submit},source:e.source??null,draw_id:e.drawId??null}),result_success:e.success,result_error:e.errorMessage?S7(e.errorMessage):null,result_json:JSON.stringify({outcome:e.outcome,confirmationRef:e.confirmationRef??null,source:e.source??null,remainingMinor:e.remainingMinor??null,...e.paymentStatus?{paymentStatus:e.paymentStatus}:{},...e.settlementVerified===void 0?{}:{settlementVerified:e.settlementVerified}}),payment_rail:e.action==="pay"&&e.submit===!0?"card":null,payment_amount:e.action==="pay"&&e.submit===!0?e.amountMinor/100:null,payment_currency:uOe(e.currency),merchant_name:e.merchantHost,transaction_id:null,tx_hash:null,protocol:null,http_status:null,duration_ms:Math.max(0,Date.now()-e.startedAt),source:"cli",endpoint:"/v4/checkout",resolved_model:null,session_budget_id:null}])}catch(t){Ce.warn("pay_merchant:telemetry_failed",{action:e.action,error:t instanceof Error?t.message:String(t)})}}async function eOe(e){try{await e.emitTelemetry([{timestamp:new Date().toISOString(),tool_name:"start_card_mandate",user_prompt:"",tool_params:JSON.stringify({rail:"card",merchant_host:e.merchantHost,ceiling_minor:e.ceilingMinor,currency:e.currency}),result_success:e.success,result_error:e.errorMessage?S7(e.errorMessage):null,result_json:JSON.stringify({outcome:e.outcome,mandateId:e.mandateId??null,remainingMinor:e.remainingMinor??null}),payment_rail:null,payment_amount:null,payment_currency:uOe(e.currency),merchant_name:e.merchantHost,transaction_id:null,tx_hash:null,protocol:null,http_status:null,duration_ms:Math.max(0,Date.now()-e.startedAt),source:"cli",endpoint:"/v4/mandate",resolved_model:null,session_budget_id:null}])}catch(t){Ce.warn("start_card_mandate:telemetry_failed",{error:t instanceof Error?t.message:String(t)})}}function fne(e){if(typeof e!="string"||!/^\d+(\.\d{1,2})?$/.test(e)||Number(e)<=0)throw new U0(`Invalid amount ${JSON.stringify(e)}. Expected a positive decimal like "5.00".`);return e}function dOe(e,t){if(e.status==="completed")return{...e.result??{},action:t,approvalStatus:"completed",operationId:e.operationId,reviewId:e.reviewId,expiresAt:e.expiresAt};if(e.status==="failed"){let r=S7(e.error??"approval failed");return{success:!1,action:t,approvalStatus:"failed",operationId:e.operationId,reviewId:e.reviewId,expiresAt:e.expiresAt,message:`${r}. Nothing was charged unless a returned receipt explicitly says confirmed.`}}return e.status==="awaiting_passkey"&&e.approvalUrl?{success:!0,action:t,approvalStatus:"awaiting_passkey",operationId:e.operationId,reviewId:e.reviewId,expiresAt:e.expiresAt,requiresBrowser:!0,browserUrl:e.approvalUrl,approval:{type:"visa_passkey",url:e.approvalUrl,expiresAt:e.expiresAt,button:{label:"Open Visa approval",webApp:{url:e.approvalUrl}}},message:"Open the Visa approval link and complete the passkey. This Telegram or messaging handoff is not itself the passkey and has not charged the card."}:e.status==="reconciling"?{success:!1,action:t,approvalStatus:"reconciling",operationId:e.operationId,reviewId:e.reviewId,expiresAt:e.expiresAt,message:"The approval window expired while checkout was still in progress. Check this operation again for a receipt and reconcile with the merchant before starting a fresh review."}:{success:!0,action:t,approvalStatus:"starting",operationId:e.operationId,reviewId:e.reviewId,expiresAt:e.expiresAt,message:"Visa is preparing the hosted passkey approval. Check this approval again shortly."}}async function lOe(e={},t={}){if(await(t.flagDisabled??hne)())return{success:!1,message:"pay_merchant_status requires the checkout_agent_access flag on your account. Ask an admin to enable it, then retry."};let n=typeof e.operationId=="string"&&/^[A-Za-z0-9_-]{1,200}$/.test(e.operationId)?e.operationId:null;if(!n)return{success:!1,action:"status",approvalStatus:"unknown",message:'A valid operationId from pay_merchant action "authorize" is required.'};let o=(t.approvalJobs??cOe).get(n);return o?dOe(o,"status"):{success:!1,action:"status",operationId:n,approvalStatus:"unknown",message:"No active approval operation exists. It may have expired or the MCP process may have restarted. If approval or merchant submission may have begun, reconcile the merchant order or receipt before starting a fresh review; never retry a purchase blindly."}}async function pOe(e={},t={}){let r=(e.rail??"card").toLowerCase();if(r!=="card")return{success:!1,message:`pay_merchant only implements the "card" rail today (got ${JSON.stringify(r)}). For stablecoin/x402, use the wallet tools (wallet_pay / wallet_directory_pay).`};let n=t.verifyUrl!==void 0?t.verifyUrl:Vee()&&!process.env.VISA_VERIFY_WEB_URL?null:cy();if(n===null)return{success:!1,message:"pay_merchant is not available in stable CLI builds (it runs an on-device mint and is limited to tester/RC builds). Use a preview build with VISA_VERIFY_WEB_URL set and the checkout_agent_access flag enabled."};if(await(t.flagDisabled??hne)())return{success:!1,message:"pay_merchant requires the checkout_agent_access flag on your account. Ask an admin to enable it, then retry."};let o=e.action??"review";if(!["review","pay","authorize"].includes(o))return{success:!1,message:`Unknown pay_merchant action ${JSON.stringify(o)}. Use "review" (default), "authorize", or "pay".`};let s=t.approvalJobs??cOe,a,c,u=(e.currency??"USD").toUpperCase();if(!/^[A-Z]{3}$/.test(u))return{success:!1,message:`Invalid currency ${JSON.stringify(e.currency)}. Expected a 3-letter ISO code like "USD".`};try{a=VCe(e.url??"").toString(),c=fne(e.amount)}catch(I){if(I instanceof U0)return{success:!1,message:I.message};throw I}let d=t.credentialPath??sOe,l=t.contactPath??aOe;try{await(0,x7.readFile)(d,"utf8")}catch{return{success:!1,message:"No legacy VIC card authority is provisioned on this device. Identity pairing does not create or repair card authority, and this internal build has no self-serve attachment flow yet. Use a pre-provisioned VIC test runtime or ask the VIC operator; no checkout started."}}let p;try{p=JSON.parse(await(0,x7.readFile)(l,"utf8"))}catch{return{success:!1,message:`No contact details at ${l}. Write your name/email/address there (chmod 600) first.`}}let f=null;if(o==="pay"||o==="authorize"){let I=typeof e.confirm=="string"?e.confirm.trim():"",T=/^PAY (\S+)$/.exec(I);if(!T)return{success:!1,action:o,message:'Confirmation required: pass confirm:"PAY <reviewId>" using the reviewId from a prior pay_merchant { action:"review" } call. Nothing was charged.'};f=T[1]}let m=t.allowSubmit??process.env.CHECKOUT_AGENT_ALLOW_SUBMIT==="1";if(o==="pay"&&!m)return{success:!1,action:"pay",reviewId:f,outcome:"not-submitted",paymentStatus:"not_submitted",settlementVerified:!1,message:'Checkout submission is disabled. No payment credential was requested, filled, or submitted. Use action:"review" for safe inspection, or explicitly enable checkout submission before a real pay call.'};let h=t.loadEngine??oOe,y;try{y=await h()}catch(I){let T=I instanceof Error?I.message:String(I);if(/ERR_MODULE_NOT_FOUND|Cannot find (module|package)/.test(T))return{success:!1,message:/checkout engine was not packaged/.test(T)?"The checkout engine was not packaged into this @visa/cli build (a build/packaging fault). Reinstall @visa/cli from a release that includes it. No charge was made.":"The checkout browser runtime is not installed (playwright-core is an optional dependency of @visa/cli). Install it with `npm i playwright-core` in the CLI install, then retry. No charge was made."};throw I}let v={url:a,amount:c,currency:u,credentialPath:d,contact:p,approvalBaseUrl:n},E=t.emitTelemetry??(I=>gd.emitTelemetry(I)),_=new URL(a).hostname,w=Math.round(Number(c)*100),A=Date.now();if(o==="review"){Ce.info("pay_merchant:review",{host:_,currency:u});let I;try{I=await y.review(v)}catch(T){throw await lM({emitTelemetry:E,action:"review",merchantHost:_,amountMinor:w,currency:u,outcome:"engine-error",success:!1,errorMessage:T instanceof Error?T.message:String(T),startedAt:A}),T}return await lM({emitTelemetry:E,action:"review",merchantHost:_,amountMinor:w,currency:u,outcome:"reviewed",success:!0,startedAt:A}),{success:!0,action:"review",...I,message:`Review ${I.reviewId}: ${I.merchantHost} wants ${E8(I.amountMinor,I.currency)}. For a messaging handoff, call pay_merchant { action: "authorize", url, amount, confirm: "PAY ${I.reviewId}" }; for a blocking terminal flow use action "pay". No charge yet.`}}let x=f,S=async I=>{Ce.info("pay_merchant:pay",{reviewId:x,submit:m,approvalMode:o==="authorize"?"handoff":"blocking"});let T;try{T=await y.pay({...v,reviewId:x,submit:m,...I?{onApprovalUrl:I}:{}})}catch(U){throw await lM({emitTelemetry:E,action:"pay",merchantHost:_,amountMinor:w,currency:u,outcome:"engine-error",success:!1,errorMessage:U instanceof Error?U.message:String(U),startedAt:A,submit:m}),U}let C=T.outcome==="confirmed"||T.outcome==="reviewed-dry-run",j=T.outcome==="reviewed-dry-run"?"not_submitted":T.outcome==="declined"?"declined":"unverified";await lM({emitTelemetry:E,action:"pay",merchantHost:_,amountMinor:w,currency:u,outcome:T.outcome,confirmationRef:T.confirmationRef,success:C,errorMessage:C?null:T.detail??T.outcome,startedAt:A,submit:m,source:T.source??null,remainingMinor:T.remainingMinor??null,paymentStatus:j,settlementVerified:!1,drawId:T.source==="mandate"?x:null});let M=T.source==="mandate"?` Credential issued from a tap-free active mandate${typeof T.remainingMinor=="number"?` (${T.remainingMinor} ${u} minor units remaining)`:""}.`:T.source==="fresh-tap"?" Credential issued with a fresh per-purchase passkey.":"";return{success:C,action:"pay",reviewId:x,...T,paymentStatus:j,settlementVerified:!1,message:T.outcome==="confirmed"?`Checkout submitted. The merchant reported confirmation ${T.confirmationRef??"(none captured)"}, but processor settlement is not independently verified. Receipt ${T.receiptPath??"(not written)"}.${M}`:T.outcome==="reviewed-dry-run"?"Checkout review validated without requesting, filling, or submitting a payment credential.":T.outcome==="filled-dry-run"?`Legacy credential-disclosure dry-run completed. A usable credential reached the merchant page and may have consumed authority even though no submit click was made.${M}`:`Outcome: ${T.outcome}${T.detail?` \u2014 ${T.detail}`:""}. Do not retry blindly \u2014 verify with the merchant before any re-run.`}};if(o==="authorize"){let I=(0,nOe.createHash)("sha256").update(JSON.stringify([x,a,c,u,m])).digest("hex");Ce.info("pay_merchant:approval_handoff_started",{reviewId:x,merchantHost:_,currency:u,submit:m});try{let T=await s.start({reviewId:x,fingerprint:I,run:async C=>{try{let j=await S(M=>{Ce.info("pay_merchant:approval_handoff_ready",{reviewId:x}),C(M)});return Ce.info("pay_merchant:approval_handoff_completed",{reviewId:x,success:j.success===!0}),j}catch(j){throw Ce.warn("pay_merchant:approval_handoff_failed",{reviewId:x,error:S7(j instanceof Error?j.message:String(j))}),j}}});return dOe(T,"authorize")}catch(T){if(T instanceof E7)return Ce.warn("pay_merchant:approval_handoff_conflict",{reviewId:x}),{success:!1,action:"authorize",reviewId:x,approvalStatus:"conflict",message:"This review already has an approval handoff with different checkout inputs. Do not retry it; create and confirm a fresh review."};throw T}}return S()}async function fOe(e={},t={}){let r=t.verifyUrl!==void 0?t.verifyUrl:cy();if(r===null)return{success:!1,message:"start_card_mandate is not available in stable CLI builds (it runs a server-side mint and is limited to tester/RC builds). Use a preview build with VISA_VERIFY_WEB_URL set and the checkout_agent_access flag enabled."};if(await(t.flagDisabled??hne)())return{success:!1,message:"start_card_mandate requires the checkout_agent_access flag on your account. Ask an admin to enable it, then retry."};let i="USD",o;try{o=fne(e.ceiling)}catch(_){if(_ instanceof U0)return{success:!1,message:_.message};throw _}let s;if(e.perTransaction!==void 0){try{s=fne(e.perTransaction)}catch(_){if(_ instanceof U0)return{success:!1,message:_.message};throw _}if(Number(s)>Number(o))return{success:!1,message:"perTransaction cannot exceed the ceiling."}}let a;if(e.intent!==void 0){if(typeof e.intent!="string")return{success:!1,message:"intent must be a short string."};let _=e.intent.replace(/[\p{Cc}\u2028\u2029]/gu,"").trim().slice(0,200).trim();a=_.length>0?_:void 0}let c=t.credentialPath??sOe,u=t.contactPath??aOe;try{await(0,x7.readFile)(c,"utf8")}catch{return{success:!1,message:"No legacy VIC card authority is provisioned on this device. Identity pairing does not create or repair card authority, and this internal build has no self-serve attachment flow yet. Use a pre-provisioned VIC test runtime or ask the VIC operator; no budget was created."}}let d;try{d=JSON.parse(await(0,x7.readFile)(u,"utf8"))}catch{return{success:!1,message:`No contact details at ${u}. Write your name/email/address there (chmod 600) first.`}}let l=t.loadEngine??oOe,p;try{p=await l()}catch(_){let w=_ instanceof Error?_.message:String(_);if(/ERR_MODULE_NOT_FOUND|Cannot find (module|package)/.test(w))return{success:!1,message:"The checkout engine was not packaged into this @visa/cli build (a build/packaging fault). Reinstall @visa/cli from a release that includes it. No mandate was created."};throw _}let f="retail-mcc-5999",m=Math.round(Number(o)*100),h=t.emitTelemetry??(_=>gd.emitTelemetry(_)),y=Date.now();Ce.info("start_card_mandate:create",{host:f,currency:i});let v;try{v=await p.startCardMandate({...e.agent?.trim()?{agentRef:e.agent.trim()}:{},ceiling:o,currency:i,credentialPath:c,contact:d,approvalBaseUrl:r,...s!==void 0?{perTransaction:s}:{},...a!==void 0?{intent:a}:{}})}catch(_){let w=_ instanceof Error?S7(_.message):String(_);return Ce.warn("start_card_mandate:failed",{message:w}),await eOe({emitTelemetry:h,merchantHost:f,ceilingMinor:m,currency:i,outcome:"engine-error",success:!1,errorMessage:_ instanceof Error?_.message:String(_),startedAt:y}),{success:!1,message:`Could not create the mandate: ${w}`}}let E=v.registerFailed===!0;return E&&Ce.warn("start_card_mandate:register_failed",{mandateId:v.mandateId,host:f}),await eOe({emitTelemetry:h,merchantHost:f,ceilingMinor:m,currency:i,outcome:E?"created-register-failed":"created",success:!E,mandateId:v.mandateId,remainingMinor:v.remainingMinor,startedAt:y}),E?{success:!1,mandateId:v.mandateId,ceiling:o,remainingMinor:v.remainingMinor,currency:v.currencyCode,merchant:v.merchant,merchantHost:v.merchantHost,maxPurchases:v.maxDraws,expiresAt:v.expiresAt,message:`Mandate ${v.mandateId} was created but could NOT be registered for tap-free draws, so it will not be used \u2014 your next pay_merchant will fall through to a fresh per-purchase passkey tap. Re-run to try again once the auth server is reachable.`}:{success:!0,mandateId:v.mandateId,ceiling:o,remainingMinor:v.remainingMinor,currency:v.currencyCode,merchant:v.merchant,merchantHost:v.merchantHost,maxPurchases:v.maxDraws,expiresAt:v.expiresAt,message:`Mandate ${v.mandateId} active: up to ${E8(m,v.currencyCode)} at eligible retail merchants (network category 5999), across up to ${v.maxDraws} purchases, until ${v.expiresAt}. pay_merchant will draw against it tap-free until the budget, purchase count, or time limit is reached. A declined draw leaves the budget untouched and disables this mandate; the next checkout can use a fresh per-purchase approval.`}}var oke=require("node:crypto");var tke=require("node:crypto");var Lr={};Pi(Lr,{BRAND:()=>QEt,DIRTY:()=>u6,EMPTY_PATH:()=>kEt,INVALID:()=>bt,NEVER:()=>CAt,OK:()=>Gs,ParseStatus:()=>ds,Schema:()=>zt,ZodAny:()=>ky,ZodArray:()=>L0,ZodBigInt:()=>l6,ZodBoolean:()=>p6,ZodBranded:()=>I7,ZodCatch:()=>A6,ZodDate:()=>f6,ZodDefault:()=>E6,ZodDiscriminatedUnion:()=>mM,ZodEffects:()=>vd,ZodEnum:()=>v6,ZodError:()=>uc,ZodFirstPartyTypeKind:()=>xt,ZodFunction:()=>yM,ZodIntersection:()=>g6,ZodIssueCode:()=>ye,ZodLazy:()=>b6,ZodLiteral:()=>_6,ZodMap:()=>P8,ZodNaN:()=>O8,ZodNativeEnum:()=>w6,ZodNever:()=>Dl,ZodNull:()=>h6,ZodNullable:()=>Ef,ZodNumber:()=>d6,ZodObject:()=>dc,ZodOptional:()=>bd,ZodParsedType:()=>je,ZodPipeline:()=>P7,ZodPromise:()=>Ry,ZodReadonly:()=>x6,ZodRecord:()=>hM,ZodSchema:()=>zt,ZodSet:()=>C8,ZodString:()=>Oy,ZodSymbol:()=>T8,ZodTransformer:()=>vd,ZodTuple:()=>wf,ZodType:()=>zt,ZodUndefined:()=>m6,ZodUnion:()=>y6,ZodUnknown:()=>D0,ZodVoid:()=>I8,addIssueToContext:()=>Te,any:()=>Ed,array:()=>ue,bigint:()=>nAt,boolean:()=>wd,coerce:()=>hu,custom:()=>wOe,date:()=>iAt,datetimeRegex:()=>_Oe,defaultErrorMap:()=>M0,discriminatedUnion:()=>lAt,effect:()=>wAt,enum:()=>Ad,function:()=>yAt,getErrorMap:()=>A8,getParsedType:()=>vf,instanceof:()=>tAt,intersection:()=>pAt,isAborted:()=>pM,isAsync:()=>x8,isDirty:()=>fM,isValid:()=>Cy,late:()=>eAt,lazy:()=>gAt,literal:()=>bAt,makeIssue:()=>T7,map:()=>mAt,nan:()=>rAt,nativeEnum:()=>_At,never:()=>cAt,null:()=>k8,nullable:()=>AAt,number:()=>Or,object:()=>fe,objectUtil:()=>yne,oboolean:()=>PAt,onumber:()=>IAt,optional:()=>EAt,ostring:()=>TAt,pipeline:()=>SAt,preprocess:()=>xAt,promise:()=>vAt,quotelessJson:()=>PEt,record:()=>Xt,set:()=>hAt,setErrorMap:()=>OEt,strictObject:()=>dAt,string:()=>z,symbol:()=>oAt,transformer:()=>wAt,tuple:()=>fAt,undefined:()=>sAt,union:()=>R8,unknown:()=>aAt,util:()=>Zt,void:()=>uAt});var Zt;(function(e){e.assertEqual=i=>{};function t(i){}e.assertIs=t;function r(i){throw new Error}e.assertNever=r,e.arrayToEnum=i=>{let o={};for(let s of i)o[s]=s;return o},e.getValidEnumValues=i=>{let o=e.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),s={};for(let a of o)s[a]=i[a];return e.objectValues(s)},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 s in i)Object.prototype.hasOwnProperty.call(i,s)&&o.push(s);return o},e.find=(i,o)=>{for(let s of i)if(o(s))return s},e.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,o=" | "){return i.map(s=>typeof s=="string"?`'${s}'`:s).join(o)}e.joinValues=n,e.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(Zt||(Zt={}));var yne;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(yne||(yne={}));var je=Zt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),vf=e=>{switch(typeof e){case"undefined":return je.undefined;case"string":return je.string;case"number":return Number.isNaN(e)?je.nan:je.number;case"boolean":return je.boolean;case"function":return je.function;case"bigint":return je.bigint;case"symbol":return je.symbol;case"object":return Array.isArray(e)?je.array:e===null?je.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?je.promise:typeof Map<"u"&&e instanceof Map?je.map:typeof Set<"u"&&e instanceof Set?je.set:typeof Date<"u"&&e instanceof Date?je.date:je.object;default:return je.unknown}};var ye=Zt.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"]),PEt=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),uc=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){let r=t||function(o){return o.message},n={_errors:[]},i=o=>{for(let s of o.issues)if(s.code==="invalid_union")s.unionErrors.map(i);else if(s.code==="invalid_return_type")i(s.returnTypeError);else if(s.code==="invalid_arguments")i(s.argumentsError);else if(s.path.length===0)n._errors.push(r(s));else{let a=n,c=0;for(;c<s.path.length;){let u=s.path[c];c===s.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(s))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return i(this),n}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,Zt.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){let r={},n=[];for(let i of this.issues)if(i.path.length>0){let o=i.path[0];r[o]=r[o]||[],r[o].push(t(i))}else n.push(t(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};uc.create=e=>new uc(e);var CEt=(e,t)=>{let r;switch(e.code){case ye.invalid_type:e.received===je.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case ye.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,Zt.jsonStringifyReplacer)}`;break;case ye.unrecognized_keys:r=`Unrecognized key(s) in object: ${Zt.joinValues(e.keys,", ")}`;break;case ye.invalid_union:r="Invalid input";break;case ye.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Zt.joinValues(e.options)}`;break;case ye.invalid_enum_value:r=`Invalid enum value. Expected ${Zt.joinValues(e.options)}, received '${e.received}'`;break;case ye.invalid_arguments:r="Invalid function arguments";break;case ye.invalid_return_type:r="Invalid function return type";break;case ye.invalid_date:r="Invalid date";break;case ye.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:Zt.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case ye.too_small:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:r="Invalid input";break;case ye.too_big:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:r="Invalid input";break;case ye.custom:r="Invalid input";break;case ye.invalid_intersection_types:r="Intersection results could not be merged";break;case ye.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case ye.not_finite:r="Number must be finite";break;default:r=t.defaultError,Zt.assertNever(e)}return{message:r}},M0=CEt;var mOe=M0;function OEt(e){mOe=e}function A8(){return mOe}var T7=e=>{let{data:t,path:r,errorMaps:n,issueData:i}=e,o=[...r,...i.path||[]],s={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(s,{data:t,defaultError:a}).message;return{...i,path:o,message:a}},kEt=[];function Te(e,t){let r=A8(),n=T7({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===M0?void 0:M0].filter(i=>!!i)});e.common.issues.push(n)}var ds=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){let n=[];for(let i of r){if(i.status==="aborted")return bt;i.status==="dirty"&&t.dirty(),n.push(i.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,r){let n=[];for(let i of r){let o=await i.key,s=await i.value;n.push({key:o,value:s})}return e.mergeObjectSync(t,n)}static mergeObjectSync(t,r){let n={};for(let i of r){let{key:o,value:s}=i;if(o.status==="aborted"||s.status==="aborted")return bt;o.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof s.value<"u"||i.alwaysSet)&&(n[o.value]=s.value)}return{status:t.value,value:n}}},bt=Object.freeze({status:"aborted"}),u6=e=>({status:"dirty",value:e}),Gs=e=>({status:"valid",value:e}),pM=e=>e.status==="aborted",fM=e=>e.status==="dirty",Cy=e=>e.status==="valid",x8=e=>typeof Promise<"u"&&e instanceof Promise;var et;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(et||(et={}));var _d=class{constructor(t,r,n,i){this._cachedPath=[],this.parent=t,this.data=r,this._path=n,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}},hOe=(e,t)=>{if(Cy(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 r=new uc(e.common.issues);return this._error=r,this._error}}};function Mt(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:i}=e;if(t&&(r||n))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:(s,a)=>{let{message:c}=e;return s.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:i}}var zt=class{get description(){return this._def.description}_getType(t){return vf(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:vf(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ds,ctx:{common:t.parent.common,data:t.data,parsedType:vf(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(x8(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){let r=this._parse(t);return Promise.resolve(r)}parse(t,r){let n=this.safeParse(t,r);if(n.success)return n.data;throw n.error}safeParse(t,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:vf(t)},i=this._parseSync({data:t,path:n.path,parent:n});return hOe(n,i)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:vf(t)};if(!this["~standard"].async)try{let n=this._parseSync({data:t,path:[],parent:r});return Cy(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(n=>Cy(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(t,r){let n=await this.safeParseAsync(t,r);if(n.success)return n.data;throw n.error}async safeParseAsync(t,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:vf(t)},i=this._parse({data:t,path:n.path,parent:n}),o=await(x8(i)?i:Promise.resolve(i));return hOe(n,o)}refine(t,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,o)=>{let s=t(i),a=()=>o.addIssue({code:ye.custom,...n(i)});return typeof Promise<"u"&&s instanceof Promise?s.then(c=>c?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(t,r){return this._refinement((n,i)=>t(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(t){return new vd({schema:this,typeName:xt.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:r=>this["~validate"](r)}}optional(){return bd.create(this,this._def)}nullable(){return Ef.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return L0.create(this)}promise(){return Ry.create(this,this._def)}or(t){return y6.create([this,t],this._def)}and(t){return g6.create(this,t,this._def)}transform(t){return new vd({...Mt(this._def),schema:this,typeName:xt.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new E6({...Mt(this._def),innerType:this,defaultValue:r,typeName:xt.ZodDefault})}brand(){return new I7({typeName:xt.ZodBranded,type:this,...Mt(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new A6({...Mt(this._def),innerType:this,catchValue:r,typeName:xt.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return P7.create(this,t)}readonly(){return x6.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},REt=/^c[^\s-]{8,}$/i,NEt=/^[0-9a-z]+$/,BEt=/^[0-9A-HJKMNP-TV-Z]{26}$/i,jEt=/^[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,UEt=/^[a-z0-9_-]{21}$/i,MEt=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,qEt=/^[-+]?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)?)??$/,DEt=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,LEt="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",gne,zEt=/^(?:(?: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])$/,HEt=/^(?:(?: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])$/,$Et=/^(([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]))$/,FEt=/^(([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])$/,VEt=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,KEt=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,gOe="((\\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])))",WEt=new RegExp(`^${gOe}$`);function bOe(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function GEt(e){return new RegExp(`^${bOe(e)}$`)}function _Oe(e){let t=`${gOe}T${bOe(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function JEt(e,t){return!!((t==="v4"||!t)&&zEt.test(e)||(t==="v6"||!t)&&$Et.test(e))}function YEt(e,t){if(!MEt.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||t&&i.alg!==t)}catch{return!1}}function ZEt(e,t){return!!((t==="v4"||!t)&&HEt.test(e)||(t==="v6"||!t)&&FEt.test(e))}var Oy=class e extends zt{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==je.string){let o=this._getOrReturnCtx(t);return Te(o,{code:ye.invalid_type,expected:je.string,received:o.parsedType}),bt}let n=new ds,i;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")t.data.length>o.value&&(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let s=t.data.length>o.value,a=t.data.length<o.value;(s||a)&&(i=this._getOrReturnCtx(t,i),s?Te(i,{code:ye.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&Te(i,{code:ye.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")DEt.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"email",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")gne||(gne=new RegExp(LEt,"u")),gne.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"emoji",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")jEt.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"uuid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")UEt.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"nanoid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")REt.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"cuid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")NEt.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"cuid2",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")BEt.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"ulid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),Te(i,{validation:"url",code:ye.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"regex",code:ye.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?t.data=t.data.trim():o.kind==="includes"?t.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.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),Te(i,{code:ye.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?_Oe(o).test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?WEt.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?GEt(o).test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?qEt.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"duration",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?JEt(t.data,o.version)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"ip",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?YEt(t.data,o.alg)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"jwt",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?ZEt(t.data,o.version)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"cidr",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?VEt.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"base64",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?KEt.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"base64url",code:ye.invalid_string,message:o.message}),n.dirty()):Zt.assertNever(o);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(i=>t.test(i),{validation:r,code:ye.invalid_string,...et.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...et.errToObj(t)})}url(t){return this._addCheck({kind:"url",...et.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...et.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...et.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...et.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...et.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...et.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...et.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...et.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...et.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...et.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...et.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...et.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,...et.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,...et.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...et.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...et.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...et.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...et.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...et.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...et.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...et.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...et.errToObj(r)})}nonempty(t){return this.min(1,et.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 r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};Oy.create=e=>new Oy({checks:[],typeName:xt.ZodString,coerce:e?.coerce??!1,...Mt(e)});function XEt(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,i=r>n?r:n,o=Number.parseInt(e.toFixed(i).replace(".","")),s=Number.parseInt(t.toFixed(i).replace(".",""));return o%s/10**i}var d6=class e extends zt{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)!==je.number){let o=this._getOrReturnCtx(t);return Te(o,{code:ye.invalid_type,expected:je.number,received:o.parsedType}),bt}let n,i=new ds;for(let o of this._def.checks)o.kind==="int"?Zt.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),Te(n,{code:ye.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(n=this._getOrReturnCtx(t,n),Te(n,{code:ye.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)&&(n=this._getOrReturnCtx(t,n),Te(n,{code:ye.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?XEt(t.data,o.value)!==0&&(n=this._getOrReturnCtx(t,n),Te(n,{code:ye.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),Te(n,{code:ye.not_finite,message:o.message}),i.dirty()):Zt.assertNever(o);return{status:i.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,et.toString(r))}gt(t,r){return this.setLimit("min",t,!1,et.toString(r))}lte(t,r){return this.setLimit("max",t,!0,et.toString(r))}lt(t,r){return this.setLimit("max",t,!1,et.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:et.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:et.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:et.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:et.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:et.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:et.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:et.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:et.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:et.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:et.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&Zt.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(t===null||n.value<t)&&(t=n.value)}return Number.isFinite(r)&&Number.isFinite(t)}};d6.create=e=>new d6({checks:[],typeName:xt.ZodNumber,coerce:e?.coerce||!1,...Mt(e)});var l6=class e extends zt{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)!==je.bigint)return this._getInvalidInput(t);let n,i=new ds;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(n=this._getOrReturnCtx(t,n),Te(n,{code:ye.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)&&(n=this._getOrReturnCtx(t,n),Te(n,{code:ye.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),Te(n,{code:ye.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):Zt.assertNever(o);return{status:i.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return Te(r,{code:ye.invalid_type,expected:je.bigint,received:r.parsedType}),bt}gte(t,r){return this.setLimit("min",t,!0,et.toString(r))}gt(t,r){return this.setLimit("min",t,!1,et.toString(r))}lte(t,r){return this.setLimit("max",t,!0,et.toString(r))}lt(t,r){return this.setLimit("max",t,!1,et.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:et.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:et.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:et.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:et.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:et.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:et.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};l6.create=e=>new l6({checks:[],typeName:xt.ZodBigInt,coerce:e?.coerce??!1,...Mt(e)});var p6=class extends zt{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==je.boolean){let n=this._getOrReturnCtx(t);return Te(n,{code:ye.invalid_type,expected:je.boolean,received:n.parsedType}),bt}return Gs(t.data)}};p6.create=e=>new p6({typeName:xt.ZodBoolean,coerce:e?.coerce||!1,...Mt(e)});var f6=class e extends zt{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==je.date){let o=this._getOrReturnCtx(t);return Te(o,{code:ye.invalid_type,expected:je.date,received:o.parsedType}),bt}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return Te(o,{code:ye.invalid_date}),bt}let n=new ds,i;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?t.data.getTime()>o.value&&(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):Zt.assertNever(o);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:et.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:et.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}};f6.create=e=>new f6({checks:[],coerce:e?.coerce||!1,typeName:xt.ZodDate,...Mt(e)});var T8=class extends zt{_parse(t){if(this._getType(t)!==je.symbol){let n=this._getOrReturnCtx(t);return Te(n,{code:ye.invalid_type,expected:je.symbol,received:n.parsedType}),bt}return Gs(t.data)}};T8.create=e=>new T8({typeName:xt.ZodSymbol,...Mt(e)});var m6=class extends zt{_parse(t){if(this._getType(t)!==je.undefined){let n=this._getOrReturnCtx(t);return Te(n,{code:ye.invalid_type,expected:je.undefined,received:n.parsedType}),bt}return Gs(t.data)}};m6.create=e=>new m6({typeName:xt.ZodUndefined,...Mt(e)});var h6=class extends zt{_parse(t){if(this._getType(t)!==je.null){let n=this._getOrReturnCtx(t);return Te(n,{code:ye.invalid_type,expected:je.null,received:n.parsedType}),bt}return Gs(t.data)}};h6.create=e=>new h6({typeName:xt.ZodNull,...Mt(e)});var ky=class extends zt{constructor(){super(...arguments),this._any=!0}_parse(t){return Gs(t.data)}};ky.create=e=>new ky({typeName:xt.ZodAny,...Mt(e)});var D0=class extends zt{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Gs(t.data)}};D0.create=e=>new D0({typeName:xt.ZodUnknown,...Mt(e)});var Dl=class extends zt{_parse(t){let r=this._getOrReturnCtx(t);return Te(r,{code:ye.invalid_type,expected:je.never,received:r.parsedType}),bt}};Dl.create=e=>new Dl({typeName:xt.ZodNever,...Mt(e)});var I8=class extends zt{_parse(t){if(this._getType(t)!==je.undefined){let n=this._getOrReturnCtx(t);return Te(n,{code:ye.invalid_type,expected:je.void,received:n.parsedType}),bt}return Gs(t.data)}};I8.create=e=>new I8({typeName:xt.ZodVoid,...Mt(e)});var L0=class e extends zt{_parse(t){let{ctx:r,status:n}=this._processInputParams(t),i=this._def;if(r.parsedType!==je.array)return Te(r,{code:ye.invalid_type,expected:je.array,received:r.parsedType}),bt;if(i.exactLength!==null){let s=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(s||a)&&(Te(r,{code:s?ye.too_big:ye.too_small,minimum:a?i.exactLength.value:void 0,maximum:s?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(Te(r,{code:ye.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(Te(r,{code:ye.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((s,a)=>i.type._parseAsync(new _d(r,s,r.path,a)))).then(s=>ds.mergeArray(n,s));let o=[...r.data].map((s,a)=>i.type._parseSync(new _d(r,s,r.path,a)));return ds.mergeArray(n,o)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:et.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:et.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:et.toString(r)}})}nonempty(t){return this.min(1,t)}};L0.create=(e,t)=>new L0({type:e,minLength:null,maxLength:null,exactLength:null,typeName:xt.ZodArray,...Mt(t)});function S8(e){if(e instanceof dc){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=bd.create(S8(n))}return new dc({...e._def,shape:()=>t})}else return e instanceof L0?new L0({...e._def,type:S8(e.element)}):e instanceof bd?bd.create(S8(e.unwrap())):e instanceof Ef?Ef.create(S8(e.unwrap())):e instanceof wf?wf.create(e.items.map(t=>S8(t))):e}var dc=class e extends zt{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(),r=Zt.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==je.object){let u=this._getOrReturnCtx(t);return Te(u,{code:ye.invalid_type,expected:je.object,received:u.parsedType}),bt}let{status:n,ctx:i}=this._processInputParams(t),{shape:o,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof Dl&&this._def.unknownKeys==="strip"))for(let u in i.data)s.includes(u)||a.push(u);let c=[];for(let u of s){let d=o[u],l=i.data[u];c.push({key:{status:"valid",value:u},value:d._parse(new _d(i,l,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof Dl){let u=this._def.unknownKeys;if(u==="passthrough")for(let d of a)c.push({key:{status:"valid",value:d},value:{status:"valid",value:i.data[d]}});else if(u==="strict")a.length>0&&(Te(i,{code:ye.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let d of a){let l=i.data[d];c.push({key:{status:"valid",value:d},value:u._parse(new _d(i,l,i.path,d)),alwaysSet:d in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let u=[];for(let d of c){let l=await d.key,p=await d.value;u.push({key:l,value:p,alwaysSet:d.alwaysSet})}return u}).then(u=>ds.mergeObjectSync(n,u)):ds.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(t){return et.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:et.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:xt.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let r={};for(let n of Zt.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}omit(t){let r={};for(let n of Zt.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}deepPartial(){return S8(this)}partial(t){let r={};for(let n of Zt.objectKeys(this.shape)){let i=this.shape[n];t&&!t[n]?r[n]=i:r[n]=i.optional()}return new e({...this._def,shape:()=>r})}required(t){let r={};for(let n of Zt.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof bd;)o=o._def.innerType;r[n]=o}return new e({...this._def,shape:()=>r})}keyof(){return vOe(Zt.objectKeys(this.shape))}};dc.create=(e,t)=>new dc({shape:()=>e,unknownKeys:"strip",catchall:Dl.create(),typeName:xt.ZodObject,...Mt(t)});dc.strictCreate=(e,t)=>new dc({shape:()=>e,unknownKeys:"strict",catchall:Dl.create(),typeName:xt.ZodObject,...Mt(t)});dc.lazycreate=(e,t)=>new dc({shape:e,unknownKeys:"strip",catchall:Dl.create(),typeName:xt.ZodObject,...Mt(t)});var y6=class extends zt{_parse(t){let{ctx:r}=this._processInputParams(t),n=this._def.options;function i(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let s=o.map(a=>new uc(a.ctx.common.issues));return Te(r,{code:ye.invalid_union,unionErrors:s}),bt}if(r.common.async)return Promise.all(n.map(async o=>{let s={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:s}),ctx:s}})).then(i);{let o,s=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},d=c._parseSync({data:r.data,path:r.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!o&&(o={result:d,ctx:u}),u.common.issues.length&&s.push(u.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let a=s.map(c=>new uc(c));return Te(r,{code:ye.invalid_union,unionErrors:a}),bt}}get options(){return this._def.options}};y6.create=(e,t)=>new y6({options:e,typeName:xt.ZodUnion,...Mt(t)});var q0=e=>e instanceof b6?q0(e.schema):e instanceof vd?q0(e.innerType()):e instanceof _6?[e.value]:e instanceof v6?e.options:e instanceof w6?Zt.objectValues(e.enum):e instanceof E6?q0(e._def.innerType):e instanceof m6?[void 0]:e instanceof h6?[null]:e instanceof bd?[void 0,...q0(e.unwrap())]:e instanceof Ef?[null,...q0(e.unwrap())]:e instanceof I7||e instanceof x6?q0(e.unwrap()):e instanceof A6?q0(e._def.innerType):[],mM=class e extends zt{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==je.object)return Te(r,{code:ye.invalid_type,expected:je.object,received:r.parsedType}),bt;let n=this.discriminator,i=r.data[n],o=this.optionsMap.get(i);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(Te(r,{code:ye.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),bt)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,n){let i=new Map;for(let o of r){let s=q0(o.shape[t]);if(!s.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of s){if(i.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);i.set(a,o)}}return new e({typeName:xt.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:i,...Mt(n)})}};function bne(e,t){let r=vf(e),n=vf(t);if(e===t)return{valid:!0,data:e};if(r===je.object&&n===je.object){let i=Zt.objectKeys(t),o=Zt.objectKeys(e).filter(a=>i.indexOf(a)!==-1),s={...e,...t};for(let a of o){let c=bne(e[a],t[a]);if(!c.valid)return{valid:!1};s[a]=c.data}return{valid:!0,data:s}}else if(r===je.array&&n===je.array){if(e.length!==t.length)return{valid:!1};let i=[];for(let o=0;o<e.length;o++){let s=e[o],a=t[o],c=bne(s,a);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else return r===je.date&&n===je.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var g6=class extends zt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=(o,s)=>{if(pM(o)||pM(s))return bt;let a=bne(o.value,s.value);return a.valid?((fM(o)||fM(s))&&r.dirty(),{status:r.value,value:a.data}):(Te(n,{code:ye.invalid_intersection_types}),bt)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,s])=>i(o,s)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};g6.create=(e,t,r)=>new g6({left:e,right:t,typeName:xt.ZodIntersection,...Mt(r)});var wf=class e extends zt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==je.array)return Te(n,{code:ye.invalid_type,expected:je.array,received:n.parsedType}),bt;if(n.data.length<this._def.items.length)return Te(n,{code:ye.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),bt;!this._def.rest&&n.data.length>this._def.items.length&&(Te(n,{code:ye.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...n.data].map((s,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new _d(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>ds.mergeArray(r,s)):ds.mergeArray(r,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};wf.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new wf({items:e,typeName:xt.ZodTuple,rest:null,...Mt(t)})};var hM=class e extends zt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==je.object)return Te(n,{code:ye.invalid_type,expected:je.object,received:n.parsedType}),bt;let i=[],o=this._def.keyType,s=this._def.valueType;for(let a in n.data)i.push({key:o._parse(new _d(n,a,n.path,a)),value:s._parse(new _d(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?ds.mergeObjectAsync(r,i):ds.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof zt?new e({keyType:t,valueType:r,typeName:xt.ZodRecord,...Mt(n)}):new e({keyType:Oy.create(),valueType:t,typeName:xt.ZodRecord,...Mt(r)})}},P8=class extends zt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==je.map)return Te(n,{code:ye.invalid_type,expected:je.map,received:n.parsedType}),bt;let i=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([a,c],u)=>({key:i._parse(new _d(n,a,n.path,[u,"key"])),value:o._parse(new _d(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of s){let u=await c.key,d=await c.value;if(u.status==="aborted"||d.status==="aborted")return bt;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of s){let u=c.key,d=c.value;if(u.status==="aborted"||d.status==="aborted")return bt;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}}}};P8.create=(e,t,r)=>new P8({valueType:t,keyType:e,typeName:xt.ZodMap,...Mt(r)});var C8=class e extends zt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==je.set)return Te(n,{code:ye.invalid_type,expected:je.set,received:n.parsedType}),bt;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(Te(n,{code:ye.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(Te(n,{code:ye.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let o=this._def.valueType;function s(c){let u=new Set;for(let d of c){if(d.status==="aborted")return bt;d.status==="dirty"&&r.dirty(),u.add(d.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>o._parse(new _d(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>s(c)):s(a)}min(t,r){return new e({...this._def,minSize:{value:t,message:et.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:et.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};C8.create=(e,t)=>new C8({valueType:e,minSize:null,maxSize:null,typeName:xt.ZodSet,...Mt(t)});var yM=class e extends zt{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==je.function)return Te(r,{code:ye.invalid_type,expected:je.function,received:r.parsedType}),bt;function n(a,c){return T7({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,A8(),M0].filter(u=>!!u),issueData:{code:ye.invalid_arguments,argumentsError:c}})}function i(a,c){return T7({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,A8(),M0].filter(u=>!!u),issueData:{code:ye.invalid_return_type,returnTypeError:c}})}let o={errorMap:r.common.contextualErrorMap},s=r.data;if(this._def.returns instanceof Ry){let a=this;return Gs(async function(...c){let u=new uc([]),d=await a._def.args.parseAsync(c,o).catch(f=>{throw u.addIssue(n(c,f)),u}),l=await Reflect.apply(s,this,d);return await a._def.returns._def.type.parseAsync(l,o).catch(f=>{throw u.addIssue(i(l,f)),u})})}else{let a=this;return Gs(function(...c){let u=a._def.args.safeParse(c,o);if(!u.success)throw new uc([n(c,u.error)]);let d=Reflect.apply(s,this,u.data),l=a._def.returns.safeParse(d,o);if(!l.success)throw new uc([i(d,l.error)]);return l.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:wf.create(t).rest(D0.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,r,n){return new e({args:t||wf.create([]).rest(D0.create()),returns:r||D0.create(),typeName:xt.ZodFunction,...Mt(n)})}},b6=class extends zt{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};b6.create=(e,t)=>new b6({getter:e,typeName:xt.ZodLazy,...Mt(t)});var _6=class extends zt{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return Te(r,{received:r.data,code:ye.invalid_literal,expected:this._def.value}),bt}return{status:"valid",value:t.data}}get value(){return this._def.value}};_6.create=(e,t)=>new _6({value:e,typeName:xt.ZodLiteral,...Mt(t)});function vOe(e,t){return new v6({values:e,typeName:xt.ZodEnum,...Mt(t)})}var v6=class e extends zt{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return Te(r,{expected:Zt.joinValues(n),received:r.parsedType,code:ye.invalid_type}),bt}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let r=this._getOrReturnCtx(t),n=this._def.values;return Te(r,{received:r.data,code:ye.invalid_enum_value,options:n}),bt}return Gs(t.data)}get options(){return this._def.values}get enum(){let t={};for(let r of this._def.values)t[r]=r;return t}get Values(){let t={};for(let r of this._def.values)t[r]=r;return t}get Enum(){let t={};for(let r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return e.create(t,{...this._def,...r})}exclude(t,r=this._def){return e.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}};v6.create=vOe;var w6=class extends zt{_parse(t){let r=Zt.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==je.string&&n.parsedType!==je.number){let i=Zt.objectValues(r);return Te(n,{expected:Zt.joinValues(i),received:n.parsedType,code:ye.invalid_type}),bt}if(this._cache||(this._cache=new Set(Zt.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=Zt.objectValues(r);return Te(n,{received:n.data,code:ye.invalid_enum_value,options:i}),bt}return Gs(t.data)}get enum(){return this._def.values}};w6.create=(e,t)=>new w6({values:e,typeName:xt.ZodNativeEnum,...Mt(t)});var Ry=class extends zt{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==je.promise&&r.common.async===!1)return Te(r,{code:ye.invalid_type,expected:je.promise,received:r.parsedType}),bt;let n=r.parsedType===je.promise?r.data:Promise.resolve(r.data);return Gs(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Ry.create=(e,t)=>new Ry({type:e,typeName:xt.ZodPromise,...Mt(t)});var vd=class extends zt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===xt.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=this._def.effect||null,o={addIssue:s=>{Te(n,s),s.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let s=i.transform(n.data,o);if(n.common.async)return Promise.resolve(s).then(async a=>{if(r.value==="aborted")return bt;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?bt:c.status==="dirty"?u6(c.value):r.value==="dirty"?u6(c.value):c});{if(r.value==="aborted")return bt;let a=this._def.schema._parseSync({data:s,path:n.path,parent:n});return a.status==="aborted"?bt:a.status==="dirty"?u6(a.value):r.value==="dirty"?u6(a.value):a}}if(i.type==="refinement"){let s=a=>{let c=i.refinement(a,o);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?bt:(a.status==="dirty"&&r.dirty(),s(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?bt:(a.status==="dirty"&&r.dirty(),s(a.value).then(()=>({status:r.value,value:a.value}))))}if(i.type==="transform")if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Cy(s))return bt;let a=i.transform(s.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>Cy(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:r.value,value:a})):bt);Zt.assertNever(i)}};vd.create=(e,t,r)=>new vd({schema:e,typeName:xt.ZodEffects,effect:t,...Mt(r)});vd.createWithPreprocess=(e,t,r)=>new vd({schema:t,effect:{type:"preprocess",transform:e},typeName:xt.ZodEffects,...Mt(r)});var bd=class extends zt{_parse(t){return this._getType(t)===je.undefined?Gs(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};bd.create=(e,t)=>new bd({innerType:e,typeName:xt.ZodOptional,...Mt(t)});var Ef=class extends zt{_parse(t){return this._getType(t)===je.null?Gs(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Ef.create=(e,t)=>new Ef({innerType:e,typeName:xt.ZodNullable,...Mt(t)});var E6=class extends zt{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return r.parsedType===je.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};E6.create=(e,t)=>new E6({innerType:e,typeName:xt.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Mt(t)});var A6=class extends zt{_parse(t){let{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return x8(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new uc(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new uc(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};A6.create=(e,t)=>new A6({innerType:e,typeName:xt.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Mt(t)});var O8=class extends zt{_parse(t){if(this._getType(t)!==je.nan){let n=this._getOrReturnCtx(t);return Te(n,{code:ye.invalid_type,expected:je.nan,received:n.parsedType}),bt}return{status:"valid",value:t.data}}};O8.create=e=>new O8({typeName:xt.ZodNaN,...Mt(e)});var QEt=Symbol("zod_brand"),I7=class extends zt{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},P7=class e extends zt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?bt:o.status==="dirty"?(r.dirty(),u6(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?bt:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(t,r){return new e({in:t,out:r,typeName:xt.ZodPipeline})}},x6=class extends zt{_parse(t){let r=this._def.innerType._parse(t),n=i=>(Cy(i)&&(i.value=Object.freeze(i.value)),i);return x8(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};x6.create=(e,t)=>new x6({innerType:e,typeName:xt.ZodReadonly,...Mt(t)});function yOe(e,t){let r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function wOe(e,t={},r){return e?ky.create().superRefine((n,i)=>{let o=e(n);if(o instanceof Promise)return o.then(s=>{if(!s){let a=yOe(t,n),c=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:c})}});if(!o){let s=yOe(t,n),a=s.fatal??r??!0;i.addIssue({code:"custom",...s,fatal:a})}}):ky.create()}var eAt={object:dc.lazycreate},xt;(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"})(xt||(xt={}));var tAt=(e,t={message:`Input not instance of ${e.name}`})=>wOe(r=>r instanceof e,t),z=Oy.create,Or=d6.create,rAt=O8.create,nAt=l6.create,wd=p6.create,iAt=f6.create,oAt=T8.create,sAt=m6.create,k8=h6.create,Ed=ky.create,aAt=D0.create,cAt=Dl.create,uAt=I8.create,ue=L0.create,fe=dc.create,dAt=dc.strictCreate,R8=y6.create,lAt=mM.create,pAt=g6.create,fAt=wf.create,Xt=hM.create,mAt=P8.create,hAt=C8.create,yAt=yM.create,gAt=b6.create,bAt=_6.create,Ad=v6.create,_At=w6.create,vAt=Ry.create,wAt=vd.create,EAt=bd.create,AAt=Ef.create,xAt=vd.createWithPreprocess,SAt=P7.create,TAt=()=>z().optional(),IAt=()=>Or().optional(),PAt=()=>wd().optional(),hu={string:(e=>Oy.create({...e,coerce:!0})),number:(e=>d6.create({...e,coerce:!0})),boolean:(e=>p6.create({...e,coerce:!0})),bigint:(e=>l6.create({...e,coerce:!0})),date:(e=>f6.create({...e,coerce:!0}))};var CAt=bt;var kAt=Ad(["enc","sig"]),RAt=Ad(["markdown","plain"]),NAt=Ad(["recoverable","requires_buyer_input","requires_buyer_review","unrecoverable"]),BAt=Ad(["error","info","warning"]),j8=Ad(["canceled","complete_in_progress","completed","incomplete","ready_for_complete","requires_escalation"]),jAt=Ad(["completed","failed","pending"]),UAt=Ad(["digital","pickup","shipping"]),MAt=Ad(["fulfilled","partial","processing","removed"]),qAt=Ad(["across","each"]),_ne=Ad(["pickup","shipping"]),DAt=fe({config:Xt(z(),Ed()),config_schema:z(),id:z(),instrument_schemas:ue(z()),name:z(),spec:z(),version:z()}),LAt=fe({alg:z().optional(),crv:z().optional(),e:z().optional(),kid:z(),kty:z(),n:z().optional(),use:kAt.optional(),x:z().optional(),y:z().optional()}),zAt=fe({config:Xt(z(),Ed()).optional(),extends:z().optional(),name:z(),schema:z(),spec:z(),version:z()}),HAt=fe({endpoint:z()}),$At=fe({schema:z()}),EOe=fe({endpoint:z(),schema:z()}),FAt=EOe,VAt=EOe,Ta=fe({email:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional()}),fo=fe({address_country:z().optional(),address_region:z().optional(),currency:z().optional(),eligibility:ue(z()).optional(),intent:z().optional(),language:z().optional(),postal_code:z().optional()}),vne=fo,AOe=fe({id:z()}),KAt=AOe,WAt=AOe,C7=fe({address_country:z().optional(),address_locality:z().optional(),address_region:z().optional(),extended_address:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional(),postal_code:z().optional(),street_address:z().optional()}),gM=fe({type:z()}),Vi=fe({"dev.ucp.buyer_ip":z().optional(),"dev.ucp.user_agent":z().optional()}),wne=Vi,xOe=fe({id:z(),image_url:z().optional(),price:Or(),title:z()}),bM=fe({amount:Or(),display_text:z().optional(),type:z()}),Ny=fe({title:z().optional(),type:z(),url:z()}),z0=fe({code:z().optional(),content:z(),content_type:RAt.optional(),path:z().optional(),severity:NAt.optional(),type:BAt,image_url:z().optional(),presentation:z().optional(),url:z().optional()}),Ene=z0,U8=fe({id:z(),label:z().optional(),permalink_url:z()}),GAt=fe({amount:Or(),display_text:z()}),JAt=fe({config:Xt(z(),Ed()).optional(),extends:z().optional(),name:z(),schema:z().optional(),spec:z().optional(),version:z()}),Ane=fe({id:z(),quantity:Or()}),YAt=Ane,ZAt=Ane,XAt=Ane,QAt=fe({fulfilled:Or(),original:Or().optional(),total:Or()}),ext=fe({billing_address:C7.optional(),credential:gM.optional(),display:Xt(z(),Ed()).optional(),handler_id:z(),id:z(),type:z()}),txt=fe({checkout_mandate:z()}),rxt=fe({merchant_authorization:z().optional(),checkout_mandate:z()}),nxt=fe({analytics:wd().optional(),marketing:wd().optional(),preferences:wd().optional(),sale_of_data:wd().optional()});var ixt=nxt;var SOe=fe({codes:ue(z()).optional()}),oxt=SOe,sxt=fe({amount:Or(),path:z()}),axt=fe({address_country:z().optional(),address_locality:z().optional(),address_region:z().optional(),extended_address:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional(),postal_code:z().optional(),street_address:z().optional(),id:z().optional(),address:C7.optional(),name:z().optional()}),cxt=fe({carrier:z().optional(),description:z().optional(),earliest_fulfillment_time:hu.date().optional(),id:z(),latest_fulfillment_time:hu.date().optional(),title:z(),totals:ue(bM)}),uxt=fe({description:z().optional(),fulfillable_on:R8([k8(),z()]).optional(),line_item_ids:ue(z()),type:_ne}),dxt=fe({address_country:z().optional(),address_locality:z().optional(),address_region:z().optional(),extended_address:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional(),postal_code:z().optional(),street_address:z().optional(),id:z(),address:C7.optional(),name:z().optional()}),lxt=fe({max:Or().optional(),min:Or().optional()}),O7=fe({taxonomy:z().optional(),value:z()}),k7=fe({html:z().optional(),markdown:z().optional(),plain:z().optional()}),N8=fe({amount:Or(),currency:z()}),R7=fe({alt_text:z().optional(),height:Or().optional(),type:z(),url:z(),width:Or().optional()}),pxt=fe({id:z().optional(),label:z()}),N7=fe({count:Or().optional(),scale_max:Or(),scale_min:Or().optional(),value:Or()}),TOe=fe({available:wd().optional(),status:z().optional()}),fxt=TOe,IOe=fe({type:z(),value:z()}),mxt=IOe,hxt=fe({id:z(),match:z().optional()}),xne=fe({id:z().optional(),label:z(),name:z()}),POe=xne,COe=fe({links:ue(Ny).optional(),name:z().optional()}),yxt=COe,OOe=fe({unit:z(),value:Or()});var gxt=OOe,bxt=fe({cursor:z().optional(),limit:Or().optional()}),_xt=fe({cursor:z().optional(),has_next_page:wd(),total_count:Or().optional()}),vxt=fe({handlers:ue(DAt).optional()}),wxt=fe({a2a:HAt.optional(),embedded:$At.optional(),mcp:FAt.optional(),rest:VAt.optional(),spec:z(),version:z()}),M8=fe({item:KAt,quantity:Or()}),Ext=fe({billing_address:C7.optional(),credential:gM.optional(),display:Xt(z(),Ed()).optional(),handler_id:z(),id:z(),type:z(),selected:wd().optional()}),B7=fe({id:z().optional(),item:WAt,parent_id:z().optional(),quantity:Or()}),_M=fe({instruments:ue(Ext).optional()}),Axt=_M,j7=_M,q8=_M,vM=_M,S6=fe({id:z(),item:xOe,parent_id:z().optional(),quantity:Or(),totals:ue(bM)}),By=fe({amount:Or(),display_text:z().optional(),type:z(),lines:ue(GAt).optional()}),Ll=fe({capabilities:Xt(z(),ue(JAt)),version:z()}),xxt=fe({description:z().optional(),id:z(),line_items:ue(YAt).optional(),occurred_at:hu.date(),status:jAt,totals:ue(bM).optional(),type:z()}),Sxt=fe({carrier:z().optional(),description:z().optional(),id:z(),line_items:ue(ZAt),occurred_at:hu.date(),tracking_number:z().optional(),tracking_url:z().optional(),type:z()}),Txt=fe({description:z().optional(),destination:C7,fulfillable_on:z().optional(),id:z(),line_items:ue(XAt),method_type:UAt}),Ixt=fe({id:z(),item:xOe,parent_id:z().optional(),quantity:QAt,status:MAt,totals:ue(bM)}),WMr=fe({payment_data:ext}),GMr=fe({ap2:txt.optional()}),JMr=fe({attribution:Xt(z(),z()).optional(),buyer:Ta.optional(),context:fo.optional(),continue_url:z().optional(),currency:z(),expires_at:hu.date().optional(),id:z(),line_items:ue(S6),links:ue(Ny),messages:ue(z0).optional(),order:U8.optional(),payment:q8.optional(),signals:Vi.optional(),status:j8,totals:ue(By),ucp:Ll,ap2:rxt.optional()}),Sne=fe({email:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional(),consent:ixt.optional()}),Pxt=Sne,Cxt=Sne,kOe=fe({attribution:Xt(z(),z()).optional(),buyer:Ta.optional(),context:fo.optional(),line_items:ue(B7),payment:vM.optional(),signals:Vi.optional(),discounts:oxt.optional()}),Oxt=fe({allocations:ue(sxt).optional(),amount:Or(),automatic:wd().optional(),code:z().optional(),eligibility:z().optional(),method:qAt.optional(),priority:Or().optional(),provisional:wd().optional(),title:z()}),ROe=fe({id:z(),line_item_ids:ue(z()),options:ue(cxt).optional(),selected_option_id:R8([k8(),z()]).optional()}),kxt=fe({destinations:ue(dxt).optional(),groups:ue(ROe).optional(),id:z(),line_item_ids:ue(z()),selected_destination_id:R8([k8(),z()]).optional(),type:_ne}),YMr=fe({attribution:Xt(z(),z()).optional(),buyer:Ta.optional(),context:fo.optional(),line_items:ue(M8),signals:Vi.optional()}),ZMr=fe({attribution:Xt(z(),z()).optional(),buyer:Ta.optional(),context:fo.optional(),id:z(),line_items:ue(B7),signals:Vi.optional()}),XMr=fe({attribution:Xt(z(),z()).optional(),buyer:Ta.optional(),context:fo.optional(),continue_url:z().optional(),currency:z(),expires_at:hu.date().optional(),id:z(),line_items:ue(S6),links:ue(Ny).optional(),messages:ue(z0).optional(),signals:Vi.optional(),totals:ue(By),ucp:Ll}),Rxt=fe({attribution:Xt(z(),z()).optional(),buyer:Ta.optional(),context:fo.optional(),line_items:ue(B7),payment:vM.optional(),signals:Vi.optional()}),NOe=Rxt,QMr=fe({attribution:Xt(z(),z()).optional(),buyer:Ta.optional(),context:fo.optional(),continue_url:z().optional(),currency:z(),expires_at:hu.date().optional(),id:z(),line_items:ue(S6),links:ue(Ny),messages:ue(z0).optional(),order:U8.optional(),payment:q8.optional(),signals:Vi.optional(),status:j8,totals:ue(By),ucp:Ll,cart_id:z().optional()}),Tne=fe({categories:ue(z()).optional(),price:lxt.optional()}),B8=fe({max:N8,min:N8}),Ine=fe({name:z(),values:ue(pxt)}),BOe=fe({amount:Or(),currency:z(),measure:OOe,reference:gxt}),Nxt=BOe,eqr=fe({attribution:Xt(z(),z()).optional(),context:vne.optional(),filters:Tne.optional(),id:z(),preferences:ue(z()).optional(),selected:ue(POe).optional(),signals:wne.optional()}),tqr=fe({attribution:Xt(z(),z()).optional(),context:vne.optional(),filters:Tne.optional(),pagination:bxt.optional(),query:z().optional(),signals:wne.optional()}),Bxt=fe({capabilities:ue(zAt),services:Xt(z(),wxt),version:z()}),rqr=fe({attribution:Xt(z(),z()).optional(),payment:Axt,signals:Vi.optional()}),jOe=fe({attribution:Xt(z(),z()).optional(),buyer:Ta.optional(),context:fo.optional(),continue_url:z().optional(),currency:z(),expires_at:hu.date().optional(),id:z(),line_items:ue(S6),links:ue(Ny),messages:ue(z0).optional(),order:U8.optional(),payment:q8.optional(),signals:Vi.optional(),status:j8,totals:ue(By),ucp:Ll}),jxt=fe({events:ue(Sxt).optional(),expectations:ue(Txt).optional()}),UOe=fe({attribution:Xt(z(),z()).optional(),buyer:Sne.optional(),context:fo.optional(),line_items:ue(M8),payment:j7.optional(),signals:Vi.optional()}),MOe=fe({attribution:Xt(z(),z()).optional(),buyer:Cxt.optional(),context:fo.optional(),line_items:ue(B7),payment:vM.optional(),signals:Vi.optional()}),qOe=fe({attribution:Xt(z(),z()).optional(),buyer:Pxt.optional(),context:fo.optional(),continue_url:z().optional(),currency:z(),expires_at:hu.date().optional(),id:z(),line_items:ue(S6),links:ue(Ny),messages:ue(z0).optional(),order:U8.optional(),payment:q8.optional(),signals:Vi.optional(),status:j8,totals:ue(By),ucp:Ll}),DOe=fe({attribution:Xt(z(),z()).optional(),buyer:Ta.optional(),context:fo.optional(),line_items:ue(M8),payment:j7.optional(),signals:Vi.optional(),discounts:SOe.optional()}),Uxt=fe({applied:ue(Oxt).optional(),codes:ue(z()).optional()}),Mxt=fe({destinations:ue(axt).optional(),groups:ue(ROe).optional(),line_item_ids:ue(z()).optional(),selected_destination_id:R8([k8(),z()]).optional(),type:_ne}),qxt=fe({available_methods:ue(uxt).optional(),methods:ue(kxt).optional()}),LOe=fe({attribution:Xt(z(),z()).optional(),buyer:Ta.optional(),context:fo.optional(),line_items:ue(M8),payment:j7.optional(),signals:Vi.optional(),cart_id:z().optional()}),nqr=fe({attribution:Xt(z(),z()).optional(),context:vne.optional(),filters:Tne.optional(),ids:ue(z()),signals:wne.optional()}),Dxt=fe({availability:TOe.optional(),barcodes:ue(IOe).optional(),categories:ue(O7).optional(),description:k7,handle:z().optional(),id:z(),list_price:N8.optional(),media:ue(R7).optional(),metadata:Xt(z(),Ed()).optional(),options:ue(xne).optional(),price:N8,rating:N7.optional(),seller:COe.optional(),sku:z().optional(),tags:ue(z()).optional(),title:z(),unit_price:BOe.optional(),url:z().optional(),inputs:ue(hxt)}),zOe=fe({availability:fxt.optional(),barcodes:ue(mxt).optional(),categories:ue(O7).optional(),description:k7,handle:z().optional(),id:z(),list_price:N8.optional(),media:ue(R7).optional(),metadata:Xt(z(),Ed()).optional(),options:ue(xne).optional(),price:N8,rating:N7.optional(),seller:yxt.optional(),sku:z().optional(),tags:ue(z()).optional(),title:z(),unit_price:Nxt.optional(),url:z().optional()}),Lxt=fe({categories:ue(O7).optional(),description:k7,handle:z().optional(),id:z(),list_price_range:B8.optional(),media:ue(R7).optional(),metadata:Xt(z(),Ed()).optional(),options:ue(Ine).optional(),price_range:B8,rating:N7.optional(),tags:ue(z()).optional(),title:z(),url:z().optional(),variants:ue(zOe)}),iqr=fe({payment:vxt.optional(),signing_keys:ue(LAt).optional(),ucp:Bxt}),HOe=fe({attribution:Xt(z(),z()).optional(),buyer:Ta.optional(),context:fo.optional(),line_items:ue(M8),payment:j7.optional(),signals:Vi.optional()}),zxt=fe({adjustments:ue(xxt).optional(),attribution:Xt(z(),z()).optional(),checkout_id:z(),currency:z(),fulfillment:jxt,id:z(),label:z().optional(),line_items:ue(Ixt),messages:ue(z0).optional(),permalink_url:z(),totals:ue(By),ucp:Ll}),$Oe=fe({attribution:Xt(z(),z()).optional(),buyer:Ta.optional(),context:fo.optional(),continue_url:z().optional(),currency:z(),expires_at:hu.date().optional(),id:z(),line_items:ue(S6),links:ue(Ny),messages:ue(z0).optional(),order:U8.optional(),payment:q8.optional(),signals:Vi.optional(),status:j8,totals:ue(By),ucp:Ll,discounts:Uxt.optional()}),FOe=fe({methods:ue(Mxt).optional()}),VOe=fe({attribution:Xt(z(),z()).optional(),buyer:Ta.optional(),context:fo.optional(),line_items:ue(B7),payment:vM.optional(),signals:Vi.optional(),fulfillment:FOe.optional()}),KOe=fe({attribution:Xt(z(),z()).optional(),buyer:Ta.optional(),context:fo.optional(),continue_url:z().optional(),currency:z(),expires_at:hu.date().optional(),id:z(),line_items:ue(S6),links:ue(Ny),messages:ue(z0).optional(),order:U8.optional(),payment:q8.optional(),signals:Vi.optional(),status:j8,totals:ue(By),ucp:Ll,fulfillment:qxt.optional()}),Hxt=fe({categories:ue(O7).optional(),description:k7,handle:z().optional(),id:z(),list_price_range:B8.optional(),media:ue(R7).optional(),metadata:Xt(z(),Ed()).optional(),options:ue(Ine).optional(),price_range:B8,rating:N7.optional(),tags:ue(z()).optional(),title:z(),url:z().optional(),variants:ue(Dxt)}),$xt=fe({options:ue(Ine).optional(),selected:ue(POe).optional(),categories:ue(O7).optional(),description:k7,handle:z().optional(),id:z(),list_price_range:B8.optional(),media:ue(R7).optional(),metadata:Xt(z(),Ed()).optional(),price_range:B8,rating:N7.optional(),tags:ue(z()).optional(),title:z(),url:z().optional(),variants:ue(zOe)}),oqr=fe({messages:ue(Ene).optional(),pagination:_xt.optional(),products:ue(Lxt),ucp:Ll}),WOe=fe({attribution:Xt(z(),z()).optional(),buyer:Ta.optional(),context:fo.optional(),line_items:ue(M8),payment:j7.optional(),signals:Vi.optional(),fulfillment:FOe.optional()}),sqr=fe({messages:ue(Ene).optional(),products:ue(Hxt),ucp:Ll}),aqr=fe({messages:ue(Ene).optional(),product:$xt,ucp:Ll});var lqr=gM.extend({token:Lr.string().optional()}),Fxt=Lr.object({webhook_url:Lr.string().url().optional()}),GOe=jOe.extend(KOe.pick({fulfillment:!0}).shape).extend($Oe.pick({discounts:!0}).shape).extend(qOe.pick({buyer:!0}).shape).extend({platform:Fxt.optional()}),JOe=HOe.extend(WOe.pick({fulfillment:!0}).shape).extend(DOe.pick({discounts:!0}).shape).extend(UOe.pick({buyer:!0}).shape).extend(LOe.pick({cart_id:!0}).shape),YOe=NOe.extend(VOe.pick({fulfillment:!0}).shape).extend(kOe.pick({discounts:!0}).shape).extend(MOe.pick({buyer:!0}).shape);pd();async function wM(e,t,r){let n=e.headers.get("content-length");if(n!==null){let c=Number(n);if(Number.isSafeInteger(c)&&c>t)throw new Error(r)}if(!e.body)return"";let i=e.body.getReader(),o=new TextDecoder,s=0,a="";try{for(;;){let{done:c,value:u}=await i.read();if(c)break;if(s+=u.byteLength,s>t){try{await i.cancel()}catch{}throw new Error(r)}a+=o.decode(u,{stream:!0})}return a+o.decode()}finally{i.releaseLock()}}function EM(e,t){let r=new AbortController,n=()=>r.abort(t?.reason);t?.aborted?n():t?.addEventListener("abort",n,{once:!0});let i=setTimeout(()=>r.abort(),e);return{signal:r.signal,cleanup:()=>{clearTimeout(i),t?.removeEventListener("abort",n)}}}var Vxt=3e4,ZOe=2*1024*1024,zl=class extends Error{constructor(r,n,i){super(r);this.rpcCode=n;this.httpStatus=i;this.name="UcpRpcError"}rpcCode;httpStatus};function XOe(e,t){let r=new URL(e);if(r.protocol!=="https:")throw new Error(`${t} must use HTTPS`);if(r.username||r.password)throw new Error(`${t} must not contain embedded credentials`);if(r.hash)throw new Error(`${t} must not contain a fragment`);return r}function QOe(e,t){if(!/^[A-Z]{3}$/.test(String(e.currency??"")))throw new Error("UCP checkout input requires an uppercase ISO 4217 currency");if(!Array.isArray(e.line_items)||e.line_items.length===0)throw new Error("UCP checkout input requires at least one line item");if(Object.hasOwn(e,"id"))throw new Error("UCP checkout input must not contain an id; pass it as a top-level argument");if(!(t==="create"?JOe:YOe).safeParse(e).success)throw new Error(`UCP ${t} checkout input failed schema validation`);return e}function Kxt(e){if(!e||typeof e!="object")return!1;let t=e;if(t.jsonrpc!=="2.0"||!Object.hasOwn(t,"id")||t.id!==null&&typeof t.id!="string"&&typeof t.id!="number")return!1;let r=Object.hasOwn(t,"result"),n=Object.hasOwn(t,"error");if(r===n)return!1;if(!n)return!0;let i=t.error;return!!i&&typeof i=="object"&&!Array.isArray(i)&&typeof i.code=="number"&&typeof i.message=="string"}function eke(e,t,r,n){try{e[t](r,n)}catch{}}function Wxt(e){if(!e||typeof e!="object")return e;let t=e,r=t.ucp;if(!r||typeof r!="object")return e;let n=r.capabilities;return!n||typeof n!="object"||Array.isArray(n)?e:{...t,ucp:{...r,capabilities:Object.fromEntries(Object.entries(n).map(([i,o])=>[i,Array.isArray(o)?o.map(s=>s&&typeof s=="object"?{...s,name:i}:s):o]))}}}var AM=class{endpoint;platformProfileUrl;fetchImpl;signal;timeoutMs;boundaryLogger;requestId=1;constructor(t){this.endpoint=XOe(t.endpoint,"UCP MCP endpoint").toString(),this.platformProfileUrl=XOe(t.platformProfileUrl,"UCP platform profile URL").toString(),this.fetchImpl=t.fetch??fetch,this.signal=t.signal,this.timeoutMs=t.timeoutMs??Vxt,this.boundaryLogger=t.logger??Ce}async createCheckout(t){return await this.callCheckout("create_checkout",{meta:this.metadata(),checkout:QOe(t,"create")})}async getCheckout(t){if(!t)throw new Error("UCP checkout id is required");return await this.callCheckout("get_checkout",{meta:this.metadata(),id:t})}async updateCheckout(t,r){if(!t)throw new Error("UCP checkout id is required");return await this.callCheckout("update_checkout",{meta:this.metadata(),id:t,checkout:QOe(r,"update")})}metadata(){return{"ucp-agent":{profile:this.platformProfileUrl}}}async callCheckout(t,r){let n=this.requestId++,i=EM(this.timeoutMs,this.signal),o=(0,tke.randomUUID)(),s=new URL(this.endpoint).origin,a=Date.now(),c;try{let u=await this.fetchImpl(this.endpoint,{method:"POST",redirect:"error",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:n,method:"tools/call",params:{name:t,arguments:r}}),signal:i.signal});c=u.status;let d;try{d=await wM(u,ZOe,"UCP MCP response exceeds the 2 MiB limit")}catch(m){throw m instanceof Error&&m.message==="UCP MCP response exceeds the 2 MiB limit"?new zl(m.message,void 0,u.status):m}if(Buffer.byteLength(d)>ZOe)throw new zl("UCP MCP response exceeds the 2 MiB limit",void 0,u.status);let l;try{l=JSON.parse(d)}catch{throw new zl("UCP MCP response is not valid JSON",void 0,u.status)}if(!Kxt(l))throw new zl("UCP MCP response is not a valid JSON-RPC envelope",void 0,u.status);if(l.id!==n)throw new zl("UCP MCP response id does not match the request",void 0,u.status);if("error"in l)throw new zl(`UCP MCP error ${l.error.code}: ${l.error.message}`,l.error.code,u.status);if(!u.ok)throw new zl(`UCP MCP request failed with HTTP ${u.status}`,void 0,u.status);let p=l.result;if(!p?.structuredContent)throw new zl("UCP MCP response is missing result.structuredContent");if(!GOe.safeParse(Wxt(p.structuredContent)).success)throw new zl("UCP checkout response failed schema validation");return eke(this.boundaryLogger,"info","ucp:checkout_rpc",{correlationId:o,endpointOrigin:s,rpcMethod:t,httpStatus:c,elapsedMs:Date.now()-a}),p.structuredContent}catch(u){throw eke(this.boundaryLogger,"warn","ucp:checkout_rpc_failed",{correlationId:o,endpointOrigin:s,rpcMethod:t,...c===void 0?{}:{httpStatus:c},elapsedMs:Date.now()-a,errorClass:u instanceof Error?u.name:"UnknownError"}),u}finally{i.cleanup()}}};var nke=require("node:crypto");pd();var SM="2026-04-08",Gxt="dev.ucp.shopping",Jxt="dev.ucp.shopping.checkout",Yxt=1024*1024,Zxt=1e4,Xxt="https://ucp.dev",U7=Lr.string().url().refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password},"must be an HTTPS URL without embedded credentials"),Qxt=Lr.object({version:Lr.string().regex(/^\d{4}-\d{2}-\d{2}$/),spec:U7,schema:U7,transport:Lr.enum(["rest","mcp","a2a","embedded"]),endpoint:U7.optional()}).passthrough(),e9t=Lr.object({version:Lr.string().regex(/^\d{4}-\d{2}-\d{2}$/),spec:U7,schema:U7,extends:Lr.union([Lr.string(),Lr.array(Lr.string()).min(1)]).optional()}).passthrough(),t9t=Lr.object({ucp:Lr.object({version:Lr.string().regex(/^\d{4}-\d{2}-\d{2}$/),services:Lr.record(Lr.array(Qxt)),capabilities:Lr.record(Lr.array(e9t)),payment_handlers:Lr.record(Lr.array(Lr.unknown())).optional()}).passthrough(),signing_keys:Lr.array(Lr.unknown()).optional()}).passthrough();function r9t(e,t){let r=new URL(e);if(r.protocol!=="https:")throw new Error(`${t} must use HTTPS`);if(r.username||r.password)throw new Error(`${t} must not contain embedded credentials`);if(r.pathname!=="/"||r.search||r.hash)throw new Error(`${t} must be a bare origin`);return r}function xM(e,t){if(new URL(e).origin!==Xxt)throw new Error(`${t} must be governed by the ucp.dev namespace`)}function rke(e,t,r,n){try{e[t](r,n)}catch{}}async function n9t(e,t={}){let r=r9t(e,"UCP business URL"),n=EM(t.timeoutMs??Zxt,t.signal),i=t.logger??Ce,o=(0,nke.randomUUID)(),s=Date.now(),a;try{let c=await(t.fetch??fetch)(new URL("/.well-known/ucp",r),{headers:{accept:"application/json"},redirect:"error",signal:n.signal});if(a=c.status,!c.ok)throw new Error(`UCP profile fetch failed with HTTP ${c.status}`);let u=await wM(c,Yxt,"UCP profile exceeds the 1 MiB response limit"),d;try{d=JSON.parse(u)}catch{throw new Error("UCP profile response is not valid JSON")}let l=t9t.safeParse(d);if(!l.success)throw new Error("UCP profile response does not match the 2026-04-08 profile shape");return rke(i,"info","ucp:profile_fetch",{correlationId:o,businessOrigin:r.origin,method:"GET",httpStatus:a,elapsedMs:Date.now()-s}),{businessOrigin:r.origin,profile:l.data}}catch(c){throw rke(i,"warn","ucp:profile_fetch_failed",{correlationId:o,businessOrigin:r.origin,method:"GET",...a===void 0?{}:{httpStatus:a},elapsedMs:Date.now()-s,errorClass:c instanceof Error?c.name:"UnknownError"}),c}finally{n.cleanup()}}function i9t(e){if(e.ucp.version!==SM)throw new Error(`Unsupported UCP version: ${e.ucp.version}`);let t=e.ucp.capabilities[Jxt]?.find(i=>i.version===SM);if(!t)throw new Error("Business does not advertise UCP checkout 2026-04-08");xM(t.spec,"Checkout capability spec"),xM(t.schema,"Checkout capability schema");let r=e.ucp.services[Gxt]?.find(i=>i.version===SM&&i.transport==="mcp");if(!r)throw new Error("Business does not advertise a UCP shopping MCP service");if(!r.endpoint)throw new Error("UCP shopping MCP service is missing its endpoint");xM(r.spec,"Shopping service spec"),xM(r.schema,"Shopping service schema");let n=new URL(r.endpoint);if(n.hash)throw new Error("UCP shopping MCP endpoint must not contain a fragment");return n.toString()}async function ike(e,t={}){let r=await n9t(e,t);return{...r,endpoint:i9t(r.profile),version:SM}}var o9t="https://app.visacli.sh/.well-known/ucp";function s9t(e){let t=new URL(e);if(t.protocol!=="https:"||t.username||t.password||t.hash)throw new Error("UCP platform profile URL must be HTTPS and credential-free");return t.toString()}function a9t(e,t){if(typeof e=="string")try{let r=new URL(e);r.protocol==="https:"&&!r.username&&!r.password&&t.add(r.origin.toLowerCase())}catch{}}function Pne(e,t=new Set){if(Array.isArray(e))for(let r of e)Pne(r,t);else if(e&&typeof e=="object")for(let[r,n]of Object.entries(e))r==="endpoint"?a9t(n,t):Pne(n,t);return t}function c9t(e,t,r){let n=new URL(e),i=new URL(t);if(i.protocol!=="https:"||i.username||i.password)throw new Error("UCP continuation URL must be HTTPS and credential-free");let o=i.hostname.toLowerCase(),s=n.hostname.toLowerCase();if(i.origin.toLowerCase()===n.origin.toLowerCase())return i.hash="",{url:i.toString(),sourceHost:o,targetHost:s,originRewritten:!1};let a=r.ucp.services["dev.ucp.shopping"],c=Pne(a);if(!(o.endsWith(".myshopify.com")&&c.has(i.origin.toLowerCase())))throw new Error(`Refusing cross-host UCP continuation from ${o} to ${s}`);return i.hash="",{url:i.toString(),sourceHost:o,targetHost:o,originRewritten:!1}}function ske(e){let t=Array.isArray(e.totals)?e.totals.find(a=>a&&typeof a=="object"&&a.type==="total"):void 0,r=t&&typeof t=="object"?t:void 0,n=r?.amount,o=r?.currency??e.currency;if(!Number.isSafeInteger(n)||Number(n)<0)throw new Error("UCP checkout is missing an integer totals[type=total].amount");if(o!=="USD")throw new Error(`UCP checkout handoff currently supports USD only; refusing ${String(o)} until currency exponents are implemented`);let s=Number(n);return{minor:s,decimal:`${Math.floor(s/100)}.${String(s%100).padStart(2,"0")}`,currency:o}}function u9t(e){return Array.isArray(e.messages)?e.messages.flatMap(t=>{if(!t||typeof t!="object")return[];let r=t,n={...typeof r.type=="string"?{type:r.type}:{},...typeof r.code=="string"?{code:r.code}:{},...typeof r.severity=="string"?{severity:r.severity}:{}};return Object.keys(n).length>0?[n]:[]}):[]}async function ake(e,t){if(!e.business?.trim())throw new Error("UCP business origin is required");if(!e.checkoutId?.trim())throw new Error("UCP checkout id is required");let r=await(t.discover??ike)(e.business),i=await(t.getCheckout??(async(o,s)=>await new AM({endpoint:o.endpoint,platformProfileUrl:s9t(t.platformProfileUrl??process.env.VISA_UCP_PROFILE_URL??o9t)}).getCheckout(s)))(r,e.checkoutId);if(i.id!==e.checkoutId)throw new Error("UCP checkout response id does not match the requested checkout");return{service:r,checkout:i}}async function cke(e,t={}){let{service:r,checkout:n}=await ake(e,t),i=String(n.status??"unknown");if(i==="completed")return{success:!1,status:"not_ready",checkoutId:e.checkoutId,checkoutStatus:i,reason:"checkout_already_completed"};if(i!=="requires_escalation")return{success:!1,status:"not_ready",checkoutId:e.checkoutId,checkoutStatus:i,reason:"checkout_not_escalated"};if(typeof n.continue_url!="string"||!n.continue_url)return{success:!1,status:"not_ready",checkoutId:e.checkoutId,checkoutStatus:i,reason:"missing_continue_url"};let o=ske(n),s=c9t(r.businessOrigin,n.continue_url,r.profile),a=`ucp_${(0,oke.createHash)("sha256").update([r.businessOrigin,e.checkoutId,i,o.currency,String(o.minor),s.url].join("\0")).digest("hex").slice(0,24)}`;return{success:!0,status:"ready_for_review",checkoutId:e.checkoutId,handoffId:a,checkoutStatus:"requires_escalation",amount:o,merchant:{businessOrigin:r.businessOrigin,sourceHost:s.sourceHost,targetHost:s.targetHost,originRewritten:s.originRewritten},payMerchantRequest:{action:"review",url:s.url,amount:o.decimal,currency:o.currency},messages:u9t(n),nextAction:"Copy the payMerchantRequest checkout fields unchanged to pay_merchant and include its required user_context. Show the returned merchant and exact total to the user; never authorize until they explicitly approve PAY <reviewId>."}}function d9t(e){if(!e.order||typeof e.order!="object"||Array.isArray(e.order))return null;let t=e.order;if(typeof t.id!="string"||!t.id.trim()||typeof t.permalink_url!="string"||!t.permalink_url)return null;let r;try{r=new URL(t.permalink_url)}catch{return null}return r.protocol!=="https:"||r.username||r.password||r.hash?null:{id:t.id,permalinkHost:r.hostname.toLowerCase()}}async function uke(e,t={}){if(!Number.isSafeInteger(e.expectedAmountMinor)||e.expectedAmountMinor<0)throw new Error("UCP reconciliation expectedAmountMinor must be a non-negative integer");if(e.expectedCurrency!=="USD")throw new Error("UCP reconciliation currently supports expectedCurrency USD only");let{checkout:r}=await ake(e,t),n=ske(r),i=String(r.status??"unknown");if(n.minor!==e.expectedAmountMinor)return{success:!1,status:"not_confirmed",checkoutId:e.checkoutId,checkoutStatus:i,reason:"amount_mismatch",amount:n,nextAction:"Do not retry payment. The merchant checkout total no longer matches the reviewed amount; reconcile the merchant order manually."};if(i!=="completed")return{success:!1,status:"not_confirmed",checkoutId:e.checkoutId,checkoutStatus:i,reason:"checkout_not_completed",amount:n,nextAction:"Do not retry payment. Poll this same checkout or inspect the merchant order before starting any new review."};let o=d9t(r);return o?{success:!0,status:"confirmed",checkoutId:e.checkoutId,checkoutStatus:"completed",amount:n,order:o,nextAction:"Report success only after matching this UCP order id and amount to the Visa checkout receipt."}:{success:!1,status:"not_confirmed",checkoutId:e.checkoutId,checkoutStatus:i,reason:"missing_order_confirmation",amount:n,nextAction:"Do not report purchase success or retry payment. The checkout says completed but lacks a valid merchant order confirmation."}}ay();function Cne(){return Sa()}var gd=new fd(()=>An.getSessionToken()),l9t="4.1.0-rc.50",Vqr=["","","You're ready to go! Try:","","Verified Agent:",'\u2022 "Enroll this agent" \u2192 enroll_agent','\u2022 "Show my wallet and policy" \u2192 wallet_status','\u2022 "Find a paid weather service" \u2192 wallet_discover','\u2022 "Pay this x402 service with a $0.10 maximum" \u2192 wallet_pay','\u2022 "Review this card checkout" \u2192 pay_merchant','\u2022 "Show my account status" \u2192 get_status'].join(`
|
|
20933
|
+
If building from source, run native/build-win.bat first.`);tn.mkdirSync(uy,{recursive:!0}),tn.copyFileSync(e,A0);let t=Hj(A0);return tn.writeFileSync(xTe,t,{mode:384}),tn.writeFileSync(ATe,ETe,{mode:384}),A0}async function Qvt(){return J4()?Vj():NTe()}var $j="visa-cli",Fj="attestation-key";async function e5t(e){if(!await sf())throw new Error("macOS Keychain is unavailable in this environment (no default keychain), so the Touch ID key cannot be stored. Run this command in a regular user session.");try{await x0("security",["delete-generic-password","-s",$j,"-a",Fj],{timeout:5e3})}catch{}try{await x0("security",["add-generic-password","-s",$j,"-a",Fj,"-w",e],{timeout:5e3})}catch(t){throw new Error(`Could not store the Touch ID key in the macOS Keychain (${t5t(t)}).`)}}function t5t(e){let t=e,r=[t?.stderr,t?.message].filter(n=>typeof n=="string").join(" ").toLowerCase();return/canceled|cancelled/.test(r)?"the Keychain authorization was canceled":/locked/.test(r)?"the Keychain is locked":/not permitted|permission denied|not authorized/.test(r)?"Keychain access was denied":/could not be found|no default keychain/.test(r)?"no default keychain was found":"the security tool reported an error"}function r5t(e){let t=typeof e?.code=="number"?e.code:void 0,r=typeof e?.stderr=="string"?e.stderr:"",n=typeof e?.stdout=="string"?e.stdout:"",i=[r,n,e?.message].filter(Boolean).join(" ").trim();return t===44||/could not be found|item(?: was)? not found|no such keychain item|not found/i.test(i)?{state:"absent",usable:!1,message:"No local attestation key was found."}:/user interaction is not allowed|user canceled|user cancelled|authorization failed|interaction not allowed|keychain.*locked|denied|not authorized/i.test(i)?{state:"denied",usable:!1,message:"The local attestation key exists but Keychain access was denied or unavailable."}:{state:"error",usable:!1,message:i||"Could not read the local attestation key from Keychain."}}async function n5t(){if(!await sf())return{key:null,status:{state:"denied",usable:!1,message:"macOS Keychain is unavailable in this environment (no default keychain)."}};try{let{stdout:e}=await x0("security",["find-generic-password","-s",$j,"-a",Fj,"-w"],{timeout:5e3}),t=e.trim();return t?{key:t,status:{state:"present",usable:!0}}:{key:null,status:{state:"absent",usable:!1,message:"No local attestation key was found."}}}catch(e){return{key:null,status:r5t(e)}}}async function i5t(){let e=await n5t();if(e.key)return e.key;if(e.status.state==="absent")return null;throw new Error(e.status.message||"Could not read the local attestation key from Keychain.")}async function jTe(e){let t=await Qvt(),r;try{r=(await x0(t,e,{timeout:6e4})).stdout}catch(n){r=n.stdout||"";let i=r.trim();throw i.startsWith("ERROR:")?new Error(i.slice(6)):new Error(n.stderr?.toString().trim()||n.message||"Unknown error")}return Xvt(r)}var ITe=!1;function o5t(){if(!J4())return!1;try{return tn.existsSync(A0)||BTe()!==null?!0:(ITe||(ITe=!0,Ce.warn("binary:missing:win32",{message:"visa-keychain-win.exe not found; Windows Hello attestation unavailable on this install.",binPath:A0,searchedPrebuiltPaths:RTe})),!1)}catch{return!1}}function S0(){return IT()||Zvt()?!0:J4()?o5t():!1}async function UTe(){if(J4()){let i=await Vj(),{stdout:o}=await x0(i,["generate-key"],{timeout:3e4}),s=o.trim();if(s.startsWith("OK:"))return s.slice(3);throw new Error(s.startsWith("ERROR:")?s.slice(6):"Key generation failed")}let e=await jTe(["generate-key"]);if(!e)throw new Error("Key generation returned no output");let t=e.indexOf(":");if(t<0)throw new Error("Unexpected generate-key output format");let r=e.slice(0,t),n=e.slice(t+1);return await e5t(r),n}async function Jee(e,t,r={}){if(IT())return Promise.resolve(Z9e());let n=r.timeoutMs??Yvt;if(J4()){let a=await Vj(),c=["sign",e];t&&c.push(t);let u;try{u=(await x0(a,c,{timeout:n})).stdout}catch(l){throw STe(l)?TTe(n):l}let d=u.trim();if(d.startsWith("OK:"))return d.slice(3);throw new Error(d.startsWith("ERROR:")?d.slice(6):"Unknown error")}let i=await i5t();if(!i)throw new Error("Attestation key not found. Run setup to generate a new key.");let o=await NTe(),s=["sign",e];return t&&s.push(t),new Promise((a,c)=>{let u=(0,Gee.execFile)(o,s,{timeout:n},(d,l)=>{let p=(l||"").trim();if(d){p.startsWith("ERROR:")?c(new Error(p.slice(6))):STe(d)?c(TTe(n)):c(new Error(d.stderr?.toString().trim()||d.message||"Unknown error"));return}p.startsWith("OK:")?a(p.slice(3)):c(new Error(p.startsWith("ERROR:")?p.slice(6):"Unknown error"))});u.stdin.write(i),u.stdin.end()})}async function Kj(){if(J4()){try{let e=await Vj();await x0(e,["delete-key"],{timeout:1e4})}catch{}return}if(await sf())try{await x0("security",["delete-generic-password","-s",$j,"-a",Fj],{timeout:5e3})}catch{}try{await jTe(["delete-key"])}catch{}}w0();pd();_j();RU();r6();var lke=require("child_process"),TM=_e(require("fs")),IM=_e(require("os")),pke=_e(require("path"));MT();ay();dj();var HCe="4.1.0-rc.51";function ane(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function uEt(e,t,r){let n=process.env[e];if(n!==void 0)return{value:r==="opt-in"?n==="true":n!=="false",source:{kind:"env",var:e}};let i=Fee(t);return i!==void 0?{value:i,source:{kind:"settings"}}:{value:r!=="opt-in",source:{kind:"default"}}}function w8(e){return e==null?"\u2014":e?"yes":"no"}async function _7(e){let t=null,r=null;try{t=await e.api.getStatus()}catch(l){r=l?.message||"unknown error"}let n=[],i=process.env.VISA_AUTH_URL,o=$ee("auth.serverUrl"),s=Sa(),a=i!==void 0&&i!==""?{kind:"env",var:"VISA_AUTH_URL"}:o!==void 0?{kind:"settings"}:{kind:"default"};n.push({key:"auth.serverUrl",value:s,formatted:s,source:a,hint:a.kind==="default"?"Persist with `visa-cli config set auth.serverUrl <url>` (or set VISA_AUTH_URL for one-off overrides).":void 0}),n.push({key:"account.enrolled",value:t?.enrolled??null,formatted:w8(t?.enrolled),source:t?{kind:"server"}:{kind:"unknown",reason:r||"offline"}}),t?.login&&n.push({key:"account.principal",value:t.login,formatted:t.principalKind?`${t.login} (${t.principalKind})`:t.login,source:{kind:"server"},hint:"The identity your CLI session resolves on. Feature-flag access (checkout, mandate) is granted per this exact principal."}),t?.userId&&n.push({key:"account.userId",value:t.userId,formatted:t.userId,source:{kind:"server"},hint:"Opaque stable account id used for account-scoped local credentials."});let c=uEt("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");n.push({key:"ui.suppressBrowser",value:c.value,formatted:w8(c.value),source:c.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let u=oy(),d;if(process.env.VISA_CLI_NO_UPDATE_CHECK?d={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?d={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?d={kind:"env",var:"NODE_ENV"}:d={kind:"default"},n.push({key:"ui.updateCheck",value:!u,formatted:w8(!u),source:d}),n.push({key:"client.version",value:HCe,formatted:HCe,source:{kind:"default"}}),e.includeDev){let l=process.env.VISA_MOCK_KEYCHAIN,p=ty();n.push({key:"dev.mockKeychain",value:p,formatted:w8(p),source:ane("VISA_MOCK_KEYCHAIN",!!l),hint:mee()});let f=process.env.VISA_MOCK_TOUCHID,m=IT();n.push({key:"dev.mockTouchid",value:m,formatted:w8(m),source:ane("VISA_MOCK_TOUCHID",!!f),hint:mee()});let h=process.env.VISA_CLI_DEBUG;n.push({key:"dev.debug",value:!!h,formatted:w8(!!h),source:ane("VISA_CLI_DEBUG",!!h)})}return{entries:n,statusError:r}}function dEt(e){switch(e.kind){case"default":return"default";case"env":return`env ${e.var}`;case"settings":return"settings.json";case"server":return"server";case"device":return"device";case"unset":return"unset";case"unknown":return`unknown (${e.reason})`}}function $Ce(e,t={}){if(e.length===0)return"";let r=Math.max(...e.map(o=>o.key.length)),n=Math.max(...e.map(o=>o.formatted.length)),i=[];for(let o of e){let s=o.key.padEnd(r+2),a=o.formatted.padEnd(n+2);i.push(`${s}${a}(${dEt(o.source)})`),t.verbose&&o.hint&&i.push(` ${"\u21B3".padStart(r)} ${o.hint}`)}return i.join(`
|
|
20934
|
+
`)}function FCe(e){return JSON.stringify({config:e.entries.map(t=>({key:t.key,value:t.value,source:t.source,hint:t.hint})),statusError:e.statusError},null,2)}var mne=require("node:os"),A7=require("node:path"),x7=require("node:fs/promises"),tOe=require("node:fs"),rOe=require("node:url"),nOe=require("node:crypto");pd();var lEt=new Set(["USD","USDC","EUR","GBP","CAD","AUD"]);function E8(e,t){let r=t.toUpperCase();return!Number.isFinite(e)||!lEt.has(r)?`${e} ${r} (minor units)`:`${(e/100).toFixed(2)} ${r}`}var U0=class extends Error{constructor(t){super(t),this.name="PayValidationError"}};function VCe(e){let t;try{t=new URL(e)}catch{throw new U0(`Invalid URL: ${e}. Expected a fully-qualified http(s) URL.`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new U0(`Unsupported URL scheme "${t.protocol}". Only http and https are allowed.`);return t}pd();var pEt={ucp_checkout_handoff:"checkout_agent_access",ucp_checkout_reconcile:"checkout_agent_access",pay_merchant:"checkout_agent_access",pay_merchant_status:"checkout_agent_access",start_card_mandate:"checkout_agent_access"},fEt=300*1e3,cne={},KCe=0,v7=null;function mEt(){return v7||(v7=(async()=>{try{let e=await gd.getFeatureFlags();cne=e&&e.flags||{},KCe=Date.now()}catch(e){cne={},Ce.warn("feature-flags:fetch-failed",{error:e instanceof Error?e.message:String(e)})}finally{v7=null}})(),v7)}async function w7(){Date.now()-KCe<fEt||await mEt()}function Py(e){let t=pEt[e];return t?cne[t]!==!0:!1}var WCe=require("node:crypto"),E7=class extends Error{constructor(r){super(`Approval handoff already exists with different inputs for review ${r}`);this.reviewId=r;this.name="PayMerchantApprovalConflictError"}reviewId},cM=class{constructor(t={}){this.options=t}options;jobsByOperation=new Map;operationByReview=new Map;now(){return(this.options.now??Date.now)()}activeTtlMs(){return this.options.activeTtlMs??300*1e3}terminalTtlMs(){return this.options.terminalTtlMs??300*1e3}async waitUntilQueryable(t){let r;try{await Promise.race([t,new Promise(n=>{r=setTimeout(n,Math.max(0,this.options.initialWaitMs??1e3)),r.unref?.()})])}finally{r&&clearTimeout(r)}}finish(t,r){t.inFlight=!1,t.status=r,t.expiresAtMs=this.now()+this.terminalTtlMs(),t.resolveReady()}pruneExpired(){let t=this.now();for(let[r,n]of this.jobsByOperation)if(!(n.expiresAtMs>t)){if(n.inFlight){(n.status==="starting"||n.status==="awaiting_passkey")&&(n.status="reconciling",n.error="Approval handoff expired while the checkout was in progress; reconcile with the merchant before retrying",n.resolveReady()),n.expiresAtMs=t+this.terminalTtlMs();continue}this.jobsByOperation.delete(r),this.operationByReview.get(n.reviewId)===r&&this.operationByReview.delete(n.reviewId)}}snapshot(t){return{operationId:t.operationId,reviewId:t.reviewId,status:t.status,approvalUrl:t.approvalUrl,result:t.result,error:t.error,expiresAt:new Date(t.expiresAtMs).toISOString()}}get(t){this.pruneExpired();let r=this.jobsByOperation.get(t);return r?this.snapshot(r):null}async start(t){this.pruneExpired();let r=this.operationByReview.get(t.reviewId),n=r?this.jobsByOperation.get(r):void 0;if(n){if(n.fingerprint!==t.fingerprint)throw new E7(t.reviewId);return await this.waitUntilQueryable(n.ready),this.snapshot(n)}let i=()=>{},o=new Promise(u=>{i=u}),s=(this.options.idFactory??WCe.randomUUID)(),a={operationId:s,reviewId:t.reviewId,fingerprint:t.fingerprint,status:"starting",approvalUrl:null,result:null,error:null,expiresAtMs:this.now()+this.activeTtlMs(),inFlight:!0,ready:o,resolveReady:i};this.jobsByOperation.set(s,a),this.operationByReview.set(t.reviewId,s);let c=u=>{a.status==="starting"&&(a.approvalUrl=u,a.status="awaiting_passkey",a.resolveReady())};return Promise.resolve().then(()=>t.run(c)).then(u=>{a.result=u,a.error=null,this.finish(a,"completed")}).catch(u=>{a.error=u instanceof Error?u.message:String(u),this.finish(a,"failed")}),await this.waitUntilQueryable(o),this.snapshot(a)}};function iOe(e){return[(0,A7.join)(e,"checkout-engine","index.js"),(0,A7.join)(e,"..","checkout-engine","index.js")]}function xEt(e,t=tOe.existsSync){return iOe(e).find(r=>t(r))??null}var dM=null,oOe=async()=>{if(dM)return dM;let e=xEt(__dirname);if(!e)throw new Error(`Cannot find module: the checkout engine was not packaged (looked in ${iOe(__dirname).join(" and ")}).`);return dM=(await import((0,rOe.pathToFileURL)(e).href)).createCliCheckoutEngine({cardDrawVerdict:await SEt(),cardMandateRegister:await TEt()}),dM};async function SEt(){let e=await Promise.resolve().then(()=>(pne(),lne));return{loadCapability:t=>e.loadCardMandateCapability({agentRef:t}),fetchVerdict:t=>e.fetchCardDrawVerdict(t)}}async function TEt(){let e=await Promise.resolve().then(()=>(pne(),lne));return{loadCapability:t=>e.loadCardMandateCapability({agentRef:t}),register:t=>e.registerCardMandate(t)}}async function hne(){return Py("pay_merchant")?(await w7(),Py("pay_merchant")):!1}var sOe=(0,A7.join)((0,mne.homedir)(),".visa-mcp","agent-credential.json"),aOe=(0,A7.join)((0,mne.homedir)(),".visa-mcp","contact.json"),cOe=new cM;function S7(e){return e.replace(/https?:\/\/[^\s"')\]]+/gi,t=>{try{return new URL(t).origin}catch{return"[url]"}}).slice(0,300)}var IEt=new Set(["USD","USDC","EUR","GBP","CAD","AUD"]);function uOe(e){return IEt.has(e)?e:null}async function lM(e){try{await e.emitTelemetry([{timestamp:new Date().toISOString(),tool_name:"pay_merchant",user_prompt:"",tool_params:JSON.stringify({action:e.action,rail:"card",merchant_host:e.merchantHost,amount_minor:e.amountMinor,payment_amount_unit:"major",currency:e.currency,...e.submit===void 0?{}:{submit:e.submit},source:e.source??null,draw_id:e.drawId??null}),result_success:e.success,result_error:e.errorMessage?S7(e.errorMessage):null,result_json:JSON.stringify({outcome:e.outcome,confirmationRef:e.confirmationRef??null,source:e.source??null,remainingMinor:e.remainingMinor??null,...e.paymentStatus?{paymentStatus:e.paymentStatus}:{},...e.settlementVerified===void 0?{}:{settlementVerified:e.settlementVerified}}),payment_rail:e.action==="pay"&&e.submit===!0?"card":null,payment_amount:e.action==="pay"&&e.submit===!0?e.amountMinor/100:null,payment_currency:uOe(e.currency),merchant_name:e.merchantHost,transaction_id:null,tx_hash:null,protocol:null,http_status:null,duration_ms:Math.max(0,Date.now()-e.startedAt),source:"cli",endpoint:"/v4/checkout",resolved_model:null,session_budget_id:null}])}catch(t){Ce.warn("pay_merchant:telemetry_failed",{action:e.action,error:t instanceof Error?t.message:String(t)})}}async function eOe(e){try{await e.emitTelemetry([{timestamp:new Date().toISOString(),tool_name:"start_card_mandate",user_prompt:"",tool_params:JSON.stringify({rail:"card",merchant_host:e.merchantHost,ceiling_minor:e.ceilingMinor,currency:e.currency}),result_success:e.success,result_error:e.errorMessage?S7(e.errorMessage):null,result_json:JSON.stringify({outcome:e.outcome,mandateId:e.mandateId??null,remainingMinor:e.remainingMinor??null}),payment_rail:null,payment_amount:null,payment_currency:uOe(e.currency),merchant_name:e.merchantHost,transaction_id:null,tx_hash:null,protocol:null,http_status:null,duration_ms:Math.max(0,Date.now()-e.startedAt),source:"cli",endpoint:"/v4/mandate",resolved_model:null,session_budget_id:null}])}catch(t){Ce.warn("start_card_mandate:telemetry_failed",{error:t instanceof Error?t.message:String(t)})}}function fne(e){if(typeof e!="string"||!/^\d+(\.\d{1,2})?$/.test(e)||Number(e)<=0)throw new U0(`Invalid amount ${JSON.stringify(e)}. Expected a positive decimal like "5.00".`);return e}function dOe(e,t){if(e.status==="completed")return{...e.result??{},action:t,approvalStatus:"completed",operationId:e.operationId,reviewId:e.reviewId,expiresAt:e.expiresAt};if(e.status==="failed"){let r=S7(e.error??"approval failed");return{success:!1,action:t,approvalStatus:"failed",operationId:e.operationId,reviewId:e.reviewId,expiresAt:e.expiresAt,message:`${r}. Nothing was charged unless a returned receipt explicitly says confirmed.`}}return e.status==="awaiting_passkey"&&e.approvalUrl?{success:!0,action:t,approvalStatus:"awaiting_passkey",operationId:e.operationId,reviewId:e.reviewId,expiresAt:e.expiresAt,requiresBrowser:!0,browserUrl:e.approvalUrl,approval:{type:"visa_passkey",url:e.approvalUrl,expiresAt:e.expiresAt,button:{label:"Open Visa approval",webApp:{url:e.approvalUrl}}},message:"Open the Visa approval link and complete the passkey. This Telegram or messaging handoff is not itself the passkey and has not charged the card."}:e.status==="reconciling"?{success:!1,action:t,approvalStatus:"reconciling",operationId:e.operationId,reviewId:e.reviewId,expiresAt:e.expiresAt,message:"The approval window expired while checkout was still in progress. Check this operation again for a receipt and reconcile with the merchant before starting a fresh review."}:{success:!0,action:t,approvalStatus:"starting",operationId:e.operationId,reviewId:e.reviewId,expiresAt:e.expiresAt,message:"Visa is preparing the hosted passkey approval. Check this approval again shortly."}}async function lOe(e={},t={}){if(await(t.flagDisabled??hne)())return{success:!1,message:"pay_merchant_status requires the checkout_agent_access flag on your account. Ask an admin to enable it, then retry."};let n=typeof e.operationId=="string"&&/^[A-Za-z0-9_-]{1,200}$/.test(e.operationId)?e.operationId:null;if(!n)return{success:!1,action:"status",approvalStatus:"unknown",message:'A valid operationId from pay_merchant action "authorize" is required.'};let o=(t.approvalJobs??cOe).get(n);return o?dOe(o,"status"):{success:!1,action:"status",operationId:n,approvalStatus:"unknown",message:"No active approval operation exists. It may have expired or the MCP process may have restarted. If approval or merchant submission may have begun, reconcile the merchant order or receipt before starting a fresh review; never retry a purchase blindly."}}async function pOe(e={},t={}){let r=(e.rail??"card").toLowerCase();if(r!=="card")return{success:!1,message:`pay_merchant only implements the "card" rail today (got ${JSON.stringify(r)}). For stablecoin/x402, use the wallet tools (wallet_pay / wallet_directory_pay).`};let n=t.verifyUrl!==void 0?t.verifyUrl:Vee()&&!process.env.VISA_VERIFY_WEB_URL?null:cy();if(n===null)return{success:!1,message:"pay_merchant is not available in stable CLI builds (it runs an on-device mint and is limited to tester/RC builds). Use a preview build with VISA_VERIFY_WEB_URL set and the checkout_agent_access flag enabled."};if(await(t.flagDisabled??hne)())return{success:!1,message:"pay_merchant requires the checkout_agent_access flag on your account. Ask an admin to enable it, then retry."};let o=e.action??"review";if(!["review","pay","authorize"].includes(o))return{success:!1,message:`Unknown pay_merchant action ${JSON.stringify(o)}. Use "review" (default), "authorize", or "pay".`};let s=t.approvalJobs??cOe,a,c,u=(e.currency??"USD").toUpperCase();if(!/^[A-Z]{3}$/.test(u))return{success:!1,message:`Invalid currency ${JSON.stringify(e.currency)}. Expected a 3-letter ISO code like "USD".`};try{a=VCe(e.url??"").toString(),c=fne(e.amount)}catch(I){if(I instanceof U0)return{success:!1,message:I.message};throw I}let d=t.credentialPath??sOe,l=t.contactPath??aOe;try{await(0,x7.readFile)(d,"utf8")}catch{return{success:!1,message:"No legacy VIC card authority is provisioned on this device. Identity pairing does not create or repair card authority, and this internal build has no self-serve attachment flow yet. Use a pre-provisioned VIC test runtime or ask the VIC operator; no checkout started."}}let p;try{p=JSON.parse(await(0,x7.readFile)(l,"utf8"))}catch{return{success:!1,message:`No contact details at ${l}. Write your name/email/address there (chmod 600) first.`}}let f=null;if(o==="pay"||o==="authorize"){let I=typeof e.confirm=="string"?e.confirm.trim():"",T=/^PAY (\S+)$/.exec(I);if(!T)return{success:!1,action:o,message:'Confirmation required: pass confirm:"PAY <reviewId>" using the reviewId from a prior pay_merchant { action:"review" } call. Nothing was charged.'};f=T[1]}let m=t.allowSubmit??process.env.CHECKOUT_AGENT_ALLOW_SUBMIT==="1";if(o==="pay"&&!m)return{success:!1,action:"pay",reviewId:f,outcome:"not-submitted",paymentStatus:"not_submitted",settlementVerified:!1,message:'Checkout submission is disabled. No payment credential was requested, filled, or submitted. Use action:"review" for safe inspection, or explicitly enable checkout submission before a real pay call.'};let h=t.loadEngine??oOe,y;try{y=await h()}catch(I){let T=I instanceof Error?I.message:String(I);if(/ERR_MODULE_NOT_FOUND|Cannot find (module|package)/.test(T))return{success:!1,message:/checkout engine was not packaged/.test(T)?"The checkout engine was not packaged into this @visa/cli build (a build/packaging fault). Reinstall @visa/cli from a release that includes it. No charge was made.":"The checkout browser runtime is not installed (playwright-core is an optional dependency of @visa/cli). Install it with `npm i playwright-core` in the CLI install, then retry. No charge was made."};throw I}let v={url:a,amount:c,currency:u,credentialPath:d,contact:p,approvalBaseUrl:n},E=t.emitTelemetry??(I=>gd.emitTelemetry(I)),_=new URL(a).hostname,w=Math.round(Number(c)*100),A=Date.now();if(o==="review"){Ce.info("pay_merchant:review",{host:_,currency:u});let I;try{I=await y.review(v)}catch(T){throw await lM({emitTelemetry:E,action:"review",merchantHost:_,amountMinor:w,currency:u,outcome:"engine-error",success:!1,errorMessage:T instanceof Error?T.message:String(T),startedAt:A}),T}return await lM({emitTelemetry:E,action:"review",merchantHost:_,amountMinor:w,currency:u,outcome:"reviewed",success:!0,startedAt:A}),{success:!0,action:"review",...I,message:`Review ${I.reviewId}: ${I.merchantHost} wants ${E8(I.amountMinor,I.currency)}. For a messaging handoff, call pay_merchant { action: "authorize", url, amount, confirm: "PAY ${I.reviewId}" }; for a blocking terminal flow use action "pay". No charge yet.`}}let x=f,S=async I=>{Ce.info("pay_merchant:pay",{reviewId:x,submit:m,approvalMode:o==="authorize"?"handoff":"blocking"});let T;try{T=await y.pay({...v,reviewId:x,submit:m,...I?{onApprovalUrl:I}:{}})}catch(U){throw await lM({emitTelemetry:E,action:"pay",merchantHost:_,amountMinor:w,currency:u,outcome:"engine-error",success:!1,errorMessage:U instanceof Error?U.message:String(U),startedAt:A,submit:m}),U}let C=T.outcome==="confirmed"||T.outcome==="reviewed-dry-run",j=T.outcome==="reviewed-dry-run"?"not_submitted":T.outcome==="declined"?"declined":"unverified";await lM({emitTelemetry:E,action:"pay",merchantHost:_,amountMinor:w,currency:u,outcome:T.outcome,confirmationRef:T.confirmationRef,success:C,errorMessage:C?null:T.detail??T.outcome,startedAt:A,submit:m,source:T.source??null,remainingMinor:T.remainingMinor??null,paymentStatus:j,settlementVerified:!1,drawId:T.source==="mandate"?x:null});let M=T.source==="mandate"?` Credential issued from a tap-free active mandate${typeof T.remainingMinor=="number"?` (${T.remainingMinor} ${u} minor units remaining)`:""}.`:T.source==="fresh-tap"?" Credential issued with a fresh per-purchase passkey.":"";return{success:C,action:"pay",reviewId:x,...T,paymentStatus:j,settlementVerified:!1,message:T.outcome==="confirmed"?`Checkout submitted. The merchant reported confirmation ${T.confirmationRef??"(none captured)"}, but processor settlement is not independently verified. Receipt ${T.receiptPath??"(not written)"}.${M}`:T.outcome==="reviewed-dry-run"?"Checkout review validated without requesting, filling, or submitting a payment credential.":T.outcome==="filled-dry-run"?`Legacy credential-disclosure dry-run completed. A usable credential reached the merchant page and may have consumed authority even though no submit click was made.${M}`:`Outcome: ${T.outcome}${T.detail?` \u2014 ${T.detail}`:""}. Do not retry blindly \u2014 verify with the merchant before any re-run.`}};if(o==="authorize"){let I=(0,nOe.createHash)("sha256").update(JSON.stringify([x,a,c,u,m])).digest("hex");Ce.info("pay_merchant:approval_handoff_started",{reviewId:x,merchantHost:_,currency:u,submit:m});try{let T=await s.start({reviewId:x,fingerprint:I,run:async C=>{try{let j=await S(M=>{Ce.info("pay_merchant:approval_handoff_ready",{reviewId:x}),C(M)});return Ce.info("pay_merchant:approval_handoff_completed",{reviewId:x,success:j.success===!0}),j}catch(j){throw Ce.warn("pay_merchant:approval_handoff_failed",{reviewId:x,error:S7(j instanceof Error?j.message:String(j))}),j}}});return dOe(T,"authorize")}catch(T){if(T instanceof E7)return Ce.warn("pay_merchant:approval_handoff_conflict",{reviewId:x}),{success:!1,action:"authorize",reviewId:x,approvalStatus:"conflict",message:"This review already has an approval handoff with different checkout inputs. Do not retry it; create and confirm a fresh review."};throw T}}return S()}async function fOe(e={},t={}){let r=t.verifyUrl!==void 0?t.verifyUrl:cy();if(r===null)return{success:!1,message:"start_card_mandate is not available in stable CLI builds (it runs a server-side mint and is limited to tester/RC builds). Use a preview build with VISA_VERIFY_WEB_URL set and the checkout_agent_access flag enabled."};if(await(t.flagDisabled??hne)())return{success:!1,message:"start_card_mandate requires the checkout_agent_access flag on your account. Ask an admin to enable it, then retry."};let i="USD",o;try{o=fne(e.ceiling)}catch(_){if(_ instanceof U0)return{success:!1,message:_.message};throw _}let s;if(e.perTransaction!==void 0){try{s=fne(e.perTransaction)}catch(_){if(_ instanceof U0)return{success:!1,message:_.message};throw _}if(Number(s)>Number(o))return{success:!1,message:"perTransaction cannot exceed the ceiling."}}let a;if(e.intent!==void 0){if(typeof e.intent!="string")return{success:!1,message:"intent must be a short string."};let _=e.intent.replace(/[\p{Cc}\u2028\u2029]/gu,"").trim().slice(0,200).trim();a=_.length>0?_:void 0}let c=t.credentialPath??sOe,u=t.contactPath??aOe;try{await(0,x7.readFile)(c,"utf8")}catch{return{success:!1,message:"No legacy VIC card authority is provisioned on this device. Identity pairing does not create or repair card authority, and this internal build has no self-serve attachment flow yet. Use a pre-provisioned VIC test runtime or ask the VIC operator; no budget was created."}}let d;try{d=JSON.parse(await(0,x7.readFile)(u,"utf8"))}catch{return{success:!1,message:`No contact details at ${u}. Write your name/email/address there (chmod 600) first.`}}let l=t.loadEngine??oOe,p;try{p=await l()}catch(_){let w=_ instanceof Error?_.message:String(_);if(/ERR_MODULE_NOT_FOUND|Cannot find (module|package)/.test(w))return{success:!1,message:"The checkout engine was not packaged into this @visa/cli build (a build/packaging fault). Reinstall @visa/cli from a release that includes it. No mandate was created."};throw _}let f="retail-mcc-5999",m=Math.round(Number(o)*100),h=t.emitTelemetry??(_=>gd.emitTelemetry(_)),y=Date.now();Ce.info("start_card_mandate:create",{host:f,currency:i});let v;try{v=await p.startCardMandate({...e.agent?.trim()?{agentRef:e.agent.trim()}:{},ceiling:o,currency:i,credentialPath:c,contact:d,approvalBaseUrl:r,...s!==void 0?{perTransaction:s}:{},...a!==void 0?{intent:a}:{}})}catch(_){let w=_ instanceof Error?S7(_.message):String(_);return Ce.warn("start_card_mandate:failed",{message:w}),await eOe({emitTelemetry:h,merchantHost:f,ceilingMinor:m,currency:i,outcome:"engine-error",success:!1,errorMessage:_ instanceof Error?_.message:String(_),startedAt:y}),{success:!1,message:`Could not create the mandate: ${w}`}}let E=v.registerFailed===!0;return E&&Ce.warn("start_card_mandate:register_failed",{mandateId:v.mandateId,host:f}),await eOe({emitTelemetry:h,merchantHost:f,ceilingMinor:m,currency:i,outcome:E?"created-register-failed":"created",success:!E,mandateId:v.mandateId,remainingMinor:v.remainingMinor,startedAt:y}),E?{success:!1,mandateId:v.mandateId,ceiling:o,remainingMinor:v.remainingMinor,currency:v.currencyCode,merchant:v.merchant,merchantHost:v.merchantHost,maxPurchases:v.maxDraws,expiresAt:v.expiresAt,message:`Mandate ${v.mandateId} was created but could NOT be registered for tap-free draws, so it will not be used \u2014 your next pay_merchant will fall through to a fresh per-purchase passkey tap. Re-run to try again once the auth server is reachable.`}:{success:!0,mandateId:v.mandateId,ceiling:o,remainingMinor:v.remainingMinor,currency:v.currencyCode,merchant:v.merchant,merchantHost:v.merchantHost,maxPurchases:v.maxDraws,expiresAt:v.expiresAt,message:`Mandate ${v.mandateId} active: up to ${E8(m,v.currencyCode)} at eligible retail merchants (network category 5999), across up to ${v.maxDraws} purchases, until ${v.expiresAt}. pay_merchant will draw against it tap-free until the budget, purchase count, or time limit is reached. A declined draw leaves the budget untouched and disables this mandate; the next checkout can use a fresh per-purchase approval.`}}var oke=require("node:crypto");var tke=require("node:crypto");var Lr={};Pi(Lr,{BRAND:()=>QEt,DIRTY:()=>u6,EMPTY_PATH:()=>kEt,INVALID:()=>bt,NEVER:()=>CAt,OK:()=>Gs,ParseStatus:()=>ds,Schema:()=>zt,ZodAny:()=>ky,ZodArray:()=>L0,ZodBigInt:()=>l6,ZodBoolean:()=>p6,ZodBranded:()=>I7,ZodCatch:()=>A6,ZodDate:()=>f6,ZodDefault:()=>E6,ZodDiscriminatedUnion:()=>mM,ZodEffects:()=>vd,ZodEnum:()=>v6,ZodError:()=>uc,ZodFirstPartyTypeKind:()=>xt,ZodFunction:()=>yM,ZodIntersection:()=>g6,ZodIssueCode:()=>ye,ZodLazy:()=>b6,ZodLiteral:()=>_6,ZodMap:()=>P8,ZodNaN:()=>O8,ZodNativeEnum:()=>w6,ZodNever:()=>Dl,ZodNull:()=>h6,ZodNullable:()=>Ef,ZodNumber:()=>d6,ZodObject:()=>dc,ZodOptional:()=>bd,ZodParsedType:()=>je,ZodPipeline:()=>P7,ZodPromise:()=>Ry,ZodReadonly:()=>x6,ZodRecord:()=>hM,ZodSchema:()=>zt,ZodSet:()=>C8,ZodString:()=>Oy,ZodSymbol:()=>T8,ZodTransformer:()=>vd,ZodTuple:()=>wf,ZodType:()=>zt,ZodUndefined:()=>m6,ZodUnion:()=>y6,ZodUnknown:()=>D0,ZodVoid:()=>I8,addIssueToContext:()=>Te,any:()=>Ed,array:()=>ue,bigint:()=>nAt,boolean:()=>wd,coerce:()=>hu,custom:()=>wOe,date:()=>iAt,datetimeRegex:()=>_Oe,defaultErrorMap:()=>M0,discriminatedUnion:()=>lAt,effect:()=>wAt,enum:()=>Ad,function:()=>yAt,getErrorMap:()=>A8,getParsedType:()=>vf,instanceof:()=>tAt,intersection:()=>pAt,isAborted:()=>pM,isAsync:()=>x8,isDirty:()=>fM,isValid:()=>Cy,late:()=>eAt,lazy:()=>gAt,literal:()=>bAt,makeIssue:()=>T7,map:()=>mAt,nan:()=>rAt,nativeEnum:()=>_At,never:()=>cAt,null:()=>k8,nullable:()=>AAt,number:()=>Or,object:()=>fe,objectUtil:()=>yne,oboolean:()=>PAt,onumber:()=>IAt,optional:()=>EAt,ostring:()=>TAt,pipeline:()=>SAt,preprocess:()=>xAt,promise:()=>vAt,quotelessJson:()=>PEt,record:()=>Xt,set:()=>hAt,setErrorMap:()=>OEt,strictObject:()=>dAt,string:()=>z,symbol:()=>oAt,transformer:()=>wAt,tuple:()=>fAt,undefined:()=>sAt,union:()=>R8,unknown:()=>aAt,util:()=>Zt,void:()=>uAt});var Zt;(function(e){e.assertEqual=i=>{};function t(i){}e.assertIs=t;function r(i){throw new Error}e.assertNever=r,e.arrayToEnum=i=>{let o={};for(let s of i)o[s]=s;return o},e.getValidEnumValues=i=>{let o=e.objectKeys(i).filter(a=>typeof i[i[a]]!="number"),s={};for(let a of o)s[a]=i[a];return e.objectValues(s)},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 s in i)Object.prototype.hasOwnProperty.call(i,s)&&o.push(s);return o},e.find=(i,o)=>{for(let s of i)if(o(s))return s},e.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&Number.isFinite(i)&&Math.floor(i)===i;function n(i,o=" | "){return i.map(s=>typeof s=="string"?`'${s}'`:s).join(o)}e.joinValues=n,e.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(Zt||(Zt={}));var yne;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(yne||(yne={}));var je=Zt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),vf=e=>{switch(typeof e){case"undefined":return je.undefined;case"string":return je.string;case"number":return Number.isNaN(e)?je.nan:je.number;case"boolean":return je.boolean;case"function":return je.function;case"bigint":return je.bigint;case"symbol":return je.symbol;case"object":return Array.isArray(e)?je.array:e===null?je.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?je.promise:typeof Map<"u"&&e instanceof Map?je.map:typeof Set<"u"&&e instanceof Set?je.set:typeof Date<"u"&&e instanceof Date?je.date:je.object;default:return je.unknown}};var ye=Zt.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"]),PEt=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),uc=class e extends Error{get errors(){return this.issues}constructor(t){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=t}format(t){let r=t||function(o){return o.message},n={_errors:[]},i=o=>{for(let s of o.issues)if(s.code==="invalid_union")s.unionErrors.map(i);else if(s.code==="invalid_return_type")i(s.returnTypeError);else if(s.code==="invalid_arguments")i(s.argumentsError);else if(s.path.length===0)n._errors.push(r(s));else{let a=n,c=0;for(;c<s.path.length;){let u=s.path[c];c===s.path.length-1?(a[u]=a[u]||{_errors:[]},a[u]._errors.push(r(s))):a[u]=a[u]||{_errors:[]},a=a[u],c++}}};return i(this),n}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,Zt.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(t=r=>r.message){let r={},n=[];for(let i of this.issues)if(i.path.length>0){let o=i.path[0];r[o]=r[o]||[],r[o].push(t(i))}else n.push(t(i));return{formErrors:n,fieldErrors:r}}get formErrors(){return this.flatten()}};uc.create=e=>new uc(e);var CEt=(e,t)=>{let r;switch(e.code){case ye.invalid_type:e.received===je.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case ye.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,Zt.jsonStringifyReplacer)}`;break;case ye.unrecognized_keys:r=`Unrecognized key(s) in object: ${Zt.joinValues(e.keys,", ")}`;break;case ye.invalid_union:r="Invalid input";break;case ye.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Zt.joinValues(e.options)}`;break;case ye.invalid_enum_value:r=`Invalid enum value. Expected ${Zt.joinValues(e.options)}, received '${e.received}'`;break;case ye.invalid_arguments:r="Invalid function arguments";break;case ye.invalid_return_type:r="Invalid function return type";break;case ye.invalid_date:r="Invalid date";break;case ye.invalid_string:typeof e.validation=="object"?"includes"in e.validation?(r=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${e.validation.position}`)):"startsWith"in e.validation?r=`Invalid input: must start with "${e.validation.startsWith}"`:"endsWith"in e.validation?r=`Invalid input: must end with "${e.validation.endsWith}"`:Zt.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case ye.too_small:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at least":"more than"} ${e.minimum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at least":"over"} ${e.minimum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="bigint"?r=`Number must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${e.minimum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly equal to ":e.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(e.minimum))}`:r="Invalid input";break;case ye.too_big:e.type==="array"?r=`Array must contain ${e.exact?"exactly":e.inclusive?"at most":"less than"} ${e.maximum} element(s)`:e.type==="string"?r=`String must contain ${e.exact?"exactly":e.inclusive?"at most":"under"} ${e.maximum} character(s)`:e.type==="number"?r=`Number must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="bigint"?r=`BigInt must be ${e.exact?"exactly":e.inclusive?"less than or equal to":"less than"} ${e.maximum}`:e.type==="date"?r=`Date must be ${e.exact?"exactly":e.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(e.maximum))}`:r="Invalid input";break;case ye.custom:r="Invalid input";break;case ye.invalid_intersection_types:r="Intersection results could not be merged";break;case ye.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case ye.not_finite:r="Number must be finite";break;default:r=t.defaultError,Zt.assertNever(e)}return{message:r}},M0=CEt;var mOe=M0;function OEt(e){mOe=e}function A8(){return mOe}var T7=e=>{let{data:t,path:r,errorMaps:n,issueData:i}=e,o=[...r,...i.path||[]],s={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let a="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)a=u(s,{data:t,defaultError:a}).message;return{...i,path:o,message:a}},kEt=[];function Te(e,t){let r=A8(),n=T7({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===M0?void 0:M0].filter(i=>!!i)});e.common.issues.push(n)}var ds=class e{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(t,r){let n=[];for(let i of r){if(i.status==="aborted")return bt;i.status==="dirty"&&t.dirty(),n.push(i.value)}return{status:t.value,value:n}}static async mergeObjectAsync(t,r){let n=[];for(let i of r){let o=await i.key,s=await i.value;n.push({key:o,value:s})}return e.mergeObjectSync(t,n)}static mergeObjectSync(t,r){let n={};for(let i of r){let{key:o,value:s}=i;if(o.status==="aborted"||s.status==="aborted")return bt;o.status==="dirty"&&t.dirty(),s.status==="dirty"&&t.dirty(),o.value!=="__proto__"&&(typeof s.value<"u"||i.alwaysSet)&&(n[o.value]=s.value)}return{status:t.value,value:n}}},bt=Object.freeze({status:"aborted"}),u6=e=>({status:"dirty",value:e}),Gs=e=>({status:"valid",value:e}),pM=e=>e.status==="aborted",fM=e=>e.status==="dirty",Cy=e=>e.status==="valid",x8=e=>typeof Promise<"u"&&e instanceof Promise;var et;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(et||(et={}));var _d=class{constructor(t,r,n,i){this._cachedPath=[],this.parent=t,this.data=r,this._path=n,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}},hOe=(e,t)=>{if(Cy(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 r=new uc(e.common.issues);return this._error=r,this._error}}};function Mt(e){if(!e)return{};let{errorMap:t,invalid_type_error:r,required_error:n,description:i}=e;if(t&&(r||n))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:(s,a)=>{let{message:c}=e;return s.code==="invalid_enum_value"?{message:c??a.defaultError}:typeof a.data>"u"?{message:c??n??a.defaultError}:s.code!=="invalid_type"?{message:a.defaultError}:{message:c??r??a.defaultError}},description:i}}var zt=class{get description(){return this._def.description}_getType(t){return vf(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:vf(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ds,ctx:{common:t.parent.common,data:t.data,parsedType:vf(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(x8(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(t){let r=this._parse(t);return Promise.resolve(r)}parse(t,r){let n=this.safeParse(t,r);if(n.success)return n.data;throw n.error}safeParse(t,r){let n={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:vf(t)},i=this._parseSync({data:t,path:n.path,parent:n});return hOe(n,i)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:vf(t)};if(!this["~standard"].async)try{let n=this._parseSync({data:t,path:[],parent:r});return Cy(n)?{value:n.value}:{issues:r.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:t,path:[],parent:r}).then(n=>Cy(n)?{value:n.value}:{issues:r.common.issues})}async parseAsync(t,r){let n=await this.safeParseAsync(t,r);if(n.success)return n.data;throw n.error}async safeParseAsync(t,r){let n={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:vf(t)},i=this._parse({data:t,path:n.path,parent:n}),o=await(x8(i)?i:Promise.resolve(i));return hOe(n,o)}refine(t,r){let n=i=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(i):r;return this._refinement((i,o)=>{let s=t(i),a=()=>o.addIssue({code:ye.custom,...n(i)});return typeof Promise<"u"&&s instanceof Promise?s.then(c=>c?!0:(a(),!1)):s?!0:(a(),!1)})}refinement(t,r){return this._refinement((n,i)=>t(n)?!0:(i.addIssue(typeof r=="function"?r(n,i):r),!1))}_refinement(t){return new vd({schema:this,typeName:xt.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:r=>this["~validate"](r)}}optional(){return bd.create(this,this._def)}nullable(){return Ef.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return L0.create(this)}promise(){return Ry.create(this,this._def)}or(t){return y6.create([this,t],this._def)}and(t){return g6.create(this,t,this._def)}transform(t){return new vd({...Mt(this._def),schema:this,typeName:xt.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new E6({...Mt(this._def),innerType:this,defaultValue:r,typeName:xt.ZodDefault})}brand(){return new I7({typeName:xt.ZodBranded,type:this,...Mt(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new A6({...Mt(this._def),innerType:this,catchValue:r,typeName:xt.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return P7.create(this,t)}readonly(){return x6.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},REt=/^c[^\s-]{8,}$/i,NEt=/^[0-9a-z]+$/,BEt=/^[0-9A-HJKMNP-TV-Z]{26}$/i,jEt=/^[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,UEt=/^[a-z0-9_-]{21}$/i,MEt=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,qEt=/^[-+]?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)?)??$/,DEt=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,LEt="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",gne,zEt=/^(?:(?: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])$/,HEt=/^(?:(?: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])$/,$Et=/^(([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]))$/,FEt=/^(([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])$/,VEt=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,KEt=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,gOe="((\\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])))",WEt=new RegExp(`^${gOe}$`);function bOe(e){let t="[0-5]\\d";e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision==null&&(t=`${t}(\\.\\d+)?`);let r=e.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${r}`}function GEt(e){return new RegExp(`^${bOe(e)}$`)}function _Oe(e){let t=`${gOe}T${bOe(e)}`,r=[];return r.push(e.local?"Z?":"Z"),e.offset&&r.push("([+-]\\d{2}:?\\d{2})"),t=`${t}(${r.join("|")})`,new RegExp(`^${t}$`)}function JEt(e,t){return!!((t==="v4"||!t)&&zEt.test(e)||(t==="v6"||!t)&&$Et.test(e))}function YEt(e,t){if(!MEt.test(e))return!1;try{let[r]=e.split(".");if(!r)return!1;let n=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||"typ"in i&&i?.typ!=="JWT"||!i.alg||t&&i.alg!==t)}catch{return!1}}function ZEt(e,t){return!!((t==="v4"||!t)&&HEt.test(e)||(t==="v6"||!t)&&FEt.test(e))}var Oy=class e extends zt{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==je.string){let o=this._getOrReturnCtx(t);return Te(o,{code:ye.invalid_type,expected:je.string,received:o.parsedType}),bt}let n=new ds,i;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="max")t.data.length>o.value&&(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let s=t.data.length>o.value,a=t.data.length<o.value;(s||a)&&(i=this._getOrReturnCtx(t,i),s?Te(i,{code:ye.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&Te(i,{code:ye.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")DEt.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"email",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")gne||(gne=new RegExp(LEt,"u")),gne.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"emoji",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")jEt.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"uuid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")UEt.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"nanoid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")REt.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"cuid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")NEt.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"cuid2",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")BEt.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"ulid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),Te(i,{validation:"url",code:ye.invalid_string,message:o.message}),n.dirty()}else o.kind==="regex"?(o.regex.lastIndex=0,o.regex.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"regex",code:ye.invalid_string,message:o.message}),n.dirty())):o.kind==="trim"?t.data=t.data.trim():o.kind==="includes"?t.data.includes(o.value,o.position)||(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.invalid_string,validation:{includes:o.value,position:o.position},message:o.message}),n.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),Te(i,{code:ye.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?_Oe(o).test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?WEt.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?GEt(o).test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?qEt.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"duration",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?JEt(t.data,o.version)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"ip",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?YEt(t.data,o.alg)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"jwt",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?ZEt(t.data,o.version)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"cidr",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?VEt.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"base64",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?KEt.test(t.data)||(i=this._getOrReturnCtx(t,i),Te(i,{validation:"base64url",code:ye.invalid_string,message:o.message}),n.dirty()):Zt.assertNever(o);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(i=>t.test(i),{validation:r,code:ye.invalid_string,...et.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...et.errToObj(t)})}url(t){return this._addCheck({kind:"url",...et.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...et.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...et.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...et.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...et.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...et.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...et.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...et.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...et.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...et.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...et.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...et.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,...et.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,...et.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...et.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...et.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...et.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...et.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...et.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...et.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...et.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...et.errToObj(r)})}nonempty(t){return this.min(1,et.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 r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxLength(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};Oy.create=e=>new Oy({checks:[],typeName:xt.ZodString,coerce:e?.coerce??!1,...Mt(e)});function XEt(e,t){let r=(e.toString().split(".")[1]||"").length,n=(t.toString().split(".")[1]||"").length,i=r>n?r:n,o=Number.parseInt(e.toFixed(i).replace(".","")),s=Number.parseInt(t.toFixed(i).replace(".",""));return o%s/10**i}var d6=class e extends zt{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)!==je.number){let o=this._getOrReturnCtx(t);return Te(o,{code:ye.invalid_type,expected:je.number,received:o.parsedType}),bt}let n,i=new ds;for(let o of this._def.checks)o.kind==="int"?Zt.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),Te(n,{code:ye.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(n=this._getOrReturnCtx(t,n),Te(n,{code:ye.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)&&(n=this._getOrReturnCtx(t,n),Te(n,{code:ye.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?XEt(t.data,o.value)!==0&&(n=this._getOrReturnCtx(t,n),Te(n,{code:ye.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),Te(n,{code:ye.not_finite,message:o.message}),i.dirty()):Zt.assertNever(o);return{status:i.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,et.toString(r))}gt(t,r){return this.setLimit("min",t,!1,et.toString(r))}lte(t,r){return this.setLimit("max",t,!0,et.toString(r))}lt(t,r){return this.setLimit("max",t,!1,et.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:et.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:et.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:et.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:et.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:et.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:et.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:et.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:et.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:et.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:et.toString(t)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}get isInt(){return!!this._def.checks.find(t=>t.kind==="int"||t.kind==="multipleOf"&&Zt.isInteger(t.value))}get isFinite(){let t=null,r=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(r===null||n.value>r)&&(r=n.value):n.kind==="max"&&(t===null||n.value<t)&&(t=n.value)}return Number.isFinite(r)&&Number.isFinite(t)}};d6.create=e=>new d6({checks:[],typeName:xt.ZodNumber,coerce:e?.coerce||!1,...Mt(e)});var l6=class e extends zt{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)!==je.bigint)return this._getInvalidInput(t);let n,i=new ds;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?t.data<o.value:t.data<=o.value)&&(n=this._getOrReturnCtx(t,n),Te(n,{code:ye.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)&&(n=this._getOrReturnCtx(t,n),Te(n,{code:ye.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?t.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(t,n),Te(n,{code:ye.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):Zt.assertNever(o);return{status:i.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return Te(r,{code:ye.invalid_type,expected:je.bigint,received:r.parsedType}),bt}gte(t,r){return this.setLimit("min",t,!0,et.toString(r))}gt(t,r){return this.setLimit("min",t,!1,et.toString(r))}lte(t,r){return this.setLimit("max",t,!0,et.toString(r))}lt(t,r){return this.setLimit("max",t,!1,et.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:et.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:et.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:et.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:et.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:et.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:et.toString(r)})}get minValue(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t}get maxValue(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t}};l6.create=e=>new l6({checks:[],typeName:xt.ZodBigInt,coerce:e?.coerce??!1,...Mt(e)});var p6=class extends zt{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==je.boolean){let n=this._getOrReturnCtx(t);return Te(n,{code:ye.invalid_type,expected:je.boolean,received:n.parsedType}),bt}return Gs(t.data)}};p6.create=e=>new p6({typeName:xt.ZodBoolean,coerce:e?.coerce||!1,...Mt(e)});var f6=class e extends zt{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==je.date){let o=this._getOrReturnCtx(t);return Te(o,{code:ye.invalid_type,expected:je.date,received:o.parsedType}),bt}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return Te(o,{code:ye.invalid_date}),bt}let n=new ds,i;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.too_small,message:o.message,inclusive:!0,exact:!1,minimum:o.value,type:"date"}),n.dirty()):o.kind==="max"?t.data.getTime()>o.value&&(i=this._getOrReturnCtx(t,i),Te(i,{code:ye.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):Zt.assertNever(o);return{status:n.value,value:new Date(t.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(t,r){return this._addCheck({kind:"min",value:t.getTime(),message:et.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:et.toString(r)})}get minDate(){let t=null;for(let r of this._def.checks)r.kind==="min"&&(t===null||r.value>t)&&(t=r.value);return t!=null?new Date(t):null}get maxDate(){let t=null;for(let r of this._def.checks)r.kind==="max"&&(t===null||r.value<t)&&(t=r.value);return t!=null?new Date(t):null}};f6.create=e=>new f6({checks:[],coerce:e?.coerce||!1,typeName:xt.ZodDate,...Mt(e)});var T8=class extends zt{_parse(t){if(this._getType(t)!==je.symbol){let n=this._getOrReturnCtx(t);return Te(n,{code:ye.invalid_type,expected:je.symbol,received:n.parsedType}),bt}return Gs(t.data)}};T8.create=e=>new T8({typeName:xt.ZodSymbol,...Mt(e)});var m6=class extends zt{_parse(t){if(this._getType(t)!==je.undefined){let n=this._getOrReturnCtx(t);return Te(n,{code:ye.invalid_type,expected:je.undefined,received:n.parsedType}),bt}return Gs(t.data)}};m6.create=e=>new m6({typeName:xt.ZodUndefined,...Mt(e)});var h6=class extends zt{_parse(t){if(this._getType(t)!==je.null){let n=this._getOrReturnCtx(t);return Te(n,{code:ye.invalid_type,expected:je.null,received:n.parsedType}),bt}return Gs(t.data)}};h6.create=e=>new h6({typeName:xt.ZodNull,...Mt(e)});var ky=class extends zt{constructor(){super(...arguments),this._any=!0}_parse(t){return Gs(t.data)}};ky.create=e=>new ky({typeName:xt.ZodAny,...Mt(e)});var D0=class extends zt{constructor(){super(...arguments),this._unknown=!0}_parse(t){return Gs(t.data)}};D0.create=e=>new D0({typeName:xt.ZodUnknown,...Mt(e)});var Dl=class extends zt{_parse(t){let r=this._getOrReturnCtx(t);return Te(r,{code:ye.invalid_type,expected:je.never,received:r.parsedType}),bt}};Dl.create=e=>new Dl({typeName:xt.ZodNever,...Mt(e)});var I8=class extends zt{_parse(t){if(this._getType(t)!==je.undefined){let n=this._getOrReturnCtx(t);return Te(n,{code:ye.invalid_type,expected:je.void,received:n.parsedType}),bt}return Gs(t.data)}};I8.create=e=>new I8({typeName:xt.ZodVoid,...Mt(e)});var L0=class e extends zt{_parse(t){let{ctx:r,status:n}=this._processInputParams(t),i=this._def;if(r.parsedType!==je.array)return Te(r,{code:ye.invalid_type,expected:je.array,received:r.parsedType}),bt;if(i.exactLength!==null){let s=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(s||a)&&(Te(r,{code:s?ye.too_big:ye.too_small,minimum:a?i.exactLength.value:void 0,maximum:s?i.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:i.exactLength.message}),n.dirty())}if(i.minLength!==null&&r.data.length<i.minLength.value&&(Te(r,{code:ye.too_small,minimum:i.minLength.value,type:"array",inclusive:!0,exact:!1,message:i.minLength.message}),n.dirty()),i.maxLength!==null&&r.data.length>i.maxLength.value&&(Te(r,{code:ye.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),r.common.async)return Promise.all([...r.data].map((s,a)=>i.type._parseAsync(new _d(r,s,r.path,a)))).then(s=>ds.mergeArray(n,s));let o=[...r.data].map((s,a)=>i.type._parseSync(new _d(r,s,r.path,a)));return ds.mergeArray(n,o)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:et.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:et.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:et.toString(r)}})}nonempty(t){return this.min(1,t)}};L0.create=(e,t)=>new L0({type:e,minLength:null,maxLength:null,exactLength:null,typeName:xt.ZodArray,...Mt(t)});function S8(e){if(e instanceof dc){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=bd.create(S8(n))}return new dc({...e._def,shape:()=>t})}else return e instanceof L0?new L0({...e._def,type:S8(e.element)}):e instanceof bd?bd.create(S8(e.unwrap())):e instanceof Ef?Ef.create(S8(e.unwrap())):e instanceof wf?wf.create(e.items.map(t=>S8(t))):e}var dc=class e extends zt{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(),r=Zt.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==je.object){let u=this._getOrReturnCtx(t);return Te(u,{code:ye.invalid_type,expected:je.object,received:u.parsedType}),bt}let{status:n,ctx:i}=this._processInputParams(t),{shape:o,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof Dl&&this._def.unknownKeys==="strip"))for(let u in i.data)s.includes(u)||a.push(u);let c=[];for(let u of s){let d=o[u],l=i.data[u];c.push({key:{status:"valid",value:u},value:d._parse(new _d(i,l,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof Dl){let u=this._def.unknownKeys;if(u==="passthrough")for(let d of a)c.push({key:{status:"valid",value:d},value:{status:"valid",value:i.data[d]}});else if(u==="strict")a.length>0&&(Te(i,{code:ye.unrecognized_keys,keys:a}),n.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let d of a){let l=i.data[d];c.push({key:{status:"valid",value:d},value:u._parse(new _d(i,l,i.path,d)),alwaysSet:d in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let u=[];for(let d of c){let l=await d.key,p=await d.value;u.push({key:l,value:p,alwaysSet:d.alwaysSet})}return u}).then(u=>ds.mergeObjectSync(n,u)):ds.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(t){return et.errToObj,new e({...this._def,unknownKeys:"strict",...t!==void 0?{errorMap:(r,n)=>{let i=this._def.errorMap?.(r,n).message??n.defaultError;return r.code==="unrecognized_keys"?{message:et.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:xt.ZodObject})}setKey(t,r){return this.augment({[t]:r})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let r={};for(let n of Zt.objectKeys(t))t[n]&&this.shape[n]&&(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}omit(t){let r={};for(let n of Zt.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}deepPartial(){return S8(this)}partial(t){let r={};for(let n of Zt.objectKeys(this.shape)){let i=this.shape[n];t&&!t[n]?r[n]=i:r[n]=i.optional()}return new e({...this._def,shape:()=>r})}required(t){let r={};for(let n of Zt.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof bd;)o=o._def.innerType;r[n]=o}return new e({...this._def,shape:()=>r})}keyof(){return vOe(Zt.objectKeys(this.shape))}};dc.create=(e,t)=>new dc({shape:()=>e,unknownKeys:"strip",catchall:Dl.create(),typeName:xt.ZodObject,...Mt(t)});dc.strictCreate=(e,t)=>new dc({shape:()=>e,unknownKeys:"strict",catchall:Dl.create(),typeName:xt.ZodObject,...Mt(t)});dc.lazycreate=(e,t)=>new dc({shape:e,unknownKeys:"strip",catchall:Dl.create(),typeName:xt.ZodObject,...Mt(t)});var y6=class extends zt{_parse(t){let{ctx:r}=this._processInputParams(t),n=this._def.options;function i(o){for(let a of o)if(a.result.status==="valid")return a.result;for(let a of o)if(a.result.status==="dirty")return r.common.issues.push(...a.ctx.common.issues),a.result;let s=o.map(a=>new uc(a.ctx.common.issues));return Te(r,{code:ye.invalid_union,unionErrors:s}),bt}if(r.common.async)return Promise.all(n.map(async o=>{let s={...r,common:{...r.common,issues:[]},parent:null};return{result:await o._parseAsync({data:r.data,path:r.path,parent:s}),ctx:s}})).then(i);{let o,s=[];for(let c of n){let u={...r,common:{...r.common,issues:[]},parent:null},d=c._parseSync({data:r.data,path:r.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!o&&(o={result:d,ctx:u}),u.common.issues.length&&s.push(u.common.issues)}if(o)return r.common.issues.push(...o.ctx.common.issues),o.result;let a=s.map(c=>new uc(c));return Te(r,{code:ye.invalid_union,unionErrors:a}),bt}}get options(){return this._def.options}};y6.create=(e,t)=>new y6({options:e,typeName:xt.ZodUnion,...Mt(t)});var q0=e=>e instanceof b6?q0(e.schema):e instanceof vd?q0(e.innerType()):e instanceof _6?[e.value]:e instanceof v6?e.options:e instanceof w6?Zt.objectValues(e.enum):e instanceof E6?q0(e._def.innerType):e instanceof m6?[void 0]:e instanceof h6?[null]:e instanceof bd?[void 0,...q0(e.unwrap())]:e instanceof Ef?[null,...q0(e.unwrap())]:e instanceof I7||e instanceof x6?q0(e.unwrap()):e instanceof A6?q0(e._def.innerType):[],mM=class e extends zt{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==je.object)return Te(r,{code:ye.invalid_type,expected:je.object,received:r.parsedType}),bt;let n=this.discriminator,i=r.data[n],o=this.optionsMap.get(i);return o?r.common.async?o._parseAsync({data:r.data,path:r.path,parent:r}):o._parseSync({data:r.data,path:r.path,parent:r}):(Te(r,{code:ye.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),bt)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,r,n){let i=new Map;for(let o of r){let s=q0(o.shape[t]);if(!s.length)throw new Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let a of s){if(i.has(a))throw new Error(`Discriminator property ${String(t)} has duplicate value ${String(a)}`);i.set(a,o)}}return new e({typeName:xt.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:i,...Mt(n)})}};function bne(e,t){let r=vf(e),n=vf(t);if(e===t)return{valid:!0,data:e};if(r===je.object&&n===je.object){let i=Zt.objectKeys(t),o=Zt.objectKeys(e).filter(a=>i.indexOf(a)!==-1),s={...e,...t};for(let a of o){let c=bne(e[a],t[a]);if(!c.valid)return{valid:!1};s[a]=c.data}return{valid:!0,data:s}}else if(r===je.array&&n===je.array){if(e.length!==t.length)return{valid:!1};let i=[];for(let o=0;o<e.length;o++){let s=e[o],a=t[o],c=bne(s,a);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else return r===je.date&&n===je.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var g6=class extends zt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=(o,s)=>{if(pM(o)||pM(s))return bt;let a=bne(o.value,s.value);return a.valid?((fM(o)||fM(s))&&r.dirty(),{status:r.value,value:a.data}):(Te(n,{code:ye.invalid_intersection_types}),bt)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,s])=>i(o,s)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};g6.create=(e,t,r)=>new g6({left:e,right:t,typeName:xt.ZodIntersection,...Mt(r)});var wf=class e extends zt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==je.array)return Te(n,{code:ye.invalid_type,expected:je.array,received:n.parsedType}),bt;if(n.data.length<this._def.items.length)return Te(n,{code:ye.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),bt;!this._def.rest&&n.data.length>this._def.items.length&&(Te(n,{code:ye.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let o=[...n.data].map((s,a)=>{let c=this._def.items[a]||this._def.rest;return c?c._parse(new _d(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>ds.mergeArray(r,s)):ds.mergeArray(r,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};wf.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new wf({items:e,typeName:xt.ZodTuple,rest:null,...Mt(t)})};var hM=class e extends zt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==je.object)return Te(n,{code:ye.invalid_type,expected:je.object,received:n.parsedType}),bt;let i=[],o=this._def.keyType,s=this._def.valueType;for(let a in n.data)i.push({key:o._parse(new _d(n,a,n.path,a)),value:s._parse(new _d(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?ds.mergeObjectAsync(r,i):ds.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof zt?new e({keyType:t,valueType:r,typeName:xt.ZodRecord,...Mt(n)}):new e({keyType:Oy.create(),valueType:t,typeName:xt.ZodRecord,...Mt(r)})}},P8=class extends zt{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==je.map)return Te(n,{code:ye.invalid_type,expected:je.map,received:n.parsedType}),bt;let i=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([a,c],u)=>({key:i._parse(new _d(n,a,n.path,[u,"key"])),value:o._parse(new _d(n,c,n.path,[u,"value"]))}));if(n.common.async){let a=new Map;return Promise.resolve().then(async()=>{for(let c of s){let u=await c.key,d=await c.value;if(u.status==="aborted"||d.status==="aborted")return bt;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}})}else{let a=new Map;for(let c of s){let u=c.key,d=c.value;if(u.status==="aborted"||d.status==="aborted")return bt;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}}}};P8.create=(e,t,r)=>new P8({valueType:t,keyType:e,typeName:xt.ZodMap,...Mt(r)});var C8=class e extends zt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==je.set)return Te(n,{code:ye.invalid_type,expected:je.set,received:n.parsedType}),bt;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(Te(n,{code:ye.too_small,minimum:i.minSize.value,type:"set",inclusive:!0,exact:!1,message:i.minSize.message}),r.dirty()),i.maxSize!==null&&n.data.size>i.maxSize.value&&(Te(n,{code:ye.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),r.dirty());let o=this._def.valueType;function s(c){let u=new Set;for(let d of c){if(d.status==="aborted")return bt;d.status==="dirty"&&r.dirty(),u.add(d.value)}return{status:r.value,value:u}}let a=[...n.data.values()].map((c,u)=>o._parse(new _d(n,c,n.path,u)));return n.common.async?Promise.all(a).then(c=>s(c)):s(a)}min(t,r){return new e({...this._def,minSize:{value:t,message:et.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:et.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};C8.create=(e,t)=>new C8({valueType:e,minSize:null,maxSize:null,typeName:xt.ZodSet,...Mt(t)});var yM=class e extends zt{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==je.function)return Te(r,{code:ye.invalid_type,expected:je.function,received:r.parsedType}),bt;function n(a,c){return T7({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,A8(),M0].filter(u=>!!u),issueData:{code:ye.invalid_arguments,argumentsError:c}})}function i(a,c){return T7({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,A8(),M0].filter(u=>!!u),issueData:{code:ye.invalid_return_type,returnTypeError:c}})}let o={errorMap:r.common.contextualErrorMap},s=r.data;if(this._def.returns instanceof Ry){let a=this;return Gs(async function(...c){let u=new uc([]),d=await a._def.args.parseAsync(c,o).catch(f=>{throw u.addIssue(n(c,f)),u}),l=await Reflect.apply(s,this,d);return await a._def.returns._def.type.parseAsync(l,o).catch(f=>{throw u.addIssue(i(l,f)),u})})}else{let a=this;return Gs(function(...c){let u=a._def.args.safeParse(c,o);if(!u.success)throw new uc([n(c,u.error)]);let d=Reflect.apply(s,this,u.data),l=a._def.returns.safeParse(d,o);if(!l.success)throw new uc([i(d,l.error)]);return l.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:wf.create(t).rest(D0.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,r,n){return new e({args:t||wf.create([]).rest(D0.create()),returns:r||D0.create(),typeName:xt.ZodFunction,...Mt(n)})}},b6=class extends zt{get schema(){return this._def.getter()}_parse(t){let{ctx:r}=this._processInputParams(t);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};b6.create=(e,t)=>new b6({getter:e,typeName:xt.ZodLazy,...Mt(t)});var _6=class extends zt{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return Te(r,{received:r.data,code:ye.invalid_literal,expected:this._def.value}),bt}return{status:"valid",value:t.data}}get value(){return this._def.value}};_6.create=(e,t)=>new _6({value:e,typeName:xt.ZodLiteral,...Mt(t)});function vOe(e,t){return new v6({values:e,typeName:xt.ZodEnum,...Mt(t)})}var v6=class e extends zt{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return Te(r,{expected:Zt.joinValues(n),received:r.parsedType,code:ye.invalid_type}),bt}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(t.data)){let r=this._getOrReturnCtx(t),n=this._def.values;return Te(r,{received:r.data,code:ye.invalid_enum_value,options:n}),bt}return Gs(t.data)}get options(){return this._def.values}get enum(){let t={};for(let r of this._def.values)t[r]=r;return t}get Values(){let t={};for(let r of this._def.values)t[r]=r;return t}get Enum(){let t={};for(let r of this._def.values)t[r]=r;return t}extract(t,r=this._def){return e.create(t,{...this._def,...r})}exclude(t,r=this._def){return e.create(this.options.filter(n=>!t.includes(n)),{...this._def,...r})}};v6.create=vOe;var w6=class extends zt{_parse(t){let r=Zt.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==je.string&&n.parsedType!==je.number){let i=Zt.objectValues(r);return Te(n,{expected:Zt.joinValues(i),received:n.parsedType,code:ye.invalid_type}),bt}if(this._cache||(this._cache=new Set(Zt.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=Zt.objectValues(r);return Te(n,{received:n.data,code:ye.invalid_enum_value,options:i}),bt}return Gs(t.data)}get enum(){return this._def.values}};w6.create=(e,t)=>new w6({values:e,typeName:xt.ZodNativeEnum,...Mt(t)});var Ry=class extends zt{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==je.promise&&r.common.async===!1)return Te(r,{code:ye.invalid_type,expected:je.promise,received:r.parsedType}),bt;let n=r.parsedType===je.promise?r.data:Promise.resolve(r.data);return Gs(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Ry.create=(e,t)=>new Ry({type:e,typeName:xt.ZodPromise,...Mt(t)});var vd=class extends zt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===xt.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=this._def.effect||null,o={addIssue:s=>{Te(n,s),s.fatal?r.abort():r.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let s=i.transform(n.data,o);if(n.common.async)return Promise.resolve(s).then(async a=>{if(r.value==="aborted")return bt;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?bt:c.status==="dirty"?u6(c.value):r.value==="dirty"?u6(c.value):c});{if(r.value==="aborted")return bt;let a=this._def.schema._parseSync({data:s,path:n.path,parent:n});return a.status==="aborted"?bt:a.status==="dirty"?u6(a.value):r.value==="dirty"?u6(a.value):a}}if(i.type==="refinement"){let s=a=>{let c=i.refinement(a,o);if(n.common.async)return Promise.resolve(c);if(c instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return a};if(n.common.async===!1){let a=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?bt:(a.status==="dirty"&&r.dirty(),s(a.value),{status:r.value,value:a.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(a=>a.status==="aborted"?bt:(a.status==="dirty"&&r.dirty(),s(a.value).then(()=>({status:r.value,value:a.value}))))}if(i.type==="transform")if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Cy(s))return bt;let a=i.transform(s.value,o);if(a instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:a}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>Cy(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:r.value,value:a})):bt);Zt.assertNever(i)}};vd.create=(e,t,r)=>new vd({schema:e,typeName:xt.ZodEffects,effect:t,...Mt(r)});vd.createWithPreprocess=(e,t,r)=>new vd({schema:t,effect:{type:"preprocess",transform:e},typeName:xt.ZodEffects,...Mt(r)});var bd=class extends zt{_parse(t){return this._getType(t)===je.undefined?Gs(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};bd.create=(e,t)=>new bd({innerType:e,typeName:xt.ZodOptional,...Mt(t)});var Ef=class extends zt{_parse(t){return this._getType(t)===je.null?Gs(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Ef.create=(e,t)=>new Ef({innerType:e,typeName:xt.ZodNullable,...Mt(t)});var E6=class extends zt{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return r.parsedType===je.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};E6.create=(e,t)=>new E6({innerType:e,typeName:xt.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Mt(t)});var A6=class extends zt{_parse(t){let{ctx:r}=this._processInputParams(t),n={...r,common:{...r.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return x8(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new uc(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new uc(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};A6.create=(e,t)=>new A6({innerType:e,typeName:xt.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Mt(t)});var O8=class extends zt{_parse(t){if(this._getType(t)!==je.nan){let n=this._getOrReturnCtx(t);return Te(n,{code:ye.invalid_type,expected:je.nan,received:n.parsedType}),bt}return{status:"valid",value:t.data}}};O8.create=e=>new O8({typeName:xt.ZodNaN,...Mt(e)});var QEt=Symbol("zod_brand"),I7=class extends zt{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return this._def.type._parse({data:n,path:r.path,parent:r})}unwrap(){return this._def.type}},P7=class e extends zt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?bt:o.status==="dirty"?(r.dirty(),u6(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?bt:i.status==="dirty"?(r.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(t,r){return new e({in:t,out:r,typeName:xt.ZodPipeline})}},x6=class extends zt{_parse(t){let r=this._def.innerType._parse(t),n=i=>(Cy(i)&&(i.value=Object.freeze(i.value)),i);return x8(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};x6.create=(e,t)=>new x6({innerType:e,typeName:xt.ZodReadonly,...Mt(t)});function yOe(e,t){let r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function wOe(e,t={},r){return e?ky.create().superRefine((n,i)=>{let o=e(n);if(o instanceof Promise)return o.then(s=>{if(!s){let a=yOe(t,n),c=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:c})}});if(!o){let s=yOe(t,n),a=s.fatal??r??!0;i.addIssue({code:"custom",...s,fatal:a})}}):ky.create()}var eAt={object:dc.lazycreate},xt;(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"})(xt||(xt={}));var tAt=(e,t={message:`Input not instance of ${e.name}`})=>wOe(r=>r instanceof e,t),z=Oy.create,Or=d6.create,rAt=O8.create,nAt=l6.create,wd=p6.create,iAt=f6.create,oAt=T8.create,sAt=m6.create,k8=h6.create,Ed=ky.create,aAt=D0.create,cAt=Dl.create,uAt=I8.create,ue=L0.create,fe=dc.create,dAt=dc.strictCreate,R8=y6.create,lAt=mM.create,pAt=g6.create,fAt=wf.create,Xt=hM.create,mAt=P8.create,hAt=C8.create,yAt=yM.create,gAt=b6.create,bAt=_6.create,Ad=v6.create,_At=w6.create,vAt=Ry.create,wAt=vd.create,EAt=bd.create,AAt=Ef.create,xAt=vd.createWithPreprocess,SAt=P7.create,TAt=()=>z().optional(),IAt=()=>Or().optional(),PAt=()=>wd().optional(),hu={string:(e=>Oy.create({...e,coerce:!0})),number:(e=>d6.create({...e,coerce:!0})),boolean:(e=>p6.create({...e,coerce:!0})),bigint:(e=>l6.create({...e,coerce:!0})),date:(e=>f6.create({...e,coerce:!0}))};var CAt=bt;var kAt=Ad(["enc","sig"]),RAt=Ad(["markdown","plain"]),NAt=Ad(["recoverable","requires_buyer_input","requires_buyer_review","unrecoverable"]),BAt=Ad(["error","info","warning"]),j8=Ad(["canceled","complete_in_progress","completed","incomplete","ready_for_complete","requires_escalation"]),jAt=Ad(["completed","failed","pending"]),UAt=Ad(["digital","pickup","shipping"]),MAt=Ad(["fulfilled","partial","processing","removed"]),qAt=Ad(["across","each"]),_ne=Ad(["pickup","shipping"]),DAt=fe({config:Xt(z(),Ed()),config_schema:z(),id:z(),instrument_schemas:ue(z()),name:z(),spec:z(),version:z()}),LAt=fe({alg:z().optional(),crv:z().optional(),e:z().optional(),kid:z(),kty:z(),n:z().optional(),use:kAt.optional(),x:z().optional(),y:z().optional()}),zAt=fe({config:Xt(z(),Ed()).optional(),extends:z().optional(),name:z(),schema:z(),spec:z(),version:z()}),HAt=fe({endpoint:z()}),$At=fe({schema:z()}),EOe=fe({endpoint:z(),schema:z()}),FAt=EOe,VAt=EOe,Ta=fe({email:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional()}),fo=fe({address_country:z().optional(),address_region:z().optional(),currency:z().optional(),eligibility:ue(z()).optional(),intent:z().optional(),language:z().optional(),postal_code:z().optional()}),vne=fo,AOe=fe({id:z()}),KAt=AOe,WAt=AOe,C7=fe({address_country:z().optional(),address_locality:z().optional(),address_region:z().optional(),extended_address:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional(),postal_code:z().optional(),street_address:z().optional()}),gM=fe({type:z()}),Vi=fe({"dev.ucp.buyer_ip":z().optional(),"dev.ucp.user_agent":z().optional()}),wne=Vi,xOe=fe({id:z(),image_url:z().optional(),price:Or(),title:z()}),bM=fe({amount:Or(),display_text:z().optional(),type:z()}),Ny=fe({title:z().optional(),type:z(),url:z()}),z0=fe({code:z().optional(),content:z(),content_type:RAt.optional(),path:z().optional(),severity:NAt.optional(),type:BAt,image_url:z().optional(),presentation:z().optional(),url:z().optional()}),Ene=z0,U8=fe({id:z(),label:z().optional(),permalink_url:z()}),GAt=fe({amount:Or(),display_text:z()}),JAt=fe({config:Xt(z(),Ed()).optional(),extends:z().optional(),name:z(),schema:z().optional(),spec:z().optional(),version:z()}),Ane=fe({id:z(),quantity:Or()}),YAt=Ane,ZAt=Ane,XAt=Ane,QAt=fe({fulfilled:Or(),original:Or().optional(),total:Or()}),ext=fe({billing_address:C7.optional(),credential:gM.optional(),display:Xt(z(),Ed()).optional(),handler_id:z(),id:z(),type:z()}),txt=fe({checkout_mandate:z()}),rxt=fe({merchant_authorization:z().optional(),checkout_mandate:z()}),nxt=fe({analytics:wd().optional(),marketing:wd().optional(),preferences:wd().optional(),sale_of_data:wd().optional()});var ixt=nxt;var SOe=fe({codes:ue(z()).optional()}),oxt=SOe,sxt=fe({amount:Or(),path:z()}),axt=fe({address_country:z().optional(),address_locality:z().optional(),address_region:z().optional(),extended_address:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional(),postal_code:z().optional(),street_address:z().optional(),id:z().optional(),address:C7.optional(),name:z().optional()}),cxt=fe({carrier:z().optional(),description:z().optional(),earliest_fulfillment_time:hu.date().optional(),id:z(),latest_fulfillment_time:hu.date().optional(),title:z(),totals:ue(bM)}),uxt=fe({description:z().optional(),fulfillable_on:R8([k8(),z()]).optional(),line_item_ids:ue(z()),type:_ne}),dxt=fe({address_country:z().optional(),address_locality:z().optional(),address_region:z().optional(),extended_address:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional(),postal_code:z().optional(),street_address:z().optional(),id:z(),address:C7.optional(),name:z().optional()}),lxt=fe({max:Or().optional(),min:Or().optional()}),O7=fe({taxonomy:z().optional(),value:z()}),k7=fe({html:z().optional(),markdown:z().optional(),plain:z().optional()}),N8=fe({amount:Or(),currency:z()}),R7=fe({alt_text:z().optional(),height:Or().optional(),type:z(),url:z(),width:Or().optional()}),pxt=fe({id:z().optional(),label:z()}),N7=fe({count:Or().optional(),scale_max:Or(),scale_min:Or().optional(),value:Or()}),TOe=fe({available:wd().optional(),status:z().optional()}),fxt=TOe,IOe=fe({type:z(),value:z()}),mxt=IOe,hxt=fe({id:z(),match:z().optional()}),xne=fe({id:z().optional(),label:z(),name:z()}),POe=xne,COe=fe({links:ue(Ny).optional(),name:z().optional()}),yxt=COe,OOe=fe({unit:z(),value:Or()});var gxt=OOe,bxt=fe({cursor:z().optional(),limit:Or().optional()}),_xt=fe({cursor:z().optional(),has_next_page:wd(),total_count:Or().optional()}),vxt=fe({handlers:ue(DAt).optional()}),wxt=fe({a2a:HAt.optional(),embedded:$At.optional(),mcp:FAt.optional(),rest:VAt.optional(),spec:z(),version:z()}),M8=fe({item:KAt,quantity:Or()}),Ext=fe({billing_address:C7.optional(),credential:gM.optional(),display:Xt(z(),Ed()).optional(),handler_id:z(),id:z(),type:z(),selected:wd().optional()}),B7=fe({id:z().optional(),item:WAt,parent_id:z().optional(),quantity:Or()}),_M=fe({instruments:ue(Ext).optional()}),Axt=_M,j7=_M,q8=_M,vM=_M,S6=fe({id:z(),item:xOe,parent_id:z().optional(),quantity:Or(),totals:ue(bM)}),By=fe({amount:Or(),display_text:z().optional(),type:z(),lines:ue(GAt).optional()}),Ll=fe({capabilities:Xt(z(),ue(JAt)),version:z()}),xxt=fe({description:z().optional(),id:z(),line_items:ue(YAt).optional(),occurred_at:hu.date(),status:jAt,totals:ue(bM).optional(),type:z()}),Sxt=fe({carrier:z().optional(),description:z().optional(),id:z(),line_items:ue(ZAt),occurred_at:hu.date(),tracking_number:z().optional(),tracking_url:z().optional(),type:z()}),Txt=fe({description:z().optional(),destination:C7,fulfillable_on:z().optional(),id:z(),line_items:ue(XAt),method_type:UAt}),Ixt=fe({id:z(),item:xOe,parent_id:z().optional(),quantity:QAt,status:MAt,totals:ue(bM)}),WMr=fe({payment_data:ext}),GMr=fe({ap2:txt.optional()}),JMr=fe({attribution:Xt(z(),z()).optional(),buyer:Ta.optional(),context:fo.optional(),continue_url:z().optional(),currency:z(),expires_at:hu.date().optional(),id:z(),line_items:ue(S6),links:ue(Ny),messages:ue(z0).optional(),order:U8.optional(),payment:q8.optional(),signals:Vi.optional(),status:j8,totals:ue(By),ucp:Ll,ap2:rxt.optional()}),Sne=fe({email:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional(),consent:ixt.optional()}),Pxt=Sne,Cxt=Sne,kOe=fe({attribution:Xt(z(),z()).optional(),buyer:Ta.optional(),context:fo.optional(),line_items:ue(B7),payment:vM.optional(),signals:Vi.optional(),discounts:oxt.optional()}),Oxt=fe({allocations:ue(sxt).optional(),amount:Or(),automatic:wd().optional(),code:z().optional(),eligibility:z().optional(),method:qAt.optional(),priority:Or().optional(),provisional:wd().optional(),title:z()}),ROe=fe({id:z(),line_item_ids:ue(z()),options:ue(cxt).optional(),selected_option_id:R8([k8(),z()]).optional()}),kxt=fe({destinations:ue(dxt).optional(),groups:ue(ROe).optional(),id:z(),line_item_ids:ue(z()),selected_destination_id:R8([k8(),z()]).optional(),type:_ne}),YMr=fe({attribution:Xt(z(),z()).optional(),buyer:Ta.optional(),context:fo.optional(),line_items:ue(M8),signals:Vi.optional()}),ZMr=fe({attribution:Xt(z(),z()).optional(),buyer:Ta.optional(),context:fo.optional(),id:z(),line_items:ue(B7),signals:Vi.optional()}),XMr=fe({attribution:Xt(z(),z()).optional(),buyer:Ta.optional(),context:fo.optional(),continue_url:z().optional(),currency:z(),expires_at:hu.date().optional(),id:z(),line_items:ue(S6),links:ue(Ny).optional(),messages:ue(z0).optional(),signals:Vi.optional(),totals:ue(By),ucp:Ll}),Rxt=fe({attribution:Xt(z(),z()).optional(),buyer:Ta.optional(),context:fo.optional(),line_items:ue(B7),payment:vM.optional(),signals:Vi.optional()}),NOe=Rxt,QMr=fe({attribution:Xt(z(),z()).optional(),buyer:Ta.optional(),context:fo.optional(),continue_url:z().optional(),currency:z(),expires_at:hu.date().optional(),id:z(),line_items:ue(S6),links:ue(Ny),messages:ue(z0).optional(),order:U8.optional(),payment:q8.optional(),signals:Vi.optional(),status:j8,totals:ue(By),ucp:Ll,cart_id:z().optional()}),Tne=fe({categories:ue(z()).optional(),price:lxt.optional()}),B8=fe({max:N8,min:N8}),Ine=fe({name:z(),values:ue(pxt)}),BOe=fe({amount:Or(),currency:z(),measure:OOe,reference:gxt}),Nxt=BOe,eqr=fe({attribution:Xt(z(),z()).optional(),context:vne.optional(),filters:Tne.optional(),id:z(),preferences:ue(z()).optional(),selected:ue(POe).optional(),signals:wne.optional()}),tqr=fe({attribution:Xt(z(),z()).optional(),context:vne.optional(),filters:Tne.optional(),pagination:bxt.optional(),query:z().optional(),signals:wne.optional()}),Bxt=fe({capabilities:ue(zAt),services:Xt(z(),wxt),version:z()}),rqr=fe({attribution:Xt(z(),z()).optional(),payment:Axt,signals:Vi.optional()}),jOe=fe({attribution:Xt(z(),z()).optional(),buyer:Ta.optional(),context:fo.optional(),continue_url:z().optional(),currency:z(),expires_at:hu.date().optional(),id:z(),line_items:ue(S6),links:ue(Ny),messages:ue(z0).optional(),order:U8.optional(),payment:q8.optional(),signals:Vi.optional(),status:j8,totals:ue(By),ucp:Ll}),jxt=fe({events:ue(Sxt).optional(),expectations:ue(Txt).optional()}),UOe=fe({attribution:Xt(z(),z()).optional(),buyer:Sne.optional(),context:fo.optional(),line_items:ue(M8),payment:j7.optional(),signals:Vi.optional()}),MOe=fe({attribution:Xt(z(),z()).optional(),buyer:Cxt.optional(),context:fo.optional(),line_items:ue(B7),payment:vM.optional(),signals:Vi.optional()}),qOe=fe({attribution:Xt(z(),z()).optional(),buyer:Pxt.optional(),context:fo.optional(),continue_url:z().optional(),currency:z(),expires_at:hu.date().optional(),id:z(),line_items:ue(S6),links:ue(Ny),messages:ue(z0).optional(),order:U8.optional(),payment:q8.optional(),signals:Vi.optional(),status:j8,totals:ue(By),ucp:Ll}),DOe=fe({attribution:Xt(z(),z()).optional(),buyer:Ta.optional(),context:fo.optional(),line_items:ue(M8),payment:j7.optional(),signals:Vi.optional(),discounts:SOe.optional()}),Uxt=fe({applied:ue(Oxt).optional(),codes:ue(z()).optional()}),Mxt=fe({destinations:ue(axt).optional(),groups:ue(ROe).optional(),line_item_ids:ue(z()).optional(),selected_destination_id:R8([k8(),z()]).optional(),type:_ne}),qxt=fe({available_methods:ue(uxt).optional(),methods:ue(kxt).optional()}),LOe=fe({attribution:Xt(z(),z()).optional(),buyer:Ta.optional(),context:fo.optional(),line_items:ue(M8),payment:j7.optional(),signals:Vi.optional(),cart_id:z().optional()}),nqr=fe({attribution:Xt(z(),z()).optional(),context:vne.optional(),filters:Tne.optional(),ids:ue(z()),signals:wne.optional()}),Dxt=fe({availability:TOe.optional(),barcodes:ue(IOe).optional(),categories:ue(O7).optional(),description:k7,handle:z().optional(),id:z(),list_price:N8.optional(),media:ue(R7).optional(),metadata:Xt(z(),Ed()).optional(),options:ue(xne).optional(),price:N8,rating:N7.optional(),seller:COe.optional(),sku:z().optional(),tags:ue(z()).optional(),title:z(),unit_price:BOe.optional(),url:z().optional(),inputs:ue(hxt)}),zOe=fe({availability:fxt.optional(),barcodes:ue(mxt).optional(),categories:ue(O7).optional(),description:k7,handle:z().optional(),id:z(),list_price:N8.optional(),media:ue(R7).optional(),metadata:Xt(z(),Ed()).optional(),options:ue(xne).optional(),price:N8,rating:N7.optional(),seller:yxt.optional(),sku:z().optional(),tags:ue(z()).optional(),title:z(),unit_price:Nxt.optional(),url:z().optional()}),Lxt=fe({categories:ue(O7).optional(),description:k7,handle:z().optional(),id:z(),list_price_range:B8.optional(),media:ue(R7).optional(),metadata:Xt(z(),Ed()).optional(),options:ue(Ine).optional(),price_range:B8,rating:N7.optional(),tags:ue(z()).optional(),title:z(),url:z().optional(),variants:ue(zOe)}),iqr=fe({payment:vxt.optional(),signing_keys:ue(LAt).optional(),ucp:Bxt}),HOe=fe({attribution:Xt(z(),z()).optional(),buyer:Ta.optional(),context:fo.optional(),line_items:ue(M8),payment:j7.optional(),signals:Vi.optional()}),zxt=fe({adjustments:ue(xxt).optional(),attribution:Xt(z(),z()).optional(),checkout_id:z(),currency:z(),fulfillment:jxt,id:z(),label:z().optional(),line_items:ue(Ixt),messages:ue(z0).optional(),permalink_url:z(),totals:ue(By),ucp:Ll}),$Oe=fe({attribution:Xt(z(),z()).optional(),buyer:Ta.optional(),context:fo.optional(),continue_url:z().optional(),currency:z(),expires_at:hu.date().optional(),id:z(),line_items:ue(S6),links:ue(Ny),messages:ue(z0).optional(),order:U8.optional(),payment:q8.optional(),signals:Vi.optional(),status:j8,totals:ue(By),ucp:Ll,discounts:Uxt.optional()}),FOe=fe({methods:ue(Mxt).optional()}),VOe=fe({attribution:Xt(z(),z()).optional(),buyer:Ta.optional(),context:fo.optional(),line_items:ue(B7),payment:vM.optional(),signals:Vi.optional(),fulfillment:FOe.optional()}),KOe=fe({attribution:Xt(z(),z()).optional(),buyer:Ta.optional(),context:fo.optional(),continue_url:z().optional(),currency:z(),expires_at:hu.date().optional(),id:z(),line_items:ue(S6),links:ue(Ny),messages:ue(z0).optional(),order:U8.optional(),payment:q8.optional(),signals:Vi.optional(),status:j8,totals:ue(By),ucp:Ll,fulfillment:qxt.optional()}),Hxt=fe({categories:ue(O7).optional(),description:k7,handle:z().optional(),id:z(),list_price_range:B8.optional(),media:ue(R7).optional(),metadata:Xt(z(),Ed()).optional(),options:ue(Ine).optional(),price_range:B8,rating:N7.optional(),tags:ue(z()).optional(),title:z(),url:z().optional(),variants:ue(Dxt)}),$xt=fe({options:ue(Ine).optional(),selected:ue(POe).optional(),categories:ue(O7).optional(),description:k7,handle:z().optional(),id:z(),list_price_range:B8.optional(),media:ue(R7).optional(),metadata:Xt(z(),Ed()).optional(),price_range:B8,rating:N7.optional(),tags:ue(z()).optional(),title:z(),url:z().optional(),variants:ue(zOe)}),oqr=fe({messages:ue(Ene).optional(),pagination:_xt.optional(),products:ue(Lxt),ucp:Ll}),WOe=fe({attribution:Xt(z(),z()).optional(),buyer:Ta.optional(),context:fo.optional(),line_items:ue(M8),payment:j7.optional(),signals:Vi.optional(),fulfillment:FOe.optional()}),sqr=fe({messages:ue(Ene).optional(),products:ue(Hxt),ucp:Ll}),aqr=fe({messages:ue(Ene).optional(),product:$xt,ucp:Ll});var lqr=gM.extend({token:Lr.string().optional()}),Fxt=Lr.object({webhook_url:Lr.string().url().optional()}),GOe=jOe.extend(KOe.pick({fulfillment:!0}).shape).extend($Oe.pick({discounts:!0}).shape).extend(qOe.pick({buyer:!0}).shape).extend({platform:Fxt.optional()}),JOe=HOe.extend(WOe.pick({fulfillment:!0}).shape).extend(DOe.pick({discounts:!0}).shape).extend(UOe.pick({buyer:!0}).shape).extend(LOe.pick({cart_id:!0}).shape),YOe=NOe.extend(VOe.pick({fulfillment:!0}).shape).extend(kOe.pick({discounts:!0}).shape).extend(MOe.pick({buyer:!0}).shape);pd();async function wM(e,t,r){let n=e.headers.get("content-length");if(n!==null){let c=Number(n);if(Number.isSafeInteger(c)&&c>t)throw new Error(r)}if(!e.body)return"";let i=e.body.getReader(),o=new TextDecoder,s=0,a="";try{for(;;){let{done:c,value:u}=await i.read();if(c)break;if(s+=u.byteLength,s>t){try{await i.cancel()}catch{}throw new Error(r)}a+=o.decode(u,{stream:!0})}return a+o.decode()}finally{i.releaseLock()}}function EM(e,t){let r=new AbortController,n=()=>r.abort(t?.reason);t?.aborted?n():t?.addEventListener("abort",n,{once:!0});let i=setTimeout(()=>r.abort(),e);return{signal:r.signal,cleanup:()=>{clearTimeout(i),t?.removeEventListener("abort",n)}}}var Vxt=3e4,ZOe=2*1024*1024,zl=class extends Error{constructor(r,n,i){super(r);this.rpcCode=n;this.httpStatus=i;this.name="UcpRpcError"}rpcCode;httpStatus};function XOe(e,t){let r=new URL(e);if(r.protocol!=="https:")throw new Error(`${t} must use HTTPS`);if(r.username||r.password)throw new Error(`${t} must not contain embedded credentials`);if(r.hash)throw new Error(`${t} must not contain a fragment`);return r}function QOe(e,t){if(!/^[A-Z]{3}$/.test(String(e.currency??"")))throw new Error("UCP checkout input requires an uppercase ISO 4217 currency");if(!Array.isArray(e.line_items)||e.line_items.length===0)throw new Error("UCP checkout input requires at least one line item");if(Object.hasOwn(e,"id"))throw new Error("UCP checkout input must not contain an id; pass it as a top-level argument");if(!(t==="create"?JOe:YOe).safeParse(e).success)throw new Error(`UCP ${t} checkout input failed schema validation`);return e}function Kxt(e){if(!e||typeof e!="object")return!1;let t=e;if(t.jsonrpc!=="2.0"||!Object.hasOwn(t,"id")||t.id!==null&&typeof t.id!="string"&&typeof t.id!="number")return!1;let r=Object.hasOwn(t,"result"),n=Object.hasOwn(t,"error");if(r===n)return!1;if(!n)return!0;let i=t.error;return!!i&&typeof i=="object"&&!Array.isArray(i)&&typeof i.code=="number"&&typeof i.message=="string"}function eke(e,t,r,n){try{e[t](r,n)}catch{}}function Wxt(e){if(!e||typeof e!="object")return e;let t=e,r=t.ucp;if(!r||typeof r!="object")return e;let n=r.capabilities;return!n||typeof n!="object"||Array.isArray(n)?e:{...t,ucp:{...r,capabilities:Object.fromEntries(Object.entries(n).map(([i,o])=>[i,Array.isArray(o)?o.map(s=>s&&typeof s=="object"?{...s,name:i}:s):o]))}}}var AM=class{endpoint;platformProfileUrl;fetchImpl;signal;timeoutMs;boundaryLogger;requestId=1;constructor(t){this.endpoint=XOe(t.endpoint,"UCP MCP endpoint").toString(),this.platformProfileUrl=XOe(t.platformProfileUrl,"UCP platform profile URL").toString(),this.fetchImpl=t.fetch??fetch,this.signal=t.signal,this.timeoutMs=t.timeoutMs??Vxt,this.boundaryLogger=t.logger??Ce}async createCheckout(t){return await this.callCheckout("create_checkout",{meta:this.metadata(),checkout:QOe(t,"create")})}async getCheckout(t){if(!t)throw new Error("UCP checkout id is required");return await this.callCheckout("get_checkout",{meta:this.metadata(),id:t})}async updateCheckout(t,r){if(!t)throw new Error("UCP checkout id is required");return await this.callCheckout("update_checkout",{meta:this.metadata(),id:t,checkout:QOe(r,"update")})}metadata(){return{"ucp-agent":{profile:this.platformProfileUrl}}}async callCheckout(t,r){let n=this.requestId++,i=EM(this.timeoutMs,this.signal),o=(0,tke.randomUUID)(),s=new URL(this.endpoint).origin,a=Date.now(),c;try{let u=await this.fetchImpl(this.endpoint,{method:"POST",redirect:"error",headers:{accept:"application/json","content-type":"application/json"},body:JSON.stringify({jsonrpc:"2.0",id:n,method:"tools/call",params:{name:t,arguments:r}}),signal:i.signal});c=u.status;let d;try{d=await wM(u,ZOe,"UCP MCP response exceeds the 2 MiB limit")}catch(m){throw m instanceof Error&&m.message==="UCP MCP response exceeds the 2 MiB limit"?new zl(m.message,void 0,u.status):m}if(Buffer.byteLength(d)>ZOe)throw new zl("UCP MCP response exceeds the 2 MiB limit",void 0,u.status);let l;try{l=JSON.parse(d)}catch{throw new zl("UCP MCP response is not valid JSON",void 0,u.status)}if(!Kxt(l))throw new zl("UCP MCP response is not a valid JSON-RPC envelope",void 0,u.status);if(l.id!==n)throw new zl("UCP MCP response id does not match the request",void 0,u.status);if("error"in l)throw new zl(`UCP MCP error ${l.error.code}: ${l.error.message}`,l.error.code,u.status);if(!u.ok)throw new zl(`UCP MCP request failed with HTTP ${u.status}`,void 0,u.status);let p=l.result;if(!p?.structuredContent)throw new zl("UCP MCP response is missing result.structuredContent");if(!GOe.safeParse(Wxt(p.structuredContent)).success)throw new zl("UCP checkout response failed schema validation");return eke(this.boundaryLogger,"info","ucp:checkout_rpc",{correlationId:o,endpointOrigin:s,rpcMethod:t,httpStatus:c,elapsedMs:Date.now()-a}),p.structuredContent}catch(u){throw eke(this.boundaryLogger,"warn","ucp:checkout_rpc_failed",{correlationId:o,endpointOrigin:s,rpcMethod:t,...c===void 0?{}:{httpStatus:c},elapsedMs:Date.now()-a,errorClass:u instanceof Error?u.name:"UnknownError"}),u}finally{i.cleanup()}}};var nke=require("node:crypto");pd();var SM="2026-04-08",Gxt="dev.ucp.shopping",Jxt="dev.ucp.shopping.checkout",Yxt=1024*1024,Zxt=1e4,Xxt="https://ucp.dev",U7=Lr.string().url().refine(e=>{let t=new URL(e);return t.protocol==="https:"&&!t.username&&!t.password},"must be an HTTPS URL without embedded credentials"),Qxt=Lr.object({version:Lr.string().regex(/^\d{4}-\d{2}-\d{2}$/),spec:U7,schema:U7,transport:Lr.enum(["rest","mcp","a2a","embedded"]),endpoint:U7.optional()}).passthrough(),e9t=Lr.object({version:Lr.string().regex(/^\d{4}-\d{2}-\d{2}$/),spec:U7,schema:U7,extends:Lr.union([Lr.string(),Lr.array(Lr.string()).min(1)]).optional()}).passthrough(),t9t=Lr.object({ucp:Lr.object({version:Lr.string().regex(/^\d{4}-\d{2}-\d{2}$/),services:Lr.record(Lr.array(Qxt)),capabilities:Lr.record(Lr.array(e9t)),payment_handlers:Lr.record(Lr.array(Lr.unknown())).optional()}).passthrough(),signing_keys:Lr.array(Lr.unknown()).optional()}).passthrough();function r9t(e,t){let r=new URL(e);if(r.protocol!=="https:")throw new Error(`${t} must use HTTPS`);if(r.username||r.password)throw new Error(`${t} must not contain embedded credentials`);if(r.pathname!=="/"||r.search||r.hash)throw new Error(`${t} must be a bare origin`);return r}function xM(e,t){if(new URL(e).origin!==Xxt)throw new Error(`${t} must be governed by the ucp.dev namespace`)}function rke(e,t,r,n){try{e[t](r,n)}catch{}}async function n9t(e,t={}){let r=r9t(e,"UCP business URL"),n=EM(t.timeoutMs??Zxt,t.signal),i=t.logger??Ce,o=(0,nke.randomUUID)(),s=Date.now(),a;try{let c=await(t.fetch??fetch)(new URL("/.well-known/ucp",r),{headers:{accept:"application/json"},redirect:"error",signal:n.signal});if(a=c.status,!c.ok)throw new Error(`UCP profile fetch failed with HTTP ${c.status}`);let u=await wM(c,Yxt,"UCP profile exceeds the 1 MiB response limit"),d;try{d=JSON.parse(u)}catch{throw new Error("UCP profile response is not valid JSON")}let l=t9t.safeParse(d);if(!l.success)throw new Error("UCP profile response does not match the 2026-04-08 profile shape");return rke(i,"info","ucp:profile_fetch",{correlationId:o,businessOrigin:r.origin,method:"GET",httpStatus:a,elapsedMs:Date.now()-s}),{businessOrigin:r.origin,profile:l.data}}catch(c){throw rke(i,"warn","ucp:profile_fetch_failed",{correlationId:o,businessOrigin:r.origin,method:"GET",...a===void 0?{}:{httpStatus:a},elapsedMs:Date.now()-s,errorClass:c instanceof Error?c.name:"UnknownError"}),c}finally{n.cleanup()}}function i9t(e){if(e.ucp.version!==SM)throw new Error(`Unsupported UCP version: ${e.ucp.version}`);let t=e.ucp.capabilities[Jxt]?.find(i=>i.version===SM);if(!t)throw new Error("Business does not advertise UCP checkout 2026-04-08");xM(t.spec,"Checkout capability spec"),xM(t.schema,"Checkout capability schema");let r=e.ucp.services[Gxt]?.find(i=>i.version===SM&&i.transport==="mcp");if(!r)throw new Error("Business does not advertise a UCP shopping MCP service");if(!r.endpoint)throw new Error("UCP shopping MCP service is missing its endpoint");xM(r.spec,"Shopping service spec"),xM(r.schema,"Shopping service schema");let n=new URL(r.endpoint);if(n.hash)throw new Error("UCP shopping MCP endpoint must not contain a fragment");return n.toString()}async function ike(e,t={}){let r=await n9t(e,t);return{...r,endpoint:i9t(r.profile),version:SM}}var o9t="https://app.visacli.sh/.well-known/ucp";function s9t(e){let t=new URL(e);if(t.protocol!=="https:"||t.username||t.password||t.hash)throw new Error("UCP platform profile URL must be HTTPS and credential-free");return t.toString()}function a9t(e,t){if(typeof e=="string")try{let r=new URL(e);r.protocol==="https:"&&!r.username&&!r.password&&t.add(r.origin.toLowerCase())}catch{}}function Pne(e,t=new Set){if(Array.isArray(e))for(let r of e)Pne(r,t);else if(e&&typeof e=="object")for(let[r,n]of Object.entries(e))r==="endpoint"?a9t(n,t):Pne(n,t);return t}function c9t(e,t,r){let n=new URL(e),i=new URL(t);if(i.protocol!=="https:"||i.username||i.password)throw new Error("UCP continuation URL must be HTTPS and credential-free");let o=i.hostname.toLowerCase(),s=n.hostname.toLowerCase();if(i.origin.toLowerCase()===n.origin.toLowerCase())return i.hash="",{url:i.toString(),sourceHost:o,targetHost:s,originRewritten:!1};let a=r.ucp.services["dev.ucp.shopping"],c=Pne(a);if(!(o.endsWith(".myshopify.com")&&c.has(i.origin.toLowerCase())))throw new Error(`Refusing cross-host UCP continuation from ${o} to ${s}`);return i.hash="",{url:i.toString(),sourceHost:o,targetHost:o,originRewritten:!1}}function ske(e){let t=Array.isArray(e.totals)?e.totals.find(a=>a&&typeof a=="object"&&a.type==="total"):void 0,r=t&&typeof t=="object"?t:void 0,n=r?.amount,o=r?.currency??e.currency;if(!Number.isSafeInteger(n)||Number(n)<0)throw new Error("UCP checkout is missing an integer totals[type=total].amount");if(o!=="USD")throw new Error(`UCP checkout handoff currently supports USD only; refusing ${String(o)} until currency exponents are implemented`);let s=Number(n);return{minor:s,decimal:`${Math.floor(s/100)}.${String(s%100).padStart(2,"0")}`,currency:o}}function u9t(e){return Array.isArray(e.messages)?e.messages.flatMap(t=>{if(!t||typeof t!="object")return[];let r=t,n={...typeof r.type=="string"?{type:r.type}:{},...typeof r.code=="string"?{code:r.code}:{},...typeof r.severity=="string"?{severity:r.severity}:{}};return Object.keys(n).length>0?[n]:[]}):[]}async function ake(e,t){if(!e.business?.trim())throw new Error("UCP business origin is required");if(!e.checkoutId?.trim())throw new Error("UCP checkout id is required");let r=await(t.discover??ike)(e.business),i=await(t.getCheckout??(async(o,s)=>await new AM({endpoint:o.endpoint,platformProfileUrl:s9t(t.platformProfileUrl??process.env.VISA_UCP_PROFILE_URL??o9t)}).getCheckout(s)))(r,e.checkoutId);if(i.id!==e.checkoutId)throw new Error("UCP checkout response id does not match the requested checkout");return{service:r,checkout:i}}async function cke(e,t={}){let{service:r,checkout:n}=await ake(e,t),i=String(n.status??"unknown");if(i==="completed")return{success:!1,status:"not_ready",checkoutId:e.checkoutId,checkoutStatus:i,reason:"checkout_already_completed"};if(i!=="requires_escalation")return{success:!1,status:"not_ready",checkoutId:e.checkoutId,checkoutStatus:i,reason:"checkout_not_escalated"};if(typeof n.continue_url!="string"||!n.continue_url)return{success:!1,status:"not_ready",checkoutId:e.checkoutId,checkoutStatus:i,reason:"missing_continue_url"};let o=ske(n),s=c9t(r.businessOrigin,n.continue_url,r.profile),a=`ucp_${(0,oke.createHash)("sha256").update([r.businessOrigin,e.checkoutId,i,o.currency,String(o.minor),s.url].join("\0")).digest("hex").slice(0,24)}`;return{success:!0,status:"ready_for_review",checkoutId:e.checkoutId,handoffId:a,checkoutStatus:"requires_escalation",amount:o,merchant:{businessOrigin:r.businessOrigin,sourceHost:s.sourceHost,targetHost:s.targetHost,originRewritten:s.originRewritten},payMerchantRequest:{action:"review",url:s.url,amount:o.decimal,currency:o.currency},messages:u9t(n),nextAction:"Copy the payMerchantRequest checkout fields unchanged to pay_merchant and include its required user_context. Show the returned merchant and exact total to the user; never authorize until they explicitly approve PAY <reviewId>."}}function d9t(e){if(!e.order||typeof e.order!="object"||Array.isArray(e.order))return null;let t=e.order;if(typeof t.id!="string"||!t.id.trim()||typeof t.permalink_url!="string"||!t.permalink_url)return null;let r;try{r=new URL(t.permalink_url)}catch{return null}return r.protocol!=="https:"||r.username||r.password||r.hash?null:{id:t.id,permalinkHost:r.hostname.toLowerCase()}}async function uke(e,t={}){if(!Number.isSafeInteger(e.expectedAmountMinor)||e.expectedAmountMinor<0)throw new Error("UCP reconciliation expectedAmountMinor must be a non-negative integer");if(e.expectedCurrency!=="USD")throw new Error("UCP reconciliation currently supports expectedCurrency USD only");let{checkout:r}=await ake(e,t),n=ske(r),i=String(r.status??"unknown");if(n.minor!==e.expectedAmountMinor)return{success:!1,status:"not_confirmed",checkoutId:e.checkoutId,checkoutStatus:i,reason:"amount_mismatch",amount:n,nextAction:"Do not retry payment. The merchant checkout total no longer matches the reviewed amount; reconcile the merchant order manually."};if(i!=="completed")return{success:!1,status:"not_confirmed",checkoutId:e.checkoutId,checkoutStatus:i,reason:"checkout_not_completed",amount:n,nextAction:"Do not retry payment. Poll this same checkout or inspect the merchant order before starting any new review."};let o=d9t(r);return o?{success:!0,status:"confirmed",checkoutId:e.checkoutId,checkoutStatus:"completed",amount:n,order:o,nextAction:"Report success only after matching this UCP order id and amount to the Visa checkout receipt."}:{success:!1,status:"not_confirmed",checkoutId:e.checkoutId,checkoutStatus:i,reason:"missing_order_confirmation",amount:n,nextAction:"Do not report purchase success or retry payment. The checkout says completed but lacks a valid merchant order confirmation."}}ay();function Cne(){return Sa()}var gd=new fd(()=>An.getSessionToken()),l9t="4.1.0-rc.51",Vqr=["","","You're ready to go! Try:","","Verified Agent:",'\u2022 "Enroll this agent" \u2192 enroll_agent','\u2022 "Show my wallet and policy" \u2192 wallet_status','\u2022 "Find a paid weather service" \u2192 wallet_discover','\u2022 "Pay this x402 service with a $0.10 maximum" \u2192 wallet_pay','\u2022 "Review this card checkout" \u2192 pay_merchant','\u2022 "Show my account status" \u2192 get_status'].join(`
|
|
20935
20935
|
`);function p9t(e){if(!e||typeof e!="string")return{opened:!1,blockedReason:"invalid_url"};let t=OT(e);if(!t)return{opened:!1,blockedReason:"invalid_url"};if(mTe())return{opened:!1,url:t,blockedReason:"suppressed"};let r=CT();if(r.headless)return Ce.info(`Browser auto-open skipped (${r.reason}). URL: ${t}`),{opened:!1,url:t,blockedReason:"headless"};let i=[Cne(),cy()].filter(s=>!!s).map(s=>cSe(t,s)).find(Boolean)??null;if(!i)return Ce.info(`Browser auto-open skipped (non-internal host). URL: ${t}`),{opened:!1,url:t,blockedReason:"non_internal_host"};let o=dSe(i);return o?((0,lke.execFile)(o.cmd,o.args,s=>{s&&Ce.warn(`Browser open failed: ${s.message}. URL: ${i}`)}),{opened:!0,url:i}):(Ce.info(`No browser command for platform "${IM.platform()}". URL: ${i}`),{opened:!1,url:i,blockedReason:"unsupported_platform"})}function f9t(){let e=!1,t;try{let n=pke.join(IM.homedir(),".claude","settings.json");if(TM.existsSync(n)){let i=JSON.parse(TM.readFileSync(n,"utf-8")),o=typeof i.statusLine=="object"?i.statusLine.command:"";e=iy(o)}}catch{}let r=Sj();return r||(t="visa-cli config hud enable"),{statusLine:e,shellHud:r,...t?{shellHudSetup:t}:{}}}async function m9t(e){let t=await gd.getStatus(e);t.hud=f9t(),!t.hud.statusLine&&!t.hud.shellHud&&(t._hud_nudge="The user has no HUD surfaces enabled. Mention once, naturally, that they can enable the Visa HUD with `visa-cli config hud enable`."),t.version=l9t;try{let r=h8();if(r){let n=await gd.getAgentTapStatus(r.identity_key.jkt);n&&(t.tap={status:n.status,registeredAt:n.registeredAt})}}catch(r){Ce.warn({component:"get-status-tap",msg:"tap_status_unavailable",error:r?.message})}return t}async function h9t(e,t){return await gd.feedback(e.message,e.transaction_id,t)}async function y9t(e){let t=await _7({api:gd,includeDev:!!e.includeDev});return{config:t.entries.map(r=>({key:r.key,value:r.value,source:r.source,hint:r.hint})),statusError:t.statusError}}var One=new Set(["auth.serverUrl"]);function M7(){return Object.keys(j_).filter(e=>!One.has(e)).sort()}function fke(e,t){let r=t==="set"?`visa-cli config set ${e}=<value>`:`visa-cli config unset ${e}`;return{success:!1,error:`${e} cannot be changed via MCP. Run \`${r}\` directly from a shell instead.`,code:"MCP_FORBIDDEN_KEY",reason:"auth-trust-boundary key \u2014 a prompt-injected agent could redirect bearer-auth API calls to an attacker host (codex CLI-001 #752).",settableKeys:M7()}}async function g9t(e){if(!e.key||typeof e.key!="string")return{success:!1,error:"key is required. Call config_list first to see available keys."};if(e.value===void 0)return{success:!1,error:"value is required. Use config_unset to remove a setting."};if(One.has(e.key))return Ce.warn("config:set:rejected:mcp-forbidden",{key:e.key}),fke(e.key,"set");Ce.info("config:set",{key:e.key});try{let t=qj(e.key,e.value);return Ce.info("config:set:success",{key:t.key,requiresRestart:t.requiresRestart}),{success:!0,key:t.key,value:t.value,requiresRestart:t.requiresRestart,path:t.path,message:t.requiresRestart?`Saved ${t.key}. Restart Claude Code for the change to take effect.`:`Saved ${t.key}.`}}catch(t){let r=t instanceof Ul?"UNKNOWN_KEY":"INVALID_VALUE",n=t instanceof Ul?`Unknown setting "${e.key}". MCP-settable keys: ${M7().join(", ")}. For auth.serverUrl, use the shell command instead.`:t.message;return Ce.warn("config:set:rejected",{key:e.key,code:r,error:n}),{success:!1,error:n,code:r,settableKeys:M7()}}}async function b9t(e){if(!e.key||typeof e.key!="string")return{success:!1,error:"key is required. Call config_list first to see which keys are currently set via settings.json."};if(One.has(e.key))return Ce.warn("config:unset:rejected:mcp-forbidden",{key:e.key}),fke(e.key,"unset");Ce.info("config:unset",{key:e.key});try{let t=Dj(e.key);return Ce.info("config:unset:success",{key:t.key,removed:t.removed}),{success:!0,key:t.key,removed:t.removed,requiresRestart:t.requiresRestart,path:t.path,message:t.removed?t.requiresRestart?`Removed ${t.key}. Restart Claude Code for the change to take effect.`:`Removed ${t.key}.`:`${t.key} was not set in settings.json \u2014 nothing to remove.`}}catch(t){let r=t instanceof Ul?"UNKNOWN_KEY":"INVALID_VALUE",n=t instanceof Ul?`Unknown setting "${e.key}". MCP-settable keys: ${M7().join(", ")}. For auth.serverUrl, use the shell command instead.`:t.message;return Ce.warn("config:unset:rejected",{key:e.key,code:r,error:n}),{success:!1,error:n,code:r,settableKeys:M7()}}}async function _9t(e=Cne(),t=!1){if(!e)return{success:!1,message:"No auth server is configured. Set auth.serverUrl before pairing this runtime."};if(!t){let r=h8();if(r){let n=r.display_name,i;if(process.env.SUBWAY_MESH==="visa"&&n){let{registerOnVisaMeshIfEnabled:s}=await Promise.resolve().then(()=>(ZU(),DCe));i=await s(n)}Ce.info("agent:enroll_already_connected",{keyBound:!0,meshRegistered:i});let o=i===void 0?"":i?` Registered ${n??"this device"} on the .visa mesh.`:` Could not reach the .visa mesh \u2014 run \`visa register ${n??"<name>"}\` to join it.`;return{success:!0,alreadyConnected:!0,...n?{name:n}:{},keyBound:!0,...i!==void 0?{meshRegistered:i}:{},message:`This device is already connected${n?` as ${n}`:""} \u2014 nothing to pair. To add or change spending on this identity, approve it in your account settings (agent card \u2192 Spend).`+o+' Call enroll_agent with {"action":"start","force":true} to start a brand-new enrollment anyway.'}}}try{let r=await c7({authUrl:e,runtime:"visa-cli-mcp",contextLabel:"Pair this MCP runtime"});Ce.info("agent:pairing_open",{pairingId:r.pairingId,agentId:r.agentId});let n=p9t(r.authorizationUrl),i=n.url??r.authorizationUrl;return{success:!0,protocolVersion:r.protocolVersion,pairingId:r.pairingId,agentId:r.agentId,requestKeyFingerprint:r.requestKeyFingerprint,opened:n.opened,requiresBrowser:!n.opened,browserUrl:i,expiresAt:r.expiresAt,message:n.opened?`Opened the authorization page for agent ${r.agentId}. Compare public request-key fingerprint ${r.requestKeyFingerprint} exactly, approve the runtime, then call enroll_agent with {"action":"claim"}. Pairing establishes identity only; payment methods and communication channels are configured separately.`:`Open ${i} to approve agent ${r.agentId}. Compare public request-key fingerprint ${r.requestKeyFingerprint} exactly, then call enroll_agent with {"action":"claim"}. Pairing establishes identity only; payment methods and communication channels are configured separately.`}}catch(r){return{success:!1,message:r instanceof Error?r.message:String(r)}}}async function v9t(e=Cne()){if(!e)return{success:!1,message:"No auth server is configured. Set auth.serverUrl before pairing this runtime."};let t=await u7({authUrl:e});switch(Ce.info("agent:enroll_claim",{status:t.status}),t.status){case"activated":return{success:!0,status:t.status,protocolVersion:t.protocolVersion,pairingId:t.pairingId,agentId:t.agentId,displayName:t.displayName,identityKeyJkt:t.identityKeyJkt,message:`Agent ${t.displayName} (${t.agentId}) is paired to this runtime. Its exportable Ed25519 private identity key remains in an owner-only local file. Copying that file transfers identity proof; losing it blocks new proofs because same-agent key recovery is not available yet. Payment methods and communication channels are configured separately.`};case"no_pending":return{success:!1,message:'No pairing is in progress on this device \u2014 call enroll_agent with {"action":"start"} first.'};case"not_ready":return{success:!1,status:t.status,protocolVersion:t.protocolVersion,pairingId:t.pairingId,agentId:t.agentId,likelyExpired:t.likelyExpired,message:t.likelyExpired?"This pairing has likely expired. Start a fresh pairing ceremony.":`Authorization is not complete for agent ${t.agentId}. Approve the browser request, then claim again.`};case"error":return{success:!1,message:t.message}}}async function dke(){if(await An.clearAll(),!!S0())try{await Kj()}catch(e){Ce.warn("reset:touchid_key_delete_failed",{error:e instanceof Error?e.message:String(e)})}}async function w9t(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return{success:!1,message:"Please confirm by setting confirm: true to reset"};if(Ce.info("reset:attempt"),e.localOnly)return await dke(),Ce.info("reset:success",{localOnly:!0}),{success:!0,message:"Device account state reset locally. The account session credential and local biometric key were removed. Stored agent identity records and server-side agents were not changed. Agent pairing is not account-session or biometric recovery."};try{await gd.logout(void 0,t)}catch{}return await dke(),Ce.info("reset:success"),{success:!0,message:"Device account state reset. The server session, local account credential, and local biometric key were removed. Stored agent identity records and server-side agents were not changed. Agent pairing is not account-session or biometric recovery."}}async function E9t(e){if(!e.name)return{success:!1,error:"name is required"};try{let{registerName:t,ensureMailbox:r}=await Promise.resolve().then(()=>(s6(),y7)),n=await t(e.name);return await r(e.name),{success:!0,...n}}catch(t){let{VisaBindingRequiredError:r}=await Promise.resolve().then(()=>(WT(),M7e));return t instanceof r?{success:!1,binding_required:!0,reason:t.reason,recovery_tool:null,error:t.message,message:`${t.message} Pairing alone does not provision a .visa name or TAP/channel binding.`}:{success:!1,error:t instanceof Error?t.message:String(t)}}}async function A9t(e){if(!e.name)return{success:!1,error:"name is required"};try{let{resolveMeshName:t}=await Promise.resolve().then(()=>(s6(),y7));return{success:!0,...await t(e.name)}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async function x9t(e){if(!e.to||!e.text)return{success:!1,error:"to and text are required"};try{let{sendVia:t,resolveActingName:r}=await Promise.resolve().then(()=>(s6(),y7)),n=e.as??r(void 0);return{success:!0,...await t(n,e.to,e.text)}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async function S9t(e){try{let{readInbox:t,resolveActingName:r,meshName:n}=await Promise.resolve().then(()=>(s6(),y7)),i=e.as??r(void 0),o=await t(i,e.limit??20,!!e.clear);return{success:!0,as:n(i),count:o.length,messages:o}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}var D8=class{static async subwayRegister(t){return E9t(t||{})}static async subwayFind(t){return A9t(t||{})}static async subwaySend(t){return x9t(t||{})}static async subwayInbox(t){return S9t(t||{})}static async getStatus(t){return m9t(t)}static async feedback(t,r){return h9t(t,r)}static async configList(t){return y9t(t||{})}static async configSet(t){return g9t(t||{})}static async configUnset(t){return b9t(t||{})}static async reset(t,r){return w9t(t,r)}static async enrollAgent(t={},r){let n=t?.action??"start";return n==="start"?_9t(void 0,t?.force===!0):n==="claim"?v9t():{success:!1,message:`Unknown enroll_agent action ${JSON.stringify(n)}. Use "start" (default \u2014 opens identity-pairing approval) or "claim" (activates the approved identity on this runtime).`}}static async payMerchant(t={},r){return pOe(t)}static async ucpCheckoutHandoff(t,r){return Py("ucp_checkout_handoff")&&(await w7(),Py("ucp_checkout_handoff"))?{success:!1,message:"ucp_checkout_handoff requires the checkout_agent_access flag on your account. Ask an admin to enable it, then retry."}:cke(t)}static async ucpCheckoutReconcile(t,r){if(Py("ucp_checkout_reconcile")&&(await w7(),Py("ucp_checkout_reconcile")))return{success:!1,message:"ucp_checkout_reconcile requires the checkout_agent_access flag on your account. Ask an admin to enable it, then retry."};let n=Date.now(),i=(()=>{try{return new URL(t.business).hostname}catch{return"invalid"}})();Ce.info("ucp_checkout_reconcile:start",{businessHost:i});try{let o=await uke(t);return Ce.info("ucp_checkout_reconcile:complete",{businessHost:i,checkoutStatus:o.checkoutStatus,reconciliationStatus:o.status,durationMs:Date.now()-n}),o}catch(o){throw Ce.warn("ucp_checkout_reconcile:failed",{businessHost:i,durationMs:Date.now()-n,errorName:o instanceof Error?o.name:"unknown"}),o}}static async payMerchantStatus(t={},r){return lOe(t)}static async startCardMandate(t={},r){return fOe(t)}static async submitFeedback(t,r,n){Ce.info("feedback:submit",{length:t.length,transactionId:r,hasContext:!!n});try{let i=await gd.submitFeedback(t,r,n);return Ce.info("feedback:submitted",{transactionId:r}),i}catch(i){let o=i instanceof Error?i.message:"Unknown error";throw Ce.error("feedback:error",{error:o,transactionId:r}),i}}static async getFeedback(t,r){Ce.info("feedback:list",{limit:t||20});try{let n=await gd.getFeedback(t,r);return Ce.info("feedback:listed",{count:n?.feedback?.length||0}),n}catch(n){let i=n instanceof Error?n.message:"Unknown error";throw Ce.error("feedback:error",{error:i}),n}}};async function mke(e,t,r,n){let i=n.log??console.log,o=n.error??console.error,s=n.exit??(c=>process.exit(c)),a=n.env??process.env;try{let c=r.currency,u=r.rail,d=await n.payMerchant({action:"review",rail:u,url:e,amount:t,currency:c});if(!d||d.success!==!0)return o(d?.message||"Review failed."),void s(1);if(i(d.message),!r.submit){i("Review only \u2014 nothing charged. Re-run with --submit to authorize (passkey required).");return}let l=d.reviewId;if(typeof l!="string"||l.length===0)return o("Review did not return a usable reviewId \u2014 cannot authorize a charge. Nothing charged."),void s(1);a.CHECKOUT_AGENT_ALLOW_SUBMIT="1";let p=await n.payMerchant({action:"pay",rail:u,url:e,amount:t,currency:c,confirm:`PAY ${l}`});if(i(p?.message),!p||p.success!==!0)return void s(1)}catch(c){return o("Error:",c.message),void s(1)}}var hke=require("node:fs/promises"),yke=require("node:os"),gke=require("node:path");async function bke(e,t,r){let n=r.log??console.log,i=r.error??console.error,o=r.exit??(s=>process.exit(s));try{let s={...t.agent?{agent:t.agent}:{},ceiling:e,...t.perTransaction?{perTransaction:t.perTransaction}:{},...t.intent?{intent:t.intent}:{}},a=await r.startCardMandate(s);if(!a||a.success!==!0)return i(a?.message||"Could not create the mandate."),void o(1);n(a.message),n(""),n(` mandate: ${a.mandateId}`),n(` ceiling: ${a.ceiling} ${a.currency}`),typeof a.remainingMinor=="number"&&n(` remaining: ${E8(a.remainingMinor,a.currency??"USD")}`),n(" scope: eligible retail merchants (network category 5999)"),typeof a.maxPurchases=="number"&&n(` purchases: up to ${a.maxPurchases}`),a.expiresAt&&n(` expires: ${a.expiresAt}`)}catch(s){return i("Error:",s.message),void o(1)}}var T9t=300*1e3;function I9t(){return process.env.VISA_CARD_MANDATE_LEDGER_FILE??(0,gke.join)((0,yke.homedir)(),".visa-mcp","card-mandates.json")}async function P9t(){try{let e=JSON.parse(await(0,hke.readFile)(I9t(),"utf8"));return!e||!Array.isArray(e.mandates)?{mandates:[]}:e}catch(e){if(e.code==="ENOENT")return null;throw e}}function C9t(e,t){let r=(e.reservations??[]).reduce((n,i)=>{let o=i.reservedAt!==void 0?Date.parse(i.reservedAt):NaN;return!Number.isFinite(o)||t-o>T9t?n:n+i.amountMinor},0);return e.ceilingMinor-e.spentMinor-r}function O9t(e){return e.length>18?`${e.slice(0,8)}\u2026${e.slice(-6)}`:e}async function _ke(e={}){let t=e.log??console.log,r=e.error??console.error,n=e.exit??(s=>process.exit(s)),i=e.readLedger??P9t,o=(e.now??(()=>new Date))().getTime();try{let c=((await i())?.mandates??[]).filter(u=>{let d=Date.parse(u.expiresAt);return Number.isFinite(d)&&d>o});if(c.length===0){t("No active mandates. Create one with: visa-cli mandate start <ceiling>");return}t(`Active mandates
|
|
20936
20936
|
`);for(let u of c){if(t(` ${u.mandateId}`),t(u.crossMerchant?" scope: eligible retail merchants (network category 5999)":` merchant: ${u.merchantName||u.merchantHost||"(unknown)"}`),u.agentJkt&&t(` request key: ${O9t(u.agentJkt)}`),t(` remaining: ${E8(C9t(u,o),u.currencyCode)}`),Number.isSafeInteger(u.maxDraws)&&u.maxDraws>0){let d=(u.draws??[]).filter(l=>l.status==="committed").length;t(` credentials issued: ${d} of ${u.maxDraws}`)}t(` expires: ${u.expiresAt}`),u.unhonoredAt&&t(` unhonored: yes (disabled ${u.unhonoredAt}) \u2014 next checkout uses a fresh tap`),u.registerFailedAt&&t(` register: FAILED (${u.registerFailedAt}) \u2014 not used for tap-free draws; next checkout uses a fresh tap`)}}catch(s){return r("Error:",s.message),void n(1)}}pd();MT();function vke(e,t=process.stderr){if(oy()||!e?.updateAvailable)return!1;let{latestVersion:r}=e.updateAvailable;if(!r)return!1;let n=`Update available: v${r}. Run: visa-cli update`;return t.write(`
|
|
20937
20937
|
\x1B[33m\u2191 ${n}\x1B[0m
|
|
@@ -20947,7 +20947,7 @@ If building from source, run native/build-win.bat first.`);tn.mkdirSync(uy,{recu
|
|
|
20947
20947
|
`)}function WNr(e,t){return e.length<=t?e:`${e.slice(0,Math.max(t-1,0))}\u2026`}function GNr(e){if(e.length===0)return"No matching paid services.";let t=["ID","Protocol","Price","Health","Service"],r=e.map(i=>[i.id,i.protocol,i.listedPriceUsd?`$${i.listedPriceUsd}`:"runtime",i.health,WNr(i.name,48)]),n=t.map((i,o)=>Math.max(i.length,...r.map(s=>s[o].length)));return[t,...r].map(i=>i.map((o,s)=>o.padEnd(n[s])).join(" ").trimEnd()).join(`
|
|
20948
20948
|
`)}function JNr(){let e=jU.map(r=>({id:r.id,detected:rre(r),connected:ure(r)})),t={id:Math.max(6,...e.map(r=>r.id.length))};return[`${"Client".padEnd(t.id)} Detected Connected`,...e.map(r=>`${r.id.padEnd(t.id)} ${(r.detected?"yes":"no").padEnd(8)} ${r.connected?"yes":"no"}`)].join(`
|
|
20949
20949
|
`)}function YNr(e,t){if(e==="find"){let r=t.listings;C9e(GNr(r));return}if(e==="connections"){C9e(JNr());return}C9e(JSON.stringify(t,null,2))}async function rf(e,t,r){let n="table";try{n=KNr(t);let i=await r();n==="table"?YNr(e,i):Nne(Eke(e,{data:i}),n)}catch(i){let o=i instanceof Error?i.message:String(i);n==="table"?process.stderr.write(`Error: ${o}
|
|
20950
|
-
`):Nne(Ake(e,o),n),process.exitCode=1}}function ZNr(){this.help({error:!1})}function y_t(e){tf(e.command("find <intent>").description("Find payable services by outcome; discovery never spends money.").option("--provider <provider>",`Directory provider: all, ${ree.join(", ")}`,"all").option("--protocol <protocol>","Filter by payment protocol: x402, mpp, l402, vic").option("--max <usd>","Only show listings at or below this advisory price").option("--limit <count>","Maximum results","10")).action(async(r,n)=>{await rf("find",n,async()=>{let i=["all",...ree];if(!i.includes(n.provider))throw new Error(`--provider must be one of: ${i.join(", ")}`);let o=["x402","mpp","l402","vic"];if(n.protocol&&!o.includes(n.protocol))throw new Error(`--protocol must be one of: ${o.join(", ")}`);let s=Number(n.limit);if(!Number.isInteger(s)||s<1||s>50)throw new Error("--limit must be an integer between 1 and 50");return T_().find({intent:r,provider:n.provider,protocol:n.protocol,maxUsd:n.max,limit:s})})}),tf(e.command("inspect [listing-id]").description("Inspect a directory listing or fetch a fresh x402 challenge without paying.").option("--url <url>","Inspect an advanced direct endpoint instead of a listing").option("--input <source>","POST JSON from @file or - for stdin")).action(async(r,n)=>{await rf("inspect",n,()=>T_().inspect({listingId:r,url:n.url,bodyJson:h_t(n.input)}))}),tf(e.command("pay [listing-id]").description("Disclose a bounded x402 authorization; the outcome remains reconciling until trusted settlement evidence exists.").option("--url <url>","Pay an advanced direct endpoint instead of a listing").requiredOption("--max <usd>","Hard USD ceiling; the wallet refuses a pricier challenge").option("--input <source>","POST JSON from @file or - for stdin")).action(async(r,n)=>{await rf("pay",n,()=>T_().pay({listingId:r,url:n.url,maxUsd:n.max,bodyJson:h_t(n.input)}))});let t=e.command("wallet").description("Inspect, fund, and constrain the principal v4 wallet.").action(ZNr);tf(t.command("show").description("Show wallet, network, policy, and budgets.")).action(async r=>rf("wallet show",r,()=>T_().status())),tf(t.command("fund").description("Show the wallet funding address and network guidance.")).action(async r=>rf("wallet fund",r,()=>T_().fund())),tf(t.command("limits").description("Show or update wallet spending limits.").option("--per-transaction <usd>","Per-transaction cap").option("--daily <usd>","Daily cap").option("--session <usd>","Current session cap").option("--expires-at <timestamp>","ISO timestamp after which paying is blocked")).action(async r=>rf("wallet limits",r,()=>T_().limits({perTransaction:r.perTransaction,daily:r.daily,session:r.session,expiresAt:r.expiresAt}))),tf(e.command("activity").description("Show legacy receipts and reconciling x402 authorizations.").option("--limit <count>","Return at most the newest N activity entries")).action(async r=>{await rf("activity",r,()=>{let n=r.limit===void 0?void 0:Number(r.limit);if(n!==void 0&&(!Number.isInteger(n)||n<1))throw new Error("--limit must be a positive integer");return T_().activity(n)})}),tf(e.command("receipt <activity-id>").description("Show one journaled wallet activity entry by its stable id.")).action(async(r,n)=>{await rf("receipt",n,()=>T_().receipt(r))}),tf(e.command("connections").description("Show supported MCP client connections.")).action(async r=>rf("connections",r,async()=>jU.map(n=>({id:n.id,name:n.displayName,detected:rre(n),connected:ure(n)})))),tf(e.command("connect <client>").description("Connect Visa to an AI or MCP client.")).action(async(r,n)=>{await rf("connect",n,async()=>{let i=n7(r);if(!i)throw new Error(`unknown client: ${r}`);return _Pe(i)})}),tf(e.command("disconnect <client>").description("Remove Visa from an AI or MCP client.")).action(async(r,n)=>{await rf("disconnect",n,async()=>{let i=n7(r);if(!i)throw new Error(`unknown client: ${r}`);return wPe(i)})})}pd();var k9e=!1;async function R9e(e,t,r){try{return await t()}catch(n){if(!(n.message==="Invalid signature"||n.code==="ATTESTATION_KEY_DRIFT"||n.error_code==="ATTESTATION_KEY_DRIFT"||n.name==="AttestationDriftError")||!S0())throw n;if(Ce.warn("attestation:key-mismatch",{action:"browser-recovery"}),r){if(k9e)throw Ce.warn("attestation:browser-recovery-suppressed",{reason:"already-attempted-in-process"}),n;k9e=!0,Ce.info("attestation:starting-browser-recovery");try{let o=await r();if(!o.success)throw Ce.error("attestation:browser-recovery-failed",{message:o.message}),n;let s=await UTe();await e.registerAttestationKey(s),await e.setBiometricPreference({required:!0}),Ce.info("attestation:requirement-restored-after-recovery",{surface:"retry"}),Ce.info("attestation:key-reregistered-after-recovery");let a=await t();return k9e=!1,a}catch(o){throw Ce.error("attestation:recovery-failure",{error:o.message}),n}}throw n}}function N9e(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}r6();Fte();s6();var XNr="4.1.0-rc.50";async function g_t(e){let t=await h7(e);console.log(`\u2713 registered "${t.relayName}" on the "${t.mesh}" mesh`),console.log(` peer: ${t.peerId??"(pending)"}`),console.log(` identity: ${t.tapAgentId?`reused TAP key ${t.tapAgentId}`:"stable Subway key (no TAP agent found)"}`),console.log(` relay: ${m7} (mesh="${t.mesh}")`),console.log(` chat: visa subway listen --as ${e} | visa subway send --as ${e} <to> "<text>"`)}var sj=(e,t)=>{console.error(`\u2717 ${e} failed: ${t instanceof Error?t.message:String(t)}`),process.exitCode=1};function b_t(e){if(!Hre(XNr))return;e.command("register <name>").description(`Register a name on the "${Ci}" Subway mesh (reuses your CLI agent key \u2014 no TAP setup needed).`).action(async r=>{try{await g_t(r)}catch(n){sj("register",n)}});let t=e.command("subway").description("Subway agent-to-agent messaging over the Visa CLI.");t.command("register <name>").description("Alias of `visa register <name>`.").action(async r=>{try{await g_t(r)}catch(n){sj("register",n)}}),t.command("send <to> <text>").description("Send a direct signed message to another agent.").option("--as <name>","Registered name to send as (default: the only one registered)").action(async(r,n,i)=>{try{let o=eM(i.as),s=await Wre(o,r,n);console.log(`\u2713 sent to ${s.to} as ${s.as}`)}catch(o){sj("send",o)}}),t.command("find <name>").description("Look up another agent on the .visa relay \u2014 is it live, and who is it?").action(async r=>{try{let n=await Kre(r);n.found?(console.log(`\u2713 ${n.relayName} is live`),console.log(` peer: ${n.peerId}`)):(console.log(`\u2717 ${n.relayName} not found${n.error?` (${n.error})`:""}`),process.exitCode=1)}catch(n){sj("find",n)}}),t.command("listen").description("Stay connected and print inbound messages (Ctrl-C to stop).").option("--as <name>","Registered name to listen as (default: the only one registered)").option("--room <topic>","Also subscribe to a room topic").action(async r=>{try{let n=eM(r.as),i=b8(n,{autoReconnect:!0});await _8(i);let o=a=>new Date(a).toLocaleTimeString();i.onMessage(a=>{let c=a.verified?"":" (unverified)";console.log(`[${o(a.timestampMs)}] ${a.fromName}${c}: ${a.payload}`)}),r.room&&i.subscribe(r.room,a=>{console.log(`[${o(a.timestampMs)}] #${a.topic} ${a.fromName}: ${a.payload}`)}),console.log(`\u2026 listening as ${G_(n)} on "${Ci}" mesh${r.room?` (room #${r.room})`:""}. Ctrl-C to stop.`);let s=()=>{i.disconnect(),process.exit(0)};process.on("SIGINT",s),process.on("SIGTERM",s),await new Promise(()=>{})}catch(n){sj("listen",n)}}),t.command("whoami").description("List names this CLI has registered on the relay.").action(()=>{let r=Gre();if(r.length===0){console.log("No Subway names registered. Run `visa register <name>`.");return}for(let n of r)console.log(`${n.relayName} mesh=${n.mesh} peer=${n.peerId??"?"} ${n.tapAgentId?`tap=${n.tapAgentId}`:"(standalone key)"} registered=${n.registeredAt}`)})}var mBr=_e(require("fs")),L_t=_e(require("os")),of=_e(require("path")),z_t=require("node:readline/promises");G4();w0();var ey=_e(require("fs")),_0=_e(require("path"));var QNr=1,D4={CLAUDE_CODE:"claude-code",CODEX:"codex",UNKNOWN:"unknown"},eBr=["terminal","claude","claude-code","all"];function iee(e){let t=e.toLowerCase();return eBr.includes(t)?t:null}var tBr=50,rBr=64*1024,__t=10,B9e=80,ot={get reset(){return Ls().reset},get visaBlue(){return Ls().visaBlue},get visaBlueSoft(){return Ls().visaBlueSoft},get visaGold(){return Ls().visaGold},get green(){return Ls().green},get muted(){return Ls().muted},get chrome(){return Ls().chrome}};function ct(e,t){return e.length===0||process.env.NO_COLOR||Ej()?e:`${t}${e}${ot.reset}`}function v_t(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u001F\u007F]/g,"").length}async function x_t(e=process.stdin){return e.isTTY?null:new Promise(t=>{let r=[],n=!1,i=()=>{e.removeListener("data",s),e.removeListener("end",a),e.removeListener("error",c),clearTimeout(u)},o=d=>{n||(n=!0,i(),t(d))},s=d=>{r.push(typeof d=="string"?Buffer.from(d):d)},a=()=>{let d=Buffer.concat(r).toString("utf-8").trim();if(!d)return o(null);try{let l=JSON.parse(d);o(l&&typeof l=="object"?l:null)}catch{o(null)}},c=()=>o(null),u=setTimeout(()=>{r.length>0?a():o(null)},tBr);e.on("data",s),e.on("end",a),e.on("error",c)})}function aj(e){let r=Math.round(Math.max(0,Math.min(1,e))*10),n="\u2588".repeat(r),i="\u2591".repeat(10-r);return`${ct(n||"",ot.visaBlueSoft)}${ct(i||"",ot.chrome)}`}function cj(e){return!Number.isFinite(e)||e<0?"0":e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:String(Math.round(e))}function nBr(e){if(B_t(e))return oBr(e);let t=` ${ct("\u2502",ot.chrome)} `,r=nee(e)||"claude",n=e.cwd?lo(_0.basename(e.cwd)):"",i=oee(e.workspace),o=n||i,s=i&&i!==o?` ${ct(`@${i}`,ot.visaBlueSoft)}`:"",a=[ct(`[${r}]`,ot.visaBlueSoft)];o&&a.push(`${ct(o,ot.visaGold)}${s}`);let c=lo(e.git_branch??e.branch??"");c&&a.push(`${ct("git:(",ot.muted)}${ct(c,ot.visaBlueSoft)}${ct(")",ot.muted)}`);let u=a.join(t),d=Number(e.context_window?.context_window_size??0),l=typeof e.context_window?.used_percentage=="number"?e.context_window.used_percentage:typeof e.context_window?.remaining_percentage=="number"?100-e.context_window.remaining_percentage:null,p=e.context_window?.current_usage,f=[p?.input_tokens,p?.output_tokens,p?.cache_creation_input_tokens,p?.cache_read_input_tokens].filter(x=>typeof x=="number"&&Number.isFinite(x)),m=f.length>0?f.reduce((x,S)=>x+S,0):null,h=Number(e.context_window?.total_input_tokens??m??p?.input_tokens??0),y=l!==null?Math.max(0,Math.min(1,l/100)):d>0?Math.max(0,Math.min(1,h/d)):0,v=l!==null&&d>0?Math.round(y*d):h,E;if(d>0||l!==null){let x=`${String(Math.round(y*100)).padStart(2," ")}%`,S=d>0?` ${ct(`(${cj(v)}/${cj(d)})`,ot.muted)}`:"";E=`${ct("Context",ot.muted)} ${aj(y)} ${ct(x,ot.green)}${S}`}else E=`${ct("Context",ot.muted)} ${ct("-",ot.muted)}`;let _=S_t(e.rate_limits),w=[E];_&&w.push(_);let A=w.join(t);return`${u}
|
|
20950
|
+
`):Nne(Ake(e,o),n),process.exitCode=1}}function ZNr(){this.help({error:!1})}function y_t(e){tf(e.command("find <intent>").description("Find payable services by outcome; discovery never spends money.").option("--provider <provider>",`Directory provider: all, ${ree.join(", ")}`,"all").option("--protocol <protocol>","Filter by payment protocol: x402, mpp, l402, vic").option("--max <usd>","Only show listings at or below this advisory price").option("--limit <count>","Maximum results","10")).action(async(r,n)=>{await rf("find",n,async()=>{let i=["all",...ree];if(!i.includes(n.provider))throw new Error(`--provider must be one of: ${i.join(", ")}`);let o=["x402","mpp","l402","vic"];if(n.protocol&&!o.includes(n.protocol))throw new Error(`--protocol must be one of: ${o.join(", ")}`);let s=Number(n.limit);if(!Number.isInteger(s)||s<1||s>50)throw new Error("--limit must be an integer between 1 and 50");return T_().find({intent:r,provider:n.provider,protocol:n.protocol,maxUsd:n.max,limit:s})})}),tf(e.command("inspect [listing-id]").description("Inspect a directory listing or fetch a fresh x402 challenge without paying.").option("--url <url>","Inspect an advanced direct endpoint instead of a listing").option("--input <source>","POST JSON from @file or - for stdin")).action(async(r,n)=>{await rf("inspect",n,()=>T_().inspect({listingId:r,url:n.url,bodyJson:h_t(n.input)}))}),tf(e.command("pay [listing-id]").description("Disclose a bounded x402 authorization; the outcome remains reconciling until trusted settlement evidence exists.").option("--url <url>","Pay an advanced direct endpoint instead of a listing").requiredOption("--max <usd>","Hard USD ceiling; the wallet refuses a pricier challenge").option("--input <source>","POST JSON from @file or - for stdin")).action(async(r,n)=>{await rf("pay",n,()=>T_().pay({listingId:r,url:n.url,maxUsd:n.max,bodyJson:h_t(n.input)}))});let t=e.command("wallet").description("Inspect, fund, and constrain the principal v4 wallet.").action(ZNr);tf(t.command("show").description("Show wallet, network, policy, and budgets.")).action(async r=>rf("wallet show",r,()=>T_().status())),tf(t.command("fund").description("Show the wallet funding address and network guidance.")).action(async r=>rf("wallet fund",r,()=>T_().fund())),tf(t.command("limits").description("Show or update wallet spending limits.").option("--per-transaction <usd>","Per-transaction cap").option("--daily <usd>","Daily cap").option("--session <usd>","Current session cap").option("--expires-at <timestamp>","ISO timestamp after which paying is blocked")).action(async r=>rf("wallet limits",r,()=>T_().limits({perTransaction:r.perTransaction,daily:r.daily,session:r.session,expiresAt:r.expiresAt}))),tf(e.command("activity").description("Show legacy receipts and reconciling x402 authorizations.").option("--limit <count>","Return at most the newest N activity entries")).action(async r=>{await rf("activity",r,()=>{let n=r.limit===void 0?void 0:Number(r.limit);if(n!==void 0&&(!Number.isInteger(n)||n<1))throw new Error("--limit must be a positive integer");return T_().activity(n)})}),tf(e.command("receipt <activity-id>").description("Show one journaled wallet activity entry by its stable id.")).action(async(r,n)=>{await rf("receipt",n,()=>T_().receipt(r))}),tf(e.command("connections").description("Show supported MCP client connections.")).action(async r=>rf("connections",r,async()=>jU.map(n=>({id:n.id,name:n.displayName,detected:rre(n),connected:ure(n)})))),tf(e.command("connect <client>").description("Connect Visa to an AI or MCP client.")).action(async(r,n)=>{await rf("connect",n,async()=>{let i=n7(r);if(!i)throw new Error(`unknown client: ${r}`);return _Pe(i)})}),tf(e.command("disconnect <client>").description("Remove Visa from an AI or MCP client.")).action(async(r,n)=>{await rf("disconnect",n,async()=>{let i=n7(r);if(!i)throw new Error(`unknown client: ${r}`);return wPe(i)})})}pd();var k9e=!1;async function R9e(e,t,r){try{return await t()}catch(n){if(!(n.message==="Invalid signature"||n.code==="ATTESTATION_KEY_DRIFT"||n.error_code==="ATTESTATION_KEY_DRIFT"||n.name==="AttestationDriftError")||!S0())throw n;if(Ce.warn("attestation:key-mismatch",{action:"browser-recovery"}),r){if(k9e)throw Ce.warn("attestation:browser-recovery-suppressed",{reason:"already-attempted-in-process"}),n;k9e=!0,Ce.info("attestation:starting-browser-recovery");try{let o=await r();if(!o.success)throw Ce.error("attestation:browser-recovery-failed",{message:o.message}),n;let s=await UTe();await e.registerAttestationKey(s),await e.setBiometricPreference({required:!0}),Ce.info("attestation:requirement-restored-after-recovery",{surface:"retry"}),Ce.info("attestation:key-reregistered-after-recovery");let a=await t();return k9e=!1,a}catch(o){throw Ce.error("attestation:recovery-failure",{error:o.message}),n}}throw n}}function N9e(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}r6();Fte();s6();var XNr="4.1.0-rc.51";async function g_t(e){let t=await h7(e);console.log(`\u2713 registered "${t.relayName}" on the "${t.mesh}" mesh`),console.log(` peer: ${t.peerId??"(pending)"}`),console.log(` identity: ${t.tapAgentId?`reused TAP key ${t.tapAgentId}`:"stable Subway key (no TAP agent found)"}`),console.log(` relay: ${m7} (mesh="${t.mesh}")`),console.log(` chat: visa subway listen --as ${e} | visa subway send --as ${e} <to> "<text>"`)}var sj=(e,t)=>{console.error(`\u2717 ${e} failed: ${t instanceof Error?t.message:String(t)}`),process.exitCode=1};function b_t(e){if(!Hre(XNr))return;e.command("register <name>").description(`Register a name on the "${Ci}" Subway mesh (reuses your CLI agent key \u2014 no TAP setup needed).`).action(async r=>{try{await g_t(r)}catch(n){sj("register",n)}});let t=e.command("subway").description("Subway agent-to-agent messaging over the Visa CLI.");t.command("register <name>").description("Alias of `visa register <name>`.").action(async r=>{try{await g_t(r)}catch(n){sj("register",n)}}),t.command("send <to> <text>").description("Send a direct signed message to another agent.").option("--as <name>","Registered name to send as (default: the only one registered)").action(async(r,n,i)=>{try{let o=eM(i.as),s=await Wre(o,r,n);console.log(`\u2713 sent to ${s.to} as ${s.as}`)}catch(o){sj("send",o)}}),t.command("find <name>").description("Look up another agent on the .visa relay \u2014 is it live, and who is it?").action(async r=>{try{let n=await Kre(r);n.found?(console.log(`\u2713 ${n.relayName} is live`),console.log(` peer: ${n.peerId}`)):(console.log(`\u2717 ${n.relayName} not found${n.error?` (${n.error})`:""}`),process.exitCode=1)}catch(n){sj("find",n)}}),t.command("listen").description("Stay connected and print inbound messages (Ctrl-C to stop).").option("--as <name>","Registered name to listen as (default: the only one registered)").option("--room <topic>","Also subscribe to a room topic").action(async r=>{try{let n=eM(r.as),i=b8(n,{autoReconnect:!0});await _8(i);let o=a=>new Date(a).toLocaleTimeString();i.onMessage(a=>{let c=a.verified?"":" (unverified)";console.log(`[${o(a.timestampMs)}] ${a.fromName}${c}: ${a.payload}`)}),r.room&&i.subscribe(r.room,a=>{console.log(`[${o(a.timestampMs)}] #${a.topic} ${a.fromName}: ${a.payload}`)}),console.log(`\u2026 listening as ${G_(n)} on "${Ci}" mesh${r.room?` (room #${r.room})`:""}. Ctrl-C to stop.`);let s=()=>{i.disconnect(),process.exit(0)};process.on("SIGINT",s),process.on("SIGTERM",s),await new Promise(()=>{})}catch(n){sj("listen",n)}}),t.command("whoami").description("List names this CLI has registered on the relay.").action(()=>{let r=Gre();if(r.length===0){console.log("No Subway names registered. Run `visa register <name>`.");return}for(let n of r)console.log(`${n.relayName} mesh=${n.mesh} peer=${n.peerId??"?"} ${n.tapAgentId?`tap=${n.tapAgentId}`:"(standalone key)"} registered=${n.registeredAt}`)})}var mBr=_e(require("fs")),L_t=_e(require("os")),of=_e(require("path")),z_t=require("node:readline/promises");G4();w0();var ey=_e(require("fs")),_0=_e(require("path"));var QNr=1,D4={CLAUDE_CODE:"claude-code",CODEX:"codex",UNKNOWN:"unknown"},eBr=["terminal","claude","claude-code","all"];function iee(e){let t=e.toLowerCase();return eBr.includes(t)?t:null}var tBr=50,rBr=64*1024,__t=10,B9e=80,ot={get reset(){return Ls().reset},get visaBlue(){return Ls().visaBlue},get visaBlueSoft(){return Ls().visaBlueSoft},get visaGold(){return Ls().visaGold},get green(){return Ls().green},get muted(){return Ls().muted},get chrome(){return Ls().chrome}};function ct(e,t){return e.length===0||process.env.NO_COLOR||Ej()?e:`${t}${e}${ot.reset}`}function v_t(e){return e.replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u001F\u007F]/g,"").length}async function x_t(e=process.stdin){return e.isTTY?null:new Promise(t=>{let r=[],n=!1,i=()=>{e.removeListener("data",s),e.removeListener("end",a),e.removeListener("error",c),clearTimeout(u)},o=d=>{n||(n=!0,i(),t(d))},s=d=>{r.push(typeof d=="string"?Buffer.from(d):d)},a=()=>{let d=Buffer.concat(r).toString("utf-8").trim();if(!d)return o(null);try{let l=JSON.parse(d);o(l&&typeof l=="object"?l:null)}catch{o(null)}},c=()=>o(null),u=setTimeout(()=>{r.length>0?a():o(null)},tBr);e.on("data",s),e.on("end",a),e.on("error",c)})}function aj(e){let r=Math.round(Math.max(0,Math.min(1,e))*10),n="\u2588".repeat(r),i="\u2591".repeat(10-r);return`${ct(n||"",ot.visaBlueSoft)}${ct(i||"",ot.chrome)}`}function cj(e){return!Number.isFinite(e)||e<0?"0":e>=1e6?`${(e/1e6).toFixed(1)}M`:e>=1e3?`${Math.round(e/1e3)}k`:String(Math.round(e))}function nBr(e){if(B_t(e))return oBr(e);let t=` ${ct("\u2502",ot.chrome)} `,r=nee(e)||"claude",n=e.cwd?lo(_0.basename(e.cwd)):"",i=oee(e.workspace),o=n||i,s=i&&i!==o?` ${ct(`@${i}`,ot.visaBlueSoft)}`:"",a=[ct(`[${r}]`,ot.visaBlueSoft)];o&&a.push(`${ct(o,ot.visaGold)}${s}`);let c=lo(e.git_branch??e.branch??"");c&&a.push(`${ct("git:(",ot.muted)}${ct(c,ot.visaBlueSoft)}${ct(")",ot.muted)}`);let u=a.join(t),d=Number(e.context_window?.context_window_size??0),l=typeof e.context_window?.used_percentage=="number"?e.context_window.used_percentage:typeof e.context_window?.remaining_percentage=="number"?100-e.context_window.remaining_percentage:null,p=e.context_window?.current_usage,f=[p?.input_tokens,p?.output_tokens,p?.cache_creation_input_tokens,p?.cache_read_input_tokens].filter(x=>typeof x=="number"&&Number.isFinite(x)),m=f.length>0?f.reduce((x,S)=>x+S,0):null,h=Number(e.context_window?.total_input_tokens??m??p?.input_tokens??0),y=l!==null?Math.max(0,Math.min(1,l/100)):d>0?Math.max(0,Math.min(1,h/d)):0,v=l!==null&&d>0?Math.round(y*d):h,E;if(d>0||l!==null){let x=`${String(Math.round(y*100)).padStart(2," ")}%`,S=d>0?` ${ct(`(${cj(v)}/${cj(d)})`,ot.muted)}`:"";E=`${ct("Context",ot.muted)} ${aj(y)} ${ct(x,ot.green)}${S}`}else E=`${ct("Context",ot.muted)} ${ct("-",ot.muted)}`;let _=S_t(e.rate_limits),w=[E];_&&w.push(_);let A=w.join(t);return`${u}
|
|
20951
20951
|
${A}`}function iBr(e){if(B_t(e))return null;let t=` ${ct("\u2502",ot.chrome)} `,r=nee(e)||"claude",n=e.cwd?lo(_0.basename(e.cwd)):"",i=oee(e.workspace),o=n||i,s=i&&i!==o?` ${ct(`@${i}`,ot.visaBlueSoft)}`:"",a=[ct(`[${r}]`,ot.visaBlueSoft)];o&&a.push(`${ct(o,ot.visaGold)}${s}`);let c=lo(e.git_branch??e.branch??"");c&&a.push(`${ct("git:(",ot.muted)}${ct(c,ot.visaBlueSoft)}${ct(")",ot.muted)}`);let u=Number(e.context_window?.context_window_size??0),d=typeof e.context_window?.used_percentage=="number"?e.context_window.used_percentage:typeof e.context_window?.remaining_percentage=="number"?100-e.context_window.remaining_percentage:null,l=e.context_window?.current_usage,p=[l?.input_tokens,l?.output_tokens,l?.cache_creation_input_tokens,l?.cache_read_input_tokens].filter(w=>typeof w=="number"&&Number.isFinite(w)),f=p.length>0?p.reduce((w,A)=>w+A,0):null,m=Number(e.context_window?.total_input_tokens??f??l?.input_tokens??0),h=d!==null?Math.max(0,Math.min(1,d/100)):u>0?Math.max(0,Math.min(1,m/u)):0,y=d!==null&&u>0?Math.round(h*u):m,v;if(u>0||d!==null){let w=`${String(Math.round(h*100)).padStart(2," ")}%`,A=u>0?` ${ct(`(${cj(y)}/${cj(u)})`,ot.muted)}`:"";v=`${ct("Context",ot.muted)} ${aj(h)} ${ct(w,ot.green)}${A}`}else v=`${ct("Context",ot.muted)} ${ct("-",ot.muted)}`;let E=S_t(e.rate_limits),_=[v];return E&&_.push(E),{identity:a.join(t),metrics:_.join(t)}}function oBr(e){let t=` ${ct("\u2502",ot.chrome)} `,r=j_t(e),n=r.model||"codex",i=[ct(`[${n}]`,ot.visaBlueSoft)];r.project&&i.push(ct(r.project,ot.visaGold)),r.gitBranch&&i.push(`${ct("git",ot.muted)} ${ct(r.gitBranch,ot.visaGold)}`);let o=i.join(t),s=[];if(typeof r.contextUsedPercent=="number"){let c=Math.max(0,Math.min(1,r.contextUsedPercent/100));s.push(`${ct("Context",ot.muted)} ${aj(c)} ${ct(`${Math.round(r.contextUsedPercent)}%`,ot.green)}`)}else if(typeof r.contextRemainingPercent=="number"){let c=100-r.contextRemainingPercent,u=Math.max(0,Math.min(1,c/100));s.push(`${ct("Context",ot.muted)} ${aj(u)} ${ct(`${Math.round(c)}%`,ot.green)}`)}typeof r.usedTokens=="number"&&s.push(`${ct("Tokens",ot.muted)} ${cj(r.usedTokens)}`),r.status&&s.push(`${ct("Status",ot.muted)} ${ct(r.status,ot.visaBlueSoft)}`),r.threadTitle&&s.push(`${ct("Thread",ot.muted)} ${ct(r.threadTitle,ot.visaBlueSoft)}`);let a=s.length>0?s.join(t):`${ct("Context",ot.muted)} ${ct("-",ot.muted)}`;return`${o}
|
|
20952
20952
|
${a}`}function sBr(e){if(typeof e!="number"||e<=0)return"";let r=(e>1e12?e:e*1e3)-Date.now();if(r<=0||r>=10080*60*1e3)return"";let n=Math.floor(r/6e4),i=Math.floor(n/60),o=n%60;return i>0?`${i}h ${o}m`:`${o}m`}function w_t(e,t){if(!e||typeof e.used_percentage!="number")return null;let r=Math.max(0,Math.min(100,e.used_percentage)),n=r/100,i=aj(n),o=r>=90?"\x1B[38;5;196m":r>=70?ot.visaGold:ot.green,s=`${String(Math.round(r)).padStart(2," ")}%`,a=sBr(e.resets_at),c=a?` ${ct(`(${a} / ${t})`,ot.muted)}`:` ${ct(`(${t})`,ot.muted)}`;return`${i} ${ct(s,o)}${c}`}function S_t(e){if(!e)return null;let t=w_t(e.five_hour,"5h"),r=typeof e.seven_day?.used_percentage=="number"?e.seven_day.used_percentage:null,n=r!==null&&r>=90?w_t(e.seven_day,"7d"):null;if(!t&&!n)return null;let i=` ${ct("\u2502",ot.chrome)} `,o=[t,n].filter(Boolean);return`${ct("Usage",ot.muted)} ${o.join(i)}`}function T_t(e){let t;try{let r=ey.statSync(e);if(!r.isFile())return null;let n=r.size;if(n===0)return null;let i=Math.min(n,rBr),o=n-i;t=ey.openSync(e,"r");let s=Buffer.alloc(i);ey.readSync(t,s,0,i,o);let a=s.toString("utf-8");if(o>0){let c=Buffer.alloc(1);if(ey.readSync(t,c,0,1,o-1),c[0]!==10){let u=a.indexOf(`
|
|
20953
20953
|
`);u>=0&&(a=a.slice(u+1))}}return a}catch{return null}finally{if(t!==void 0)try{ey.closeSync(t)}catch{}}}function aBr(e){if(!e||typeof e!="object")return;let t=e,r=["file_path","path","notebook_path","pattern","command","url"];for(let n of r){let i=t[n];if(typeof i=="string"&&i.length>0){if(n.endsWith("_path")||n==="path"){let o=_0.basename(_0.dirname(i)),s=_0.basename(i);return o&&o!=="."&&o!=="/"?`${o}/${s}`:s}return i}}}function cBr(e){let t=e.split(`
|