@visa/cli 4.1.0-rc.33 → 4.1.0-rc.34

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,7 +1,7 @@
1
1
  #!/usr/bin/env node
2
2
  "use strict";var Bmt=Object.create;var Dk=Object.defineProperty;var Nmt=Object.getOwnPropertyDescriptor;var jmt=Object.getOwnPropertyNames;var qmt=Object.getPrototypeOf,Umt=Object.prototype.hasOwnProperty;var P=(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}},Gi=(e,t)=>{for(var r in t)Dk(e,r,{get:t[r],enumerable:!0})},M8e=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of jmt(t))!Umt.call(e,i)&&i!==r&&Dk(e,i,{get:()=>t[i],enumerable:!(n=Nmt(t,i))||n.enumerable});return e};var Ze=(e,t,r)=>(r=e!=null?Bmt(qmt(e)):{},M8e(t||!e||!e.__esModule?Dk(r,"default",{value:e,enumerable:!0}):r,e)),ie=e=>M8e(Dk({},"__esModule",{value:!0}),e);var Hk,V8e,K8e,OY,Q1,CY=P(()=>{"use strict";Hk=Ze(require("fs")),V8e=Ze(require("path")),K8e=Ze(require("os")),OY=V8e.join(K8e.homedir(),".visa-mcp"),Q1=class{static ensureConfigDir(){Hk.existsSync(OY)||Hk.mkdirSync(OY,{recursive:!0,mode:448})}static getConfigDir(){return OY}}});function Lmt(){Ma.existsSync(kY)||Ma.mkdirSync(kY,{recursive:!0,mode:448})}function Hmt(){if(!RY){if(Lmt(),Ma.existsSync(CA)&&Ma.statSync(CA).size>zmt){let t=CA+".1";Ma.existsSync(t)&&Ma.unlinkSync(t),Ma.renameSync(CA,t)}RY=Ma.createWriteStream(CA,{flags:"a"})}return RY}function Fmt(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"}function Fk(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}
3
- `;Fmt(e)&&process.stderr.write(i),Hmt().write(i)}var Ma,BY,W8e,kY,CA,zmt,RY,Be,Dc=P(()=>{"use strict";Ma=Ze(require("fs")),BY=Ze(require("path")),W8e=Ze(require("os")),kY=BY.join(W8e.homedir(),".visa-mcp"),CA=BY.join(kY,"mcp-server.log"),zmt=5*1024*1024,RY=null;Be={debug:(...e)=>Fk("DEBUG",...e),info:(...e)=>Fk("INFO",...e),warn:(...e)=>Fk("WARN",...e),error:(...e)=>Fk("ERROR",...e)}});var $k=g((Kxr,$mt)=>{$mt.exports={name:"@visa/cli",version:"4.1.0-rc.33",description:"AI-powered payments for Claude Code",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:catalog-e2e":"jest --config jest.catalog-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 G8e(e){let t=J8e.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function Vk(){return Y8e.join(Q1.getConfigDir(),Vmt)}function Z8e(e){if((0,jY.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function Wmt(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 Z8e(i)}function Gmt(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let r=(0,jY.isIP)(t);return r===4?Z8e(t):r===6?t==="::1"||Wmt(t):!1}function NY(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:"&&Gmt(r.hostname)))throw new Error(`${t} ${Kmt}`)}function Kk(){let e=Vk();if(!eh.existsSync(e))return{};try{let t=eh.readFileSync(e,"utf-8"),r=JSON.parse(t);return!r||typeof r!="object"||Array.isArray(r)?(Be.warn("settings:corrupt",{path:G8e(e),reason:"not_object"}),{}):r}catch(t){return Be.warn("settings:corrupt",{path:G8e(e),error:t?.message||String(t)}),{}}}function X8e(e){Q1.ensureConfigDir();let t=Vk(),r=`${t}.tmp`,n=JSON.stringify(e,null,2)+`
4
- `;eh.writeFileSync(r,n,{mode:384}),eh.renameSync(r,t)}function qY(e){let t=Kk()[e];return typeof t=="string"?t:void 0}function UY(e){let t=Kk()[e];return typeof t=="boolean"?t:void 0}function Q8e(e,t){let r=RA[e];if(!r)throw new Om(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=Kk();return i[e]=n,X8e(i),{key:e,value:n,requiresRestart:!!r.requiresRestart,path:Vk()}}function e3e(e){let t=RA[e];if(!t)throw new Om(e);let r=Kk(),n=e in r;return n&&(delete r[e],X8e(r)),{key:e,removed:n,requiresRestart:n&&!!t.requiresRestart,path:Vk()}}function Zmt(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function Xmt(){try{let e=$k();return Zmt(e.version)}catch{return!1}}function Qmt(e){return e.envVar!==void 0&&e.envVar!==""?(NY(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(NY(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?Ymt:Jmt}function ju(){return Qmt({envVar:process.env.VISA_AUTH_URL,settingValue:qY("auth.serverUrl"),isPrerelease:Xmt()})}function t3e(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":UY("ui.suppressBrowser")??!1}var eh,jY,J8e,Y8e,Vmt,Kmt,RA,Om,Jmt,Ymt,a4=P(()=>{"use strict";eh=Ze(require("fs")),jY=require("node:net"),J8e=Ze(require("os")),Y8e=Ze(require("path"));CY();Dc();Vmt="settings.json",Kmt="must use https unless it points at localhost/loopback for local development";RA={"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");NY(e)}},"ui.suppressBrowser":{type:"boolean",description:"When true, the CLI/MCP server stops auto-opening result URLs in your browser."}};Om=class extends Error{constructor(t){let r=Object.keys(RA).sort().join(", ");super(`Unknown setting "${t}". Settable keys: ${r}.`),this.name="UnknownSettingKeyError"}};Jmt="https://auth.visacli.sh",Ymt="https://auth-visa-code-preview.up.railway.app"});function MY(e=o0t){return/^\d+\.\d+\.\d+$/.test(e)&&e!=="0.0.0"}function r3e(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function rl(e=process.env){let t=e.VISA_VERIFY_WEB_URL?.trim();return r3e(t||s0t)}function kA(e){return`${r3e(e)}${a0t}`}var o0t,s0t,a0t,DY=P(()=>{"use strict";o0t="4.1.0-rc.33",s0t="https://app.visacli.sh",a0t="/agent/enroll"});var Cm,zY=P(()=>{"use strict";Cm="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1"});function a3e(e){return`${e}-${o3e.randomBytes(24).toString("base64url")}`}function c3e(e=process.env){return e.NODE_ENV==="test"||e[s3e]==="true"}function th(e=process.env){return e.VISA_MOCK_KEYCHAIN==="true"&&c3e(e)}function Jk(e=process.env){return e.VISA_MOCK_TOUCHID==="true"&&c3e(e)}function LY(){return`Set ${s3e}=true only for local debugging; it enables insecure mock credential hooks outside NODE_ENV=test.`}function u3e(){return n3e??=a3e("mock-session"),n3e}function d3e(e=process.env){return e.NODE_ENV==="test"?Cm:(i3e??=a3e("mock-rc"),i3e)}var o3e,s3e,n3e,i3e,Yk=P(()=>{"use strict";o3e=Ze(require("crypto"));zY();s3e="VISA_ALLOW_INSECURE_MOCKS"});function u0t(e){let t=e;return[t?.message,t?.stderr].filter(r=>typeof r=="string").join(`
3
+ `;Fmt(e)&&process.stderr.write(i),Hmt().write(i)}var Ma,BY,W8e,kY,CA,zmt,RY,Be,Dc=P(()=>{"use strict";Ma=Ze(require("fs")),BY=Ze(require("path")),W8e=Ze(require("os")),kY=BY.join(W8e.homedir(),".visa-mcp"),CA=BY.join(kY,"mcp-server.log"),zmt=5*1024*1024,RY=null;Be={debug:(...e)=>Fk("DEBUG",...e),info:(...e)=>Fk("INFO",...e),warn:(...e)=>Fk("WARN",...e),error:(...e)=>Fk("ERROR",...e)}});var $k=g((Kxr,$mt)=>{$mt.exports={name:"@visa/cli",version:"4.1.0-rc.34",description:"AI-powered payments for Claude Code",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:catalog-e2e":"jest --config jest.catalog-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 G8e(e){let t=J8e.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function Vk(){return Y8e.join(Q1.getConfigDir(),Vmt)}function Z8e(e){if((0,jY.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function Wmt(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 Z8e(i)}function Gmt(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let r=(0,jY.isIP)(t);return r===4?Z8e(t):r===6?t==="::1"||Wmt(t):!1}function NY(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:"&&Gmt(r.hostname)))throw new Error(`${t} ${Kmt}`)}function Kk(){let e=Vk();if(!eh.existsSync(e))return{};try{let t=eh.readFileSync(e,"utf-8"),r=JSON.parse(t);return!r||typeof r!="object"||Array.isArray(r)?(Be.warn("settings:corrupt",{path:G8e(e),reason:"not_object"}),{}):r}catch(t){return Be.warn("settings:corrupt",{path:G8e(e),error:t?.message||String(t)}),{}}}function X8e(e){Q1.ensureConfigDir();let t=Vk(),r=`${t}.tmp`,n=JSON.stringify(e,null,2)+`
4
+ `;eh.writeFileSync(r,n,{mode:384}),eh.renameSync(r,t)}function qY(e){let t=Kk()[e];return typeof t=="string"?t:void 0}function UY(e){let t=Kk()[e];return typeof t=="boolean"?t:void 0}function Q8e(e,t){let r=RA[e];if(!r)throw new Om(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=Kk();return i[e]=n,X8e(i),{key:e,value:n,requiresRestart:!!r.requiresRestart,path:Vk()}}function e3e(e){let t=RA[e];if(!t)throw new Om(e);let r=Kk(),n=e in r;return n&&(delete r[e],X8e(r)),{key:e,removed:n,requiresRestart:n&&!!t.requiresRestart,path:Vk()}}function Zmt(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function Xmt(){try{let e=$k();return Zmt(e.version)}catch{return!1}}function Qmt(e){return e.envVar!==void 0&&e.envVar!==""?(NY(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(NY(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?Ymt:Jmt}function ju(){return Qmt({envVar:process.env.VISA_AUTH_URL,settingValue:qY("auth.serverUrl"),isPrerelease:Xmt()})}function t3e(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":UY("ui.suppressBrowser")??!1}var eh,jY,J8e,Y8e,Vmt,Kmt,RA,Om,Jmt,Ymt,a4=P(()=>{"use strict";eh=Ze(require("fs")),jY=require("node:net"),J8e=Ze(require("os")),Y8e=Ze(require("path"));CY();Dc();Vmt="settings.json",Kmt="must use https unless it points at localhost/loopback for local development";RA={"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");NY(e)}},"ui.suppressBrowser":{type:"boolean",description:"When true, the CLI/MCP server stops auto-opening result URLs in your browser."}};Om=class extends Error{constructor(t){let r=Object.keys(RA).sort().join(", ");super(`Unknown setting "${t}". Settable keys: ${r}.`),this.name="UnknownSettingKeyError"}};Jmt="https://auth.visacli.sh",Ymt="https://auth-visa-code-preview.up.railway.app"});function MY(e=o0t){return/^\d+\.\d+\.\d+$/.test(e)&&e!=="0.0.0"}function r3e(e){let t=e.length;for(;t>0&&e.charCodeAt(t-1)===47;)t--;return e.slice(0,t)}function rl(e=process.env){let t=e.VISA_VERIFY_WEB_URL?.trim();return r3e(t||s0t)}function kA(e){return`${r3e(e)}${a0t}`}var o0t,s0t,a0t,DY=P(()=>{"use strict";o0t="4.1.0-rc.34",s0t="https://app.visacli.sh",a0t="/agent/enroll"});var Cm,zY=P(()=>{"use strict";Cm="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1"});function a3e(e){return`${e}-${o3e.randomBytes(24).toString("base64url")}`}function c3e(e=process.env){return e.NODE_ENV==="test"||e[s3e]==="true"}function th(e=process.env){return e.VISA_MOCK_KEYCHAIN==="true"&&c3e(e)}function Jk(e=process.env){return e.VISA_MOCK_TOUCHID==="true"&&c3e(e)}function LY(){return`Set ${s3e}=true only for local debugging; it enables insecure mock credential hooks outside NODE_ENV=test.`}function u3e(){return n3e??=a3e("mock-session"),n3e}function d3e(e=process.env){return e.NODE_ENV==="test"?Cm:(i3e??=a3e("mock-rc"),i3e)}var o3e,s3e,n3e,i3e,Yk=P(()=>{"use strict";o3e=Ze(require("crypto"));zY();s3e="VISA_ALLOW_INSECURE_MOCKS"});function u0t(e){let t=e;return[t?.message,t?.stderr].filter(r=>typeof r=="string").join(`
5
5
  `)}function WY(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let r=u0t(e).toLowerCase();return r.includes("operation not permitted")||r.includes("permission denied")}function ih(){return process.platform!=="darwin"?Promise.resolve(!1):(l3e??=(async()=>{try{return await nl("security",["default-keychain","-d","user"],{timeout:5e3}),!0}catch(e){return WY(e)}})(),l3e)}async function d0t(){if(!await ih())return null;try{let{stdout:e}=await nl("security",["find-generic-password","-s",qu,"-a",rh,"-w"],{timeout:5e3});return e.trim()||null}catch(e){if(WY(e))throw new Xk("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 l0t(e){if(!await ih())return!1;try{try{await nl("security",["delete-generic-password","-s",qu,"-a",rh],{timeout:5e3})}catch{}return await nl("security",["add-generic-password","-s",qu,"-a",rh,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function p0t(){if(await ih())try{await nl("security",["delete-generic-password","-s",qu,"-a",rh],{timeout:5e3})}catch{}}async function f0t(){if(!GY())return null;try{let{stdout:e}=await nl("secret-tool",["lookup","service",qu,"account",rh],{timeout:5e3});return e.trim()||null}catch{return null}}async function m0t(e){if(!GY())return!1;try{let t=(0,Qk.execFile)("secret-tool",["store","--label",`${qu} ${rh}`,"service",qu,"account",rh]);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"))},c0t))]),!0):!1}catch{return!1}}async function h0t(){if(GY())try{await nl("secret-tool",["clear","service",qu,"account",rh],{timeout:5e3})}catch{}}function GY(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function y0t(){if(!await ih())return null;try{let{stdout:e}=await nl("security",["find-generic-password","-s",qu,"-a",Zk,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function g0t(e){if(await ih())try{try{await nl("security",["delete-generic-password","-s",qu,"-a",Zk],{timeout:5e3})}catch{}await nl("security",["add-generic-password","-s",qu,"-a",Zk,"-w",e],{timeout:5e3})}catch{}}async function b0t(){if(await ih())try{await nl("security",["delete-generic-password","-s",qu,"-a",Zk],{timeout:5e3})}catch{}}function FY(){try{return nh.readFileSync(BA,"utf-8").trim()||null}catch(e){if(WY(e))throw new Xk(`Unable to read Visa CLI credentials from ${BA}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function f3e(e){nh.mkdirSync(KY,{recursive:!0,mode:448}),nh.writeFileSync(BA,e,{mode:384}),process.platform==="win32"&&_0t(BA)}function $Y(){try{nh.unlinkSync(BA)}catch{}}function _0t(e){try{let t=eB.userInfo().username;(0,Qk.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 HY(){switch(process.platform){case"darwin":return{get:d0t,store:l0t,delete:p0t};case"linux":return{get:f0t,store:m0t,delete:h0t};default:return{get:async()=>FY(),store:async e=>{try{return f3e(e),!0}catch{return!1}},delete:async()=>$Y(),storesInSessionFile:!0}}}var Qk,p3e,nh,eB,VY,nl,KY,BA,qu,rh,Zk,c0t,Xk,l3e,Uu,NA=P(()=>{"use strict";Qk=require("child_process"),p3e=require("util"),nh=Ze(require("fs")),eB=Ze(require("os")),VY=Ze(require("path"));Yk();nl=(0,p3e.promisify)(Qk.execFile),KY=VY.join(eB.homedir(),".visa-mcp"),BA=VY.join(KY,"session-token"),qu="visa-cli",rh="session-token",Zk="rc-access",c0t=5e3,Xk=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};l3e=null;Uu=class{static async getSessionToken(){if(th())return Promise.resolve(u3e());let t=HY(),r=await t.get();if(r)return r;let n=FY();return n?(await t.store(n),n):null}static async saveSessionToken(t){if(th())return;let r=HY();if(await r.store(t)){if(await r.get()===t){r.storesInSessionFile||$Y();return}await r.delete()}if(f3e(t),FY()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${KY} is writable.`))}static async getRcAccessToken(){return th()?d3e():y0t()}static async saveRcAccessToken(t){th()||await g0t(t)}static async deleteSessionToken(){if(th())return;await HY().delete(),$Y()}static async clearAll(){await this.deleteSessionToken(),await b0t()}}});function jA(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 O0t(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(`
6
6
  `)}function qA(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 B3e(e,t){let r=qA(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 N3e(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 iB(e,t=process.platform){let r=qA(e);return r?N3e(r,t):null}function R3e(e,t){e(` Could not open browser automatically (${t.message}).`),e(" Open the URL above manually to continue."),e("")}async function oB(e,t={}){let r=t.log??(u=>console.log(u)),n=t.env??process.env,i=t.platform??process.platform,o=qA(e),s=t.spawn??((u,d,l)=>{(0,k3e.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 O0t(o??e).split(`
7
7
  `))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=jA(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=N3e(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?R3e(r,l):(r(" Opened browser. Waiting for you to sign in..."),r("")),u()};try{s(c.cmd,c.args,d)}catch(l){R3e(r,l instanceof Error?l:new Error(String(l))),u()}})}var k3e,JY=P(()=>{"use strict";k3e=require("child_process")});function J0t(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function a9e(e,t,r=""){let n=J0t(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 H3e(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 Y0t(e,t){a9e(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 nZ(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function QY(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Z0t(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 e1t(e,t=!1){return t?{h:Number(e&sB),l:Number(e>>F3e&sB)}:{h:Number(e>>F3e&sB)|0,l:Number(e&sB)|0}}function t1t(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}=e1t(e[o],t);[n[o],i[o]]=[s,a]}return[n,i]}function Bm(e,t,r,n){let i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:i|0}}function f1t(){return V0t.randomSecretKey()}function MA(e){return z0t(e)}function mB(){let e=f1t();return{secretKey:e,publicKey:MA(e)}}function u9e(e){if(e.length!==W3e)throw new Error(`Ed25519 seed must be ${W3e} bytes, got ${e.length}`);return{secretKey:e,publicKey:MA(e)}}function f4(e,t){return F0t(t,e)}function m1t(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function h1t(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 iZ(e){return m1t(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function y1t(e){let t=e.length%4===0?0:4-e.length%4,r=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat(t);return h1t(r)}function g1t(e){if(e.kty!=="OKP"||e.crv!=="Ed25519")throw new Error("not an Ed25519 OKP JWK")}function m4(e){let t=MA(e);return{kty:"OKP",crv:"Ed25519",x:iZ(t),d:iZ(e)}}function ch(e){return{kty:"OKP",crv:"Ed25519",x:iZ(e)}}function DA(e){if(g1t(e),!e.d)throw new Error("Ed25519 JWK has no private component (d)");return y1t(e.d)}function p9e(){return zA.default.randomBytes(32).toString("base64url")}function f9e(e){if(!/^[A-Za-z0-9_-]{43}$/.test(e))throw new Error("pairing verifier must be 32 unpadded base64url bytes");return mZ(e)}function _1t(e){return e.toUpperCase().replace(/[^A-Z0-9]/g,"")}function v1t(e){let t=_1t(e);return`${t.slice(0,4)}-${t.slice(4)}`}function m9e(){return zA.default.randomBytes(32).toString("base64url")}function fZ(e){if(!/^[A-Za-z0-9_-]{43}$/.test(e))throw new Error("claim token must be 32 unpadded base64url bytes");return mZ(`visa-agent-pairing-claim-token:v1:${e}`)}function hB(e,t){fZ(t);let r=zA.default.createHash("sha256").update(`visa-agent-pairing-derived-code:v1:${e}:${t}`,"utf8").digest(),n="";for(let i=0;i<b1t;i+=1)n+=pZ[r[i]&l9e];return v1t(n)}function h9e(e){return b9e("visa-agent-pairing-claim:v1",{agentJkt:e.agentJkt,claimTokenHash:e.claimTokenHash,contextLabel:e.runtime.contextLabel,pairingId:e.pairingId,platform:e.runtime.platform??"",runtime:e.runtime.runtime,serverNonce:e.serverNonce,walletPublicKey:e.walletPublicKey})}function y9e(e){return b9e("visa-agent-pairing-activation:v1",{agentJkt:e.agentJkt,artifactHash:e.artifactHash,pairingId:e.pairingId,termsHash:e.termsHash})}function g9e(e){return mZ(`visa-agent-pairing-artifacts:v1:${oZ(e)}`)}function mZ(e){return zA.default.createHash("sha256").update(e,"utf8").digest("base64url")}function b9e(e,t){return`${e}
@@ -20675,7 +20675,7 @@ ${e.senderName}
20675
20675
  ${e.timestampMs}
20676
20676
  ${e.messageType}
20677
20677
  ${t}
20678
- ${e.nonce}`;return x4r.encode(r)}function S4r(e,t,r,n,i,o,s){return A4r({messageId:e,senderPeerId:t,senderName:r,timestampMs:n,messageType:i,payload:o,nonce:s})}function T4r(e){let t=0;for(;t<e.length;){let r=e[t],n=r>>3,i=r&7;if(t++,i===0){for(;t<e.length&&e[t]&128;)t++;t++}else if(i===2){let o=0,s=0;for(;t<e.length&&e[t]&128;)o|=(e[t]&127)<<s,s+=7,t++;if(o|=(e[t]&127)<<s,t++,n===2&&o>=64)return e.slice(t,t+32);t+=o}else return null}return null}function Y4r(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function tpt(e,t,r=""){let n=Y4r(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 glt(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 Z4r(e,t){tpt(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 Twe(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function vwe(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function X4r(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 twr(e,t=!1){return t?{h:Number(e&NJ),l:Number(e>>blt&NJ)}:{h:Number(e>>blt&NJ)|0,l:Number(e&NJ)|0}}function rwr(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}=twr(e[o],t);[n[o],i[o]]=[s,a]}return[n,i]}function K1(e,t,r,n){let i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:i|0}}function mwr(){return K4r.randomSecretKey()}function npt(e){return $4r(e)}function hwr(){let e=mwr();return{secretKey:e,publicKey:npt(e)}}function ywr(e){if((0,e2.existsSync)(e)){let r=(0,e2.readFileSync)(e),n=new Uint8Array(r.buffer.slice(r.byteOffset,r.byteOffset+32));return{secretKey:n,publicKey:npt(n)}}let t=hwr();return(0,e2.mkdirSync)((0,Elt.dirname)(e),{recursive:!0}),(0,e2.writeFileSync)(e,new Uint8Array(t.secretKey)),t}function gwr(e){let{secretKey:t,publicKey:r}=ywr(e);return{privateKey:t,publicKey:r}}async function bwr(e,t,r,n,i,o,s,a){let c=S4r(t,r,n,i,o,s,a);return{signature:await _4r(e,c),signatureInput:E4r.subwayAgentMsgV1}}function xlt(e){return w4r(e)}var e2,Elt,Pvr,Ivr,Ovr,Cvr,Rvr,Alt,DJ,UJ,Xdt,Qdt,fwe,mwe,kvr,VJ,Bvr,bs,Nvr,jvr,qvr,W1,KJ,Pwe,Slt,Iwe,F1,elt,Owe,Tlt,Uvr,cA,Mvr,zJ,Tv,Tn,tlt,Ve,Plt,Ilt,Olt,Clt,hwe,wwe,fk,kv,Cv,Rlt,klt,xm,Dvr,rlt,zvr,xwe,Cwe,Lvr,Blt,Hvr,Fvr,$vr,Vvr,Kvr,Wvr,Rwe,Nlt,LJ,Gvr,jlt,Ewe,Jvr,nlt,ilt,Yvr,Mlt,Dlt,Gb,ra,RJ,slt,alt,clt,iA,oA,kJ,BJ,n4r,i4r,o4r,s4r,a4r,c4r,u4r,Jb,d4r,l4r,zlt,p4r,f4r,Yb,Zb,m4r,h4r,y4r,g4r,ult,v4r,Llt,x4r,E4r,Hlt,P4r,Flt,HJ,MJ,dlt,llt,gwe,bwe,I4r,uA,O4r,_s,C4r,R4r,k4r,t2,WJ,kwe,$lt,Vlt,V1,plt,Klt,Wlt,B4r,Bwe,N4r,FJ,Iv,Fn,flt,Ke,j4r,q4r,Glt,Jlt,_we,Awe,mk,dA,Rv,U4r,Ylt,Am,M4r,mlt,D4r,z4r,L4r,H4r,Zlt,F4r,Xlt,$4r,Qlt,V4r,K4r,$J,W4r,ept,Swe,G4r,hlt,ylt,J4r,Q4r,ewr,na,NJ,blt,_lt,vlt,sA,aA,jJ,qJ,nwr,iwr,owr,swr,awr,cwr,rpt,uwr,dwr,Xb,Qb,lwr,pwr,fwr,wlt,_wr,vwr,ipt,opt=P(()=>{"use strict";dwe();dwe();lwe();e2=require("fs"),Elt=require("path");Pvr=1e3,Ivr=10,Ovr=3e4,Cvr=3e4,Rvr=class{url;ws=null;_status="disconnected";messageHandlers=new Set;statusHandlers=new Set;reconnectAttempt=0;reconnectTimer=null;pingTimer=null;stopped=!1;autoReconnect;reconnectInterval;maxReconnectAttempts;pingInterval;constructor(e){this.url=e.url,this.autoReconnect=e.autoReconnect??!0,this.reconnectInterval=e.reconnectInterval??Pvr,this.maxReconnectAttempts=e.maxReconnectAttempts??Ivr,this.pingInterval=e.pingInterval??Ovr}get status(){return this._status}onMessage(e){return this.messageHandlers.add(e),()=>this.messageHandlers.delete(e)}onStatusChange(e){return this.statusHandlers.add(e),()=>this.statusHandlers.delete(e)}connect(){return this.stopped=!1,new Promise((e,t)=>{let r=Svr();if(!r){t(new ta('No WebSocket implementation available. Install the "ws" package for Node.js.'));return}this.setStatus("connecting");try{this.ws=new r(this.url)}catch(i){t(new ta(`Failed to create WebSocket: ${i}`));return}let n=!1;this.ws.onopen=()=>{this.reconnectAttempt=0,this.setStatus("connected"),this.startPing(),n||(n=!0,e())},this.ws.onmessage=i=>{let o;try{o=JSON.parse(typeof i.data=="string"?i.data:i.data.toString())}catch{return}for(let s of this.messageHandlers)s(o)},this.ws.onclose=()=>{this.ws=null,this.stopPing(),!this.stopped&&this.autoReconnect?this.scheduleReconnect():this.setStatus("disconnected"),n||(n=!0,t(new ta("WebSocket closed before connection established")))},this.ws.onerror=()=>{n||(n=!0,t(new ta(`WebSocket connection failed: ${this.url}`)))}})}disconnect(){this.stopped=!0,this.clearReconnectTimer(),this.stopPing(),this.ws&&(this.ws.onclose=null,this.ws.onerror=null,this.ws.onmessage=null,this.ws.close(),this.ws=null),this.setStatus("disconnected")}send(e){if(!this.ws||this.ws.readyState!==1)throw new ta("WebSocket is not connected");this.ws.send(JSON.stringify(e))}startPing(){this.stopPing(),this.pingInterval>0&&(this.pingTimer=setInterval(()=>{try{this.send({type:"ping"})}catch{}},this.pingInterval))}stopPing(){this.pingTimer!==null&&(clearInterval(this.pingTimer),this.pingTimer=null)}scheduleReconnect(){if(this.reconnectAttempt>=this.maxReconnectAttempts){this.setStatus("disconnected");return}this.setStatus("reconnecting");let e=Tvr(this.reconnectInterval*Math.pow(2,this.reconnectAttempt),this.reconnectInterval,Cvr);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{if(!this.stopped)try{await this.connect()}catch{}},e)}clearReconnectTimer(){this.reconnectTimer!==null&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}setStatus(e){if(this._status!==e){this._status=e;for(let t of this.statusHandlers)t(e)}}},Alt=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:DJ,n:UJ,Gx:Xdt,Gy:Qdt,a:fwe,d:mwe,h:kvr}=Alt,VJ=32,Bvr=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},bs=(e="")=>{let t=new Error(e);throw Bvr(t,bs),t},Nvr=e=>typeof e=="bigint",jvr=e=>typeof e=="string",qvr=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,W1=(e,t,r="")=>{let n=qvr(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},KJ=e=>new Uint8Array(e),Pwe=e=>Uint8Array.from(e),Slt=(e,t)=>e.toString(16).padStart(t,"0"),Iwe=e=>Array.from(W1(e)).map(t=>Slt(t,2)).join(""),F1={_0:48,_9:57,A:65,F:70,a:97,f:102},elt=e=>{if(e>=F1._0&&e<=F1._9)return e-F1._0;if(e>=F1.A&&e<=F1.F)return e-(F1.A-10);if(e>=F1.a&&e<=F1.f)return e-(F1.a-10)},Owe=e=>{let t="hex invalid";if(!jvr(e))return bs(t);let r=e.length,n=r/2;if(r%2)return bs(t);let i=KJ(n);for(let o=0,s=0;o<n;o++,s+=2){let a=elt(e.charCodeAt(s)),c=elt(e.charCodeAt(s+1));if(a===void 0||c===void 0)return bs(t);i[o]=a*16+c}return i},Tlt=()=>globalThis?.crypto,Uvr=()=>Tlt()?.subtle??bs("crypto.subtle must be defined, consider polyfill"),cA=(...e)=>{let t=0;for(let i of e)t+=W1(i).length;let r=KJ(t),n=0;return e.forEach(i=>{r.set(i,n),n+=i.length}),r},Mvr=(e=VJ)=>Tlt().getRandomValues(KJ(e)),zJ=BigInt,Tv=(e,t,r,n="bad number: out of range")=>{if(!Nvr(e))throw new TypeError(n);if(t<=e&&e<r)return e;throw new RangeError(n)},Tn=(e,t=DJ)=>{let r=e%t;return r>=0n?r:t+r},tlt=(1n<<255n)-1n,Ve=e=>{e<0n&&bs("negative coordinate");let t=(e>>255n)*19n+(e&tlt);return t=(t>>255n)*19n+(t&tlt),t%DJ},Plt=e=>Tn(e,UJ),Ilt=(e,t)=>{(e===0n||t<=0n)&&bs("no inverse n="+e+" mod="+t);let r=Tn(e,t),n=t,i=0n,o=1n;for(;r!==0n;){let s=n/r,a=n%r,c=i-o*s;n=r,r=a,i=o,o=c}return n===1n?Tn(i,t):bs("no inverse")},Olt=e=>{let t=Nlt[e];return typeof t!="function"&&bs("hashes."+e+" not set"),t},Clt=e=>W1(e,64,"digest"),hwe=e=>e instanceof fk?e:bs("Point expected"),wwe=2n**256n,fk=class Pv{static BASE;static ZERO;X;Y;Z;T;constructor(t,r,n,i){let o=wwe;this.X=Tv(t,0n,o),this.Y=Tv(r,0n,o),this.Z=Tv(n,1n,o),this.T=Tv(i,0n,o),Object.freeze(this)}static CURVE(){return Alt}static fromAffine(t){return new Pv(t.x,t.y,1n,Ve(t.x*t.y))}static fromBytes(t,r=!1){let n=mwe,i=Pwe(W1(t,VJ)),o=t[31];i[31]=o&-129;let s=klt(i);Tv(s,0n,r?wwe:DJ);let c=Ve(s*s),u=Tn(c-1n),d=Ve(n*c+1n),{isValid:l,value:p}=zvr(u,d);l||bs("bad point: y not sqrt");let f=(p&1n)===1n,m=(o&128)!==0;return!r&&p===0n&&m&&bs("bad point: x==0, isLastByteOdd"),m!==f&&(p=Tn(-p)),new Pv(p,s,1n,Ve(p*s))}static fromHex(t,r){return Pv.fromBytes(Owe(t),r)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=fwe,r=mwe,n=this;if(n.is0())return bs("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=Tn(l+Ve(r*Ve(c*u)));if(f!==m)return bs("bad point: equation left != right (1)");let h=Ve(i*o),y=Ve(s*a);return h!==y?bs("bad point: equation left != right (2)"):this}equals(t){let{X:r,Y:n,Z:i}=this,{X:o,Y:s,Z:a}=hwe(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(Cv)}negate(){return new Pv(Tn(-this.X),this.Y,this.Z,Tn(-this.T))}double(){let{X:t,Y:r,Z:n}=this,i=fwe,o=Ve(t*t),s=Ve(r*r),a=Ve(2n*n*n),c=Ve(i*o),u=Tn(t+r),d=Tn(Ve(u*u)-o-s),l=Tn(c+s),p=Tn(l-a),f=Tn(c-s),m=Ve(d*p),h=Ve(l*f),y=Ve(d*f),w=Ve(p*l);return new Pv(m,h,w,y)}add(t){let{X:r,Y:n,Z:i,T:o}=this,{X:s,Y:a,Z:c,T:u}=hwe(t),d=fwe,l=mwe,p=Ve(r*s),f=Ve(n*a),m=Ve(Ve(o*l)*u),h=Ve(i*c),y=Tn(Ve(Tn(r+n)*Tn(s+a))-p-f),w=Tn(h-m),x=Tn(h+m),_=Tn(f-Ve(d*p)),v=Ve(y*w),E=Ve(x*_),A=Ve(y*_),S=Ve(w*x);return new Pv(v,E,S,A)}subtract(t){return this.add(hwe(t).negate())}multiply(t,r=!0){if(!r&&t===0n||(Tv(t,1n,UJ),!r&&this.is0()))return Cv;if(t===1n)return this;if(this.equals(kv))return Yvr(t).p;let n=Cv,i=kv;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(Cv))return{x:0n,y:1n};let i=Ilt(n,DJ);Ve(n*i)!==1n&&bs("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=Rlt(r);return n[31]|=t&1n?128:0,n}toHex(){return Iwe(this.toBytes())}clearCofactor(){return this.multiply(zJ(kvr),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(UJ/2n,!1).double();return UJ%2n&&(t=t.add(this)),t.is0()}},kv=new fk(Xdt,Qdt,1n,Tn(Xdt*Qdt)),Cv=new fk(0n,1n,1n,0n);fk.BASE=kv;fk.ZERO=Cv;Rlt=e=>Owe(Slt(Tv(e,0n,wwe),64)).reverse(),klt=e=>zJ("0x"+Iwe(Pwe(W1(e)).reverse())),xm=(e,t)=>{let r=e;for(;t-- >0n;)r=Ve(r*r);return r},Dvr=e=>{let t=Ve(e*e),r=Ve(t*e),n=Ve(xm(r,2n)*r),i=Ve(xm(n,1n)*e),o=Ve(xm(i,5n)*i),s=Ve(xm(o,10n)*o),a=Ve(xm(s,20n)*s),c=Ve(xm(a,40n)*a),u=Ve(xm(c,80n)*c),d=Ve(xm(u,80n)*c),l=Ve(xm(d,10n)*o);return{pow_p_5_8:Ve(xm(l,2n)*e),b2:r}},rlt=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,zvr=(e,t)=>{let r=Ve(t*Ve(t*t)),n=Ve(Ve(r*r)*t),i=Dvr(Ve(e*n)).pow_p_5_8,o=Ve(e*Ve(r*i)),s=Ve(t*Ve(o*o)),a=o,c=Ve(o*rlt),u=s===e,d=s===Tn(-e),l=s===Tn(-e*rlt);return u&&(o=a),(d||l)&&(o=c),(Tn(o)&1n)===1n&&(o=Tn(-o)),{isValid:u||d,value:o}},xwe=e=>Plt(klt(e)),Cwe=(...e)=>Promise.resolve(Olt("sha512Async")(cA(...e))).then(Clt),Lvr=(...e)=>Clt(Olt("sha512")(cA(...e))),Blt=e=>{let t=Pwe(e),r=t.slice(0,32);r[0]&=248,r[31]&=127,r[31]|=64;let n=t.slice(32,64),i=xwe(r),o=kv.multiply(i),s=o.toBytes();return{head:r,prefix:n,scalar:i,point:o,pointBytes:s}},Hvr=e=>Cwe(W1(e,VJ)).then(Blt),Fvr=e=>Blt(Lvr(W1(e,VJ))),$vr=e=>Fvr(e).pointBytes,Vvr=e=>Cwe(e.hashable).then(e.finish),Kvr=(e,t,r)=>{let{pointBytes:n,scalar:i}=e,o=xwe(t),s=kv.multiply(o).toBytes();return{hashable:cA(s,n,r),finish:u=>{let d=Plt(o+xwe(u)*i);return W1(cA(s,Rlt(d)),64)}}},Wvr=async(e,t)=>{let r=W1(e),n=await Hvr(t),i=await Cwe(n.prefix,r);return Vvr(Kvr(n,i,r))},Rwe=Object.freeze({bytesToHex:Iwe,hexToBytes:Owe,concatBytes:cA,mod:Tn,invert:Ilt,randomBytes:Mvr}),Nlt={sha512Async:async e=>{let t=Uvr(),r=cA(e);return KJ(await t.digest("SHA-512",r.buffer))},sha512:void 0},LJ=8,Gvr=256,jlt=Math.ceil(Gvr/LJ)+1,Ewe=2**(LJ-1),Jvr=()=>{let e=[],t=kv,r=t;for(let n=0;n<jlt;n++){r=t,e.push(r);for(let i=1;i<Ewe;i++)r=r.add(t),e.push(r);t=r.double()}return e},nlt=void 0,ilt=(e,t)=>{let r=t.negate();return e?r:t},Yvr=e=>{let t=nlt||(nlt=Jvr()),r=Cv,n=kv,i=2**LJ,o=i,s=zJ(i-1),a=zJ(LJ);for(let c=0;c<jlt;c++){let u=Number(e&s);e>>=a,u>Ewe&&(u-=o,e+=1n);let d=c*Ewe,l=d,p=d+Math.abs(u)-1,f=c%2!==0,m=u<0;u===0?n=n.add(ilt(f,t[l])):r=r.add(ilt(m,t[p]))}return e!==0n&&bs("invalid wnaf"),{p:r,f:n}};Mlt=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});Dlt=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=ywe(this.buffer)}update(e){olt(this),qlt(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=ywe(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){olt(this),Xvr(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:i}=this,{pos:o}=this;t[o++]=128,pk(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=ywe(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()}},Gb=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ra=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),RJ=BigInt(2**32-1),slt=BigInt(32);alt=(e,t,r)=>e>>>r,clt=(e,t,r)=>e<<32-r|t>>>r,iA=(e,t,r)=>e>>>r|t<<32-r,oA=(e,t,r)=>e<<32-r|t>>>r,kJ=(e,t,r)=>e<<64-r|t>>>r-32,BJ=(e,t,r)=>e>>>r-32|t<<64-r;n4r=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),i4r=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,o4r=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),s4r=(e,t,r,n,i)=>t+r+n+i+(e/2**32|0)|0,a4r=(e,t,r,n,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(i>>>0),c4r=(e,t,r,n,i,o)=>t+r+n+i+o+(e/2**32|0)|0,u4r=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Jb=new Uint32Array(64),d4r=class extends Dlt{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:r,D:n,E:i,F:o,G:s,H:a}=this;return[e,t,r,n,i,o,s,a]}set(e,t,r,n,i,o,s,a){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=i|0,this.F=o|0,this.G=s|0,this.H=a|0}process(e,t){for(let d=0;d<16;d++,t+=4)Jb[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let l=Jb[d-15],p=Jb[d-2],f=Em(l,7)^Em(l,18)^l>>>3,m=Em(p,17)^Em(p,19)^p>>>10;Jb[d]=m+Jb[d-7]+f+Jb[d-16]|0}let{A:r,B:n,C:i,D:o,E:s,F:a,G:c,H:u}=this;for(let d=0;d<64;d++){let l=Em(s,6)^Em(s,11)^Em(s,25),p=u+l+Qvr(s,a,c)+u4r[d]+Jb[d]|0,m=(Em(r,2)^Em(r,13)^Em(r,22))+e4r(r,n,i)|0;u=c,c=a,a=s,s=o+p|0,o=i,i=n,n=r,r=p+m|0}r=r+this.A|0,n=n+this.B|0,i=i+this.C|0,o=o+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(r,n,i,o,s,a,c,u)}roundClean(){pk(Jb)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),pk(this.buffer)}},l4r=class extends d4r{A=Gb[0]|0;B=Gb[1]|0;C=Gb[2]|0;D=Gb[3]|0;E=Gb[4]|0;F=Gb[5]|0;G=Gb[6]|0;H=Gb[7]|0;constructor(){super(32)}},zlt=r4r(["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))),p4r=zlt[0],f4r=zlt[1],Yb=new Uint32Array(80),Zb=new Uint32Array(80),m4r=class extends Dlt{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 x=0;x<16;x++,t+=4)Yb[x]=e.getUint32(t),Zb[x]=e.getUint32(t+=4);for(let x=16;x<80;x++){let _=Yb[x-15]|0,v=Zb[x-15]|0,E=iA(_,v,1)^iA(_,v,8)^alt(_,v,7),A=oA(_,v,1)^oA(_,v,8)^clt(_,v,7),S=Yb[x-2]|0,C=Zb[x-2]|0,I=iA(S,C,19)^kJ(S,C,61)^alt(S,C,6),R=oA(S,C,19)^BJ(S,C,61)^clt(S,C,6),U=o4r(A,R,Zb[x-7],Zb[x-16]),j=s4r(U,E,I,Yb[x-7],Yb[x-16]);Yb[x]=j|0,Zb[x]=U|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:w}=this;for(let x=0;x<80;x++){let _=iA(d,l,14)^iA(d,l,18)^kJ(d,l,41),v=oA(d,l,14)^oA(d,l,18)^BJ(d,l,41),E=d&p^~d&m,A=l&f^~l&h,S=a4r(w,v,A,f4r[x],Zb[x]),C=c4r(S,y,_,E,p4r[x],Yb[x]),I=S|0,R=iA(r,n,28)^kJ(r,n,34)^kJ(r,n,39),U=oA(r,n,28)^BJ(r,n,34)^BJ(r,n,39),j=r&i^r&s^i&s,q=n&o^n&a^o&a;y=m|0,w=h|0,m=p|0,h=f|0,p=d|0,f=l|0,{h:d,l}=$1(c|0,u|0,C|0,I|0),c=s|0,u=a|0,s=i|0,a=o|0,i=r|0,o=n|0;let B=n4r(I,U,q);r=i4r(B,C,R,j),n=B|0}({h:r,l:n}=$1(this.Ah|0,this.Al|0,r|0,n|0)),{h:i,l:o}=$1(this.Bh|0,this.Bl|0,i|0,o|0),{h:s,l:a}=$1(this.Ch|0,this.Cl|0,s|0,a|0),{h:c,l:u}=$1(this.Dh|0,this.Dl|0,c|0,u|0),{h:d,l}=$1(this.Eh|0,this.El|0,d|0,l|0),{h:p,l:f}=$1(this.Fh|0,this.Fl|0,p|0,f|0),{h:m,l:h}=$1(this.Gh|0,this.Gl|0,m|0,h|0),{h:y,l:w}=$1(this.Hh|0,this.Hl|0,y|0,w|0),this.set(r,n,i,o,s,a,c,u,d,l,p,f,m,h,y,w)}roundClean(){pk(Yb,Zb)}destroy(){this.destroyed=!0,pk(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},h4r=class extends m4r{Ah=ra[0]|0;Al=ra[1]|0;Bh=ra[2]|0;Bl=ra[3]|0;Ch=ra[4]|0;Cl=ra[5]|0;Dh=ra[6]|0;Dl=ra[7]|0;Eh=ra[8]|0;El=ra[9]|0;Fh=ra[10]|0;Fl=ra[11]|0;Gh=ra[12]|0;Gl=ra[13]|0;Hh=ra[14]|0;Hl=ra[15]|0;constructor(){super(64)}},y4r=Ult(()=>new l4r,Mlt(1)),g4r=Ult(()=>new h4r,Mlt(3)),ult=Nlt;ult.sha512||(ult.sha512=e=>g4r(e));v4r=Rwe.bytesToHex,Llt=Rwe.hexToBytes;Rwe.concatBytes;x4r=new TextEncoder,E4r={subwayAgentMsgV1:"message_id;sender_peer_id;sender_name;timestamp_ms;message_type;payload_hash;nonce"};Llt("302e020100300506032b657004220420");Llt("302a300506032b6570032100");Hlt="ABCDEFGHJKLMNPQRSTUVWXYZ23456789",P4r=Hlt.length-1;if((Hlt.length&P4r)!==0)throw new Error("agent pairing code alphabet must contain a power-of-two number of symbols");Flt=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:HJ,n:MJ,Gx:dlt,Gy:llt,a:gwe,d:bwe,h:I4r}=Flt,uA=32,O4r=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},_s=(e="")=>{let t=new Error(e);throw O4r(t,_s),t},C4r=e=>typeof e=="bigint",R4r=e=>typeof e=="string",k4r=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,t2=(e,t,r="")=>{let n=k4r(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},WJ=e=>new Uint8Array(e),kwe=e=>Uint8Array.from(e),$lt=(e,t)=>e.toString(16).padStart(t,"0"),Vlt=e=>Array.from(t2(e)).map(t=>$lt(t,2)).join(""),V1={_0:48,_9:57,A:65,F:70,a:97,f:102},plt=e=>{if(e>=V1._0&&e<=V1._9)return e-V1._0;if(e>=V1.A&&e<=V1.F)return e-(V1.A-10);if(e>=V1.a&&e<=V1.f)return e-(V1.a-10)},Klt=e=>{let t="hex invalid";if(!R4r(e))return _s(t);let r=e.length,n=r/2;if(r%2)return _s(t);let i=WJ(n);for(let o=0,s=0;o<n;o++,s+=2){let a=plt(e.charCodeAt(s)),c=plt(e.charCodeAt(s+1));if(a===void 0||c===void 0)return _s(t);i[o]=a*16+c}return i},Wlt=()=>globalThis?.crypto,B4r=()=>Wlt()?.subtle??_s("crypto.subtle must be defined, consider polyfill"),Bwe=(...e)=>{let t=0;for(let i of e)t+=t2(i).length;let r=WJ(t),n=0;return e.forEach(i=>{r.set(i,n),n+=i.length}),r},N4r=(e=uA)=>Wlt().getRandomValues(WJ(e)),FJ=BigInt,Iv=(e,t,r,n="bad number: out of range")=>{if(!C4r(e))throw new TypeError(n);if(t<=e&&e<r)return e;throw new RangeError(n)},Fn=(e,t=HJ)=>{let r=e%t;return r>=0n?r:t+r},flt=(1n<<255n)-1n,Ke=e=>{e<0n&&_s("negative coordinate");let t=(e>>255n)*19n+(e&flt);return t=(t>>255n)*19n+(t&flt),t%HJ},j4r=e=>Fn(e,MJ),q4r=(e,t)=>{(e===0n||t<=0n)&&_s("no inverse n="+e+" mod="+t);let r=Fn(e,t),n=t,i=0n,o=1n;for(;r!==0n;){let s=n/r,a=n%r,c=i-o*s;n=r,r=a,i=o,o=c}return n===1n?Fn(i,t):_s("no inverse")},Glt=e=>{let t=Qlt[e];return typeof t!="function"&&_s("hashes."+e+" not set"),t},Jlt=e=>t2(e,64,"digest"),_we=e=>e instanceof mk?e:_s("Point expected"),Awe=2n**256n,mk=class Ov{static BASE;static ZERO;X;Y;Z;T;constructor(t,r,n,i){let o=Awe;this.X=Iv(t,0n,o),this.Y=Iv(r,0n,o),this.Z=Iv(n,1n,o),this.T=Iv(i,0n,o),Object.freeze(this)}static CURVE(){return Flt}static fromAffine(t){return new Ov(t.x,t.y,1n,Ke(t.x*t.y))}static fromBytes(t,r=!1){let n=bwe,i=kwe(t2(t,uA)),o=t[31];i[31]=o&-129;let s=Ylt(i);Iv(s,0n,r?Awe:HJ);let c=Ke(s*s),u=Fn(c-1n),d=Ke(n*c+1n),{isValid:l,value:p}=D4r(u,d);l||_s("bad point: y not sqrt");let f=(p&1n)===1n,m=(o&128)!==0;return!r&&p===0n&&m&&_s("bad point: x==0, isLastByteOdd"),m!==f&&(p=Fn(-p)),new Ov(p,s,1n,Ke(p*s))}static fromHex(t,r){return Ov.fromBytes(Klt(t),r)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=gwe,r=bwe,n=this;if(n.is0())return _s("bad point: ZERO");let{X:i,Y:o,Z:s,T:a}=n,c=Ke(i*i),u=Ke(o*o),d=Ke(s*s),l=Ke(d*d),p=Ke(c*t),f=Ke(d*(p+u)),m=Fn(l+Ke(r*Ke(c*u)));if(f!==m)return _s("bad point: equation left != right (1)");let h=Ke(i*o),y=Ke(s*a);return h!==y?_s("bad point: equation left != right (2)"):this}equals(t){let{X:r,Y:n,Z:i}=this,{X:o,Y:s,Z:a}=_we(t),c=Ke(r*a),u=Ke(o*i),d=Ke(n*a),l=Ke(s*i);return c===u&&d===l}is0(){return this.equals(Rv)}negate(){return new Ov(Fn(-this.X),this.Y,this.Z,Fn(-this.T))}double(){let{X:t,Y:r,Z:n}=this,i=gwe,o=Ke(t*t),s=Ke(r*r),a=Ke(2n*n*n),c=Ke(i*o),u=Fn(t+r),d=Fn(Ke(u*u)-o-s),l=Fn(c+s),p=Fn(l-a),f=Fn(c-s),m=Ke(d*p),h=Ke(l*f),y=Ke(d*f),w=Ke(p*l);return new Ov(m,h,w,y)}add(t){let{X:r,Y:n,Z:i,T:o}=this,{X:s,Y:a,Z:c,T:u}=_we(t),d=gwe,l=bwe,p=Ke(r*s),f=Ke(n*a),m=Ke(Ke(o*l)*u),h=Ke(i*c),y=Fn(Ke(Fn(r+n)*Fn(s+a))-p-f),w=Fn(h-m),x=Fn(h+m),_=Fn(f-Ke(d*p)),v=Ke(y*w),E=Ke(x*_),A=Ke(y*_),S=Ke(w*x);return new Ov(v,E,S,A)}subtract(t){return this.add(_we(t).negate())}multiply(t,r=!0){if(!r&&t===0n||(Iv(t,1n,MJ),!r&&this.is0()))return Rv;if(t===1n)return this;if(this.equals(dA))return J4r(t).p;let n=Rv,i=dA;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(Rv))return{x:0n,y:1n};let i=q4r(n,HJ);Ke(n*i)!==1n&&_s("invalid inverse");let o=Ke(t*i),s=Ke(r*i);return{x:o,y:s}}toBytes(){let{x:t,y:r}=this.toAffine(),n=U4r(r);return n[31]|=t&1n?128:0,n}toHex(){return Vlt(this.toBytes())}clearCofactor(){return this.multiply(FJ(I4r),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(MJ/2n,!1).double();return MJ%2n&&(t=t.add(this)),t.is0()}},dA=new mk(dlt,llt,1n,Fn(dlt*llt)),Rv=new mk(0n,1n,1n,0n);mk.BASE=dA;mk.ZERO=Rv;U4r=e=>Klt($lt(Iv(e,0n,Awe),64)).reverse(),Ylt=e=>FJ("0x"+Vlt(kwe(t2(e)).reverse())),Am=(e,t)=>{let r=e;for(;t-- >0n;)r=Ke(r*r);return r},M4r=e=>{let t=Ke(e*e),r=Ke(t*e),n=Ke(Am(r,2n)*r),i=Ke(Am(n,1n)*e),o=Ke(Am(i,5n)*i),s=Ke(Am(o,10n)*o),a=Ke(Am(s,20n)*s),c=Ke(Am(a,40n)*a),u=Ke(Am(c,80n)*c),d=Ke(Am(u,80n)*c),l=Ke(Am(d,10n)*o);return{pow_p_5_8:Ke(Am(l,2n)*e),b2:r}},mlt=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,D4r=(e,t)=>{let r=Ke(t*Ke(t*t)),n=Ke(Ke(r*r)*t),i=M4r(Ke(e*n)).pow_p_5_8,o=Ke(e*Ke(r*i)),s=Ke(t*Ke(o*o)),a=o,c=Ke(o*mlt),u=s===e,d=s===Fn(-e),l=s===Fn(-e*mlt);return u&&(o=a),(d||l)&&(o=c),(Fn(o)&1n)===1n&&(o=Fn(-o)),{isValid:u||d,value:o}},z4r=e=>j4r(Ylt(e)),L4r=(...e)=>Promise.resolve(Glt("sha512Async")(Bwe(...e))).then(Jlt),H4r=(...e)=>Jlt(Glt("sha512")(Bwe(...e))),Zlt=e=>{let t=kwe(e),r=t.slice(0,32);r[0]&=248,r[31]&=127,r[31]|=64;let n=t.slice(32,64),i=z4r(r),o=dA.multiply(i),s=o.toBytes();return{head:r,prefix:n,scalar:i,point:o,pointBytes:s}},F4r=e=>L4r(t2(e,uA)).then(Zlt),Xlt=e=>Zlt(H4r(t2(e,uA))),$4r=e=>Xlt(e).pointBytes,Qlt={sha512Async:async e=>{let t=B4r(),r=Bwe(e);return WJ(await t.digest("SHA-512",r.buffer))},sha512:void 0},V4r=e=>(e=e===void 0?N4r(uA):e,t2(e,uA)),K4r=Object.freeze({getExtendedPublicKeyAsync:F4r,getExtendedPublicKey:Xlt,randomSecretKey:V4r}),$J=8,W4r=256,ept=Math.ceil(W4r/$J)+1,Swe=2**($J-1),G4r=()=>{let e=[],t=dA,r=t;for(let n=0;n<ept;n++){r=t,e.push(r);for(let i=1;i<Swe;i++)r=r.add(t),e.push(r);t=r.double()}return e},hlt=void 0,ylt=(e,t)=>{let r=t.negate();return e?r:t},J4r=e=>{let t=hlt||(hlt=G4r()),r=Rv,n=dA,i=2**$J,o=i,s=FJ(i-1),a=FJ($J);for(let c=0;c<ept;c++){let u=Number(e&s);e>>=a,u>Swe&&(u-=o,e+=1n);let d=c*Swe,l=d,p=d+Math.abs(u)-1,f=c%2!==0,m=u<0;u===0?n=n.add(ylt(f,t[l])):r=r.add(ylt(m,t[p]))}return e!==0n&&_s("invalid wnaf"),{p:r,f:n}};Q4r=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}),ewr=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=vwe(this.buffer)}update(e){glt(this),tpt(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=vwe(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){glt(this),Z4r(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:i}=this,{pos:o}=this;t[o++]=128,Twe(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=vwe(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()}},na=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),NJ=BigInt(2**32-1),blt=BigInt(32);_lt=(e,t,r)=>e>>>r,vlt=(e,t,r)=>e<<32-r|t>>>r,sA=(e,t,r)=>e>>>r|t<<32-r,aA=(e,t,r)=>e<<32-r|t>>>r,jJ=(e,t,r)=>e<<64-r|t>>>r-32,qJ=(e,t,r)=>e>>>r-32|t<<64-r;nwr=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),iwr=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,owr=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),swr=(e,t,r,n,i)=>t+r+n+i+(e/2**32|0)|0,awr=(e,t,r,n,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(i>>>0),cwr=(e,t,r,n,i,o)=>t+r+n+i+o+(e/2**32|0)|0,rpt=rwr(["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))),uwr=rpt[0],dwr=rpt[1],Xb=new Uint32Array(80),Qb=new Uint32Array(80),lwr=class extends ewr{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 x=0;x<16;x++,t+=4)Xb[x]=e.getUint32(t),Qb[x]=e.getUint32(t+=4);for(let x=16;x<80;x++){let _=Xb[x-15]|0,v=Qb[x-15]|0,E=sA(_,v,1)^sA(_,v,8)^_lt(_,v,7),A=aA(_,v,1)^aA(_,v,8)^vlt(_,v,7),S=Xb[x-2]|0,C=Qb[x-2]|0,I=sA(S,C,19)^jJ(S,C,61)^_lt(S,C,6),R=aA(S,C,19)^qJ(S,C,61)^vlt(S,C,6),U=owr(A,R,Qb[x-7],Qb[x-16]),j=swr(U,E,I,Xb[x-7],Xb[x-16]);Xb[x]=j|0,Qb[x]=U|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:w}=this;for(let x=0;x<80;x++){let _=sA(d,l,14)^sA(d,l,18)^jJ(d,l,41),v=aA(d,l,14)^aA(d,l,18)^qJ(d,l,41),E=d&p^~d&m,A=l&f^~l&h,S=awr(w,v,A,dwr[x],Qb[x]),C=cwr(S,y,_,E,uwr[x],Xb[x]),I=S|0,R=sA(r,n,28)^jJ(r,n,34)^jJ(r,n,39),U=aA(r,n,28)^qJ(r,n,34)^qJ(r,n,39),j=r&i^r&s^i&s,q=n&o^n&a^o&a;y=m|0,w=h|0,m=p|0,h=f|0,p=d|0,f=l|0,{h:d,l}=K1(c|0,u|0,C|0,I|0),c=s|0,u=a|0,s=i|0,a=o|0,i=r|0,o=n|0;let B=nwr(I,U,q);r=iwr(B,C,R,j),n=B|0}({h:r,l:n}=K1(this.Ah|0,this.Al|0,r|0,n|0)),{h:i,l:o}=K1(this.Bh|0,this.Bl|0,i|0,o|0),{h:s,l:a}=K1(this.Ch|0,this.Cl|0,s|0,a|0),{h:c,l:u}=K1(this.Dh|0,this.Dl|0,c|0,u|0),{h:d,l}=K1(this.Eh|0,this.El|0,d|0,l|0),{h:p,l:f}=K1(this.Fh|0,this.Fl|0,p|0,f|0),{h:m,l:h}=K1(this.Gh|0,this.Gl|0,m|0,h|0),{h:y,l:w}=K1(this.Hh|0,this.Hl|0,y|0,w|0),this.set(r,n,i,o,s,a,c,u,d,l,p,f,m,h,y,w)}roundClean(){Twe(Xb,Qb)}destroy(){this.destroyed=!0,Twe(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},pwr=class extends lwr{Ah=na[0]|0;Al=na[1]|0;Bh=na[2]|0;Bl=na[3]|0;Ch=na[4]|0;Cl=na[5]|0;Dh=na[6]|0;Dl=na[7]|0;Eh=na[8]|0;El=na[9]|0;Fh=na[10]|0;Fl=na[11]|0;Gh=na[12]|0;Gl=na[13]|0;Hh=na[14]|0;Hl=na[15]|0;constructor(){super(64)}},fwr=X4r(()=>new pwr,Q4r(3)),wlt=Qlt;wlt.sha512||(wlt.sha512=e=>fwr(e));_wr="ws://localhost:9001/ws",vwr=3e4,ipt=class{transport;options;_peerId=null;_name;_keypair=null;messageHandlers=new Set;topicHandlers=new Map;rpcHandlers=new Map;defaultRpcHandler=null;pendingCalls=new Map;pendingSend=new Map;pendingResolve=new Map;eventListeners=new Map;registerPromise=null;hasConnectedOnce=!1;constructor(e){if(this._name=lk(e.name),e.keyPath)try{this._keypair=gwr(e.keyPath)}catch{}this.options={name:this._name,url:e.url??_wr,relay:e.relay??"",autoReconnect:e.autoReconnect??!0,reconnectInterval:e.reconnectInterval??1e3,maxReconnectAttempts:e.maxReconnectAttempts??10,rpcTimeout:e.rpcTimeout??vwr,pingInterval:e.pingInterval??3e4,binding:e.binding??""},this.transport=new Rvr({url:this.options.url,autoReconnect:this.options.autoReconnect,reconnectInterval:this.options.reconnectInterval,maxReconnectAttempts:this.options.maxReconnectAttempts,pingInterval:this.options.pingInterval}),this.transport.onMessage(t=>this.handleBridgeMessage(t)),this.transport.onStatusChange(t=>this.handleStatusChange(t))}initKeypairFromSecret(e){try{let t=Buffer.from(e,"base64"),r=T4r(new Uint8Array(t));r&&(this._keypair={privateKey:r,publicKey:b4r(r)})}catch{}}get name(){return this._name}get peerId(){return this._peerId}get status(){return this.transport.status}async connect(){return await this.transport.connect(),new Promise((e,t)=>{this.registerPromise={resolve:e,reject:t};let r={type:"register",name:this._name};this.options.relay&&(r.relay=this.options.relay),this._keypair&&(r.public_key=xlt(this._keypair.publicKey)),this.options.binding&&(r.binding=this.options.binding);try{this.transport.send(r)}catch(n){this.registerPromise=null,t(n instanceof Error?n:new ta(String(n)))}})}disconnect(){for(let[,e]of this.pendingCalls)clearTimeout(e.timer),e.reject(new ta("Client disconnected"));this.pendingCalls.clear();for(let[,e]of this.pendingSend)e.reject(new ta("Client disconnected"));this.pendingSend.clear();for(let[,e]of this.pendingResolve)e.reject(new ta("Client disconnected"));this.pendingResolve.clear(),this.registerPromise&&(this.registerPromise.reject(new ta("Client disconnected")),this.registerPromise=null),this.transport.disconnect(),this._peerId=null,this.hasConnectedOnce=!1}async send(e,t,r,n){let i=lk(e),o=pwe();return new Promise((s,a)=>{this.pendingSend.set(i,{resolve:s,reject:a});try{this.transport.send({type:"send",to:i,message_type:t,payload:r,metadata:n})}catch(c){this.pendingSend.delete(i),a(c instanceof Error?c:new ta(String(c)))}setTimeout(()=>{this.pendingSend.has(i)&&(this.pendingSend.delete(i),s({messageId:o,to:i}))},5e3)})}async sendSigned(e,t,r,n){if(!this._keypair||!this._peerId)return this.send(e,t,r,n);let i=lk(e),o=pwe(),s=Date.now(),a=Math.floor(Math.random()*2**32),c=new TextEncoder().encode(r),{signature:u,signatureInput:d}=await bwr(this._keypair.privateKey,o,this._peerId,this._name,s,t,c,a);return new Promise((l,p)=>{this.pendingSend.set(i,{resolve:l,reject:p});try{this.transport.send({type:"send_signed",to:i,message_id:o,sender_peer_id:this._peerId,sender_name:this._name,timestamp_ms:s,message_type:t,payload:r,metadata:n,signature:Buffer.from(u).toString("base64"),signature_input:d,nonce:a})}catch(f){this.pendingSend.delete(i),p(f instanceof Error?f:new ta(String(f)))}setTimeout(()=>{this.pendingSend.has(i)&&(this.pendingSend.delete(i),l({messageId:o,to:i}))},5e3)})}async call(e,t,r,n){let i=lk(e),o=n?.correlationId??pwe(),s=n?.timeout??this.options.rpcTimeout;return new Promise((a,c)=>{let u=setTimeout(()=>{this.pendingCalls.delete(o),c(new dk(`RPC call to ${i}.${t} timed out after ${s}ms`))},s);this.pendingCalls.set(o,{resolve:a,reject:c,timer:u});try{this.transport.send({type:"call",to:i,method:t,payload:r??"",correlation_id:o})}catch(d){clearTimeout(u),this.pendingCalls.delete(o),c(d instanceof Error?d:new ta(String(d)))}})}async broadcast(e,t,r){this.transport.send({type:"broadcast",topic:e,message_type:t,payload:r})}subscribe(e,t){let r=this.topicHandlers.get(e);if(!r){r=new Set,this.topicHandlers.set(e,r);try{this.transport.send({type:"subscribe",topic:e})}catch{}}return r.add(t),()=>{r.delete(t),r.size===0&&this.topicHandlers.delete(e)}}onMessage(e){return this.messageHandlers.add(e),()=>this.messageHandlers.delete(e)}onCall(e,t){return this.rpcHandlers.set(e,t),()=>this.rpcHandlers.delete(e)}onAnyCall(e){return this.defaultRpcHandler=e,()=>{this.defaultRpcHandler=null}}async resolve(e){let t=lk(e);return new Promise((r,n)=>{this.pendingResolve.set(t,{resolve:r,reject:n});try{this.transport.send({type:"resolve",name:t})}catch(i){this.pendingResolve.delete(t),n(i instanceof Error?i:new ta(String(i)))}setTimeout(()=>{this.pendingResolve.has(t)&&(this.pendingResolve.delete(t),n(new dk(`Resolve ${t} timed out`)))},1e4)})}on(e,t){let r=this.eventListeners.get(e);return r||(r=new Set,this.eventListeners.set(e,r)),r.add(t),()=>r.delete(t)}off(e,t){let r=this.eventListeners.get(e);r&&r.delete(t)}emit(e,...t){let r=this.eventListeners.get(e);if(r)for(let n of r)try{n(...t)}catch{}}handleBridgeMessage(e){switch(e.type){case"registered":this._peerId=e.peer_id,this._name=e.name,e.secret_key&&!this._keypair&&this.initKeypairFromSecret(e.secret_key),this.hasConnectedOnce=!0,this.registerPromise&&(this.registerPromise.resolve(),this.registerPromise=null),this.emit("connected",{name:e.name,peerId:e.peer_id}),this.resubscribeTopics();break;case"sent":{let t=this.pendingSend.get(e.to);t&&(this.pendingSend.delete(e.to),t.resolve({messageId:e.message_id,to:e.to}));break}case"call_result":{let t=this.pendingCalls.get(e.correlation_id);t&&(clearTimeout(t.timer),this.pendingCalls.delete(e.correlation_id),t.resolve({correlationId:e.correlation_id,success:e.success,payload:e.payload,error:e.error}));break}case"message":{let t={fromName:e.from_name,fromPeerId:e.from_peer_id,messageId:e.message_id,messageType:e.message_type,payload:e.payload,metadata:e.metadata??{},timestampMs:e.timestamp_ms,verified:e.verified,provenance:e.provenance?.map(r=>({signerName:r.signer_name,verified:r.verified})),attestation:e.attestation?{relayName:e.attestation.relay_name,verified:e.attestation.verified}:void 0,delegation:e.delegation?{parentName:e.delegation.parent_name,scope:e.delegation.scope,valid:e.delegation.valid,expired:e.delegation.expired}:void 0};for(let r of this.messageHandlers)try{r(t)}catch{}this.emit("message",t);break}case"inbound_call":this.handleInboundCall(e);break;case"broadcast_message":{let t={topic:e.topic,fromName:e.from_name,fromPeerId:e.from_peer_id,messageId:e.message_id,messageType:e.message_type,payload:e.payload,metadata:e.metadata??{},timestampMs:e.timestamp_ms,verified:e.verified,provenance:e.provenance?.map(n=>({signerName:n.signer_name,verified:n.verified})),attestation:e.attestation?{relayName:e.attestation.relay_name,verified:e.attestation.verified}:void 0,delegation:e.delegation?{parentName:e.delegation.parent_name,scope:e.delegation.scope,valid:e.delegation.valid,expired:e.delegation.expired}:void 0},r=this.topicHandlers.get(e.topic);if(r)for(let n of r)try{n(t)}catch{}this.emit("broadcast",t);break}case"resolved":{let t=this.pendingResolve.get(e.name);t&&(this.pendingResolve.delete(e.name),t.resolve({name:e.name,peerId:e.peer_id}));break}case"error":{let t=uwe(e.code,e.message);this.registerPromise&&e.code==="register_failed"&&(this.registerPromise.reject(new CJ(e.message)),this.registerPromise=null),this.emit("error",t);break}}}async handleInboundCall(e){let t={correlationId:e.correlation_id,fromName:e.from_name,fromPeerId:e.from_peer_id,method:e.method,payload:e.payload,verified:e.verified},r=this.rpcHandlers.get(e.method)??this.defaultRpcHandler,n;if(!r)n={success:!1,error:`No handler for method: ${e.method}`};else try{n=await r(t)}catch(i){n={success:!1,error:i instanceof Error?i.message:String(i)}}try{this.transport.send({type:"call_response",correlation_id:e.correlation_id,success:n.success,payload:n.payload??"",error:n.error??""})}catch{}}handleStatusChange(e){switch(e){case"disconnected":this._peerId=null,this.emit("disconnected");break;case"reconnecting":this.emit("reconnecting",this.transport.reconnectAttempt??0);break;case"connected":if(this.hasConnectedOnce){let t={type:"register",name:this.options.name};this.options.relay&&(t.relay=this.options.relay),this._keypair&&(t.public_key=xlt(this._keypair.publicKey));try{this.transport.send(t)}catch{}}break}}resubscribeTopics(){for(let e of this.topicHandlers.keys())try{this.transport.send({type:"subscribe",topic:e})}catch{}}};});var zwe={};Gi(zwe,{SUBWAY_PROTOCOL:()=>ypt,registerDirect:()=>Bwr,resolveDirect:()=>Nwr});function qwe(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 Wd(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 Uwe(e,t){return e<<3|t}function hk(e,t,r){e.push(Uwe(t,2)),qwe(e,r.length);for(let n of r)e.push(n)}function wwr(e,t){let r=[];return hk(r,1,jwe.encode(e)),t&&t.length>0&&hk(r,2,jwe.encode(t)),Uint8Array.from(r)}function xwr(e,t,r){let n=[];return r!==0n&&(n.push(Uwe(1,0)),qwe(n,r)),hk(n,2,wwr(e,t)),Uint8Array.from(n)}function Ewr(e){let t=[];return hk(t,1,jwe.encode(e)),Uint8Array.from(t)}function Awr(e,t){let r=[];return t!==0n&&(r.push(Uwe(1,0)),qwe(r,t)),hk(r,3,Ewr(e)),Uint8Array.from(r)}function Swr(e){let t=0,r={success:!1,error:""};for(;t<e.length;){let[n,i]=Wd(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===0){let[a,c]=Wd(e,t);t=c,r.success=a!==0n}else if(o===2&&s===2){let[a,c]=Wd(e,t),u=c,d=u+Number(a);r.error=mpt.decode(e.subarray(u,d)),t=d}else t=Mwe(e,t,s)}return r}function Twr(e){let t=0,r={peerId:new Uint8Array(0),error:""};for(;t<e.length;){let[n,i]=Wd(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===2){let[a,c]=Wd(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]=Wd(e,t),u=c,d=u+Number(a);r.error=mpt.decode(e.subarray(u,d)),t=d}else t=Mwe(e,t,s)}return r}function Mwe(e,t,r){if(r===0)return Wd(e,t)[1];if(r===2){let[n,i]=Wd(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 hpt(e){let t=0,r={requestId:0n};for(;t<e.length;){let[n,i]=Wd(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===0){let[a,c]=Wd(e,t);t=c,r.requestId=a}else if(o===13&&s===2){let[a,c]=Wd(e,t),u=c,d=u+Number(a);r.registerNameResponse=Swr(e.subarray(u,d)),t=d}else if(o===14&&s===2){let[a,c]=Wd(e,t),u=c,d=u+Number(a);r.resolveNameResponse=Twr(e.subarray(u,d)),t=d}else t=Mwe(e,t,s)}return r}function Pwr(e){let t=new Uint8Array(4+e.length);return new DataView(t.buffer).setUint32(0,e.length,!1),t.set(e,4),t}function Dwe(e){return new DataView(e.buffer,e.byteOffset,4).getUint32(0,!1)}function Iwr(e){if(e.length<4)return{success:!1,error:"short reply (no length prefix)"};let t=Dwe(e.subarray(0,4));return e.length<4+t?{success:!1,error:`truncated frame (have ${e.length-4}, need ${t})`}:hpt(e.subarray(4,4+t)).registerNameResponse??{success:!1,error:"reply carried no register_name_response"}}function Owr(e){if(e.length<4)return{peerId:new Uint8Array(0),error:"short reply (no length prefix)"};let t=Dwe(e.subarray(0,4));return e.length<4+t?{peerId:new Uint8Array(0),error:`truncated frame (have ${e.length-4}, need ${t})`}:hpt(e.subarray(4,4+t)).resolveNameResponse??{peerId:new Uint8Array(0),error:"reply carried no resolve_name_response"}}function Nwe(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 kwr(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>spt)throw new Error("subway: reply exceeded max size");if(n<0&&r>=4&&(n=4+Dwe(Nwe(t).subarray(0,4)),n>spt))throw new Error("subway: declared frame exceeds max size");if(n>=0&&r>=n)return Nwe(t).subarray(0,n)}return Nwe(t)}async function gpt(e){return(0,apt.createLibp2p)({...e?{privateKey:await(0,lpt.generateKeyPairFromSeed)("Ed25519",e)}:{},transports:[(0,cpt.tcp)()],connectionEncrypters:[(0,upt.noise)()],streamMuxers:[(0,dpt.yamux)()],connectionGater:{denyDialMultiaddr:async()=>!1}})}async function bpt(e,t,r){let n=await e.dialProtocol((0,ppt.multiaddr)(t),ypt,{signal:AbortSignal.timeout(Cwr)});n.send(Pwr(r));let i;return Promise.race([kwr(n),new Promise((o,s)=>{i=setTimeout(()=>s(new Error("subway: request timed out")),Rwr)})]).finally(()=>clearTimeout(i))}async function Bwr(e){let t=await gpt(e.seed);try{let r=await bpt(t,e.relayMultiaddr,xwr(e.name,e.binding,e.requestId??1n)),n=Iwr(r);return{success:n.success,error:n.error,peerId:t.peerId.toString()}}finally{await t.stop()}}async function Nwr(e){let t=await gpt(e.seed);try{let r=await bpt(t,e.relayMultiaddr,Awr(e.name,e.requestId??1n)),n=Owr(r);return n.peerId.length===0?{found:!1,peerId:"",error:n.error||"name not found"}:{found:!0,peerId:(0,fpt.toString)(n.peerId,"base58btc"),error:""}}finally{await t.stop()}}var apt,cpt,upt,dpt,lpt,ppt,fpt,jwe,mpt,ypt,Cwr,Rwr,spt,Lwe=P(()=>{"use strict";lwe();apt=require("libp2p"),cpt=require("@libp2p/tcp"),upt=require("@chainsafe/libp2p-noise"),dpt=require("@chainsafe/libp2p-yamux"),lpt=require("@libp2p/crypto/keys"),ppt=require("@multiformats/multiaddr"),fpt=require("uint8arrays/to-string"),jwe=new TextEncoder,mpt=new TextDecoder;ypt="/subway/p2p/1.0.0",Cwr=15e3,Rwr=15e3,spt=1<<20});var gk={};Gi(gk,{DEFAULT_VISA_RELAY_MULTIADDR:()=>vpt,MESH:()=>vs,RELAY_URL:()=>Wwe,connectOrThrow:()=>ZJ,ensureMailbox:()=>Qwe,isSubwayEnabled:()=>Gwe,listRegistered:()=>Dwr,loadBindingFor:()=>Zwe,loadRegistry:()=>Bv,makeClient:()=>YJ,maybeMintVisaBinding:()=>xpt,meshName:()=>gp,pairedVisaBinding:()=>Ept,readInbox:()=>Lwr,registerName:()=>Xwe,resolveActingName:()=>qwr,resolveMeshName:()=>Uwr,seedSubwayKeyFromTapAgent:()=>wpt,sendMessage:()=>Mwr,sendVia:()=>Hwr,subwayKeyPath:()=>JJ,visaRelayMultiaddr:()=>Kwe});function Kwe(e=process.env){return e.SUBWAY_RELAY_MULTIADDR??vpt}function gp(e){return e.includes(".")?e:`${e}.${vs}`}function Gwe(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 Ywe(){co.mkdirSync(Jwe,{recursive:!0,mode:448})}function jwr(e){return e.replace(/[^a-zA-Z0-9_.-]/g,"_")}function JJ(e){return lA.join(Jwe,`${jwr(e)}.key`)}function Bv(){if(!co.existsSync(Vwe))return{};try{return JSON.parse(co.readFileSync(Vwe,"utf8"))}catch{return{}}}function Fwe(e){Ywe(),co.writeFileSync(Vwe,JSON.stringify(e,null,2),{mode:384})}function $we(){try{return yk.userInfo().username}catch{return"local"}}function wpt(e){if(co.existsSync(e)||!co.existsSync(Hwe))return null;let t=co.readdirSync(Hwe).filter(n=>n.endsWith(".json"));if(t.length===0)return null;let r=t.map(n=>lA.join(Hwe,n)).sort((n,i)=>co.statSync(i).mtimeMs-co.statSync(n).mtimeMs)[0];try{let n=JSON.parse(co.readFileSync(r,"utf8"));if(!n.private_key_jwk)return null;let i=DA(n.private_key_jwk);return Ywe(),co.writeFileSync(e,Buffer.from(i),{mode:384}),n.agent_id??null}catch{return null}}function YJ(e,t={}){return new ipt({name:gp(e),url:Wwe,keyPath:JJ(e),autoReconnect:t.autoReconnect??!1,binding:t.binding})}function Zwe(e){if(vs!=="visa")return;let t=Bv()[e];if(t?.binding&&!(t.bindingExpiresAt&&Date.parse(t.bindingExpiresAt)<=Date.now()))return t.binding}async function ZJ(e,t=15e3){await Promise.race([e.connect(),new Promise((r,n)=>setTimeout(()=>n(new Error(`Subway relay connect timed out after ${t}ms (${Wwe})`)),t))])}function qwr(e){if(e)return e;let t=Object.keys(Bv());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>.`)}async function xpt(e){if(vs!=="visa")return null;let t=process.env.VISA_CLI_API_KEY?.trim();if(!t)throw new m2("No enrolled V4 agent or Visa Key is available for the trusted .visa mesh.","no_key");try{return await hZ({authUrl:ju(),apiKey:t,seed:gB(JJ(e)),name:gp(e)})}catch(r){if(r instanceof m2)throw r;return console.warn(`[subway] Visa binding not minted: ${r instanceof Error?r.message:String(r)}`),null}}function Ept(e=Date.now()){let t=e8e();if(!t?.binding_jwt)return null;let r=bk(t.binding_jwt);if(!r||r.mesh!=="visa")return null;let n=typeof r.exp=="number"?r.exp:NaN;return!Number.isFinite(n)||n*1e3<=e?null:{binding:t.binding_jwt,bindingExpiresAt:new Date(n*1e3).toISOString()}}async function Xwe(e){let t=JJ(e),r=wpt(t),n=gp(e);vs==="visa"&&!co.existsSync(t)&&(Ywe(),co.writeFileSync(t,(0,_pt.randomBytes)(32),{mode:384}));let i=vs==="visa"?Ept():null,o,s={};if(i)o=i.binding,s={binding:i.binding,bindingExpiresAt:i.bindingExpiresAt};else{let u=await xpt(e);u&&(o=u.binding,s={binding:u.binding,bindingExpiresAt:new Date(Date.now()+u.expires_in*1e3).toISOString()})}let a=vs==="visa"?Kwe():process.env.SUBWAY_RELAY_MULTIADDR;if(vs==="visa"&&a){let{registerDirect:u}=await Promise.resolve().then(()=>(Lwe(),zwe)),d=await u({relayMultiaddr:a,seed:gB(t),name:n,binding:o});if(!d.success)throw new Error(`.visa relay admission failed: ${d.error||"unknown"}`);let l=Bv();return l[e]={relayName:n,mesh:vs,peerId:d.peerId,owner:$we(),tapAgentId:r,registeredAt:new Date().toISOString(),...s},Fwe(l),{relayName:n,mesh:vs,peerId:d.peerId,tapAgentId:r,...o?{binding:o}:{}}}if(vs==="visa"&&!process.env.SUBWAY_RELAY){let u=Bv();return u[e]={relayName:n,mesh:vs,peerId:null,owner:$we(),tapAgentId:r,registeredAt:new Date().toISOString(),...s},Fwe(u),{relayName:n,mesh:vs,peerId:null,tapAgentId:r,...o?{binding:o}:{},note:o?"Visa binding ready; relay admission pending a .visa relay (set SUBWAY_RELAY).":"No Visa binding; pair/enroll this agent, or set VISA_CLI_API_KEY (card on file), for a .visa binding."}}let c=YJ(e,{autoReconnect:!1,binding:o});try{await ZJ(c);let u=Bv();return u[e]={relayName:n,mesh:vs,peerId:c.peerId,owner:$we(),tapAgentId:r,registeredAt:new Date().toISOString(),...s},Fwe(u),{relayName:n,mesh:vs,peerId:c.peerId,tapAgentId:r,...o?{binding:o}:{}}}finally{c.disconnect()}}async function Uwr(e){let t=gp(e),r=vs==="visa"?Kwe():process.env.SUBWAY_RELAY_MULTIADDR;if(vs==="visa"&&r){let{resolveDirect:n}=await Promise.resolve().then(()=>(Lwe(),zwe)),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 Mwr(e,t,r){let n=YJ(e,{autoReconnect:!1,binding:Zwe(e)});try{await ZJ(n);let i=gp(t);return await n.sendSigned(i,"chat",r),{to:i,as:gp(e)}}finally{n.disconnect()}}function Dwr(){let e=Bv();return Object.entries(e).map(([t,r])=>({name:t,...r}))}async function Qwe(e){let t=GJ.get(e);if(t)return{relayName:gp(e),peerId:t.client.peerId};let r=YJ(e,{autoReconnect:!0,binding:Zwe(e)}),n=[];return r.onMessage(i=>{n.push({from:i.fromName,text:i.payload,ts:i.timestampMs,verified:!!i.verified}),n.length>zwr&&n.shift()}),GJ.set(e,{client:r,buffer:n}),await ZJ(r),{relayName:gp(e),peerId:r.peerId}}async function Lwr(e,t=20,r=!1){await Qwe(e);let n=GJ.get(e);if(!n)return[];let i=n.buffer.slice(-t);return r&&(n.buffer.length=0),i}async function Hwr(e,t,r){await Qwe(e);let n=GJ.get(e);if(!n)throw new Error(`mailbox for ${e} unavailable`);let i=gp(t);return await n.client.sendSigned(i,"chat",r),{to:i,as:gp(e)}}var co,yk,lA,_pt,vs,vpt,Wwe,Jwe,Vwe,Hwe,GJ,zwr,Nv=P(()=>{"use strict";opt();f2();co=Ze(require("fs")),yk=Ze(require("os")),lA=Ze(require("path")),_pt=require("crypto");a4();LA();XJ();vs=process.env.SUBWAY_MESH??"relay",vpt="/dns4/subway-relay-visa.fly.dev/tcp/9100/p2p/12D3KooWM2q6SXgKFxj5wvnJ7gTD4XPjhvc5tHVVjDBrZRnJ3CKU";Wwe=process.env.SUBWAY_RELAY??"wss://relay.subway.dev/ws";Jwe=lA.join(yk.homedir(),".visa-cli","subway"),Vwe=lA.join(Jwe,"registry.json"),Hwe=lA.join(yk.homedir(),".visa-cli","agents");GJ=new Map,zwr=200});async function Fwr(e){if(process.env.SUBWAY_MESH==="visa")try{await Xwe(e)}catch(t){Be.warn("subway:pairing-auto-register-failed",{name:e,mesh:"visa",error:t instanceof Error?t.message:String(t)})}}function $wr(e=process.env.VISA_V4_HOME||pA.join(t8e.homedir(),".visa-v4")){try{let t=qc.readFileSync(pA.join(e,"identity","mailbox.json"),"utf8"),r=JSON.parse(t);return typeof r.email!="string"||!r.email.includes("@")||typeof r.inboxId!="string"||r.inboxId.length===0?null:{email:r.email,inboxId:r.inboxId}}catch{return null}}function r8e(e,t,r=_k){return pA.join(r,`${e}.${t}.json`)}function Spt(e,t=_k){qc.mkdirSync(t,{recursive:!0,mode:448}),qc.writeFileSync(r8e(e.pairingId,e.role,t),JSON.stringify(e,null,2),{mode:384})}function vk(e,t,r=_k){qc.rmSync(r8e(e,t,r),{force:!0})}function QJ(e,t,r=_k){try{let n=JSON.parse(qc.readFileSync(r8e(e,t,r),"utf8"));return n?.pairingId===e&&n.role===t?n:null}catch{return null}}function n8e(e=_k){return qc.existsSync(e)?qc.readdirSync(e).filter(r=>r.endsWith(".human.json")).map(r=>{try{return JSON.parse(qc.readFileSync(pA.join(e,r),"utf8"))}catch{return null}}).filter(r=>r?.role==="human").sort((r,n)=>n.createdAt.localeCompare(r.createdAt))[0]??null:null}async function jv(e,t,r){let n=await r(e,{...t,headers:{"X-Source":"cli","X-Visa-CLI-Version":Apt,...t.headers??{}}}),i=await n.json().catch(()=>({}));if(!n.ok&&n.status!==202)throw new Error(i.error??i.detail??`pairing server returned ${n.status}`);return{status:n.status,body:i}}async function i8e(e={}){let t=(e.authUrl??ju()).replace(/\/+$/,""),r=p9e(),n=$wr(),{body:i}=await jv(`${t}/v4/agent-pairings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cliChallenge:f9e(r),...n?{mailbox:n}:{}})},e.fetchImpl??fetch);if(!i.pairingId||!i.skillUrl||!i.expiresAt)throw new Error("pairing server returned an incomplete initiation response");let o={role:"human",pairingId:i.pairingId,verifier:r,authUrl:t,skillUrl:i.skillUrl,expiresAt:i.expiresAt,createdAt:new Date().toISOString()};return Spt(o,e.pairingDir),o}async function eY(e){let{pairing:t}=e,{body:r}=await jv(`${t.authUrl}/v4/agent-pairings/${encodeURIComponent(t.pairingId)}/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({verifier:t.verifier,code:e.code})},e.fetchImpl??fetch);return r}async function o8e(e){let t=(e.authUrl??ju()).replace(/\/+$/,""),{body:r}=await jv(`${t}/v4/agent-pairings/${encodeURIComponent(e.pairingId)}`,{method:"GET",cache:"no-store"},e.fetchImpl??fetch);return r}function Tpt(e,t){return Buffer.from(f4(e,Buffer.from(t,"utf8"))).toString("base64url")}async function s8e(e){let t=(e.authUrl??ju()).replace(/\/+$/,""),r=e.fetchImpl??fetch,n=await o8e({pairingId:e.pairingId,authUrl:t,fetchImpl:r});if(n.state!=="awaiting_agent"||!n.serverNonce)throw new Error(`pairing cannot be claimed from state ${n.state}`);let i,o,s;if(e.existingCredential)s=e.existingCredential.privateKeyJwk,o=e.existingCredential.publicKeyJwk,i=Buffer.from(s.d,"base64url");else{let m=mB();i=m.secretKey,s=m4(i),o=ch(m.publicKey)}let a=h4(o),c=AJ(),u=m9e(),d={runtime:e.runtime,contextLabel:e.contextLabel,platform:`${process.platform}/${process.arch}`,cliVersion:Apt},l=Tpt(i,h9e({pairingId:e.pairingId,serverNonce:n.serverNonce,claimTokenHash:fZ(u),agentJkt:a,walletPublicKey:c.publicKey,runtime:d})),p={role:"runtime",pairingId:e.pairingId,authUrl:t,claimToken:u,agentJkt:a,publicKeyJwk:o,privateKeyJwk:s,walletPublicKey:c.publicKey,walletPrivateKey:c.privateKey,createdAt:new Date().toISOString()};Spt(p,e.pairingDir);let{body:f}=await jv(`${t}/v4/agent-pairings/${encodeURIComponent(e.pairingId)}/claim`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentPublicJwk:o,walletPublicKey:c.publicKey,runtime:d,signature:l,claimToken:u})},r);if(!f.verificationCode||f.claimToken!==u)throw new Error("pairing server returned an incomplete claim response");if(f.verificationCode!==hB(e.pairingId,u))throw new Error("pairing server returned a mismatched verification code");return{pending:p,verificationCode:f.verificationCode}}async function tY(e){let t=e.fetchImpl??fetch,r=e.wait??(o=>new Promise(s=>setTimeout(s,o))),n=e.maxPolls??450,i="";for(let o=0;o<n;o+=1){let{body:s,status:a}=await jv(`${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);if(s.state!==i&&(i=s.state,e.onState?.(s.state)),a===202){if(["expired","cancelled","failed","revoked"].includes(s.state))throw new Error(`pairing ended in state ${s.state}`);await r(e.pollIntervalMs??2e3);continue}if(!s.artifacts||!s.artifactHash)throw new Error("pairing delivery omitted identity artifacts");let c=s.artifacts,u=c.terms?.name,d=c.wallet?.turnkey,l=c.terms?.mode==="wallet"||c.terms?.mode==="both",p=EJ(d?.network);if(c.agentJkt!==e.pending.agentJkt||typeof c.bindingJwt!="string"||typeof c.registrationJwt!="string"||typeof c.termsHash!="string"||typeof u!="string"||c.wallet?.credentialPublicKey!==e.pending.walletPublicKey||l&&(!d||typeof d.organizationId!="string"||typeof d.walletId!="string"||typeof d.address!="string"||!/^0x[0-9a-f]{40}$/i.test(d.address)||!p||!Number.isSafeInteger(c.terms?.dailyLimitCents)||!Number.isSafeInteger(c.terms?.perTransactionLimitCents))||g9e(s.artifacts)!==s.artifactHash)throw new Error("pairing artifact integrity check failed");let f=Tpt(Buffer.from(e.pending.privateKeyJwk.d,"base64url"),y9e({pairingId:e.pending.pairingId,agentJkt:e.pending.agentJkt,termsHash:c.termsHash,artifactHash:s.artifactHash}));if((await jv(`${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({signature:f})},t)).body.state!=="activated")throw new Error("pairing activation was not acknowledged");let h={agent_jkt:e.pending.agentJkt,name:u,public_key_jwk:e.pending.publicKeyJwk,private_key_jwk:e.pending.privateKeyJwk,binding_jwt:c.bindingJwt,registration_jwt:c.registrationJwt,wallet_public_key:e.pending.walletPublicKey,pairing_id:e.pending.pairingId,pairing_status:"activated",artifacts:s.artifacts,auth_url:e.pending.authUrl,created_at:new Date().toISOString()};return l&&d&&await xJ({apiPublicKey:e.pending.walletPublicKey,apiPrivateKey:e.pending.walletPrivateKey,organizationId:d.organizationId,walletId:d.walletId,address:d.address,network:p,perTransactionLimitCents:c.terms?.perTransactionLimitCents,dailyLimitCents:c.terms?.dailyLimitCents,...e.walletHome?{homeDir:e.walletHome}:{}}),a8e(h,e.agentDir),await Fwr(u),vk(e.pending.pairingId,"runtime",e.pairingDir),{record:h,name:u,agentJkt:e.pending.agentJkt}}throw new Error("timed out waiting for human authorization")}async function Ppt(e){let{pairing:t}=e,{body:r}=await jv(`${t.authUrl}/v4/agent-pairings/${encodeURIComponent(t.pairingId)}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({verifier:t.verifier})},e.fetchImpl??fetch);return r.state==="cancelled"&&vk(t.pairingId,"human",e.pairingDir),r}var qc,t8e,pA,Apt,_k,Ipt=P(()=>{"use strict";qc=Ze(require("node:fs")),t8e=Ze(require("node:os")),pA=Ze(require("node:path"));f2();LA();Nv();a4();Dc();W4e();XJ();Apt="4.1.0-rc.33",_k=pA.join(t8e.homedir(),".visa-cli","pairings")});var qpt={};Gi(qpt,{agentFilePath:()=>xk,agentFormatIsJson:()=>wk,attachAgentCommand:()=>Gwr,claimOptsFromFlags:()=>d8e,decodeBindingClaims:()=>bk,enrollClaimEnvelope:()=>Npt,isAgentCommandEnabled:()=>Bpt,isAgentRecord:()=>Ek,listAgentFiles:()=>rY,newestAgentRecord:()=>e8e,readAgent:()=>l8e,resolveAgentByRef:()=>jpt,writeAgent:()=>a8e});function Ek(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 Bpt(){return!0}function wk(e){return e==="json"}function Npt(e){switch(e.status){case"claimed":return{json:{status:"claimed",...e.name?{name:e.name}:{},tokenId:e.tokenId,credentialPath:e.credentialPath,keyBound:e.keyBound,sessionSaved:e.sessionSaved,walletProvisioned:e.walletProvisioned},exitCode:0};case"not_ready":return{json:{status:"not_ready",likelyExpired:e.likelyExpired,error:e.likelyExpired?"the 15-minute enrollment window has likely expired":"not ready yet \u2014 finish the browser flow through the final minted screen"},exitCode:3};case"no_pending":return{json:{status:"no_pending",error:"no enrollment hand-off in progress"},exitCode:1};case"confirm_mismatch":return{json:{status:"confirm_mismatch",confirmCode:e.confirmCode,error:"this enrollment hand-off did not match this terminal"},exitCode:1};case"error":return{json:{status:"error",error:e.message},exitCode:1}}}function d8e(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 c8e(e){return`${e.opened?`\u2713 Enrollment link opened in your browser.
20678
+ ${e.nonce}`;return x4r.encode(r)}function S4r(e,t,r,n,i,o,s){return A4r({messageId:e,senderPeerId:t,senderName:r,timestampMs:n,messageType:i,payload:o,nonce:s})}function T4r(e){let t=0;for(;t<e.length;){let r=e[t],n=r>>3,i=r&7;if(t++,i===0){for(;t<e.length&&e[t]&128;)t++;t++}else if(i===2){let o=0,s=0;for(;t<e.length&&e[t]&128;)o|=(e[t]&127)<<s,s+=7,t++;if(o|=(e[t]&127)<<s,t++,n===2&&o>=64)return e.slice(t,t+32);t+=o}else return null}return null}function Y4r(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function tpt(e,t,r=""){let n=Y4r(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 glt(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 Z4r(e,t){tpt(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 Twe(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function vwe(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function X4r(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 twr(e,t=!1){return t?{h:Number(e&NJ),l:Number(e>>blt&NJ)}:{h:Number(e>>blt&NJ)|0,l:Number(e&NJ)|0}}function rwr(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}=twr(e[o],t);[n[o],i[o]]=[s,a]}return[n,i]}function K1(e,t,r,n){let i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:i|0}}function mwr(){return K4r.randomSecretKey()}function npt(e){return $4r(e)}function hwr(){let e=mwr();return{secretKey:e,publicKey:npt(e)}}function ywr(e){if((0,e2.existsSync)(e)){let r=(0,e2.readFileSync)(e),n=new Uint8Array(r.buffer.slice(r.byteOffset,r.byteOffset+32));return{secretKey:n,publicKey:npt(n)}}let t=hwr();return(0,e2.mkdirSync)((0,Elt.dirname)(e),{recursive:!0}),(0,e2.writeFileSync)(e,new Uint8Array(t.secretKey)),t}function gwr(e){let{secretKey:t,publicKey:r}=ywr(e);return{privateKey:t,publicKey:r}}async function bwr(e,t,r,n,i,o,s,a){let c=S4r(t,r,n,i,o,s,a);return{signature:await _4r(e,c),signatureInput:E4r.subwayAgentMsgV1}}function xlt(e){return w4r(e)}var e2,Elt,Pvr,Ivr,Ovr,Cvr,Rvr,Alt,DJ,UJ,Xdt,Qdt,fwe,mwe,kvr,VJ,Bvr,bs,Nvr,jvr,qvr,W1,KJ,Pwe,Slt,Iwe,F1,elt,Owe,Tlt,Uvr,cA,Mvr,zJ,Tv,Tn,tlt,Ve,Plt,Ilt,Olt,Clt,hwe,wwe,fk,kv,Cv,Rlt,klt,xm,Dvr,rlt,zvr,xwe,Cwe,Lvr,Blt,Hvr,Fvr,$vr,Vvr,Kvr,Wvr,Rwe,Nlt,LJ,Gvr,jlt,Ewe,Jvr,nlt,ilt,Yvr,Mlt,Dlt,Gb,ra,RJ,slt,alt,clt,iA,oA,kJ,BJ,n4r,i4r,o4r,s4r,a4r,c4r,u4r,Jb,d4r,l4r,zlt,p4r,f4r,Yb,Zb,m4r,h4r,y4r,g4r,ult,v4r,Llt,x4r,E4r,Hlt,P4r,Flt,HJ,MJ,dlt,llt,gwe,bwe,I4r,uA,O4r,_s,C4r,R4r,k4r,t2,WJ,kwe,$lt,Vlt,V1,plt,Klt,Wlt,B4r,Bwe,N4r,FJ,Iv,Fn,flt,Ke,j4r,q4r,Glt,Jlt,_we,Awe,mk,dA,Rv,U4r,Ylt,Am,M4r,mlt,D4r,z4r,L4r,H4r,Zlt,F4r,Xlt,$4r,Qlt,V4r,K4r,$J,W4r,ept,Swe,G4r,hlt,ylt,J4r,Q4r,ewr,na,NJ,blt,_lt,vlt,sA,aA,jJ,qJ,nwr,iwr,owr,swr,awr,cwr,rpt,uwr,dwr,Xb,Qb,lwr,pwr,fwr,wlt,_wr,vwr,ipt,opt=P(()=>{"use strict";dwe();dwe();lwe();e2=require("fs"),Elt=require("path");Pvr=1e3,Ivr=10,Ovr=3e4,Cvr=3e4,Rvr=class{url;ws=null;_status="disconnected";messageHandlers=new Set;statusHandlers=new Set;reconnectAttempt=0;reconnectTimer=null;pingTimer=null;stopped=!1;autoReconnect;reconnectInterval;maxReconnectAttempts;pingInterval;constructor(e){this.url=e.url,this.autoReconnect=e.autoReconnect??!0,this.reconnectInterval=e.reconnectInterval??Pvr,this.maxReconnectAttempts=e.maxReconnectAttempts??Ivr,this.pingInterval=e.pingInterval??Ovr}get status(){return this._status}onMessage(e){return this.messageHandlers.add(e),()=>this.messageHandlers.delete(e)}onStatusChange(e){return this.statusHandlers.add(e),()=>this.statusHandlers.delete(e)}connect(){return this.stopped=!1,new Promise((e,t)=>{let r=Svr();if(!r){t(new ta('No WebSocket implementation available. Install the "ws" package for Node.js.'));return}this.setStatus("connecting");try{this.ws=new r(this.url)}catch(i){t(new ta(`Failed to create WebSocket: ${i}`));return}let n=!1;this.ws.onopen=()=>{this.reconnectAttempt=0,this.setStatus("connected"),this.startPing(),n||(n=!0,e())},this.ws.onmessage=i=>{let o;try{o=JSON.parse(typeof i.data=="string"?i.data:i.data.toString())}catch{return}for(let s of this.messageHandlers)s(o)},this.ws.onclose=()=>{this.ws=null,this.stopPing(),!this.stopped&&this.autoReconnect?this.scheduleReconnect():this.setStatus("disconnected"),n||(n=!0,t(new ta("WebSocket closed before connection established")))},this.ws.onerror=()=>{n||(n=!0,t(new ta(`WebSocket connection failed: ${this.url}`)))}})}disconnect(){this.stopped=!0,this.clearReconnectTimer(),this.stopPing(),this.ws&&(this.ws.onclose=null,this.ws.onerror=null,this.ws.onmessage=null,this.ws.close(),this.ws=null),this.setStatus("disconnected")}send(e){if(!this.ws||this.ws.readyState!==1)throw new ta("WebSocket is not connected");this.ws.send(JSON.stringify(e))}startPing(){this.stopPing(),this.pingInterval>0&&(this.pingTimer=setInterval(()=>{try{this.send({type:"ping"})}catch{}},this.pingInterval))}stopPing(){this.pingTimer!==null&&(clearInterval(this.pingTimer),this.pingTimer=null)}scheduleReconnect(){if(this.reconnectAttempt>=this.maxReconnectAttempts){this.setStatus("disconnected");return}this.setStatus("reconnecting");let e=Tvr(this.reconnectInterval*Math.pow(2,this.reconnectAttempt),this.reconnectInterval,Cvr);this.reconnectAttempt++,this.reconnectTimer=setTimeout(async()=>{if(!this.stopped)try{await this.connect()}catch{}},e)}clearReconnectTimer(){this.reconnectTimer!==null&&(clearTimeout(this.reconnectTimer),this.reconnectTimer=null)}setStatus(e){if(this._status!==e){this._status=e;for(let t of this.statusHandlers)t(e)}}},Alt=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:DJ,n:UJ,Gx:Xdt,Gy:Qdt,a:fwe,d:mwe,h:kvr}=Alt,VJ=32,Bvr=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},bs=(e="")=>{let t=new Error(e);throw Bvr(t,bs),t},Nvr=e=>typeof e=="bigint",jvr=e=>typeof e=="string",qvr=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,W1=(e,t,r="")=>{let n=qvr(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},KJ=e=>new Uint8Array(e),Pwe=e=>Uint8Array.from(e),Slt=(e,t)=>e.toString(16).padStart(t,"0"),Iwe=e=>Array.from(W1(e)).map(t=>Slt(t,2)).join(""),F1={_0:48,_9:57,A:65,F:70,a:97,f:102},elt=e=>{if(e>=F1._0&&e<=F1._9)return e-F1._0;if(e>=F1.A&&e<=F1.F)return e-(F1.A-10);if(e>=F1.a&&e<=F1.f)return e-(F1.a-10)},Owe=e=>{let t="hex invalid";if(!jvr(e))return bs(t);let r=e.length,n=r/2;if(r%2)return bs(t);let i=KJ(n);for(let o=0,s=0;o<n;o++,s+=2){let a=elt(e.charCodeAt(s)),c=elt(e.charCodeAt(s+1));if(a===void 0||c===void 0)return bs(t);i[o]=a*16+c}return i},Tlt=()=>globalThis?.crypto,Uvr=()=>Tlt()?.subtle??bs("crypto.subtle must be defined, consider polyfill"),cA=(...e)=>{let t=0;for(let i of e)t+=W1(i).length;let r=KJ(t),n=0;return e.forEach(i=>{r.set(i,n),n+=i.length}),r},Mvr=(e=VJ)=>Tlt().getRandomValues(KJ(e)),zJ=BigInt,Tv=(e,t,r,n="bad number: out of range")=>{if(!Nvr(e))throw new TypeError(n);if(t<=e&&e<r)return e;throw new RangeError(n)},Tn=(e,t=DJ)=>{let r=e%t;return r>=0n?r:t+r},tlt=(1n<<255n)-1n,Ve=e=>{e<0n&&bs("negative coordinate");let t=(e>>255n)*19n+(e&tlt);return t=(t>>255n)*19n+(t&tlt),t%DJ},Plt=e=>Tn(e,UJ),Ilt=(e,t)=>{(e===0n||t<=0n)&&bs("no inverse n="+e+" mod="+t);let r=Tn(e,t),n=t,i=0n,o=1n;for(;r!==0n;){let s=n/r,a=n%r,c=i-o*s;n=r,r=a,i=o,o=c}return n===1n?Tn(i,t):bs("no inverse")},Olt=e=>{let t=Nlt[e];return typeof t!="function"&&bs("hashes."+e+" not set"),t},Clt=e=>W1(e,64,"digest"),hwe=e=>e instanceof fk?e:bs("Point expected"),wwe=2n**256n,fk=class Pv{static BASE;static ZERO;X;Y;Z;T;constructor(t,r,n,i){let o=wwe;this.X=Tv(t,0n,o),this.Y=Tv(r,0n,o),this.Z=Tv(n,1n,o),this.T=Tv(i,0n,o),Object.freeze(this)}static CURVE(){return Alt}static fromAffine(t){return new Pv(t.x,t.y,1n,Ve(t.x*t.y))}static fromBytes(t,r=!1){let n=mwe,i=Pwe(W1(t,VJ)),o=t[31];i[31]=o&-129;let s=klt(i);Tv(s,0n,r?wwe:DJ);let c=Ve(s*s),u=Tn(c-1n),d=Ve(n*c+1n),{isValid:l,value:p}=zvr(u,d);l||bs("bad point: y not sqrt");let f=(p&1n)===1n,m=(o&128)!==0;return!r&&p===0n&&m&&bs("bad point: x==0, isLastByteOdd"),m!==f&&(p=Tn(-p)),new Pv(p,s,1n,Ve(p*s))}static fromHex(t,r){return Pv.fromBytes(Owe(t),r)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=fwe,r=mwe,n=this;if(n.is0())return bs("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=Tn(l+Ve(r*Ve(c*u)));if(f!==m)return bs("bad point: equation left != right (1)");let h=Ve(i*o),y=Ve(s*a);return h!==y?bs("bad point: equation left != right (2)"):this}equals(t){let{X:r,Y:n,Z:i}=this,{X:o,Y:s,Z:a}=hwe(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(Cv)}negate(){return new Pv(Tn(-this.X),this.Y,this.Z,Tn(-this.T))}double(){let{X:t,Y:r,Z:n}=this,i=fwe,o=Ve(t*t),s=Ve(r*r),a=Ve(2n*n*n),c=Ve(i*o),u=Tn(t+r),d=Tn(Ve(u*u)-o-s),l=Tn(c+s),p=Tn(l-a),f=Tn(c-s),m=Ve(d*p),h=Ve(l*f),y=Ve(d*f),w=Ve(p*l);return new Pv(m,h,w,y)}add(t){let{X:r,Y:n,Z:i,T:o}=this,{X:s,Y:a,Z:c,T:u}=hwe(t),d=fwe,l=mwe,p=Ve(r*s),f=Ve(n*a),m=Ve(Ve(o*l)*u),h=Ve(i*c),y=Tn(Ve(Tn(r+n)*Tn(s+a))-p-f),w=Tn(h-m),x=Tn(h+m),_=Tn(f-Ve(d*p)),v=Ve(y*w),E=Ve(x*_),A=Ve(y*_),S=Ve(w*x);return new Pv(v,E,S,A)}subtract(t){return this.add(hwe(t).negate())}multiply(t,r=!0){if(!r&&t===0n||(Tv(t,1n,UJ),!r&&this.is0()))return Cv;if(t===1n)return this;if(this.equals(kv))return Yvr(t).p;let n=Cv,i=kv;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(Cv))return{x:0n,y:1n};let i=Ilt(n,DJ);Ve(n*i)!==1n&&bs("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=Rlt(r);return n[31]|=t&1n?128:0,n}toHex(){return Iwe(this.toBytes())}clearCofactor(){return this.multiply(zJ(kvr),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(UJ/2n,!1).double();return UJ%2n&&(t=t.add(this)),t.is0()}},kv=new fk(Xdt,Qdt,1n,Tn(Xdt*Qdt)),Cv=new fk(0n,1n,1n,0n);fk.BASE=kv;fk.ZERO=Cv;Rlt=e=>Owe(Slt(Tv(e,0n,wwe),64)).reverse(),klt=e=>zJ("0x"+Iwe(Pwe(W1(e)).reverse())),xm=(e,t)=>{let r=e;for(;t-- >0n;)r=Ve(r*r);return r},Dvr=e=>{let t=Ve(e*e),r=Ve(t*e),n=Ve(xm(r,2n)*r),i=Ve(xm(n,1n)*e),o=Ve(xm(i,5n)*i),s=Ve(xm(o,10n)*o),a=Ve(xm(s,20n)*s),c=Ve(xm(a,40n)*a),u=Ve(xm(c,80n)*c),d=Ve(xm(u,80n)*c),l=Ve(xm(d,10n)*o);return{pow_p_5_8:Ve(xm(l,2n)*e),b2:r}},rlt=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,zvr=(e,t)=>{let r=Ve(t*Ve(t*t)),n=Ve(Ve(r*r)*t),i=Dvr(Ve(e*n)).pow_p_5_8,o=Ve(e*Ve(r*i)),s=Ve(t*Ve(o*o)),a=o,c=Ve(o*rlt),u=s===e,d=s===Tn(-e),l=s===Tn(-e*rlt);return u&&(o=a),(d||l)&&(o=c),(Tn(o)&1n)===1n&&(o=Tn(-o)),{isValid:u||d,value:o}},xwe=e=>Plt(klt(e)),Cwe=(...e)=>Promise.resolve(Olt("sha512Async")(cA(...e))).then(Clt),Lvr=(...e)=>Clt(Olt("sha512")(cA(...e))),Blt=e=>{let t=Pwe(e),r=t.slice(0,32);r[0]&=248,r[31]&=127,r[31]|=64;let n=t.slice(32,64),i=xwe(r),o=kv.multiply(i),s=o.toBytes();return{head:r,prefix:n,scalar:i,point:o,pointBytes:s}},Hvr=e=>Cwe(W1(e,VJ)).then(Blt),Fvr=e=>Blt(Lvr(W1(e,VJ))),$vr=e=>Fvr(e).pointBytes,Vvr=e=>Cwe(e.hashable).then(e.finish),Kvr=(e,t,r)=>{let{pointBytes:n,scalar:i}=e,o=xwe(t),s=kv.multiply(o).toBytes();return{hashable:cA(s,n,r),finish:u=>{let d=Plt(o+xwe(u)*i);return W1(cA(s,Rlt(d)),64)}}},Wvr=async(e,t)=>{let r=W1(e),n=await Hvr(t),i=await Cwe(n.prefix,r);return Vvr(Kvr(n,i,r))},Rwe=Object.freeze({bytesToHex:Iwe,hexToBytes:Owe,concatBytes:cA,mod:Tn,invert:Ilt,randomBytes:Mvr}),Nlt={sha512Async:async e=>{let t=Uvr(),r=cA(e);return KJ(await t.digest("SHA-512",r.buffer))},sha512:void 0},LJ=8,Gvr=256,jlt=Math.ceil(Gvr/LJ)+1,Ewe=2**(LJ-1),Jvr=()=>{let e=[],t=kv,r=t;for(let n=0;n<jlt;n++){r=t,e.push(r);for(let i=1;i<Ewe;i++)r=r.add(t),e.push(r);t=r.double()}return e},nlt=void 0,ilt=(e,t)=>{let r=t.negate();return e?r:t},Yvr=e=>{let t=nlt||(nlt=Jvr()),r=Cv,n=kv,i=2**LJ,o=i,s=zJ(i-1),a=zJ(LJ);for(let c=0;c<jlt;c++){let u=Number(e&s);e>>=a,u>Ewe&&(u-=o,e+=1n);let d=c*Ewe,l=d,p=d+Math.abs(u)-1,f=c%2!==0,m=u<0;u===0?n=n.add(ilt(f,t[l])):r=r.add(ilt(m,t[p]))}return e!==0n&&bs("invalid wnaf"),{p:r,f:n}};Mlt=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});Dlt=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=ywe(this.buffer)}update(e){olt(this),qlt(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=ywe(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){olt(this),Xvr(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:i}=this,{pos:o}=this;t[o++]=128,pk(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=ywe(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()}},Gb=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),ra=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),RJ=BigInt(2**32-1),slt=BigInt(32);alt=(e,t,r)=>e>>>r,clt=(e,t,r)=>e<<32-r|t>>>r,iA=(e,t,r)=>e>>>r|t<<32-r,oA=(e,t,r)=>e<<32-r|t>>>r,kJ=(e,t,r)=>e<<64-r|t>>>r-32,BJ=(e,t,r)=>e>>>r-32|t<<64-r;n4r=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),i4r=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,o4r=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),s4r=(e,t,r,n,i)=>t+r+n+i+(e/2**32|0)|0,a4r=(e,t,r,n,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(i>>>0),c4r=(e,t,r,n,i,o)=>t+r+n+i+o+(e/2**32|0)|0,u4r=Uint32Array.from([1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,1426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,2227730452,2361852424,2428436474,2756734187,3204031479,3329325298]),Jb=new Uint32Array(64),d4r=class extends Dlt{constructor(e){super(64,e,8,!1)}get(){let{A:e,B:t,C:r,D:n,E:i,F:o,G:s,H:a}=this;return[e,t,r,n,i,o,s,a]}set(e,t,r,n,i,o,s,a){this.A=e|0,this.B=t|0,this.C=r|0,this.D=n|0,this.E=i|0,this.F=o|0,this.G=s|0,this.H=a|0}process(e,t){for(let d=0;d<16;d++,t+=4)Jb[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let l=Jb[d-15],p=Jb[d-2],f=Em(l,7)^Em(l,18)^l>>>3,m=Em(p,17)^Em(p,19)^p>>>10;Jb[d]=m+Jb[d-7]+f+Jb[d-16]|0}let{A:r,B:n,C:i,D:o,E:s,F:a,G:c,H:u}=this;for(let d=0;d<64;d++){let l=Em(s,6)^Em(s,11)^Em(s,25),p=u+l+Qvr(s,a,c)+u4r[d]+Jb[d]|0,m=(Em(r,2)^Em(r,13)^Em(r,22))+e4r(r,n,i)|0;u=c,c=a,a=s,s=o+p|0,o=i,i=n,n=r,r=p+m|0}r=r+this.A|0,n=n+this.B|0,i=i+this.C|0,o=o+this.D|0,s=s+this.E|0,a=a+this.F|0,c=c+this.G|0,u=u+this.H|0,this.set(r,n,i,o,s,a,c,u)}roundClean(){pk(Jb)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),pk(this.buffer)}},l4r=class extends d4r{A=Gb[0]|0;B=Gb[1]|0;C=Gb[2]|0;D=Gb[3]|0;E=Gb[4]|0;F=Gb[5]|0;G=Gb[6]|0;H=Gb[7]|0;constructor(){super(32)}},zlt=r4r(["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))),p4r=zlt[0],f4r=zlt[1],Yb=new Uint32Array(80),Zb=new Uint32Array(80),m4r=class extends Dlt{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 x=0;x<16;x++,t+=4)Yb[x]=e.getUint32(t),Zb[x]=e.getUint32(t+=4);for(let x=16;x<80;x++){let _=Yb[x-15]|0,v=Zb[x-15]|0,E=iA(_,v,1)^iA(_,v,8)^alt(_,v,7),A=oA(_,v,1)^oA(_,v,8)^clt(_,v,7),S=Yb[x-2]|0,C=Zb[x-2]|0,I=iA(S,C,19)^kJ(S,C,61)^alt(S,C,6),R=oA(S,C,19)^BJ(S,C,61)^clt(S,C,6),U=o4r(A,R,Zb[x-7],Zb[x-16]),j=s4r(U,E,I,Yb[x-7],Yb[x-16]);Yb[x]=j|0,Zb[x]=U|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:w}=this;for(let x=0;x<80;x++){let _=iA(d,l,14)^iA(d,l,18)^kJ(d,l,41),v=oA(d,l,14)^oA(d,l,18)^BJ(d,l,41),E=d&p^~d&m,A=l&f^~l&h,S=a4r(w,v,A,f4r[x],Zb[x]),C=c4r(S,y,_,E,p4r[x],Yb[x]),I=S|0,R=iA(r,n,28)^kJ(r,n,34)^kJ(r,n,39),U=oA(r,n,28)^BJ(r,n,34)^BJ(r,n,39),j=r&i^r&s^i&s,q=n&o^n&a^o&a;y=m|0,w=h|0,m=p|0,h=f|0,p=d|0,f=l|0,{h:d,l}=$1(c|0,u|0,C|0,I|0),c=s|0,u=a|0,s=i|0,a=o|0,i=r|0,o=n|0;let B=n4r(I,U,q);r=i4r(B,C,R,j),n=B|0}({h:r,l:n}=$1(this.Ah|0,this.Al|0,r|0,n|0)),{h:i,l:o}=$1(this.Bh|0,this.Bl|0,i|0,o|0),{h:s,l:a}=$1(this.Ch|0,this.Cl|0,s|0,a|0),{h:c,l:u}=$1(this.Dh|0,this.Dl|0,c|0,u|0),{h:d,l}=$1(this.Eh|0,this.El|0,d|0,l|0),{h:p,l:f}=$1(this.Fh|0,this.Fl|0,p|0,f|0),{h:m,l:h}=$1(this.Gh|0,this.Gl|0,m|0,h|0),{h:y,l:w}=$1(this.Hh|0,this.Hl|0,y|0,w|0),this.set(r,n,i,o,s,a,c,u,d,l,p,f,m,h,y,w)}roundClean(){pk(Yb,Zb)}destroy(){this.destroyed=!0,pk(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},h4r=class extends m4r{Ah=ra[0]|0;Al=ra[1]|0;Bh=ra[2]|0;Bl=ra[3]|0;Ch=ra[4]|0;Cl=ra[5]|0;Dh=ra[6]|0;Dl=ra[7]|0;Eh=ra[8]|0;El=ra[9]|0;Fh=ra[10]|0;Fl=ra[11]|0;Gh=ra[12]|0;Gl=ra[13]|0;Hh=ra[14]|0;Hl=ra[15]|0;constructor(){super(64)}},y4r=Ult(()=>new l4r,Mlt(1)),g4r=Ult(()=>new h4r,Mlt(3)),ult=Nlt;ult.sha512||(ult.sha512=e=>g4r(e));v4r=Rwe.bytesToHex,Llt=Rwe.hexToBytes;Rwe.concatBytes;x4r=new TextEncoder,E4r={subwayAgentMsgV1:"message_id;sender_peer_id;sender_name;timestamp_ms;message_type;payload_hash;nonce"};Llt("302e020100300506032b657004220420");Llt("302a300506032b6570032100");Hlt="ABCDEFGHJKLMNPQRSTUVWXYZ23456789",P4r=Hlt.length-1;if((Hlt.length&P4r)!==0)throw new Error("agent pairing code alphabet must contain a power-of-two number of symbols");Flt=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:HJ,n:MJ,Gx:dlt,Gy:llt,a:gwe,d:bwe,h:I4r}=Flt,uA=32,O4r=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},_s=(e="")=>{let t=new Error(e);throw O4r(t,_s),t},C4r=e=>typeof e=="bigint",R4r=e=>typeof e=="string",k4r=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,t2=(e,t,r="")=>{let n=k4r(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},WJ=e=>new Uint8Array(e),kwe=e=>Uint8Array.from(e),$lt=(e,t)=>e.toString(16).padStart(t,"0"),Vlt=e=>Array.from(t2(e)).map(t=>$lt(t,2)).join(""),V1={_0:48,_9:57,A:65,F:70,a:97,f:102},plt=e=>{if(e>=V1._0&&e<=V1._9)return e-V1._0;if(e>=V1.A&&e<=V1.F)return e-(V1.A-10);if(e>=V1.a&&e<=V1.f)return e-(V1.a-10)},Klt=e=>{let t="hex invalid";if(!R4r(e))return _s(t);let r=e.length,n=r/2;if(r%2)return _s(t);let i=WJ(n);for(let o=0,s=0;o<n;o++,s+=2){let a=plt(e.charCodeAt(s)),c=plt(e.charCodeAt(s+1));if(a===void 0||c===void 0)return _s(t);i[o]=a*16+c}return i},Wlt=()=>globalThis?.crypto,B4r=()=>Wlt()?.subtle??_s("crypto.subtle must be defined, consider polyfill"),Bwe=(...e)=>{let t=0;for(let i of e)t+=t2(i).length;let r=WJ(t),n=0;return e.forEach(i=>{r.set(i,n),n+=i.length}),r},N4r=(e=uA)=>Wlt().getRandomValues(WJ(e)),FJ=BigInt,Iv=(e,t,r,n="bad number: out of range")=>{if(!C4r(e))throw new TypeError(n);if(t<=e&&e<r)return e;throw new RangeError(n)},Fn=(e,t=HJ)=>{let r=e%t;return r>=0n?r:t+r},flt=(1n<<255n)-1n,Ke=e=>{e<0n&&_s("negative coordinate");let t=(e>>255n)*19n+(e&flt);return t=(t>>255n)*19n+(t&flt),t%HJ},j4r=e=>Fn(e,MJ),q4r=(e,t)=>{(e===0n||t<=0n)&&_s("no inverse n="+e+" mod="+t);let r=Fn(e,t),n=t,i=0n,o=1n;for(;r!==0n;){let s=n/r,a=n%r,c=i-o*s;n=r,r=a,i=o,o=c}return n===1n?Fn(i,t):_s("no inverse")},Glt=e=>{let t=Qlt[e];return typeof t!="function"&&_s("hashes."+e+" not set"),t},Jlt=e=>t2(e,64,"digest"),_we=e=>e instanceof mk?e:_s("Point expected"),Awe=2n**256n,mk=class Ov{static BASE;static ZERO;X;Y;Z;T;constructor(t,r,n,i){let o=Awe;this.X=Iv(t,0n,o),this.Y=Iv(r,0n,o),this.Z=Iv(n,1n,o),this.T=Iv(i,0n,o),Object.freeze(this)}static CURVE(){return Flt}static fromAffine(t){return new Ov(t.x,t.y,1n,Ke(t.x*t.y))}static fromBytes(t,r=!1){let n=bwe,i=kwe(t2(t,uA)),o=t[31];i[31]=o&-129;let s=Ylt(i);Iv(s,0n,r?Awe:HJ);let c=Ke(s*s),u=Fn(c-1n),d=Ke(n*c+1n),{isValid:l,value:p}=D4r(u,d);l||_s("bad point: y not sqrt");let f=(p&1n)===1n,m=(o&128)!==0;return!r&&p===0n&&m&&_s("bad point: x==0, isLastByteOdd"),m!==f&&(p=Fn(-p)),new Ov(p,s,1n,Ke(p*s))}static fromHex(t,r){return Ov.fromBytes(Klt(t),r)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=gwe,r=bwe,n=this;if(n.is0())return _s("bad point: ZERO");let{X:i,Y:o,Z:s,T:a}=n,c=Ke(i*i),u=Ke(o*o),d=Ke(s*s),l=Ke(d*d),p=Ke(c*t),f=Ke(d*(p+u)),m=Fn(l+Ke(r*Ke(c*u)));if(f!==m)return _s("bad point: equation left != right (1)");let h=Ke(i*o),y=Ke(s*a);return h!==y?_s("bad point: equation left != right (2)"):this}equals(t){let{X:r,Y:n,Z:i}=this,{X:o,Y:s,Z:a}=_we(t),c=Ke(r*a),u=Ke(o*i),d=Ke(n*a),l=Ke(s*i);return c===u&&d===l}is0(){return this.equals(Rv)}negate(){return new Ov(Fn(-this.X),this.Y,this.Z,Fn(-this.T))}double(){let{X:t,Y:r,Z:n}=this,i=gwe,o=Ke(t*t),s=Ke(r*r),a=Ke(2n*n*n),c=Ke(i*o),u=Fn(t+r),d=Fn(Ke(u*u)-o-s),l=Fn(c+s),p=Fn(l-a),f=Fn(c-s),m=Ke(d*p),h=Ke(l*f),y=Ke(d*f),w=Ke(p*l);return new Ov(m,h,w,y)}add(t){let{X:r,Y:n,Z:i,T:o}=this,{X:s,Y:a,Z:c,T:u}=_we(t),d=gwe,l=bwe,p=Ke(r*s),f=Ke(n*a),m=Ke(Ke(o*l)*u),h=Ke(i*c),y=Fn(Ke(Fn(r+n)*Fn(s+a))-p-f),w=Fn(h-m),x=Fn(h+m),_=Fn(f-Ke(d*p)),v=Ke(y*w),E=Ke(x*_),A=Ke(y*_),S=Ke(w*x);return new Ov(v,E,S,A)}subtract(t){return this.add(_we(t).negate())}multiply(t,r=!0){if(!r&&t===0n||(Iv(t,1n,MJ),!r&&this.is0()))return Rv;if(t===1n)return this;if(this.equals(dA))return J4r(t).p;let n=Rv,i=dA;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(Rv))return{x:0n,y:1n};let i=q4r(n,HJ);Ke(n*i)!==1n&&_s("invalid inverse");let o=Ke(t*i),s=Ke(r*i);return{x:o,y:s}}toBytes(){let{x:t,y:r}=this.toAffine(),n=U4r(r);return n[31]|=t&1n?128:0,n}toHex(){return Vlt(this.toBytes())}clearCofactor(){return this.multiply(FJ(I4r),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(MJ/2n,!1).double();return MJ%2n&&(t=t.add(this)),t.is0()}},dA=new mk(dlt,llt,1n,Fn(dlt*llt)),Rv=new mk(0n,1n,1n,0n);mk.BASE=dA;mk.ZERO=Rv;U4r=e=>Klt($lt(Iv(e,0n,Awe),64)).reverse(),Ylt=e=>FJ("0x"+Vlt(kwe(t2(e)).reverse())),Am=(e,t)=>{let r=e;for(;t-- >0n;)r=Ke(r*r);return r},M4r=e=>{let t=Ke(e*e),r=Ke(t*e),n=Ke(Am(r,2n)*r),i=Ke(Am(n,1n)*e),o=Ke(Am(i,5n)*i),s=Ke(Am(o,10n)*o),a=Ke(Am(s,20n)*s),c=Ke(Am(a,40n)*a),u=Ke(Am(c,80n)*c),d=Ke(Am(u,80n)*c),l=Ke(Am(d,10n)*o);return{pow_p_5_8:Ke(Am(l,2n)*e),b2:r}},mlt=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,D4r=(e,t)=>{let r=Ke(t*Ke(t*t)),n=Ke(Ke(r*r)*t),i=M4r(Ke(e*n)).pow_p_5_8,o=Ke(e*Ke(r*i)),s=Ke(t*Ke(o*o)),a=o,c=Ke(o*mlt),u=s===e,d=s===Fn(-e),l=s===Fn(-e*mlt);return u&&(o=a),(d||l)&&(o=c),(Fn(o)&1n)===1n&&(o=Fn(-o)),{isValid:u||d,value:o}},z4r=e=>j4r(Ylt(e)),L4r=(...e)=>Promise.resolve(Glt("sha512Async")(Bwe(...e))).then(Jlt),H4r=(...e)=>Jlt(Glt("sha512")(Bwe(...e))),Zlt=e=>{let t=kwe(e),r=t.slice(0,32);r[0]&=248,r[31]&=127,r[31]|=64;let n=t.slice(32,64),i=z4r(r),o=dA.multiply(i),s=o.toBytes();return{head:r,prefix:n,scalar:i,point:o,pointBytes:s}},F4r=e=>L4r(t2(e,uA)).then(Zlt),Xlt=e=>Zlt(H4r(t2(e,uA))),$4r=e=>Xlt(e).pointBytes,Qlt={sha512Async:async e=>{let t=B4r(),r=Bwe(e);return WJ(await t.digest("SHA-512",r.buffer))},sha512:void 0},V4r=e=>(e=e===void 0?N4r(uA):e,t2(e,uA)),K4r=Object.freeze({getExtendedPublicKeyAsync:F4r,getExtendedPublicKey:Xlt,randomSecretKey:V4r}),$J=8,W4r=256,ept=Math.ceil(W4r/$J)+1,Swe=2**($J-1),G4r=()=>{let e=[],t=dA,r=t;for(let n=0;n<ept;n++){r=t,e.push(r);for(let i=1;i<Swe;i++)r=r.add(t),e.push(r);t=r.double()}return e},hlt=void 0,ylt=(e,t)=>{let r=t.negate();return e?r:t},J4r=e=>{let t=hlt||(hlt=G4r()),r=Rv,n=dA,i=2**$J,o=i,s=FJ(i-1),a=FJ($J);for(let c=0;c<ept;c++){let u=Number(e&s);e>>=a,u>Swe&&(u-=o,e+=1n);let d=c*Swe,l=d,p=d+Math.abs(u)-1,f=c%2!==0,m=u<0;u===0?n=n.add(ylt(f,t[l])):r=r.add(ylt(m,t[p]))}return e!==0n&&_s("invalid wnaf"),{p:r,f:n}};Q4r=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}),ewr=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=vwe(this.buffer)}update(e){glt(this),tpt(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=vwe(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){glt(this),Z4r(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:i}=this,{pos:o}=this;t[o++]=128,Twe(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=vwe(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()}},na=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),NJ=BigInt(2**32-1),blt=BigInt(32);_lt=(e,t,r)=>e>>>r,vlt=(e,t,r)=>e<<32-r|t>>>r,sA=(e,t,r)=>e>>>r|t<<32-r,aA=(e,t,r)=>e<<32-r|t>>>r,jJ=(e,t,r)=>e<<64-r|t>>>r-32,qJ=(e,t,r)=>e>>>r-32|t<<64-r;nwr=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),iwr=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,owr=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),swr=(e,t,r,n,i)=>t+r+n+i+(e/2**32|0)|0,awr=(e,t,r,n,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(i>>>0),cwr=(e,t,r,n,i,o)=>t+r+n+i+o+(e/2**32|0)|0,rpt=rwr(["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))),uwr=rpt[0],dwr=rpt[1],Xb=new Uint32Array(80),Qb=new Uint32Array(80),lwr=class extends ewr{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 x=0;x<16;x++,t+=4)Xb[x]=e.getUint32(t),Qb[x]=e.getUint32(t+=4);for(let x=16;x<80;x++){let _=Xb[x-15]|0,v=Qb[x-15]|0,E=sA(_,v,1)^sA(_,v,8)^_lt(_,v,7),A=aA(_,v,1)^aA(_,v,8)^vlt(_,v,7),S=Xb[x-2]|0,C=Qb[x-2]|0,I=sA(S,C,19)^jJ(S,C,61)^_lt(S,C,6),R=aA(S,C,19)^qJ(S,C,61)^vlt(S,C,6),U=owr(A,R,Qb[x-7],Qb[x-16]),j=swr(U,E,I,Xb[x-7],Xb[x-16]);Xb[x]=j|0,Qb[x]=U|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:w}=this;for(let x=0;x<80;x++){let _=sA(d,l,14)^sA(d,l,18)^jJ(d,l,41),v=aA(d,l,14)^aA(d,l,18)^qJ(d,l,41),E=d&p^~d&m,A=l&f^~l&h,S=awr(w,v,A,dwr[x],Qb[x]),C=cwr(S,y,_,E,uwr[x],Xb[x]),I=S|0,R=sA(r,n,28)^jJ(r,n,34)^jJ(r,n,39),U=aA(r,n,28)^qJ(r,n,34)^qJ(r,n,39),j=r&i^r&s^i&s,q=n&o^n&a^o&a;y=m|0,w=h|0,m=p|0,h=f|0,p=d|0,f=l|0,{h:d,l}=K1(c|0,u|0,C|0,I|0),c=s|0,u=a|0,s=i|0,a=o|0,i=r|0,o=n|0;let B=nwr(I,U,q);r=iwr(B,C,R,j),n=B|0}({h:r,l:n}=K1(this.Ah|0,this.Al|0,r|0,n|0)),{h:i,l:o}=K1(this.Bh|0,this.Bl|0,i|0,o|0),{h:s,l:a}=K1(this.Ch|0,this.Cl|0,s|0,a|0),{h:c,l:u}=K1(this.Dh|0,this.Dl|0,c|0,u|0),{h:d,l}=K1(this.Eh|0,this.El|0,d|0,l|0),{h:p,l:f}=K1(this.Fh|0,this.Fl|0,p|0,f|0),{h:m,l:h}=K1(this.Gh|0,this.Gl|0,m|0,h|0),{h:y,l:w}=K1(this.Hh|0,this.Hl|0,y|0,w|0),this.set(r,n,i,o,s,a,c,u,d,l,p,f,m,h,y,w)}roundClean(){Twe(Xb,Qb)}destroy(){this.destroyed=!0,Twe(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},pwr=class extends lwr{Ah=na[0]|0;Al=na[1]|0;Bh=na[2]|0;Bl=na[3]|0;Ch=na[4]|0;Cl=na[5]|0;Dh=na[6]|0;Dl=na[7]|0;Eh=na[8]|0;El=na[9]|0;Fh=na[10]|0;Fl=na[11]|0;Gh=na[12]|0;Gl=na[13]|0;Hh=na[14]|0;Hl=na[15]|0;constructor(){super(64)}},fwr=X4r(()=>new pwr,Q4r(3)),wlt=Qlt;wlt.sha512||(wlt.sha512=e=>fwr(e));_wr="ws://localhost:9001/ws",vwr=3e4,ipt=class{transport;options;_peerId=null;_name;_keypair=null;messageHandlers=new Set;topicHandlers=new Map;rpcHandlers=new Map;defaultRpcHandler=null;pendingCalls=new Map;pendingSend=new Map;pendingResolve=new Map;eventListeners=new Map;registerPromise=null;hasConnectedOnce=!1;constructor(e){if(this._name=lk(e.name),e.keyPath)try{this._keypair=gwr(e.keyPath)}catch{}this.options={name:this._name,url:e.url??_wr,relay:e.relay??"",autoReconnect:e.autoReconnect??!0,reconnectInterval:e.reconnectInterval??1e3,maxReconnectAttempts:e.maxReconnectAttempts??10,rpcTimeout:e.rpcTimeout??vwr,pingInterval:e.pingInterval??3e4,binding:e.binding??""},this.transport=new Rvr({url:this.options.url,autoReconnect:this.options.autoReconnect,reconnectInterval:this.options.reconnectInterval,maxReconnectAttempts:this.options.maxReconnectAttempts,pingInterval:this.options.pingInterval}),this.transport.onMessage(t=>this.handleBridgeMessage(t)),this.transport.onStatusChange(t=>this.handleStatusChange(t))}initKeypairFromSecret(e){try{let t=Buffer.from(e,"base64"),r=T4r(new Uint8Array(t));r&&(this._keypair={privateKey:r,publicKey:b4r(r)})}catch{}}get name(){return this._name}get peerId(){return this._peerId}get status(){return this.transport.status}async connect(){return await this.transport.connect(),new Promise((e,t)=>{this.registerPromise={resolve:e,reject:t};let r={type:"register",name:this._name};this.options.relay&&(r.relay=this.options.relay),this._keypair&&(r.public_key=xlt(this._keypair.publicKey)),this.options.binding&&(r.binding=this.options.binding);try{this.transport.send(r)}catch(n){this.registerPromise=null,t(n instanceof Error?n:new ta(String(n)))}})}disconnect(){for(let[,e]of this.pendingCalls)clearTimeout(e.timer),e.reject(new ta("Client disconnected"));this.pendingCalls.clear();for(let[,e]of this.pendingSend)e.reject(new ta("Client disconnected"));this.pendingSend.clear();for(let[,e]of this.pendingResolve)e.reject(new ta("Client disconnected"));this.pendingResolve.clear(),this.registerPromise&&(this.registerPromise.reject(new ta("Client disconnected")),this.registerPromise=null),this.transport.disconnect(),this._peerId=null,this.hasConnectedOnce=!1}async send(e,t,r,n){let i=lk(e),o=pwe();return new Promise((s,a)=>{this.pendingSend.set(i,{resolve:s,reject:a});try{this.transport.send({type:"send",to:i,message_type:t,payload:r,metadata:n})}catch(c){this.pendingSend.delete(i),a(c instanceof Error?c:new ta(String(c)))}setTimeout(()=>{this.pendingSend.has(i)&&(this.pendingSend.delete(i),s({messageId:o,to:i}))},5e3)})}async sendSigned(e,t,r,n){if(!this._keypair||!this._peerId)return this.send(e,t,r,n);let i=lk(e),o=pwe(),s=Date.now(),a=Math.floor(Math.random()*2**32),c=new TextEncoder().encode(r),{signature:u,signatureInput:d}=await bwr(this._keypair.privateKey,o,this._peerId,this._name,s,t,c,a);return new Promise((l,p)=>{this.pendingSend.set(i,{resolve:l,reject:p});try{this.transport.send({type:"send_signed",to:i,message_id:o,sender_peer_id:this._peerId,sender_name:this._name,timestamp_ms:s,message_type:t,payload:r,metadata:n,signature:Buffer.from(u).toString("base64"),signature_input:d,nonce:a})}catch(f){this.pendingSend.delete(i),p(f instanceof Error?f:new ta(String(f)))}setTimeout(()=>{this.pendingSend.has(i)&&(this.pendingSend.delete(i),l({messageId:o,to:i}))},5e3)})}async call(e,t,r,n){let i=lk(e),o=n?.correlationId??pwe(),s=n?.timeout??this.options.rpcTimeout;return new Promise((a,c)=>{let u=setTimeout(()=>{this.pendingCalls.delete(o),c(new dk(`RPC call to ${i}.${t} timed out after ${s}ms`))},s);this.pendingCalls.set(o,{resolve:a,reject:c,timer:u});try{this.transport.send({type:"call",to:i,method:t,payload:r??"",correlation_id:o})}catch(d){clearTimeout(u),this.pendingCalls.delete(o),c(d instanceof Error?d:new ta(String(d)))}})}async broadcast(e,t,r){this.transport.send({type:"broadcast",topic:e,message_type:t,payload:r})}subscribe(e,t){let r=this.topicHandlers.get(e);if(!r){r=new Set,this.topicHandlers.set(e,r);try{this.transport.send({type:"subscribe",topic:e})}catch{}}return r.add(t),()=>{r.delete(t),r.size===0&&this.topicHandlers.delete(e)}}onMessage(e){return this.messageHandlers.add(e),()=>this.messageHandlers.delete(e)}onCall(e,t){return this.rpcHandlers.set(e,t),()=>this.rpcHandlers.delete(e)}onAnyCall(e){return this.defaultRpcHandler=e,()=>{this.defaultRpcHandler=null}}async resolve(e){let t=lk(e);return new Promise((r,n)=>{this.pendingResolve.set(t,{resolve:r,reject:n});try{this.transport.send({type:"resolve",name:t})}catch(i){this.pendingResolve.delete(t),n(i instanceof Error?i:new ta(String(i)))}setTimeout(()=>{this.pendingResolve.has(t)&&(this.pendingResolve.delete(t),n(new dk(`Resolve ${t} timed out`)))},1e4)})}on(e,t){let r=this.eventListeners.get(e);return r||(r=new Set,this.eventListeners.set(e,r)),r.add(t),()=>r.delete(t)}off(e,t){let r=this.eventListeners.get(e);r&&r.delete(t)}emit(e,...t){let r=this.eventListeners.get(e);if(r)for(let n of r)try{n(...t)}catch{}}handleBridgeMessage(e){switch(e.type){case"registered":this._peerId=e.peer_id,this._name=e.name,e.secret_key&&!this._keypair&&this.initKeypairFromSecret(e.secret_key),this.hasConnectedOnce=!0,this.registerPromise&&(this.registerPromise.resolve(),this.registerPromise=null),this.emit("connected",{name:e.name,peerId:e.peer_id}),this.resubscribeTopics();break;case"sent":{let t=this.pendingSend.get(e.to);t&&(this.pendingSend.delete(e.to),t.resolve({messageId:e.message_id,to:e.to}));break}case"call_result":{let t=this.pendingCalls.get(e.correlation_id);t&&(clearTimeout(t.timer),this.pendingCalls.delete(e.correlation_id),t.resolve({correlationId:e.correlation_id,success:e.success,payload:e.payload,error:e.error}));break}case"message":{let t={fromName:e.from_name,fromPeerId:e.from_peer_id,messageId:e.message_id,messageType:e.message_type,payload:e.payload,metadata:e.metadata??{},timestampMs:e.timestamp_ms,verified:e.verified,provenance:e.provenance?.map(r=>({signerName:r.signer_name,verified:r.verified})),attestation:e.attestation?{relayName:e.attestation.relay_name,verified:e.attestation.verified}:void 0,delegation:e.delegation?{parentName:e.delegation.parent_name,scope:e.delegation.scope,valid:e.delegation.valid,expired:e.delegation.expired}:void 0};for(let r of this.messageHandlers)try{r(t)}catch{}this.emit("message",t);break}case"inbound_call":this.handleInboundCall(e);break;case"broadcast_message":{let t={topic:e.topic,fromName:e.from_name,fromPeerId:e.from_peer_id,messageId:e.message_id,messageType:e.message_type,payload:e.payload,metadata:e.metadata??{},timestampMs:e.timestamp_ms,verified:e.verified,provenance:e.provenance?.map(n=>({signerName:n.signer_name,verified:n.verified})),attestation:e.attestation?{relayName:e.attestation.relay_name,verified:e.attestation.verified}:void 0,delegation:e.delegation?{parentName:e.delegation.parent_name,scope:e.delegation.scope,valid:e.delegation.valid,expired:e.delegation.expired}:void 0},r=this.topicHandlers.get(e.topic);if(r)for(let n of r)try{n(t)}catch{}this.emit("broadcast",t);break}case"resolved":{let t=this.pendingResolve.get(e.name);t&&(this.pendingResolve.delete(e.name),t.resolve({name:e.name,peerId:e.peer_id}));break}case"error":{let t=uwe(e.code,e.message);this.registerPromise&&e.code==="register_failed"&&(this.registerPromise.reject(new CJ(e.message)),this.registerPromise=null),this.emit("error",t);break}}}async handleInboundCall(e){let t={correlationId:e.correlation_id,fromName:e.from_name,fromPeerId:e.from_peer_id,method:e.method,payload:e.payload,verified:e.verified},r=this.rpcHandlers.get(e.method)??this.defaultRpcHandler,n;if(!r)n={success:!1,error:`No handler for method: ${e.method}`};else try{n=await r(t)}catch(i){n={success:!1,error:i instanceof Error?i.message:String(i)}}try{this.transport.send({type:"call_response",correlation_id:e.correlation_id,success:n.success,payload:n.payload??"",error:n.error??""})}catch{}}handleStatusChange(e){switch(e){case"disconnected":this._peerId=null,this.emit("disconnected");break;case"reconnecting":this.emit("reconnecting",this.transport.reconnectAttempt??0);break;case"connected":if(this.hasConnectedOnce){let t={type:"register",name:this.options.name};this.options.relay&&(t.relay=this.options.relay),this._keypair&&(t.public_key=xlt(this._keypair.publicKey));try{this.transport.send(t)}catch{}}break}}resubscribeTopics(){for(let e of this.topicHandlers.keys())try{this.transport.send({type:"subscribe",topic:e})}catch{}}};});var zwe={};Gi(zwe,{SUBWAY_PROTOCOL:()=>ypt,registerDirect:()=>Bwr,resolveDirect:()=>Nwr});function qwe(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 Wd(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 Uwe(e,t){return e<<3|t}function hk(e,t,r){e.push(Uwe(t,2)),qwe(e,r.length);for(let n of r)e.push(n)}function wwr(e,t){let r=[];return hk(r,1,jwe.encode(e)),t&&t.length>0&&hk(r,2,jwe.encode(t)),Uint8Array.from(r)}function xwr(e,t,r){let n=[];return r!==0n&&(n.push(Uwe(1,0)),qwe(n,r)),hk(n,2,wwr(e,t)),Uint8Array.from(n)}function Ewr(e){let t=[];return hk(t,1,jwe.encode(e)),Uint8Array.from(t)}function Awr(e,t){let r=[];return t!==0n&&(r.push(Uwe(1,0)),qwe(r,t)),hk(r,3,Ewr(e)),Uint8Array.from(r)}function Swr(e){let t=0,r={success:!1,error:""};for(;t<e.length;){let[n,i]=Wd(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===0){let[a,c]=Wd(e,t);t=c,r.success=a!==0n}else if(o===2&&s===2){let[a,c]=Wd(e,t),u=c,d=u+Number(a);r.error=mpt.decode(e.subarray(u,d)),t=d}else t=Mwe(e,t,s)}return r}function Twr(e){let t=0,r={peerId:new Uint8Array(0),error:""};for(;t<e.length;){let[n,i]=Wd(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===2){let[a,c]=Wd(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]=Wd(e,t),u=c,d=u+Number(a);r.error=mpt.decode(e.subarray(u,d)),t=d}else t=Mwe(e,t,s)}return r}function Mwe(e,t,r){if(r===0)return Wd(e,t)[1];if(r===2){let[n,i]=Wd(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 hpt(e){let t=0,r={requestId:0n};for(;t<e.length;){let[n,i]=Wd(e,t);t=i;let o=Number(n)>>3,s=Number(n)&7;if(o===1&&s===0){let[a,c]=Wd(e,t);t=c,r.requestId=a}else if(o===13&&s===2){let[a,c]=Wd(e,t),u=c,d=u+Number(a);r.registerNameResponse=Swr(e.subarray(u,d)),t=d}else if(o===14&&s===2){let[a,c]=Wd(e,t),u=c,d=u+Number(a);r.resolveNameResponse=Twr(e.subarray(u,d)),t=d}else t=Mwe(e,t,s)}return r}function Pwr(e){let t=new Uint8Array(4+e.length);return new DataView(t.buffer).setUint32(0,e.length,!1),t.set(e,4),t}function Dwe(e){return new DataView(e.buffer,e.byteOffset,4).getUint32(0,!1)}function Iwr(e){if(e.length<4)return{success:!1,error:"short reply (no length prefix)"};let t=Dwe(e.subarray(0,4));return e.length<4+t?{success:!1,error:`truncated frame (have ${e.length-4}, need ${t})`}:hpt(e.subarray(4,4+t)).registerNameResponse??{success:!1,error:"reply carried no register_name_response"}}function Owr(e){if(e.length<4)return{peerId:new Uint8Array(0),error:"short reply (no length prefix)"};let t=Dwe(e.subarray(0,4));return e.length<4+t?{peerId:new Uint8Array(0),error:`truncated frame (have ${e.length-4}, need ${t})`}:hpt(e.subarray(4,4+t)).resolveNameResponse??{peerId:new Uint8Array(0),error:"reply carried no resolve_name_response"}}function Nwe(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 kwr(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>spt)throw new Error("subway: reply exceeded max size");if(n<0&&r>=4&&(n=4+Dwe(Nwe(t).subarray(0,4)),n>spt))throw new Error("subway: declared frame exceeds max size");if(n>=0&&r>=n)return Nwe(t).subarray(0,n)}return Nwe(t)}async function gpt(e){return(0,apt.createLibp2p)({...e?{privateKey:await(0,lpt.generateKeyPairFromSeed)("Ed25519",e)}:{},transports:[(0,cpt.tcp)()],connectionEncrypters:[(0,upt.noise)()],streamMuxers:[(0,dpt.yamux)()],connectionGater:{denyDialMultiaddr:async()=>!1}})}async function bpt(e,t,r){let n=await e.dialProtocol((0,ppt.multiaddr)(t),ypt,{signal:AbortSignal.timeout(Cwr)});n.send(Pwr(r));let i;return Promise.race([kwr(n),new Promise((o,s)=>{i=setTimeout(()=>s(new Error("subway: request timed out")),Rwr)})]).finally(()=>clearTimeout(i))}async function Bwr(e){let t=await gpt(e.seed);try{let r=await bpt(t,e.relayMultiaddr,xwr(e.name,e.binding,e.requestId??1n)),n=Iwr(r);return{success:n.success,error:n.error,peerId:t.peerId.toString()}}finally{await t.stop()}}async function Nwr(e){let t=await gpt(e.seed);try{let r=await bpt(t,e.relayMultiaddr,Awr(e.name,e.requestId??1n)),n=Owr(r);return n.peerId.length===0?{found:!1,peerId:"",error:n.error||"name not found"}:{found:!0,peerId:(0,fpt.toString)(n.peerId,"base58btc"),error:""}}finally{await t.stop()}}var apt,cpt,upt,dpt,lpt,ppt,fpt,jwe,mpt,ypt,Cwr,Rwr,spt,Lwe=P(()=>{"use strict";lwe();apt=require("libp2p"),cpt=require("@libp2p/tcp"),upt=require("@chainsafe/libp2p-noise"),dpt=require("@chainsafe/libp2p-yamux"),lpt=require("@libp2p/crypto/keys"),ppt=require("@multiformats/multiaddr"),fpt=require("uint8arrays/to-string"),jwe=new TextEncoder,mpt=new TextDecoder;ypt="/subway/p2p/1.0.0",Cwr=15e3,Rwr=15e3,spt=1<<20});var gk={};Gi(gk,{DEFAULT_VISA_RELAY_MULTIADDR:()=>vpt,MESH:()=>vs,RELAY_URL:()=>Wwe,connectOrThrow:()=>ZJ,ensureMailbox:()=>Qwe,isSubwayEnabled:()=>Gwe,listRegistered:()=>Dwr,loadBindingFor:()=>Zwe,loadRegistry:()=>Bv,makeClient:()=>YJ,maybeMintVisaBinding:()=>xpt,meshName:()=>gp,pairedVisaBinding:()=>Ept,readInbox:()=>Lwr,registerName:()=>Xwe,resolveActingName:()=>qwr,resolveMeshName:()=>Uwr,seedSubwayKeyFromTapAgent:()=>wpt,sendMessage:()=>Mwr,sendVia:()=>Hwr,subwayKeyPath:()=>JJ,visaRelayMultiaddr:()=>Kwe});function Kwe(e=process.env){return e.SUBWAY_RELAY_MULTIADDR??vpt}function gp(e){return e.includes(".")?e:`${e}.${vs}`}function Gwe(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 Ywe(){co.mkdirSync(Jwe,{recursive:!0,mode:448})}function jwr(e){return e.replace(/[^a-zA-Z0-9_.-]/g,"_")}function JJ(e){return lA.join(Jwe,`${jwr(e)}.key`)}function Bv(){if(!co.existsSync(Vwe))return{};try{return JSON.parse(co.readFileSync(Vwe,"utf8"))}catch{return{}}}function Fwe(e){Ywe(),co.writeFileSync(Vwe,JSON.stringify(e,null,2),{mode:384})}function $we(){try{return yk.userInfo().username}catch{return"local"}}function wpt(e){if(co.existsSync(e)||!co.existsSync(Hwe))return null;let t=co.readdirSync(Hwe).filter(n=>n.endsWith(".json"));if(t.length===0)return null;let r=t.map(n=>lA.join(Hwe,n)).sort((n,i)=>co.statSync(i).mtimeMs-co.statSync(n).mtimeMs)[0];try{let n=JSON.parse(co.readFileSync(r,"utf8"));if(!n.private_key_jwk)return null;let i=DA(n.private_key_jwk);return Ywe(),co.writeFileSync(e,Buffer.from(i),{mode:384}),n.agent_id??null}catch{return null}}function YJ(e,t={}){return new ipt({name:gp(e),url:Wwe,keyPath:JJ(e),autoReconnect:t.autoReconnect??!1,binding:t.binding})}function Zwe(e){if(vs!=="visa")return;let t=Bv()[e];if(t?.binding&&!(t.bindingExpiresAt&&Date.parse(t.bindingExpiresAt)<=Date.now()))return t.binding}async function ZJ(e,t=15e3){await Promise.race([e.connect(),new Promise((r,n)=>setTimeout(()=>n(new Error(`Subway relay connect timed out after ${t}ms (${Wwe})`)),t))])}function qwr(e){if(e)return e;let t=Object.keys(Bv());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>.`)}async function xpt(e){if(vs!=="visa")return null;let t=process.env.VISA_CLI_API_KEY?.trim();if(!t)throw new m2("No enrolled V4 agent or Visa Key is available for the trusted .visa mesh.","no_key");try{return await hZ({authUrl:ju(),apiKey:t,seed:gB(JJ(e)),name:gp(e)})}catch(r){if(r instanceof m2)throw r;return console.warn(`[subway] Visa binding not minted: ${r instanceof Error?r.message:String(r)}`),null}}function Ept(e=Date.now()){let t=e8e();if(!t?.binding_jwt)return null;let r=bk(t.binding_jwt);if(!r||r.mesh!=="visa")return null;let n=typeof r.exp=="number"?r.exp:NaN;return!Number.isFinite(n)||n*1e3<=e?null:{binding:t.binding_jwt,bindingExpiresAt:new Date(n*1e3).toISOString()}}async function Xwe(e){let t=JJ(e),r=wpt(t),n=gp(e);vs==="visa"&&!co.existsSync(t)&&(Ywe(),co.writeFileSync(t,(0,_pt.randomBytes)(32),{mode:384}));let i=vs==="visa"?Ept():null,o,s={};if(i)o=i.binding,s={binding:i.binding,bindingExpiresAt:i.bindingExpiresAt};else{let u=await xpt(e);u&&(o=u.binding,s={binding:u.binding,bindingExpiresAt:new Date(Date.now()+u.expires_in*1e3).toISOString()})}let a=vs==="visa"?Kwe():process.env.SUBWAY_RELAY_MULTIADDR;if(vs==="visa"&&a){let{registerDirect:u}=await Promise.resolve().then(()=>(Lwe(),zwe)),d=await u({relayMultiaddr:a,seed:gB(t),name:n,binding:o});if(!d.success)throw new Error(`.visa relay admission failed: ${d.error||"unknown"}`);let l=Bv();return l[e]={relayName:n,mesh:vs,peerId:d.peerId,owner:$we(),tapAgentId:r,registeredAt:new Date().toISOString(),...s},Fwe(l),{relayName:n,mesh:vs,peerId:d.peerId,tapAgentId:r,...o?{binding:o}:{}}}if(vs==="visa"&&!process.env.SUBWAY_RELAY){let u=Bv();return u[e]={relayName:n,mesh:vs,peerId:null,owner:$we(),tapAgentId:r,registeredAt:new Date().toISOString(),...s},Fwe(u),{relayName:n,mesh:vs,peerId:null,tapAgentId:r,...o?{binding:o}:{},note:o?"Visa binding ready; relay admission pending a .visa relay (set SUBWAY_RELAY).":"No Visa binding; pair/enroll this agent, or set VISA_CLI_API_KEY (card on file), for a .visa binding."}}let c=YJ(e,{autoReconnect:!1,binding:o});try{await ZJ(c);let u=Bv();return u[e]={relayName:n,mesh:vs,peerId:c.peerId,owner:$we(),tapAgentId:r,registeredAt:new Date().toISOString(),...s},Fwe(u),{relayName:n,mesh:vs,peerId:c.peerId,tapAgentId:r,...o?{binding:o}:{}}}finally{c.disconnect()}}async function Uwr(e){let t=gp(e),r=vs==="visa"?Kwe():process.env.SUBWAY_RELAY_MULTIADDR;if(vs==="visa"&&r){let{resolveDirect:n}=await Promise.resolve().then(()=>(Lwe(),zwe)),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 Mwr(e,t,r){let n=YJ(e,{autoReconnect:!1,binding:Zwe(e)});try{await ZJ(n);let i=gp(t);return await n.sendSigned(i,"chat",r),{to:i,as:gp(e)}}finally{n.disconnect()}}function Dwr(){let e=Bv();return Object.entries(e).map(([t,r])=>({name:t,...r}))}async function Qwe(e){let t=GJ.get(e);if(t)return{relayName:gp(e),peerId:t.client.peerId};let r=YJ(e,{autoReconnect:!0,binding:Zwe(e)}),n=[];return r.onMessage(i=>{n.push({from:i.fromName,text:i.payload,ts:i.timestampMs,verified:!!i.verified}),n.length>zwr&&n.shift()}),GJ.set(e,{client:r,buffer:n}),await ZJ(r),{relayName:gp(e),peerId:r.peerId}}async function Lwr(e,t=20,r=!1){await Qwe(e);let n=GJ.get(e);if(!n)return[];let i=n.buffer.slice(-t);return r&&(n.buffer.length=0),i}async function Hwr(e,t,r){await Qwe(e);let n=GJ.get(e);if(!n)throw new Error(`mailbox for ${e} unavailable`);let i=gp(t);return await n.client.sendSigned(i,"chat",r),{to:i,as:gp(e)}}var co,yk,lA,_pt,vs,vpt,Wwe,Jwe,Vwe,Hwe,GJ,zwr,Nv=P(()=>{"use strict";opt();f2();co=Ze(require("fs")),yk=Ze(require("os")),lA=Ze(require("path")),_pt=require("crypto");a4();LA();XJ();vs=process.env.SUBWAY_MESH??"relay",vpt="/dns4/subway-relay-visa.fly.dev/tcp/9100/p2p/12D3KooWM2q6SXgKFxj5wvnJ7gTD4XPjhvc5tHVVjDBrZRnJ3CKU";Wwe=process.env.SUBWAY_RELAY??"wss://relay.subway.dev/ws";Jwe=lA.join(yk.homedir(),".visa-cli","subway"),Vwe=lA.join(Jwe,"registry.json"),Hwe=lA.join(yk.homedir(),".visa-cli","agents");GJ=new Map,zwr=200});async function Fwr(e){if(process.env.SUBWAY_MESH==="visa")try{await Xwe(e)}catch(t){Be.warn("subway:pairing-auto-register-failed",{name:e,mesh:"visa",error:t instanceof Error?t.message:String(t)})}}function $wr(e=process.env.VISA_V4_HOME||pA.join(t8e.homedir(),".visa-v4")){try{let t=qc.readFileSync(pA.join(e,"identity","mailbox.json"),"utf8"),r=JSON.parse(t);return typeof r.email!="string"||!r.email.includes("@")||typeof r.inboxId!="string"||r.inboxId.length===0?null:{email:r.email,inboxId:r.inboxId}}catch{return null}}function r8e(e,t,r=_k){return pA.join(r,`${e}.${t}.json`)}function Spt(e,t=_k){qc.mkdirSync(t,{recursive:!0,mode:448}),qc.writeFileSync(r8e(e.pairingId,e.role,t),JSON.stringify(e,null,2),{mode:384})}function vk(e,t,r=_k){qc.rmSync(r8e(e,t,r),{force:!0})}function QJ(e,t,r=_k){try{let n=JSON.parse(qc.readFileSync(r8e(e,t,r),"utf8"));return n?.pairingId===e&&n.role===t?n:null}catch{return null}}function n8e(e=_k){return qc.existsSync(e)?qc.readdirSync(e).filter(r=>r.endsWith(".human.json")).map(r=>{try{return JSON.parse(qc.readFileSync(pA.join(e,r),"utf8"))}catch{return null}}).filter(r=>r?.role==="human").sort((r,n)=>n.createdAt.localeCompare(r.createdAt))[0]??null:null}async function jv(e,t,r){let n=await r(e,{...t,headers:{"X-Source":"cli","X-Visa-CLI-Version":Apt,...t.headers??{}}}),i=await n.json().catch(()=>({}));if(!n.ok&&n.status!==202)throw new Error(i.error??i.detail??`pairing server returned ${n.status}`);return{status:n.status,body:i}}async function i8e(e={}){let t=(e.authUrl??ju()).replace(/\/+$/,""),r=p9e(),n=$wr(),{body:i}=await jv(`${t}/v4/agent-pairings`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({cliChallenge:f9e(r),...n?{mailbox:n}:{}})},e.fetchImpl??fetch);if(!i.pairingId||!i.skillUrl||!i.expiresAt)throw new Error("pairing server returned an incomplete initiation response");let o={role:"human",pairingId:i.pairingId,verifier:r,authUrl:t,skillUrl:i.skillUrl,expiresAt:i.expiresAt,createdAt:new Date().toISOString()};return Spt(o,e.pairingDir),o}async function eY(e){let{pairing:t}=e,{body:r}=await jv(`${t.authUrl}/v4/agent-pairings/${encodeURIComponent(t.pairingId)}/verify`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({verifier:t.verifier,code:e.code})},e.fetchImpl??fetch);return r}async function o8e(e){let t=(e.authUrl??ju()).replace(/\/+$/,""),{body:r}=await jv(`${t}/v4/agent-pairings/${encodeURIComponent(e.pairingId)}`,{method:"GET",cache:"no-store"},e.fetchImpl??fetch);return r}function Tpt(e,t){return Buffer.from(f4(e,Buffer.from(t,"utf8"))).toString("base64url")}async function s8e(e){let t=(e.authUrl??ju()).replace(/\/+$/,""),r=e.fetchImpl??fetch,n=await o8e({pairingId:e.pairingId,authUrl:t,fetchImpl:r});if(n.state!=="awaiting_agent"||!n.serverNonce)throw new Error(`pairing cannot be claimed from state ${n.state}`);let i,o,s;if(e.existingCredential)s=e.existingCredential.privateKeyJwk,o=e.existingCredential.publicKeyJwk,i=Buffer.from(s.d,"base64url");else{let m=mB();i=m.secretKey,s=m4(i),o=ch(m.publicKey)}let a=h4(o),c=AJ(),u=m9e(),d={runtime:e.runtime,contextLabel:e.contextLabel,platform:`${process.platform}/${process.arch}`,cliVersion:Apt},l=Tpt(i,h9e({pairingId:e.pairingId,serverNonce:n.serverNonce,claimTokenHash:fZ(u),agentJkt:a,walletPublicKey:c.publicKey,runtime:d})),p={role:"runtime",pairingId:e.pairingId,authUrl:t,claimToken:u,agentJkt:a,publicKeyJwk:o,privateKeyJwk:s,walletPublicKey:c.publicKey,walletPrivateKey:c.privateKey,createdAt:new Date().toISOString()};Spt(p,e.pairingDir);let{body:f}=await jv(`${t}/v4/agent-pairings/${encodeURIComponent(e.pairingId)}/claim`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({agentPublicJwk:o,walletPublicKey:c.publicKey,runtime:d,signature:l,claimToken:u})},r);if(!f.verificationCode||f.claimToken!==u)throw new Error("pairing server returned an incomplete claim response");if(f.verificationCode!==hB(e.pairingId,u))throw new Error("pairing server returned a mismatched verification code");return{pending:p,verificationCode:f.verificationCode}}async function tY(e){let t=e.fetchImpl??fetch,r=e.wait??(o=>new Promise(s=>setTimeout(s,o))),n=e.maxPolls??450,i="";for(let o=0;o<n;o+=1){let{body:s,status:a}=await jv(`${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);if(s.state!==i&&(i=s.state,e.onState?.(s.state)),a===202){if(["expired","cancelled","failed","revoked"].includes(s.state))throw new Error(`pairing ended in state ${s.state}`);await r(e.pollIntervalMs??2e3);continue}if(!s.artifacts||!s.artifactHash)throw new Error("pairing delivery omitted identity artifacts");let c=s.artifacts,u=c.terms?.name,d=c.wallet?.turnkey,l=c.terms?.mode==="wallet"||c.terms?.mode==="both",p=EJ(d?.network);if(c.agentJkt!==e.pending.agentJkt||typeof c.bindingJwt!="string"||typeof c.registrationJwt!="string"||typeof c.termsHash!="string"||typeof u!="string"||c.wallet?.credentialPublicKey!==e.pending.walletPublicKey||l&&(!d||typeof d.organizationId!="string"||typeof d.walletId!="string"||typeof d.address!="string"||!/^0x[0-9a-f]{40}$/i.test(d.address)||!p||!Number.isSafeInteger(c.terms?.dailyLimitCents)||!Number.isSafeInteger(c.terms?.perTransactionLimitCents))||g9e(s.artifacts)!==s.artifactHash)throw new Error("pairing artifact integrity check failed");let f=Tpt(Buffer.from(e.pending.privateKeyJwk.d,"base64url"),y9e({pairingId:e.pending.pairingId,agentJkt:e.pending.agentJkt,termsHash:c.termsHash,artifactHash:s.artifactHash}));if((await jv(`${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({signature:f})},t)).body.state!=="activated")throw new Error("pairing activation was not acknowledged");let h={agent_jkt:e.pending.agentJkt,name:u,public_key_jwk:e.pending.publicKeyJwk,private_key_jwk:e.pending.privateKeyJwk,binding_jwt:c.bindingJwt,registration_jwt:c.registrationJwt,wallet_public_key:e.pending.walletPublicKey,pairing_id:e.pending.pairingId,pairing_status:"activated",artifacts:s.artifacts,auth_url:e.pending.authUrl,created_at:new Date().toISOString()};return l&&d&&await xJ({apiPublicKey:e.pending.walletPublicKey,apiPrivateKey:e.pending.walletPrivateKey,organizationId:d.organizationId,walletId:d.walletId,address:d.address,network:p,perTransactionLimitCents:c.terms?.perTransactionLimitCents,dailyLimitCents:c.terms?.dailyLimitCents,...e.walletHome?{homeDir:e.walletHome}:{}}),a8e(h,e.agentDir),await Fwr(u),vk(e.pending.pairingId,"runtime",e.pairingDir),{record:h,name:u,agentJkt:e.pending.agentJkt}}throw new Error("timed out waiting for human authorization")}async function Ppt(e){let{pairing:t}=e,{body:r}=await jv(`${t.authUrl}/v4/agent-pairings/${encodeURIComponent(t.pairingId)}`,{method:"DELETE",headers:{"Content-Type":"application/json"},body:JSON.stringify({verifier:t.verifier})},e.fetchImpl??fetch);return r.state==="cancelled"&&vk(t.pairingId,"human",e.pairingDir),r}var qc,t8e,pA,Apt,_k,Ipt=P(()=>{"use strict";qc=Ze(require("node:fs")),t8e=Ze(require("node:os")),pA=Ze(require("node:path"));f2();LA();Nv();a4();Dc();W4e();XJ();Apt="4.1.0-rc.34",_k=pA.join(t8e.homedir(),".visa-cli","pairings")});var qpt={};Gi(qpt,{agentFilePath:()=>xk,agentFormatIsJson:()=>wk,attachAgentCommand:()=>Gwr,claimOptsFromFlags:()=>d8e,decodeBindingClaims:()=>bk,enrollClaimEnvelope:()=>Npt,isAgentCommandEnabled:()=>Bpt,isAgentRecord:()=>Ek,listAgentFiles:()=>rY,newestAgentRecord:()=>e8e,readAgent:()=>l8e,resolveAgentByRef:()=>jpt,writeAgent:()=>a8e});function Ek(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 Bpt(){return!0}function wk(e){return e==="json"}function Npt(e){switch(e.status){case"claimed":return{json:{status:"claimed",...e.name?{name:e.name}:{},tokenId:e.tokenId,credentialPath:e.credentialPath,keyBound:e.keyBound,sessionSaved:e.sessionSaved,walletProvisioned:e.walletProvisioned},exitCode:0};case"not_ready":return{json:{status:"not_ready",likelyExpired:e.likelyExpired,error:e.likelyExpired?"the 15-minute enrollment window has likely expired":"not ready yet \u2014 finish the browser flow through the final minted screen"},exitCode:3};case"no_pending":return{json:{status:"no_pending",error:"no enrollment hand-off in progress"},exitCode:1};case"confirm_mismatch":return{json:{status:"confirm_mismatch",confirmCode:e.confirmCode,error:"this enrollment hand-off did not match this terminal"},exitCode:1};case"error":return{json:{status:"error",error:e.message},exitCode:1}}}function d8e(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 c8e(e){return`${e.opened?`\u2713 Enrollment link opened in your browser.
20679
20679
  If it did not open, paste this into your phone or browser:
20680
20680
  `:`Enrollment link (open on your phone):
20681
20681
  `}
@@ -20708,7 +20708,7 @@ ${e.nonce}`;return x4r.encode(r)}function S4r(e,t,r,n,i,o,s){return A4r({message
20708
20708
  `;case"error":return` MCP: mount failed (skill still installed) \u2014 ${e.note}
20709
20709
  `}}function Opt(e,t){if(t){process.stdout.write(JSON.stringify({status:"already_connected",...e.name?{name:e.name}:{},keyBound:e.keyBound})+`
20710
20710
  `);return}process.stdout.write(`\u2713 This device is already connected${e.name?` as ${e.name}`:""} \u2014 nothing to pair.
20711
- To add or change spending on this identity, run: visa agent add-rail
20711
+ To add or change spending on this identity, approve it in your account settings (agent card \u2192 Spend).
20712
20712
  (Re-run with --new to force a brand-new enrollment anyway.)
20713
20713
  `)}function Cpt(e,t){let{json:r,exitCode:n}=Npt(e);if(t)process.stdout.write(JSON.stringify(r)+`
20714
20714
  `);else{let{text:i,toStderr:o}=Vwr(e);(o?process.stderr:process.stdout).write(i)}n!==0&&(process.exitCode=n)}function Wwr(e=Uv){Do.mkdirSync(e,{recursive:!0,mode:448})}function xk(e,t=Uv){return qv.join(t,`${e}.json`)}function rY(e=Uv){return Do.existsSync(e)?Do.readdirSync(e).filter(t=>t.endsWith(".json")).map(t=>qv.join(e,t)):[]}function l8e(e,t=Uv){let r=xk(e,t);if(!Do.existsSync(r))return null;try{let n=JSON.parse(Do.readFileSync(r,"utf8"));return Ek(n)?n:null}catch{return null}}function jpt(e,t=Uv){let r=e.trim();if(!r)return null;let n=l8e(r,t);if(n)return n;let i=r.replace(/\.visa$/i,"").toLowerCase(),o=[];for(let s of rY(t)){let a;try{a=JSON.parse(Do.readFileSync(s,"utf8"))}catch{continue}Ek(a)&&a.name.replace(/\.visa$/i,"").toLowerCase()===i&&o.push(a)}if(o.length>1)throw new Error(`more than one agent is named "${r}" on this machine \u2014 re-run with the agent's jkt instead`);return o[0]??null}function a8e(e,t=Uv){Wwr(t);let r=xk(e.agent_jkt,t);Do.writeFileSync(r,JSON.stringify(e,null,2),{mode:384})}function e8e(e=Uv){let t=rY(e).sort((r,n)=>Do.statSync(n).mtimeMs-Do.statSync(r).mtimeMs)[0];if(!t)return null;try{let r=JSON.parse(Do.readFileSync(t,"utf8"));return Ek(r)?r:null}catch{return null}}function bk(e){let t=e.split(".");if(t.length!==3)return null;try{let r=JSON.parse(Buffer.from(t[1],"base64url").toString("utf8"));return r===null||typeof r!="object"||Array.isArray(r)?null:r}catch{return null}}function Gwr(e){if(!Bpt())return;let t=e.command("agent").description("Connect and manage agent runtimes with human-approved Visa identities.");t.command("create").description("Create a secure runtime pairing and authorize it in the browser.").action(async()=>{try{let r=await i8e();if(process.stdout.write(["Agent pairing ready.","","Give this skill link to the agent you want to connect:","",` ${r.skillUrl}`,"",`Pairing expires at ${r.expiresAt}.`].join(`
@@ -20769,13 +20769,13 @@ Approve it in your browser \u2014 grant the new rail to your existing agent.
20769
20769
  `)}}),t.command("show <jkt>").description("Show an agent record and the decoded (unverified) binding claims.").action(r=>{let n=l8e(r);if(!n){let o=xk(r);process.stderr.write(Do.existsSync(o)?`Invalid or unreadable agent record: ${r}
20770
20770
  `:`Agent not found: ${r}
20771
20771
  `),process.exit(1)}let i=n.binding_jwt?bk(n.binding_jwt):null;process.stdout.write([`agent 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)`,`wallet key: ${n.wallet_public_key}`,"registration: stored",`key file: ${xk(n.agent_jkt)}`,"binding claims (decoded locally, NOT verified):",i?JSON.stringify(i,null,2):" (no binding stored or malformed JWT)",""].join(`
20772
- `))})}var Rpt,Do,kpt,qv,u8e,Uv,XJ=P(()=>{"use strict";Rpt=require("node:child_process"),Do=Ze(require("fs")),kpt=Ze(require("os")),qv=Ze(require("path")),u8e=require("node:readline/promises");f2();JY();DY();X4e();Hdt();Vdt();Ipt();Uv=qv.join(kpt.homedir(),".visa-cli","agents")});var m8e={};Gi(m8e,{CardDrawRefusedError:()=>Mv,cardDrawIntentHash:()=>zpt,decimalUsdToCents:()=>f8e,fetchCardDrawVerdict:()=>r8r,loadCardMandateCapability:()=>t8r,registerCardMandate:()=>n8r});function Ywr(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,p8e.createHash)("sha256").update(t,"utf8").digest().toString("base64url")}function Zwr(e){let{secretKey:t,publicKey:r}=u9e(e),n=m4(t),i=ch(r);return{privateJwk:n,publicJwk:i,jkt:Ywr(i)}}async function Mpt(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:Jwr},o=`${Upt(i)}.${Upt(n)}`,s=DA(e.privateJwk),a=f4(s,Buffer.from(o,"utf8"));return`${o}.${Buffer.from(a).toString("base64url")}`}function Dpt(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(!Xwr.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:Qwr,amount:t,currency:o,payee:n,intentId:i??null,settlementHash:null});return(0,p8e.createHash)("sha256").update(s,"utf8").digest().toString("base64url")}function e8r(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 f8e(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 zpt(e,t){let r=f8e(e.amount);return r===null?null:Dpt({amount:r,currency:e.currency,payee:e.merchantUrl,intentId:t})}function t8r(e={}){let t=e.record!==void 0?e.record:(XJ(),ie(qpt)).newestAgentRecord();if(!t||!t.binding_jwt||!t.auth_url)return null;let r=e8r(t.binding_jwt);if(r!=="card"&&r!=="both")return null;let n;try{n=Zwr(DA(t.private_key_jwk))}catch{return null}return n.jkt!==t.agent_jkt?null:{agentKey:n,agentJkt:t.agent_jkt,authBaseUrl:t.auth_url}}function Lpt(e){return e.replace(/\/+$/,"")}async function r8r(e){let t=e.fetchImpl??fetch,r=e.now??(()=>Math.floor(Date.now()/1e3)),n=Lpt(e.authBaseUrl),i=zpt(e.draw,e.drawId);if(i===null)throw new Mv(400,["invalid_amount"]);let o=await t(`${n}/v4/card/draw/challenge`,{method:"POST",headers:{"content-type":"application/json","x-source":"cli"}});if(!o.ok)throw new Mv(o.status,["challenge_failed"]);let s=await o.json();if(!s.nonce||!s.audience)throw new Mv(502,["challenge_malformed"]);let a=await Mpt(e.agentKey,{nonce:s.nonce,audience:s.audience,nowSec:r(),intentHash:i}),c=await 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 Mv(c.status,u?.reasons??["verdict_refused"]);return{verdict:u.verdict,remainingCents:Number(u.remainingCents??0)}}async function n8r(e){try{let t=e.fetchImpl??fetch,r=e.now??(()=>Math.floor(Date.now()/1e3)),n=Lpt(e.authBaseUrl),i=f8e(e.ceiling);if(i===null)return{ok:!1,reason:"invalid_amount"};let o=Dpt({amount:i,currency:e.currency,payee:"card-mandate-register",intentId:e.mandateId}),s=await 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 Mpt(e.agentKey,{nonce:a.nonce,audience:a.audience,nowSec:r(),intentHash:o}),u=await 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 p8e,Jwr,Upt,Xwr,Qwr,Mv,h8e=P(()=>{"use strict";p8e=require("node:crypto");f2();Jwr="visa-agent-pop+jwt",Upt=e=>Buffer.from(JSON.stringify(e),"utf8").toString("base64url");Xwr=new Set(["USD","EUR","GBP","CAD","AUD","JPY","CHF","CNY","HKD","SGD","INR","MXN","BRL","NZD","SEK","NOK","DKK","ZAR","AED"]),Qwr=1;Mv=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}});var AY={};Gi(AY,{initSentry:()=>Cxr,isSentryConfigured:()=>Oxr,reportFatal:()=>Rxr});function Oxr(){return!1}async function Cxr(){return null}async function Rxr(e,t){process.exit(t?.exitCode??1)}var SY=P(()=>{});var wmt=require("@modelcontextprotocol/sdk/server/index.js"),xmt=require("@modelcontextprotocol/sdk/server/stdio.js"),Im=require("@modelcontextprotocol/sdk/types.js");async function D8e(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 zk=class extends Error{code="ATTESTATION_KEY_DRIFT";hint;constructor(t,r){super(t),this.name="AttestationDriftError",this.hint=r}};var z8e={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 L8e(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&&z8e[r]?z8e[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 Mmt=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function F8e(e,t){let r=H8e(e),n=H8e(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:Dmt(r.pre,n.pre)>0}function H8e(e){if(typeof e!="string")return null;let r=e.trim().replace(/^v/,"").match(Mmt);return r?{main:[Number(r[1]),Number(r[2]),Number(r[3])],pre:r[4]??null}:null}function Dmt(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}function Lk(){return!!($8e(process.env.VISA_CLI_NO_UPDATE_CHECK)||$8e(process.env.CI)||process.env.NODE_ENV==="test")}function $8e(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}a4();var Wk="4.1.0-rc.33",e0t=/^vk_(?:live|test)_[A-Za-z0-9_-]{16,128}$/;function t0t(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}).`)}var r0t="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";function c4(e){return typeof e=="string"?e.trim():""}function n0t(e){let t=e&&typeof e=="object"?e:{},r=c4(t.error)||c4(t.message);if(!r)return r0t;let n=c4(t.error_code),i=[["surface",c4(t.disabled_surface)],["flag",c4(t.flag)],["correlation_id",c4(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 i0t(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?e0t.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(`
20772
+ `))})}var Rpt,Do,kpt,qv,u8e,Uv,XJ=P(()=>{"use strict";Rpt=require("node:child_process"),Do=Ze(require("fs")),kpt=Ze(require("os")),qv=Ze(require("path")),u8e=require("node:readline/promises");f2();JY();DY();X4e();Hdt();Vdt();Ipt();Uv=qv.join(kpt.homedir(),".visa-cli","agents")});var m8e={};Gi(m8e,{CardDrawRefusedError:()=>Mv,cardDrawIntentHash:()=>zpt,decimalUsdToCents:()=>f8e,fetchCardDrawVerdict:()=>r8r,loadCardMandateCapability:()=>t8r,registerCardMandate:()=>n8r});function Ywr(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,p8e.createHash)("sha256").update(t,"utf8").digest().toString("base64url")}function Zwr(e){let{secretKey:t,publicKey:r}=u9e(e),n=m4(t),i=ch(r);return{privateJwk:n,publicJwk:i,jkt:Ywr(i)}}async function Mpt(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:Jwr},o=`${Upt(i)}.${Upt(n)}`,s=DA(e.privateJwk),a=f4(s,Buffer.from(o,"utf8"));return`${o}.${Buffer.from(a).toString("base64url")}`}function Dpt(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(!Xwr.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:Qwr,amount:t,currency:o,payee:n,intentId:i??null,settlementHash:null});return(0,p8e.createHash)("sha256").update(s,"utf8").digest().toString("base64url")}function e8r(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 f8e(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 zpt(e,t){let r=f8e(e.amount);return r===null?null:Dpt({amount:r,currency:e.currency,payee:e.merchantUrl,intentId:t})}function t8r(e={}){let t=e.record!==void 0?e.record:(XJ(),ie(qpt)).newestAgentRecord();if(!t||!t.binding_jwt||!t.auth_url)return null;let r=e8r(t.binding_jwt);if(r!=="card"&&r!=="both")return null;let n;try{n=Zwr(DA(t.private_key_jwk))}catch{return null}return n.jkt!==t.agent_jkt?null:{agentKey:n,agentJkt:t.agent_jkt,authBaseUrl:t.auth_url}}function Lpt(e){return e.replace(/\/+$/,"")}async function r8r(e){let t=e.fetchImpl??fetch,r=e.now??(()=>Math.floor(Date.now()/1e3)),n=Lpt(e.authBaseUrl),i=zpt(e.draw,e.drawId);if(i===null)throw new Mv(400,["invalid_amount"]);let o=await t(`${n}/v4/card/draw/challenge`,{method:"POST",headers:{"content-type":"application/json","x-source":"cli"}});if(!o.ok)throw new Mv(o.status,["challenge_failed"]);let s=await o.json();if(!s.nonce||!s.audience)throw new Mv(502,["challenge_malformed"]);let a=await Mpt(e.agentKey,{nonce:s.nonce,audience:s.audience,nowSec:r(),intentHash:i}),c=await 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 Mv(c.status,u?.reasons??["verdict_refused"]);return{verdict:u.verdict,remainingCents:Number(u.remainingCents??0)}}async function n8r(e){try{let t=e.fetchImpl??fetch,r=e.now??(()=>Math.floor(Date.now()/1e3)),n=Lpt(e.authBaseUrl),i=f8e(e.ceiling);if(i===null)return{ok:!1,reason:"invalid_amount"};let o=Dpt({amount:i,currency:e.currency,payee:"card-mandate-register",intentId:e.mandateId}),s=await 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 Mpt(e.agentKey,{nonce:a.nonce,audience:a.audience,nowSec:r(),intentHash:o}),u=await 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 p8e,Jwr,Upt,Xwr,Qwr,Mv,h8e=P(()=>{"use strict";p8e=require("node:crypto");f2();Jwr="visa-agent-pop+jwt",Upt=e=>Buffer.from(JSON.stringify(e),"utf8").toString("base64url");Xwr=new Set(["USD","EUR","GBP","CAD","AUD","JPY","CHF","CNY","HKD","SGD","INR","MXN","BRL","NZD","SEK","NOK","DKK","ZAR","AED"]),Qwr=1;Mv=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}});var AY={};Gi(AY,{initSentry:()=>Cxr,isSentryConfigured:()=>Oxr,reportFatal:()=>Rxr});function Oxr(){return!1}async function Cxr(){return null}async function Rxr(e,t){process.exit(t?.exitCode??1)}var SY=P(()=>{});var wmt=require("@modelcontextprotocol/sdk/server/index.js"),xmt=require("@modelcontextprotocol/sdk/server/stdio.js"),Im=require("@modelcontextprotocol/sdk/types.js");async function D8e(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 zk=class extends Error{code="ATTESTATION_KEY_DRIFT";hint;constructor(t,r){super(t),this.name="AttestationDriftError",this.hint=r}};var z8e={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 L8e(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&&z8e[r]?z8e[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 Mmt=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function F8e(e,t){let r=H8e(e),n=H8e(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:Dmt(r.pre,n.pre)>0}function H8e(e){if(typeof e!="string")return null;let r=e.trim().replace(/^v/,"").match(Mmt);return r?{main:[Number(r[1]),Number(r[2]),Number(r[3])],pre:r[4]??null}:null}function Dmt(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}function Lk(){return!!($8e(process.env.VISA_CLI_NO_UPDATE_CHECK)||$8e(process.env.CI)||process.env.NODE_ENV==="test")}function $8e(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}a4();var Wk="4.1.0-rc.34",e0t=/^vk_(?:live|test)_[A-Za-z0-9_-]{16,128}$/;function t0t(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}).`)}var r0t="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";function c4(e){return typeof e=="string"?e.trim():""}function n0t(e){let t=e&&typeof e=="object"?e:{},r=c4(t.error)||c4(t.message);if(!r)return r0t;let n=c4(t.error_code),i=[["surface",c4(t.disabled_surface)],["flag",c4(t.flag)],["correlation_id",c4(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 i0t(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?e0t.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(`
20773
20773
  `)}var Gk=class{constructor(t){this.getSessionToken=t;this.baseUrl=ju()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!Lk()){let n=t.headers.get("X-Latest-Version");n&&F8e(n,Wk)&&(this.lastSignals.updateAvailable={currentVersion:Wk,latestVersion:n})}let r=t.headers.get("X-Feedback-Prompt");if(r)try{this.lastSignals.feedbackPrompt=JSON.parse(r)}catch{}}getClientVersion(){return Wk}throwIfAttestationDrift(t){if(t?.error_code==="ATTESTATION_KEY_DRIFT")throw new zk(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(n0t(r))}async request(t,r,n,i,o){let s=await this.getSessionToken();if(!s)throw new Error(i0t());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 D8e(`${this.baseUrl}${r}`,{method:t,headers:{...a,"X-Visa-CLI-Version":Wk,"X-Source":"cli"},body:n?JSON.stringify(n):void 0,timeoutMs:i})}catch(d){throw new Error(L8e(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),t0t(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 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)}};DY();var w3e=require("child_process"),x3e=require("util"),E3e=Ze(require("crypto")),$r=Ze(require("fs")),A3e=Ze(require("os")),xs=Ze(require("path"));Dc();Yk();NA();var tB=(0,x3e.promisify)(w3e.execFile);var v0t=()=>process.platform==="darwin",nB=()=>process.platform==="win32",oh=xs.join(A3e.homedir(),".visa-mcp","bin"),c2=xs.join(oh,"Visa CLI"),Rm=xs.join(oh,"visa-keychain-win.exe"),S3e=xs.join(__dirname,"..","native"),m3e="6",h3e=xs.join(oh,"visa-keychain.version"),y3e=xs.join(oh,"visa-keychain.sha256"),g3e="1",b3e=xs.join(oh,"visa-keychain-win.version"),_3e=xs.join(oh,"visa-keychain-win.sha256"),T3e=[xs.join(S3e,"bin","win32-x64","visa-keychain-win.exe"),xs.resolve(__dirname,"..","..","native","bin","win32-x64","visa-keychain-win.exe"),xs.resolve(__dirname,"..","native","bin","win32-x64","visa-keychain-win.exe")];function rB(e){let t=$r.readFileSync(e);return E3e.createHash("sha256").update(t).digest("hex")}function w0t(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)}async function x0t(){try{if($r.readFileSync(h3e,"utf-8").trim()===m3e&&$r.existsSync(c2)){let n=$r.readFileSync(y3e,"utf-8").trim();if(rB(c2)!==n)Be.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),$r.unlinkSync(c2);else return c2}}catch{}let e=xs.join(S3e,"visa-keychain.m");if($r.existsSync(e)||(e=xs.resolve(__dirname,"..","..","native","visa-keychain.m")),$r.existsSync(e)||(e=xs.resolve(__dirname,"..","native","visa-keychain.m")),!$r.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");$r.mkdirSync(oh,{recursive:!0,mode:448});try{await tB("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",c2,e],{timeout:3e4})}catch(r){throw r.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):r}let t=rB(c2);return $r.writeFileSync(y3e,t,{mode:384}),$r.writeFileSync(h3e,m3e,{mode:384}),c2}function P3e(){for(let e of T3e)if($r.existsSync(e))return e;return null}async function I3e(){try{if($r.readFileSync(b3e,"utf-8").trim()===g3e&&$r.existsSync(Rm)){let n=$r.readFileSync(_3e,"utf-8").trim();if(rB(Rm)!==n)Be.warn("binary:hash-mismatch:win32",{message:"Windows binary hash mismatch. Redeploying."}),$r.unlinkSync(Rm);else return Rm}}catch{}let e=P3e();if(!e)throw new Error(`visa-keychain-win.exe not found in package. Reinstall @visa/cli.
20774
20774
  If building from source, run native/build-win.bat first.`);$r.mkdirSync(oh,{recursive:!0}),$r.copyFileSync(e,Rm);let t=rB(Rm);return $r.writeFileSync(_3e,t,{mode:384}),$r.writeFileSync(b3e,g3e,{mode:384}),Rm}async function E0t(){return nB()?I3e():x0t()}var A0t="visa-cli",S0t="attestation-key";async function T0t(e){let t=await E0t(),r;try{r=(await tB(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 w0t(r)}var v3e=!1;function P0t(){if(!nB())return!1;try{return $r.existsSync(Rm)||P3e()!==null?!0:(v3e||(v3e=!0,Be.warn("binary:missing:win32",{message:"visa-keychain-win.exe not found; Windows Hello attestation unavailable on this install.",binPath:Rm,searchedPrebuiltPaths:T3e})),!1)}catch{return!1}}function O3e(){return Jk()||v0t()?!0:nB()?P0t():!1}async function C3e(){if(nB()){try{let e=await I3e();await tB(e,["delete-key"],{timeout:1e4})}catch{}return}if(await ih())try{await tB("security",["delete-generic-password","-s",A0t,"-a",S0t],{timeout:5e3})}catch{}try{await T0t(["delete-key"])}catch{}}NA();Dc();JY();X4e();var Yft=require("child_process"),_Y=Ze(require("fs")),vY=Ze(require("os")),Zft=Ze(require("path"));var _m=Ze(require("fs")),SJ=Ze(require("os")),yp=Ze(require("path"));var K5r="# >>> visa-cli shell hud v2 >>>",W5r="# <<< visa-cli shell hud v2 <<<";function G5r(e){let t=e??process.env.SHELL;if(!t)return null;let r=yp.basename(t.replace(/\\/g,"/")).toLowerCase();return r==="zsh"?"zsh":r==="bash"?"bash":r==="pwsh"||r==="pwsh.exe"||r==="powershell"||r==="powershell.exe"?"powershell":null}function J5r(e){let t=evr();if(e==="zsh")return yp.join(t,".zshrc");if(e==="bash")return yp.join(t,".bashrc");let r=(process.platform==="win32","PowerShell");return yp.join(t,"Documents",r,"Microsoft.PowerShell_profile.ps1")}function Y5r(e){return e.includes("_visa_cli_shell_hud_precmd")||e.includes("visa-cli config shell-hud refresh")||e.includes("shell-hud.line")||e.includes("__visa_cli_original_prompt")||e.includes("function global:prompt")}function Z5r(e,t,r){let n=new RegExp(`(^|\\n)([ \\t]*${wdt(t)}[ \\t]*\\r?\\n)([\\s\\S]*?)(\\r?\\n[ \\t]*${wdt(r)}[ \\t]*)(?=\\r?\\n|$)(\\r?\\n)?`,"g");return e.replace(n,(i,o,s,a,c,u,d)=>{if(!Y5r(a))return i;let l=d>0?e[d-1]:"";return o===`
20775
20775
  `&&l!==`
20776
20776
  `?`
20777
- `:""})}function X5r(e){return Z5r(e,K5r,W5r).trimEnd()}function Q5r(e){return X5r(e)!==e.trimEnd()}function TJ(e=G5r()){if(!e)return!1;try{let t=J5r(e),r=_m.readFileSync(t,"utf-8");return Q5r(r)}catch{return!1}}function wdt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function evr(){let e=SJ.homedir();if(!e||!yp.isAbsolute(e))throw new Error("unable to determine a valid home directory");return yp.resolve(e)}var g5n=1440*60*1e3;var tvr="# visa-cli-hud-v1";function xdt(e){return typeof e!="string"?!1:e.includes(tvr)?!0:e.includes("visa-cli")&&e.includes("statusline")}a4();Yk();var Edt="4.1.0-rc.33";function Q4e(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function rvr(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=UY(t);return i!==void 0?{value:i,source:{kind:"settings"}}:{value:r!=="opt-in",source:{kind:"default"}}}function rA(e){return e==null?"\u2014":e?"yes":"no"}async function Adt(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=qY("auth.serverUrl"),s=ju(),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:rA(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=rvr("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");n.push({key:"ui.suppressBrowser",value:c.value,formatted:rA(c.value),source:c.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let u=Lk(),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:rA(!u),source:d}),n.push({key:"client.version",value:Edt,formatted:Edt,source:{kind:"default"}}),e.includeDev){let l=process.env.VISA_MOCK_KEYCHAIN,p=th();n.push({key:"dev.mockKeychain",value:p,formatted:rA(p),source:Q4e("VISA_MOCK_KEYCHAIN",!!l),hint:LY()});let f=process.env.VISA_MOCK_TOUCHID,m=Jk();n.push({key:"dev.mockTouchid",value:m,formatted:rA(m),source:Q4e("VISA_MOCK_TOUCHID",!!f),hint:LY()});let h=process.env.VISA_CLI_DEBUG;n.push({key:"dev.debug",value:!!h,formatted:rA(!!h),source:Q4e("VISA_CLI_DEBUG",!!h)})}return{entries:n,statusError:r}}var g8e=require("node:os"),Ak=require("node:path"),Sk=require("node:fs/promises"),Fpt=require("node:fs"),$pt=require("node:url"),Vpt=require("node:crypto");Dc();var nvr=new Set(["USD","USDC","EUR","GBP","CAD","AUD"]);function ewe(e,t){let r=t.toUpperCase();return!Number.isFinite(e)||!nvr.has(r)?`${e} ${r} (minor units)`:`${(e/100).toFixed(2)} ${r}`}var L1=class extends Error{constructor(t){super(t),this.name="PayValidationError"}};function twe(e){let t;try{t=new URL(e)}catch{throw new L1(`Invalid URL: ${e}. Expected a fully-qualified http(s) URL.`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new L1(`Unsupported URL scheme "${t.protocol}". Only http and https are allowed.`);return t}Dc();var ivr={ucp_checkout_handoff:"checkout_agent_access",pay_merchant:"checkout_agent_access",pay_merchant_status:"checkout_agent_access",start_card_mandate:"checkout_agent_access"},Sdt=300*1e3,rwe={},nwe=0,ak=null;function iwe(){return ak||(ak=(async()=>{try{let e=await Qs.getFeatureFlags();rwe=e&&e.flags||{},nwe=Date.now()}catch(e){rwe={},Be.warn("feature-flags:fetch-failed",{error:e instanceof Error?e.message:String(e)})}finally{ak=null}})(),ak)}async function Tdt(){await iwe()}function Pdt(){Date.now()-nwe<Sdt||iwe()}async function nA(){Date.now()-nwe<Sdt||await iwe()}function vm(e){let t=ivr[e];return t?rwe[t]!==!0:!1}var Idt=require("node:crypto"),ck=class extends Error{constructor(r){super(`Approval handoff already exists with different inputs for review ${r}`);this.reviewId=r;this.name="PayMerchantApprovalConflictError"}reviewId},PJ=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 ck(t.reviewId);return await this.waitUntilQueryable(n.ready),this.snapshot(n)}let i=()=>{},o=new Promise(u=>{i=u}),s=(this.options.idFactory??Idt.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 Kpt(e){return[(0,Ak.join)(e,"checkout-engine","index.js"),(0,Ak.join)(e,"..","checkout-engine","index.js")]}function i8r(e,t=Fpt.existsSync){return Kpt(e).find(r=>t(r))??null}var nY=null,Wpt=async()=>{if(nY)return nY;let e=i8r(__dirname);if(!e)throw new Error(`Cannot find module: the checkout engine was not packaged (looked in ${Kpt(__dirname).join(" and ")}).`);return nY=(await import((0,$pt.pathToFileURL)(e).href)).createCliCheckoutEngine({cardDrawVerdict:await o8r(),cardMandateRegister:await s8r()}),nY};async function o8r(){let e=await Promise.resolve().then(()=>(h8e(),m8e));return{loadCapability:()=>e.loadCardMandateCapability(),fetchVerdict:t=>e.fetchCardDrawVerdict(t)}}async function s8r(){let e=await Promise.resolve().then(()=>(h8e(),m8e));return{loadCapability:()=>e.loadCardMandateCapability(),register:t=>e.registerCardMandate(t)}}async function b8e(){return vm("pay_merchant")?(await nA(),vm("pay_merchant")):!1}var Gpt=(0,Ak.join)((0,g8e.homedir)(),".visa-mcp","agent-credential.json"),Jpt=(0,Ak.join)((0,g8e.homedir)(),".visa-mcp","contact.json"),Ypt=new PJ;function Tk(e){return e.replace(/https?:\/\/[^\s"')\]]+/gi,t=>{try{return new URL(t).origin}catch{return"[url]"}}).slice(0,300)}var a8r=new Set(["USD","USDC","EUR","GBP","CAD","AUD"]);function Zpt(e){return a8r.has(e)?e:null}async function iY(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,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?Tk(e.errorMessage):null,result_json:JSON.stringify({outcome:e.outcome,confirmationRef:e.confirmationRef??null,source:e.source??null,remainingMinor:e.remainingMinor??null}),payment_rail:e.action==="pay"?"card":null,payment_amount:e.action==="pay"?e.amountMinor:null,payment_currency:Zpt(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){Be.warn("pay_merchant:telemetry_failed",{action:e.action,error:t instanceof Error?t.message:String(t)})}}async function Hpt(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?Tk(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:Zpt(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){Be.warn("start_card_mandate:telemetry_failed",{error:t instanceof Error?t.message:String(t)})}}function y8e(e){if(typeof e!="string"||!/^\d+(\.\d{1,2})?$/.test(e)||Number(e)<=0)throw new L1(`Invalid amount ${JSON.stringify(e)}. Expected a positive decimal like "5.00".`);return e}function Xpt(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=Tk(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 Qpt(e={},t={}){if(await(t.flagDisabled??b8e)())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??Ypt).get(n);return o?Xpt(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 eft(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:MY()&&!process.env.VISA_VERIFY_WEB_URL?null:rl();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??b8e)())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??Ypt,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=twe(e.url??"").toString(),c=y8e(e.amount)}catch(C){if(C instanceof L1)return{success:!1,message:C.message};throw C}let d=t.credentialPath??Gpt,l=t.contactPath??Jpt;try{await(0,Sk.readFile)(d,"utf8")}catch{return{success:!1,message:"No enrolled agent credential on this device \u2014 run enroll_agent (start -> claim) first, then retry pay_merchant."}}let p;try{p=JSON.parse(await(0,Sk.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 C=typeof e.confirm=="string"?e.confirm.trim():"",I=/^PAY (\S+)$/.exec(C);if(!I)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=I[1]}let m=t.loadEngine??Wpt,h;try{h=await m()}catch(C){let I=C instanceof Error?C.message:String(C);if(/ERR_MODULE_NOT_FOUND|Cannot find (module|package)/.test(I))return{success:!1,message:/checkout engine was not packaged/.test(I)?"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 C}let y={url:a,amount:c,currency:u,credentialPath:d,contact:p,approvalBaseUrl:n},w=t.emitTelemetry??(C=>Qs.emitTelemetry(C)),x=new URL(a).hostname,_=Math.round(Number(c)*100),v=Date.now();if(o==="review"){Be.info("pay_merchant:review",{host:x,currency:u});let C;try{C=await h.review(y)}catch(I){throw await iY({emitTelemetry:w,action:"review",merchantHost:x,amountMinor:_,currency:u,outcome:"engine-error",success:!1,errorMessage:I instanceof Error?I.message:String(I),startedAt:v}),I}return await iY({emitTelemetry:w,action:"review",merchantHost:x,amountMinor:_,currency:u,outcome:"reviewed",success:!0,startedAt:v}),{success:!0,action:"review",...C,message:`Review ${C.reviewId}: ${C.merchantHost} wants ${ewe(C.amountMinor,C.currency)}. For a messaging handoff, call pay_merchant { action: "authorize", url, amount, confirm: "PAY ${C.reviewId}" }; for a blocking terminal flow use action "pay". No charge yet.`}}let E=f,A=t.allowSubmit??process.env.CHECKOUT_AGENT_ALLOW_SUBMIT==="1",S=async C=>{Be.info("pay_merchant:pay",{reviewId:E,submit:A,approvalMode:o==="authorize"?"handoff":"blocking"});let I;try{I=await h.pay({...y,reviewId:E,submit:A,...C?{onApprovalUrl:C}:{}})}catch(j){throw await iY({emitTelemetry:w,action:"pay",merchantHost:x,amountMinor:_,currency:u,outcome:"engine-error",success:!1,errorMessage:j instanceof Error?j.message:String(j),startedAt:v,submit:A}),j}let R=I.outcome==="confirmed"||I.outcome==="filled-dry-run";await iY({emitTelemetry:w,action:"pay",merchantHost:x,amountMinor:_,currency:u,outcome:I.outcome,confirmationRef:I.confirmationRef,success:R,errorMessage:R?null:I.detail??I.outcome,startedAt:v,submit:A,source:I.source??null,remainingMinor:I.remainingMinor??null,drawId:I.source==="mandate"?E:null});let U=I.source==="mandate"?` Drawn tap-free from an active card mandate${typeof I.remainingMinor=="number"?` (${I.remainingMinor} ${u} minor units remaining)`:""}.`:I.source==="fresh-tap"?" Paid with a fresh per-purchase passkey.":"";return{success:R,action:"pay",reviewId:E,...I,message:I.outcome==="confirmed"?`Paid. Confirmation ${I.confirmationRef??"(none captured)"} \xB7 receipt ${I.receiptPath??"(not written)"}.${U}`:`Outcome: ${I.outcome}${I.detail?` \u2014 ${I.detail}`:""}. Do not retry blindly \u2014 verify with the merchant before any re-run.`}};if(o==="authorize"){let C=(0,Vpt.createHash)("sha256").update(JSON.stringify([E,a,c,u,A])).digest("hex");Be.info("pay_merchant:approval_handoff_started",{reviewId:E,merchantHost:x,currency:u,submit:A});try{let I=await s.start({reviewId:E,fingerprint:C,run:async R=>{try{let U=await S(j=>{Be.info("pay_merchant:approval_handoff_ready",{reviewId:E}),R(j)});return Be.info("pay_merchant:approval_handoff_completed",{reviewId:E,success:U.success===!0}),U}catch(U){throw Be.warn("pay_merchant:approval_handoff_failed",{reviewId:E,error:Tk(U instanceof Error?U.message:String(U))}),U}}});return Xpt(I,"authorize")}catch(I){if(I instanceof ck)return Be.warn("pay_merchant:approval_handoff_conflict",{reviewId:E}),{success:!1,action:"authorize",reviewId:E,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 I}}return S()}async function tft(e={},t={}){let r=(e.rail??"card").toLowerCase();if(r!=="card")return{success:!1,message:`start_card_mandate only supports the "card" rail (got ${JSON.stringify(r)}). For x402/stablecoin payments, use wallet_policy_set and wallet_pay.`};let n=t.verifyUrl!==void 0?t.verifyUrl:rl();if(n===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??b8e)())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 o=(e.currency??"USD").toUpperCase();if(!/^[A-Z]{3}$/.test(o))return{success:!1,message:`Invalid currency ${JSON.stringify(e.currency)}. Expected a 3-letter ISO code like "USD".`};let s=e.anyMerchant===!0,a,c;try{a=s?void 0:twe(e.url??"").toString(),c=y8e(e.ceiling??e.amount)}catch(A){if(A instanceof L1)return{success:!1,message:A.message};throw A}if(e.expiresAt!==void 0){let A=Date.parse(e.expiresAt);if(!Number.isFinite(A)||A<=Date.now())return{success:!1,message:`Invalid expiresAt ${JSON.stringify(e.expiresAt)}. Expected a future ISO 8601 timestamp.`}}if(e.maxDraws!==void 0&&(!Number.isSafeInteger(e.maxDraws)||e.maxDraws<1))return{success:!1,message:"maxDraws must be a positive integer."};let u;if(e.perTransaction!==void 0){try{u=y8e(e.perTransaction)}catch(A){if(A instanceof L1)return{success:!1,message:A.message};throw A}if(Number(u)>Number(c))return{success:!1,message:"perTransaction cannot exceed the ceiling."}}let d;if(e.intent!==void 0){if(typeof e.intent!="string")return{success:!1,message:"intent must be a short string."};let A=e.intent.replace(/[\p{Cc}\u2028\u2029]/gu,"").trim().slice(0,200).trim();d=A.length>0?A:void 0}let l=t.credentialPath??Gpt,p=t.contactPath??Jpt;try{await(0,Sk.readFile)(l,"utf8")}catch{return{success:!1,message:"No enrolled agent credential on this device \u2014 run enroll_agent (start -> claim) first, then retry start_card_mandate."}}let f;try{f=JSON.parse(await(0,Sk.readFile)(p,"utf8"))}catch{return{success:!1,message:`No contact details at ${p}. Write your name/email/address there (chmod 600) first.`}}let m=t.loadEngine??Wpt,h;try{h=await m()}catch(A){let S=A instanceof Error?A.message:String(A);if(/ERR_MODULE_NOT_FOUND|Cannot find (module|package)/.test(S))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 A}let y=s?"any-merchant":new URL(a).hostname,w=Math.round(Number(c)*100),x=t.emitTelemetry??(A=>Qs.emitTelemetry(A)),_=Date.now();Be.info("start_card_mandate:create",{host:y,currency:o});let v;try{v=await h.startCardMandate({...a?{url:a}:{},ceiling:c,currency:o,credentialPath:l,contact:f,approvalBaseUrl:n,...s?{anyMerchant:!0}:{},...e.merchantName?{merchantName:e.merchantName}:{},...e.expiresAt?{expiresAt:e.expiresAt}:{},...e.maxDraws!==void 0?{maxDraws:e.maxDraws}:{},...u!==void 0?{perTransaction:u}:{},...d!==void 0?{intent:d}:{}})}catch(A){let S=A instanceof Error?Tk(A.message):String(A);return Be.warn("start_card_mandate:failed",{message:S}),await Hpt({emitTelemetry:x,merchantHost:y,ceilingMinor:w,currency:o,outcome:"engine-error",success:!1,errorMessage:A instanceof Error?A.message:String(A),startedAt:_}),{success:!1,message:`Could not create the mandate: ${S}`}}let E=v.registerFailed===!0;return E&&Be.warn("start_card_mandate:register_failed",{mandateId:v.mandateId,host:y}),await Hpt({emitTelemetry:x,merchantHost:y,ceilingMinor:w,currency:o,outcome:E?"created-register-failed":"created",success:!E,mandateId:v.mandateId,remainingMinor:v.remainingMinor,startedAt:_}),E?{success:!1,mandateId:v.mandateId,ceiling:c,remainingMinor:v.remainingMinor,currency:v.currencyCode,merchant:v.merchant,merchantHost:v.merchantHost,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:c,remainingMinor:v.remainingMinor,currency:v.currencyCode,merchant:v.merchant,merchantHost:v.merchantHost,expiresAt:v.expiresAt,message:`Mandate ${v.mandateId} active: up to ${ewe(w,v.currencyCode)} at ${v.merchantHost} until ${v.expiresAt}. pay_merchant will now draw against it tap-free (no fresh passkey) until the budget is spent or it expires. NOTE: honoring a ceiling-scoped assurance across multiple draws is unproven live \u2014 if the network declines a draw, the budget is left untouched and that mandate is disabled, so your next pay_merchant uses a fresh per-purchase tap (it does NOT fall back within the same call).`}}var Wft=require("node:crypto");var Fft=require("node:crypto");var jr={};Gi(jr,{BRAND:()=>B8r,DIRTY:()=>Dv,EMPTY_PATH:()=>l8r,INVALID:()=>ht,NEVER:()=>u3r,OK:()=>ia,ParseStatus:()=>ws,Schema:()=>Ut,ZodAny:()=>i2,ZodArray:()=>Z1,ZodBigInt:()=>Lv,ZodBoolean:()=>Hv,ZodBranded:()=>Ik,ZodCatch:()=>Qv,ZodDate:()=>Fv,ZodDefault:()=>Xv,ZodDiscriminatedUnion:()=>aY,ZodEffects:()=>Yd,ZodEnum:()=>Yv,ZodError:()=>Uc,ZodFirstPartyTypeKind:()=>wt,ZodFunction:()=>uY,ZodIntersection:()=>Wv,ZodIssueCode:()=>ye,ZodLazy:()=>Gv,ZodLiteral:()=>Jv,ZodMap:()=>bA,ZodNaN:()=>vA,ZodNativeEnum:()=>Zv,ZodNever:()=>bp,ZodNull:()=>Vv,ZodNullable:()=>Pm,ZodNumber:()=>zv,ZodObject:()=>Mc,ZodOptional:()=>Gd,ZodParsedType:()=>Ce,ZodPipeline:()=>Ok,ZodPromise:()=>o2,ZodReadonly:()=>e4,ZodRecord:()=>cY,ZodSchema:()=>Ut,ZodSet:()=>_A,ZodString:()=>n2,ZodSymbol:()=>yA,ZodTransformer:()=>Yd,ZodTuple:()=>Tm,ZodType:()=>Ut,ZodUndefined:()=>$v,ZodUnion:()=>Kv,ZodUnknown:()=>Y1,ZodVoid:()=>gA,addIssueToContext:()=>Ae,any:()=>Xd,array:()=>ue,bigint:()=>U8r,boolean:()=>Zd,coerce:()=>Nu,custom:()=>uft,date:()=>M8r,datetimeRegex:()=>aft,defaultErrorMap:()=>G1,discriminatedUnion:()=>V8r,effect:()=>t3r,enum:()=>Qd,function:()=>Y8r,getErrorMap:()=>fA,getParsedType:()=>Sm,instanceof:()=>j8r,intersection:()=>K8r,isAborted:()=>oY,isAsync:()=>mA,isDirty:()=>sY,isValid:()=>r2,late:()=>N8r,lazy:()=>Z8r,literal:()=>X8r,makeIssue:()=>Pk,map:()=>G8r,nan:()=>q8r,nativeEnum:()=>Q8r,never:()=>H8r,null:()=>wA,nullable:()=>n3r,number:()=>Ir,object:()=>fe,objectUtil:()=>_8e,oboolean:()=>c3r,onumber:()=>a3r,optional:()=>r3r,ostring:()=>s3r,pipeline:()=>o3r,preprocess:()=>i3r,promise:()=>e3r,quotelessJson:()=>c8r,record:()=>Zt,set:()=>J8r,setErrorMap:()=>d8r,strictObject:()=>$8r,string:()=>z,symbol:()=>D8r,transformer:()=>t3r,tuple:()=>W8r,undefined:()=>z8r,union:()=>xA,unknown:()=>L8r,util:()=>Yt,void:()=>F8r});var Yt;(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})(Yt||(Yt={}));var _8e;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(_8e||(_8e={}));var Ce=Yt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Sm=e=>{switch(typeof e){case"undefined":return Ce.undefined;case"string":return Ce.string;case"number":return Number.isNaN(e)?Ce.nan:Ce.number;case"boolean":return Ce.boolean;case"function":return Ce.function;case"bigint":return Ce.bigint;case"symbol":return Ce.symbol;case"object":return Array.isArray(e)?Ce.array:e===null?Ce.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?Ce.promise:typeof Map<"u"&&e instanceof Map?Ce.map:typeof Set<"u"&&e instanceof Set?Ce.set:typeof Date<"u"&&e instanceof Date?Ce.date:Ce.object;default:return Ce.unknown}};var ye=Yt.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"]),c8r=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,Yt.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 u8r=(e,t)=>{let r;switch(e.code){case ye.invalid_type:e.received===Ce.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case ye.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,Yt.jsonStringifyReplacer)}`;break;case ye.unrecognized_keys:r=`Unrecognized key(s) in object: ${Yt.joinValues(e.keys,", ")}`;break;case ye.invalid_union:r="Invalid input";break;case ye.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Yt.joinValues(e.options)}`;break;case ye.invalid_enum_value:r=`Invalid enum value. Expected ${Yt.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}"`:Yt.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,Yt.assertNever(e)}return{message:r}},G1=u8r;var rft=G1;function d8r(e){rft=e}function fA(){return rft}var Pk=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}},l8r=[];function Ae(e,t){let r=fA(),n=Pk({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===G1?void 0:G1].filter(i=>!!i)});e.common.issues.push(n)}var ws=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 ht;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 ht;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}}},ht=Object.freeze({status:"aborted"}),Dv=e=>({status:"dirty",value:e}),ia=e=>({status:"valid",value:e}),oY=e=>e.status==="aborted",sY=e=>e.status==="dirty",r2=e=>e.status==="valid",mA=e=>typeof Promise<"u"&&e instanceof Promise;var Qe;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(Qe||(Qe={}));var Jd=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}},nft=(e,t)=>{if(r2(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 Bt(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 Ut=class{get description(){return this._def.description}_getType(t){return Sm(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:Sm(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ws,ctx:{common:t.parent.common,data:t.data,parsedType:Sm(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(mA(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:Sm(t)},i=this._parseSync({data:t,path:n.path,parent:n});return nft(n,i)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Sm(t)};if(!this["~standard"].async)try{let n=this._parseSync({data:t,path:[],parent:r});return r2(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=>r2(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:Sm(t)},i=this._parse({data:t,path:n.path,parent:n}),o=await(mA(i)?i:Promise.resolve(i));return nft(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 Yd({schema:this,typeName:wt.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 Gd.create(this,this._def)}nullable(){return Pm.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Z1.create(this)}promise(){return o2.create(this,this._def)}or(t){return Kv.create([this,t],this._def)}and(t){return Wv.create(this,t,this._def)}transform(t){return new Yd({...Bt(this._def),schema:this,typeName:wt.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new Xv({...Bt(this._def),innerType:this,defaultValue:r,typeName:wt.ZodDefault})}brand(){return new Ik({typeName:wt.ZodBranded,type:this,...Bt(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new Qv({...Bt(this._def),innerType:this,catchValue:r,typeName:wt.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return Ok.create(this,t)}readonly(){return e4.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},p8r=/^c[^\s-]{8,}$/i,f8r=/^[0-9a-z]+$/,m8r=/^[0-9A-HJKMNP-TV-Z]{26}$/i,h8r=/^[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,y8r=/^[a-z0-9_-]{21}$/i,g8r=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,b8r=/^[-+]?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)?)??$/,_8r=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,v8r="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",v8e,w8r=/^(?:(?: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])$/,x8r=/^(?:(?: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])$/,E8r=/^(([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]))$/,A8r=/^(([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])$/,S8r=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,T8r=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,oft="((\\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])))",P8r=new RegExp(`^${oft}$`);function sft(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 I8r(e){return new RegExp(`^${sft(e)}$`)}function aft(e){let t=`${oft}T${sft(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 O8r(e,t){return!!((t==="v4"||!t)&&w8r.test(e)||(t==="v6"||!t)&&E8r.test(e))}function C8r(e,t){if(!g8r.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 R8r(e,t){return!!((t==="v4"||!t)&&x8r.test(e)||(t==="v6"||!t)&&A8r.test(e))}var n2=class e extends Ut{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==Ce.string){let o=this._getOrReturnCtx(t);return Ae(o,{code:ye.invalid_type,expected:Ce.string,received:o.parsedType}),ht}let n=new ws,i;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(i=this._getOrReturnCtx(t,i),Ae(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),Ae(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?Ae(i,{code:ye.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&Ae(i,{code:ye.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")_8r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"email",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")v8e||(v8e=new RegExp(v8r,"u")),v8e.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"emoji",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")h8r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"uuid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")y8r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"nanoid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")p8r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"cuid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")f8r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"cuid2",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")m8r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(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),Ae(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),Ae(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),Ae(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),Ae(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),Ae(i,{code:ye.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?aft(o).test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{code:ye.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?P8r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{code:ye.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?I8r(o).test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{code:ye.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?b8r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"duration",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?O8r(t.data,o.version)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"ip",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?C8r(t.data,o.alg)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"jwt",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?R8r(t.data,o.version)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"cidr",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?S8r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"base64",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?T8r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"base64url",code:ye.invalid_string,message:o.message}),n.dirty()):Yt.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,...Qe.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...Qe.errToObj(t)})}url(t){return this._addCheck({kind:"url",...Qe.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...Qe.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...Qe.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...Qe.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...Qe.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...Qe.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...Qe.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...Qe.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...Qe.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...Qe.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...Qe.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...Qe.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,...Qe.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,...Qe.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...Qe.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...Qe.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...Qe.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...Qe.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...Qe.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...Qe.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...Qe.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...Qe.errToObj(r)})}nonempty(t){return this.min(1,Qe.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}};n2.create=e=>new n2({checks:[],typeName:wt.ZodString,coerce:e?.coerce??!1,...Bt(e)});function k8r(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 zv=class e extends Ut{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)!==Ce.number){let o=this._getOrReturnCtx(t);return Ae(o,{code:ye.invalid_type,expected:Ce.number,received:o.parsedType}),ht}let n,i=new ws;for(let o of this._def.checks)o.kind==="int"?Yt.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),Ae(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),Ae(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),Ae(n,{code:ye.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?k8r(t.data,o.value)!==0&&(n=this._getOrReturnCtx(t,n),Ae(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),Ae(n,{code:ye.not_finite,message:o.message}),i.dirty()):Yt.assertNever(o);return{status:i.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,Qe.toString(r))}gt(t,r){return this.setLimit("min",t,!1,Qe.toString(r))}lte(t,r){return this.setLimit("max",t,!0,Qe.toString(r))}lt(t,r){return this.setLimit("max",t,!1,Qe.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:Qe.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:Qe.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Qe.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Qe.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Qe.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Qe.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:Qe.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:Qe.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Qe.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Qe.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"&&Yt.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)}};zv.create=e=>new zv({checks:[],typeName:wt.ZodNumber,coerce:e?.coerce||!1,...Bt(e)});var Lv=class e extends Ut{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)!==Ce.bigint)return this._getInvalidInput(t);let n,i=new ws;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),Ae(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),Ae(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),Ae(n,{code:ye.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):Yt.assertNever(o);return{status:i.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return Ae(r,{code:ye.invalid_type,expected:Ce.bigint,received:r.parsedType}),ht}gte(t,r){return this.setLimit("min",t,!0,Qe.toString(r))}gt(t,r){return this.setLimit("min",t,!1,Qe.toString(r))}lte(t,r){return this.setLimit("max",t,!0,Qe.toString(r))}lt(t,r){return this.setLimit("max",t,!1,Qe.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:Qe.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:Qe.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Qe.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Qe.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Qe.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:Qe.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}};Lv.create=e=>new Lv({checks:[],typeName:wt.ZodBigInt,coerce:e?.coerce??!1,...Bt(e)});var Hv=class extends Ut{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==Ce.boolean){let n=this._getOrReturnCtx(t);return Ae(n,{code:ye.invalid_type,expected:Ce.boolean,received:n.parsedType}),ht}return ia(t.data)}};Hv.create=e=>new Hv({typeName:wt.ZodBoolean,coerce:e?.coerce||!1,...Bt(e)});var Fv=class e extends Ut{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==Ce.date){let o=this._getOrReturnCtx(t);return Ae(o,{code:ye.invalid_type,expected:Ce.date,received:o.parsedType}),ht}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return Ae(o,{code:ye.invalid_date}),ht}let n=new ws,i;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(i=this._getOrReturnCtx(t,i),Ae(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),Ae(i,{code:ye.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):Yt.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:Qe.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:Qe.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}};Fv.create=e=>new Fv({checks:[],coerce:e?.coerce||!1,typeName:wt.ZodDate,...Bt(e)});var yA=class extends Ut{_parse(t){if(this._getType(t)!==Ce.symbol){let n=this._getOrReturnCtx(t);return Ae(n,{code:ye.invalid_type,expected:Ce.symbol,received:n.parsedType}),ht}return ia(t.data)}};yA.create=e=>new yA({typeName:wt.ZodSymbol,...Bt(e)});var $v=class extends Ut{_parse(t){if(this._getType(t)!==Ce.undefined){let n=this._getOrReturnCtx(t);return Ae(n,{code:ye.invalid_type,expected:Ce.undefined,received:n.parsedType}),ht}return ia(t.data)}};$v.create=e=>new $v({typeName:wt.ZodUndefined,...Bt(e)});var Vv=class extends Ut{_parse(t){if(this._getType(t)!==Ce.null){let n=this._getOrReturnCtx(t);return Ae(n,{code:ye.invalid_type,expected:Ce.null,received:n.parsedType}),ht}return ia(t.data)}};Vv.create=e=>new Vv({typeName:wt.ZodNull,...Bt(e)});var i2=class extends Ut{constructor(){super(...arguments),this._any=!0}_parse(t){return ia(t.data)}};i2.create=e=>new i2({typeName:wt.ZodAny,...Bt(e)});var Y1=class extends Ut{constructor(){super(...arguments),this._unknown=!0}_parse(t){return ia(t.data)}};Y1.create=e=>new Y1({typeName:wt.ZodUnknown,...Bt(e)});var bp=class extends Ut{_parse(t){let r=this._getOrReturnCtx(t);return Ae(r,{code:ye.invalid_type,expected:Ce.never,received:r.parsedType}),ht}};bp.create=e=>new bp({typeName:wt.ZodNever,...Bt(e)});var gA=class extends Ut{_parse(t){if(this._getType(t)!==Ce.undefined){let n=this._getOrReturnCtx(t);return Ae(n,{code:ye.invalid_type,expected:Ce.void,received:n.parsedType}),ht}return ia(t.data)}};gA.create=e=>new gA({typeName:wt.ZodVoid,...Bt(e)});var Z1=class e extends Ut{_parse(t){let{ctx:r,status:n}=this._processInputParams(t),i=this._def;if(r.parsedType!==Ce.array)return Ae(r,{code:ye.invalid_type,expected:Ce.array,received:r.parsedType}),ht;if(i.exactLength!==null){let s=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(s||a)&&(Ae(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&&(Ae(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&&(Ae(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 Jd(r,s,r.path,a)))).then(s=>ws.mergeArray(n,s));let o=[...r.data].map((s,a)=>i.type._parseSync(new Jd(r,s,r.path,a)));return ws.mergeArray(n,o)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:Qe.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:Qe.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:Qe.toString(r)}})}nonempty(t){return this.min(1,t)}};Z1.create=(e,t)=>new Z1({type:e,minLength:null,maxLength:null,exactLength:null,typeName:wt.ZodArray,...Bt(t)});function hA(e){if(e instanceof Mc){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=Gd.create(hA(n))}return new Mc({...e._def,shape:()=>t})}else return e instanceof Z1?new Z1({...e._def,type:hA(e.element)}):e instanceof Gd?Gd.create(hA(e.unwrap())):e instanceof Pm?Pm.create(hA(e.unwrap())):e instanceof Tm?Tm.create(e.items.map(t=>hA(t))):e}var Mc=class e extends Ut{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=Yt.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==Ce.object){let u=this._getOrReturnCtx(t);return Ae(u,{code:ye.invalid_type,expected:Ce.object,received:u.parsedType}),ht}let{status:n,ctx:i}=this._processInputParams(t),{shape:o,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof bp&&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 Jd(i,l,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof bp){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&&(Ae(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 Jd(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=>ws.mergeObjectSync(n,u)):ws.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(t){return Qe.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:Qe.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:wt.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 Yt.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 Yt.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}deepPartial(){return hA(this)}partial(t){let r={};for(let n of Yt.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 Yt.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof Gd;)o=o._def.innerType;r[n]=o}return new e({...this._def,shape:()=>r})}keyof(){return cft(Yt.objectKeys(this.shape))}};Mc.create=(e,t)=>new Mc({shape:()=>e,unknownKeys:"strip",catchall:bp.create(),typeName:wt.ZodObject,...Bt(t)});Mc.strictCreate=(e,t)=>new Mc({shape:()=>e,unknownKeys:"strict",catchall:bp.create(),typeName:wt.ZodObject,...Bt(t)});Mc.lazycreate=(e,t)=>new Mc({shape:e,unknownKeys:"strip",catchall:bp.create(),typeName:wt.ZodObject,...Bt(t)});var Kv=class extends Ut{_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 Ae(r,{code:ye.invalid_union,unionErrors:s}),ht}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 Ae(r,{code:ye.invalid_union,unionErrors:a}),ht}}get options(){return this._def.options}};Kv.create=(e,t)=>new Kv({options:e,typeName:wt.ZodUnion,...Bt(t)});var J1=e=>e instanceof Gv?J1(e.schema):e instanceof Yd?J1(e.innerType()):e instanceof Jv?[e.value]:e instanceof Yv?e.options:e instanceof Zv?Yt.objectValues(e.enum):e instanceof Xv?J1(e._def.innerType):e instanceof $v?[void 0]:e instanceof Vv?[null]:e instanceof Gd?[void 0,...J1(e.unwrap())]:e instanceof Pm?[null,...J1(e.unwrap())]:e instanceof Ik||e instanceof e4?J1(e.unwrap()):e instanceof Qv?J1(e._def.innerType):[],aY=class e extends Ut{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Ce.object)return Ae(r,{code:ye.invalid_type,expected:Ce.object,received:r.parsedType}),ht;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}):(Ae(r,{code:ye.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),ht)}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=J1(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:wt.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:i,...Bt(n)})}};function w8e(e,t){let r=Sm(e),n=Sm(t);if(e===t)return{valid:!0,data:e};if(r===Ce.object&&n===Ce.object){let i=Yt.objectKeys(t),o=Yt.objectKeys(e).filter(a=>i.indexOf(a)!==-1),s={...e,...t};for(let a of o){let c=w8e(e[a],t[a]);if(!c.valid)return{valid:!1};s[a]=c.data}return{valid:!0,data:s}}else if(r===Ce.array&&n===Ce.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=w8e(s,a);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else return r===Ce.date&&n===Ce.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var Wv=class extends Ut{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=(o,s)=>{if(oY(o)||oY(s))return ht;let a=w8e(o.value,s.value);return a.valid?((sY(o)||sY(s))&&r.dirty(),{status:r.value,value:a.data}):(Ae(n,{code:ye.invalid_intersection_types}),ht)};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}))}};Wv.create=(e,t,r)=>new Wv({left:e,right:t,typeName:wt.ZodIntersection,...Bt(r)});var Tm=class e extends Ut{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Ce.array)return Ae(n,{code:ye.invalid_type,expected:Ce.array,received:n.parsedType}),ht;if(n.data.length<this._def.items.length)return Ae(n,{code:ye.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ht;!this._def.rest&&n.data.length>this._def.items.length&&(Ae(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 Jd(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>ws.mergeArray(r,s)):ws.mergeArray(r,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Tm.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Tm({items:e,typeName:wt.ZodTuple,rest:null,...Bt(t)})};var cY=class e extends Ut{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!==Ce.object)return Ae(n,{code:ye.invalid_type,expected:Ce.object,received:n.parsedType}),ht;let i=[],o=this._def.keyType,s=this._def.valueType;for(let a in n.data)i.push({key:o._parse(new Jd(n,a,n.path,a)),value:s._parse(new Jd(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?ws.mergeObjectAsync(r,i):ws.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof Ut?new e({keyType:t,valueType:r,typeName:wt.ZodRecord,...Bt(n)}):new e({keyType:n2.create(),valueType:t,typeName:wt.ZodRecord,...Bt(r)})}},bA=class extends Ut{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!==Ce.map)return Ae(n,{code:ye.invalid_type,expected:Ce.map,received:n.parsedType}),ht;let i=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([a,c],u)=>({key:i._parse(new Jd(n,a,n.path,[u,"key"])),value:o._parse(new Jd(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 ht;(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 ht;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}}}};bA.create=(e,t,r)=>new bA({valueType:t,keyType:e,typeName:wt.ZodMap,...Bt(r)});var _A=class e extends Ut{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Ce.set)return Ae(n,{code:ye.invalid_type,expected:Ce.set,received:n.parsedType}),ht;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(Ae(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&&(Ae(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 ht;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 Jd(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:Qe.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:Qe.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};_A.create=(e,t)=>new _A({valueType:e,minSize:null,maxSize:null,typeName:wt.ZodSet,...Bt(t)});var uY=class e extends Ut{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Ce.function)return Ae(r,{code:ye.invalid_type,expected:Ce.function,received:r.parsedType}),ht;function n(a,c){return Pk({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,fA(),G1].filter(u=>!!u),issueData:{code:ye.invalid_arguments,argumentsError:c}})}function i(a,c){return Pk({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,fA(),G1].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 o2){let a=this;return ia(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 ia(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:Tm.create(t).rest(Y1.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||Tm.create([]).rest(Y1.create()),returns:r||Y1.create(),typeName:wt.ZodFunction,...Bt(n)})}},Gv=class extends Ut{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})}};Gv.create=(e,t)=>new Gv({getter:e,typeName:wt.ZodLazy,...Bt(t)});var Jv=class extends Ut{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return Ae(r,{received:r.data,code:ye.invalid_literal,expected:this._def.value}),ht}return{status:"valid",value:t.data}}get value(){return this._def.value}};Jv.create=(e,t)=>new Jv({value:e,typeName:wt.ZodLiteral,...Bt(t)});function cft(e,t){return new Yv({values:e,typeName:wt.ZodEnum,...Bt(t)})}var Yv=class e extends Ut{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return Ae(r,{expected:Yt.joinValues(n),received:r.parsedType,code:ye.invalid_type}),ht}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 Ae(r,{received:r.data,code:ye.invalid_enum_value,options:n}),ht}return ia(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})}};Yv.create=cft;var Zv=class extends Ut{_parse(t){let r=Yt.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==Ce.string&&n.parsedType!==Ce.number){let i=Yt.objectValues(r);return Ae(n,{expected:Yt.joinValues(i),received:n.parsedType,code:ye.invalid_type}),ht}if(this._cache||(this._cache=new Set(Yt.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=Yt.objectValues(r);return Ae(n,{received:n.data,code:ye.invalid_enum_value,options:i}),ht}return ia(t.data)}get enum(){return this._def.values}};Zv.create=(e,t)=>new Zv({values:e,typeName:wt.ZodNativeEnum,...Bt(t)});var o2=class extends Ut{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Ce.promise&&r.common.async===!1)return Ae(r,{code:ye.invalid_type,expected:Ce.promise,received:r.parsedType}),ht;let n=r.parsedType===Ce.promise?r.data:Promise.resolve(r.data);return ia(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};o2.create=(e,t)=>new o2({type:e,typeName:wt.ZodPromise,...Bt(t)});var Yd=class extends Ut{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===wt.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=>{Ae(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 ht;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?ht:c.status==="dirty"?Dv(c.value):r.value==="dirty"?Dv(c.value):c});{if(r.value==="aborted")return ht;let a=this._def.schema._parseSync({data:s,path:n.path,parent:n});return a.status==="aborted"?ht:a.status==="dirty"?Dv(a.value):r.value==="dirty"?Dv(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"?ht:(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"?ht:(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(!r2(s))return ht;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=>r2(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:r.value,value:a})):ht);Yt.assertNever(i)}};Yd.create=(e,t,r)=>new Yd({schema:e,typeName:wt.ZodEffects,effect:t,...Bt(r)});Yd.createWithPreprocess=(e,t,r)=>new Yd({schema:t,effect:{type:"preprocess",transform:e},typeName:wt.ZodEffects,...Bt(r)});var Gd=class extends Ut{_parse(t){return this._getType(t)===Ce.undefined?ia(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Gd.create=(e,t)=>new Gd({innerType:e,typeName:wt.ZodOptional,...Bt(t)});var Pm=class extends Ut{_parse(t){return this._getType(t)===Ce.null?ia(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Pm.create=(e,t)=>new Pm({innerType:e,typeName:wt.ZodNullable,...Bt(t)});var Xv=class extends Ut{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return r.parsedType===Ce.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Xv.create=(e,t)=>new Xv({innerType:e,typeName:wt.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Bt(t)});var Qv=class extends Ut{_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 mA(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}};Qv.create=(e,t)=>new Qv({innerType:e,typeName:wt.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Bt(t)});var vA=class extends Ut{_parse(t){if(this._getType(t)!==Ce.nan){let n=this._getOrReturnCtx(t);return Ae(n,{code:ye.invalid_type,expected:Ce.nan,received:n.parsedType}),ht}return{status:"valid",value:t.data}}};vA.create=e=>new vA({typeName:wt.ZodNaN,...Bt(e)});var B8r=Symbol("zod_brand"),Ik=class extends Ut{_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}},Ok=class e extends Ut{_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"?ht:o.status==="dirty"?(r.dirty(),Dv(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"?ht: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:wt.ZodPipeline})}},e4=class extends Ut{_parse(t){let r=this._def.innerType._parse(t),n=i=>(r2(i)&&(i.value=Object.freeze(i.value)),i);return mA(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};e4.create=(e,t)=>new e4({innerType:e,typeName:wt.ZodReadonly,...Bt(t)});function ift(e,t){let r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function uft(e,t={},r){return e?i2.create().superRefine((n,i)=>{let o=e(n);if(o instanceof Promise)return o.then(s=>{if(!s){let a=ift(t,n),c=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:c})}});if(!o){let s=ift(t,n),a=s.fatal??r??!0;i.addIssue({code:"custom",...s,fatal:a})}}):i2.create()}var N8r={object:Mc.lazycreate},wt;(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"})(wt||(wt={}));var j8r=(e,t={message:`Input not instance of ${e.name}`})=>uft(r=>r instanceof e,t),z=n2.create,Ir=zv.create,q8r=vA.create,U8r=Lv.create,Zd=Hv.create,M8r=Fv.create,D8r=yA.create,z8r=$v.create,wA=Vv.create,Xd=i2.create,L8r=Y1.create,H8r=bp.create,F8r=gA.create,ue=Z1.create,fe=Mc.create,$8r=Mc.strictCreate,xA=Kv.create,V8r=aY.create,K8r=Wv.create,W8r=Tm.create,Zt=cY.create,G8r=bA.create,J8r=_A.create,Y8r=uY.create,Z8r=Gv.create,X8r=Jv.create,Qd=Yv.create,Q8r=Zv.create,e3r=o2.create,t3r=Yd.create,r3r=Gd.create,n3r=Pm.create,i3r=Yd.createWithPreprocess,o3r=Ok.create,s3r=()=>z().optional(),a3r=()=>Ir().optional(),c3r=()=>Zd().optional(),Nu={string:(e=>n2.create({...e,coerce:!0})),number:(e=>zv.create({...e,coerce:!0})),boolean:(e=>Hv.create({...e,coerce:!0})),bigint:(e=>Lv.create({...e,coerce:!0})),date:(e=>Fv.create({...e,coerce:!0}))};var u3r=ht;var l3r=Qd(["enc","sig"]),p3r=Qd(["markdown","plain"]),f3r=Qd(["recoverable","requires_buyer_input","requires_buyer_review","unrecoverable"]),m3r=Qd(["error","info","warning"]),SA=Qd(["canceled","complete_in_progress","completed","incomplete","ready_for_complete","requires_escalation"]),h3r=Qd(["completed","failed","pending"]),y3r=Qd(["digital","pickup","shipping"]),g3r=Qd(["fulfilled","partial","processing","removed"]),b3r=Qd(["across","each"]),x8e=Qd(["pickup","shipping"]),_3r=fe({config:Zt(z(),Xd()),config_schema:z(),id:z(),instrument_schemas:ue(z()),name:z(),spec:z(),version:z()}),v3r=fe({alg:z().optional(),crv:z().optional(),e:z().optional(),kid:z(),kty:z(),n:z().optional(),use:l3r.optional(),x:z().optional(),y:z().optional()}),w3r=fe({config:Zt(z(),Xd()).optional(),extends:z().optional(),name:z(),schema:z(),spec:z(),version:z()}),x3r=fe({endpoint:z()}),E3r=fe({schema:z()}),dft=fe({endpoint:z(),schema:z()}),A3r=dft,S3r=dft,qa=fe({email:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional()}),uo=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()}),E8e=uo,lft=fe({id:z()}),T3r=lft,P3r=lft,Ck=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()}),dY=fe({type:z()}),Ki=fe({"dev.ucp.buyer_ip":z().optional(),"dev.ucp.user_agent":z().optional()}),A8e=Ki,pft=fe({id:z(),image_url:z().optional(),price:Ir(),title:z()}),lY=fe({amount:Ir(),display_text:z().optional(),type:z()}),s2=fe({title:z().optional(),type:z(),url:z()}),X1=fe({code:z().optional(),content:z(),content_type:p3r.optional(),path:z().optional(),severity:f3r.optional(),type:m3r,image_url:z().optional(),presentation:z().optional(),url:z().optional()}),S8e=X1,TA=fe({id:z(),label:z().optional(),permalink_url:z()}),I3r=fe({amount:Ir(),display_text:z()}),O3r=fe({config:Zt(z(),Xd()).optional(),extends:z().optional(),name:z(),schema:z().optional(),spec:z().optional(),version:z()}),T8e=fe({id:z(),quantity:Ir()}),C3r=T8e,R3r=T8e,k3r=T8e,B3r=fe({fulfilled:Ir(),original:Ir().optional(),total:Ir()}),N3r=fe({billing_address:Ck.optional(),credential:dY.optional(),display:Zt(z(),Xd()).optional(),handler_id:z(),id:z(),type:z()}),j3r=fe({checkout_mandate:z()}),q3r=fe({merchant_authorization:z().optional(),checkout_mandate:z()}),U3r=fe({analytics:Zd().optional(),marketing:Zd().optional(),preferences:Zd().optional(),sale_of_data:Zd().optional()});var M3r=U3r;var fft=fe({codes:ue(z()).optional()}),D3r=fft,z3r=fe({amount:Ir(),path:z()}),L3r=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:Ck.optional(),name:z().optional()}),H3r=fe({carrier:z().optional(),description:z().optional(),earliest_fulfillment_time:Nu.date().optional(),id:z(),latest_fulfillment_time:Nu.date().optional(),title:z(),totals:ue(lY)}),F3r=fe({description:z().optional(),fulfillable_on:xA([wA(),z()]).optional(),line_item_ids:ue(z()),type:x8e}),$3r=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:Ck.optional(),name:z().optional()}),V3r=fe({max:Ir().optional(),min:Ir().optional()}),Rk=fe({taxonomy:z().optional(),value:z()}),kk=fe({html:z().optional(),markdown:z().optional(),plain:z().optional()}),EA=fe({amount:Ir(),currency:z()}),Bk=fe({alt_text:z().optional(),height:Ir().optional(),type:z(),url:z(),width:Ir().optional()}),K3r=fe({id:z().optional(),label:z()}),Nk=fe({count:Ir().optional(),scale_max:Ir(),scale_min:Ir().optional(),value:Ir()}),mft=fe({available:Zd().optional(),status:z().optional()}),W3r=mft,hft=fe({type:z(),value:z()}),G3r=hft,J3r=fe({id:z(),match:z().optional()}),P8e=fe({id:z().optional(),label:z(),name:z()}),yft=P8e,gft=fe({links:ue(s2).optional(),name:z().optional()}),Y3r=gft,bft=fe({unit:z(),value:Ir()});var Z3r=bft,X3r=fe({cursor:z().optional(),limit:Ir().optional()}),Q3r=fe({cursor:z().optional(),has_next_page:Zd(),total_count:Ir().optional()}),e9r=fe({handlers:ue(_3r).optional()}),t9r=fe({a2a:x3r.optional(),embedded:E3r.optional(),mcp:A3r.optional(),rest:S3r.optional(),spec:z(),version:z()}),PA=fe({item:T3r,quantity:Ir()}),r9r=fe({billing_address:Ck.optional(),credential:dY.optional(),display:Zt(z(),Xd()).optional(),handler_id:z(),id:z(),type:z(),selected:Zd().optional()}),jk=fe({id:z().optional(),item:P3r,parent_id:z().optional(),quantity:Ir()}),pY=fe({instruments:ue(r9r).optional()}),n9r=pY,qk=pY,IA=pY,fY=pY,t4=fe({id:z(),item:pft,parent_id:z().optional(),quantity:Ir(),totals:ue(lY)}),a2=fe({amount:Ir(),display_text:z().optional(),type:z(),lines:ue(I3r).optional()}),_p=fe({capabilities:Zt(z(),ue(O3r)),version:z()}),i9r=fe({description:z().optional(),id:z(),line_items:ue(C3r).optional(),occurred_at:Nu.date(),status:h3r,totals:ue(lY).optional(),type:z()}),o9r=fe({carrier:z().optional(),description:z().optional(),id:z(),line_items:ue(R3r),occurred_at:Nu.date(),tracking_number:z().optional(),tracking_url:z().optional(),type:z()}),s9r=fe({description:z().optional(),destination:Ck,fulfillable_on:z().optional(),id:z(),line_items:ue(k3r),method_type:y3r}),a9r=fe({id:z(),item:pft,parent_id:z().optional(),quantity:B3r,status:g3r,totals:ue(lY)}),o4n=fe({payment_data:N3r}),s4n=fe({ap2:j3r.optional()}),a4n=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),continue_url:z().optional(),currency:z(),expires_at:Nu.date().optional(),id:z(),line_items:ue(t4),links:ue(s2),messages:ue(X1).optional(),order:TA.optional(),payment:IA.optional(),signals:Ki.optional(),status:SA,totals:ue(a2),ucp:_p,ap2:q3r.optional()}),I8e=fe({email:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional(),consent:M3r.optional()}),c9r=I8e,u9r=I8e,_ft=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),line_items:ue(jk),payment:fY.optional(),signals:Ki.optional(),discounts:D3r.optional()}),d9r=fe({allocations:ue(z3r).optional(),amount:Ir(),automatic:Zd().optional(),code:z().optional(),eligibility:z().optional(),method:b3r.optional(),priority:Ir().optional(),provisional:Zd().optional(),title:z()}),vft=fe({id:z(),line_item_ids:ue(z()),options:ue(H3r).optional(),selected_option_id:xA([wA(),z()]).optional()}),l9r=fe({destinations:ue($3r).optional(),groups:ue(vft).optional(),id:z(),line_item_ids:ue(z()),selected_destination_id:xA([wA(),z()]).optional(),type:x8e}),c4n=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),line_items:ue(PA),signals:Ki.optional()}),u4n=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),id:z(),line_items:ue(jk),signals:Ki.optional()}),d4n=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),continue_url:z().optional(),currency:z(),expires_at:Nu.date().optional(),id:z(),line_items:ue(t4),links:ue(s2).optional(),messages:ue(X1).optional(),signals:Ki.optional(),totals:ue(a2),ucp:_p}),p9r=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),line_items:ue(jk),payment:fY.optional(),signals:Ki.optional()}),wft=p9r,l4n=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),continue_url:z().optional(),currency:z(),expires_at:Nu.date().optional(),id:z(),line_items:ue(t4),links:ue(s2),messages:ue(X1).optional(),order:TA.optional(),payment:IA.optional(),signals:Ki.optional(),status:SA,totals:ue(a2),ucp:_p,cart_id:z().optional()}),O8e=fe({categories:ue(z()).optional(),price:V3r.optional()}),AA=fe({max:EA,min:EA}),C8e=fe({name:z(),values:ue(K3r)}),xft=fe({amount:Ir(),currency:z(),measure:bft,reference:Z3r}),f9r=xft,p4n=fe({attribution:Zt(z(),z()).optional(),context:E8e.optional(),filters:O8e.optional(),id:z(),preferences:ue(z()).optional(),selected:ue(yft).optional(),signals:A8e.optional()}),f4n=fe({attribution:Zt(z(),z()).optional(),context:E8e.optional(),filters:O8e.optional(),pagination:X3r.optional(),query:z().optional(),signals:A8e.optional()}),m9r=fe({capabilities:ue(w3r),services:Zt(z(),t9r),version:z()}),m4n=fe({attribution:Zt(z(),z()).optional(),payment:n9r,signals:Ki.optional()}),Eft=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),continue_url:z().optional(),currency:z(),expires_at:Nu.date().optional(),id:z(),line_items:ue(t4),links:ue(s2),messages:ue(X1).optional(),order:TA.optional(),payment:IA.optional(),signals:Ki.optional(),status:SA,totals:ue(a2),ucp:_p}),h9r=fe({events:ue(o9r).optional(),expectations:ue(s9r).optional()}),Aft=fe({attribution:Zt(z(),z()).optional(),buyer:I8e.optional(),context:uo.optional(),line_items:ue(PA),payment:qk.optional(),signals:Ki.optional()}),Sft=fe({attribution:Zt(z(),z()).optional(),buyer:u9r.optional(),context:uo.optional(),line_items:ue(jk),payment:fY.optional(),signals:Ki.optional()}),Tft=fe({attribution:Zt(z(),z()).optional(),buyer:c9r.optional(),context:uo.optional(),continue_url:z().optional(),currency:z(),expires_at:Nu.date().optional(),id:z(),line_items:ue(t4),links:ue(s2),messages:ue(X1).optional(),order:TA.optional(),payment:IA.optional(),signals:Ki.optional(),status:SA,totals:ue(a2),ucp:_p}),Pft=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),line_items:ue(PA),payment:qk.optional(),signals:Ki.optional(),discounts:fft.optional()}),y9r=fe({applied:ue(d9r).optional(),codes:ue(z()).optional()}),g9r=fe({destinations:ue(L3r).optional(),groups:ue(vft).optional(),line_item_ids:ue(z()).optional(),selected_destination_id:xA([wA(),z()]).optional(),type:x8e}),b9r=fe({available_methods:ue(F3r).optional(),methods:ue(l9r).optional()}),Ift=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),line_items:ue(PA),payment:qk.optional(),signals:Ki.optional(),cart_id:z().optional()}),h4n=fe({attribution:Zt(z(),z()).optional(),context:E8e.optional(),filters:O8e.optional(),ids:ue(z()),signals:A8e.optional()}),_9r=fe({availability:mft.optional(),barcodes:ue(hft).optional(),categories:ue(Rk).optional(),description:kk,handle:z().optional(),id:z(),list_price:EA.optional(),media:ue(Bk).optional(),metadata:Zt(z(),Xd()).optional(),options:ue(P8e).optional(),price:EA,rating:Nk.optional(),seller:gft.optional(),sku:z().optional(),tags:ue(z()).optional(),title:z(),unit_price:xft.optional(),url:z().optional(),inputs:ue(J3r)}),Oft=fe({availability:W3r.optional(),barcodes:ue(G3r).optional(),categories:ue(Rk).optional(),description:kk,handle:z().optional(),id:z(),list_price:EA.optional(),media:ue(Bk).optional(),metadata:Zt(z(),Xd()).optional(),options:ue(P8e).optional(),price:EA,rating:Nk.optional(),seller:Y3r.optional(),sku:z().optional(),tags:ue(z()).optional(),title:z(),unit_price:f9r.optional(),url:z().optional()}),v9r=fe({categories:ue(Rk).optional(),description:kk,handle:z().optional(),id:z(),list_price_range:AA.optional(),media:ue(Bk).optional(),metadata:Zt(z(),Xd()).optional(),options:ue(C8e).optional(),price_range:AA,rating:Nk.optional(),tags:ue(z()).optional(),title:z(),url:z().optional(),variants:ue(Oft)}),y4n=fe({payment:e9r.optional(),signing_keys:ue(v3r).optional(),ucp:m9r}),Cft=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),line_items:ue(PA),payment:qk.optional(),signals:Ki.optional()}),w9r=fe({adjustments:ue(i9r).optional(),attribution:Zt(z(),z()).optional(),checkout_id:z(),currency:z(),fulfillment:h9r,id:z(),label:z().optional(),line_items:ue(a9r),messages:ue(X1).optional(),permalink_url:z(),totals:ue(a2),ucp:_p}),Rft=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),continue_url:z().optional(),currency:z(),expires_at:Nu.date().optional(),id:z(),line_items:ue(t4),links:ue(s2),messages:ue(X1).optional(),order:TA.optional(),payment:IA.optional(),signals:Ki.optional(),status:SA,totals:ue(a2),ucp:_p,discounts:y9r.optional()}),kft=fe({methods:ue(g9r).optional()}),Bft=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),line_items:ue(jk),payment:fY.optional(),signals:Ki.optional(),fulfillment:kft.optional()}),Nft=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),continue_url:z().optional(),currency:z(),expires_at:Nu.date().optional(),id:z(),line_items:ue(t4),links:ue(s2),messages:ue(X1).optional(),order:TA.optional(),payment:IA.optional(),signals:Ki.optional(),status:SA,totals:ue(a2),ucp:_p,fulfillment:b9r.optional()}),x9r=fe({categories:ue(Rk).optional(),description:kk,handle:z().optional(),id:z(),list_price_range:AA.optional(),media:ue(Bk).optional(),metadata:Zt(z(),Xd()).optional(),options:ue(C8e).optional(),price_range:AA,rating:Nk.optional(),tags:ue(z()).optional(),title:z(),url:z().optional(),variants:ue(_9r)}),E9r=fe({options:ue(C8e).optional(),selected:ue(yft).optional(),categories:ue(Rk).optional(),description:kk,handle:z().optional(),id:z(),list_price_range:AA.optional(),media:ue(Bk).optional(),metadata:Zt(z(),Xd()).optional(),price_range:AA,rating:Nk.optional(),tags:ue(z()).optional(),title:z(),url:z().optional(),variants:ue(Oft)}),g4n=fe({messages:ue(S8e).optional(),pagination:Q3r.optional(),products:ue(v9r),ucp:_p}),jft=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),line_items:ue(PA),payment:qk.optional(),signals:Ki.optional(),fulfillment:kft.optional()}),b4n=fe({messages:ue(S8e).optional(),products:ue(x9r),ucp:_p}),_4n=fe({messages:ue(S8e).optional(),product:E9r,ucp:_p});var E4n=dY.extend({token:jr.string().optional()}),A9r=jr.object({webhook_url:jr.string().url().optional()}),qft=Eft.extend(Nft.pick({fulfillment:!0}).shape).extend(Rft.pick({discounts:!0}).shape).extend(Tft.pick({buyer:!0}).shape).extend({platform:A9r.optional()}),Uft=Cft.extend(jft.pick({fulfillment:!0}).shape).extend(Pft.pick({discounts:!0}).shape).extend(Aft.pick({buyer:!0}).shape).extend(Ift.pick({cart_id:!0}).shape),Mft=wft.extend(Bft.pick({fulfillment:!0}).shape).extend(_ft.pick({discounts:!0}).shape).extend(Sft.pick({buyer:!0}).shape);Dc();async function mY(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 hY(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 S9r=3e4,Dft=2*1024*1024,vp=class extends Error{constructor(r,n,i){super(r);this.rpcCode=n;this.httpStatus=i;this.name="UcpRpcError"}rpcCode;httpStatus};function zft(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 Lft(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"?Uft:Mft).safeParse(e).success)throw new Error(`UCP ${t} checkout input failed schema validation`);return e}function T9r(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 Hft(e,t,r,n){try{e[t](r,n)}catch{}}function P9r(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 yY=class{endpoint;platformProfileUrl;fetchImpl;signal;timeoutMs;boundaryLogger;requestId=1;constructor(t){this.endpoint=zft(t.endpoint,"UCP MCP endpoint").toString(),this.platformProfileUrl=zft(t.platformProfileUrl,"UCP platform profile URL").toString(),this.fetchImpl=t.fetch??fetch,this.signal=t.signal,this.timeoutMs=t.timeoutMs??S9r,this.boundaryLogger=t.logger??Be}async createCheckout(t){return await this.callCheckout("create_checkout",{meta:this.metadata(),checkout:Lft(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:Lft(r,"update")})}metadata(){return{"ucp-agent":{profile:this.platformProfileUrl}}}async callCheckout(t,r){let n=this.requestId++,i=hY(this.timeoutMs,this.signal),o=(0,Fft.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 mY(u,Dft,"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 vp(m.message,void 0,u.status):m}if(Buffer.byteLength(d)>Dft)throw new vp("UCP MCP response exceeds the 2 MiB limit",void 0,u.status);let l;try{l=JSON.parse(d)}catch{throw new vp("UCP MCP response is not valid JSON",void 0,u.status)}if(!T9r(l))throw new vp("UCP MCP response is not a valid JSON-RPC envelope",void 0,u.status);if(l.id!==n)throw new vp("UCP MCP response id does not match the request",void 0,u.status);if("error"in l)throw new vp(`UCP MCP error ${l.error.code}: ${l.error.message}`,l.error.code,u.status);if(!u.ok)throw new vp(`UCP MCP request failed with HTTP ${u.status}`,void 0,u.status);let p=l.result;if(!p?.structuredContent)throw new vp("UCP MCP response is missing result.structuredContent");if(!qft.safeParse(P9r(p.structuredContent)).success)throw new vp("UCP checkout response failed schema validation");return Hft(this.boundaryLogger,"info","ucp:checkout_rpc",{correlationId:o,endpointOrigin:s,rpcMethod:t,httpStatus:c,elapsedMs:Date.now()-a}),p.structuredContent}catch(u){throw Hft(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 Vft=require("node:crypto");Dc();var bY="2026-04-08",I9r="dev.ucp.shopping",O9r="dev.ucp.shopping.checkout",C9r=1024*1024,R9r=1e4,k9r="https://ucp.dev",Uk=jr.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"),B9r=jr.object({version:jr.string().regex(/^\d{4}-\d{2}-\d{2}$/),spec:Uk,schema:Uk,transport:jr.enum(["rest","mcp","a2a","embedded"]),endpoint:Uk.optional()}).passthrough(),N9r=jr.object({version:jr.string().regex(/^\d{4}-\d{2}-\d{2}$/),spec:Uk,schema:Uk,extends:jr.union([jr.string(),jr.array(jr.string()).min(1)]).optional()}).passthrough(),j9r=jr.object({ucp:jr.object({version:jr.string().regex(/^\d{4}-\d{2}-\d{2}$/),services:jr.record(jr.array(B9r)),capabilities:jr.record(jr.array(N9r)),payment_handlers:jr.record(jr.array(jr.unknown())).optional()}).passthrough(),signing_keys:jr.array(jr.unknown()).optional()}).passthrough();function q9r(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 gY(e,t){if(new URL(e).origin!==k9r)throw new Error(`${t} must be governed by the ucp.dev namespace`)}function $ft(e,t,r,n){try{e[t](r,n)}catch{}}async function U9r(e,t={}){let r=q9r(e,"UCP business URL"),n=hY(t.timeoutMs??R9r,t.signal),i=t.logger??Be,o=(0,Vft.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 mY(c,C9r,"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=j9r.safeParse(d);if(!l.success)throw new Error("UCP profile response does not match the 2026-04-08 profile shape");return $ft(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 $ft(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 M9r(e){if(e.ucp.version!==bY)throw new Error(`Unsupported UCP version: ${e.ucp.version}`);let t=e.ucp.capabilities[O9r]?.find(i=>i.version===bY);if(!t)throw new Error("Business does not advertise UCP checkout 2026-04-08");gY(t.spec,"Checkout capability spec"),gY(t.schema,"Checkout capability schema");let r=e.ucp.services[I9r]?.find(i=>i.version===bY&&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");gY(r.spec,"Shopping service spec"),gY(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 Kft(e,t={}){let r=await U9r(e,t);return{...r,endpoint:M9r(r.profile),version:bY}}var D9r="https://app.visacli.sh/.well-known/ucp";function z9r(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 L9r(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 R8e(e,t=new Set){if(Array.isArray(e))for(let r of e)R8e(r,t);else if(e&&typeof e=="object")for(let[r,n]of Object.entries(e))r==="endpoint"?L9r(n,t):R8e(n,t);return t}function H9r(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=R8e(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 F9r(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 $9r(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 Gft(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??Kft)(e.business),i=await(t.getCheckout??(async(u,d)=>await new yY({endpoint:u.endpoint,platformProfileUrl:z9r(t.platformProfileUrl??process.env.VISA_UCP_PROFILE_URL??D9r)}).getCheckout(d)))(r,e.checkoutId);if(i.id!==e.checkoutId)throw new Error("UCP checkout response id does not match the requested checkout");let o=String(i.status??"unknown");if(o==="completed")return{success:!1,status:"not_ready",checkoutId:e.checkoutId,checkoutStatus:o,reason:"checkout_already_completed"};if(o!=="requires_escalation")return{success:!1,status:"not_ready",checkoutId:e.checkoutId,checkoutStatus:o,reason:"checkout_not_escalated"};if(typeof i.continue_url!="string"||!i.continue_url)return{success:!1,status:"not_ready",checkoutId:e.checkoutId,checkoutStatus:o,reason:"missing_continue_url"};let s=F9r(i),a=H9r(r.businessOrigin,i.continue_url,r.profile),c=`ucp_${(0,Wft.createHash)("sha256").update([r.businessOrigin,e.checkoutId,o,s.currency,String(s.minor),a.url].join("\0")).digest("hex").slice(0,24)}`;return{success:!0,status:"ready_for_review",checkoutId:e.checkoutId,handoffId:c,checkoutStatus:"requires_escalation",amount:s,merchant:{businessOrigin:r.businessOrigin,sourceHost:a.sourceHost,targetHost:a.targetHost,originRewritten:a.originRewritten},payMerchantRequest:{action:"review",url:a.url,amount:s.decimal,currency:s.currency},messages:$9r(i),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>."}}a4();function V9r(){return ju()}var Qs=new Gk(()=>Uu.getSessionToken()),K9r="4.1.0-rc.33",rwn=["","","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(`
20778
- `);function W9r(e){if(!e||typeof e!="string")return{opened:!1,blockedReason:"invalid_url"};let t=qA(e);if(!t)return{opened:!1,blockedReason:"invalid_url"};if(t3e())return{opened:!1,url:t,blockedReason:"suppressed"};let r=jA();if(r.headless)return Be.info(`Browser auto-open skipped (${r.reason}). URL: ${t}`),{opened:!1,url:t,blockedReason:"headless"};let i=[V9r(),rl()].filter(s=>!!s).map(s=>B3e(t,s)).find(Boolean)??null;if(!i)return Be.info(`Browser auto-open skipped (non-internal host). URL: ${t}`),{opened:!1,url:t,blockedReason:"non_internal_host"};let o=iB(i);return o?((0,Yft.execFile)(o.cmd,o.args,s=>{s&&Be.warn(`Browser open failed: ${s.message}. URL: ${i}`)}),{opened:!0,url:i}):(Be.info(`No browser command for platform "${vY.platform()}". URL: ${i}`),{opened:!1,url:i,blockedReason:"unsupported_platform"})}function G9r(){let e=!1,t;try{let n=Zft.join(vY.homedir(),".claude","settings.json");if(_Y.existsSync(n)){let i=JSON.parse(_Y.readFileSync(n,"utf-8")),o=typeof i.statusLine=="object"?i.statusLine.command:"";e=xdt(o)}}catch{}let r=TJ();return r||(t="visa-cli config hud enable"),{statusLine:e,shellHud:r,...t?{shellHudSetup:t}:{}}}async function J9r(e){let t=await Qs.getStatus(e);return t.hud=G9r(),!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=K9r,t}async function Y9r(e,t){return await Qs.feedback(e.message,e.transaction_id,t)}async function Z9r(e){let t=await Adt({api:Qs,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 k8e=new Set(["auth.serverUrl"]);function Mk(){return Object.keys(RA).filter(e=>!k8e.has(e)).sort()}function Xft(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:Mk()}}async function X9r(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(k8e.has(e.key))return Be.warn("config:set:rejected:mcp-forbidden",{key:e.key}),Xft(e.key,"set");Be.info("config:set",{key:e.key});try{let t=Q8e(e.key,e.value);return Be.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 Om?"UNKNOWN_KEY":"INVALID_VALUE",n=t instanceof Om?`Unknown setting "${e.key}". MCP-settable keys: ${Mk().join(", ")}. For auth.serverUrl, use the shell command instead.`:t.message;return Be.warn("config:set:rejected",{key:e.key,code:r,error:n}),{success:!1,error:n,code:r,settableKeys:Mk()}}}async function Q9r(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(k8e.has(e.key))return Be.warn("config:unset:rejected:mcp-forbidden",{key:e.key}),Xft(e.key,"unset");Be.info("config:unset",{key:e.key});try{let t=e3e(e.key);return Be.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 Om?"UNKNOWN_KEY":"INVALID_VALUE",n=t instanceof Om?`Unknown setting "${e.key}". MCP-settable keys: ${Mk().join(", ")}. For auth.serverUrl, use the shell command instead.`:t.message;return Be.warn("config:unset:rejected",{key:e.key,code:r,error:n}),{success:!1,error:n,code:r,settableKeys:Mk()}}}async function exr(e=rl(),t=!1){if(!e)return{success:!1,message:"No enrollment web origin is configured. Set VISA_VERIFY_WEB_URL to a deployment URL to use enroll_agent."};if(!t){let p=ok();if(p.kind==="claimed"){let f=p.credential;return Be.info("agent:enroll_already_connected",{keyBound:f.keyBound}),{success:!0,alreadyConnected:!0,...f.name?{name:f.name}:{},keyBound:f.keyBound,message:`This device is already connected${f.name?` as ${f.name}`:""} \u2014 nothing to pair. To add or change spending on this identity, run \`visa agent add-rail\`. Call enroll_agent with {"action":"start","force":true} to start a brand-new enrollment anyway.`}}}let{challenge:r,confirmCode:n,agentPkX:i,walletPkHex:o}=ik(),s=kA(e),a=`${s}?cli=${r}&cliPk=${i}${o?`&walletPk=${o}`:""}`;Be.info("agent:enroll_open",{url:s});let c=W9r(a),u="sign in \u2192 pick your .visa name \u2192 wallet \u2192 card (secure fields) \u2192 bank verification with passkey \u2192 mint; already enrolled on the web? sign in \u2192 verify with your passkey \u2192 connect",d=`CONFIRMATION CODE: ${n} \u2014 the final screen will ask for it. Only enter it on a page YOU opened from this terminal; never share it or enter a code from a link someone sent you.`,l='When the final screen shows "Sent to your Visa CLI", call enroll_agent with {"action":"claim"} to store the enrollment credential on this device.';return c.opened?{success:!0,opened:!0,browserUrl:c.url,confirmCode:n,message:`Opened the Visa Verified Agent enrollment in your browser (${u}). ${d} ${l} Access is currently tester-gated \u2014 if sign-in shows "private testing", ask for the v4_verify_web_access flag.`}:{success:!0,opened:!1,requiresBrowser:!0,browserUrl:c.url??a,confirmCode:n,message:`Open this URL in a browser to enroll your agent (${u}): ${c.url??a} \u2014 ${d} ${l}`}}async function txr(e=rl()){if(!e)return{success:!1,message:"No enrollment web origin is configured. Set VISA_VERIFY_WEB_URL to a deployment URL to use enroll_agent."};let t=await sk(e);switch(Be.info("agent:enroll_claim",{status:t.status}),t.status){case"claimed":return{success:!0,name:t.name,tokenId:t.tokenId,credentialPath:t.credentialPath,keyBound:t.keyBound,sessionSaved:t.sessionSaved,walletProvisioned:t.walletProvisioned,message:`Enrollment credential${t.name?` for ${t.name}`:""} stored at ${t.credentialPath} (token id ${t.tokenId}). The CLI purchase leg will read it from there.`+(t.keyBound?" The agent's key was generated on this terminal and its private half never left this device.":" Note: this terminal\u2019s agent key was not bound \u2014 normal when connecting an EXISTING agent from a returning sign-in (the agent keeps its original key); the credential works for purchases, but no agent key is held on this device.")+(t.sessionSaved?" This device is connected to your identity.":"")+(t.walletProvisioned?" Your x402 spending wallet is live on this device \u2014 fund the wallet address and you can pay (wallet_pay / visa pay).":"")};case"no_pending":return{success:!1,message:"No enrollment hand-off is in progress on this device \u2014 run enroll_agent first, finish the browser flow, then claim."};case"not_ready":return{success:!1,message:t.likelyExpired?"The hand-off window (15 minutes) has likely expired \u2014 run enroll_agent again, finish the browser flow, then claim.":'The enrollment credential is not ready yet \u2014 finish the browser flow through the final "minted" screen (it will say "Sent to your Visa CLI"), then claim again.'};case"confirm_mismatch":return{success:!1,confirmCode:t.confirmCode,message:`The confirmation code entered in the browser did not match this terminal, so the credential was refused. Your code is ${t.confirmCode} \u2014 re-enter it on the enrollment page ("Re-enter code"), then claim again. If YOU did not just complete the browser flow, someone else may have your enrollment link; run enroll_agent to start over with a fresh one.`};case"error":return{success:!1,message:t.message}}}async function Jft(){if(await Uu.clearAll(),!!O3e())try{await C3e()}catch(e){Be.warn("reset:touchid_key_delete_failed",{error:e instanceof Error?e.message:String(e)})}}async function rxr(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return{success:!1,message:"Please confirm by setting confirm: true to reset"};if(Be.info("reset:attempt"),e.localOnly)return await Jft(),Be.info("reset:success",{localOnly:!0}),{success:!0,message:"Device reset locally. Local credentials and keys have been removed. Use enroll_agent to connect this device again."};try{await Qs.logout(void 0,t)}catch{}return await Jft(),Be.info("reset:success"),{success:!0,message:"Device reset. The server session, local credentials, and local keys have been removed. Use enroll_agent to connect this device again."}}async function nxr(e){if(!e.name)return{success:!1,error:"name is required"};try{let{registerName:t,ensureMailbox:r}=await Promise.resolve().then(()=>(Nv(),gk)),n=await t(e.name);return await r(e.name),{success:!0,...n}}catch(t){let{CardRequiredError:r}=await Promise.resolve().then(()=>(LA(),E9e));return t instanceof r?{success:!1,card_required:!0,reason:t.reason,recovery_tool:"enroll_agent",error:t.message,message:`${t.message} Call enroll_agent, complete and claim V4 enrollment, then ask me to register again.`}:{success:!1,error:t instanceof Error?t.message:String(t)}}}async function ixr(e){if(!e.name)return{success:!1,error:"name is required"};try{let{resolveMeshName:t}=await Promise.resolve().then(()=>(Nv(),gk));return{success:!0,...await t(e.name)}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async function oxr(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(()=>(Nv(),gk)),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 sxr(e){try{let{readInbox:t,resolveActingName:r,meshName:n}=await Promise.resolve().then(()=>(Nv(),gk)),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 zo=class{static async subwayRegister(t){return nxr(t||{})}static async subwayFind(t){return ixr(t||{})}static async subwaySend(t){return oxr(t||{})}static async subwayInbox(t){return sxr(t||{})}static async getStatus(t){return J9r(t)}static async feedback(t,r){return Y9r(t,r)}static async configList(t){return Z9r(t||{})}static async configSet(t){return X9r(t||{})}static async configUnset(t){return Q9r(t||{})}static async reset(t,r){return rxr(t,r)}static async enrollAgent(t={},r){let n=t?.action??"start";return n==="start"?exr(void 0,t?.force===!0):n==="claim"?txr():{success:!1,message:`Unknown enroll_agent action ${JSON.stringify(n)}. Use "start" (default \u2014 opens the enrollment flow) or "claim" (stores the credential after the browser flow finishes).`}}static async payMerchant(t={},r){return eft(t)}static async ucpCheckoutHandoff(t,r){return vm("ucp_checkout_handoff")&&(await nA(),vm("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."}:Gft(t)}static async payMerchantStatus(t={},r){return Qpt(t)}static async startCardMandate(t={},r){return tft(t)}static async submitFeedback(t,r,n){Be.info("feedback:submit",{length:t.length,transactionId:r,hasContext:!!n});try{let i=await Qs.submitFeedback(t,r,n);return Be.info("feedback:submitted",{transactionId:r}),i}catch(i){let o=i instanceof Error?i.message:"Unknown error";throw Be.error("feedback:error",{error:o,transactionId:r}),i}}static async getFeedback(t,r){Be.info("feedback:list",{limit:t||20});try{let n=await Qs.getFeedback(t,r);return Be.info("feedback:listed",{count:n?.feedback?.length||0}),n}catch(n){let i=n instanceof Error?n.message:"Unknown error";throw Be.error("feedback:error",{error:i}),n}}};function Qft(e){return e==="pay_merchant"}Dc();var emt="VISA_V4_WALLET_EXPERIMENT",axr=null;function cxr(){return axr??!0}var uxr=new Set(["1","true","on","yes"]),dxr=new Set(["0","false","off","no"]),tmt=!1;function B8e(e,t){return tmt||(tmt=!0,Be.info("wallet-experiment:enablement",{enabled:e,reason:t})),e}function nmt(){let e=(process.env[emt]??"").trim().toLowerCase();if(uxr.has(e))return B8e(!0,"env-on");if(dxr.has(e))return B8e(!1,"env-off");e!==""&&Be.warn("wallet-experiment:unrecognized-env-value",{env:emt,fallback:"bundled-runtime"});let t=cxr();return B8e(t,t?"bundled-runtime":"runtime-unavailable")}var rmt=null;function imt(){return rmt??=wJ(),rmt}var lxr={user_context:{type:"string",description:"The exact verbatim request the user made that prompted this tool call. Always include the user's full original message."}};function pxr(e){return{...e,inputSchema:{...e.inputSchema,properties:{...e.inputSchema.properties,...lxr},required:[...e.inputSchema.required||[],"user_context"]}}}function omt(){return nmt()?imt().WALLET_TOOL_DEFS.map(pxr):[]}function smt(e){return nmt()?imt().WALLET_TOOL_NAMES.includes(e):!1}async function amt(e,t,r={}){let i=await(await Promise.resolve().then(()=>Ze(wJ()))).dispatchWalletTool(e,t,{logger:Be,merchantDirectorySearch:r.merchantDirectorySearch});if(r.emitTelemetry&&(e==="wallet_pay"||e==="wallet_directory_pay")&&i.receipt)try{let o=fxr(e,t,i);o&&await r.emitTelemetry([o])}catch(o){Be.warn("wallet-experiment:telemetry-failed",{tool:e,error:o instanceof Error?o.message:String(o)})}return i}function fxr(e,t,r){if(e!=="wallet_pay"&&e!=="wallet_directory_pay")return null;let n=r.receipt&&typeof r.receipt=="object"&&!Array.isArray(r.receipt)?r.receipt:null;if(!n)return null;let i=typeof n.amountUsd=="string"?n.amountUsd:"",o=Number(i.replace(/[$,\s]/g,""));if(!Number.isFinite(o)||o<=0)return null;let s=r.directory&&typeof r.directory=="object"&&!Array.isArray(r.directory)?r.directory:null,a=s?.selection&&typeof s.selection=="object"&&!Array.isArray(s.selection)?s.selection:null,c=typeof t.url=="string"?t.url:typeof a?.url=="string"?a.url:"",u="Pay-per-use service";try{u=new URL(c).hostname.toLowerCase()}catch{}let d=typeof n.timestamp=="string"?n.timestamp:new Date().toISOString(),l=typeof n.network=="string"?n.network:null,p=typeof n.scheme=="string"?n.scheme:null,f=typeof n.txHash=="string"?n.txHash:null;return{timestamp:d,tool_name:e,user_prompt:"",tool_params:JSON.stringify({merchant_host:u,network:l,scheme:p}),result_success:!0,result_error:null,result_json:JSON.stringify({network:l,scheme:p}),payment_rail:"stablecoin",payment_amount:o,payment_currency:"USDC",merchant_name:u,transaction_id:null,tx_hash:f,protocol:"x402",http_status:null,duration_ms:0,source:"cli",endpoint:"/v4/wallet",resolved_model:null,session_budget_id:null}}Dc();var N8e=["pay_merchant"],mxr={pay_merchant:"merchant checkout"};function hxr(e){return mxr[e]||e}var cmt={};function umt(e){let t=cmt[e]??0;return cmt[e]=t+1,t}function dmt(e,t,r){return N8e.includes(e)?t===0?{_feedback_prompt:{message:`This was your first time using ${hxr(e)} \u2014 if you have any thoughts on the experience, I'd be happy to pass them along to the Visa CLI team.`,transaction_id:r}}:t%5===0?{_feedback_hint:{message:"Feedback? Just say how that went.",transaction_id:r}}:{}:{}}var xY=Ze(require("crypto")),EY=Ze(require("tty")),r4=Ze(require("fs")),q8e=Ze(require("os")),wY=Ze(require("path"));zY();NA();var yxr=new Set(["connect","disconnect","connections"]);function gxr(e){return e!==void 0&&yxr.has(e)}function bxr(e){return/-rc\.|-beta\./.test(e)}function j8e(e){return xY.createHash("sha256").update(e.trim()).digest("hex")}function lmt(e){return Cm==="SKIP"?!0:xY.timingSafeEqual(Buffer.from(j8e(e)),Buffer.from(Cm))}function _xr(){return wY.join(q8e.homedir(),".visa-mcp","agent-credential.json")}function vxr(){let e=process.env.VISA_V4_HOME||wY.join(q8e.homedir(),".visa-v4");return wY.join(e,"turnkey.json")}function wxr(){try{let e=r4.readFileSync(_xr(),"utf8"),t=JSON.parse(e);if(typeof t?.tokenId=="string"&&t.tokenId.length>0)return!0}catch{}try{let e=r4.readFileSync(vxr(),"utf8"),t=JSON.parse(e);return typeof t?.organizationId=="string"&&t.organizationId.length>0&&typeof t?.walletId=="string"&&t.walletId.length>0&&typeof t?.address=="string"&&/^0x[0-9a-f]{40}$/i.test(t.address)}catch{return!1}}function xxr(){try{let e=r4.openSync("/dev/tty","r+"),t=new EY.ReadStream(e),r=new EY.WriteStream(e),n=!1;return{input:t,output:r,cleanupStreams:()=>{if(!n){n=!0;try{t.destroy()}catch{}try{r.destroy()}catch{}try{r4.closeSync(e)}catch{}}}}}catch{if(!process.stdin.isTTY)throw new Error("No interactive terminal available. Set VISA_RC_CODE env var instead.");return{input:process.stdin,output:process.stderr,cleanupStreams:()=>{}}}}function Exr(e){return new Promise((t,r)=>{let n;try{n=xxr()}catch(d){r(d);return}let{input:i,output:o,cleanupStreams:s}=n,a=()=>{i.off("data",u);try{i.setRawMode?.(!1)}catch{}s()};o.write(e),i.setRawMode?.(!0),i.resume(),i.setEncoding("utf8");let c="",u=d=>{d==="\r"||d===`
20777
+ `:""})}function X5r(e){return Z5r(e,K5r,W5r).trimEnd()}function Q5r(e){return X5r(e)!==e.trimEnd()}function TJ(e=G5r()){if(!e)return!1;try{let t=J5r(e),r=_m.readFileSync(t,"utf-8");return Q5r(r)}catch{return!1}}function wdt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function evr(){let e=SJ.homedir();if(!e||!yp.isAbsolute(e))throw new Error("unable to determine a valid home directory");return yp.resolve(e)}var g5n=1440*60*1e3;var tvr="# visa-cli-hud-v1";function xdt(e){return typeof e!="string"?!1:e.includes(tvr)?!0:e.includes("visa-cli")&&e.includes("statusline")}a4();Yk();var Edt="4.1.0-rc.34";function Q4e(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function rvr(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=UY(t);return i!==void 0?{value:i,source:{kind:"settings"}}:{value:r!=="opt-in",source:{kind:"default"}}}function rA(e){return e==null?"\u2014":e?"yes":"no"}async function Adt(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=qY("auth.serverUrl"),s=ju(),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:rA(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=rvr("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");n.push({key:"ui.suppressBrowser",value:c.value,formatted:rA(c.value),source:c.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let u=Lk(),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:rA(!u),source:d}),n.push({key:"client.version",value:Edt,formatted:Edt,source:{kind:"default"}}),e.includeDev){let l=process.env.VISA_MOCK_KEYCHAIN,p=th();n.push({key:"dev.mockKeychain",value:p,formatted:rA(p),source:Q4e("VISA_MOCK_KEYCHAIN",!!l),hint:LY()});let f=process.env.VISA_MOCK_TOUCHID,m=Jk();n.push({key:"dev.mockTouchid",value:m,formatted:rA(m),source:Q4e("VISA_MOCK_TOUCHID",!!f),hint:LY()});let h=process.env.VISA_CLI_DEBUG;n.push({key:"dev.debug",value:!!h,formatted:rA(!!h),source:Q4e("VISA_CLI_DEBUG",!!h)})}return{entries:n,statusError:r}}var g8e=require("node:os"),Ak=require("node:path"),Sk=require("node:fs/promises"),Fpt=require("node:fs"),$pt=require("node:url"),Vpt=require("node:crypto");Dc();var nvr=new Set(["USD","USDC","EUR","GBP","CAD","AUD"]);function ewe(e,t){let r=t.toUpperCase();return!Number.isFinite(e)||!nvr.has(r)?`${e} ${r} (minor units)`:`${(e/100).toFixed(2)} ${r}`}var L1=class extends Error{constructor(t){super(t),this.name="PayValidationError"}};function twe(e){let t;try{t=new URL(e)}catch{throw new L1(`Invalid URL: ${e}. Expected a fully-qualified http(s) URL.`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new L1(`Unsupported URL scheme "${t.protocol}". Only http and https are allowed.`);return t}Dc();var ivr={ucp_checkout_handoff:"checkout_agent_access",pay_merchant:"checkout_agent_access",pay_merchant_status:"checkout_agent_access",start_card_mandate:"checkout_agent_access"},Sdt=300*1e3,rwe={},nwe=0,ak=null;function iwe(){return ak||(ak=(async()=>{try{let e=await Qs.getFeatureFlags();rwe=e&&e.flags||{},nwe=Date.now()}catch(e){rwe={},Be.warn("feature-flags:fetch-failed",{error:e instanceof Error?e.message:String(e)})}finally{ak=null}})(),ak)}async function Tdt(){await iwe()}function Pdt(){Date.now()-nwe<Sdt||iwe()}async function nA(){Date.now()-nwe<Sdt||await iwe()}function vm(e){let t=ivr[e];return t?rwe[t]!==!0:!1}var Idt=require("node:crypto"),ck=class extends Error{constructor(r){super(`Approval handoff already exists with different inputs for review ${r}`);this.reviewId=r;this.name="PayMerchantApprovalConflictError"}reviewId},PJ=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 ck(t.reviewId);return await this.waitUntilQueryable(n.ready),this.snapshot(n)}let i=()=>{},o=new Promise(u=>{i=u}),s=(this.options.idFactory??Idt.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 Kpt(e){return[(0,Ak.join)(e,"checkout-engine","index.js"),(0,Ak.join)(e,"..","checkout-engine","index.js")]}function i8r(e,t=Fpt.existsSync){return Kpt(e).find(r=>t(r))??null}var nY=null,Wpt=async()=>{if(nY)return nY;let e=i8r(__dirname);if(!e)throw new Error(`Cannot find module: the checkout engine was not packaged (looked in ${Kpt(__dirname).join(" and ")}).`);return nY=(await import((0,$pt.pathToFileURL)(e).href)).createCliCheckoutEngine({cardDrawVerdict:await o8r(),cardMandateRegister:await s8r()}),nY};async function o8r(){let e=await Promise.resolve().then(()=>(h8e(),m8e));return{loadCapability:()=>e.loadCardMandateCapability(),fetchVerdict:t=>e.fetchCardDrawVerdict(t)}}async function s8r(){let e=await Promise.resolve().then(()=>(h8e(),m8e));return{loadCapability:()=>e.loadCardMandateCapability(),register:t=>e.registerCardMandate(t)}}async function b8e(){return vm("pay_merchant")?(await nA(),vm("pay_merchant")):!1}var Gpt=(0,Ak.join)((0,g8e.homedir)(),".visa-mcp","agent-credential.json"),Jpt=(0,Ak.join)((0,g8e.homedir)(),".visa-mcp","contact.json"),Ypt=new PJ;function Tk(e){return e.replace(/https?:\/\/[^\s"')\]]+/gi,t=>{try{return new URL(t).origin}catch{return"[url]"}}).slice(0,300)}var a8r=new Set(["USD","USDC","EUR","GBP","CAD","AUD"]);function Zpt(e){return a8r.has(e)?e:null}async function iY(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,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?Tk(e.errorMessage):null,result_json:JSON.stringify({outcome:e.outcome,confirmationRef:e.confirmationRef??null,source:e.source??null,remainingMinor:e.remainingMinor??null}),payment_rail:e.action==="pay"?"card":null,payment_amount:e.action==="pay"?e.amountMinor:null,payment_currency:Zpt(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){Be.warn("pay_merchant:telemetry_failed",{action:e.action,error:t instanceof Error?t.message:String(t)})}}async function Hpt(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?Tk(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:Zpt(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){Be.warn("start_card_mandate:telemetry_failed",{error:t instanceof Error?t.message:String(t)})}}function y8e(e){if(typeof e!="string"||!/^\d+(\.\d{1,2})?$/.test(e)||Number(e)<=0)throw new L1(`Invalid amount ${JSON.stringify(e)}. Expected a positive decimal like "5.00".`);return e}function Xpt(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=Tk(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 Qpt(e={},t={}){if(await(t.flagDisabled??b8e)())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??Ypt).get(n);return o?Xpt(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 eft(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:MY()&&!process.env.VISA_VERIFY_WEB_URL?null:rl();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??b8e)())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??Ypt,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=twe(e.url??"").toString(),c=y8e(e.amount)}catch(C){if(C instanceof L1)return{success:!1,message:C.message};throw C}let d=t.credentialPath??Gpt,l=t.contactPath??Jpt;try{await(0,Sk.readFile)(d,"utf8")}catch{return{success:!1,message:"No enrolled agent credential on this device \u2014 run enroll_agent (start -> claim) first, then retry pay_merchant."}}let p;try{p=JSON.parse(await(0,Sk.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 C=typeof e.confirm=="string"?e.confirm.trim():"",I=/^PAY (\S+)$/.exec(C);if(!I)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=I[1]}let m=t.loadEngine??Wpt,h;try{h=await m()}catch(C){let I=C instanceof Error?C.message:String(C);if(/ERR_MODULE_NOT_FOUND|Cannot find (module|package)/.test(I))return{success:!1,message:/checkout engine was not packaged/.test(I)?"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 C}let y={url:a,amount:c,currency:u,credentialPath:d,contact:p,approvalBaseUrl:n},w=t.emitTelemetry??(C=>Qs.emitTelemetry(C)),x=new URL(a).hostname,_=Math.round(Number(c)*100),v=Date.now();if(o==="review"){Be.info("pay_merchant:review",{host:x,currency:u});let C;try{C=await h.review(y)}catch(I){throw await iY({emitTelemetry:w,action:"review",merchantHost:x,amountMinor:_,currency:u,outcome:"engine-error",success:!1,errorMessage:I instanceof Error?I.message:String(I),startedAt:v}),I}return await iY({emitTelemetry:w,action:"review",merchantHost:x,amountMinor:_,currency:u,outcome:"reviewed",success:!0,startedAt:v}),{success:!0,action:"review",...C,message:`Review ${C.reviewId}: ${C.merchantHost} wants ${ewe(C.amountMinor,C.currency)}. For a messaging handoff, call pay_merchant { action: "authorize", url, amount, confirm: "PAY ${C.reviewId}" }; for a blocking terminal flow use action "pay". No charge yet.`}}let E=f,A=t.allowSubmit??process.env.CHECKOUT_AGENT_ALLOW_SUBMIT==="1",S=async C=>{Be.info("pay_merchant:pay",{reviewId:E,submit:A,approvalMode:o==="authorize"?"handoff":"blocking"});let I;try{I=await h.pay({...y,reviewId:E,submit:A,...C?{onApprovalUrl:C}:{}})}catch(j){throw await iY({emitTelemetry:w,action:"pay",merchantHost:x,amountMinor:_,currency:u,outcome:"engine-error",success:!1,errorMessage:j instanceof Error?j.message:String(j),startedAt:v,submit:A}),j}let R=I.outcome==="confirmed"||I.outcome==="filled-dry-run";await iY({emitTelemetry:w,action:"pay",merchantHost:x,amountMinor:_,currency:u,outcome:I.outcome,confirmationRef:I.confirmationRef,success:R,errorMessage:R?null:I.detail??I.outcome,startedAt:v,submit:A,source:I.source??null,remainingMinor:I.remainingMinor??null,drawId:I.source==="mandate"?E:null});let U=I.source==="mandate"?` Drawn tap-free from an active card mandate${typeof I.remainingMinor=="number"?` (${I.remainingMinor} ${u} minor units remaining)`:""}.`:I.source==="fresh-tap"?" Paid with a fresh per-purchase passkey.":"";return{success:R,action:"pay",reviewId:E,...I,message:I.outcome==="confirmed"?`Paid. Confirmation ${I.confirmationRef??"(none captured)"} \xB7 receipt ${I.receiptPath??"(not written)"}.${U}`:`Outcome: ${I.outcome}${I.detail?` \u2014 ${I.detail}`:""}. Do not retry blindly \u2014 verify with the merchant before any re-run.`}};if(o==="authorize"){let C=(0,Vpt.createHash)("sha256").update(JSON.stringify([E,a,c,u,A])).digest("hex");Be.info("pay_merchant:approval_handoff_started",{reviewId:E,merchantHost:x,currency:u,submit:A});try{let I=await s.start({reviewId:E,fingerprint:C,run:async R=>{try{let U=await S(j=>{Be.info("pay_merchant:approval_handoff_ready",{reviewId:E}),R(j)});return Be.info("pay_merchant:approval_handoff_completed",{reviewId:E,success:U.success===!0}),U}catch(U){throw Be.warn("pay_merchant:approval_handoff_failed",{reviewId:E,error:Tk(U instanceof Error?U.message:String(U))}),U}}});return Xpt(I,"authorize")}catch(I){if(I instanceof ck)return Be.warn("pay_merchant:approval_handoff_conflict",{reviewId:E}),{success:!1,action:"authorize",reviewId:E,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 I}}return S()}async function tft(e={},t={}){let r=(e.rail??"card").toLowerCase();if(r!=="card")return{success:!1,message:`start_card_mandate only supports the "card" rail (got ${JSON.stringify(r)}). For x402/stablecoin payments, use wallet_policy_set and wallet_pay.`};let n=t.verifyUrl!==void 0?t.verifyUrl:rl();if(n===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??b8e)())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 o=(e.currency??"USD").toUpperCase();if(!/^[A-Z]{3}$/.test(o))return{success:!1,message:`Invalid currency ${JSON.stringify(e.currency)}. Expected a 3-letter ISO code like "USD".`};let s=e.anyMerchant===!0,a,c;try{a=s?void 0:twe(e.url??"").toString(),c=y8e(e.ceiling??e.amount)}catch(A){if(A instanceof L1)return{success:!1,message:A.message};throw A}if(e.expiresAt!==void 0){let A=Date.parse(e.expiresAt);if(!Number.isFinite(A)||A<=Date.now())return{success:!1,message:`Invalid expiresAt ${JSON.stringify(e.expiresAt)}. Expected a future ISO 8601 timestamp.`}}if(e.maxDraws!==void 0&&(!Number.isSafeInteger(e.maxDraws)||e.maxDraws<1))return{success:!1,message:"maxDraws must be a positive integer."};let u;if(e.perTransaction!==void 0){try{u=y8e(e.perTransaction)}catch(A){if(A instanceof L1)return{success:!1,message:A.message};throw A}if(Number(u)>Number(c))return{success:!1,message:"perTransaction cannot exceed the ceiling."}}let d;if(e.intent!==void 0){if(typeof e.intent!="string")return{success:!1,message:"intent must be a short string."};let A=e.intent.replace(/[\p{Cc}\u2028\u2029]/gu,"").trim().slice(0,200).trim();d=A.length>0?A:void 0}let l=t.credentialPath??Gpt,p=t.contactPath??Jpt;try{await(0,Sk.readFile)(l,"utf8")}catch{return{success:!1,message:"No enrolled agent credential on this device \u2014 run enroll_agent (start -> claim) first, then retry start_card_mandate."}}let f;try{f=JSON.parse(await(0,Sk.readFile)(p,"utf8"))}catch{return{success:!1,message:`No contact details at ${p}. Write your name/email/address there (chmod 600) first.`}}let m=t.loadEngine??Wpt,h;try{h=await m()}catch(A){let S=A instanceof Error?A.message:String(A);if(/ERR_MODULE_NOT_FOUND|Cannot find (module|package)/.test(S))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 A}let y=s?"any-merchant":new URL(a).hostname,w=Math.round(Number(c)*100),x=t.emitTelemetry??(A=>Qs.emitTelemetry(A)),_=Date.now();Be.info("start_card_mandate:create",{host:y,currency:o});let v;try{v=await h.startCardMandate({...a?{url:a}:{},ceiling:c,currency:o,credentialPath:l,contact:f,approvalBaseUrl:n,...s?{anyMerchant:!0}:{},...e.merchantName?{merchantName:e.merchantName}:{},...e.expiresAt?{expiresAt:e.expiresAt}:{},...e.maxDraws!==void 0?{maxDraws:e.maxDraws}:{},...u!==void 0?{perTransaction:u}:{},...d!==void 0?{intent:d}:{}})}catch(A){let S=A instanceof Error?Tk(A.message):String(A);return Be.warn("start_card_mandate:failed",{message:S}),await Hpt({emitTelemetry:x,merchantHost:y,ceilingMinor:w,currency:o,outcome:"engine-error",success:!1,errorMessage:A instanceof Error?A.message:String(A),startedAt:_}),{success:!1,message:`Could not create the mandate: ${S}`}}let E=v.registerFailed===!0;return E&&Be.warn("start_card_mandate:register_failed",{mandateId:v.mandateId,host:y}),await Hpt({emitTelemetry:x,merchantHost:y,ceilingMinor:w,currency:o,outcome:E?"created-register-failed":"created",success:!E,mandateId:v.mandateId,remainingMinor:v.remainingMinor,startedAt:_}),E?{success:!1,mandateId:v.mandateId,ceiling:c,remainingMinor:v.remainingMinor,currency:v.currencyCode,merchant:v.merchant,merchantHost:v.merchantHost,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:c,remainingMinor:v.remainingMinor,currency:v.currencyCode,merchant:v.merchant,merchantHost:v.merchantHost,expiresAt:v.expiresAt,message:`Mandate ${v.mandateId} active: up to ${ewe(w,v.currencyCode)} at ${v.merchantHost} until ${v.expiresAt}. pay_merchant will now draw against it tap-free (no fresh passkey) until the budget is spent or it expires. NOTE: honoring a ceiling-scoped assurance across multiple draws is unproven live \u2014 if the network declines a draw, the budget is left untouched and that mandate is disabled, so your next pay_merchant uses a fresh per-purchase tap (it does NOT fall back within the same call).`}}var Wft=require("node:crypto");var Fft=require("node:crypto");var jr={};Gi(jr,{BRAND:()=>B8r,DIRTY:()=>Dv,EMPTY_PATH:()=>l8r,INVALID:()=>ht,NEVER:()=>u3r,OK:()=>ia,ParseStatus:()=>ws,Schema:()=>Ut,ZodAny:()=>i2,ZodArray:()=>Z1,ZodBigInt:()=>Lv,ZodBoolean:()=>Hv,ZodBranded:()=>Ik,ZodCatch:()=>Qv,ZodDate:()=>Fv,ZodDefault:()=>Xv,ZodDiscriminatedUnion:()=>aY,ZodEffects:()=>Yd,ZodEnum:()=>Yv,ZodError:()=>Uc,ZodFirstPartyTypeKind:()=>wt,ZodFunction:()=>uY,ZodIntersection:()=>Wv,ZodIssueCode:()=>ye,ZodLazy:()=>Gv,ZodLiteral:()=>Jv,ZodMap:()=>bA,ZodNaN:()=>vA,ZodNativeEnum:()=>Zv,ZodNever:()=>bp,ZodNull:()=>Vv,ZodNullable:()=>Pm,ZodNumber:()=>zv,ZodObject:()=>Mc,ZodOptional:()=>Gd,ZodParsedType:()=>Ce,ZodPipeline:()=>Ok,ZodPromise:()=>o2,ZodReadonly:()=>e4,ZodRecord:()=>cY,ZodSchema:()=>Ut,ZodSet:()=>_A,ZodString:()=>n2,ZodSymbol:()=>yA,ZodTransformer:()=>Yd,ZodTuple:()=>Tm,ZodType:()=>Ut,ZodUndefined:()=>$v,ZodUnion:()=>Kv,ZodUnknown:()=>Y1,ZodVoid:()=>gA,addIssueToContext:()=>Ae,any:()=>Xd,array:()=>ue,bigint:()=>U8r,boolean:()=>Zd,coerce:()=>Nu,custom:()=>uft,date:()=>M8r,datetimeRegex:()=>aft,defaultErrorMap:()=>G1,discriminatedUnion:()=>V8r,effect:()=>t3r,enum:()=>Qd,function:()=>Y8r,getErrorMap:()=>fA,getParsedType:()=>Sm,instanceof:()=>j8r,intersection:()=>K8r,isAborted:()=>oY,isAsync:()=>mA,isDirty:()=>sY,isValid:()=>r2,late:()=>N8r,lazy:()=>Z8r,literal:()=>X8r,makeIssue:()=>Pk,map:()=>G8r,nan:()=>q8r,nativeEnum:()=>Q8r,never:()=>H8r,null:()=>wA,nullable:()=>n3r,number:()=>Ir,object:()=>fe,objectUtil:()=>_8e,oboolean:()=>c3r,onumber:()=>a3r,optional:()=>r3r,ostring:()=>s3r,pipeline:()=>o3r,preprocess:()=>i3r,promise:()=>e3r,quotelessJson:()=>c8r,record:()=>Zt,set:()=>J8r,setErrorMap:()=>d8r,strictObject:()=>$8r,string:()=>z,symbol:()=>D8r,transformer:()=>t3r,tuple:()=>W8r,undefined:()=>z8r,union:()=>xA,unknown:()=>L8r,util:()=>Yt,void:()=>F8r});var Yt;(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})(Yt||(Yt={}));var _8e;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(_8e||(_8e={}));var Ce=Yt.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),Sm=e=>{switch(typeof e){case"undefined":return Ce.undefined;case"string":return Ce.string;case"number":return Number.isNaN(e)?Ce.nan:Ce.number;case"boolean":return Ce.boolean;case"function":return Ce.function;case"bigint":return Ce.bigint;case"symbol":return Ce.symbol;case"object":return Array.isArray(e)?Ce.array:e===null?Ce.null:e.then&&typeof e.then=="function"&&e.catch&&typeof e.catch=="function"?Ce.promise:typeof Map<"u"&&e instanceof Map?Ce.map:typeof Set<"u"&&e instanceof Set?Ce.set:typeof Date<"u"&&e instanceof Date?Ce.date:Ce.object;default:return Ce.unknown}};var ye=Yt.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"]),c8r=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,Yt.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 u8r=(e,t)=>{let r;switch(e.code){case ye.invalid_type:e.received===Ce.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case ye.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,Yt.jsonStringifyReplacer)}`;break;case ye.unrecognized_keys:r=`Unrecognized key(s) in object: ${Yt.joinValues(e.keys,", ")}`;break;case ye.invalid_union:r="Invalid input";break;case ye.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Yt.joinValues(e.options)}`;break;case ye.invalid_enum_value:r=`Invalid enum value. Expected ${Yt.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}"`:Yt.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,Yt.assertNever(e)}return{message:r}},G1=u8r;var rft=G1;function d8r(e){rft=e}function fA(){return rft}var Pk=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}},l8r=[];function Ae(e,t){let r=fA(),n=Pk({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===G1?void 0:G1].filter(i=>!!i)});e.common.issues.push(n)}var ws=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 ht;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 ht;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}}},ht=Object.freeze({status:"aborted"}),Dv=e=>({status:"dirty",value:e}),ia=e=>({status:"valid",value:e}),oY=e=>e.status==="aborted",sY=e=>e.status==="dirty",r2=e=>e.status==="valid",mA=e=>typeof Promise<"u"&&e instanceof Promise;var Qe;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(Qe||(Qe={}));var Jd=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}},nft=(e,t)=>{if(r2(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 Bt(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 Ut=class{get description(){return this._def.description}_getType(t){return Sm(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:Sm(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new ws,ctx:{common:t.parent.common,data:t.data,parsedType:Sm(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(mA(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:Sm(t)},i=this._parseSync({data:t,path:n.path,parent:n});return nft(n,i)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:Sm(t)};if(!this["~standard"].async)try{let n=this._parseSync({data:t,path:[],parent:r});return r2(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=>r2(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:Sm(t)},i=this._parse({data:t,path:n.path,parent:n}),o=await(mA(i)?i:Promise.resolve(i));return nft(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 Yd({schema:this,typeName:wt.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 Gd.create(this,this._def)}nullable(){return Pm.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Z1.create(this)}promise(){return o2.create(this,this._def)}or(t){return Kv.create([this,t],this._def)}and(t){return Wv.create(this,t,this._def)}transform(t){return new Yd({...Bt(this._def),schema:this,typeName:wt.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new Xv({...Bt(this._def),innerType:this,defaultValue:r,typeName:wt.ZodDefault})}brand(){return new Ik({typeName:wt.ZodBranded,type:this,...Bt(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new Qv({...Bt(this._def),innerType:this,catchValue:r,typeName:wt.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return Ok.create(this,t)}readonly(){return e4.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},p8r=/^c[^\s-]{8,}$/i,f8r=/^[0-9a-z]+$/,m8r=/^[0-9A-HJKMNP-TV-Z]{26}$/i,h8r=/^[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,y8r=/^[a-z0-9_-]{21}$/i,g8r=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,b8r=/^[-+]?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)?)??$/,_8r=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,v8r="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",v8e,w8r=/^(?:(?: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])$/,x8r=/^(?:(?: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])$/,E8r=/^(([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]))$/,A8r=/^(([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])$/,S8r=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,T8r=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,oft="((\\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])))",P8r=new RegExp(`^${oft}$`);function sft(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 I8r(e){return new RegExp(`^${sft(e)}$`)}function aft(e){let t=`${oft}T${sft(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 O8r(e,t){return!!((t==="v4"||!t)&&w8r.test(e)||(t==="v6"||!t)&&E8r.test(e))}function C8r(e,t){if(!g8r.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 R8r(e,t){return!!((t==="v4"||!t)&&x8r.test(e)||(t==="v6"||!t)&&A8r.test(e))}var n2=class e extends Ut{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==Ce.string){let o=this._getOrReturnCtx(t);return Ae(o,{code:ye.invalid_type,expected:Ce.string,received:o.parsedType}),ht}let n=new ws,i;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(i=this._getOrReturnCtx(t,i),Ae(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),Ae(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?Ae(i,{code:ye.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&Ae(i,{code:ye.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")_8r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"email",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")v8e||(v8e=new RegExp(v8r,"u")),v8e.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"emoji",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")h8r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"uuid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")y8r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"nanoid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")p8r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"cuid",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")f8r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"cuid2",code:ye.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")m8r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(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),Ae(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),Ae(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),Ae(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),Ae(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),Ae(i,{code:ye.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?aft(o).test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{code:ye.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?P8r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{code:ye.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?I8r(o).test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{code:ye.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?b8r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"duration",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?O8r(t.data,o.version)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"ip",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?C8r(t.data,o.alg)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"jwt",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?R8r(t.data,o.version)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"cidr",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?S8r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"base64",code:ye.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?T8r.test(t.data)||(i=this._getOrReturnCtx(t,i),Ae(i,{validation:"base64url",code:ye.invalid_string,message:o.message}),n.dirty()):Yt.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,...Qe.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...Qe.errToObj(t)})}url(t){return this._addCheck({kind:"url",...Qe.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...Qe.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...Qe.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...Qe.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...Qe.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...Qe.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...Qe.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...Qe.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...Qe.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...Qe.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...Qe.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...Qe.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,...Qe.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,...Qe.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...Qe.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...Qe.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...Qe.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...Qe.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...Qe.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...Qe.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...Qe.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...Qe.errToObj(r)})}nonempty(t){return this.min(1,Qe.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}};n2.create=e=>new n2({checks:[],typeName:wt.ZodString,coerce:e?.coerce??!1,...Bt(e)});function k8r(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 zv=class e extends Ut{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)!==Ce.number){let o=this._getOrReturnCtx(t);return Ae(o,{code:ye.invalid_type,expected:Ce.number,received:o.parsedType}),ht}let n,i=new ws;for(let o of this._def.checks)o.kind==="int"?Yt.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),Ae(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),Ae(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),Ae(n,{code:ye.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?k8r(t.data,o.value)!==0&&(n=this._getOrReturnCtx(t,n),Ae(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),Ae(n,{code:ye.not_finite,message:o.message}),i.dirty()):Yt.assertNever(o);return{status:i.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,Qe.toString(r))}gt(t,r){return this.setLimit("min",t,!1,Qe.toString(r))}lte(t,r){return this.setLimit("max",t,!0,Qe.toString(r))}lt(t,r){return this.setLimit("max",t,!1,Qe.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:Qe.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:Qe.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Qe.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Qe.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Qe.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Qe.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:Qe.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:Qe.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Qe.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Qe.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"&&Yt.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)}};zv.create=e=>new zv({checks:[],typeName:wt.ZodNumber,coerce:e?.coerce||!1,...Bt(e)});var Lv=class e extends Ut{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)!==Ce.bigint)return this._getInvalidInput(t);let n,i=new ws;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),Ae(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),Ae(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),Ae(n,{code:ye.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):Yt.assertNever(o);return{status:i.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return Ae(r,{code:ye.invalid_type,expected:Ce.bigint,received:r.parsedType}),ht}gte(t,r){return this.setLimit("min",t,!0,Qe.toString(r))}gt(t,r){return this.setLimit("min",t,!1,Qe.toString(r))}lte(t,r){return this.setLimit("max",t,!0,Qe.toString(r))}lt(t,r){return this.setLimit("max",t,!1,Qe.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:Qe.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:Qe.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Qe.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Qe.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Qe.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:Qe.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}};Lv.create=e=>new Lv({checks:[],typeName:wt.ZodBigInt,coerce:e?.coerce??!1,...Bt(e)});var Hv=class extends Ut{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==Ce.boolean){let n=this._getOrReturnCtx(t);return Ae(n,{code:ye.invalid_type,expected:Ce.boolean,received:n.parsedType}),ht}return ia(t.data)}};Hv.create=e=>new Hv({typeName:wt.ZodBoolean,coerce:e?.coerce||!1,...Bt(e)});var Fv=class e extends Ut{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==Ce.date){let o=this._getOrReturnCtx(t);return Ae(o,{code:ye.invalid_type,expected:Ce.date,received:o.parsedType}),ht}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return Ae(o,{code:ye.invalid_date}),ht}let n=new ws,i;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(i=this._getOrReturnCtx(t,i),Ae(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),Ae(i,{code:ye.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):Yt.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:Qe.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:Qe.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}};Fv.create=e=>new Fv({checks:[],coerce:e?.coerce||!1,typeName:wt.ZodDate,...Bt(e)});var yA=class extends Ut{_parse(t){if(this._getType(t)!==Ce.symbol){let n=this._getOrReturnCtx(t);return Ae(n,{code:ye.invalid_type,expected:Ce.symbol,received:n.parsedType}),ht}return ia(t.data)}};yA.create=e=>new yA({typeName:wt.ZodSymbol,...Bt(e)});var $v=class extends Ut{_parse(t){if(this._getType(t)!==Ce.undefined){let n=this._getOrReturnCtx(t);return Ae(n,{code:ye.invalid_type,expected:Ce.undefined,received:n.parsedType}),ht}return ia(t.data)}};$v.create=e=>new $v({typeName:wt.ZodUndefined,...Bt(e)});var Vv=class extends Ut{_parse(t){if(this._getType(t)!==Ce.null){let n=this._getOrReturnCtx(t);return Ae(n,{code:ye.invalid_type,expected:Ce.null,received:n.parsedType}),ht}return ia(t.data)}};Vv.create=e=>new Vv({typeName:wt.ZodNull,...Bt(e)});var i2=class extends Ut{constructor(){super(...arguments),this._any=!0}_parse(t){return ia(t.data)}};i2.create=e=>new i2({typeName:wt.ZodAny,...Bt(e)});var Y1=class extends Ut{constructor(){super(...arguments),this._unknown=!0}_parse(t){return ia(t.data)}};Y1.create=e=>new Y1({typeName:wt.ZodUnknown,...Bt(e)});var bp=class extends Ut{_parse(t){let r=this._getOrReturnCtx(t);return Ae(r,{code:ye.invalid_type,expected:Ce.never,received:r.parsedType}),ht}};bp.create=e=>new bp({typeName:wt.ZodNever,...Bt(e)});var gA=class extends Ut{_parse(t){if(this._getType(t)!==Ce.undefined){let n=this._getOrReturnCtx(t);return Ae(n,{code:ye.invalid_type,expected:Ce.void,received:n.parsedType}),ht}return ia(t.data)}};gA.create=e=>new gA({typeName:wt.ZodVoid,...Bt(e)});var Z1=class e extends Ut{_parse(t){let{ctx:r,status:n}=this._processInputParams(t),i=this._def;if(r.parsedType!==Ce.array)return Ae(r,{code:ye.invalid_type,expected:Ce.array,received:r.parsedType}),ht;if(i.exactLength!==null){let s=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(s||a)&&(Ae(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&&(Ae(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&&(Ae(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 Jd(r,s,r.path,a)))).then(s=>ws.mergeArray(n,s));let o=[...r.data].map((s,a)=>i.type._parseSync(new Jd(r,s,r.path,a)));return ws.mergeArray(n,o)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:Qe.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:Qe.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:Qe.toString(r)}})}nonempty(t){return this.min(1,t)}};Z1.create=(e,t)=>new Z1({type:e,minLength:null,maxLength:null,exactLength:null,typeName:wt.ZodArray,...Bt(t)});function hA(e){if(e instanceof Mc){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=Gd.create(hA(n))}return new Mc({...e._def,shape:()=>t})}else return e instanceof Z1?new Z1({...e._def,type:hA(e.element)}):e instanceof Gd?Gd.create(hA(e.unwrap())):e instanceof Pm?Pm.create(hA(e.unwrap())):e instanceof Tm?Tm.create(e.items.map(t=>hA(t))):e}var Mc=class e extends Ut{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=Yt.objectKeys(t);return this._cached={shape:t,keys:r},this._cached}_parse(t){if(this._getType(t)!==Ce.object){let u=this._getOrReturnCtx(t);return Ae(u,{code:ye.invalid_type,expected:Ce.object,received:u.parsedType}),ht}let{status:n,ctx:i}=this._processInputParams(t),{shape:o,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof bp&&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 Jd(i,l,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof bp){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&&(Ae(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 Jd(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=>ws.mergeObjectSync(n,u)):ws.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(t){return Qe.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:Qe.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:wt.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 Yt.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 Yt.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}deepPartial(){return hA(this)}partial(t){let r={};for(let n of Yt.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 Yt.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof Gd;)o=o._def.innerType;r[n]=o}return new e({...this._def,shape:()=>r})}keyof(){return cft(Yt.objectKeys(this.shape))}};Mc.create=(e,t)=>new Mc({shape:()=>e,unknownKeys:"strip",catchall:bp.create(),typeName:wt.ZodObject,...Bt(t)});Mc.strictCreate=(e,t)=>new Mc({shape:()=>e,unknownKeys:"strict",catchall:bp.create(),typeName:wt.ZodObject,...Bt(t)});Mc.lazycreate=(e,t)=>new Mc({shape:e,unknownKeys:"strip",catchall:bp.create(),typeName:wt.ZodObject,...Bt(t)});var Kv=class extends Ut{_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 Ae(r,{code:ye.invalid_union,unionErrors:s}),ht}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 Ae(r,{code:ye.invalid_union,unionErrors:a}),ht}}get options(){return this._def.options}};Kv.create=(e,t)=>new Kv({options:e,typeName:wt.ZodUnion,...Bt(t)});var J1=e=>e instanceof Gv?J1(e.schema):e instanceof Yd?J1(e.innerType()):e instanceof Jv?[e.value]:e instanceof Yv?e.options:e instanceof Zv?Yt.objectValues(e.enum):e instanceof Xv?J1(e._def.innerType):e instanceof $v?[void 0]:e instanceof Vv?[null]:e instanceof Gd?[void 0,...J1(e.unwrap())]:e instanceof Pm?[null,...J1(e.unwrap())]:e instanceof Ik||e instanceof e4?J1(e.unwrap()):e instanceof Qv?J1(e._def.innerType):[],aY=class e extends Ut{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Ce.object)return Ae(r,{code:ye.invalid_type,expected:Ce.object,received:r.parsedType}),ht;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}):(Ae(r,{code:ye.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),ht)}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=J1(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:wt.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:i,...Bt(n)})}};function w8e(e,t){let r=Sm(e),n=Sm(t);if(e===t)return{valid:!0,data:e};if(r===Ce.object&&n===Ce.object){let i=Yt.objectKeys(t),o=Yt.objectKeys(e).filter(a=>i.indexOf(a)!==-1),s={...e,...t};for(let a of o){let c=w8e(e[a],t[a]);if(!c.valid)return{valid:!1};s[a]=c.data}return{valid:!0,data:s}}else if(r===Ce.array&&n===Ce.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=w8e(s,a);if(!c.valid)return{valid:!1};i.push(c.data)}return{valid:!0,data:i}}else return r===Ce.date&&n===Ce.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var Wv=class extends Ut{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=(o,s)=>{if(oY(o)||oY(s))return ht;let a=w8e(o.value,s.value);return a.valid?((sY(o)||sY(s))&&r.dirty(),{status:r.value,value:a.data}):(Ae(n,{code:ye.invalid_intersection_types}),ht)};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}))}};Wv.create=(e,t,r)=>new Wv({left:e,right:t,typeName:wt.ZodIntersection,...Bt(r)});var Tm=class e extends Ut{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Ce.array)return Ae(n,{code:ye.invalid_type,expected:Ce.array,received:n.parsedType}),ht;if(n.data.length<this._def.items.length)return Ae(n,{code:ye.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ht;!this._def.rest&&n.data.length>this._def.items.length&&(Ae(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 Jd(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>ws.mergeArray(r,s)):ws.mergeArray(r,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Tm.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new Tm({items:e,typeName:wt.ZodTuple,rest:null,...Bt(t)})};var cY=class e extends Ut{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!==Ce.object)return Ae(n,{code:ye.invalid_type,expected:Ce.object,received:n.parsedType}),ht;let i=[],o=this._def.keyType,s=this._def.valueType;for(let a in n.data)i.push({key:o._parse(new Jd(n,a,n.path,a)),value:s._parse(new Jd(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?ws.mergeObjectAsync(r,i):ws.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof Ut?new e({keyType:t,valueType:r,typeName:wt.ZodRecord,...Bt(n)}):new e({keyType:n2.create(),valueType:t,typeName:wt.ZodRecord,...Bt(r)})}},bA=class extends Ut{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!==Ce.map)return Ae(n,{code:ye.invalid_type,expected:Ce.map,received:n.parsedType}),ht;let i=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([a,c],u)=>({key:i._parse(new Jd(n,a,n.path,[u,"key"])),value:o._parse(new Jd(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 ht;(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 ht;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}}}};bA.create=(e,t,r)=>new bA({valueType:t,keyType:e,typeName:wt.ZodMap,...Bt(r)});var _A=class e extends Ut{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Ce.set)return Ae(n,{code:ye.invalid_type,expected:Ce.set,received:n.parsedType}),ht;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(Ae(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&&(Ae(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 ht;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 Jd(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:Qe.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:Qe.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};_A.create=(e,t)=>new _A({valueType:e,minSize:null,maxSize:null,typeName:wt.ZodSet,...Bt(t)});var uY=class e extends Ut{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Ce.function)return Ae(r,{code:ye.invalid_type,expected:Ce.function,received:r.parsedType}),ht;function n(a,c){return Pk({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,fA(),G1].filter(u=>!!u),issueData:{code:ye.invalid_arguments,argumentsError:c}})}function i(a,c){return Pk({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,fA(),G1].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 o2){let a=this;return ia(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 ia(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:Tm.create(t).rest(Y1.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||Tm.create([]).rest(Y1.create()),returns:r||Y1.create(),typeName:wt.ZodFunction,...Bt(n)})}},Gv=class extends Ut{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})}};Gv.create=(e,t)=>new Gv({getter:e,typeName:wt.ZodLazy,...Bt(t)});var Jv=class extends Ut{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return Ae(r,{received:r.data,code:ye.invalid_literal,expected:this._def.value}),ht}return{status:"valid",value:t.data}}get value(){return this._def.value}};Jv.create=(e,t)=>new Jv({value:e,typeName:wt.ZodLiteral,...Bt(t)});function cft(e,t){return new Yv({values:e,typeName:wt.ZodEnum,...Bt(t)})}var Yv=class e extends Ut{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return Ae(r,{expected:Yt.joinValues(n),received:r.parsedType,code:ye.invalid_type}),ht}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 Ae(r,{received:r.data,code:ye.invalid_enum_value,options:n}),ht}return ia(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})}};Yv.create=cft;var Zv=class extends Ut{_parse(t){let r=Yt.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==Ce.string&&n.parsedType!==Ce.number){let i=Yt.objectValues(r);return Ae(n,{expected:Yt.joinValues(i),received:n.parsedType,code:ye.invalid_type}),ht}if(this._cache||(this._cache=new Set(Yt.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=Yt.objectValues(r);return Ae(n,{received:n.data,code:ye.invalid_enum_value,options:i}),ht}return ia(t.data)}get enum(){return this._def.values}};Zv.create=(e,t)=>new Zv({values:e,typeName:wt.ZodNativeEnum,...Bt(t)});var o2=class extends Ut{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Ce.promise&&r.common.async===!1)return Ae(r,{code:ye.invalid_type,expected:Ce.promise,received:r.parsedType}),ht;let n=r.parsedType===Ce.promise?r.data:Promise.resolve(r.data);return ia(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};o2.create=(e,t)=>new o2({type:e,typeName:wt.ZodPromise,...Bt(t)});var Yd=class extends Ut{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===wt.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=>{Ae(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 ht;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?ht:c.status==="dirty"?Dv(c.value):r.value==="dirty"?Dv(c.value):c});{if(r.value==="aborted")return ht;let a=this._def.schema._parseSync({data:s,path:n.path,parent:n});return a.status==="aborted"?ht:a.status==="dirty"?Dv(a.value):r.value==="dirty"?Dv(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"?ht:(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"?ht:(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(!r2(s))return ht;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=>r2(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:r.value,value:a})):ht);Yt.assertNever(i)}};Yd.create=(e,t,r)=>new Yd({schema:e,typeName:wt.ZodEffects,effect:t,...Bt(r)});Yd.createWithPreprocess=(e,t,r)=>new Yd({schema:t,effect:{type:"preprocess",transform:e},typeName:wt.ZodEffects,...Bt(r)});var Gd=class extends Ut{_parse(t){return this._getType(t)===Ce.undefined?ia(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Gd.create=(e,t)=>new Gd({innerType:e,typeName:wt.ZodOptional,...Bt(t)});var Pm=class extends Ut{_parse(t){return this._getType(t)===Ce.null?ia(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Pm.create=(e,t)=>new Pm({innerType:e,typeName:wt.ZodNullable,...Bt(t)});var Xv=class extends Ut{_parse(t){let{ctx:r}=this._processInputParams(t),n=r.data;return r.parsedType===Ce.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Xv.create=(e,t)=>new Xv({innerType:e,typeName:wt.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Bt(t)});var Qv=class extends Ut{_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 mA(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}};Qv.create=(e,t)=>new Qv({innerType:e,typeName:wt.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Bt(t)});var vA=class extends Ut{_parse(t){if(this._getType(t)!==Ce.nan){let n=this._getOrReturnCtx(t);return Ae(n,{code:ye.invalid_type,expected:Ce.nan,received:n.parsedType}),ht}return{status:"valid",value:t.data}}};vA.create=e=>new vA({typeName:wt.ZodNaN,...Bt(e)});var B8r=Symbol("zod_brand"),Ik=class extends Ut{_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}},Ok=class e extends Ut{_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"?ht:o.status==="dirty"?(r.dirty(),Dv(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"?ht: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:wt.ZodPipeline})}},e4=class extends Ut{_parse(t){let r=this._def.innerType._parse(t),n=i=>(r2(i)&&(i.value=Object.freeze(i.value)),i);return mA(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};e4.create=(e,t)=>new e4({innerType:e,typeName:wt.ZodReadonly,...Bt(t)});function ift(e,t){let r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function uft(e,t={},r){return e?i2.create().superRefine((n,i)=>{let o=e(n);if(o instanceof Promise)return o.then(s=>{if(!s){let a=ift(t,n),c=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:c})}});if(!o){let s=ift(t,n),a=s.fatal??r??!0;i.addIssue({code:"custom",...s,fatal:a})}}):i2.create()}var N8r={object:Mc.lazycreate},wt;(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"})(wt||(wt={}));var j8r=(e,t={message:`Input not instance of ${e.name}`})=>uft(r=>r instanceof e,t),z=n2.create,Ir=zv.create,q8r=vA.create,U8r=Lv.create,Zd=Hv.create,M8r=Fv.create,D8r=yA.create,z8r=$v.create,wA=Vv.create,Xd=i2.create,L8r=Y1.create,H8r=bp.create,F8r=gA.create,ue=Z1.create,fe=Mc.create,$8r=Mc.strictCreate,xA=Kv.create,V8r=aY.create,K8r=Wv.create,W8r=Tm.create,Zt=cY.create,G8r=bA.create,J8r=_A.create,Y8r=uY.create,Z8r=Gv.create,X8r=Jv.create,Qd=Yv.create,Q8r=Zv.create,e3r=o2.create,t3r=Yd.create,r3r=Gd.create,n3r=Pm.create,i3r=Yd.createWithPreprocess,o3r=Ok.create,s3r=()=>z().optional(),a3r=()=>Ir().optional(),c3r=()=>Zd().optional(),Nu={string:(e=>n2.create({...e,coerce:!0})),number:(e=>zv.create({...e,coerce:!0})),boolean:(e=>Hv.create({...e,coerce:!0})),bigint:(e=>Lv.create({...e,coerce:!0})),date:(e=>Fv.create({...e,coerce:!0}))};var u3r=ht;var l3r=Qd(["enc","sig"]),p3r=Qd(["markdown","plain"]),f3r=Qd(["recoverable","requires_buyer_input","requires_buyer_review","unrecoverable"]),m3r=Qd(["error","info","warning"]),SA=Qd(["canceled","complete_in_progress","completed","incomplete","ready_for_complete","requires_escalation"]),h3r=Qd(["completed","failed","pending"]),y3r=Qd(["digital","pickup","shipping"]),g3r=Qd(["fulfilled","partial","processing","removed"]),b3r=Qd(["across","each"]),x8e=Qd(["pickup","shipping"]),_3r=fe({config:Zt(z(),Xd()),config_schema:z(),id:z(),instrument_schemas:ue(z()),name:z(),spec:z(),version:z()}),v3r=fe({alg:z().optional(),crv:z().optional(),e:z().optional(),kid:z(),kty:z(),n:z().optional(),use:l3r.optional(),x:z().optional(),y:z().optional()}),w3r=fe({config:Zt(z(),Xd()).optional(),extends:z().optional(),name:z(),schema:z(),spec:z(),version:z()}),x3r=fe({endpoint:z()}),E3r=fe({schema:z()}),dft=fe({endpoint:z(),schema:z()}),A3r=dft,S3r=dft,qa=fe({email:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional()}),uo=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()}),E8e=uo,lft=fe({id:z()}),T3r=lft,P3r=lft,Ck=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()}),dY=fe({type:z()}),Ki=fe({"dev.ucp.buyer_ip":z().optional(),"dev.ucp.user_agent":z().optional()}),A8e=Ki,pft=fe({id:z(),image_url:z().optional(),price:Ir(),title:z()}),lY=fe({amount:Ir(),display_text:z().optional(),type:z()}),s2=fe({title:z().optional(),type:z(),url:z()}),X1=fe({code:z().optional(),content:z(),content_type:p3r.optional(),path:z().optional(),severity:f3r.optional(),type:m3r,image_url:z().optional(),presentation:z().optional(),url:z().optional()}),S8e=X1,TA=fe({id:z(),label:z().optional(),permalink_url:z()}),I3r=fe({amount:Ir(),display_text:z()}),O3r=fe({config:Zt(z(),Xd()).optional(),extends:z().optional(),name:z(),schema:z().optional(),spec:z().optional(),version:z()}),T8e=fe({id:z(),quantity:Ir()}),C3r=T8e,R3r=T8e,k3r=T8e,B3r=fe({fulfilled:Ir(),original:Ir().optional(),total:Ir()}),N3r=fe({billing_address:Ck.optional(),credential:dY.optional(),display:Zt(z(),Xd()).optional(),handler_id:z(),id:z(),type:z()}),j3r=fe({checkout_mandate:z()}),q3r=fe({merchant_authorization:z().optional(),checkout_mandate:z()}),U3r=fe({analytics:Zd().optional(),marketing:Zd().optional(),preferences:Zd().optional(),sale_of_data:Zd().optional()});var M3r=U3r;var fft=fe({codes:ue(z()).optional()}),D3r=fft,z3r=fe({amount:Ir(),path:z()}),L3r=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:Ck.optional(),name:z().optional()}),H3r=fe({carrier:z().optional(),description:z().optional(),earliest_fulfillment_time:Nu.date().optional(),id:z(),latest_fulfillment_time:Nu.date().optional(),title:z(),totals:ue(lY)}),F3r=fe({description:z().optional(),fulfillable_on:xA([wA(),z()]).optional(),line_item_ids:ue(z()),type:x8e}),$3r=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:Ck.optional(),name:z().optional()}),V3r=fe({max:Ir().optional(),min:Ir().optional()}),Rk=fe({taxonomy:z().optional(),value:z()}),kk=fe({html:z().optional(),markdown:z().optional(),plain:z().optional()}),EA=fe({amount:Ir(),currency:z()}),Bk=fe({alt_text:z().optional(),height:Ir().optional(),type:z(),url:z(),width:Ir().optional()}),K3r=fe({id:z().optional(),label:z()}),Nk=fe({count:Ir().optional(),scale_max:Ir(),scale_min:Ir().optional(),value:Ir()}),mft=fe({available:Zd().optional(),status:z().optional()}),W3r=mft,hft=fe({type:z(),value:z()}),G3r=hft,J3r=fe({id:z(),match:z().optional()}),P8e=fe({id:z().optional(),label:z(),name:z()}),yft=P8e,gft=fe({links:ue(s2).optional(),name:z().optional()}),Y3r=gft,bft=fe({unit:z(),value:Ir()});var Z3r=bft,X3r=fe({cursor:z().optional(),limit:Ir().optional()}),Q3r=fe({cursor:z().optional(),has_next_page:Zd(),total_count:Ir().optional()}),e9r=fe({handlers:ue(_3r).optional()}),t9r=fe({a2a:x3r.optional(),embedded:E3r.optional(),mcp:A3r.optional(),rest:S3r.optional(),spec:z(),version:z()}),PA=fe({item:T3r,quantity:Ir()}),r9r=fe({billing_address:Ck.optional(),credential:dY.optional(),display:Zt(z(),Xd()).optional(),handler_id:z(),id:z(),type:z(),selected:Zd().optional()}),jk=fe({id:z().optional(),item:P3r,parent_id:z().optional(),quantity:Ir()}),pY=fe({instruments:ue(r9r).optional()}),n9r=pY,qk=pY,IA=pY,fY=pY,t4=fe({id:z(),item:pft,parent_id:z().optional(),quantity:Ir(),totals:ue(lY)}),a2=fe({amount:Ir(),display_text:z().optional(),type:z(),lines:ue(I3r).optional()}),_p=fe({capabilities:Zt(z(),ue(O3r)),version:z()}),i9r=fe({description:z().optional(),id:z(),line_items:ue(C3r).optional(),occurred_at:Nu.date(),status:h3r,totals:ue(lY).optional(),type:z()}),o9r=fe({carrier:z().optional(),description:z().optional(),id:z(),line_items:ue(R3r),occurred_at:Nu.date(),tracking_number:z().optional(),tracking_url:z().optional(),type:z()}),s9r=fe({description:z().optional(),destination:Ck,fulfillable_on:z().optional(),id:z(),line_items:ue(k3r),method_type:y3r}),a9r=fe({id:z(),item:pft,parent_id:z().optional(),quantity:B3r,status:g3r,totals:ue(lY)}),o4n=fe({payment_data:N3r}),s4n=fe({ap2:j3r.optional()}),a4n=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),continue_url:z().optional(),currency:z(),expires_at:Nu.date().optional(),id:z(),line_items:ue(t4),links:ue(s2),messages:ue(X1).optional(),order:TA.optional(),payment:IA.optional(),signals:Ki.optional(),status:SA,totals:ue(a2),ucp:_p,ap2:q3r.optional()}),I8e=fe({email:z().optional(),first_name:z().optional(),last_name:z().optional(),phone_number:z().optional(),consent:M3r.optional()}),c9r=I8e,u9r=I8e,_ft=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),line_items:ue(jk),payment:fY.optional(),signals:Ki.optional(),discounts:D3r.optional()}),d9r=fe({allocations:ue(z3r).optional(),amount:Ir(),automatic:Zd().optional(),code:z().optional(),eligibility:z().optional(),method:b3r.optional(),priority:Ir().optional(),provisional:Zd().optional(),title:z()}),vft=fe({id:z(),line_item_ids:ue(z()),options:ue(H3r).optional(),selected_option_id:xA([wA(),z()]).optional()}),l9r=fe({destinations:ue($3r).optional(),groups:ue(vft).optional(),id:z(),line_item_ids:ue(z()),selected_destination_id:xA([wA(),z()]).optional(),type:x8e}),c4n=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),line_items:ue(PA),signals:Ki.optional()}),u4n=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),id:z(),line_items:ue(jk),signals:Ki.optional()}),d4n=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),continue_url:z().optional(),currency:z(),expires_at:Nu.date().optional(),id:z(),line_items:ue(t4),links:ue(s2).optional(),messages:ue(X1).optional(),signals:Ki.optional(),totals:ue(a2),ucp:_p}),p9r=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),line_items:ue(jk),payment:fY.optional(),signals:Ki.optional()}),wft=p9r,l4n=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),continue_url:z().optional(),currency:z(),expires_at:Nu.date().optional(),id:z(),line_items:ue(t4),links:ue(s2),messages:ue(X1).optional(),order:TA.optional(),payment:IA.optional(),signals:Ki.optional(),status:SA,totals:ue(a2),ucp:_p,cart_id:z().optional()}),O8e=fe({categories:ue(z()).optional(),price:V3r.optional()}),AA=fe({max:EA,min:EA}),C8e=fe({name:z(),values:ue(K3r)}),xft=fe({amount:Ir(),currency:z(),measure:bft,reference:Z3r}),f9r=xft,p4n=fe({attribution:Zt(z(),z()).optional(),context:E8e.optional(),filters:O8e.optional(),id:z(),preferences:ue(z()).optional(),selected:ue(yft).optional(),signals:A8e.optional()}),f4n=fe({attribution:Zt(z(),z()).optional(),context:E8e.optional(),filters:O8e.optional(),pagination:X3r.optional(),query:z().optional(),signals:A8e.optional()}),m9r=fe({capabilities:ue(w3r),services:Zt(z(),t9r),version:z()}),m4n=fe({attribution:Zt(z(),z()).optional(),payment:n9r,signals:Ki.optional()}),Eft=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),continue_url:z().optional(),currency:z(),expires_at:Nu.date().optional(),id:z(),line_items:ue(t4),links:ue(s2),messages:ue(X1).optional(),order:TA.optional(),payment:IA.optional(),signals:Ki.optional(),status:SA,totals:ue(a2),ucp:_p}),h9r=fe({events:ue(o9r).optional(),expectations:ue(s9r).optional()}),Aft=fe({attribution:Zt(z(),z()).optional(),buyer:I8e.optional(),context:uo.optional(),line_items:ue(PA),payment:qk.optional(),signals:Ki.optional()}),Sft=fe({attribution:Zt(z(),z()).optional(),buyer:u9r.optional(),context:uo.optional(),line_items:ue(jk),payment:fY.optional(),signals:Ki.optional()}),Tft=fe({attribution:Zt(z(),z()).optional(),buyer:c9r.optional(),context:uo.optional(),continue_url:z().optional(),currency:z(),expires_at:Nu.date().optional(),id:z(),line_items:ue(t4),links:ue(s2),messages:ue(X1).optional(),order:TA.optional(),payment:IA.optional(),signals:Ki.optional(),status:SA,totals:ue(a2),ucp:_p}),Pft=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),line_items:ue(PA),payment:qk.optional(),signals:Ki.optional(),discounts:fft.optional()}),y9r=fe({applied:ue(d9r).optional(),codes:ue(z()).optional()}),g9r=fe({destinations:ue(L3r).optional(),groups:ue(vft).optional(),line_item_ids:ue(z()).optional(),selected_destination_id:xA([wA(),z()]).optional(),type:x8e}),b9r=fe({available_methods:ue(F3r).optional(),methods:ue(l9r).optional()}),Ift=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),line_items:ue(PA),payment:qk.optional(),signals:Ki.optional(),cart_id:z().optional()}),h4n=fe({attribution:Zt(z(),z()).optional(),context:E8e.optional(),filters:O8e.optional(),ids:ue(z()),signals:A8e.optional()}),_9r=fe({availability:mft.optional(),barcodes:ue(hft).optional(),categories:ue(Rk).optional(),description:kk,handle:z().optional(),id:z(),list_price:EA.optional(),media:ue(Bk).optional(),metadata:Zt(z(),Xd()).optional(),options:ue(P8e).optional(),price:EA,rating:Nk.optional(),seller:gft.optional(),sku:z().optional(),tags:ue(z()).optional(),title:z(),unit_price:xft.optional(),url:z().optional(),inputs:ue(J3r)}),Oft=fe({availability:W3r.optional(),barcodes:ue(G3r).optional(),categories:ue(Rk).optional(),description:kk,handle:z().optional(),id:z(),list_price:EA.optional(),media:ue(Bk).optional(),metadata:Zt(z(),Xd()).optional(),options:ue(P8e).optional(),price:EA,rating:Nk.optional(),seller:Y3r.optional(),sku:z().optional(),tags:ue(z()).optional(),title:z(),unit_price:f9r.optional(),url:z().optional()}),v9r=fe({categories:ue(Rk).optional(),description:kk,handle:z().optional(),id:z(),list_price_range:AA.optional(),media:ue(Bk).optional(),metadata:Zt(z(),Xd()).optional(),options:ue(C8e).optional(),price_range:AA,rating:Nk.optional(),tags:ue(z()).optional(),title:z(),url:z().optional(),variants:ue(Oft)}),y4n=fe({payment:e9r.optional(),signing_keys:ue(v3r).optional(),ucp:m9r}),Cft=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),line_items:ue(PA),payment:qk.optional(),signals:Ki.optional()}),w9r=fe({adjustments:ue(i9r).optional(),attribution:Zt(z(),z()).optional(),checkout_id:z(),currency:z(),fulfillment:h9r,id:z(),label:z().optional(),line_items:ue(a9r),messages:ue(X1).optional(),permalink_url:z(),totals:ue(a2),ucp:_p}),Rft=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),continue_url:z().optional(),currency:z(),expires_at:Nu.date().optional(),id:z(),line_items:ue(t4),links:ue(s2),messages:ue(X1).optional(),order:TA.optional(),payment:IA.optional(),signals:Ki.optional(),status:SA,totals:ue(a2),ucp:_p,discounts:y9r.optional()}),kft=fe({methods:ue(g9r).optional()}),Bft=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),line_items:ue(jk),payment:fY.optional(),signals:Ki.optional(),fulfillment:kft.optional()}),Nft=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),continue_url:z().optional(),currency:z(),expires_at:Nu.date().optional(),id:z(),line_items:ue(t4),links:ue(s2),messages:ue(X1).optional(),order:TA.optional(),payment:IA.optional(),signals:Ki.optional(),status:SA,totals:ue(a2),ucp:_p,fulfillment:b9r.optional()}),x9r=fe({categories:ue(Rk).optional(),description:kk,handle:z().optional(),id:z(),list_price_range:AA.optional(),media:ue(Bk).optional(),metadata:Zt(z(),Xd()).optional(),options:ue(C8e).optional(),price_range:AA,rating:Nk.optional(),tags:ue(z()).optional(),title:z(),url:z().optional(),variants:ue(_9r)}),E9r=fe({options:ue(C8e).optional(),selected:ue(yft).optional(),categories:ue(Rk).optional(),description:kk,handle:z().optional(),id:z(),list_price_range:AA.optional(),media:ue(Bk).optional(),metadata:Zt(z(),Xd()).optional(),price_range:AA,rating:Nk.optional(),tags:ue(z()).optional(),title:z(),url:z().optional(),variants:ue(Oft)}),g4n=fe({messages:ue(S8e).optional(),pagination:Q3r.optional(),products:ue(v9r),ucp:_p}),jft=fe({attribution:Zt(z(),z()).optional(),buyer:qa.optional(),context:uo.optional(),line_items:ue(PA),payment:qk.optional(),signals:Ki.optional(),fulfillment:kft.optional()}),b4n=fe({messages:ue(S8e).optional(),products:ue(x9r),ucp:_p}),_4n=fe({messages:ue(S8e).optional(),product:E9r,ucp:_p});var E4n=dY.extend({token:jr.string().optional()}),A9r=jr.object({webhook_url:jr.string().url().optional()}),qft=Eft.extend(Nft.pick({fulfillment:!0}).shape).extend(Rft.pick({discounts:!0}).shape).extend(Tft.pick({buyer:!0}).shape).extend({platform:A9r.optional()}),Uft=Cft.extend(jft.pick({fulfillment:!0}).shape).extend(Pft.pick({discounts:!0}).shape).extend(Aft.pick({buyer:!0}).shape).extend(Ift.pick({cart_id:!0}).shape),Mft=wft.extend(Bft.pick({fulfillment:!0}).shape).extend(_ft.pick({discounts:!0}).shape).extend(Sft.pick({buyer:!0}).shape);Dc();async function mY(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 hY(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 S9r=3e4,Dft=2*1024*1024,vp=class extends Error{constructor(r,n,i){super(r);this.rpcCode=n;this.httpStatus=i;this.name="UcpRpcError"}rpcCode;httpStatus};function zft(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 Lft(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"?Uft:Mft).safeParse(e).success)throw new Error(`UCP ${t} checkout input failed schema validation`);return e}function T9r(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 Hft(e,t,r,n){try{e[t](r,n)}catch{}}function P9r(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 yY=class{endpoint;platformProfileUrl;fetchImpl;signal;timeoutMs;boundaryLogger;requestId=1;constructor(t){this.endpoint=zft(t.endpoint,"UCP MCP endpoint").toString(),this.platformProfileUrl=zft(t.platformProfileUrl,"UCP platform profile URL").toString(),this.fetchImpl=t.fetch??fetch,this.signal=t.signal,this.timeoutMs=t.timeoutMs??S9r,this.boundaryLogger=t.logger??Be}async createCheckout(t){return await this.callCheckout("create_checkout",{meta:this.metadata(),checkout:Lft(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:Lft(r,"update")})}metadata(){return{"ucp-agent":{profile:this.platformProfileUrl}}}async callCheckout(t,r){let n=this.requestId++,i=hY(this.timeoutMs,this.signal),o=(0,Fft.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 mY(u,Dft,"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 vp(m.message,void 0,u.status):m}if(Buffer.byteLength(d)>Dft)throw new vp("UCP MCP response exceeds the 2 MiB limit",void 0,u.status);let l;try{l=JSON.parse(d)}catch{throw new vp("UCP MCP response is not valid JSON",void 0,u.status)}if(!T9r(l))throw new vp("UCP MCP response is not a valid JSON-RPC envelope",void 0,u.status);if(l.id!==n)throw new vp("UCP MCP response id does not match the request",void 0,u.status);if("error"in l)throw new vp(`UCP MCP error ${l.error.code}: ${l.error.message}`,l.error.code,u.status);if(!u.ok)throw new vp(`UCP MCP request failed with HTTP ${u.status}`,void 0,u.status);let p=l.result;if(!p?.structuredContent)throw new vp("UCP MCP response is missing result.structuredContent");if(!qft.safeParse(P9r(p.structuredContent)).success)throw new vp("UCP checkout response failed schema validation");return Hft(this.boundaryLogger,"info","ucp:checkout_rpc",{correlationId:o,endpointOrigin:s,rpcMethod:t,httpStatus:c,elapsedMs:Date.now()-a}),p.structuredContent}catch(u){throw Hft(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 Vft=require("node:crypto");Dc();var bY="2026-04-08",I9r="dev.ucp.shopping",O9r="dev.ucp.shopping.checkout",C9r=1024*1024,R9r=1e4,k9r="https://ucp.dev",Uk=jr.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"),B9r=jr.object({version:jr.string().regex(/^\d{4}-\d{2}-\d{2}$/),spec:Uk,schema:Uk,transport:jr.enum(["rest","mcp","a2a","embedded"]),endpoint:Uk.optional()}).passthrough(),N9r=jr.object({version:jr.string().regex(/^\d{4}-\d{2}-\d{2}$/),spec:Uk,schema:Uk,extends:jr.union([jr.string(),jr.array(jr.string()).min(1)]).optional()}).passthrough(),j9r=jr.object({ucp:jr.object({version:jr.string().regex(/^\d{4}-\d{2}-\d{2}$/),services:jr.record(jr.array(B9r)),capabilities:jr.record(jr.array(N9r)),payment_handlers:jr.record(jr.array(jr.unknown())).optional()}).passthrough(),signing_keys:jr.array(jr.unknown()).optional()}).passthrough();function q9r(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 gY(e,t){if(new URL(e).origin!==k9r)throw new Error(`${t} must be governed by the ucp.dev namespace`)}function $ft(e,t,r,n){try{e[t](r,n)}catch{}}async function U9r(e,t={}){let r=q9r(e,"UCP business URL"),n=hY(t.timeoutMs??R9r,t.signal),i=t.logger??Be,o=(0,Vft.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 mY(c,C9r,"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=j9r.safeParse(d);if(!l.success)throw new Error("UCP profile response does not match the 2026-04-08 profile shape");return $ft(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 $ft(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 M9r(e){if(e.ucp.version!==bY)throw new Error(`Unsupported UCP version: ${e.ucp.version}`);let t=e.ucp.capabilities[O9r]?.find(i=>i.version===bY);if(!t)throw new Error("Business does not advertise UCP checkout 2026-04-08");gY(t.spec,"Checkout capability spec"),gY(t.schema,"Checkout capability schema");let r=e.ucp.services[I9r]?.find(i=>i.version===bY&&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");gY(r.spec,"Shopping service spec"),gY(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 Kft(e,t={}){let r=await U9r(e,t);return{...r,endpoint:M9r(r.profile),version:bY}}var D9r="https://app.visacli.sh/.well-known/ucp";function z9r(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 L9r(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 R8e(e,t=new Set){if(Array.isArray(e))for(let r of e)R8e(r,t);else if(e&&typeof e=="object")for(let[r,n]of Object.entries(e))r==="endpoint"?L9r(n,t):R8e(n,t);return t}function H9r(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=R8e(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 F9r(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 $9r(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 Gft(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??Kft)(e.business),i=await(t.getCheckout??(async(u,d)=>await new yY({endpoint:u.endpoint,platformProfileUrl:z9r(t.platformProfileUrl??process.env.VISA_UCP_PROFILE_URL??D9r)}).getCheckout(d)))(r,e.checkoutId);if(i.id!==e.checkoutId)throw new Error("UCP checkout response id does not match the requested checkout");let o=String(i.status??"unknown");if(o==="completed")return{success:!1,status:"not_ready",checkoutId:e.checkoutId,checkoutStatus:o,reason:"checkout_already_completed"};if(o!=="requires_escalation")return{success:!1,status:"not_ready",checkoutId:e.checkoutId,checkoutStatus:o,reason:"checkout_not_escalated"};if(typeof i.continue_url!="string"||!i.continue_url)return{success:!1,status:"not_ready",checkoutId:e.checkoutId,checkoutStatus:o,reason:"missing_continue_url"};let s=F9r(i),a=H9r(r.businessOrigin,i.continue_url,r.profile),c=`ucp_${(0,Wft.createHash)("sha256").update([r.businessOrigin,e.checkoutId,o,s.currency,String(s.minor),a.url].join("\0")).digest("hex").slice(0,24)}`;return{success:!0,status:"ready_for_review",checkoutId:e.checkoutId,handoffId:c,checkoutStatus:"requires_escalation",amount:s,merchant:{businessOrigin:r.businessOrigin,sourceHost:a.sourceHost,targetHost:a.targetHost,originRewritten:a.originRewritten},payMerchantRequest:{action:"review",url:a.url,amount:s.decimal,currency:s.currency},messages:$9r(i),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>."}}a4();function V9r(){return ju()}var Qs=new Gk(()=>Uu.getSessionToken()),K9r="4.1.0-rc.34",rwn=["","","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(`
20778
+ `);function W9r(e){if(!e||typeof e!="string")return{opened:!1,blockedReason:"invalid_url"};let t=qA(e);if(!t)return{opened:!1,blockedReason:"invalid_url"};if(t3e())return{opened:!1,url:t,blockedReason:"suppressed"};let r=jA();if(r.headless)return Be.info(`Browser auto-open skipped (${r.reason}). URL: ${t}`),{opened:!1,url:t,blockedReason:"headless"};let i=[V9r(),rl()].filter(s=>!!s).map(s=>B3e(t,s)).find(Boolean)??null;if(!i)return Be.info(`Browser auto-open skipped (non-internal host). URL: ${t}`),{opened:!1,url:t,blockedReason:"non_internal_host"};let o=iB(i);return o?((0,Yft.execFile)(o.cmd,o.args,s=>{s&&Be.warn(`Browser open failed: ${s.message}. URL: ${i}`)}),{opened:!0,url:i}):(Be.info(`No browser command for platform "${vY.platform()}". URL: ${i}`),{opened:!1,url:i,blockedReason:"unsupported_platform"})}function G9r(){let e=!1,t;try{let n=Zft.join(vY.homedir(),".claude","settings.json");if(_Y.existsSync(n)){let i=JSON.parse(_Y.readFileSync(n,"utf-8")),o=typeof i.statusLine=="object"?i.statusLine.command:"";e=xdt(o)}}catch{}let r=TJ();return r||(t="visa-cli config hud enable"),{statusLine:e,shellHud:r,...t?{shellHudSetup:t}:{}}}async function J9r(e){let t=await Qs.getStatus(e);return t.hud=G9r(),!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=K9r,t}async function Y9r(e,t){return await Qs.feedback(e.message,e.transaction_id,t)}async function Z9r(e){let t=await Adt({api:Qs,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 k8e=new Set(["auth.serverUrl"]);function Mk(){return Object.keys(RA).filter(e=>!k8e.has(e)).sort()}function Xft(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:Mk()}}async function X9r(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(k8e.has(e.key))return Be.warn("config:set:rejected:mcp-forbidden",{key:e.key}),Xft(e.key,"set");Be.info("config:set",{key:e.key});try{let t=Q8e(e.key,e.value);return Be.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 Om?"UNKNOWN_KEY":"INVALID_VALUE",n=t instanceof Om?`Unknown setting "${e.key}". MCP-settable keys: ${Mk().join(", ")}. For auth.serverUrl, use the shell command instead.`:t.message;return Be.warn("config:set:rejected",{key:e.key,code:r,error:n}),{success:!1,error:n,code:r,settableKeys:Mk()}}}async function Q9r(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(k8e.has(e.key))return Be.warn("config:unset:rejected:mcp-forbidden",{key:e.key}),Xft(e.key,"unset");Be.info("config:unset",{key:e.key});try{let t=e3e(e.key);return Be.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 Om?"UNKNOWN_KEY":"INVALID_VALUE",n=t instanceof Om?`Unknown setting "${e.key}". MCP-settable keys: ${Mk().join(", ")}. For auth.serverUrl, use the shell command instead.`:t.message;return Be.warn("config:unset:rejected",{key:e.key,code:r,error:n}),{success:!1,error:n,code:r,settableKeys:Mk()}}}async function exr(e=rl(),t=!1){if(!e)return{success:!1,message:"No enrollment web origin is configured. Set VISA_VERIFY_WEB_URL to a deployment URL to use enroll_agent."};if(!t){let p=ok();if(p.kind==="claimed"){let f=p.credential;return Be.info("agent:enroll_already_connected",{keyBound:f.keyBound}),{success:!0,alreadyConnected:!0,...f.name?{name:f.name}:{},keyBound:f.keyBound,message:`This device is already connected${f.name?` as ${f.name}`:""} \u2014 nothing to pair. To add or change spending on this identity, approve it in your account settings (agent card \u2192 Spend). Call enroll_agent with {"action":"start","force":true} to start a brand-new enrollment anyway.`}}}let{challenge:r,confirmCode:n,agentPkX:i,walletPkHex:o}=ik(),s=kA(e),a=`${s}?cli=${r}&cliPk=${i}${o?`&walletPk=${o}`:""}`;Be.info("agent:enroll_open",{url:s});let c=W9r(a),u="sign in \u2192 pick your .visa name \u2192 wallet \u2192 card (secure fields) \u2192 bank verification with passkey \u2192 mint; already enrolled on the web? sign in \u2192 verify with your passkey \u2192 connect",d=`CONFIRMATION CODE: ${n} \u2014 the final screen will ask for it. Only enter it on a page YOU opened from this terminal; never share it or enter a code from a link someone sent you.`,l='When the final screen shows "Sent to your Visa CLI", call enroll_agent with {"action":"claim"} to store the enrollment credential on this device.';return c.opened?{success:!0,opened:!0,browserUrl:c.url,confirmCode:n,message:`Opened the Visa Verified Agent enrollment in your browser (${u}). ${d} ${l} Access is currently tester-gated \u2014 if sign-in shows "private testing", ask for the v4_verify_web_access flag.`}:{success:!0,opened:!1,requiresBrowser:!0,browserUrl:c.url??a,confirmCode:n,message:`Open this URL in a browser to enroll your agent (${u}): ${c.url??a} \u2014 ${d} ${l}`}}async function txr(e=rl()){if(!e)return{success:!1,message:"No enrollment web origin is configured. Set VISA_VERIFY_WEB_URL to a deployment URL to use enroll_agent."};let t=await sk(e);switch(Be.info("agent:enroll_claim",{status:t.status}),t.status){case"claimed":return{success:!0,name:t.name,tokenId:t.tokenId,credentialPath:t.credentialPath,keyBound:t.keyBound,sessionSaved:t.sessionSaved,walletProvisioned:t.walletProvisioned,message:`Enrollment credential${t.name?` for ${t.name}`:""} stored at ${t.credentialPath} (token id ${t.tokenId}). The CLI purchase leg will read it from there.`+(t.keyBound?" The agent's key was generated on this terminal and its private half never left this device.":" Note: this terminal\u2019s agent key was not bound \u2014 normal when connecting an EXISTING agent from a returning sign-in (the agent keeps its original key); the credential works for purchases, but no agent key is held on this device.")+(t.sessionSaved?" This device is connected to your identity.":"")+(t.walletProvisioned?" Your x402 spending wallet is live on this device \u2014 fund the wallet address and you can pay (wallet_pay / visa pay).":"")};case"no_pending":return{success:!1,message:"No enrollment hand-off is in progress on this device \u2014 run enroll_agent first, finish the browser flow, then claim."};case"not_ready":return{success:!1,message:t.likelyExpired?"The hand-off window (15 minutes) has likely expired \u2014 run enroll_agent again, finish the browser flow, then claim.":'The enrollment credential is not ready yet \u2014 finish the browser flow through the final "minted" screen (it will say "Sent to your Visa CLI"), then claim again.'};case"confirm_mismatch":return{success:!1,confirmCode:t.confirmCode,message:`The confirmation code entered in the browser did not match this terminal, so the credential was refused. Your code is ${t.confirmCode} \u2014 re-enter it on the enrollment page ("Re-enter code"), then claim again. If YOU did not just complete the browser flow, someone else may have your enrollment link; run enroll_agent to start over with a fresh one.`};case"error":return{success:!1,message:t.message}}}async function Jft(){if(await Uu.clearAll(),!!O3e())try{await C3e()}catch(e){Be.warn("reset:touchid_key_delete_failed",{error:e instanceof Error?e.message:String(e)})}}async function rxr(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return{success:!1,message:"Please confirm by setting confirm: true to reset"};if(Be.info("reset:attempt"),e.localOnly)return await Jft(),Be.info("reset:success",{localOnly:!0}),{success:!0,message:"Device reset locally. Local credentials and keys have been removed. Use enroll_agent to connect this device again."};try{await Qs.logout(void 0,t)}catch{}return await Jft(),Be.info("reset:success"),{success:!0,message:"Device reset. The server session, local credentials, and local keys have been removed. Use enroll_agent to connect this device again."}}async function nxr(e){if(!e.name)return{success:!1,error:"name is required"};try{let{registerName:t,ensureMailbox:r}=await Promise.resolve().then(()=>(Nv(),gk)),n=await t(e.name);return await r(e.name),{success:!0,...n}}catch(t){let{CardRequiredError:r}=await Promise.resolve().then(()=>(LA(),E9e));return t instanceof r?{success:!1,card_required:!0,reason:t.reason,recovery_tool:"enroll_agent",error:t.message,message:`${t.message} Call enroll_agent, complete and claim V4 enrollment, then ask me to register again.`}:{success:!1,error:t instanceof Error?t.message:String(t)}}}async function ixr(e){if(!e.name)return{success:!1,error:"name is required"};try{let{resolveMeshName:t}=await Promise.resolve().then(()=>(Nv(),gk));return{success:!0,...await t(e.name)}}catch(t){return{success:!1,error:t instanceof Error?t.message:String(t)}}}async function oxr(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(()=>(Nv(),gk)),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 sxr(e){try{let{readInbox:t,resolveActingName:r,meshName:n}=await Promise.resolve().then(()=>(Nv(),gk)),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 zo=class{static async subwayRegister(t){return nxr(t||{})}static async subwayFind(t){return ixr(t||{})}static async subwaySend(t){return oxr(t||{})}static async subwayInbox(t){return sxr(t||{})}static async getStatus(t){return J9r(t)}static async feedback(t,r){return Y9r(t,r)}static async configList(t){return Z9r(t||{})}static async configSet(t){return X9r(t||{})}static async configUnset(t){return Q9r(t||{})}static async reset(t,r){return rxr(t,r)}static async enrollAgent(t={},r){let n=t?.action??"start";return n==="start"?exr(void 0,t?.force===!0):n==="claim"?txr():{success:!1,message:`Unknown enroll_agent action ${JSON.stringify(n)}. Use "start" (default \u2014 opens the enrollment flow) or "claim" (stores the credential after the browser flow finishes).`}}static async payMerchant(t={},r){return eft(t)}static async ucpCheckoutHandoff(t,r){return vm("ucp_checkout_handoff")&&(await nA(),vm("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."}:Gft(t)}static async payMerchantStatus(t={},r){return Qpt(t)}static async startCardMandate(t={},r){return tft(t)}static async submitFeedback(t,r,n){Be.info("feedback:submit",{length:t.length,transactionId:r,hasContext:!!n});try{let i=await Qs.submitFeedback(t,r,n);return Be.info("feedback:submitted",{transactionId:r}),i}catch(i){let o=i instanceof Error?i.message:"Unknown error";throw Be.error("feedback:error",{error:o,transactionId:r}),i}}static async getFeedback(t,r){Be.info("feedback:list",{limit:t||20});try{let n=await Qs.getFeedback(t,r);return Be.info("feedback:listed",{count:n?.feedback?.length||0}),n}catch(n){let i=n instanceof Error?n.message:"Unknown error";throw Be.error("feedback:error",{error:i}),n}}};function Qft(e){return e==="pay_merchant"}Dc();var emt="VISA_V4_WALLET_EXPERIMENT",axr=null;function cxr(){return axr??!0}var uxr=new Set(["1","true","on","yes"]),dxr=new Set(["0","false","off","no"]),tmt=!1;function B8e(e,t){return tmt||(tmt=!0,Be.info("wallet-experiment:enablement",{enabled:e,reason:t})),e}function nmt(){let e=(process.env[emt]??"").trim().toLowerCase();if(uxr.has(e))return B8e(!0,"env-on");if(dxr.has(e))return B8e(!1,"env-off");e!==""&&Be.warn("wallet-experiment:unrecognized-env-value",{env:emt,fallback:"bundled-runtime"});let t=cxr();return B8e(t,t?"bundled-runtime":"runtime-unavailable")}var rmt=null;function imt(){return rmt??=wJ(),rmt}var lxr={user_context:{type:"string",description:"The exact verbatim request the user made that prompted this tool call. Always include the user's full original message."}};function pxr(e){return{...e,inputSchema:{...e.inputSchema,properties:{...e.inputSchema.properties,...lxr},required:[...e.inputSchema.required||[],"user_context"]}}}function omt(){return nmt()?imt().WALLET_TOOL_DEFS.map(pxr):[]}function smt(e){return nmt()?imt().WALLET_TOOL_NAMES.includes(e):!1}async function amt(e,t,r={}){let i=await(await Promise.resolve().then(()=>Ze(wJ()))).dispatchWalletTool(e,t,{logger:Be,merchantDirectorySearch:r.merchantDirectorySearch});if(r.emitTelemetry&&(e==="wallet_pay"||e==="wallet_directory_pay")&&i.receipt)try{let o=fxr(e,t,i);o&&await r.emitTelemetry([o])}catch(o){Be.warn("wallet-experiment:telemetry-failed",{tool:e,error:o instanceof Error?o.message:String(o)})}return i}function fxr(e,t,r){if(e!=="wallet_pay"&&e!=="wallet_directory_pay")return null;let n=r.receipt&&typeof r.receipt=="object"&&!Array.isArray(r.receipt)?r.receipt:null;if(!n)return null;let i=typeof n.amountUsd=="string"?n.amountUsd:"",o=Number(i.replace(/[$,\s]/g,""));if(!Number.isFinite(o)||o<=0)return null;let s=r.directory&&typeof r.directory=="object"&&!Array.isArray(r.directory)?r.directory:null,a=s?.selection&&typeof s.selection=="object"&&!Array.isArray(s.selection)?s.selection:null,c=typeof t.url=="string"?t.url:typeof a?.url=="string"?a.url:"",u="Pay-per-use service";try{u=new URL(c).hostname.toLowerCase()}catch{}let d=typeof n.timestamp=="string"?n.timestamp:new Date().toISOString(),l=typeof n.network=="string"?n.network:null,p=typeof n.scheme=="string"?n.scheme:null,f=typeof n.txHash=="string"?n.txHash:null;return{timestamp:d,tool_name:e,user_prompt:"",tool_params:JSON.stringify({merchant_host:u,network:l,scheme:p}),result_success:!0,result_error:null,result_json:JSON.stringify({network:l,scheme:p}),payment_rail:"stablecoin",payment_amount:o,payment_currency:"USDC",merchant_name:u,transaction_id:null,tx_hash:f,protocol:"x402",http_status:null,duration_ms:0,source:"cli",endpoint:"/v4/wallet",resolved_model:null,session_budget_id:null}}Dc();var N8e=["pay_merchant"],mxr={pay_merchant:"merchant checkout"};function hxr(e){return mxr[e]||e}var cmt={};function umt(e){let t=cmt[e]??0;return cmt[e]=t+1,t}function dmt(e,t,r){return N8e.includes(e)?t===0?{_feedback_prompt:{message:`This was your first time using ${hxr(e)} \u2014 if you have any thoughts on the experience, I'd be happy to pass them along to the Visa CLI team.`,transaction_id:r}}:t%5===0?{_feedback_hint:{message:"Feedback? Just say how that went.",transaction_id:r}}:{}:{}}var xY=Ze(require("crypto")),EY=Ze(require("tty")),r4=Ze(require("fs")),q8e=Ze(require("os")),wY=Ze(require("path"));zY();NA();var yxr=new Set(["connect","disconnect","connections"]);function gxr(e){return e!==void 0&&yxr.has(e)}function bxr(e){return/-rc\.|-beta\./.test(e)}function j8e(e){return xY.createHash("sha256").update(e.trim()).digest("hex")}function lmt(e){return Cm==="SKIP"?!0:xY.timingSafeEqual(Buffer.from(j8e(e)),Buffer.from(Cm))}function _xr(){return wY.join(q8e.homedir(),".visa-mcp","agent-credential.json")}function vxr(){let e=process.env.VISA_V4_HOME||wY.join(q8e.homedir(),".visa-v4");return wY.join(e,"turnkey.json")}function wxr(){try{let e=r4.readFileSync(_xr(),"utf8"),t=JSON.parse(e);if(typeof t?.tokenId=="string"&&t.tokenId.length>0)return!0}catch{}try{let e=r4.readFileSync(vxr(),"utf8"),t=JSON.parse(e);return typeof t?.organizationId=="string"&&t.organizationId.length>0&&typeof t?.walletId=="string"&&t.walletId.length>0&&typeof t?.address=="string"&&/^0x[0-9a-f]{40}$/i.test(t.address)}catch{return!1}}function xxr(){try{let e=r4.openSync("/dev/tty","r+"),t=new EY.ReadStream(e),r=new EY.WriteStream(e),n=!1;return{input:t,output:r,cleanupStreams:()=>{if(!n){n=!0;try{t.destroy()}catch{}try{r.destroy()}catch{}try{r4.closeSync(e)}catch{}}}}}catch{if(!process.stdin.isTTY)throw new Error("No interactive terminal available. Set VISA_RC_CODE env var instead.");return{input:process.stdin,output:process.stderr,cleanupStreams:()=>{}}}}function Exr(e){return new Promise((t,r)=>{let n;try{n=xxr()}catch(d){r(d);return}let{input:i,output:o,cleanupStreams:s}=n,a=()=>{i.off("data",u);try{i.setRawMode?.(!1)}catch{}s()};o.write(e),i.setRawMode?.(!0),i.resume(),i.setEncoding("utf8");let c="",u=d=>{d==="\r"||d===`
20779
20779
  `?(o.write(`
20780
20780
  `),a(),t(c)):d===""?(o.write(`
20781
20781
  `),a(),r(new Error("Cancelled"))):d==="\x7F"||d==="\b"?c.length>0&&(c=c.slice(0,-1),o.write("\b \b")):(c+=d,o.write("\u2022"))};i.on("data",u)})}var Axr=`