@visa/cli 4.1.0-rc.24 → 4.1.0-rc.25
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/mcp-server/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
"use strict";var e0t=Object.create;var Kk=Object.defineProperty;var t0t=Object.getOwnPropertyDescriptor;var r0t=Object.getOwnPropertyNames;var n0t=Object.getPrototypeOf,i0t=Object.prototype.hasOwnProperty;var I=(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}},Uo=(e,t)=>{for(var r in t)Kk(e,r,{get:t[r],enumerable:!0})},e3e=(e,t,r,n)=>{if(t&&typeof t=="object"||typeof t=="function")for(let i of r0t(t))!i0t.call(e,i)&&i!==r&&Kk(e,i,{get:()=>t[i],enumerable:!(n=t0t(t,i))||n.enumerable});return e};var qe=(e,t,r)=>(r=e!=null?e0t(n0t(e)):{},e3e(t||!e||!e.__esModule?Kk(r,"default",{value:e,enumerable:!0}):r,e)),ie=e=>e3e(Kk({},"__esModule",{value:!0}),e);function H1t(){Da.existsSync(ZY)||Da.mkdirSync(ZY,{recursive:!0,mode:448})}function z1t(){if(!YY){if(H1t(),Da.existsSync(HA)&&Da.statSync(HA).size>L1t){let t=HA+".1";Da.existsSync(t)&&Da.unlinkSync(t),Da.renameSync(HA,t)}YY=Da.createWriteStream(HA,{flags:"a"})}return YY}function F1t(e){return e==="WARN"||e==="ERROR"?!0:process.env.VISA_CLI_DEBUG==="1"||process.env.VISA_VERBOSE==="1"}function rB(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
|
-
`;F1t(e)&&process.stderr.write(i),z1t().write(i)}var Da,XY,j3e,ZY,HA,L1t,YY,W,ea=I(()=>{"use strict";Da=qe(require("fs")),XY=qe(require("path")),j3e=qe(require("os")),ZY=XY.join(j3e.homedir(),".visa-mcp"),HA=XY.join(ZY,"mcp-server.log"),L1t=5*1024*1024,YY=null;W={debug:(...e)=>rB("DEBUG",...e),info:(...e)=>rB("INFO",...e),warn:(...e)=>rB("WARN",...e),error:(...e)=>rB("ERROR",...e)}});function U3e(e=q3e){return/^\d+\.\d+\.\d+$/.test(e)&&e!=="0.0.0"}function Um(e=process.env,t=q3e){return e.VISA_VERIFY_WEB_URL?e.VISA_VERIFY_WEB_URL:U3e(t)?null:$1t}var q3e,$1t,nB=I(()=>{"use strict";q3e="4.1.0-rc.
|
|
3
|
+
`;F1t(e)&&process.stderr.write(i),z1t().write(i)}var Da,XY,j3e,ZY,HA,L1t,YY,W,ea=I(()=>{"use strict";Da=qe(require("fs")),XY=qe(require("path")),j3e=qe(require("os")),ZY=XY.join(j3e.homedir(),".visa-mcp"),HA=XY.join(ZY,"mcp-server.log"),L1t=5*1024*1024,YY=null;W={debug:(...e)=>rB("DEBUG",...e),info:(...e)=>rB("INFO",...e),warn:(...e)=>rB("WARN",...e),error:(...e)=>rB("ERROR",...e)}});function U3e(e=q3e){return/^\d+\.\d+\.\d+$/.test(e)&&e!=="0.0.0"}function Um(e=process.env,t=q3e){return e.VISA_VERIFY_WEB_URL?e.VISA_VERIFY_WEB_URL:U3e(t)?null:$1t}var q3e,$1t,nB=I(()=>{"use strict";q3e="4.1.0-rc.25",$1t="https://v4-verify-web-visa-code-preview.up.railway.app"});var oB,H3e,z3e,tZ,La,zA=I(()=>{"use strict";oB=qe(require("fs")),H3e=qe(require("path")),z3e=qe(require("os")),tZ=H3e.join(z3e.homedir(),".visa-mcp"),La=class{static ensureConfigDir(){oB.existsSync(tZ)||oB.mkdirSync(tZ,{recursive:!0,mode:448})}static getConfigDir(){return tZ}static TOOL_STATES={login:!0,get_status:!0,get_cards:!0,add_card:!0,pay:!1,transaction_history:!0,update_spending_controls:!0,enroll_device:!1,verify_otp:!1,reset:!0,batch:!0,generate_x402_image:!1,browser_launch:!1,browser_navigate:!1,browser_snapshot:!1,browser_click:!1,browser_type:!1,browser_scroll:!1,generate_music_card:!1,generate_image_card:!1,query_onchain_prices_card:!1,generate_music_tempo_card:!1,check_music_status_tempo_card:!1,generate_image_fast_card:!1,generate_video_tempo_card:!1};static loadToolStates(){return{...this.TOOL_STATES}}static getDisabledTools(){let t=new Set;for(let[r,n]of Object.entries(this.TOOL_STATES))n||t.add(r);return t}static isToolDisabled(t){return this.TOOL_STATES[t]===!1}}});var sB=g((gSr,J1t)=>{J1t.exports={name:"@visa/cli",version:"4.1.0-rc.25",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/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",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:*","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.63.0","@typescript-eslint/parser":"^8.63.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 F3e(e){let t=$3e.homedir();return t&&e.startsWith(t)?`~${e.slice(t.length)}`:e}function FA(){return V3e.join(La.getConfigDir(),Y1t)}function K3e(e){if((0,iZ.isIP)(e)!==4)return!1;let[t]=e.split(".").map(Number);return t===127}function X1t(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 K3e(i)}function Q1t(e){let t=e.toLowerCase().replace(/^\[(.*)\]$/,"$1");if(t==="localhost")return!0;let r=(0,iZ.isIP)(t);return r===4?K3e(t):r===6?t==="::1"||X1t(t):!1}function rZ(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:"&&Q1t(r.hostname)))throw new Error(`${t} ${Z1t}`)}function j2(){let e=FA();if(!ph.existsSync(e))return{};try{let t=ph.readFileSync(e,"utf-8"),r=JSON.parse(t);return!r||typeof r!="object"||Array.isArray(r)?(W.warn("settings:corrupt",{path:F3e(e),reason:"not_object"}),{}):r}catch(t){return W.warn("settings:corrupt",{path:F3e(e),error:t?.message||String(t)}),{}}}function nZ(e){La.ensureConfigDir();let t=FA(),r=`${t}.tmp`,n=JSON.stringify(e,null,2)+`
|
|
4
4
|
`;ph.writeFileSync(r,n,{mode:384}),ph.renameSync(r,t)}function cB(e){let t=j2()[e];return typeof t=="string"?t:void 0}function VA(e){let t=j2()[e];if(typeof t=="boolean")return t;if(t==="true")return!0;if(t==="false")return!1}function sZ(e){let t=j2()[e];if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"&&t.trim().length>0){let r=Number(t);if(Number.isFinite(r))return r}}function G3e(e,t){if(W3e.some(o=>e.startsWith(o)))throw new q2(e);if(e in aB)throw new Ow(e);let r=$A[e];if(!r)throw new Mm(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=j2();return i[e]=n,nZ(i),{key:e,value:n,requiresRestart:!!r.requiresRestart,path:FA()}}function J3e(e){if(W3e.some(o=>e.startsWith(o)))throw new q2(e);let t=$A[e];if(e in aB){let o=j2(),s=e in o;return s&&(delete o[e],nZ(o)),{key:e,removed:s,requiresRestart:!1,path:FA()}}if(!t)throw new Mm(e);let n=j2(),i=e in n;return i&&(delete n[e],nZ(n)),{key:e,removed:i,requiresRestart:i&&!!t.requiresRestart,path:FA()}}function uB(){let e=j2();return Object.entries(aB).filter(([t])=>t in e).map(([t,r])=>({key:t,value:e[t],hint:r}))}function rht(e){return typeof e=="string"&&/-(?:rc|alpha|beta)\./i.test(e)}function nht(){try{let e=sB();return rht(e.version)}catch{return!1}}function iht(e){return e.envVar!==void 0&&e.envVar!==""?(rZ(e.envVar,"VISA_AUTH_URL"),e.envVar):e.settingValue!==void 0?(rZ(e.settingValue,"auth.serverUrl"),e.settingValue):e.isPrerelease?tht:eht}function ta(){return iht({envVar:process.env.VISA_AUTH_URL,settingValue:cB("auth.serverUrl"),isPrerelease:nht()})}function Y3e(){let e=process.env.VISA_SUPPRESS_BROWSER;return e!==void 0?e==="true":VA("ui.suppressBrowser")??!1}function Z3e(){let e=process.env.VISA_SUPPRESS_FEED;return e!==void 0?e==="true":VA("ui.suppressFeed")??!1}function dB(){let e=process.env.VISA_DISCOVER_TOOLS;return e!==void 0?e!=="false":VA("tools.discover")??!0}function X3e(){let e=process.env.VISA_MERCHANT_DISCOVER?.trim().toLowerCase(),t=process.env.VISA_MERCHANT_SLUGS?.trim();if(e==="all"||e==="*")return{kind:"all"};if(e==="off")return{kind:"off"};if(e&&e.length>0){let o=e.split(",").map(s=>s.trim()).filter(Boolean);return o.length>0?{kind:"slugs",slugs:o}:{kind:"all"}}if(t==="*")return{kind:"all"};if(t&&t.length>0){let o=t.split(",").map(s=>s.trim()).filter(Boolean);return o.length>0?{kind:"slugs",slugs:o}:{kind:"off"}}let r=cB("merchants.discover")?.trim();if(!r)return{kind:"all"};let n=r.toLowerCase();if(n==="all"||n==="*")return{kind:"all"};if(n==="off")return{kind:"off"};let i=r.split(",").map(o=>o.trim()).filter(Boolean);return i.length>0?{kind:"slugs",slugs:i}:{kind:"off"}}function Q3e(){let e=process.env.VISA_CREDIT_SESSION_CAP_CENTS;if(e!==void 0){let r=Number(e);if(Number.isFinite(r)&&r>=10&&r<=1e4)return Math.floor(r)}let t=sZ("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?Math.floor(t):oZ}var ph,iZ,$3e,V3e,Y1t,Z1t,$A,oZ,aB,Mm,q2,Ow,W3e,eht,tht,Qd=I(()=>{"use strict";ph=qe(require("fs")),iZ=require("node:net"),$3e=qe(require("os")),V3e=qe(require("path"));zA();ea();Y1t="settings.json",Z1t="must use https unless it points at localhost/loopback for local development";$A={"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");rZ(e)}},"ui.suppressBrowser":{type:"boolean",description:"When true, the CLI/MCP server stops auto-opening result URLs in your browser."},"ui.suppressFeed":{type:"boolean",description:"When true, generated images/music are not auto-submitted to the public Made-with-Visa feed."},"tools.discover":{type:"boolean",description:"Show the dynamic-catalog tools (discover_tools, execute_tool). Restart required.",requiresRestart:!0},"merchants.discover":{type:"string",description:'Platform-merchant JIT tool discovery: "all" = every live merchant, "off" = none, comma-separated slugs = exactly those. Equivalent to VISA_MERCHANT_DISCOVER / VISA_MERCHANT_SLUGS env. Restart required.',requiresRestart:!0,validate:e=>{if(typeof e!="string")throw new Error("merchants.discover must be a string");let t=e.trim().toLowerCase();if(t===""||t==="all"||t==="off"||t==="*")return;let r=/^[a-z0-9](?:[a-z0-9-]{0,62}[a-z0-9])?$/,n=e.split(",").map(i=>i.trim()).filter(Boolean);for(let i of n)if(!r.test(i))throw new Error(`merchants.discover: "${i}" is not a valid merchant slug`)}},"credit.sessionCapCents":{type:"number",description:"Default cap (in cents) for start_session and pay-as-you-go one-shot approvals. Server clamps to [10, 10000] = $0.10\u2013$100. Default 500 ($5).",validate:e=>{if(typeof e!="number"||!Number.isFinite(e))throw new Error("credit.sessionCapCents must be a number");if(!Number.isInteger(e))throw new Error("credit.sessionCapCents must be a whole number of cents (no fractional cents)");if(e<10||e>1e4)throw new Error("credit.sessionCapCents must be between 10 ($0.10) and 10000 ($100)")}}},oZ=500,aB={"tools.specific":"Legacy direct _card MCP tools are retired. Use discover_tools/execute_tool.","tools.meta":"Category meta-tools (generate_image, run_llm, ...) are removed. Use discover_tools/execute_tool.","credit.sessionMode":"The session-mode toggle is retired. Use start_session, close_session, and get_session_status."};Mm=class extends Error{constructor(t){let r=Object.keys($A).sort().join(", ");super(`Unknown setting "${t}". Settable keys: ${r}. For server-controlled values (biometric.*, spending.*) use the dedicated tools (biometric_on/off, update_spending_controls).`),this.name="UnknownSettingKeyError"}},q2=class extends Error{constructor(t){let r="";t.startsWith("biometric.")?r="biometric_on / biometric_off":t.startsWith("spending.")?r="update_spending_controls":t.startsWith("cards.")?r="add_card / remove_card / set_default_card":t.startsWith("account.")&&(r="login / reset"),super(`"${t}" is a server-controlled value and cannot be set via config set. `+(r?`Use ${r} instead.`:"No client-side override is supported.")),this.name="ServerOnlySettingError"}},Ow=class extends Error{constructor(t){super(`"${t}" is retired and ignored. Remove it with \`visa-cli config unset ${t}\`. `+aB[t]),this.name="RetiredSettingKeyError"}},W3e=["biometric.","spending.","account.","cards.","biometric"];eht="https://auth.visacli.sh",tht="https://auth-visa-code-preview.up.railway.app"});var r9e=g(el=>{"use strict";Object.defineProperty(el,"__esModule",{value:!0});el.formatCents=t9e;el.formatUsd=fht;el.formatMicros=pB;el.formatMicrosWire=mht;el.formatTxAmount=hht;el.formatDate=yht;el.formatRelativeTime=ght;el.formatTime=bht;el.formatAge=_ht;var e9e=1e6,pht=100;function t9e(e,t={}){let r=t.fallback??"\u2014";if(e==null||!Number.isFinite(e))return r;let i=(e/pht).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??2});return t.showPlusSign&&e>0?`+${i}`:i}function fht(e,t={}){let r=t.fallback??"\u2014";if(e==null||!Number.isFinite(e))return r;let n=e.toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??2});return t.showPlusSign&&e>0?`+${n}`:n}function pB(e,t={}){let r=t.fallback??"\u2014",n=typeof e=="string"?e===""?null:Number(e):e;if(n==null||!Number.isFinite(n))return r;let o=(n/e9e).toLocaleString("en-US",{style:"currency",currency:"USD",minimumFractionDigits:t.minimumFractionDigits??2,maximumFractionDigits:t.maximumFractionDigits??6});return t.showPlusSign&&n>0?`+${o}`:o}function mht(e,t,r={}){return e&&/^-?\d+$/.test(e)?pB(e,r):t!=null&&Number.isFinite(t)?t9e(t,r):r.fallback??"\u2014"}function hht(e,t={}){let r=Number(e.amount_micros);if(Number.isFinite(r)&&e.amount_micros!=null&&e.amount_micros!=="")return pB(r,t);let n=Number(String(e.amount).replace(/^\$/,""));return Number.isFinite(n)?pB(n*e9e,t):t.fallback??"\u2014"}function yht(e,t={}){let r=t.fallback??"\u2014";if(!e)return r;let n=new Date(e);return Number.isNaN(n.getTime())?r:n.toLocaleDateString("en-US",{month:"short",day:"numeric",year:"numeric",timeZone:t.timeZone??"UTC"})}function ght(e,t=Date.now()){if(!e)return"\u2014";let r=Date.parse(e);if(Number.isNaN(r))return"\u2014";let n=t-r,i=n>=0,o=Math.abs(n),s=Math.floor(o/1e3),a=Math.floor(s/60),c=Math.floor(a/60),u=Math.floor(c/24),d=Math.floor(u/7),l=Math.floor(u/30),p=Math.floor(u/365);return s<45?"just now":a<1?i?"a minute ago":"in a minute":a<60?kw(n,i,a,"minute"):c<24?kw(n,i,c,"hour"):u===1?i?"yesterday":"tomorrow":u<7?kw(n,i,u,"day"):d<4?kw(n,i,d,"week"):l<12?kw(n,i,l,"month"):kw(n,i,p,"year")}function kw(e,t,r,n){let i=r!==1?"s":"";return t?`${r} ${n}${i} ago`:`in ${r} ${n}${i}`}function bht(e,t={}){let r=t.fallback??"\u2014";if(!e)return r;let n=new Date(e);return Number.isNaN(n.getTime())?r:n.toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric",hour:"2-digit",minute:"2-digit",timeZone:t.timeZone??"UTC"})}function _ht(e,t){if(!e)return"";let r=Date.parse(e);if(Number.isNaN(r))return"";let n=Math.max(0,t-r),i=Math.floor(n/1e3);if(i<45)return"just now";let o=Math.floor(i/60);if(o<60)return`${o}m ago`;let s=Math.floor(o/60);if(s<24)return`${s}h ago`;let a=Math.floor(s/24);if(a<30)return`${a}d ago`;let c=Math.floor(a/30);return c<12?`${c}mo ago`:`${Math.floor(a/365)}y ago`}});var Sp=g($t=>{"use strict";Object.defineProperty($t,"__esModule",{value:!0});$t.formatAge=$t.formatTime=$t.formatRelativeTime=$t.formatDate=$t.formatTxAmount=$t.formatMicrosWire=$t.formatMicros=$t.formatUsd=$t.formatCents=void 0;$t.micros=vht;$t.fromCents=wht;$t.fromUsdc=xht;$t.fromUsd=Eht;$t.toCents=Aht;$t.toCentsForAcquirer=Sht;$t.toUsdc=Tht;$t.toWire=Pht;$t.fromWire=Iht;$t.toDisplay=Cht;$t.toUsdRounded2dp=Oht;$t.add=Rht;$t.sub=kht;$t.clampNonNegative=Bht;$t.isNonNegative=Nht;$t.max=jht;$t.min=qht;var Dm=10000n,n9e=1000000n;function vht(e){return e}function wht(e){if(!Number.isFinite(e)||!Number.isInteger(e)||!Number.isSafeInteger(e))throw new TypeError(`fromCents: expected safe integer, got ${e}`);return BigInt(e)*Dm}function xht(e){return e}function Eht(e){if(!Number.isFinite(e))throw new TypeError(`fromUsd: expected finite number, got ${e}`);return BigInt(Math.round(e*1e6))}function Aht(e){if(e>=0n)return Number(e/Dm);let t=e/Dm,r=e%Dm;return Number(r===0n?t:t-1n)}function Sht(e){if(e<0n)throw new RangeError(`toCentsForAcquirer: refusing negative micros (${e}); card charges are non-negative`);return Number(e/Dm)}function Tht(e){return e}function Pht(e){return e.toString()}function Iht(e){if(typeof e!="string"||e.length===0)throw new TypeError(`fromWire: expected non-empty string, got ${typeof e} ${JSON.stringify(e)}`);if(!/^-?\d+$/.test(e))throw new TypeError(`fromWire: not a valid micros integer: ${JSON.stringify(e)}`);return BigInt(e)}function Cht(e,t={}){let r=t.decimals??2,n=t.symbol??"$",i=e<0n,o=i?-e:e,s=o/n9e,a=o%n9e,c=i?"-":"";if(r===0)return`${c}${n}${s.toString()}`;let u=a.toString().padStart(6,"0").slice(0,r);return`${c}${n}${s.toString()}.${u}`}function Oht(e){let t=e<0n,r=t?-e:e,n=r/Dm,o=r%Dm*2n,s;o<Dm?s=n:o>Dm?s=n+1n:s=n%2n===0n?n:n+1n;let a=Number(s)/100;return t?-a:a}function Rht(e,t){return e+t}function kht(e,t){return e-t}function Bht(e){return e<0n?0n:e}function Nht(e){return e>=0n}function jht(e,t){return e>t?e:t}function qht(e,t){return e<t?e:t}var Lm=r9e();Object.defineProperty($t,"formatCents",{enumerable:!0,get:function(){return Lm.formatCents}});Object.defineProperty($t,"formatUsd",{enumerable:!0,get:function(){return Lm.formatUsd}});Object.defineProperty($t,"formatMicros",{enumerable:!0,get:function(){return Lm.formatMicros}});Object.defineProperty($t,"formatMicrosWire",{enumerable:!0,get:function(){return Lm.formatMicrosWire}});Object.defineProperty($t,"formatTxAmount",{enumerable:!0,get:function(){return Lm.formatTxAmount}});Object.defineProperty($t,"formatDate",{enumerable:!0,get:function(){return Lm.formatDate}});Object.defineProperty($t,"formatRelativeTime",{enumerable:!0,get:function(){return Lm.formatRelativeTime}});Object.defineProperty($t,"formatTime",{enumerable:!0,get:function(){return Lm.formatTime}});Object.defineProperty($t,"formatAge",{enumerable:!0,get:function(){return Lm.formatAge}})});var Hm,cZ=I(()=>{"use strict";Hm="6820f6e91b762e645c9bf020c0d3673bb99d4a25a824880c0d548e10bb9bc7b1"});function uZ(e){return`${e}-${a9e.randomBytes(24).toString("base64url")}`}function u9e(e=process.env){return e.NODE_ENV==="test"||e[c9e]==="true"}function mh(e=process.env){return e.VISA_MOCK_KEYCHAIN==="true"&&u9e(e)}function YA(e=process.env){return e.VISA_MOCK_TOUCHID==="true"&&u9e(e)}function dZ(){return`Set ${c9e}=true only for local debugging; it enables insecure mock credential hooks outside NODE_ENV=test.`}function d9e(){return i9e??=uZ("mock-session"),i9e}function l9e(e=process.env){return e.NODE_ENV==="test"?Hm:(o9e??=uZ("mock-rc"),o9e)}function p9e(){return s9e??=uZ("mock-signature"),s9e}var a9e,c9e,i9e,o9e,s9e,fB=I(()=>{"use strict";a9e=qe(require("crypto"));cZ();c9e="VISA_ALLOW_INSECURE_MOCKS"});function Mht(e){let t=e;return[t?.message,t?.stderr].filter(r=>typeof r=="string").join(`
|
|
5
5
|
`)}function yZ(e){let t=e;if(t?.code==="EPERM"||t?.code==="EACCES")return!0;let r=Mht(e).toLowerCase();return r.includes("operation not permitted")||r.includes("permission denied")}function Tp(){return process.platform!=="darwin"?Promise.resolve(!1):(f9e??=(async()=>{try{return await tl("security",["default-keychain","-d","user"],{timeout:5e3}),!0}catch(e){return yZ(e)}})(),f9e)}async function Dht(){if(!await Tp())return null;try{let{stdout:e}=await tl("security",["find-generic-password","-s",qu,"-a",hh,"-w"],{timeout:5e3});return e.trim()||null}catch(e){if(yZ(e))throw new hB("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 Lht(e){if(!await Tp())return!1;try{try{await tl("security",["delete-generic-password","-s",qu,"-a",hh],{timeout:5e3})}catch{}return await tl("security",["add-generic-password","-s",qu,"-a",hh,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function Hht(){if(await Tp())try{await tl("security",["delete-generic-password","-s",qu,"-a",hh],{timeout:5e3})}catch{}}async function zht(){if(!gZ())return null;try{let{stdout:e}=await tl("secret-tool",["lookup","service",qu,"account",hh],{timeout:5e3});return e.trim()||null}catch{return null}}async function Fht(e){if(!gZ())return!1;try{let t=(0,yB.execFile)("secret-tool",["store","--label",`${qu} ${hh}`,"service",qu,"account",hh]);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"))},Uht))]),!0):!1}catch{return!1}}async function $ht(){if(gZ())try{await tl("secret-tool",["clear","service",qu,"account",hh],{timeout:5e3})}catch{}}function gZ(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function Vht(){if(!await Tp())return null;try{let{stdout:e}=await tl("security",["find-generic-password","-s",qu,"-a",mB,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function Kht(e){if(await Tp())try{try{await tl("security",["delete-generic-password","-s",qu,"-a",mB],{timeout:5e3})}catch{}await tl("security",["add-generic-password","-s",qu,"-a",mB,"-w",e],{timeout:5e3})}catch{}}async function Wht(){if(await Tp())try{await tl("security",["delete-generic-password","-s",qu,"-a",mB],{timeout:5e3})}catch{}}function pZ(){try{return yh.readFileSync(ZA,"utf-8").trim()||null}catch(e){if(yZ(e))throw new hB(`Unable to read Visa CLI credentials from ${ZA}. Check file permissions or rerun with access to the Visa CLI credential directory.`);return null}}function h9e(e){yh.mkdirSync(hZ,{recursive:!0,mode:448}),yh.writeFileSync(ZA,e,{mode:384}),process.platform==="win32"&&Ght(ZA)}function fZ(){try{yh.unlinkSync(ZA)}catch{}}function Ght(e){try{let t=gB.userInfo().username;(0,yB.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 lZ(){switch(process.platform){case"darwin":return{get:Dht,store:Lht,delete:Hht};case"linux":return{get:zht,store:Fht,delete:$ht};default:return{get:async()=>pZ(),store:async e=>{try{return h9e(e),!0}catch{return!1}},delete:async()=>fZ(),storesInSessionFile:!0}}}var yB,m9e,yh,gB,mZ,tl,hZ,ZA,qu,hh,mB,Uht,hB,f9e,ra,XA=I(()=>{"use strict";yB=require("child_process"),m9e=require("util"),yh=qe(require("fs")),gB=qe(require("os")),mZ=qe(require("path"));fB();tl=(0,m9e.promisify)(yB.execFile),hZ=mZ.join(gB.homedir(),".visa-mcp"),ZA=mZ.join(hZ,"session-token"),qu="visa-cli",hh="session-token",mB="rc-access",Uht=5e3,hB=class extends Error{constructor(t){super(t),this.name="CredentialAccessError"}};f9e=null;ra=class{static async getSessionToken(){if(mh())return Promise.resolve(d9e());let t=lZ(),r=await t.get();if(r)return r;let n=pZ();return n?(await t.store(n),n):null}static async saveSessionToken(t){if(mh())return;let r=lZ();if(await r.store(t)){if(await r.get()===t){r.storesInSessionFile||fZ();return}await r.delete()}if(h9e(t),pZ()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${hZ} is writable.`))}static async getRcAccessToken(){return mh()?l9e():Vht()}static async saveRcAccessToken(t){mh()||await Kht(t)}static async deleteSessionToken(){if(mh())return;await lZ().delete(),fZ()}static async clearAll(){await this.deleteSessionToken(),await Wht()}}});function vZ(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 xB(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 M9e(e,t){let r=xB(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 syt(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 wZ(e,t=process.platform){let r=xB(e);return r?syt(r,t):null}var xZ=I(()=>{"use strict"});function Tyt(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function dxe(e,t,r=""){let n=Tyt(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 K9e(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 Pyt(e,t){dxe(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 OZ(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function TZ(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function Iyt(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 Ryt(e,t=!1){return t?{h:Number(e&EB),l:Number(e>>W9e&EB)}:{h:Number(e>>W9e&EB)|0,l:Number(e&EB)|0}}function kyt(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}=Ryt(e[o],t);[n[o],i[o]]=[s,a]}return[n,i]}function $m(e,t,r,n){let i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:i|0}}function $yt(){return xyt.randomSecretKey()}function RB(e){return gyt(e)}function kB(){let e=$yt();return{secretKey:e,publicKey:RB(e)}}function MZ(e,t){return vyt(t,e)}function Vyt(e){let t="";for(let r=0;r<e.length;r++)t+=String.fromCharCode(e[r]);return btoa(t)}function Kyt(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 RZ(e){return Vyt(e).replace(/\+/g,"-").replace(/\//g,"_").replace(/=+$/,"")}function Wyt(e){let t=e.length%4===0?0:4-e.length%4,r=e.replace(/-/g,"+").replace(/_/g,"/")+"=".repeat(t);return Kyt(r)}function Gyt(e){if(e.kty!=="OKP"||e.crv!=="Ed25519")throw new Error("not an Ed25519 OKP JWK")}function BB(e){let t=RB(e);return{kty:"OKP",crv:"Ed25519",x:RZ(t),d:RZ(e)}}function tS(e){return{kty:"OKP",crv:"Ed25519",x:RZ(e)}}function DZ(e){if(Gyt(e),!e.d)throw new Error("Ed25519 JWK has no private component (d)");return Wyt(e.d)}var Z9e,PB,TB,D9e,L9e,EZ,AZ,ayt,jw,cyt,Do,uyt,dyt,lyt,Cp,OB,kZ,X9e,BZ,Fm,H9e,NZ,Q9e,pyt,qw,exe,IB,D2,un,z9e,He,txe,rxe,nxe,ixe,SZ,PZ,eS,z2,H2,oxe,sxe,Ip,fyt,F9e,myt,IZ,hyt,jZ,axe,yyt,qZ,gyt,byt,_yt,vyt,UZ,cxe,wyt,xyt,CB,Eyt,uxe,CZ,Ayt,$9e,V9e,Syt,Cyt,Oyt,vs,EB,W9e,G9e,J9e,Bw,Nw,AB,SB,Byt,Nyt,jyt,qyt,Uyt,Myt,lxe,Dyt,Lyt,bh,_h,Hyt,zyt,Fyt,Y9e,zSr,pxe,FSr,$Sr,VSr,KSr,fxe,Jyt,Uw=I(()=>{"use strict";Z9e=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:PB,n:TB,Gx:D9e,Gy:L9e,a:EZ,d:AZ,h:ayt}=Z9e,jw=32,cyt=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},Do=(e="")=>{let t=new Error(e);throw cyt(t,Do),t},uyt=e=>typeof e=="bigint",dyt=e=>typeof e=="string",lyt=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,Cp=(e,t,r="")=>{let n=lyt(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},OB=e=>new Uint8Array(e),kZ=e=>Uint8Array.from(e),X9e=(e,t)=>e.toString(16).padStart(t,"0"),BZ=e=>Array.from(Cp(e)).map(t=>X9e(t,2)).join(""),Fm={_0:48,_9:57,A:65,F:70,a:97,f:102},H9e=e=>{if(e>=Fm._0&&e<=Fm._9)return e-Fm._0;if(e>=Fm.A&&e<=Fm.F)return e-(Fm.A-10);if(e>=Fm.a&&e<=Fm.f)return e-(Fm.a-10)},NZ=e=>{let t="hex invalid";if(!dyt(e))return Do(t);let r=e.length,n=r/2;if(r%2)return Do(t);let i=OB(n);for(let o=0,s=0;o<n;o++,s+=2){let a=H9e(e.charCodeAt(s)),c=H9e(e.charCodeAt(s+1));if(a===void 0||c===void 0)return Do(t);i[o]=a*16+c}return i},Q9e=()=>globalThis?.crypto,pyt=()=>Q9e()?.subtle??Do("crypto.subtle must be defined, consider polyfill"),qw=(...e)=>{let t=0;for(let i of e)t+=Cp(i).length;let r=OB(t),n=0;return e.forEach(i=>{r.set(i,n),n+=i.length}),r},exe=(e=jw)=>Q9e().getRandomValues(OB(e)),IB=BigInt,D2=(e,t,r,n="bad number: out of range")=>{if(!uyt(e))throw new TypeError(n);if(t<=e&&e<r)return e;throw new RangeError(n)},un=(e,t=PB)=>{let r=e%t;return r>=0n?r:t+r},z9e=(1n<<255n)-1n,He=e=>{e<0n&&Do("negative coordinate");let t=(e>>255n)*19n+(e&z9e);return t=(t>>255n)*19n+(t&z9e),t%PB},txe=e=>un(e,TB),rxe=(e,t)=>{(e===0n||t<=0n)&&Do("no inverse n="+e+" mod="+t);let r=un(e,t),n=t,i=0n,o=1n,s=1n,a=0n;for(;r!==0n;){let c=n/r,u=n%r,d=i-s*c,l=o-a*c;n=r,r=u,i=s,o=a,s=d,a=l}return n===1n?un(i,t):Do("no inverse")},nxe=e=>{let t=cxe[e];return typeof t!="function"&&Do("hashes."+e+" not set"),t},ixe=e=>Cp(e,64,"digest"),SZ=e=>e instanceof eS?e:Do("Point expected"),PZ=2n**256n,eS=class L2{static BASE;static ZERO;X;Y;Z;T;constructor(t,r,n,i){let o=PZ;this.X=D2(t,0n,o),this.Y=D2(r,0n,o),this.Z=D2(n,1n,o),this.T=D2(i,0n,o),Object.freeze(this)}static CURVE(){return Z9e}static fromAffine(t){return new L2(t.x,t.y,1n,He(t.x*t.y))}static fromBytes(t,r=!1){let n=AZ,i=kZ(Cp(t,jw)),o=t[31];i[31]=o&-129;let s=sxe(i);D2(s,0n,r?PZ:PB);let c=He(s*s),u=un(c-1n),d=He(n*c+1n),{isValid:l,value:p}=myt(u,d);l||Do("bad point: y not sqrt");let f=(p&1n)===1n,m=(o&128)!==0;return!r&&p===0n&&m&&Do("bad point: x==0, isLastByteOdd"),m!==f&&(p=un(-p)),new L2(p,s,1n,He(p*s))}static fromHex(t,r){return L2.fromBytes(NZ(t),r)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=EZ,r=AZ,n=this;if(n.is0())return Do("bad point: ZERO");let{X:i,Y:o,Z:s,T:a}=n,c=He(i*i),u=He(o*o),d=He(s*s),l=He(d*d),p=He(c*t),f=He(d*(p+u)),m=un(l+He(r*He(c*u)));if(f!==m)return Do("bad point: equation left != right (1)");let h=He(i*o),y=He(s*a);return h!==y?Do("bad point: equation left != right (2)"):this}equals(t){let{X:r,Y:n,Z:i}=this,{X:o,Y:s,Z:a}=SZ(t),c=He(r*a),u=He(o*i),d=He(n*a),l=He(s*i);return c===u&&d===l}is0(){return this.equals(H2)}negate(){return new L2(un(-this.X),this.Y,this.Z,un(-this.T))}double(){let{X:t,Y:r,Z:n}=this,i=EZ,o=He(t*t),s=He(r*r),a=He(2n*n*n),c=He(i*o),u=un(t+r),d=un(He(u*u)-o-s),l=un(c+s),p=un(l-a),f=un(c-s),m=He(d*p),h=He(l*f),y=He(d*f),v=He(p*l);return new L2(m,h,v,y)}add(t){let{X:r,Y:n,Z:i,T:o}=this,{X:s,Y:a,Z:c,T:u}=SZ(t),d=EZ,l=AZ,p=He(r*s),f=He(n*a),m=He(He(o*l)*u),h=He(i*c),y=un(He(un(r+n)*un(s+a))-p-f),v=un(h-m),x=un(h+m),_=un(f-He(d*p)),w=He(y*v),E=He(x*_),A=He(y*_),S=He(v*x);return new L2(w,E,S,A)}subtract(t){return this.add(SZ(t).negate())}multiply(t,r=!0){if(!r&&t===0n||(D2(t,1n,TB),!r&&this.is0()))return H2;if(t===1n)return this;if(this.equals(z2))return Syt(t).p;let n=H2,i=z2;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(H2))return{x:0n,y:1n};let i=rxe(n,PB);He(n*i)!==1n&&Do("invalid inverse");let o=He(t*i),s=He(r*i);return{x:o,y:s}}toBytes(){let{x:t,y:r}=this.toAffine(),n=oxe(r);return n[31]|=t&1n?128:0,n}toHex(){return BZ(this.toBytes())}clearCofactor(){return this.multiply(IB(ayt),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(TB/2n,!1).double();return TB%2n&&(t=t.add(this)),t.is0()}},z2=new eS(D9e,L9e,1n,un(D9e*L9e)),H2=new eS(0n,1n,1n,0n);eS.BASE=z2;eS.ZERO=H2;oxe=e=>NZ(X9e(D2(e,0n,PZ),64)).reverse(),sxe=e=>IB("0x"+BZ(kZ(Cp(e)).reverse())),Ip=(e,t)=>{let r=e;for(;t-- >0n;)r=He(r*r);return r},fyt=e=>{let t=He(e*e),r=He(t*e),n=He(Ip(r,2n)*r),i=He(Ip(n,1n)*e),o=He(Ip(i,5n)*i),s=He(Ip(o,10n)*o),a=He(Ip(s,20n)*s),c=He(Ip(a,40n)*a),u=He(Ip(c,80n)*c),d=He(Ip(u,80n)*c),l=He(Ip(d,10n)*o);return{pow_p_5_8:He(Ip(l,2n)*e),b2:r}},F9e=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,myt=(e,t)=>{let r=He(t*He(t*t)),n=He(He(r*r)*t),i=fyt(He(e*n)).pow_p_5_8,o=He(e*He(r*i)),s=He(t*He(o*o)),a=o,c=He(o*F9e),u=s===e,d=s===un(-e),l=s===un(-e*F9e);return u&&(o=a),(d||l)&&(o=c),(un(o)&1n)===1n&&(o=un(-o)),{isValid:u||d,value:o}},IZ=e=>txe(sxe(e)),hyt=(...e)=>Promise.resolve(nxe("sha512Async")(qw(...e))).then(ixe),jZ=(...e)=>ixe(nxe("sha512")(qw(...e))),axe=e=>{let t=kZ(e),r=t.slice(0,32);r[0]&=248,r[31]&=127,r[31]|=64;let n=t.slice(32,64),i=IZ(r),o=z2.multiply(i),s=o.toBytes();return{head:r,prefix:n,scalar:i,point:o,pointBytes:s}},yyt=e=>hyt(Cp(e,jw)).then(axe),qZ=e=>axe(jZ(Cp(e,jw))),gyt=e=>qZ(e).pointBytes,byt=e=>e.finish(jZ(e.hashable)),_yt=(e,t,r)=>{let{pointBytes:n,scalar:i}=e,o=IZ(t),s=z2.multiply(o).toBytes();return{hashable:qw(s,n,r),finish:u=>{let d=txe(o+IZ(u)*i);return Cp(qw(s,oxe(d)),64)}}},vyt=(e,t)=>{let r=Cp(e),n=qZ(t),i=jZ(n.prefix,r);return byt(_yt(n,i,r))},UZ=Object.freeze({bytesToHex:BZ,hexToBytes:NZ,concatBytes:qw,mod:un,invert:rxe,randomBytes:exe}),cxe={sha512Async:async e=>{let t=pyt(),r=qw(e);return OB(await t.digest("SHA-512",r.buffer))},sha512:void 0},wyt=e=>(e=e===void 0?exe(jw):e,Cp(e,jw)),xyt=Object.freeze({getExtendedPublicKeyAsync:yyt,getExtendedPublicKey:qZ,randomSecretKey:wyt}),CB=8,Eyt=256,uxe=Math.ceil(Eyt/CB)+1,CZ=2**(CB-1),Ayt=()=>{let e=[],t=z2,r=t;for(let n=0;n<uxe;n++){r=t,e.push(r);for(let i=1;i<CZ;i++)r=r.add(t),e.push(r);t=r.double()}return e},$9e=void 0,V9e=(e,t)=>{let r=t.negate();return e?r:t},Syt=e=>{let t=$9e||($9e=Ayt()),r=H2,n=z2,i=2**CB,o=i,s=IB(i-1),a=IB(CB);for(let c=0;c<uxe;c++){let u=Number(e&s);e>>=a,u>CZ&&(u-=o,e+=1n);let d=c*CZ,l=d,p=d+Math.abs(u)-1,f=c%2!==0,m=u<0;u===0?n=n.add(V9e(f,t[l])):r=r.add(V9e(m,t[p]))}return e!==0n&&Do("invalid wnaf"),{p:r,f:n}};Cyt=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}),Oyt=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=TZ(this.buffer)}update(e){K9e(this),dxe(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=TZ(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){K9e(this),Pyt(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:i}=this,{pos:o}=this;t[o++]=128,OZ(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=TZ(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()}},vs=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),EB=BigInt(2**32-1),W9e=BigInt(32);G9e=(e,t,r)=>e>>>r,J9e=(e,t,r)=>e<<32-r|t>>>r,Bw=(e,t,r)=>e>>>r|t<<32-r,Nw=(e,t,r)=>e<<32-r|t>>>r,AB=(e,t,r)=>e<<64-r|t>>>r-32,SB=(e,t,r)=>e>>>r-32|t<<64-r;Byt=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),Nyt=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,jyt=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),qyt=(e,t,r,n,i)=>t+r+n+i+(e/2**32|0)|0,Uyt=(e,t,r,n,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(i>>>0),Myt=(e,t,r,n,i,o)=>t+r+n+i+o+(e/2**32|0)|0,lxe=kyt(["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))),Dyt=lxe[0],Lyt=lxe[1],bh=new Uint32Array(80),_h=new Uint32Array(80),Hyt=class extends Oyt{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)bh[x]=e.getUint32(t),_h[x]=e.getUint32(t+=4);for(let x=16;x<80;x++){let _=bh[x-15]|0,w=_h[x-15]|0,E=Bw(_,w,1)^Bw(_,w,8)^G9e(_,w,7),A=Nw(_,w,1)^Nw(_,w,8)^J9e(_,w,7),S=bh[x-2]|0,T=_h[x-2]|0,O=Bw(S,T,19)^AB(S,T,61)^G9e(S,T,6),R=Nw(S,T,19)^SB(S,T,61)^J9e(S,T,6),U=jyt(A,R,_h[x-7],_h[x-16]),q=qyt(U,E,O,bh[x-7],bh[x-16]);bh[x]=q|0,_h[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:v}=this;for(let x=0;x<80;x++){let _=Bw(d,l,14)^Bw(d,l,18)^AB(d,l,41),w=Nw(d,l,14)^Nw(d,l,18)^SB(d,l,41),E=d&p^~d&m,A=l&f^~l&h,S=Uyt(v,w,A,Lyt[x],_h[x]),T=Myt(S,y,_,E,Dyt[x],bh[x]),O=S|0,R=Bw(r,n,28)^AB(r,n,34)^AB(r,n,39),U=Nw(r,n,28)^SB(r,n,34)^SB(r,n,39),q=r&i^r&s^i&s,j=n&o^n&a^o&a;y=m|0,v=h|0,m=p|0,h=f|0,p=d|0,f=l|0,{h:d,l}=$m(c|0,u|0,T|0,O|0),c=s|0,u=a|0,s=i|0,a=o|0,i=r|0,o=n|0;let B=Byt(O,U,j);r=Nyt(B,T,R,q),n=B|0}({h:r,l:n}=$m(this.Ah|0,this.Al|0,r|0,n|0)),{h:i,l:o}=$m(this.Bh|0,this.Bl|0,i|0,o|0),{h:s,l:a}=$m(this.Ch|0,this.Cl|0,s|0,a|0),{h:c,l:u}=$m(this.Dh|0,this.Dl|0,c|0,u|0),{h:d,l}=$m(this.Eh|0,this.El|0,d|0,l|0),{h:p,l:f}=$m(this.Fh|0,this.Fl|0,p|0,f|0),{h:m,l:h}=$m(this.Gh|0,this.Gl|0,m|0,h|0),{h:y,l:v}=$m(this.Hh|0,this.Hl|0,y|0,v|0),this.set(r,n,i,o,s,a,c,u,d,l,p,f,m,h,y,v)}roundClean(){OZ(bh,_h)}destroy(){this.destroyed=!0,OZ(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},zyt=class extends Hyt{Ah=vs[0]|0;Al=vs[1]|0;Bh=vs[2]|0;Bl=vs[3]|0;Ch=vs[4]|0;Cl=vs[5]|0;Dh=vs[6]|0;Dl=vs[7]|0;Eh=vs[8]|0;El=vs[9]|0;Fh=vs[10]|0;Fl=vs[11]|0;Gh=vs[12]|0;Gl=vs[13]|0;Hh=vs[14]|0;Hl=vs[15]|0;constructor(){super(64)}},Fyt=Iyt(()=>new zyt,Cyt(3)),Y9e=cxe;Y9e.sha512||(Y9e.sha512=e=>Fyt(e));zSr=UZ.bytesToHex,pxe=UZ.hexToBytes,FSr=UZ.concatBytes;$Sr=new TextEncoder;VSr=pxe("302e020100300506032b657004220420"),KSr=pxe("302a300506032b6570032100"),fxe="ABCDEFGHJKLMNPQRSTUVWXYZ23456789",Jyt=fxe.length-1;if((fxe.length&Jyt)!==0)throw new Error("agent pairing code alphabet must contain a power-of-two number of symbols");});var bxe={};Uo(bxe,{BindingIssuanceError:()=>rS,CardRequiredError:()=>vh,buildIssuanceRequest:()=>gxe,enrollCardUrl:()=>NB,jkt:()=>Mw,proofPayload:()=>yxe,readSeed:()=>qB,requestVisaBinding:()=>jB});function Mw(e){let t=JSON.stringify({crv:e.crv,kty:e.kty,x:e.x});return mxe.createHash("sha256").update(t,"utf8").digest("base64url")}function yxe(e,t,r){return`visa-agent-binding:v1:${e}:${t}:${r}`}function gxe(e,t,r="visa",n=Math.floor(Date.now()/1e3)){let i=tS(RB(e)),o=Buffer.from(yxe(t,Mw(i),n),"utf8"),s=Buffer.from(MZ(e,o)).toString("base64url");return{name:t,mesh:r,mode:"card",agent_pubkey:i,proof:{ts:n,sig:s}}}function NB(e){try{return new URL("/enroll-card",e).toString()}catch{return"https://auth.visacli.sh/enroll-card"}}async function jB(e){let t=gxe(e.seed,e.name,e.mesh??"visa",e.nowSec),r=e.fetchImpl??fetch,n=`${e.authUrl.replace(/\/+$/,"")}/v2/harness/agents`,i=await r(n,{method:"POST",headers:{"content-type":"application/json","x-api-key":e.apiKey,"x-source":"cli"},body:JSON.stringify(t)});if(!i.ok){let o="",s="";try{let a=await i.json();o=a?.error??"",s=a?.error_code??""}catch{}throw i.status===403&&(s==="ACCOUNT_NOT_APPROVED"||/no card/i.test(o))?new vh("No card on file \u2014 enroll a card to register on the trusted .visa mesh.",NB(e.authUrl),"no_card"):new rS(`Visa binding issuance failed (${i.status})${o?`: ${o}`:""}`,i.status,s||void 0)}return await i.json()}function qB(e){return new Uint8Array(hxe.readFileSync(e))}var mxe,hxe,vh,rS,Dw=I(()=>{"use strict";mxe=qe(require("crypto")),hxe=qe(require("fs"));Uw();vh=class extends Error{enrollUrl;reason;constructor(t,r,n){super(t),this.name="CardRequiredError",this.enrollUrl=r,this.reason=n}},rS=class extends Error{status;code;constructor(t,r,n){super(t),this.name="BindingIssuanceError",this.status=r,this.code=n}}});var wh=g(Wi=>{"use strict";Object.defineProperty(Wi,"__esModule",{value:!0});Wi.TURNKEY_API_BASE_URL_ENV=Wi.CIRCLE_TESTNET_FAUCET_URL=Wi.NETWORK_ENV=Wi.NETWORKS=void 0;Wi.resolveNetwork=Yyt;Wi.turnkeyApiBaseUrl=Xyt;Wi.explorerTxUrl=Qyt;Wi.explorerAddressUrl=egt;Wi.NETWORKS={"base-mainnet":{id:"base-mainnet",caip2:"eip155:8453",chainId:8453,usdc:{address:"0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913",eip712Domain:{name:"USD Coin",version:"2"}},rpcUrl:"https://mainnet.base.org",explorerBaseUrl:"https://basescan.org",isTestnet:!1},"base-sepolia":{id:"base-sepolia",caip2:"eip155:84532",chainId:84532,usdc:{address:"0x036CbD53842c5426634e7929541eC2318f3dCF7e",eip712Domain:{name:"USDC",version:"2"}},rpcUrl:"https://sepolia.base.org",explorerBaseUrl:"https://sepolia.basescan.org",isTestnet:!0}};Wi.NETWORK_ENV="VISA_V4_NETWORK";Wi.CIRCLE_TESTNET_FAUCET_URL="https://faucet.circle.com";var _xe={"base-mainnet":"base-mainnet","base-sepolia":"base-sepolia","eip155:8453":"base-mainnet","eip155:84532":"base-sepolia"};function Yyt(e=process.env){let t=(e[Wi.NETWORK_ENV]??"").trim();if(t==="")return Wi.NETWORKS["base-mainnet"];let r=_xe[t.toLowerCase()];if(!r)throw new Error(`unknown ${Wi.NETWORK_ENV} value ${JSON.stringify(t)} \u2014 valid values: `+Object.keys(_xe).join(", "));return Wi.NETWORKS[r]}Wi.TURNKEY_API_BASE_URL_ENV="TURNKEY_API_BASE_URL";var Zyt="https://api.turnkey.com";function Xyt(e=process.env){let t=(e[Wi.TURNKEY_API_BASE_URL_ENV]??"").trim();return t===""?Zyt:t}function Qyt(e,t){return`${e.explorerBaseUrl}/tx/${t}`}function egt(e,t){return`${e.explorerBaseUrl}/address/${t}`}});var vxe=g(UB=>{"use strict";Object.defineProperty(UB,"__esModule",{value:!0});UB.version=void 0;UB.version="1.2.3"});var F2=g(MB=>{"use strict";Object.defineProperty(MB,"__esModule",{value:!0});MB.BaseError=void 0;var tgt=vxe(),LZ=class e extends Error{constructor(t,r={}){let n=r.cause instanceof e?r.cause.details:r.cause?.message?r.cause.message:r.details,i=r.cause instanceof e&&r.cause.docsPath||r.docsPath,o=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...i?[`Docs: https://abitype.dev${i}`]:[],...n?[`Details: ${n}`]:[],`Version: abitype@${tgt.version}`].join(`
|
|
6
6
|
`);super(o),Object.defineProperty(this,"details",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"docsPath",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metaMessages",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"shortMessage",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"AbiTypeError"}),r.cause&&(this.cause=r.cause),this.details=n,this.docsPath=i,this.metaMessages=r.metaMessages,this.shortMessage=t}};MB.BaseError=LZ});var wxe=g(HZ=>{"use strict";Object.defineProperty(HZ,"__esModule",{value:!0});HZ.narrow=rgt;function rgt(e){return e}});var nS=g(Vm=>{"use strict";Object.defineProperty(Vm,"__esModule",{value:!0});Vm.isTupleRegex=Vm.integerRegex=Vm.bytesRegex=void 0;Vm.execTyped=ngt;function ngt(e,t){return e.exec(t)?.groups}Vm.bytesRegex=/^bytes([1-9]|1[0-9]|2[0-9]|3[0-2])?$/;Vm.integerRegex=/^u?int(8|16|24|32|40|48|56|64|72|80|88|96|104|112|120|128|136|144|152|160|168|176|184|192|200|208|216|224|232|240|248|256)?$/;Vm.isTupleRegex=/^\(.+?\).*?$/});var $Z=g(FZ=>{"use strict";Object.defineProperty(FZ,"__esModule",{value:!0});FZ.formatAbiParameter=zZ;var igt=nS(),xxe=/^tuple(?<array>(\[(\d*)\])*)$/;function zZ(e){let t=e.type;if(xxe.test(e.type)&&"components"in e){t="(";let r=e.components.length;for(let i=0;i<r;i++){let o=e.components[i];t+=zZ(o),i<r-1&&(t+=", ")}let n=(0,igt.execTyped)(xxe,e.type);return t+=`)${n?.array||""}`,zZ({...e,type:t})}return"indexed"in e&&e.indexed&&(t=`${t} indexed`),e.name?`${t} ${e.name}`:t}});var KZ=g(VZ=>{"use strict";Object.defineProperty(VZ,"__esModule",{value:!0});VZ.formatAbiParameters=sgt;var ogt=$Z();function sgt(e){let t="",r=e.length;for(let n=0;n<r;n++){let i=e[n];t+=(0,ogt.formatAbiParameter)(i),n!==r-1&&(t+=", ")}return t}});var GZ=g(WZ=>{"use strict";Object.defineProperty(WZ,"__esModule",{value:!0});WZ.formatAbiItem=agt;var iS=KZ();function agt(e){return e.type==="function"?`function ${e.name}(${(0,iS.formatAbiParameters)(e.inputs)})${e.stateMutability&&e.stateMutability!=="nonpayable"?` ${e.stateMutability}`:""}${e.outputs?.length?` returns (${(0,iS.formatAbiParameters)(e.outputs)})`:""}`:e.type==="event"?`event ${e.name}(${(0,iS.formatAbiParameters)(e.inputs)})`:e.type==="error"?`error ${e.name}(${(0,iS.formatAbiParameters)(e.inputs)})`:e.type==="constructor"?`constructor(${(0,iS.formatAbiParameters)(e.inputs)})${e.stateMutability==="payable"?" payable":""}`:e.type==="fallback"?`fallback() external${e.stateMutability==="payable"?" payable":""}`:"receive() external payable"}});var Exe=g(JZ=>{"use strict";Object.defineProperty(JZ,"__esModule",{value:!0});JZ.formatAbi=ugt;var cgt=GZ();function ugt(e){let t=[],r=e.length;for(let n=0;n<r;n++){let i=e[n],o=(0,cgt.formatAbiItem)(i);t.push(o)}return t}});var $2=g(fi=>{"use strict";Object.defineProperty(fi,"__esModule",{value:!0});fi.functionModifiers=fi.eventModifiers=fi.modifiers=void 0;fi.isErrorSignature=dgt;fi.execErrorSignature=lgt;fi.isEventSignature=pgt;fi.execEventSignature=fgt;fi.isFunctionSignature=mgt;fi.execFunctionSignature=hgt;fi.isStructSignature=ygt;fi.execStructSignature=ggt;fi.isConstructorSignature=bgt;fi.execConstructorSignature=_gt;fi.isFallbackSignature=vgt;fi.execFallbackSignature=wgt;fi.isReceiveSignature=Egt;var Lw=nS(),Axe=/^error (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function dgt(e){return Axe.test(e)}function lgt(e){return(0,Lw.execTyped)(Axe,e)}var Sxe=/^event (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)$/;function pgt(e){return Sxe.test(e)}function fgt(e){return(0,Lw.execTyped)(Sxe,e)}var Txe=/^function (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*)\((?<parameters>.*?)\)(?: (?<scope>external|public{1}))?(?: (?<stateMutability>pure|view|nonpayable|payable{1}))?(?: returns\s?\((?<returns>.*?)\))?$/;function mgt(e){return Txe.test(e)}function hgt(e){return(0,Lw.execTyped)(Txe,e)}var Pxe=/^struct (?<name>[a-zA-Z$_][a-zA-Z0-9$_]*) \{(?<properties>.*?)\}$/;function ygt(e){return Pxe.test(e)}function ggt(e){return(0,Lw.execTyped)(Pxe,e)}var Ixe=/^constructor\((?<parameters>.*?)\)(?:\s(?<stateMutability>payable{1}))?$/;function bgt(e){return Ixe.test(e)}function _gt(e){return(0,Lw.execTyped)(Ixe,e)}var Cxe=/^fallback\(\) external(?:\s(?<stateMutability>payable{1}))?$/;function vgt(e){return Cxe.test(e)}function wgt(e){return(0,Lw.execTyped)(Cxe,e)}var xgt=/^receive\(\) external payable$/;function Egt(e){return xgt.test(e)}fi.modifiers=new Set(["memory","indexed","storage","calldata"]);fi.eventModifiers=new Set(["indexed"]);fi.functionModifiers=new Set(["calldata","memory","storage"])});var oS=g(xh=>{"use strict";Object.defineProperty(xh,"__esModule",{value:!0});xh.UnknownSolidityTypeError=xh.UnknownTypeError=xh.InvalidAbiItemError=void 0;var QZ=F2(),YZ=class extends QZ.BaseError{constructor({signature:t}){super("Failed to parse ABI item.",{details:`parseAbiItem(${JSON.stringify(t,null,2)})`,docsPath:"/api/human#parseabiitem-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiItemError"})}};xh.InvalidAbiItemError=YZ;var ZZ=class extends QZ.BaseError{constructor({type:t}){super("Unknown type.",{metaMessages:[`Type "${t}" is not a valid ABI type. Perhaps you forgot to include a struct signature?`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownTypeError"})}};xh.UnknownTypeError=ZZ;var XZ=class extends QZ.BaseError{constructor({type:t}){super("Unknown type.",{metaMessages:[`Type "${t}" is not a valid ABI type.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSolidityTypeError"})}};xh.UnknownSolidityTypeError=XZ});var Hw=g(ws=>{"use strict";Object.defineProperty(ws,"__esModule",{value:!0});ws.InvalidAbiTypeParameterError=ws.InvalidFunctionModifierError=ws.InvalidModifierError=ws.SolidityProtectedKeywordError=ws.InvalidParameterError=ws.InvalidAbiParametersError=ws.InvalidAbiParameterError=void 0;var V2=F2(),eX=class extends V2.BaseError{constructor({param:t}){super("Failed to parse ABI parameter.",{details:`parseAbiParameter(${JSON.stringify(t,null,2)})`,docsPath:"/api/human#parseabiparameter-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiParameterError"})}};ws.InvalidAbiParameterError=eX;var tX=class extends V2.BaseError{constructor({params:t}){super("Failed to parse ABI parameters.",{details:`parseAbiParameters(${JSON.stringify(t,null,2)})`,docsPath:"/api/human#parseabiparameters-1"}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiParametersError"})}};ws.InvalidAbiParametersError=tX;var rX=class extends V2.BaseError{constructor({param:t}){super("Invalid ABI parameter.",{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParameterError"})}};ws.InvalidParameterError=rX;var nX=class extends V2.BaseError{constructor({param:t,name:r}){super("Invalid ABI parameter.",{details:t,metaMessages:[`"${r}" is a protected Solidity keyword. More info: https://docs.soliditylang.org/en/latest/cheatsheet.html`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"SolidityProtectedKeywordError"})}};ws.SolidityProtectedKeywordError=nX;var iX=class extends V2.BaseError{constructor({param:t,type:r,modifier:n}){super("Invalid ABI parameter.",{details:t,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidModifierError"})}};ws.InvalidModifierError=iX;var oX=class extends V2.BaseError{constructor({param:t,type:r,modifier:n}){super("Invalid ABI parameter.",{details:t,metaMessages:[`Modifier "${n}" not allowed${r?` in "${r}" type`:""}.`,`Data location can only be specified for array, struct, or mapping types, but "${n}" was given.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidFunctionModifierError"})}};ws.InvalidFunctionModifierError=oX;var sX=class extends V2.BaseError{constructor({abiParameter:t}){super("Invalid ABI parameter.",{details:JSON.stringify(t,null,2),metaMessages:["ABI parameter type is invalid."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidAbiTypeParameterError"})}};ws.InvalidAbiTypeParameterError=sX});var DB=g(Eh=>{"use strict";Object.defineProperty(Eh,"__esModule",{value:!0});Eh.InvalidStructSignatureError=Eh.UnknownSignatureError=Eh.InvalidSignatureError=void 0;var dX=F2(),aX=class extends dX.BaseError{constructor({signature:t,type:r}){super(`Invalid ${r} signature.`,{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidSignatureError"})}};Eh.InvalidSignatureError=aX;var cX=class extends dX.BaseError{constructor({signature:t}){super("Unknown signature.",{details:t}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"UnknownSignatureError"})}};Eh.UnknownSignatureError=cX;var uX=class extends dX.BaseError{constructor({signature:t}){super("Invalid struct signature.",{details:t,metaMessages:["No properties exist."]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidStructSignatureError"})}};Eh.InvalidStructSignatureError=uX});var pX=g(LB=>{"use strict";Object.defineProperty(LB,"__esModule",{value:!0});LB.CircularReferenceError=void 0;var Agt=F2(),lX=class extends Agt.BaseError{constructor({type:t}){super("Circular reference detected.",{metaMessages:[`Struct "${t}" is a circular reference.`]}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"CircularReferenceError"})}};LB.CircularReferenceError=lX});var mX=g(HB=>{"use strict";Object.defineProperty(HB,"__esModule",{value:!0});HB.InvalidParenthesisError=void 0;var Sgt=F2(),fX=class extends Sgt.BaseError{constructor({current:t,depth:r}){super("Unbalanced parentheses.",{metaMessages:[`"${t.trim()}" has too many ${r>0?"opening":"closing"} parentheses.`],details:`Depth "${r}"`}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"InvalidParenthesisError"})}};HB.InvalidParenthesisError=fX});var Oxe=g(sS=>{"use strict";Object.defineProperty(sS,"__esModule",{value:!0});sS.parameterCache=void 0;sS.getParameterCacheKey=Tgt;function Tgt(e,t,r){let n="";if(r)for(let i of Object.entries(r)){if(!i)continue;let o="";for(let s of i[1])o+=`[${s.type}${s.name?`:${s.name}`:""}]`;n+=`(${i[0]}{${o}})`}return t?`${t}:${e}${n}`:`${e}${n}`}sS.parameterCache=new Map([["address",{type:"address"}],["bool",{type:"bool"}],["bytes",{type:"bytes"}],["bytes32",{type:"bytes32"}],["int",{type:"int256"}],["int256",{type:"int256"}],["string",{type:"string"}],["uint",{type:"uint256"}],["uint8",{type:"uint8"}],["uint16",{type:"uint16"}],["uint24",{type:"uint24"}],["uint32",{type:"uint32"}],["uint64",{type:"uint64"}],["uint96",{type:"uint96"}],["uint112",{type:"uint112"}],["uint160",{type:"uint160"}],["uint192",{type:"uint192"}],["uint256",{type:"uint256"}],["address owner",{type:"address",name:"owner"}],["address to",{type:"address",name:"to"}],["bool approved",{type:"bool",name:"approved"}],["bytes _data",{type:"bytes",name:"_data"}],["bytes data",{type:"bytes",name:"data"}],["bytes signature",{type:"bytes",name:"signature"}],["bytes32 hash",{type:"bytes32",name:"hash"}],["bytes32 r",{type:"bytes32",name:"r"}],["bytes32 root",{type:"bytes32",name:"root"}],["bytes32 s",{type:"bytes32",name:"s"}],["string name",{type:"string",name:"name"}],["string symbol",{type:"string",name:"symbol"}],["string tokenURI",{type:"string",name:"tokenURI"}],["uint tokenId",{type:"uint256",name:"tokenId"}],["uint8 v",{type:"uint8",name:"v"}],["uint256 balance",{type:"uint256",name:"balance"}],["uint256 tokenId",{type:"uint256",name:"tokenId"}],["uint256 value",{type:"uint256",name:"value"}],["event:address indexed from",{type:"address",name:"from",indexed:!0}],["event:address indexed to",{type:"address",name:"to",indexed:!0}],["event:uint indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}],["event:uint256 indexed tokenId",{type:"uint256",name:"tokenId",indexed:!0}]])});var W2=g(Dc=>{"use strict";Object.defineProperty(Dc,"__esModule",{value:!0});Dc.parseSignature=Cgt;Dc.parseFunctionSignature=Rxe;Dc.parseEventSignature=kxe;Dc.parseErrorSignature=Bxe;Dc.parseConstructorSignature=Nxe;Dc.parseFallbackSignature=jxe;Dc.parseAbiParameter=K2;Dc.splitParameters=Uu;Dc.isSolidityType=qxe;Dc.isSolidityKeyword=Uxe;Dc.isValidDataLocation=Mxe;var zw=nS(),Pgt=oS(),zB=Hw(),Fw=DB(),Igt=mX(),FB=Oxe(),na=$2();function Cgt(e,t={}){if((0,na.isFunctionSignature)(e))return Rxe(e,t);if((0,na.isEventSignature)(e))return kxe(e,t);if((0,na.isErrorSignature)(e))return Bxe(e,t);if((0,na.isConstructorSignature)(e))return Nxe(e,t);if((0,na.isFallbackSignature)(e))return jxe(e);if((0,na.isReceiveSignature)(e))return{type:"receive",stateMutability:"payable"};throw new Fw.UnknownSignatureError({signature:e})}function Rxe(e,t={}){let r=(0,na.execFunctionSignature)(e);if(!r)throw new Fw.InvalidSignatureError({signature:e,type:"function"});let n=Uu(r.parameters),i=[],o=n.length;for(let a=0;a<o;a++)i.push(K2(n[a],{modifiers:na.functionModifiers,structs:t,type:"function"}));let s=[];if(r.returns){let a=Uu(r.returns),c=a.length;for(let u=0;u<c;u++)s.push(K2(a[u],{modifiers:na.functionModifiers,structs:t,type:"function"}))}return{name:r.name,type:"function",stateMutability:r.stateMutability??"nonpayable",inputs:i,outputs:s}}function kxe(e,t={}){let r=(0,na.execEventSignature)(e);if(!r)throw new Fw.InvalidSignatureError({signature:e,type:"event"});let n=Uu(r.parameters),i=[],o=n.length;for(let s=0;s<o;s++)i.push(K2(n[s],{modifiers:na.eventModifiers,structs:t,type:"event"}));return{name:r.name,type:"event",inputs:i}}function Bxe(e,t={}){let r=(0,na.execErrorSignature)(e);if(!r)throw new Fw.InvalidSignatureError({signature:e,type:"error"});let n=Uu(r.parameters),i=[],o=n.length;for(let s=0;s<o;s++)i.push(K2(n[s],{structs:t,type:"error"}));return{name:r.name,type:"error",inputs:i}}function Nxe(e,t={}){let r=(0,na.execConstructorSignature)(e);if(!r)throw new Fw.InvalidSignatureError({signature:e,type:"constructor"});let n=Uu(r.parameters),i=[],o=n.length;for(let s=0;s<o;s++)i.push(K2(n[s],{structs:t,type:"constructor"}));return{type:"constructor",stateMutability:r.stateMutability??"nonpayable",inputs:i}}function jxe(e){let t=(0,na.execFallbackSignature)(e);if(!t)throw new Fw.InvalidSignatureError({signature:e,type:"fallback"});return{type:"fallback",stateMutability:t.stateMutability??"nonpayable"}}var Ogt=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*(?:\spayable)?)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,Rgt=/^\((?<type>.+?)\)(?<array>(?:\[\d*?\])+?)?(?:\s(?<modifier>calldata|indexed|memory|storage{1}))?(?:\s(?<name>[a-zA-Z$_][a-zA-Z0-9$_]*))?$/,kgt=/^u?int$/;function K2(e,t){let r=(0,FB.getParameterCacheKey)(e,t?.type,t?.structs);if(FB.parameterCache.has(r))return FB.parameterCache.get(r);let n=zw.isTupleRegex.test(e),i=(0,zw.execTyped)(n?Rgt:Ogt,e);if(!i)throw new zB.InvalidParameterError({param:e});if(i.name&&Uxe(i.name))throw new zB.SolidityProtectedKeywordError({param:e,name:i.name});let o=i.name?{name:i.name}:{},s=i.modifier==="indexed"?{indexed:!0}:{},a=t?.structs??{},c,u={};if(n){c="tuple";let l=Uu(i.type),p=[],f=l.length;for(let m=0;m<f;m++)p.push(K2(l[m],{structs:a}));u={components:p}}else if(i.type in a)c="tuple",u={components:a[i.type]};else if(kgt.test(i.type))c=`${i.type}256`;else if(i.type==="address payable")c="address";else if(c=i.type,t?.type!=="struct"&&!qxe(c))throw new Pgt.UnknownSolidityTypeError({type:c});if(i.modifier){if(!t?.modifiers?.has?.(i.modifier))throw new zB.InvalidModifierError({param:e,type:t?.type,modifier:i.modifier});if(na.functionModifiers.has(i.modifier)&&!Mxe(c,!!i.array))throw new zB.InvalidFunctionModifierError({param:e,type:t?.type,modifier:i.modifier})}let d={type:`${c}${i.array??""}`,...o,...s,...u};return FB.parameterCache.set(r,d),d}function Uu(e,t=[],r="",n=0){let i=e.trim().length;for(let o=0;o<i;o++){let s=e[o],a=e.slice(o+1);switch(s){case",":return n===0?Uu(a,[...t,r.trim()]):Uu(a,t,`${r}${s}`,n);case"(":return Uu(a,t,`${r}${s}`,n+1);case")":return Uu(a,t,`${r}${s}`,n-1);default:return Uu(a,t,`${r}${s}`,n)}}if(r==="")return t;if(n!==0)throw new Igt.InvalidParenthesisError({current:r,depth:n});return t.push(r.trim()),t}function qxe(e){return e==="address"||e==="bool"||e==="function"||e==="string"||zw.bytesRegex.test(e)||zw.integerRegex.test(e)}var Bgt=/^(?:after|alias|anonymous|apply|auto|byte|calldata|case|catch|constant|copyof|default|defined|error|event|external|false|final|function|immutable|implements|in|indexed|inline|internal|let|mapping|match|memory|mutable|null|of|override|partial|private|promise|public|pure|reference|relocatable|return|returns|sizeof|static|storage|struct|super|supports|switch|this|true|try|typedef|typeof|var|view|virtual)$/;function Uxe(e){return e==="address"||e==="bool"||e==="function"||e==="string"||e==="tuple"||zw.bytesRegex.test(e)||zw.integerRegex.test(e)||Bgt.test(e)}function Mxe(e,t){return t||e==="bytes"||e==="string"||e==="tuple"}});var aS=g(hX=>{"use strict";Object.defineProperty(hX,"__esModule",{value:!0});hX.parseStructs=Ugt;var Dxe=nS(),Ngt=oS(),jgt=Hw(),Lxe=DB(),qgt=pX(),Hxe=$2(),zxe=W2();function Ugt(e){let t={},r=e.length;for(let s=0;s<r;s++){let a=e[s];if(!(0,Hxe.isStructSignature)(a))continue;let c=(0,Hxe.execStructSignature)(a);if(!c)throw new Lxe.InvalidSignatureError({signature:a,type:"struct"});let u=c.properties.split(";"),d=[],l=u.length;for(let p=0;p<l;p++){let m=u[p].trim();if(!m)continue;let h=(0,zxe.parseAbiParameter)(m,{type:"struct"});d.push(h)}if(!d.length)throw new Lxe.InvalidStructSignatureError({signature:a});t[c.name]=d}let n={},i=Object.entries(t),o=i.length;for(let s=0;s<o;s++){let[a,c]=i[s];n[a]=Fxe(c,t)}return n}var Mgt=/^(?<type>[a-zA-Z$_][a-zA-Z0-9$_]*)(?<array>(?:\[\d*?\])+?)?$/;function Fxe(e=[],t={},r=new Set){let n=[],i=e.length;for(let o=0;o<i;o++){let s=e[o];if(Dxe.isTupleRegex.test(s.type))n.push(s);else{let c=(0,Dxe.execTyped)(Mgt,s.type);if(!c?.type)throw new jgt.InvalidAbiTypeParameterError({abiParameter:s});let{array:u,type:d}=c;if(d in t){if(r.has(d))throw new qgt.CircularReferenceError({type:d});n.push({...s,type:`tuple${u??""}`,components:Fxe(t[d],t,new Set([...r,d]))})}else if((0,zxe.isSolidityType)(d))n.push(s);else throw new Ngt.UnknownTypeError({type:d})}}return n}});var $xe=g(yX=>{"use strict";Object.defineProperty(yX,"__esModule",{value:!0});yX.parseAbi=zgt;var Dgt=$2(),Lgt=aS(),Hgt=W2();function zgt(e){let t=(0,Lgt.parseStructs)(e),r=[],n=e.length;for(let i=0;i<n;i++){let o=e[i];(0,Dgt.isStructSignature)(o)||r.push((0,Hgt.parseSignature)(o,t))}return r}});var Kxe=g(gX=>{"use strict";Object.defineProperty(gX,"__esModule",{value:!0});gX.parseAbiItem=Kgt;var Fgt=oS(),$gt=$2(),Vgt=aS(),Vxe=W2();function Kgt(e){let t;if(typeof e=="string")t=(0,Vxe.parseSignature)(e);else{let r=(0,Vgt.parseStructs)(e),n=e.length;for(let i=0;i<n;i++){let o=e[i];if(!(0,$gt.isStructSignature)(o)){t=(0,Vxe.parseSignature)(o,r);break}}}if(!t)throw new Fgt.InvalidAbiItemError({signature:e});return t}});var Gxe=g(_X=>{"use strict";Object.defineProperty(_X,"__esModule",{value:!0});_X.parseAbiParameter=Jgt;var Wgt=Hw(),bX=$2(),Ggt=aS(),Wxe=W2();function Jgt(e){let t;if(typeof e=="string")t=(0,Wxe.parseAbiParameter)(e,{modifiers:bX.modifiers});else{let r=(0,Ggt.parseStructs)(e),n=e.length;for(let i=0;i<n;i++){let o=e[i];if(!(0,bX.isStructSignature)(o)){t=(0,Wxe.parseAbiParameter)(o,{modifiers:bX.modifiers,structs:r});break}}}if(!t)throw new Wgt.InvalidAbiParameterError({param:e});return t}});var Zxe=g(wX=>{"use strict";Object.defineProperty(wX,"__esModule",{value:!0});wX.parseAbiParameters=Xgt;var Ygt=Hw(),vX=$2(),Zgt=aS(),Jxe=W2(),Yxe=W2();function Xgt(e){let t=[];if(typeof e=="string"){let r=(0,Jxe.splitParameters)(e),n=r.length;for(let i=0;i<n;i++)t.push((0,Yxe.parseAbiParameter)(r[i],{modifiers:vX.modifiers}))}else{let r=(0,Zgt.parseStructs)(e),n=e.length;for(let i=0;i<n;i++){let o=e[i];if((0,vX.isStructSignature)(o))continue;let s=(0,Jxe.splitParameters)(o),a=s.length;for(let c=0;c<a;c++)t.push((0,Yxe.parseAbiParameter)(s[c],{modifiers:vX.modifiers,structs:r}))}}if(t.length===0)throw new Ygt.InvalidAbiParametersError({params:e});return t}});var cS=g(at=>{"use strict";Object.defineProperty(at,"__esModule",{value:!0});at.CircularReferenceError=at.InvalidParenthesisError=at.UnknownSignatureError=at.InvalidSignatureError=at.InvalidStructSignatureError=at.InvalidAbiParameterError=at.InvalidAbiParametersError=at.InvalidParameterError=at.SolidityProtectedKeywordError=at.InvalidModifierError=at.InvalidFunctionModifierError=at.InvalidAbiTypeParameterError=at.UnknownSolidityTypeError=at.InvalidAbiItemError=at.UnknownTypeError=at.parseAbiParameters=at.parseAbiParameter=at.parseAbiItem=at.parseAbi=at.formatAbiParameters=at.formatAbiParameter=at.formatAbiItem=at.formatAbi=at.narrow=at.BaseError=void 0;var Qgt=F2();Object.defineProperty(at,"BaseError",{enumerable:!0,get:function(){return Qgt.BaseError}});var ebt=wxe();Object.defineProperty(at,"narrow",{enumerable:!0,get:function(){return ebt.narrow}});var tbt=Exe();Object.defineProperty(at,"formatAbi",{enumerable:!0,get:function(){return tbt.formatAbi}});var rbt=GZ();Object.defineProperty(at,"formatAbiItem",{enumerable:!0,get:function(){return rbt.formatAbiItem}});var nbt=$Z();Object.defineProperty(at,"formatAbiParameter",{enumerable:!0,get:function(){return nbt.formatAbiParameter}});var ibt=KZ();Object.defineProperty(at,"formatAbiParameters",{enumerable:!0,get:function(){return ibt.formatAbiParameters}});var obt=$xe();Object.defineProperty(at,"parseAbi",{enumerable:!0,get:function(){return obt.parseAbi}});var sbt=Kxe();Object.defineProperty(at,"parseAbiItem",{enumerable:!0,get:function(){return sbt.parseAbiItem}});var abt=Gxe();Object.defineProperty(at,"parseAbiParameter",{enumerable:!0,get:function(){return abt.parseAbiParameter}});var cbt=Zxe();Object.defineProperty(at,"parseAbiParameters",{enumerable:!0,get:function(){return cbt.parseAbiParameters}});var xX=oS();Object.defineProperty(at,"UnknownTypeError",{enumerable:!0,get:function(){return xX.UnknownTypeError}});Object.defineProperty(at,"InvalidAbiItemError",{enumerable:!0,get:function(){return xX.InvalidAbiItemError}});Object.defineProperty(at,"UnknownSolidityTypeError",{enumerable:!0,get:function(){return xX.UnknownSolidityTypeError}});var G2=Hw();Object.defineProperty(at,"InvalidAbiTypeParameterError",{enumerable:!0,get:function(){return G2.InvalidAbiTypeParameterError}});Object.defineProperty(at,"InvalidFunctionModifierError",{enumerable:!0,get:function(){return G2.InvalidFunctionModifierError}});Object.defineProperty(at,"InvalidModifierError",{enumerable:!0,get:function(){return G2.InvalidModifierError}});Object.defineProperty(at,"SolidityProtectedKeywordError",{enumerable:!0,get:function(){return G2.SolidityProtectedKeywordError}});Object.defineProperty(at,"InvalidParameterError",{enumerable:!0,get:function(){return G2.InvalidParameterError}});Object.defineProperty(at,"InvalidAbiParametersError",{enumerable:!0,get:function(){return G2.InvalidAbiParametersError}});Object.defineProperty(at,"InvalidAbiParameterError",{enumerable:!0,get:function(){return G2.InvalidAbiParameterError}});var EX=DB();Object.defineProperty(at,"InvalidStructSignatureError",{enumerable:!0,get:function(){return EX.InvalidStructSignatureError}});Object.defineProperty(at,"InvalidSignatureError",{enumerable:!0,get:function(){return EX.InvalidSignatureError}});Object.defineProperty(at,"UnknownSignatureError",{enumerable:!0,get:function(){return EX.UnknownSignatureError}});var ubt=mX();Object.defineProperty(at,"InvalidParenthesisError",{enumerable:!0,get:function(){return ubt.InvalidParenthesisError}});var dbt=pX();Object.defineProperty(at,"CircularReferenceError",{enumerable:!0,get:function(){return dbt.CircularReferenceError}})});var Jt=g(AX=>{"use strict";Object.defineProperty(AX,"__esModule",{value:!0});AX.getAction=lbt;function lbt(e,t,r){let n=e[t.name];if(typeof n=="function")return n;let i=e[r];return typeof i=="function"?i:o=>t(e,o)}});var Op=g($B=>{"use strict";Object.defineProperty($B,"__esModule",{value:!0});$B.formatAbiItem=fbt;$B.formatAbiParams=SX;var pbt=An();function fbt(e,{includeName:t=!1}={}){if(e.type!=="function"&&e.type!=="event"&&e.type!=="error")throw new pbt.InvalidDefinitionTypeError(e.type);return`${e.name}(${SX(e.inputs,{includeName:t})})`}function SX(e,{includeName:t=!1}={}){return e?e.map(r=>mbt(r,{includeName:t})).join(t?", ":","):""}function mbt(e,{includeName:t}){return e.type.startsWith("tuple")?`(${SX(e.components,{includeName:t})})${e.type.slice(5)}`:e.type+(t&&e.name?` ${e.name}`:"")}});var Lo=g(TX=>{"use strict";Object.defineProperty(TX,"__esModule",{value:!0});TX.isHex=hbt;function hbt(e,{strict:t=!0}={}){return!e||typeof e!="string"?!1:t?/^0x[0-9a-fA-F]*$/.test(e):e.startsWith("0x")}});var Ho=g(PX=>{"use strict";Object.defineProperty(PX,"__esModule",{value:!0});PX.size=gbt;var ybt=Lo();function gbt(e){return(0,ybt.isHex)(e,{strict:!1})?Math.ceil((e.length-2)/2):e.length}});var Xxe=g(VB=>{"use strict";Object.defineProperty(VB,"__esModule",{value:!0});VB.version=void 0;VB.version="2.54.6"});var At=g(uS=>{"use strict";Object.defineProperty(uS,"__esModule",{value:!0});uS.BaseError=void 0;uS.setErrorConfig=bbt;var Qxe=Xxe(),KB={getDocsUrl:({docsBaseUrl:e,docsPath:t="",docsSlug:r})=>t?`${e??"https://viem.sh"}${t}${r?`#${r}`:""}`:void 0,version:`viem@${Qxe.version}`};function bbt(e){KB=e}var IX=class e extends Error{constructor(t,r={}){let n=r.cause instanceof e?r.cause.details:r.cause?.message?r.cause.message:r.details,i=r.cause instanceof e&&r.cause.docsPath||r.docsPath,o=KB.getDocsUrl?.({...r,docsPath:i}),s=[t||"An error occurred.","",...r.metaMessages?[...r.metaMessages,""]:[],...o?[`Docs: ${o}`]:[],...n?[`Details: ${n}`]:[],...KB.version?[`Version: ${KB.version}`]:[]].join(`
|
|
@@ -20650,14 +20650,14 @@ ${e.senderName}
|
|
|
20650
20650
|
${e.timestampMs}
|
|
20651
20651
|
${e.messageType}
|
|
20652
20652
|
${t}
|
|
20653
|
-
${e.nonce}`;return d8r.encode(r)}function f8r(e,t,r,n,i,o,s){return p8r({messageId:e,senderPeerId:t,senderName:r,timestampMs:n,messageType:i,payload:o,nonce:s})}function m8r(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 M8r(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Wpt(e,t,r=""){let n=M8r(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 upt(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 D8r(e,t){Wpt(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 i8e(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function X4e(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function L8r(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 F8r(e,t=!1){return t?{h:Number(e&YJ),l:Number(e>>dpt&YJ)}:{h:Number(e>>dpt&YJ)|0,l:Number(e&YJ)|0}}function $8r(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}=F8r(e[o],t);[n[o],i[o]]=[s,a]}return[n,i]}function th(e,t,r,n){let i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:i|0}}function r3r(){return N8r.randomSecretKey()}function Jpt(e){return k8r(e)}function n3r(){let e=r3r();return{secretKey:e,publicKey:Jpt(e)}}function i3r(e){if((0,m2.existsSync)(e)){let r=(0,m2.readFileSync)(e),n=new Uint8Array(r.buffer.slice(r.byteOffset,r.byteOffset+32));return{secretKey:n,publicKey:Jpt(n)}}let t=n3r();return(0,m2.mkdirSync)((0,hpt.dirname)(e),{recursive:!0}),(0,m2.writeFileSync)(e,new Uint8Array(t.secretKey)),t}function o3r(e){let{secretKey:t,publicKey:r}=i3r(e);return{privateKey:t,publicKey:r}}async function s3r(e,t,r,n,i,o,s,a){let c=f8r(t,r,n,i,o,s,a);return{signature:await a8r(e,c),signatureInput:l8r.subwayAgentMsgV1}}function mpt(e){return u8r(e)}var m2,hpt,h4r,y4r,g4r,b4r,_4r,ypt,tY,QJ,$lt,Vlt,V4e,K4e,v4r,aY,w4r,hs,x4r,E4r,A4r,rh,cY,o8e,gpt,s8e,X1,Klt,a8e,bpt,S4r,TA,T4r,rY,nw,En,Wlt,$e,_pt,vpt,wpt,xpt,W4e,Q4e,Ck,uw,aw,Ept,Apt,Pm,P4r,Glt,I4r,e8e,c8e,C4r,Spt,O4r,R4r,k4r,B4r,N4r,j4r,u8e,Tpt,nY,q4r,Ppt,t8e,U4r,Jlt,Ylt,M4r,Opt,Rpt,c2,Zs,WJ,Xlt,Qlt,ept,xA,EA,GJ,JJ,V4r,K4r,W4r,G4r,J4r,Y4r,Z4r,u2,X4r,Q4r,kpt,e8r,t8r,d2,l2,r8r,n8r,i8r,o8r,tpt,c8r,Bpt,d8r,l8r,Npt,h8r,jpt,iY,eY,rpt,npt,J4e,Y4e,y8r,PA,g8r,ys,b8r,_8r,v8r,h2,uY,d8e,qpt,Upt,eh,ipt,Mpt,Dpt,w8r,l8e,x8r,oY,ow,Dn,opt,Ve,E8r,A8r,Lpt,Hpt,Z4e,r8e,Ok,IA,cw,S8r,zpt,Cm,T8r,spt,P8r,I8r,C8r,O8r,Fpt,R8r,$pt,k8r,Vpt,B8r,N8r,sY,j8r,Kpt,n8e,q8r,apt,cpt,U8r,H8r,z8r,Xs,YJ,dpt,lpt,ppt,AA,SA,ZJ,XJ,V8r,K8r,W8r,G8r,J8r,Y8r,Gpt,Z8r,X8r,p2,f2,Q8r,e3r,t3r,fpt,a3r,c3r,Ypt,Zpt=I(()=>{"use strict";z4e();z4e();F4e();m2=require("fs"),hpt=require("path");h4r=1e3,y4r=10,g4r=3e4,b4r=3e4,_4r=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??h4r,this.maxReconnectAttempts=e.maxReconnectAttempts??y4r,this.pingInterval=e.pingInterval??g4r}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=f4r();if(!r){t(new Ys('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 Ys(`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 Ys("WebSocket closed before connection established")))},this.ws.onerror=()=>{n||(n=!0,t(new Ys(`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 Ys("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=m4r(this.reconnectInterval*Math.pow(2,this.reconnectAttempt),this.reconnectInterval,b4r);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)}}},ypt=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:tY,n:QJ,Gx:$lt,Gy:Vlt,a:V4e,d:K4e,h:v4r}=ypt,aY=32,w4r=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},hs=(e="")=>{let t=new Error(e);throw w4r(t,hs),t},x4r=e=>typeof e=="bigint",E4r=e=>typeof e=="string",A4r=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,rh=(e,t,r="")=>{let n=A4r(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},cY=e=>new Uint8Array(e),o8e=e=>Uint8Array.from(e),gpt=(e,t)=>e.toString(16).padStart(t,"0"),s8e=e=>Array.from(rh(e)).map(t=>gpt(t,2)).join(""),X1={_0:48,_9:57,A:65,F:70,a:97,f:102},Klt=e=>{if(e>=X1._0&&e<=X1._9)return e-X1._0;if(e>=X1.A&&e<=X1.F)return e-(X1.A-10);if(e>=X1.a&&e<=X1.f)return e-(X1.a-10)},a8e=e=>{let t="hex invalid";if(!E4r(e))return hs(t);let r=e.length,n=r/2;if(r%2)return hs(t);let i=cY(n);for(let o=0,s=0;o<n;o++,s+=2){let a=Klt(e.charCodeAt(s)),c=Klt(e.charCodeAt(s+1));if(a===void 0||c===void 0)return hs(t);i[o]=a*16+c}return i},bpt=()=>globalThis?.crypto,S4r=()=>bpt()?.subtle??hs("crypto.subtle must be defined, consider polyfill"),TA=(...e)=>{let t=0;for(let i of e)t+=rh(i).length;let r=cY(t),n=0;return e.forEach(i=>{r.set(i,n),n+=i.length}),r},T4r=(e=aY)=>bpt().getRandomValues(cY(e)),rY=BigInt,nw=(e,t,r,n="bad number: out of range")=>{if(!x4r(e))throw new TypeError(n);if(t<=e&&e<r)return e;throw new RangeError(n)},En=(e,t=tY)=>{let r=e%t;return r>=0n?r:t+r},Wlt=(1n<<255n)-1n,$e=e=>{e<0n&&hs("negative coordinate");let t=(e>>255n)*19n+(e&Wlt);return t=(t>>255n)*19n+(t&Wlt),t%tY},_pt=e=>En(e,QJ),vpt=(e,t)=>{(e===0n||t<=0n)&&hs("no inverse n="+e+" mod="+t);let r=En(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?En(i,t):hs("no inverse")},wpt=e=>{let t=Tpt[e];return typeof t!="function"&&hs("hashes."+e+" not set"),t},xpt=e=>rh(e,64,"digest"),W4e=e=>e instanceof Ck?e:hs("Point expected"),Q4e=2n**256n,Ck=class iw{static BASE;static ZERO;X;Y;Z;T;constructor(t,r,n,i){let o=Q4e;this.X=nw(t,0n,o),this.Y=nw(r,0n,o),this.Z=nw(n,1n,o),this.T=nw(i,0n,o),Object.freeze(this)}static CURVE(){return ypt}static fromAffine(t){return new iw(t.x,t.y,1n,$e(t.x*t.y))}static fromBytes(t,r=!1){let n=K4e,i=o8e(rh(t,aY)),o=t[31];i[31]=o&-129;let s=Apt(i);nw(s,0n,r?Q4e:tY);let c=$e(s*s),u=En(c-1n),d=$e(n*c+1n),{isValid:l,value:p}=I4r(u,d);l||hs("bad point: y not sqrt");let f=(p&1n)===1n,m=(o&128)!==0;return!r&&p===0n&&m&&hs("bad point: x==0, isLastByteOdd"),m!==f&&(p=En(-p)),new iw(p,s,1n,$e(p*s))}static fromHex(t,r){return iw.fromBytes(a8e(t),r)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=V4e,r=K4e,n=this;if(n.is0())return hs("bad point: ZERO");let{X:i,Y:o,Z:s,T:a}=n,c=$e(i*i),u=$e(o*o),d=$e(s*s),l=$e(d*d),p=$e(c*t),f=$e(d*(p+u)),m=En(l+$e(r*$e(c*u)));if(f!==m)return hs("bad point: equation left != right (1)");let h=$e(i*o),y=$e(s*a);return h!==y?hs("bad point: equation left != right (2)"):this}equals(t){let{X:r,Y:n,Z:i}=this,{X:o,Y:s,Z:a}=W4e(t),c=$e(r*a),u=$e(o*i),d=$e(n*a),l=$e(s*i);return c===u&&d===l}is0(){return this.equals(aw)}negate(){return new iw(En(-this.X),this.Y,this.Z,En(-this.T))}double(){let{X:t,Y:r,Z:n}=this,i=V4e,o=$e(t*t),s=$e(r*r),a=$e(2n*n*n),c=$e(i*o),u=En(t+r),d=En($e(u*u)-o-s),l=En(c+s),p=En(l-a),f=En(c-s),m=$e(d*p),h=$e(l*f),y=$e(d*f),v=$e(p*l);return new iw(m,h,v,y)}add(t){let{X:r,Y:n,Z:i,T:o}=this,{X:s,Y:a,Z:c,T:u}=W4e(t),d=V4e,l=K4e,p=$e(r*s),f=$e(n*a),m=$e($e(o*l)*u),h=$e(i*c),y=En($e(En(r+n)*En(s+a))-p-f),v=En(h-m),x=En(h+m),_=En(f-$e(d*p)),w=$e(y*v),E=$e(x*_),A=$e(y*_),S=$e(v*x);return new iw(w,E,S,A)}subtract(t){return this.add(W4e(t).negate())}multiply(t,r=!0){if(!r&&t===0n||(nw(t,1n,QJ),!r&&this.is0()))return aw;if(t===1n)return this;if(this.equals(uw))return M4r(t).p;let n=aw,i=uw;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(aw))return{x:0n,y:1n};let i=vpt(n,tY);$e(n*i)!==1n&&hs("invalid inverse");let o=$e(t*i),s=$e(r*i);return{x:o,y:s}}toBytes(){let{x:t,y:r}=this.toAffine(),n=Ept(r);return n[31]|=t&1n?128:0,n}toHex(){return s8e(this.toBytes())}clearCofactor(){return this.multiply(rY(v4r),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(QJ/2n,!1).double();return QJ%2n&&(t=t.add(this)),t.is0()}},uw=new Ck($lt,Vlt,1n,En($lt*Vlt)),aw=new Ck(0n,1n,1n,0n);Ck.BASE=uw;Ck.ZERO=aw;Ept=e=>a8e(gpt(nw(e,0n,Q4e),64)).reverse(),Apt=e=>rY("0x"+s8e(o8e(rh(e)).reverse())),Pm=(e,t)=>{let r=e;for(;t-- >0n;)r=$e(r*r);return r},P4r=e=>{let t=$e(e*e),r=$e(t*e),n=$e(Pm(r,2n)*r),i=$e(Pm(n,1n)*e),o=$e(Pm(i,5n)*i),s=$e(Pm(o,10n)*o),a=$e(Pm(s,20n)*s),c=$e(Pm(a,40n)*a),u=$e(Pm(c,80n)*c),d=$e(Pm(u,80n)*c),l=$e(Pm(d,10n)*o);return{pow_p_5_8:$e(Pm(l,2n)*e),b2:r}},Glt=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,I4r=(e,t)=>{let r=$e(t*$e(t*t)),n=$e($e(r*r)*t),i=P4r($e(e*n)).pow_p_5_8,o=$e(e*$e(r*i)),s=$e(t*$e(o*o)),a=o,c=$e(o*Glt),u=s===e,d=s===En(-e),l=s===En(-e*Glt);return u&&(o=a),(d||l)&&(o=c),(En(o)&1n)===1n&&(o=En(-o)),{isValid:u||d,value:o}},e8e=e=>_pt(Apt(e)),c8e=(...e)=>Promise.resolve(wpt("sha512Async")(TA(...e))).then(xpt),C4r=(...e)=>xpt(wpt("sha512")(TA(...e))),Spt=e=>{let t=o8e(e),r=t.slice(0,32);r[0]&=248,r[31]&=127,r[31]|=64;let n=t.slice(32,64),i=e8e(r),o=uw.multiply(i),s=o.toBytes();return{head:r,prefix:n,scalar:i,point:o,pointBytes:s}},O4r=e=>c8e(rh(e,aY)).then(Spt),R4r=e=>Spt(C4r(rh(e,aY))),k4r=e=>R4r(e).pointBytes,B4r=e=>c8e(e.hashable).then(e.finish),N4r=(e,t,r)=>{let{pointBytes:n,scalar:i}=e,o=e8e(t),s=uw.multiply(o).toBytes();return{hashable:TA(s,n,r),finish:u=>{let d=_pt(o+e8e(u)*i);return rh(TA(s,Ept(d)),64)}}},j4r=async(e,t)=>{let r=rh(e),n=await O4r(t),i=await c8e(n.prefix,r);return B4r(N4r(n,i,r))},u8e=Object.freeze({bytesToHex:s8e,hexToBytes:a8e,concatBytes:TA,mod:En,invert:vpt,randomBytes:T4r}),Tpt={sha512Async:async e=>{let t=S4r(),r=TA(e);return cY(await t.digest("SHA-512",r.buffer))},sha512:void 0},nY=8,q4r=256,Ppt=Math.ceil(q4r/nY)+1,t8e=2**(nY-1),U4r=()=>{let e=[],t=uw,r=t;for(let n=0;n<Ppt;n++){r=t,e.push(r);for(let i=1;i<t8e;i++)r=r.add(t),e.push(r);t=r.double()}return e},Jlt=void 0,Ylt=(e,t)=>{let r=t.negate();return e?r:t},M4r=e=>{let t=Jlt||(Jlt=U4r()),r=aw,n=uw,i=2**nY,o=i,s=rY(i-1),a=rY(nY);for(let c=0;c<Ppt;c++){let u=Number(e&s);e>>=a,u>t8e&&(u-=o,e+=1n);let d=c*t8e,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&&hs("invalid wnaf"),{p:r,f:n}};Opt=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});Rpt=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=G4e(this.buffer)}update(e){Zlt(this),Ipt(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=G4e(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){Zlt(this),L4r(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:i}=this,{pos:o}=this;t[o++]=128,Ik(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=G4e(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()}},c2=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Zs=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),WJ=BigInt(2**32-1),Xlt=BigInt(32);Qlt=(e,t,r)=>e>>>r,ept=(e,t,r)=>e<<32-r|t>>>r,xA=(e,t,r)=>e>>>r|t<<32-r,EA=(e,t,r)=>e<<32-r|t>>>r,GJ=(e,t,r)=>e<<64-r|t>>>r-32,JJ=(e,t,r)=>e>>>r-32|t<<64-r;V4r=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),K4r=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,W4r=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),G4r=(e,t,r,n,i)=>t+r+n+i+(e/2**32|0)|0,J4r=(e,t,r,n,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(i>>>0),Y4r=(e,t,r,n,i,o)=>t+r+n+i+o+(e/2**32|0)|0,Z4r=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]),u2=new Uint32Array(64),X4r=class extends Rpt{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)u2[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let l=u2[d-15],p=u2[d-2],f=Im(l,7)^Im(l,18)^l>>>3,m=Im(p,17)^Im(p,19)^p>>>10;u2[d]=m+u2[d-7]+f+u2[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=Im(s,6)^Im(s,11)^Im(s,25),p=u+l+H4r(s,a,c)+Z4r[d]+u2[d]|0,m=(Im(r,2)^Im(r,13)^Im(r,22))+z4r(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(){Ik(u2)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Ik(this.buffer)}},Q4r=class extends X4r{A=c2[0]|0;B=c2[1]|0;C=c2[2]|0;D=c2[3]|0;E=c2[4]|0;F=c2[5]|0;G=c2[6]|0;H=c2[7]|0;constructor(){super(32)}},kpt=$4r(["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))),e8r=kpt[0],t8r=kpt[1],d2=new Uint32Array(80),l2=new Uint32Array(80),r8r=class extends Rpt{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)d2[x]=e.getUint32(t),l2[x]=e.getUint32(t+=4);for(let x=16;x<80;x++){let _=d2[x-15]|0,w=l2[x-15]|0,E=xA(_,w,1)^xA(_,w,8)^Qlt(_,w,7),A=EA(_,w,1)^EA(_,w,8)^ept(_,w,7),S=d2[x-2]|0,T=l2[x-2]|0,O=xA(S,T,19)^GJ(S,T,61)^Qlt(S,T,6),R=EA(S,T,19)^JJ(S,T,61)^ept(S,T,6),U=W4r(A,R,l2[x-7],l2[x-16]),q=G4r(U,E,O,d2[x-7],d2[x-16]);d2[x]=q|0,l2[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:v}=this;for(let x=0;x<80;x++){let _=xA(d,l,14)^xA(d,l,18)^GJ(d,l,41),w=EA(d,l,14)^EA(d,l,18)^JJ(d,l,41),E=d&p^~d&m,A=l&f^~l&h,S=J4r(v,w,A,t8r[x],l2[x]),T=Y4r(S,y,_,E,e8r[x],d2[x]),O=S|0,R=xA(r,n,28)^GJ(r,n,34)^GJ(r,n,39),U=EA(r,n,28)^JJ(r,n,34)^JJ(r,n,39),q=r&i^r&s^i&s,j=n&o^n&a^o&a;y=m|0,v=h|0,m=p|0,h=f|0,p=d|0,f=l|0,{h:d,l}=Q1(c|0,u|0,T|0,O|0),c=s|0,u=a|0,s=i|0,a=o|0,i=r|0,o=n|0;let B=V4r(O,U,j);r=K4r(B,T,R,q),n=B|0}({h:r,l:n}=Q1(this.Ah|0,this.Al|0,r|0,n|0)),{h:i,l:o}=Q1(this.Bh|0,this.Bl|0,i|0,o|0),{h:s,l:a}=Q1(this.Ch|0,this.Cl|0,s|0,a|0),{h:c,l:u}=Q1(this.Dh|0,this.Dl|0,c|0,u|0),{h:d,l}=Q1(this.Eh|0,this.El|0,d|0,l|0),{h:p,l:f}=Q1(this.Fh|0,this.Fl|0,p|0,f|0),{h:m,l:h}=Q1(this.Gh|0,this.Gl|0,m|0,h|0),{h:y,l:v}=Q1(this.Hh|0,this.Hl|0,y|0,v|0),this.set(r,n,i,o,s,a,c,u,d,l,p,f,m,h,y,v)}roundClean(){Ik(d2,l2)}destroy(){this.destroyed=!0,Ik(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},n8r=class extends r8r{Ah=Zs[0]|0;Al=Zs[1]|0;Bh=Zs[2]|0;Bl=Zs[3]|0;Ch=Zs[4]|0;Cl=Zs[5]|0;Dh=Zs[6]|0;Dl=Zs[7]|0;Eh=Zs[8]|0;El=Zs[9]|0;Fh=Zs[10]|0;Fl=Zs[11]|0;Gh=Zs[12]|0;Gl=Zs[13]|0;Hh=Zs[14]|0;Hl=Zs[15]|0;constructor(){super(64)}},i8r=Cpt(()=>new Q4r,Opt(1)),o8r=Cpt(()=>new n8r,Opt(3)),tpt=Tpt;tpt.sha512||(tpt.sha512=e=>o8r(e));c8r=u8e.bytesToHex,Bpt=u8e.hexToBytes;u8e.concatBytes;d8r=new TextEncoder,l8r={subwayAgentMsgV1:"message_id;sender_peer_id;sender_name;timestamp_ms;message_type;payload_hash;nonce"};Bpt("302e020100300506032b657004220420");Bpt("302a300506032b6570032100");Npt="ABCDEFGHJKLMNPQRSTUVWXYZ23456789",h8r=Npt.length-1;if((Npt.length&h8r)!==0)throw new Error("agent pairing code alphabet must contain a power-of-two number of symbols");jpt=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:iY,n:eY,Gx:rpt,Gy:npt,a:J4e,d:Y4e,h:y8r}=jpt,PA=32,g8r=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},ys=(e="")=>{let t=new Error(e);throw g8r(t,ys),t},b8r=e=>typeof e=="bigint",_8r=e=>typeof e=="string",v8r=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,h2=(e,t,r="")=>{let n=v8r(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},uY=e=>new Uint8Array(e),d8e=e=>Uint8Array.from(e),qpt=(e,t)=>e.toString(16).padStart(t,"0"),Upt=e=>Array.from(h2(e)).map(t=>qpt(t,2)).join(""),eh={_0:48,_9:57,A:65,F:70,a:97,f:102},ipt=e=>{if(e>=eh._0&&e<=eh._9)return e-eh._0;if(e>=eh.A&&e<=eh.F)return e-(eh.A-10);if(e>=eh.a&&e<=eh.f)return e-(eh.a-10)},Mpt=e=>{let t="hex invalid";if(!_8r(e))return ys(t);let r=e.length,n=r/2;if(r%2)return ys(t);let i=uY(n);for(let o=0,s=0;o<n;o++,s+=2){let a=ipt(e.charCodeAt(s)),c=ipt(e.charCodeAt(s+1));if(a===void 0||c===void 0)return ys(t);i[o]=a*16+c}return i},Dpt=()=>globalThis?.crypto,w8r=()=>Dpt()?.subtle??ys("crypto.subtle must be defined, consider polyfill"),l8e=(...e)=>{let t=0;for(let i of e)t+=h2(i).length;let r=uY(t),n=0;return e.forEach(i=>{r.set(i,n),n+=i.length}),r},x8r=(e=PA)=>Dpt().getRandomValues(uY(e)),oY=BigInt,ow=(e,t,r,n="bad number: out of range")=>{if(!b8r(e))throw new TypeError(n);if(t<=e&&e<r)return e;throw new RangeError(n)},Dn=(e,t=iY)=>{let r=e%t;return r>=0n?r:t+r},opt=(1n<<255n)-1n,Ve=e=>{e<0n&&ys("negative coordinate");let t=(e>>255n)*19n+(e&opt);return t=(t>>255n)*19n+(t&opt),t%iY},E8r=e=>Dn(e,eY),A8r=(e,t)=>{(e===0n||t<=0n)&&ys("no inverse n="+e+" mod="+t);let r=Dn(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?Dn(i,t):ys("no inverse")},Lpt=e=>{let t=Vpt[e];return typeof t!="function"&&ys("hashes."+e+" not set"),t},Hpt=e=>h2(e,64,"digest"),Z4e=e=>e instanceof Ok?e:ys("Point expected"),r8e=2n**256n,Ok=class sw{static BASE;static ZERO;X;Y;Z;T;constructor(t,r,n,i){let o=r8e;this.X=ow(t,0n,o),this.Y=ow(r,0n,o),this.Z=ow(n,1n,o),this.T=ow(i,0n,o),Object.freeze(this)}static CURVE(){return jpt}static fromAffine(t){return new sw(t.x,t.y,1n,Ve(t.x*t.y))}static fromBytes(t,r=!1){let n=Y4e,i=d8e(h2(t,PA)),o=t[31];i[31]=o&-129;let s=zpt(i);ow(s,0n,r?r8e:iY);let c=Ve(s*s),u=Dn(c-1n),d=Ve(n*c+1n),{isValid:l,value:p}=P8r(u,d);l||ys("bad point: y not sqrt");let f=(p&1n)===1n,m=(o&128)!==0;return!r&&p===0n&&m&&ys("bad point: x==0, isLastByteOdd"),m!==f&&(p=Dn(-p)),new sw(p,s,1n,Ve(p*s))}static fromHex(t,r){return sw.fromBytes(Mpt(t),r)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=J4e,r=Y4e,n=this;if(n.is0())return ys("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=Dn(l+Ve(r*Ve(c*u)));if(f!==m)return ys("bad point: equation left != right (1)");let h=Ve(i*o),y=Ve(s*a);return h!==y?ys("bad point: equation left != right (2)"):this}equals(t){let{X:r,Y:n,Z:i}=this,{X:o,Y:s,Z:a}=Z4e(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(cw)}negate(){return new sw(Dn(-this.X),this.Y,this.Z,Dn(-this.T))}double(){let{X:t,Y:r,Z:n}=this,i=J4e,o=Ve(t*t),s=Ve(r*r),a=Ve(2n*n*n),c=Ve(i*o),u=Dn(t+r),d=Dn(Ve(u*u)-o-s),l=Dn(c+s),p=Dn(l-a),f=Dn(c-s),m=Ve(d*p),h=Ve(l*f),y=Ve(d*f),v=Ve(p*l);return new sw(m,h,v,y)}add(t){let{X:r,Y:n,Z:i,T:o}=this,{X:s,Y:a,Z:c,T:u}=Z4e(t),d=J4e,l=Y4e,p=Ve(r*s),f=Ve(n*a),m=Ve(Ve(o*l)*u),h=Ve(i*c),y=Dn(Ve(Dn(r+n)*Dn(s+a))-p-f),v=Dn(h-m),x=Dn(h+m),_=Dn(f-Ve(d*p)),w=Ve(y*v),E=Ve(x*_),A=Ve(y*_),S=Ve(v*x);return new sw(w,E,S,A)}subtract(t){return this.add(Z4e(t).negate())}multiply(t,r=!0){if(!r&&t===0n||(ow(t,1n,eY),!r&&this.is0()))return cw;if(t===1n)return this;if(this.equals(IA))return U8r(t).p;let n=cw,i=IA;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(cw))return{x:0n,y:1n};let i=A8r(n,iY);Ve(n*i)!==1n&&ys("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=S8r(r);return n[31]|=t&1n?128:0,n}toHex(){return Upt(this.toBytes())}clearCofactor(){return this.multiply(oY(y8r),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(eY/2n,!1).double();return eY%2n&&(t=t.add(this)),t.is0()}},IA=new Ok(rpt,npt,1n,Dn(rpt*npt)),cw=new Ok(0n,1n,1n,0n);Ok.BASE=IA;Ok.ZERO=cw;S8r=e=>Mpt(qpt(ow(e,0n,r8e),64)).reverse(),zpt=e=>oY("0x"+Upt(d8e(h2(e)).reverse())),Cm=(e,t)=>{let r=e;for(;t-- >0n;)r=Ve(r*r);return r},T8r=e=>{let t=Ve(e*e),r=Ve(t*e),n=Ve(Cm(r,2n)*r),i=Ve(Cm(n,1n)*e),o=Ve(Cm(i,5n)*i),s=Ve(Cm(o,10n)*o),a=Ve(Cm(s,20n)*s),c=Ve(Cm(a,40n)*a),u=Ve(Cm(c,80n)*c),d=Ve(Cm(u,80n)*c),l=Ve(Cm(d,10n)*o);return{pow_p_5_8:Ve(Cm(l,2n)*e),b2:r}},spt=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,P8r=(e,t)=>{let r=Ve(t*Ve(t*t)),n=Ve(Ve(r*r)*t),i=T8r(Ve(e*n)).pow_p_5_8,o=Ve(e*Ve(r*i)),s=Ve(t*Ve(o*o)),a=o,c=Ve(o*spt),u=s===e,d=s===Dn(-e),l=s===Dn(-e*spt);return u&&(o=a),(d||l)&&(o=c),(Dn(o)&1n)===1n&&(o=Dn(-o)),{isValid:u||d,value:o}},I8r=e=>E8r(zpt(e)),C8r=(...e)=>Promise.resolve(Lpt("sha512Async")(l8e(...e))).then(Hpt),O8r=(...e)=>Hpt(Lpt("sha512")(l8e(...e))),Fpt=e=>{let t=d8e(e),r=t.slice(0,32);r[0]&=248,r[31]&=127,r[31]|=64;let n=t.slice(32,64),i=I8r(r),o=IA.multiply(i),s=o.toBytes();return{head:r,prefix:n,scalar:i,point:o,pointBytes:s}},R8r=e=>C8r(h2(e,PA)).then(Fpt),$pt=e=>Fpt(O8r(h2(e,PA))),k8r=e=>$pt(e).pointBytes,Vpt={sha512Async:async e=>{let t=w8r(),r=l8e(e);return uY(await t.digest("SHA-512",r.buffer))},sha512:void 0},B8r=e=>(e=e===void 0?x8r(PA):e,h2(e,PA)),N8r=Object.freeze({getExtendedPublicKeyAsync:R8r,getExtendedPublicKey:$pt,randomSecretKey:B8r}),sY=8,j8r=256,Kpt=Math.ceil(j8r/sY)+1,n8e=2**(sY-1),q8r=()=>{let e=[],t=IA,r=t;for(let n=0;n<Kpt;n++){r=t,e.push(r);for(let i=1;i<n8e;i++)r=r.add(t),e.push(r);t=r.double()}return e},apt=void 0,cpt=(e,t)=>{let r=t.negate();return e?r:t},U8r=e=>{let t=apt||(apt=q8r()),r=cw,n=IA,i=2**sY,o=i,s=oY(i-1),a=oY(sY);for(let c=0;c<Kpt;c++){let u=Number(e&s);e>>=a,u>n8e&&(u-=o,e+=1n);let d=c*n8e,l=d,p=d+Math.abs(u)-1,f=c%2!==0,m=u<0;u===0?n=n.add(cpt(f,t[l])):r=r.add(cpt(m,t[p]))}return e!==0n&&ys("invalid wnaf"),{p:r,f:n}};H8r=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}),z8r=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=X4e(this.buffer)}update(e){upt(this),Wpt(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=X4e(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){upt(this),D8r(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:i}=this,{pos:o}=this;t[o++]=128,i8e(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=X4e(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()}},Xs=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),YJ=BigInt(2**32-1),dpt=BigInt(32);lpt=(e,t,r)=>e>>>r,ppt=(e,t,r)=>e<<32-r|t>>>r,AA=(e,t,r)=>e>>>r|t<<32-r,SA=(e,t,r)=>e<<32-r|t>>>r,ZJ=(e,t,r)=>e<<64-r|t>>>r-32,XJ=(e,t,r)=>e>>>r-32|t<<64-r;V8r=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),K8r=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,W8r=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),G8r=(e,t,r,n,i)=>t+r+n+i+(e/2**32|0)|0,J8r=(e,t,r,n,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(i>>>0),Y8r=(e,t,r,n,i,o)=>t+r+n+i+o+(e/2**32|0)|0,Gpt=$8r(["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))),Z8r=Gpt[0],X8r=Gpt[1],p2=new Uint32Array(80),f2=new Uint32Array(80),Q8r=class extends z8r{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)p2[x]=e.getUint32(t),f2[x]=e.getUint32(t+=4);for(let x=16;x<80;x++){let _=p2[x-15]|0,w=f2[x-15]|0,E=AA(_,w,1)^AA(_,w,8)^lpt(_,w,7),A=SA(_,w,1)^SA(_,w,8)^ppt(_,w,7),S=p2[x-2]|0,T=f2[x-2]|0,O=AA(S,T,19)^ZJ(S,T,61)^lpt(S,T,6),R=SA(S,T,19)^XJ(S,T,61)^ppt(S,T,6),U=W8r(A,R,f2[x-7],f2[x-16]),q=G8r(U,E,O,p2[x-7],p2[x-16]);p2[x]=q|0,f2[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:v}=this;for(let x=0;x<80;x++){let _=AA(d,l,14)^AA(d,l,18)^ZJ(d,l,41),w=SA(d,l,14)^SA(d,l,18)^XJ(d,l,41),E=d&p^~d&m,A=l&f^~l&h,S=J8r(v,w,A,X8r[x],f2[x]),T=Y8r(S,y,_,E,Z8r[x],p2[x]),O=S|0,R=AA(r,n,28)^ZJ(r,n,34)^ZJ(r,n,39),U=SA(r,n,28)^XJ(r,n,34)^XJ(r,n,39),q=r&i^r&s^i&s,j=n&o^n&a^o&a;y=m|0,v=h|0,m=p|0,h=f|0,p=d|0,f=l|0,{h:d,l}=th(c|0,u|0,T|0,O|0),c=s|0,u=a|0,s=i|0,a=o|0,i=r|0,o=n|0;let B=V8r(O,U,j);r=K8r(B,T,R,q),n=B|0}({h:r,l:n}=th(this.Ah|0,this.Al|0,r|0,n|0)),{h:i,l:o}=th(this.Bh|0,this.Bl|0,i|0,o|0),{h:s,l:a}=th(this.Ch|0,this.Cl|0,s|0,a|0),{h:c,l:u}=th(this.Dh|0,this.Dl|0,c|0,u|0),{h:d,l}=th(this.Eh|0,this.El|0,d|0,l|0),{h:p,l:f}=th(this.Fh|0,this.Fl|0,p|0,f|0),{h:m,l:h}=th(this.Gh|0,this.Gl|0,m|0,h|0),{h:y,l:v}=th(this.Hh|0,this.Hl|0,y|0,v|0),this.set(r,n,i,o,s,a,c,u,d,l,p,f,m,h,y,v)}roundClean(){i8e(p2,f2)}destroy(){this.destroyed=!0,i8e(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},e3r=class extends Q8r{Ah=Xs[0]|0;Al=Xs[1]|0;Bh=Xs[2]|0;Bl=Xs[3]|0;Ch=Xs[4]|0;Cl=Xs[5]|0;Dh=Xs[6]|0;Dl=Xs[7]|0;Eh=Xs[8]|0;El=Xs[9]|0;Fh=Xs[10]|0;Fl=Xs[11]|0;Gh=Xs[12]|0;Gl=Xs[13]|0;Hh=Xs[14]|0;Hl=Xs[15]|0;constructor(){super(64)}},t3r=L8r(()=>new e3r,H8r(3)),fpt=Vpt;fpt.sha512||(fpt.sha512=e=>t3r(e));a3r="ws://localhost:9001/ws",c3r=3e4,Ypt=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=Pk(e.name),e.keyPath)try{this._keypair=o3r(e.keyPath)}catch{}this.options={name:this._name,url:e.url??a3r,relay:e.relay??"",autoReconnect:e.autoReconnect??!0,reconnectInterval:e.reconnectInterval??1e3,maxReconnectAttempts:e.maxReconnectAttempts??10,rpcTimeout:e.rpcTimeout??c3r,pingInterval:e.pingInterval??3e4,binding:e.binding??""},this.transport=new _4r({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=m8r(new Uint8Array(t));r&&(this._keypair={privateKey:r,publicKey:s8r(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=mpt(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 Ys(String(n)))}})}disconnect(){for(let[,e]of this.pendingCalls)clearTimeout(e.timer),e.reject(new Ys("Client disconnected"));this.pendingCalls.clear();for(let[,e]of this.pendingSend)e.reject(new Ys("Client disconnected"));this.pendingSend.clear();for(let[,e]of this.pendingResolve)e.reject(new Ys("Client disconnected"));this.pendingResolve.clear(),this.registerPromise&&(this.registerPromise.reject(new Ys("Client disconnected")),this.registerPromise=null),this.transport.disconnect(),this._peerId=null,this.hasConnectedOnce=!1}async send(e,t,r,n){let i=Pk(e),o=$4e();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 Ys(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=Pk(e),o=$4e(),s=Date.now(),a=Math.floor(Math.random()*2**32),c=new TextEncoder().encode(r),{signature:u,signatureInput:d}=await s3r(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 Ys(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=Pk(e),o=n?.correlationId??$4e(),s=n?.timeout??this.options.rpcTimeout;return new Promise((a,c)=>{let u=setTimeout(()=>{this.pendingCalls.delete(o),c(new Tk(`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 Ys(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=Pk(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 Ys(String(i)))}setTimeout(()=>{this.pendingResolve.has(t)&&(this.pendingResolve.delete(t),n(new Tk(`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=H4e(e.code,e.message);this.registerPromise&&e.code==="register_failed"&&(this.registerPromise.reject(new KJ(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=mpt(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{}}};});function Rk(){return process.env.APPDATA||Qt.join(Ln,"AppData","Roaming")}function d3r(){return process.env.LOCALAPPDATA||Qt.join(Ln,"AppData","Local")}function p8e(e){return process.platform==="win32"?e.win32:e.posix}function Qpt(){if(process.platform!=="win32")return;let e=Qt.join(d3r(),"Packages");if(y2.existsSync(e))try{let t=y2.readdirSync(e,"utf-8");for(let r of u3r){let n=t.filter(i=>i.startsWith(r)).sort()[0];if(n)return Qt.join(e,n,"LocalCache","Roaming","Claude")}}catch{return}}function l3r(){if(process.platform==="win32"){let e=Qpt();return e?Qt.join(e,"claude_desktop_config.json"):Qt.join(Rk(),"Claude","claude_desktop_config.json")}return Qt.join(Ln,"Library","Application Support","Claude","claude_desktop_config.json")}function p3r(){if(process.platform!=="win32")return[Qt.join(Ln,"Library","Application Support","Claude")];let e=[Qt.join(Rk(),"Claude")],t=Qpt();return t&&e.push(t),e}var y2,Qt,Xpt,Ln,u3r,$4n,eft=I(()=>{"use strict";y2=qe(require("fs")),Qt=qe(require("path")),Xpt=qe(require("os")),Ln=Xpt.homedir(),u3r=["Claude_","Anthropic.ClaudeDesktop_"];$4n=[{id:"claude",displayName:"Claude Code",globalConfigPath:Qt.join(Ln,".claude.json"),configKey:"mcpServers",detectPaths:[Qt.join(Ln,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:l3r(),configKey:"mcpServers",detectPaths:p3r(),postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:Qt.join(Ln,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[Qt.join(Ln,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:Qt.join(Ln,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[Qt.join(Ln,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:Qt.join(Ln,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[Qt.join(Ln,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:p8e({win32:Qt.join(Rk(),"Roo","mcp_settings.json"),posix:Qt.join(Ln,".config","Roo","mcp_settings.json")}),configKey:"mcpServers",detectPaths:[Qt.join(Ln,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:Qt.join(Ln,".vscode","mcp.json"),configKey:"servers",detectPaths:[Qt.join(Ln,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:p8e({win32:Qt.join(Rk(),"Zed","settings.json"),posix:Qt.join(Ln,".config","zed","settings.json")}),configKey:"context_servers",detectPaths:p8e({win32:[Qt.join(Rk(),"Zed")],posix:[Qt.join(Ln,".config","zed")]}),postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})},{id:"codex",displayName:"Codex",globalConfigPath:Qt.join(Ln,".codex","config.toml"),configKey:"mcp_servers",configFormat:"toml",detectPaths:[Qt.join(Ln,".codex")],postInstallHint:"Restart Codex to connect."},{id:"openclaw",displayName:"OpenClaw",globalConfigPath:Qt.join(Ln,".openclaw","openclaw.json"),configKey:"mcp.servers",detectPaths:[Qt.join(Ln,".openclaw")],postInstallHint:"Restart OpenClaw (or reload its config) to connect."},{id:"hermes",displayName:"Hermes",globalConfigPath:Qt.join(Ln,".hermes","config.yaml"),configKey:"mcp_servers",configFormat:"yaml",detectPaths:[Qt.join(Ln,".hermes")],postInstallHint:"Restart Hermes to connect."}]});var tft=I(()=>{"use strict";eft()});var rft,nft,u8n,ift=I(()=>{"use strict";rft=qe(require("node:os")),nft=qe(require("node:path"));Uw();Dw();Qd();p4e();f8e();u8n=nft.join(rft.homedir(),".visa-cli","pairings")});function h3r(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.auth_url=="string"&&typeof t.created_at=="string"}function y3r(e=sft){return Kd.existsSync(e)?Kd.readdirSync(e).filter(t=>t.endsWith(".json")).map(t=>dY.join(e,t)):[]}function aft(e=sft){let t=y3r(e).sort((r,n)=>Kd.statSync(n).mtimeMs-Kd.statSync(r).mtimeMs)[0];if(!t)return null;try{let r=JSON.parse(Kd.readFileSync(t,"utf8"));return h3r(r)?r:null}catch{return null}}function cft(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}}var Kd,oft,dY,m3r,sft,f8e=I(()=>{"use strict";Kd=qe(require("fs")),oft=qe(require("os")),dY=qe(require("path")),m3r=require("node:readline/promises");Uw();Qd();xZ();nB();g4e();Dw();tft();ift();sft=dY.join(oft.homedir(),".visa-cli","agents")});var v8e={};Uo(v8e,{SUBWAY_PROTOCOL:()=>_ft,registerDirect:()=>C3r,resolveDirect:()=>O3r});function y8e(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 g8e(e,t){return e<<3|t}function kk(e,t,r){e.push(g8e(t,2)),y8e(e,r.length);for(let n of r)e.push(n)}function g3r(e,t){let r=[];return kk(r,1,h8e.encode(e)),t&&t.length>0&&kk(r,2,h8e.encode(t)),Uint8Array.from(r)}function b3r(e,t,r){let n=[];return r!==0n&&(n.push(g8e(1,0)),y8e(n,r)),kk(n,2,g3r(e,t)),Uint8Array.from(n)}function _3r(e){let t=[];return kk(t,1,h8e.encode(e)),Uint8Array.from(t)}function v3r(e,t){let r=[];return t!==0n&&(r.push(g8e(1,0)),y8e(r,t)),kk(r,3,_3r(e)),Uint8Array.from(r)}function w3r(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=gft.decode(e.subarray(u,d)),t=d}else t=b8e(e,t,s)}return r}function x3r(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=gft.decode(e.subarray(u,d)),t=d}else t=b8e(e,t,s)}return r}function b8e(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 bft(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=w3r(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=x3r(e.subarray(u,d)),t=d}else t=b8e(e,t,s)}return r}function E3r(e){let t=new Uint8Array(4+e.length);return new DataView(t.buffer).setUint32(0,e.length,!1),t.set(e,4),t}function _8e(e){return new DataView(e.buffer,e.byteOffset,4).getUint32(0,!1)}function A3r(e){if(e.length<4)return{success:!1,error:"short reply (no length prefix)"};let t=_8e(e.subarray(0,4));return e.length<4+t?{success:!1,error:`truncated frame (have ${e.length-4}, need ${t})`}:bft(e.subarray(4,4+t)).registerNameResponse??{success:!1,error:"reply carried no register_name_response"}}function S3r(e){if(e.length<4)return{peerId:new Uint8Array(0),error:"short reply (no length prefix)"};let t=_8e(e.subarray(0,4));return e.length<4+t?{peerId:new Uint8Array(0),error:`truncated frame (have ${e.length-4}, need ${t})`}:bft(e.subarray(4,4+t)).resolveNameResponse??{peerId:new Uint8Array(0),error:"reply carried no resolve_name_response"}}function m8e(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 I3r(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>uft)throw new Error("subway: reply exceeded max size");if(n<0&&r>=4&&(n=4+_8e(m8e(t).subarray(0,4)),n>uft))throw new Error("subway: declared frame exceeds max size");if(n>=0&&r>=n)return m8e(t).subarray(0,n)}return m8e(t)}async function vft(e){return(0,dft.createLibp2p)({...e?{privateKey:await(0,mft.generateKeyPairFromSeed)("Ed25519",e)}:{},transports:[(0,lft.tcp)()],connectionEncrypters:[(0,pft.noise)()],streamMuxers:[(0,fft.yamux)()],connectionGater:{denyDialMultiaddr:async()=>!1}})}async function wft(e,t,r){let n=await e.dialProtocol((0,hft.multiaddr)(t),_ft,{signal:AbortSignal.timeout(T3r)});n.send(E3r(r));let i;return Promise.race([I3r(n),new Promise((o,s)=>{i=setTimeout(()=>s(new Error("subway: request timed out")),P3r)})]).finally(()=>clearTimeout(i))}async function C3r(e){let t=await vft(e.seed);try{let r=await wft(t,e.relayMultiaddr,b3r(e.name,e.binding,e.requestId??1n)),n=A3r(r);return{success:n.success,error:n.error,peerId:t.peerId.toString()}}finally{await t.stop()}}async function O3r(e){let t=await vft(e.seed);try{let r=await wft(t,e.relayMultiaddr,v3r(e.name,e.requestId??1n)),n=S3r(r);return n.peerId.length===0?{found:!1,peerId:"",error:n.error||"name not found"}:{found:!0,peerId:(0,yft.toString)(n.peerId,"base58btc"),error:""}}finally{await t.stop()}}var dft,lft,pft,fft,mft,hft,yft,h8e,gft,_ft,T3r,P3r,uft,w8e=I(()=>{"use strict";F4e();dft=require("libp2p"),lft=require("@libp2p/tcp"),pft=require("@chainsafe/libp2p-noise"),fft=require("@chainsafe/libp2p-yamux"),mft=require("@libp2p/crypto/keys"),hft=require("@multiformats/multiaddr"),yft=require("uint8arrays/to-string"),h8e=new TextEncoder,gft=new TextDecoder;_ft="/subway/p2p/1.0.0",T3r=15e3,P3r=15e3,uft=1<<20});var Nk={};Uo(Nk,{DEFAULT_VISA_RELAY_MULTIADDR:()=>Eft,MESH:()=>gs,RELAY_URL:()=>P8e,connectOrThrow:()=>mY,ensureMailbox:()=>k8e,isSubwayEnabled:()=>I8e,listRegistered:()=>q3r,loadBindingFor:()=>R8e,loadRegistry:()=>dw,makeClient:()=>fY,maybeMintVisaBinding:()=>Sft,meshName:()=>yp,pairedVisaBinding:()=>Tft,readInbox:()=>M3r,registerName:()=>B3r,resolveActingName:()=>k3r,resolveMeshName:()=>N3r,seedSubwayKeyFromTapAgent:()=>Aft,sendMessage:()=>j3r,sendVia:()=>D3r,subwayKeyPath:()=>pY,visaRelayMultiaddr:()=>T8e});function T8e(e=process.env){return e.SUBWAY_RELAY_MULTIADDR??Eft}function yp(e){return e.includes(".")?e:`${e}.${gs}`}function I8e(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 O8e(){so.mkdirSync(C8e,{recursive:!0,mode:448})}function R3r(e){return e.replace(/[^a-zA-Z0-9_.-]/g,"_")}function pY(e){return CA.join(C8e,`${R3r(e)}.key`)}function dw(){if(!so.existsSync(S8e))return{};try{return JSON.parse(so.readFileSync(S8e,"utf8"))}catch{return{}}}function E8e(e){O8e(),so.writeFileSync(S8e,JSON.stringify(e,null,2),{mode:384})}function A8e(){try{return Bk.userInfo().username}catch{return"local"}}function Aft(e){if(so.existsSync(e)||!so.existsSync(x8e))return null;let t=so.readdirSync(x8e).filter(n=>n.endsWith(".json"));if(t.length===0)return null;let r=t.map(n=>CA.join(x8e,n)).sort((n,i)=>so.statSync(i).mtimeMs-so.statSync(n).mtimeMs)[0];try{let n=JSON.parse(so.readFileSync(r,"utf8"));if(!n.private_key_jwk)return null;let i=DZ(n.private_key_jwk);return O8e(),so.writeFileSync(e,Buffer.from(i),{mode:384}),n.agent_id??null}catch{return null}}function fY(e,t={}){return new Ypt({name:yp(e),url:P8e,keyPath:pY(e),autoReconnect:t.autoReconnect??!1,binding:t.binding})}function R8e(e){if(gs!=="visa")return;let t=dw()[e];if(t?.binding&&!(t.bindingExpiresAt&&Date.parse(t.bindingExpiresAt)<=Date.now()))return t.binding}async function mY(e,t=15e3){await Promise.race([e.connect(),new Promise((r,n)=>setTimeout(()=>n(new Error(`Subway relay connect timed out after ${t}ms (${P8e})`)),t))])}function k3r(e){if(e)return e;let t=Object.keys(dw());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 Sft(e){if(gs!=="visa")return null;let t=process.env.VISA_CLI_API_KEY?.trim();if(!t)throw new vh("No Visa Key configured \u2014 set VISA_CLI_API_KEY (a Visa Key with a card on file) to register on the trusted .visa mesh.",NB(ta()),"no_key");try{return await jB({authUrl:ta(),apiKey:t,seed:qB(pY(e)),name:yp(e)})}catch(r){if(r instanceof vh)throw r;return console.warn(`[subway] Visa binding not minted: ${r instanceof Error?r.message:String(r)}`),null}}function Tft(e=Date.now()){let t=aft();if(!t?.binding_jwt)return null;let r=cft(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 B3r(e){let t=pY(e),r=Aft(t),n=yp(e);gs==="visa"&&!so.existsSync(t)&&(O8e(),so.writeFileSync(t,(0,xft.randomBytes)(32),{mode:384}));let i=gs==="visa"?Tft():null,o,s={};if(i)o=i.binding,s={binding:i.binding,bindingExpiresAt:i.bindingExpiresAt};else{let u=await Sft(e);u&&(o=u.binding,s={binding:u.binding,bindingExpiresAt:new Date(Date.now()+u.expires_in*1e3).toISOString()})}let a=gs==="visa"?T8e():process.env.SUBWAY_RELAY_MULTIADDR;if(gs==="visa"&&a){let{registerDirect:u}=await Promise.resolve().then(()=>(w8e(),v8e)),d=await u({relayMultiaddr:a,seed:qB(t),name:n,binding:o});if(!d.success)throw new Error(`.visa relay admission failed: ${d.error||"unknown"}`);let l=dw();return l[e]={relayName:n,mesh:gs,peerId:d.peerId,owner:A8e(),tapAgentId:r,registeredAt:new Date().toISOString(),...s},E8e(l),{relayName:n,mesh:gs,peerId:d.peerId,tapAgentId:r,...o?{binding:o}:{}}}if(gs==="visa"&&!process.env.SUBWAY_RELAY){let u=dw();return u[e]={relayName:n,mesh:gs,peerId:null,owner:A8e(),tapAgentId:r,registeredAt:new Date().toISOString(),...s},E8e(u),{relayName:n,mesh:gs,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=fY(e,{autoReconnect:!1,binding:o});try{await mY(c);let u=dw();return u[e]={relayName:n,mesh:gs,peerId:c.peerId,owner:A8e(),tapAgentId:r,registeredAt:new Date().toISOString(),...s},E8e(u),{relayName:n,mesh:gs,peerId:c.peerId,tapAgentId:r,...o?{binding:o}:{}}}finally{c.disconnect()}}async function N3r(e){let t=yp(e),r=gs==="visa"?T8e():process.env.SUBWAY_RELAY_MULTIADDR;if(gs==="visa"&&r){let{resolveDirect:n}=await Promise.resolve().then(()=>(w8e(),v8e)),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 j3r(e,t,r){let n=fY(e,{autoReconnect:!1,binding:R8e(e)});try{await mY(n);let i=yp(t);return await n.sendSigned(i,"chat",r),{to:i,as:yp(e)}}finally{n.disconnect()}}function q3r(){let e=dw();return Object.entries(e).map(([t,r])=>({name:t,...r}))}async function k8e(e){let t=lY.get(e);if(t)return{relayName:yp(e),peerId:t.client.peerId};let r=fY(e,{autoReconnect:!0,binding:R8e(e)}),n=[];return r.onMessage(i=>{n.push({from:i.fromName,text:i.payload,ts:i.timestampMs,verified:!!i.verified}),n.length>U3r&&n.shift()}),lY.set(e,{client:r,buffer:n}),await mY(r),{relayName:yp(e),peerId:r.peerId}}async function M3r(e,t=20,r=!1){await k8e(e);let n=lY.get(e);if(!n)return[];let i=n.buffer.slice(-t);return r&&(n.buffer.length=0),i}async function D3r(e,t,r){await k8e(e);let n=lY.get(e);if(!n)throw new Error(`mailbox for ${e} unavailable`);let i=yp(t);return await n.client.sendSigned(i,"chat",r),{to:i,as:yp(e)}}var so,Bk,CA,xft,gs,Eft,P8e,C8e,S8e,x8e,lY,U3r,OA=I(()=>{"use strict";Zpt();Uw();so=qe(require("fs")),Bk=qe(require("os")),CA=qe(require("path")),xft=require("crypto");Qd();Dw();f8e();gs=process.env.SUBWAY_MESH??"relay",Eft="/dns4/subway-relay-visa.fly.dev/tcp/9100/p2p/12D3KooWM2q6SXgKFxj5wvnJ7gTD4XPjhvc5tHVVjDBrZRnJ3CKU";P8e=process.env.SUBWAY_RELAY??"wss://relay.subway.dev/ws";C8e=CA.join(Bk.homedir(),".visa-cli","subway"),S8e=CA.join(C8e,"registry.json"),x8e=CA.join(Bk.homedir(),".visa-cli","agents");lY=new Map,U3r=200});var CY={};Uo(CY,{initSentry:()=>AEr,isSentryConfigured:()=>EEr,reportFatal:()=>SEr});function EEr(){return!1}async function AEr(){return null}async function SEr(e,t){process.exit(t?.exitCode??1)}var OY=I(()=>{});var Hmt=require("@modelcontextprotocol/sdk/server/index.js"),zmt=require("@modelcontextprotocol/sdk/server/stdio.js"),Rm=require("@modelcontextprotocol/sdk/types.js");var ye={};Uo(ye,{BRAND:()=>O0t,DIRTY:()=>_2,EMPTY_PATH:()=>c0t,INVALID:()=>ft,NEVER:()=>m1t,OK:()=>bs,ParseStatus:()=>Mo,Schema:()=>Bt,ZodAny:()=>uh,ZodArray:()=>jm,ZodBigInt:()=>w2,ZodBoolean:()=>x2,ZodBranded:()=>UA,ZodCatch:()=>B2,ZodDate:()=>E2,ZodDefault:()=>k2,ZodDiscriminatedUnion:()=>Jk,ZodEffects:()=>ju,ZodEnum:()=>O2,ZodError:()=>Ua,ZodFirstPartyTypeKind:()=>_t,ZodFunction:()=>Zk,ZodIntersection:()=>P2,ZodIssueCode:()=>me,ZodLazy:()=>I2,ZodLiteral:()=>C2,ZodMap:()=>Sw,ZodNaN:()=>Pw,ZodNativeEnum:()=>R2,ZodNever:()=>Xd,ZodNull:()=>S2,ZodNullable:()=>xp,ZodNumber:()=>v2,ZodObject:()=>Ma,ZodOptional:()=>Bu,ZodParsedType:()=>Ce,ZodPipeline:()=>MA,ZodPromise:()=>dh,ZodReadonly:()=>N2,ZodRecord:()=>Yk,ZodSchema:()=>Bt,ZodSet:()=>Tw,ZodString:()=>ch,ZodSymbol:()=>Ew,ZodTransformer:()=>ju,ZodTuple:()=>wp,ZodType:()=>Bt,ZodUndefined:()=>A2,ZodUnion:()=>T2,ZodUnknown:()=>Nm,ZodVoid:()=>Aw,addIssueToContext:()=>Ee,any:()=>D0t,array:()=>F0t,bigint:()=>N0t,boolean:()=>l3e,coerce:()=>f1t,custom:()=>c3e,date:()=>j0t,datetimeRegex:()=>s3e,defaultErrorMap:()=>km,discriminatedUnion:()=>W0t,effect:()=>o1t,enum:()=>r1t,function:()=>Q0t,getErrorMap:()=>vw,getParsedType:()=>vp,instanceof:()=>k0t,intersection:()=>G0t,isAborted:()=>Wk,isAsync:()=>ww,isDirty:()=>Gk,isValid:()=>ah,late:()=>R0t,lazy:()=>e1t,literal:()=>t1t,makeIssue:()=>qA,map:()=>Z0t,nan:()=>B0t,nativeEnum:()=>n1t,never:()=>H0t,null:()=>M0t,nullable:()=>a1t,number:()=>d3e,object:()=>$0t,objectUtil:()=>BY,oboolean:()=>p1t,onumber:()=>l1t,optional:()=>s1t,ostring:()=>d1t,pipeline:()=>u1t,preprocess:()=>c1t,promise:()=>i1t,quotelessJson:()=>o0t,record:()=>Y0t,set:()=>X0t,setErrorMap:()=>a0t,strictObject:()=>V0t,string:()=>u3e,symbol:()=>q0t,transformer:()=>o1t,tuple:()=>J0t,undefined:()=>U0t,union:()=>K0t,unknown:()=>L0t,util:()=>Ft,void:()=>z0t});var Ft;(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})(Ft||(Ft={}));var BY;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(BY||(BY={}));var Ce=Ft.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),vp=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 me=Ft.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"]),o0t=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),Ua=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,Ft.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()}};Ua.create=e=>new Ua(e);var s0t=(e,t)=>{let r;switch(e.code){case me.invalid_type:e.received===Ce.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case me.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,Ft.jsonStringifyReplacer)}`;break;case me.unrecognized_keys:r=`Unrecognized key(s) in object: ${Ft.joinValues(e.keys,", ")}`;break;case me.invalid_union:r="Invalid input";break;case me.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Ft.joinValues(e.options)}`;break;case me.invalid_enum_value:r=`Invalid enum value. Expected ${Ft.joinValues(e.options)}, received '${e.received}'`;break;case me.invalid_arguments:r="Invalid function arguments";break;case me.invalid_return_type:r="Invalid function return type";break;case me.invalid_date:r="Invalid date";break;case me.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}"`:Ft.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case me.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 me.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 me.custom:r="Invalid input";break;case me.invalid_intersection_types:r="Intersection results could not be merged";break;case me.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case me.not_finite:r="Number must be finite";break;default:r=t.defaultError,Ft.assertNever(e)}return{message:r}},km=s0t;var t3e=km;function a0t(e){t3e=e}function vw(){return t3e}var qA=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}},c0t=[];function Ee(e,t){let r=vw(),n=qA({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===km?void 0:km].filter(i=>!!i)});e.common.issues.push(n)}var Mo=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 ft;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 ft;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}}},ft=Object.freeze({status:"aborted"}),_2=e=>({status:"dirty",value:e}),bs=e=>({status:"valid",value:e}),Wk=e=>e.status==="aborted",Gk=e=>e.status==="dirty",ah=e=>e.status==="valid",ww=e=>typeof Promise<"u"&&e instanceof Promise;var Ye;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(Ye||(Ye={}));var Nu=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}},r3e=(e,t)=>{if(ah(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 Ua(e.common.issues);return this._error=r,this._error}}};function Ot(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 Bt=class{get description(){return this._def.description}_getType(t){return vp(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:vp(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Mo,ctx:{common:t.parent.common,data:t.data,parsedType:vp(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(ww(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:vp(t)},i=this._parseSync({data:t,path:n.path,parent:n});return r3e(n,i)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:vp(t)};if(!this["~standard"].async)try{let n=this._parseSync({data:t,path:[],parent:r});return ah(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=>ah(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:vp(t)},i=this._parse({data:t,path:n.path,parent:n}),o=await(ww(i)?i:Promise.resolve(i));return r3e(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:me.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 ju({schema:this,typeName:_t.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 Bu.create(this,this._def)}nullable(){return xp.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return jm.create(this)}promise(){return dh.create(this,this._def)}or(t){return T2.create([this,t],this._def)}and(t){return P2.create(this,t,this._def)}transform(t){return new ju({...Ot(this._def),schema:this,typeName:_t.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new k2({...Ot(this._def),innerType:this,defaultValue:r,typeName:_t.ZodDefault})}brand(){return new UA({typeName:_t.ZodBranded,type:this,...Ot(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new B2({...Ot(this._def),innerType:this,catchValue:r,typeName:_t.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return MA.create(this,t)}readonly(){return N2.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},u0t=/^c[^\s-]{8,}$/i,d0t=/^[0-9a-z]+$/,l0t=/^[0-9A-HJKMNP-TV-Z]{26}$/i,p0t=/^[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,f0t=/^[a-z0-9_-]{21}$/i,m0t=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,h0t=/^[-+]?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)?)??$/,y0t=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,g0t="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",NY,b0t=/^(?:(?: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])$/,_0t=/^(?:(?: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])$/,v0t=/^(([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]))$/,w0t=/^(([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])$/,x0t=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,E0t=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,i3e="((\\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])))",A0t=new RegExp(`^${i3e}$`);function o3e(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 S0t(e){return new RegExp(`^${o3e(e)}$`)}function s3e(e){let t=`${i3e}T${o3e(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 T0t(e,t){return!!((t==="v4"||!t)&&b0t.test(e)||(t==="v6"||!t)&&v0t.test(e))}function P0t(e,t){if(!m0t.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 I0t(e,t){return!!((t==="v4"||!t)&&_0t.test(e)||(t==="v6"||!t)&&w0t.test(e))}var ch=class e extends Bt{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==Ce.string){let o=this._getOrReturnCtx(t);return Ee(o,{code:me.invalid_type,expected:Ce.string,received:o.parsedType}),ft}let n=new Mo,i;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(i=this._getOrReturnCtx(t,i),Ee(i,{code:me.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),Ee(i,{code:me.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?Ee(i,{code:me.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&Ee(i,{code:me.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")y0t.test(t.data)||(i=this._getOrReturnCtx(t,i),Ee(i,{validation:"email",code:me.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")NY||(NY=new RegExp(g0t,"u")),NY.test(t.data)||(i=this._getOrReturnCtx(t,i),Ee(i,{validation:"emoji",code:me.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")p0t.test(t.data)||(i=this._getOrReturnCtx(t,i),Ee(i,{validation:"uuid",code:me.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")f0t.test(t.data)||(i=this._getOrReturnCtx(t,i),Ee(i,{validation:"nanoid",code:me.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")u0t.test(t.data)||(i=this._getOrReturnCtx(t,i),Ee(i,{validation:"cuid",code:me.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")d0t.test(t.data)||(i=this._getOrReturnCtx(t,i),Ee(i,{validation:"cuid2",code:me.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")l0t.test(t.data)||(i=this._getOrReturnCtx(t,i),Ee(i,{validation:"ulid",code:me.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),Ee(i,{validation:"url",code:me.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),Ee(i,{validation:"regex",code:me.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),Ee(i,{code:me.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),Ee(i,{code:me.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(i=this._getOrReturnCtx(t,i),Ee(i,{code:me.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?s3e(o).test(t.data)||(i=this._getOrReturnCtx(t,i),Ee(i,{code:me.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?A0t.test(t.data)||(i=this._getOrReturnCtx(t,i),Ee(i,{code:me.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?S0t(o).test(t.data)||(i=this._getOrReturnCtx(t,i),Ee(i,{code:me.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?h0t.test(t.data)||(i=this._getOrReturnCtx(t,i),Ee(i,{validation:"duration",code:me.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?T0t(t.data,o.version)||(i=this._getOrReturnCtx(t,i),Ee(i,{validation:"ip",code:me.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?P0t(t.data,o.alg)||(i=this._getOrReturnCtx(t,i),Ee(i,{validation:"jwt",code:me.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?I0t(t.data,o.version)||(i=this._getOrReturnCtx(t,i),Ee(i,{validation:"cidr",code:me.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?x0t.test(t.data)||(i=this._getOrReturnCtx(t,i),Ee(i,{validation:"base64",code:me.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?E0t.test(t.data)||(i=this._getOrReturnCtx(t,i),Ee(i,{validation:"base64url",code:me.invalid_string,message:o.message}),n.dirty()):Ft.assertNever(o);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(i=>t.test(i),{validation:r,code:me.invalid_string,...Ye.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...Ye.errToObj(t)})}url(t){return this._addCheck({kind:"url",...Ye.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...Ye.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...Ye.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...Ye.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...Ye.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...Ye.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...Ye.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...Ye.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...Ye.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...Ye.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...Ye.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...Ye.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,...Ye.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,...Ye.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...Ye.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...Ye.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...Ye.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...Ye.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...Ye.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...Ye.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...Ye.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...Ye.errToObj(r)})}nonempty(t){return this.min(1,Ye.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}};ch.create=e=>new ch({checks:[],typeName:_t.ZodString,coerce:e?.coerce??!1,...Ot(e)});function C0t(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 v2=class e extends Bt{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 Ee(o,{code:me.invalid_type,expected:Ce.number,received:o.parsedType}),ft}let n,i=new Mo;for(let o of this._def.checks)o.kind==="int"?Ft.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),Ee(n,{code:me.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),Ee(n,{code:me.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),Ee(n,{code:me.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?C0t(t.data,o.value)!==0&&(n=this._getOrReturnCtx(t,n),Ee(n,{code:me.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),Ee(n,{code:me.not_finite,message:o.message}),i.dirty()):Ft.assertNever(o);return{status:i.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,Ye.toString(r))}gt(t,r){return this.setLimit("min",t,!1,Ye.toString(r))}lte(t,r){return this.setLimit("max",t,!0,Ye.toString(r))}lt(t,r){return this.setLimit("max",t,!1,Ye.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:Ye.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:Ye.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Ye.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Ye.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Ye.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Ye.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:Ye.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:Ye.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Ye.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Ye.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"&&Ft.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)}};v2.create=e=>new v2({checks:[],typeName:_t.ZodNumber,coerce:e?.coerce||!1,...Ot(e)});var w2=class e extends Bt{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 Mo;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),Ee(n,{code:me.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),Ee(n,{code:me.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),Ee(n,{code:me.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):Ft.assertNever(o);return{status:i.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return Ee(r,{code:me.invalid_type,expected:Ce.bigint,received:r.parsedType}),ft}gte(t,r){return this.setLimit("min",t,!0,Ye.toString(r))}gt(t,r){return this.setLimit("min",t,!1,Ye.toString(r))}lte(t,r){return this.setLimit("max",t,!0,Ye.toString(r))}lt(t,r){return this.setLimit("max",t,!1,Ye.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:Ye.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:Ye.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Ye.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Ye.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Ye.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:Ye.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}};w2.create=e=>new w2({checks:[],typeName:_t.ZodBigInt,coerce:e?.coerce??!1,...Ot(e)});var x2=class extends Bt{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==Ce.boolean){let n=this._getOrReturnCtx(t);return Ee(n,{code:me.invalid_type,expected:Ce.boolean,received:n.parsedType}),ft}return bs(t.data)}};x2.create=e=>new x2({typeName:_t.ZodBoolean,coerce:e?.coerce||!1,...Ot(e)});var E2=class e extends Bt{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==Ce.date){let o=this._getOrReturnCtx(t);return Ee(o,{code:me.invalid_type,expected:Ce.date,received:o.parsedType}),ft}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return Ee(o,{code:me.invalid_date}),ft}let n=new Mo,i;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(i=this._getOrReturnCtx(t,i),Ee(i,{code:me.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),Ee(i,{code:me.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):Ft.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:Ye.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:Ye.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}};E2.create=e=>new E2({checks:[],coerce:e?.coerce||!1,typeName:_t.ZodDate,...Ot(e)});var Ew=class extends Bt{_parse(t){if(this._getType(t)!==Ce.symbol){let n=this._getOrReturnCtx(t);return Ee(n,{code:me.invalid_type,expected:Ce.symbol,received:n.parsedType}),ft}return bs(t.data)}};Ew.create=e=>new Ew({typeName:_t.ZodSymbol,...Ot(e)});var A2=class extends Bt{_parse(t){if(this._getType(t)!==Ce.undefined){let n=this._getOrReturnCtx(t);return Ee(n,{code:me.invalid_type,expected:Ce.undefined,received:n.parsedType}),ft}return bs(t.data)}};A2.create=e=>new A2({typeName:_t.ZodUndefined,...Ot(e)});var S2=class extends Bt{_parse(t){if(this._getType(t)!==Ce.null){let n=this._getOrReturnCtx(t);return Ee(n,{code:me.invalid_type,expected:Ce.null,received:n.parsedType}),ft}return bs(t.data)}};S2.create=e=>new S2({typeName:_t.ZodNull,...Ot(e)});var uh=class extends Bt{constructor(){super(...arguments),this._any=!0}_parse(t){return bs(t.data)}};uh.create=e=>new uh({typeName:_t.ZodAny,...Ot(e)});var Nm=class extends Bt{constructor(){super(...arguments),this._unknown=!0}_parse(t){return bs(t.data)}};Nm.create=e=>new Nm({typeName:_t.ZodUnknown,...Ot(e)});var Xd=class extends Bt{_parse(t){let r=this._getOrReturnCtx(t);return Ee(r,{code:me.invalid_type,expected:Ce.never,received:r.parsedType}),ft}};Xd.create=e=>new Xd({typeName:_t.ZodNever,...Ot(e)});var Aw=class extends Bt{_parse(t){if(this._getType(t)!==Ce.undefined){let n=this._getOrReturnCtx(t);return Ee(n,{code:me.invalid_type,expected:Ce.void,received:n.parsedType}),ft}return bs(t.data)}};Aw.create=e=>new Aw({typeName:_t.ZodVoid,...Ot(e)});var jm=class e extends Bt{_parse(t){let{ctx:r,status:n}=this._processInputParams(t),i=this._def;if(r.parsedType!==Ce.array)return Ee(r,{code:me.invalid_type,expected:Ce.array,received:r.parsedType}),ft;if(i.exactLength!==null){let s=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(s||a)&&(Ee(r,{code:s?me.too_big:me.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&&(Ee(r,{code:me.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&&(Ee(r,{code:me.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 Nu(r,s,r.path,a)))).then(s=>Mo.mergeArray(n,s));let o=[...r.data].map((s,a)=>i.type._parseSync(new Nu(r,s,r.path,a)));return Mo.mergeArray(n,o)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:Ye.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:Ye.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:Ye.toString(r)}})}nonempty(t){return this.min(1,t)}};jm.create=(e,t)=>new jm({type:e,minLength:null,maxLength:null,exactLength:null,typeName:_t.ZodArray,...Ot(t)});function xw(e){if(e instanceof Ma){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=Bu.create(xw(n))}return new Ma({...e._def,shape:()=>t})}else return e instanceof jm?new jm({...e._def,type:xw(e.element)}):e instanceof Bu?Bu.create(xw(e.unwrap())):e instanceof xp?xp.create(xw(e.unwrap())):e instanceof wp?wp.create(e.items.map(t=>xw(t))):e}var Ma=class e extends Bt{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=Ft.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 Ee(u,{code:me.invalid_type,expected:Ce.object,received:u.parsedType}),ft}let{status:n,ctx:i}=this._processInputParams(t),{shape:o,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof Xd&&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 Nu(i,l,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof Xd){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&&(Ee(i,{code:me.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 Nu(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=>Mo.mergeObjectSync(n,u)):Mo.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(t){return Ye.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:Ye.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:_t.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 Ft.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 Ft.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}deepPartial(){return xw(this)}partial(t){let r={};for(let n of Ft.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 Ft.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof Bu;)o=o._def.innerType;r[n]=o}return new e({...this._def,shape:()=>r})}keyof(){return a3e(Ft.objectKeys(this.shape))}};Ma.create=(e,t)=>new Ma({shape:()=>e,unknownKeys:"strip",catchall:Xd.create(),typeName:_t.ZodObject,...Ot(t)});Ma.strictCreate=(e,t)=>new Ma({shape:()=>e,unknownKeys:"strict",catchall:Xd.create(),typeName:_t.ZodObject,...Ot(t)});Ma.lazycreate=(e,t)=>new Ma({shape:e,unknownKeys:"strip",catchall:Xd.create(),typeName:_t.ZodObject,...Ot(t)});var T2=class extends Bt{_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 Ua(a.ctx.common.issues));return Ee(r,{code:me.invalid_union,unionErrors:s}),ft}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 Ua(c));return Ee(r,{code:me.invalid_union,unionErrors:a}),ft}}get options(){return this._def.options}};T2.create=(e,t)=>new T2({options:e,typeName:_t.ZodUnion,...Ot(t)});var Bm=e=>e instanceof I2?Bm(e.schema):e instanceof ju?Bm(e.innerType()):e instanceof C2?[e.value]:e instanceof O2?e.options:e instanceof R2?Ft.objectValues(e.enum):e instanceof k2?Bm(e._def.innerType):e instanceof A2?[void 0]:e instanceof S2?[null]:e instanceof Bu?[void 0,...Bm(e.unwrap())]:e instanceof xp?[null,...Bm(e.unwrap())]:e instanceof UA||e instanceof N2?Bm(e.unwrap()):e instanceof B2?Bm(e._def.innerType):[],Jk=class e extends Bt{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Ce.object)return Ee(r,{code:me.invalid_type,expected:Ce.object,received:r.parsedType}),ft;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}):(Ee(r,{code:me.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),ft)}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=Bm(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:_t.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:i,...Ot(n)})}};function jY(e,t){let r=vp(e),n=vp(t);if(e===t)return{valid:!0,data:e};if(r===Ce.object&&n===Ce.object){let i=Ft.objectKeys(t),o=Ft.objectKeys(e).filter(a=>i.indexOf(a)!==-1),s={...e,...t};for(let a of o){let c=jY(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=jY(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 P2=class extends Bt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=(o,s)=>{if(Wk(o)||Wk(s))return ft;let a=jY(o.value,s.value);return a.valid?((Gk(o)||Gk(s))&&r.dirty(),{status:r.value,value:a.data}):(Ee(n,{code:me.invalid_intersection_types}),ft)};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}))}};P2.create=(e,t,r)=>new P2({left:e,right:t,typeName:_t.ZodIntersection,...Ot(r)});var wp=class e extends Bt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Ce.array)return Ee(n,{code:me.invalid_type,expected:Ce.array,received:n.parsedType}),ft;if(n.data.length<this._def.items.length)return Ee(n,{code:me.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ft;!this._def.rest&&n.data.length>this._def.items.length&&(Ee(n,{code:me.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 Nu(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>Mo.mergeArray(r,s)):Mo.mergeArray(r,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};wp.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new wp({items:e,typeName:_t.ZodTuple,rest:null,...Ot(t)})};var Yk=class e extends Bt{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 Ee(n,{code:me.invalid_type,expected:Ce.object,received:n.parsedType}),ft;let i=[],o=this._def.keyType,s=this._def.valueType;for(let a in n.data)i.push({key:o._parse(new Nu(n,a,n.path,a)),value:s._parse(new Nu(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Mo.mergeObjectAsync(r,i):Mo.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof Bt?new e({keyType:t,valueType:r,typeName:_t.ZodRecord,...Ot(n)}):new e({keyType:ch.create(),valueType:t,typeName:_t.ZodRecord,...Ot(r)})}},Sw=class extends Bt{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 Ee(n,{code:me.invalid_type,expected:Ce.map,received:n.parsedType}),ft;let i=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([a,c],u)=>({key:i._parse(new Nu(n,a,n.path,[u,"key"])),value:o._parse(new Nu(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 ft;(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 ft;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}}}};Sw.create=(e,t,r)=>new Sw({valueType:t,keyType:e,typeName:_t.ZodMap,...Ot(r)});var Tw=class e extends Bt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Ce.set)return Ee(n,{code:me.invalid_type,expected:Ce.set,received:n.parsedType}),ft;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(Ee(n,{code:me.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&&(Ee(n,{code:me.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 ft;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 Nu(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:Ye.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:Ye.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};Tw.create=(e,t)=>new Tw({valueType:e,minSize:null,maxSize:null,typeName:_t.ZodSet,...Ot(t)});var Zk=class e extends Bt{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Ce.function)return Ee(r,{code:me.invalid_type,expected:Ce.function,received:r.parsedType}),ft;function n(a,c){return qA({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,vw(),km].filter(u=>!!u),issueData:{code:me.invalid_arguments,argumentsError:c}})}function i(a,c){return qA({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,vw(),km].filter(u=>!!u),issueData:{code:me.invalid_return_type,returnTypeError:c}})}let o={errorMap:r.common.contextualErrorMap},s=r.data;if(this._def.returns instanceof dh){let a=this;return bs(async function(...c){let u=new Ua([]),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 bs(function(...c){let u=a._def.args.safeParse(c,o);if(!u.success)throw new Ua([n(c,u.error)]);let d=Reflect.apply(s,this,u.data),l=a._def.returns.safeParse(d,o);if(!l.success)throw new Ua([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:wp.create(t).rest(Nm.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||wp.create([]).rest(Nm.create()),returns:r||Nm.create(),typeName:_t.ZodFunction,...Ot(n)})}},I2=class extends Bt{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})}};I2.create=(e,t)=>new I2({getter:e,typeName:_t.ZodLazy,...Ot(t)});var C2=class extends Bt{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return Ee(r,{received:r.data,code:me.invalid_literal,expected:this._def.value}),ft}return{status:"valid",value:t.data}}get value(){return this._def.value}};C2.create=(e,t)=>new C2({value:e,typeName:_t.ZodLiteral,...Ot(t)});function a3e(e,t){return new O2({values:e,typeName:_t.ZodEnum,...Ot(t)})}var O2=class e extends Bt{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return Ee(r,{expected:Ft.joinValues(n),received:r.parsedType,code:me.invalid_type}),ft}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 Ee(r,{received:r.data,code:me.invalid_enum_value,options:n}),ft}return bs(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})}};O2.create=a3e;var R2=class extends Bt{_parse(t){let r=Ft.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==Ce.string&&n.parsedType!==Ce.number){let i=Ft.objectValues(r);return Ee(n,{expected:Ft.joinValues(i),received:n.parsedType,code:me.invalid_type}),ft}if(this._cache||(this._cache=new Set(Ft.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=Ft.objectValues(r);return Ee(n,{received:n.data,code:me.invalid_enum_value,options:i}),ft}return bs(t.data)}get enum(){return this._def.values}};R2.create=(e,t)=>new R2({values:e,typeName:_t.ZodNativeEnum,...Ot(t)});var dh=class extends Bt{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Ce.promise&&r.common.async===!1)return Ee(r,{code:me.invalid_type,expected:Ce.promise,received:r.parsedType}),ft;let n=r.parsedType===Ce.promise?r.data:Promise.resolve(r.data);return bs(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};dh.create=(e,t)=>new dh({type:e,typeName:_t.ZodPromise,...Ot(t)});var ju=class extends Bt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===_t.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=>{Ee(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 ft;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?ft:c.status==="dirty"?_2(c.value):r.value==="dirty"?_2(c.value):c});{if(r.value==="aborted")return ft;let a=this._def.schema._parseSync({data:s,path:n.path,parent:n});return a.status==="aborted"?ft:a.status==="dirty"?_2(a.value):r.value==="dirty"?_2(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"?ft:(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"?ft:(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(!ah(s))return ft;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=>ah(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:r.value,value:a})):ft);Ft.assertNever(i)}};ju.create=(e,t,r)=>new ju({schema:e,typeName:_t.ZodEffects,effect:t,...Ot(r)});ju.createWithPreprocess=(e,t,r)=>new ju({schema:t,effect:{type:"preprocess",transform:e},typeName:_t.ZodEffects,...Ot(r)});var Bu=class extends Bt{_parse(t){return this._getType(t)===Ce.undefined?bs(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Bu.create=(e,t)=>new Bu({innerType:e,typeName:_t.ZodOptional,...Ot(t)});var xp=class extends Bt{_parse(t){return this._getType(t)===Ce.null?bs(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};xp.create=(e,t)=>new xp({innerType:e,typeName:_t.ZodNullable,...Ot(t)});var k2=class extends Bt{_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}};k2.create=(e,t)=>new k2({innerType:e,typeName:_t.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Ot(t)});var B2=class extends Bt{_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 ww(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ua(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Ua(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};B2.create=(e,t)=>new B2({innerType:e,typeName:_t.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Ot(t)});var Pw=class extends Bt{_parse(t){if(this._getType(t)!==Ce.nan){let n=this._getOrReturnCtx(t);return Ee(n,{code:me.invalid_type,expected:Ce.nan,received:n.parsedType}),ft}return{status:"valid",value:t.data}}};Pw.create=e=>new Pw({typeName:_t.ZodNaN,...Ot(e)});var O0t=Symbol("zod_brand"),UA=class extends Bt{_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}},MA=class e extends Bt{_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"?ft:o.status==="dirty"?(r.dirty(),_2(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"?ft: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:_t.ZodPipeline})}},N2=class extends Bt{_parse(t){let r=this._def.innerType._parse(t),n=i=>(ah(i)&&(i.value=Object.freeze(i.value)),i);return ww(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};N2.create=(e,t)=>new N2({innerType:e,typeName:_t.ZodReadonly,...Ot(t)});function n3e(e,t){let r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function c3e(e,t={},r){return e?uh.create().superRefine((n,i)=>{let o=e(n);if(o instanceof Promise)return o.then(s=>{if(!s){let a=n3e(t,n),c=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:c})}});if(!o){let s=n3e(t,n),a=s.fatal??r??!0;i.addIssue({code:"custom",...s,fatal:a})}}):uh.create()}var R0t={object:Ma.lazycreate},_t;(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"})(_t||(_t={}));var k0t=(e,t={message:`Input not instance of ${e.name}`})=>c3e(r=>r instanceof e,t),u3e=ch.create,d3e=v2.create,B0t=Pw.create,N0t=w2.create,l3e=x2.create,j0t=E2.create,q0t=Ew.create,U0t=A2.create,M0t=S2.create,D0t=uh.create,L0t=Nm.create,H0t=Xd.create,z0t=Aw.create,F0t=jm.create,$0t=Ma.create,V0t=Ma.strictCreate,K0t=T2.create,W0t=Jk.create,G0t=P2.create,J0t=wp.create,Y0t=Yk.create,Z0t=Sw.create,X0t=Tw.create,Q0t=Zk.create,e1t=I2.create,t1t=C2.create,r1t=O2.create,n1t=R2.create,i1t=dh.create,o1t=ju.create,s1t=Bu.create,a1t=xp.create,c1t=ju.createWithPreprocess,u1t=MA.create,d1t=()=>u3e().optional(),l1t=()=>d3e().optional(),p1t=()=>l3e().optional(),f1t={string:(e=>ch.create({...e,coerce:!0})),number:(e=>v2.create({...e,coerce:!0})),boolean:(e=>x2.create({...e,coerce:!0})),bigint:(e=>w2.create({...e,coerce:!0})),date:(e=>E2.create({...e,coerce:!0}))};var m1t=ft;var h1t=/^[A-Za-z0-9._-]+$/,y1t=/^[A-Za-z0-9._-]+(\|[A-Za-z0-9._-]+)*$/,p3e=new Set([".",".."]),Qs=class extends Error{pattern;constructor(t,r){super(`Invalid freeReadPathPattern ${JSON.stringify(r)}: ${t}`),this.pattern=r,this.name="FreePathPatternError"}};function g1t(e,t){if(e==="*")return{raw:e,kind:"single"};if(e==="**")return{raw:e,kind:"multi"};if(e.startsWith("(")){let r=e.endsWith(")?"),n=e.endsWith(")");if(!r&&!n)throw new Qs(`malformed alternation segment ${JSON.stringify(e)}`,t);let i=r?e.slice(1,-2):e.slice(1,-1);if(!y1t.test(i))throw new Qs(`malformed alternation segment ${JSON.stringify(e)}`,t);let o=i.split("|");if(o.some(s=>p3e.has(s)))throw new Qs(`alternation segment ${JSON.stringify(e)} may not contain '.' or '..'`,t);return{raw:e,kind:r?"alt-optional":"alt",alternatives:o}}if(h1t.test(e)){if(p3e.has(e))throw new Qs(`literal segment ${JSON.stringify(e)} is not permitted`,t);return{raw:e,kind:"literal"}}throw new Qs(`segment ${JSON.stringify(e)} must be '*', '**', a [A-Za-z0-9._-]+ literal, or (a|b) alternation`,t)}function b1t(e){if(typeof e!="string"||e.length===0)throw new Qs("must be a non-empty string",String(e));if(!e.startsWith("/"))throw new Qs("must start with '/'",e);if(e.slice(1).includes("//"))throw new Qs("empty segments ('//') are not permitted",e);if(e.length>1&&e.endsWith("/"))throw new Qs("must not end with '/'",e);let r=e.slice(1).split("/").map(o=>g1t(o,e));if(r.filter(o=>o.kind==="multi").length>1)throw new Qs("at most one '**' is permitted per pattern",e);if(r[0]?.kind==="multi")throw new Qs("'**' may not be the first segment (a literal prefix anchor is required)",e);let i=r.findIndex(o=>o.kind==="alt-optional");if(i!==-1&&i!==r.length-1)throw new Qs("optional alternation '(...)?' is only allowed as the final segment",e);return r}function qY(e){b1t(e)}var f3e=["tempo","mpp_self","merchant_self"],m3e=["catalog_static","fal_direct","fal_queue","openrouter_chat","openrouter_image","platform_proxy","tempo_gateway","x402_gateway"],h3e=["image","audio","queued_audio","video","queued_video","model_3d","llm","transcription","utility"],y3e=["images[0].url","image.url","audio.url","audio_file.url","audio_url","video.url","model_mesh.url","text","choices[0].message.content","choices[0].message.images[0].image_url.url","request_id"];var MY=ye.object({inputPerMillion:ye.number().positive(),outputPerMillion:ye.number().positive(),contextWindow:ye.number().int().positive().optional(),maxOutput:ye.number().int().positive().optional(),perRequestFeeCents:ye.number().nonnegative().optional()}),_1t=ye.object({strategy:ye.enum(["flat","token","band"]).optional(),pricingModel:ye.enum(["per-call","per-token","band"]).optional(),priceCents:ye.number().nonnegative().optional(),currency:ye.string().optional(),display:ye.string().optional(),estimate:ye.boolean().optional(),source:ye.string().optional(),priceBand:ye.record(ye.unknown()).optional(),tokenPricing:MY.optional()}).passthrough(),DY=ye.discriminatedUnion("type",[ye.object({type:ye.literal("shortcut"),routedPath:ye.string().min(1).startsWith("/")}),ye.object({type:ye.literal("custom"),merchantSlug:ye.string().min(1),subPath:ye.string().optional()}),ye.object({type:ye.literal("local"),fn:ye.string().min(1)}),ye.object({type:ye.literal("read")})]),LY=ye.object({amount:ye.number().nonnegative(),currency:ye.string().length(3).optional(),display:ye.string().optional(),free:ye.boolean().optional(),batchDiscount:ye.number().min(0).max(100).optional()}),g3e=ye.object({attestation:ye.boolean().optional(),rateLimitMs:ye.number().positive().optional()}),b3e=ye.object({displayName:ye.string().optional(),feedbackEligible:ye.boolean().optional(),suggestionEligible:ye.boolean().optional(),batchable:ye.boolean().optional()}),_3e=ye.object({enabled:ye.boolean().optional(),gatewayPath:ye.string().min(1).startsWith("/").optional(),method:ye.enum(["GET","POST","PUT","PATCH","DELETE"]).optional(),timeoutMs:ye.number().int().positive().max(12e4).optional()}).strict(),v3e=ye.enum(["image","video","audio","3d","llm","upscale","tts","transcription","utility","onchain"]),HY=v3e.options,v1t=120,w1t=120,x1t=1200,E1t=/^[^\u0000-\u001F\u007F]+$/;function UY(e,t){return ye.string().min(1).max(e).regex(E1t,`${t} must not contain control characters`)}var zY={id:ye.string().min(1),name:UY(v1t,"name"),description:UY(x1t,"description"),provider:ye.string().min(1),model:ye.string().min(1),category:v3e,priceCents:ye.number().nonnegative(),inputSchema:ye.record(ye.unknown()),gatewayUrl:ye.string().min(1),merchantName:UY(w1t,"merchantName"),isAsync:ye.boolean().optional(),pollUrl:ye.string().optional(),pollInterval:ye.number().positive().optional(),pollTimeout:ye.number().positive().optional(),tags:ye.array(ye.string()).optional(),tokenPricing:MY.optional(),priceDisplay:ye.string().optional(),pricingModel:ye.enum(["per-call","per-token","band"]).optional(),pricingInfo:_1t.optional(),status:ye.enum(["available","unavailable"]).optional(),handler:DY.optional(),pricing:LY.optional(),security:g3e.optional(),engagement:b3e.optional(),gatewayConfig:_3e.optional(),freeReadPathPattern:ye.string().optional().superRefine((e,t)=>{if(e!==void 0)try{qY(e)}catch(r){t.addIssue({code:ye.ZodIssueCode.custom,message:r instanceof Error?r.message:String(r)})}}),enabled:ye.boolean().optional(),beta:ye.boolean().optional(),deprecated:ye.boolean().optional(),internal:ye.boolean().optional(),employeeOnly:ye.boolean().optional(),employeeOnlyRolloutFlag:ye.string().min(1).max(100).optional(),replacementTool:ye.string().optional(),minCliVersion:ye.string().optional(),sunsetAt:ye.string().optional(),rail:ye.enum(f3e).optional(),executionKind:ye.enum(m3e).optional(),resultKind:ye.enum(h3e).optional(),extractionMode:ye.enum(y3e).optional(),pricingStrategy:ye.enum(["flat","token","band"]).optional()},w3e=ye.object({...zY,dispatch:ye.literal("routed"),routedPath:ye.string().min(1).startsWith("/")}).strict(),x3e=ye.object({...zY,dispatch:ye.literal("enveloped")}).strict(),E3e=ye.object({...zY,handler:DY,pricing:LY}).strict(),A3e=ye.union([ye.discriminatedUnion("dispatch",[w3e,x3e]),E3e]);var T1t="https://fal.run",I3e="https://openrouter.mpp.tempo.xyz",$Y=1024,Qk=8192,P1t=4096,I1t=10;function C1t(e){return e>=I1t?P1t:Qk}function C3e(e,t){let r=typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):$Y;return Math.min(r,t)}var O1t=["num_images","num_outputs","num_samples","num_videos","batch_size","n"];function O3e(e){for(let t of O1t)delete e[t];return e}function R1t(e){let{attestation:t,tool_id:r,...n}=e;return O3e(n)}var S3e={"1:1":"square_hd","16:9":"landscape_16_9","9:16":"portrait_16_9","4:3":"landscape_4_3","3:4":"portrait_4_3"};function Xk(e){let{attestation:t,tool_id:r,aspect_ratio:n,image_size:i,...o}=e,s=O3e({...o});return typeof i=="string"&&i.length>0?(s.image_size=i,s):(typeof n=="string"&&S3e[n]&&(s.image_size=S3e[n]),s)}function k1t(e){let{attestation:t,tool_id:r,...n}=e;return n}function T3e(e){let t={chain:e.chain,token_address:e.token_address};if(e.start_timestamp){let r=e.end_timestamp||new Date().toISOString(),n=e.time_granularity;if(!n){let i=new Date(e.start_timestamp).getTime();(new Date(r).getTime()-i)/(1e3*60*60*24)<=2?n="1h":n="1d"}return{addresses:[t],start_timestamp:e.start_timestamp,end_timestamp:r,time_granularity:n}}return[t]}function B1t(e,t,r,n,i,o,s,a,c){return{id:e,name:t,description:r,provider:n,model:i.replace(/^\//,""),category:o,gatewayUrl:`https://${n}${i}`,merchantName:t,inputSchema:a,handler:{type:"custom",merchantSlug:n,subPath:i},pricing:{amount:s,currency:"USD",display:`$${(s/100).toFixed(2)}`},priceCents:s,tags:[],...c}}function N1t(e,t,r,n,i,o,s,a){return B1t(e,t,r,"suno-ai",n,i,o,s,{merchantName:"Suno AI",...a})}function Ci(e,t,r,n,i,o,s,a){return{dispatch:"routed",id:e,name:t,description:r,provider:"fal",model:n,category:i,priceCents:o,inputSchema:s,routedPath:`/api/v1/fal/${n}`,gatewayUrl:`${T1t}/${n}`,merchantName:"fal.ai",buildBody:R1t,tags:[],...a}}function R3e(e,t=Qk){return r=>{let{attestation:n,tool_id:i,model:o,prompt:s,system_prompt:a,max_tokens:c,max_completion_tokens:u,n:d,messages:l,temperature:p,...f}=r;return typeof o=="string"&&o.length>0&&o!==e&&console.warn("[catalog] openrouterBuildBody: caller model override ignored",{catalogModel:e,callerModel:o}),{messages:Array.isArray(l)?l:[...a?[{role:"system",content:a}]:[],{role:"user",content:s}],temperature:p??.7,...f,model:e,max_tokens:C3e(c??u,t),usage:{include:!0}}}}function k3e(e,t=Qk){return r=>{let{attestation:n,tool_id:i,prompt:o,image_url:s,aspect_ratio:a,max_tokens:c,max_completion_tokens:u,n:d,model:l,messages:p,image_config:f,temperature:m,...h}=r,y=[{type:"text",text:o}];return typeof s=="string"&&s.length>0&&y.push({type:"image_url",image_url:{url:s}}),{messages:Array.isArray(p)?p:[{role:"user",content:y}],temperature:m??.7,...h,model:e,...typeof a=="string"&&a.length>0?{image_config:{aspect_ratio:a}}:{},max_tokens:C3e(c??u,t),usage:{include:!0}}}}function Hn(e,t,r,n,i,o,s){let a=s?.maxOutputTokens??C1t(o),c=s?.perRequestFeeCents??0,u=500/1e6*i*100,d=500/1e6*o*100,l=Math.max(1,Math.ceil(u+d+c)),{perRequestFeeCents:p,maxOutputTokens:f,...m}=s??{};return{dispatch:"routed",id:e,name:t,description:r,provider:"openrouter",model:n,category:"llm",priceCents:l,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"The prompt or question to send to the model"},system_prompt:{type:"string",description:"Optional system prompt to set model behavior"},max_tokens:{type:"integer",description:`Maximum tokens in response (default: ${$Y}); values above ${a} are clamped to ${a}`,minimum:1,maximum:a},temperature:{type:"number",description:"Sampling temperature 0-2 (default: 0.7)",minimum:0,maximum:2}},required:["prompt"]},routedPath:"/api/v1/chat/completions",gatewayUrl:`${I3e}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:R3e(n,a),tags:["llm","chat","text"],tokenPricing:{inputPerMillion:i,outputPerMillion:o,...c>0?{perRequestFeeCents:c}:{}},...m}}function FY(e,t,r,n,i,o){let s=o?.maxOutputTokens??Qk,{maxOutputTokens:a,...c}=o??{};return{dispatch:"routed",id:e,name:t,description:r,provider:"openrouter",model:n,category:"image",pricingStrategy:"band",priceCents:i,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate or edit"},image_url:{type:"string",description:"Optional source image URL for edits"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"1:1"},max_tokens:{type:"integer",description:`Maximum text tokens in response metadata (default: ${$Y}); values above ${s} are clamped to ${s}`,minimum:1,maximum:s},temperature:{type:"number",description:"Sampling temperature 0-2 (default: 0.7)",minimum:0,maximum:2}},required:["prompt"]},routedPath:"/api/v1/chat/completions",gatewayUrl:`${I3e}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:k3e(n,s),tags:["image","gemini","google","nano-banana","edit"],tokenPricing:{inputPerMillion:.3,outputPerMillion:2.5},...c}}var VY=[Ci("fal-flux-pro-ultra","FLUX Pro Ultra","Highest quality image generation. Best for detailed, photorealistic images.","fal-ai/flux-pro/v1.1-ultra","image",6,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"16:9"}},required:["prompt"]},{tags:["image","flux","photorealistic","high-quality"]}),Ci("fal-flux-pro","FLUX Pro","Fast, high-quality image generation. Good balance of speed and quality.","fal-ai/flux-pro/v1.1","image",4,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"16:9"}},required:["prompt"]},{tags:["image","flux","fast"],buildBody:Xk}),Ci("fal-flux-dev","FLUX Dev","Open-source image generation. Cheaper, good for experimentation.","fal-ai/flux/dev","image",3,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},{tags:["image","flux","open-source","cheap"],buildBody:Xk}),Ci("fal-flux-schnell","FLUX Schnell","Fastest image generation. Ultra-cheap, great for drafts and iteration.","fal-ai/flux/schnell","image",1,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},{tags:["image","flux","fast","cheap","draft"],buildBody:Xk}),Ci("fal-recraft-v3","Recraft V3","Design-focused image generation. Great for illustrations, icons, and graphic design.","fal-ai/recraft/v3/text-to-image","image",5,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},style:{type:"string",description:"Style preset: realistic_image, digital_illustration, vector_illustration, icon"}},required:["prompt"]},{tags:["image","design","illustration","icon","vector"]}),FY("or-gemini-nano-banana","Nano Banana","Google Gemini 2.5 Flash Image via OpenRouter for image generation and edits.","google/gemini-2.5-flash-image",4),FY("or-gemini-nano-banana-2","Nano Banana 2","Google Gemini 3.1 Flash Image Preview via OpenRouter for fast image generation and edits.","google/gemini-3.1-flash-image-preview",5,{tags:["image","gemini","google","nano-banana","edit","fast"],tokenPricing:{inputPerMillion:.5,outputPerMillion:3}}),FY("or-gemini-nano-banana-pro","Nano Banana Pro","Google Gemini 3 Pro Image Preview via OpenRouter for professional image generation, edits, and text rendering.","google/gemini-3-pro-image-preview",8,{tags:["image","gemini","google","nano-banana","pro","text-rendering"],tokenPricing:{inputPerMillion:2,outputPerMillion:12}}),Ci("fal-ideogram-v2","Ideogram V2","Excellent text rendering in images. Best for logos, posters, and text-heavy visuals.","fal-ai/ideogram/v2","image",8,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"1:1"}},required:["prompt"]},{tags:["image","text-rendering","logo","poster","typography"]}),Ci("fal-ideogram-v2-turbo","Ideogram V2 Turbo","Fast text rendering in images. Good balance of speed and text accuracy.","fal-ai/ideogram/v2/turbo","image",5,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"1:1"}},required:["prompt"]},{tags:["image","text-rendering","fast"]}),Ci("fal-fast-sdxl","Fast SDXL","Ultra-fast Stable Diffusion. 4-step inference, cheapest option.","fal-ai/fast-sdxl","image",1,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"}},required:["prompt"]},{tags:["image","stable-diffusion","fast","cheap"]}),Ci("fal-wan-video","Wan Video","Text-to-video generation. Create short video clips from text descriptions.","fal-ai/wan/v2.1/1.3b/text-to-video","video",10,{type:"object",properties:{prompt:{type:"string",description:"Text description of the video to generate"},num_frames:{type:"number",description:"Number of frames (default: 81)"}},required:["prompt"]},{tags:["video","text-to-video","wan"]}),Ci("fal-minimax-video","MiniMax Video","High-quality video generation with excellent motion and coherence.","fal-ai/minimax-video/video-01-live","video",15,{type:"object",properties:{prompt:{type:"string",description:"Text description of the video to generate"}},required:["prompt"]},{tags:["video","text-to-video","high-quality"]}),Ci("fal-kling-video","Kling Video","Professional video generation with cinematic quality.","fal-ai/kling-video/v2/master/text-to-video","video",20,{type:"object",properties:{prompt:{type:"string",description:"Text description of the video to generate"},duration:{type:"string",description:"Duration: 5 or 10 seconds",default:"5"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},{tags:["video","text-to-video","cinematic","professional"]}),Ci("fal-kling-i2v","Kling Image-to-Video","Animate a still image into a 5\u201310s video clip. Cinematic motion quality.","fal-ai/kling-video/v1.6/standard/image-to-video","video",35,{type:"object",properties:{image_url:{type:"string",description:"URL of the source image (jpg, png, webp, gif, avif)"},prompt:{type:"string",description:"Text description of the motion to animate"},duration:{type:"string",description:"Duration: 5 or 10 seconds",default:"5"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 9:16, 1:1)",default:"16:9"},negative_prompt:{type:"string",description:"Elements to avoid in the generated motion"},cfg_scale:{type:"number",description:"Classifier-free guidance (default 0.5)",default:.5}},required:["image_url","prompt"]},{tags:["video","image-to-video","kling","cinematic"]}),Ci("fal-stable-audio","Stable Audio","Generate sound effects and ambient audio from text descriptions.","fal-ai/stable-audio","audio",4,{type:"object",properties:{prompt:{type:"string",description:"Description of the audio to generate"},seconds_total:{type:"number",description:"Duration in seconds (max 47)",default:30}},required:["prompt"]},{tags:["audio","sound-effects","ambient"]}),Ci("fal-ace-step-music","ACE-Step Music","Generate full music tracks from a prompt, with optional vocals or instrumentals.","fal-ai/ace-step/prompt-to-audio","audio",2,{type:"object",properties:{prompt:{type:"string",description:"Description of the song, genre, mood, instruments, and lyrics direction"},instrumental:{type:"boolean",description:"Generate instrumental music without vocals",default:!1},duration:{type:"number",description:"Duration in seconds",default:60}},required:["prompt"]},{tags:["music","song","vocals","instrumental","ace-step"]}),N1t("suno-music","Suno Music","AI music generation. Create full songs with vocals or instrumentals.","/suno/generate-music","audio",10,{type:"object",properties:{prompt:{type:"string",description:"Description of the song (genre, mood, instruments)"},instrumental:{type:"boolean",description:"Instrumental only, no vocals",default:!1}},required:["prompt"]},{isAsync:!0,pollUrl:"https://api.sunoapi.org/suno/get-music-status",deprecated:!0,tags:["music","song","vocals","instrumental"],buildBody:e=>{let{attestation:t,tool_id:r,prompt:n,instrumental:i,...o}=e;return{prompt:n,customMode:!1,instrumental:typeof i=="boolean"?i:!1,model:"V4",...o}}}),Ci("fal-trellis-3d","Trellis 3D","Generate 3D models from images. Upload a photo, get a 3D asset.","fal-ai/trellis","3d",8,{type:"object",properties:{image_url:{type:"string",description:"URL of the image to convert to 3D"}},required:["image_url"]},{tags:["3d","model","image-to-3d"]}),Ci("fal-aura-sr","Aura SR","Upscale images to higher resolution. 4x upscaling with detail enhancement.","fal-ai/aura-sr","upscale",3,{type:"object",properties:{image_url:{type:"string",description:"URL of the image to upscale"}},required:["image_url"]},{tags:["upscale","super-resolution","enhance"]}),Ci("fal-metavoice","MetaVoice Voice Cloning","Voice cloning TTS \u2014 clone any voice from an audio sample. Provide text and a voice sample URL.","fal-ai/metavoice-v1","tts",3,{type:"object",properties:{text:{type:"string",description:"Text to convert to speech"},audio_url:{type:"string",description:"URL of the voice sample to clone"}},required:["text","audio_url"]},{tags:["tts","voice","voice-cloning","speech"]}),Ci("fal-whisper","Whisper Transcription","Transcribe audio to text. Supports multiple languages.","fal-ai/whisper","transcription",2,{type:"object",properties:{audio_url:{type:"string",description:"URL of the audio to transcribe"},language:{type:"string",description:"Language code (e.g. en, es, fr)"}},required:["audio_url"]},{tags:["transcription","speech-to-text","whisper"]}),Hn("or-gpt-4o","GPT-4o","OpenAI's flagship multimodal model. Best for complex reasoning and analysis.","openai/gpt-4o",2.5,10,{tags:["llm","gpt","openai","multimodal","reasoning"]}),Hn("or-gpt-55","GPT-5.5","OpenAI frontier model for complex professional reasoning, coding, and long-context analysis.","openai/gpt-5.5",5,30,{tags:["llm","gpt","openai","frontier","reasoning","coding","long-context"]}),Hn("or-gpt-55-pro","GPT-5.5 Pro","OpenAI high-capability frontier model optimized for deep reasoning and high-stakes workloads.","openai/gpt-5.5-pro",30,180,{tags:["llm","gpt","openai","frontier","pro","deep-reasoning","coding","long-context"]}),Hn("or-gpt-4o-mini","GPT-4o Mini","Fast, affordable GPT-4o. Great for everyday tasks, chat, and simple analysis.","openai/gpt-4o-mini",.15,.6,{tags:["llm","gpt","openai","fast","cheap"]}),Hn("or-claude-opus-4-8","Claude Opus 4.8","Anthropic's newest flagship. 1M context, strongest reasoning + coding.","anthropic/claude-opus-4.8",15,75,{tags:["llm","claude","anthropic","reasoning","coding","newest"]}),Hn("or-claude-opus","Claude Opus 4.7","Anthropic's most capable model. 1M context, reasoning, best for complex tasks.","anthropic/claude-opus-4.7",15,75,{tags:["llm","claude","anthropic","reasoning","coding"]}),Hn("or-claude-sonnet","Claude Sonnet 4.6","Anthropic's best balance of intelligence and speed. Excellent for coding and analysis.","anthropic/claude-sonnet-4.6",3,15,{tags:["llm","claude","anthropic","coding","analysis"]}),Hn("or-claude-opus-fast","Claude Opus 4.8 Fast","Fast Opus variant with lower latency.","anthropic/claude-opus-4.8-fast",10,50,{tags:["llm","claude","anthropic","fast"]}),Hn("or-claude-haiku","Claude Haiku 4.5","Anthropic's fastest model. Great for quick tasks, chat, and simple reasoning.","anthropic/claude-haiku-4.5",1,5,{tags:["llm","claude","anthropic","fast"]}),Hn("or-gemini-pro","Gemini 2.5 Flash","Google's fast multimodal model. Good for general tasks with long context.","google/gemini-2.5-flash",.3,2.5,{tags:["llm","gemini","google","multimodal","fast","cheap"]}),Hn("or-gemini-3-flash","Gemini 3 Flash","Google's high-speed thinking model for agentic workflows, coding, and multimodal tasks.","google/gemini-3-flash-preview",.5,3,{tags:["llm","gemini","google","agentic","coding","fast"]}),Hn("or-gemini-3-pro","Gemini 3.1 Pro","Google's flagship frontier model for deep reasoning, multimodal analysis, and agentic coding.","google/gemini-3.1-pro-preview",2,12,{tags:["llm","gemini","google","reasoning","coding","multimodal"]}),Hn("or-gemini-35-flash","Gemini 3.5 Flash","Google frontier Flash model for multimodal reasoning, coding, and parallel agentic workflows.","google/gemini-3.5-flash",1.5,9,{tags:["llm","gemini","google","frontier","multimodal","reasoning","coding","fast"]}),Hn("or-gemini-3-lite","Gemini 3.1 Flash Lite","Google's efficient multimodal model optimized for low-latency, high-volume agent workloads.","google/gemini-3.1-flash-lite",.25,1.5,{tags:["llm","gemini","google","fast","cheap","multimodal"]}),Hn("or-llama-70b","Llama 3.3 70B","Meta's best open model. Strong reasoning, fully open-source.","meta-llama/llama-3.3-70b-instruct",.3,.4,{tags:["llm","llama","meta","open-source","reasoning"]}),Hn("or-llama-8b","Llama 3.1 8B","Fast, lightweight open model. Great for simple tasks at minimal cost.","meta-llama/llama-3.1-8b-instruct",.05,.08,{tags:["llm","llama","meta","open-source","fast","cheap"]}),Hn("or-mistral-large","Mistral Large","Mistral's flagship model. Strong at multilingual and European languages.","mistralai/mistral-large-2512",.5,1.5,{tags:["llm","mistral","multilingual","european"]}),Hn("or-mistral-small","Mistral Small","Fast, efficient Mistral model. Good for everyday tasks.","mistralai/mistral-small-3.1-24b-instruct",.1,.3,{tags:["llm","mistral","fast","cheap"]}),Hn("or-deepseek-chat","DeepSeek Chat V3","Strong reasoning model at very low cost. Excellent for coding and math.","deepseek/deepseek-chat-v3-0324",.3,.88,{tags:["llm","deepseek","coding","math","cheap","reasoning"]}),Hn("or-deepseek-r1","DeepSeek R1","Advanced reasoning model with chain-of-thought. Best for complex problems.","deepseek/deepseek-r1",.55,2.19,{tags:["llm","deepseek","reasoning","chain-of-thought","math"]}),Hn("or-qwen-72b","Qwen 2.5 72B","Alibaba's large model. Strong at coding, math, and multilingual tasks.","qwen/qwen-2.5-72b-instruct",.3,.4,{tags:["llm","qwen","alibaba","coding","multilingual"]}),Hn("or-phi-4","Phi-4","Microsoft's compact reasoning model. Punches above its weight for size.","microsoft/phi-4",.07,.14,{tags:["llm","phi","microsoft","compact","cheap","reasoning"]}),Hn("or-perplexity-sonar","Perplexity Sonar","Search-augmented LLM. Answers with real-time web sources and citations.","perplexity/sonar",1,1,{perRequestFeeCents:.5,tags:["llm","perplexity","search","web","citations","real-time"]}),{dispatch:"enveloped",id:"query_onchain_prices",name:"Query On-Chain Prices",description:"Query real-time or historical on-chain token prices via Allium. Use this for current prices, price history over any date range, price trends, comparisons between time periods, and analytics like monthly/weekly price charts. Supports hourly and daily granularity.",provider:"allium",model:"allium-prices",category:"onchain",priceCents:1,inputSchema:{type:"object",properties:{chain:{type:"string",description:"Chain name (e.g. ethereum, solana, base, polygon)"},token_address:{type:"string",description:"Token contract address. Use the native token address for chain-native assets (e.g. ETH, SOL)."},start_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range start (e.g. '2024-01-01T00:00:00Z'). Omit for current price only."},end_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range end. Defaults to now if start_timestamp is set."},time_granularity:{type:"string",description:"Data resolution: '1h' (hourly) or '1d' (daily). Auto-selected based on date range if omitted."}},required:["chain","token_address"]},gatewayUrl:"https://agents.allium.so/api/v1/developer/prices",merchantName:"Allium",internal:!0,executionKind:"x402_gateway",resultKind:"utility",gatewayConfig:{enabled:!1,gatewayPath:"/gateway",method:"POST",timeoutMs:3e4},buildUrl:e=>e.start_timestamp?"https://agents.allium.so/api/v1/developer/prices/history":"https://agents.allium.so/api/v1/developer/prices",buildBody:T3e,tags:["onchain","prices","allium","crypto"]},{dispatch:"enveloped",id:"parallel-search-tempo",name:"Parallel Search (Tempo)",description:"Internal Tempo gateway route for Parallel's paid search endpoint.",provider:"parallel",model:"search",category:"utility",priceCents:1,inputSchema:{type:"object",properties:{query:{type:"string",description:"Search query. Mapped by Parallel to objective when provided."},objective:{type:"string",description:"Search objective. Use with search_queries for advanced requests."},search_queries:{type:"array",items:{type:"string"},description:"Optional explicit search query list."},mode:{type:"string",enum:["one-shot","fast"],description:"Parallel search mode.",default:"one-shot"}},anyOf:[{required:["query"]},{required:["objective"]}]},gatewayUrl:"https://parallelmpp.dev/api/search",merchantName:"Parallel",internal:!0,rail:"tempo",executionKind:"tempo_gateway",resultKind:"utility",gatewayConfig:{enabled:!1,gatewayPath:"/gateway",method:"POST",timeoutMs:3e4},buildBody:k1t,tags:["search","parallel","tempo","internal"]},{dispatch:"enveloped",id:"generate_image_card",name:"Generate Image (Ultra)",description:"Generate a high-quality AI image (FLUX Pro Ultra, 2K, ~$0.06).",provider:"fal",model:"fal-ai/flux-pro/v1.1-ultra",category:"image",priceCents:6,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"16:9"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux-pro/v1.1-ultra",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-pro-ultra",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),t},tags:["image","flux","ultra","legacy"]},{dispatch:"enveloped",id:"generate_image_fast_card",name:"Generate Image (Fast)",description:"Generate an AI image (FLUX Pro v1.1, 1K, ~$0.04).",provider:"fal",model:"fal-ai/flux-pro/v1.1",category:"image",priceCents:4,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux-pro/v1.1",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-pro",buildBody:e=>Xk({prompt:e.prompt,aspect_ratio:e.aspect_ratio}),tags:["image","flux","legacy"]},{dispatch:"enveloped",id:"generate_image_schnell_card",name:"Generate Image (Cheap)",description:"Cheap, fast FLUX image generation (~$0.01).",provider:"fal",model:"fal-ai/flux/schnell",category:"image",priceCents:1,inputSchema:{type:"object",properties:{prompt:{type:"string"},image_size:{type:"string"},num_inference_steps:{type:"number"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux/schnell",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-schnell",buildBody:e=>{let t={prompt:e.prompt};return e.image_size&&(t.image_size=e.image_size),e.num_inference_steps!==void 0&&(t.num_inference_steps=e.num_inference_steps),e.seed!==void 0&&(t.seed=e.seed),t},tags:["image","flux","schnell","legacy"]},{dispatch:"enveloped",id:"generate_image_recraft_card",name:"Generate Image (Recraft)",description:"Recraft V3 image generation with style control.",provider:"fal",model:"fal-ai/recraft-v3",category:"image",priceCents:5,inputSchema:{type:"object",properties:{prompt:{type:"string"},style:{type:"string"},image_size:{type:"string"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/recraft-v3",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-recraft-v3",buildBody:e=>{let t={prompt:e.prompt};return e.style&&(t.style=e.style),e.image_size&&(t.image_size=e.image_size),t},tags:["image","recraft","legacy"]},{dispatch:"enveloped",id:"generate_image_ideogram_card",name:"Generate Image (Ideogram)",description:"Ideogram V2 image generation, strong with text rendering.",provider:"fal",model:"fal-ai/ideogram/v2",category:"image",priceCents:8,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},style_type:{type:"string"},negative_prompt:{type:"string"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/ideogram/v2",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-ideogram-v2",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.style_type&&(t.style_type=e.style_type),e.negative_prompt&&(t.negative_prompt=e.negative_prompt),t},tags:["image","ideogram","text","legacy"]},Ci("upscale_image_card","Upscale Image","Upscale an image using ESRGAN.","fal-ai/esrgan","upscale",2,{type:"object",properties:{image_url:{type:"string"},scale:{type:"number"}},required:["image_url"]},{buildBody:e=>{let t={image_url:e.image_url};return e.scale!==void 0&&(t.scale=e.scale),t},tags:["upscale","esrgan"],deprecated:!0,replacementTool:"fal-aura-sr"}),Ci("edit_image_seed_card","Edit Image (SeedEdit)","Inpaint/edit an image with a prompt using SeedEdit.","fal-ai/bytedance/seededit","image",5,{type:"object",properties:{image_url:{type:"string"},prompt:{type:"string"},seed:{type:"number"}},required:["image_url","prompt"]},{buildBody:e=>{let t={image_url:e.image_url,prompt:e.prompt};return e.seed!==void 0&&(t.seed=e.seed),t},tags:["image","edit","inpaint","seededit"],deprecated:!0,replacementTool:"or-gemini-nano-banana"}),{dispatch:"enveloped",id:"generate_video_tempo_card",name:"Generate Video (Grok)",description:"Generate a video from a text prompt using Grok Imagine Video.",provider:"fal",model:"xai/grok-imagine-video/text-to-video",category:"video",priceCents:30,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},duration:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/xai/grok-imagine-video/text-to-video",merchantName:"Grok Video via fal.ai",deprecated:!0,replacementTool:"fal-minimax-video",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.duration&&(t.duration=e.duration),t},tags:["video","grok","legacy"]},{dispatch:"enveloped",id:"generate_video_kling_card",name:"Generate Video (Kling)",description:"Generate a video using Kling v1.6 (async, ~$0.40).",provider:"fal",model:"fal-ai/kling-video/v1.6/standard/text-to-video",category:"video",priceCents:40,inputSchema:{type:"object",properties:{prompt:{type:"string"},negative_prompt:{type:"string"},aspect_ratio:{type:"string"},duration:{type:"number"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/kling-video/v1.6/standard/text-to-video",merchantName:"Kling via fal.ai",deprecated:!0,replacementTool:"fal-kling-video",buildBody:e=>{let t={prompt:e.prompt};return e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.duration&&(t.duration=e.duration),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","kling","legacy"]},{dispatch:"enveloped",id:"generate_video_wan_card",name:"Generate Video (Wan)",description:"Generate a video using Wan T2V (async, ~$0.25).",provider:"fal",model:"fal-ai/wan/t2v-1.3b",category:"video",priceCents:25,inputSchema:{type:"object",properties:{prompt:{type:"string"},negative_prompt:{type:"string"},aspect_ratio:{type:"string"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/wan/t2v-1.3b",merchantName:"Wan T2V via fal.ai",deprecated:!0,replacementTool:"fal-wan-video",buildBody:e=>{let t={prompt:e.prompt};return e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","wan","legacy"]},{dispatch:"enveloped",id:"generate_video_minimax_card",name:"Generate Video (MiniMax)",description:"Generate a video using MiniMax (async, ~$0.35).",provider:"fal",model:"fal-ai/minimax/video-01",category:"video",priceCents:35,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/minimax/video-01",merchantName:"MiniMax via fal.ai",deprecated:!0,replacementTool:"fal-minimax-video",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","minimax","legacy"]},{id:"check_fal_status",name:"Check fal Async Job Status",description:"Poll an async fal.ai queue job for completion. Free.",provider:"fal",model:"queue-status",category:"image",priceCents:0,inputSchema:{type:"object",properties:{model_path:{type:"string",description:"Model path (e.g. fal-ai/kling-video/v1.6/standard/text-to-video)"},request_id:{type:"string"}},required:["model_path","request_id"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue",merchantName:"fal.ai",handler:{type:"local",fn:"check_fal_status"},pricing:{amount:0,currency:"USD",display:"$0.00",free:!0},freeReadPathPattern:"/api/v1/fal/**/requests/*/(status)?",tags:["status","fal","async"]},{dispatch:"enveloped",id:"generate_3d_card",name:"Generate 3D Model",description:"Generate a 3D mesh from a text prompt using Meshy (async, ~$0.50).",provider:"fal",model:"fal-ai/meshy-ai/text-to-3d",category:"3d",priceCents:50,inputSchema:{type:"object",properties:{object_prompt:{type:"string"},style_prompt:{type:"string"},negative_prompt:{type:"string"},art_style:{type:"string"},seed:{type:"number"}},required:["object_prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/meshy-ai/text-to-3d",merchantName:"Meshy via fal.ai",deprecated:!0,replacementTool:"fal-trellis-3d",buildBody:e=>{let t={object_prompt:e.object_prompt};return e.style_prompt&&(t.style_prompt=e.style_prompt),e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.art_style&&(t.art_style=e.art_style),e.seed!==void 0&&(t.seed=e.seed),t},tags:["3d","mesh","meshy","legacy"]},{dispatch:"enveloped",id:"generate_speech_card",name:"Generate Speech",description:"Text-to-speech using F5-TTS with optional voice cloning.",provider:"fal",model:"fal-ai/f5-tts",category:"tts",priceCents:3,inputSchema:{type:"object",properties:{gen_text:{type:"string",description:"Text to synthesize"},ref_audio_url:{type:"string",description:"Reference audio URL (for voice cloning)"},ref_text:{type:"string",description:"Transcription of ref audio"},remove_silence:{type:"boolean"}},required:["gen_text"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/f5-tts",merchantName:"fal.ai",buildBody:e=>{let t={gen_text:e.gen_text};return e.ref_audio_url&&(t.ref_audio_url=e.ref_audio_url),e.ref_text&&(t.ref_text=e.ref_text),e.remove_silence!==void 0&&(t.remove_silence=e.remove_silence),t},deprecated:!0,replacementTool:"fal-metavoice",tags:["tts","speech","f5-tts","legacy"]},{dispatch:"enveloped",id:"generate_music_tempo_card",name:"Generate Music (Suno) \u2014 retired",description:"[Retired] Suno music generation. Use `generate_music` (ACE-Step) instead.",enabled:!1,sunsetAt:"2026-06-25",provider:"suno",model:"suno-v4",category:"audio",priceCents:50,inputSchema:{type:"object",properties:{prompt:{type:"string"},instrumental:{type:"boolean"},model:{type:"string",default:"V4"}},required:["prompt"]},gatewayUrl:"https://suno.mpp.paywithlocus.com/suno/generate-music",merchantName:"Suno via Tempo",buildBody:e=>({prompt:e.prompt,customMode:!1,instrumental:e.instrumental??!1,model:e.model||"V4"}),isAsync:!0,pollUrl:"https://suno.mpp.paywithlocus.com/suno/get-music-status",pollInterval:15e3,pollTimeout:3e5,deprecated:!0,replacementTool:"fal-ace-step-music",tags:["music","audio","suno","async","legacy"]},{dispatch:"enveloped",id:"check_music_status_tempo_card",name:"Check Music Status (Suno) \u2014 retired",description:"[Retired] Suno status poll. No replacement; ACE-Step jobs poll via `check_fal_status`.",enabled:!1,sunsetAt:"2026-06-25",provider:"suno",model:"suno-status",category:"audio",priceCents:0,inputSchema:{type:"object",properties:{taskId:{type:"string"}},required:["taskId"]},gatewayUrl:"https://suno.mpp.paywithlocus.com/suno/get-music-status",merchantName:"Suno Status",buildBody:e=>({taskId:e.taskId}),deprecated:!0,tags:["music","status","suno","legacy"]},{dispatch:"enveloped",id:"query_onchain_prices_card",name:"Query On-Chain Prices",description:"Query real-time or historical on-chain token prices via Allium. Use this for current prices, price history over any date range, price trends, comparisons between time periods, and analytics like monthly/weekly price charts. Supports hourly, daily, and weekly granularity.",provider:"allium",model:"allium-prices",category:"llm",priceCents:1,inputSchema:{type:"object",properties:{chain:{type:"string",description:"Chain name (e.g. ethereum, solana, base, polygon)"},token_address:{type:"string",description:"Token contract address. Use the native token address for chain-native assets (e.g. ETH, SOL)."},start_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range start (e.g. '2024-01-01T00:00:00Z'). Omit for current price only."},end_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range end. Defaults to now if start_timestamp is set."},time_granularity:{type:"string",description:"Data resolution: '1h' (hourly), '1d' (daily), or '1w' (weekly). Auto-selected based on date range if omitted."}},required:["chain","token_address"]},gatewayUrl:"https://agents.allium.so/api/v1/developer/prices",merchantName:"Allium",deprecated:!0,replacementTool:"query_onchain_prices",buildUrl:e=>e.start_timestamp?"https://agents.allium.so/api/v1/developer/prices/history":"https://agents.allium.so/api/v1/developer/prices",buildBody:T3e,tags:["onchain","prices","allium","crypto","legacy"]}];function DA(e){return VY.find(t=>t.id===e)}function KY(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function WY(e,t){return Array.isArray(e.type)?e.type.includes(t):e.type===t}function U1t(e){return!!e.properties&&Object.keys(e.properties).length>0}function GY(e){let t=KY(e);if(!t||t.type!==void 0&&!WY(t,"object"))return!0;let r=Array.isArray(t.required)?t.required:[];return!U1t(t)&&r.length===0&&t.additionalProperties!==!1}function JY(e,t,r){let n=KY(e);if(!n||n.type!==void 0&&!WY(n,"object"))return`Input schema is unavailable for ${r}.`;let i=n.properties??{};if(n.additionalProperties!==!0){for(let s of Object.keys(t))if(!Object.prototype.hasOwnProperty.call(i,s)){let a=Object.keys(i),c=a.length>0?` Expected: ${a.join(", ")}.`:"";return`Unknown parameter "${s}" for ${r}.${c}`}}let o=(n.required??[]).filter(s=>!Object.prototype.hasOwnProperty.call(t,s)||t[s]===void 0);if(o.length>1)return`${o.join(", ")} are required for ${r}.`;for(let s of n.required??[]){if(!Object.prototype.hasOwnProperty.call(t,s)||t[s]===void 0)return`${s} is required for ${r}.`;if(t[s]===null)return`${s} cannot be null.`;if(typeof t[s]=="string"&&t[s].trim()==="")return`${s} cannot be empty.`}for(let[s,a]of Object.entries(t)){let c=i[s];if(!c||a===void 0||a===null)continue;let u=LA(s,a,c);if(u)return u}return null}var M1t=[{type:"integer",matches:e=>typeof e=="number"&&Number.isInteger(e),phrase:"an integer"},{type:"number",matches:e=>typeof e=="number"&&Number.isFinite(e),phrase:"a number"},{type:"string",matches:e=>typeof e=="string",phrase:"a string"},{type:"boolean",matches:e=>typeof e=="boolean",phrase:"a boolean"},{type:"array",matches:e=>Array.isArray(e),phrase:"an array"},{type:"object",matches:e=>typeof e=="object"&&e!==null&&!Array.isArray(e),phrase:"an object"}];function D1t(e,t){let n=(Array.isArray(t.type)?t.type:t.type!==void 0?[t.type]:[]).flatMap(o=>M1t.filter(s=>s.type===o)),i=new Set(n.filter(o=>o.matches(e)).map(o=>o.type));return{declared:n,matched:i}}function LA(e,t,r){if(r.enum&&!r.enum.includes(t))return`${e} must be one of: ${r.enum.map(String).join(", ")}.`;let{declared:n,matched:i}=D1t(t,r);if(n.length>0&&i.size===0)return`${e} must be ${n.map(o=>o.phrase).join(" or ")}.`;if(i.has("string")&&typeof t=="string"){if(t.trim()==="")return`${e} cannot be empty.`;if(r.minLength!==void 0&&t.length<r.minLength)return`${e} is too short.`;if(r.maxLength!==void 0&&t.length>r.maxLength)return`${e} is too long.`}if(typeof t=="number"){if(r.minimum!==void 0&&t<r.minimum)return`${e} must be at least ${r.minimum}.`;if(r.maximum!==void 0&&t>r.maximum)return`${e} must be at most ${r.maximum}.`}return null}function B3e(e,t){let r={unknown_params:[],missing_required:[],invalid_params:[]},n=KY(e);if(!n||n.type!==void 0&&!WY(n,"object"))return r;let i=n.properties??{};if(n.additionalProperties!==!0)for(let s of Object.keys(t))Object.prototype.hasOwnProperty.call(i,s)||r.unknown_params.push(s);let o=new Set;for(let s of n.required??[])!Object.prototype.hasOwnProperty.call(t,s)||t[s]===void 0?r.missing_required.push(s):(t[s]===null||typeof t[s]=="string"&&t[s].trim()==="")&&o.add(s);for(let[s,a]of Object.entries(t)){let c=i[s];!c||a===void 0||a===null||LA(s,a,c)&&o.add(s)}return r.invalid_params=[...o],r}function eB(e,t,r){if(GY(e))return{success:!1,error_code:"SCHEMA_UNAVAILABLE",code:"SCHEMA_UNAVAILABLE",error:`Cannot run paid platform tool '${r}' because its input schema is unavailable. Ask the provider to publish a request schema before running this paid direct tool.`,tool_id:r};let n=JY(e,t,r);return n?{success:!1,error_code:"INVALID_TOOL_PARAMS",code:"INVALID_TOOL_PARAMS",error:n,message:n,tool_id:r,violations:B3e(e,t)}:null}async function Ep(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 tB=class extends Error{code="ATTESTATION_KEY_DRIFT";hint;constructor(t,r){super(t),this.name="AttestationDriftError",this.hint=r}},Iw=class extends Error{code;budgetId;status;constructor(t,r,n={}){super(t),this.name="SessionInvalidError",this.code=r,this.budgetId=n.budgetId,this.status=n.status}},qm=class extends Error{code="SESSION_LOCK_CONTENDED";retryAfterSecs;status;constructor(t,r=1,n){super(t),this.name="SessionLockContendedError",this.retryAfterSecs=r,this.status=n}},Ap=class extends Error{code="PARENTLESS_NOT_ENABLED";status;serverErrorCode;constructor(t,r={}){super(t),this.name="ParentlessNotEnabledError",this.status=r.status,this.serverErrorCode=r.serverErrorCode}},Oi=class extends Error{retryable;code;reason;paymentErrorClass;correlationId;transactionId;retryAfter;constructor(t,r,n,i,o,s,a,c){super(t),this.name="CardDeclinedError",this.retryable=r,this.code=n,this.reason=i,this.paymentErrorClass=o,this.correlationId=s,this.transactionId=a,this.retryAfter=c}},lh=class extends Error{code;transactionId;retryable;reconciliationRequired;constructor(t,r,n={}){super(t),this.name="TopupAmbiguousError",this.code=r,this.transactionId=n.transactionId,this.retryable=n.retryable??!1,this.reconciliationRequired=n.reconciliationRequired??!0}};var N3e={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 Cw(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&&N3e[r]?N3e[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.`}ea();nB();var V1t="visa-cli setup",K1t="visa-cli agent enroll";function QY(e=process.env){return Um(e)!==null}function eZ(e=QY()){return e?`Note: \`${V1t}\` signs in to your Visa CLI account \u2014 separate from your v4 agent + card, which you set up with \`${K1t}\`.`:""}var W1t=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function D3e(e,t){let r=M3e(e),n=M3e(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:G1t(r.pre,n.pre)>0}function M3e(e){if(typeof e!="string")return null;let r=e.trim().replace(/^v/,"").match(W1t);return r?{main:[Number(r[1]),Number(r[2]),Number(r[3])],pre:r[4]??null}:null}function G1t(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 iB(){return!!(L3e(process.env.VISA_CLI_NO_UPDATE_CHECK)||L3e(process.env.CI)||process.env.NODE_ENV==="test")}function L3e(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}Qd();var oht="CARD_REENROLLMENT_REQUIRED",sht="https://auth.visacli.sh/enroll-card";function aht(){try{return new URL("/enroll-card",ta()).toString()}catch{return sht}}function cht(e){let t=aht();if(typeof e!="string")return t;try{let r=new URL(e),n=new URL(t);if(r.origin===n.origin&&r.pathname==="/enroll-card")return r.toString()}catch{}return W.warn("card-reenroll:reenroll_url_rejected_fallback",{reason:"untrusted_or_malformed_reenroll_url",fallbackPath:"/enroll-card"}),t}var fh="4.1.0-rc.24",uht=/^(?:VisaKey_[A-Za-z0-9_-]{16,128}|visakey_[A-Za-z0-9_-]{16,128}|vk_[A-Za-z0-9_-]{32,128})$/;async function KA(e){let t=null;try{t=await e.json()}catch{}if(t&&(t.error_code==="TOOL_UPSTREAM_AUTH_FAILED"||typeof t.upstream_status=="number"))return new Error(typeof t.error=="string"&&t.error?t.error:"The tool upstream rejected the request credentials.");let r=eZ();return new Error("Your session has expired. Run: visa-cli setup"+(r?`
|
|
20653
|
+
${e.nonce}`;return d8r.encode(r)}function f8r(e,t,r,n,i,o,s){return p8r({messageId:e,senderPeerId:t,senderName:r,timestampMs:n,messageType:i,payload:o,nonce:s})}function m8r(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 M8r(e){return e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1}function Wpt(e,t,r=""){let n=M8r(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 upt(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 D8r(e,t){Wpt(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 i8e(...e){for(let t=0;t<e.length;t++)e[t].fill(0)}function X4e(e){return new DataView(e.buffer,e.byteOffset,e.byteLength)}function L8r(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 F8r(e,t=!1){return t?{h:Number(e&YJ),l:Number(e>>dpt&YJ)}:{h:Number(e>>dpt&YJ)|0,l:Number(e&YJ)|0}}function $8r(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}=F8r(e[o],t);[n[o],i[o]]=[s,a]}return[n,i]}function th(e,t,r,n){let i=(t>>>0)+(n>>>0);return{h:e+r+(i/2**32|0)|0,l:i|0}}function r3r(){return N8r.randomSecretKey()}function Jpt(e){return k8r(e)}function n3r(){let e=r3r();return{secretKey:e,publicKey:Jpt(e)}}function i3r(e){if((0,m2.existsSync)(e)){let r=(0,m2.readFileSync)(e),n=new Uint8Array(r.buffer.slice(r.byteOffset,r.byteOffset+32));return{secretKey:n,publicKey:Jpt(n)}}let t=n3r();return(0,m2.mkdirSync)((0,hpt.dirname)(e),{recursive:!0}),(0,m2.writeFileSync)(e,new Uint8Array(t.secretKey)),t}function o3r(e){let{secretKey:t,publicKey:r}=i3r(e);return{privateKey:t,publicKey:r}}async function s3r(e,t,r,n,i,o,s,a){let c=f8r(t,r,n,i,o,s,a);return{signature:await a8r(e,c),signatureInput:l8r.subwayAgentMsgV1}}function mpt(e){return u8r(e)}var m2,hpt,h4r,y4r,g4r,b4r,_4r,ypt,tY,QJ,$lt,Vlt,V4e,K4e,v4r,aY,w4r,hs,x4r,E4r,A4r,rh,cY,o8e,gpt,s8e,X1,Klt,a8e,bpt,S4r,TA,T4r,rY,nw,En,Wlt,$e,_pt,vpt,wpt,xpt,W4e,Q4e,Ck,uw,aw,Ept,Apt,Pm,P4r,Glt,I4r,e8e,c8e,C4r,Spt,O4r,R4r,k4r,B4r,N4r,j4r,u8e,Tpt,nY,q4r,Ppt,t8e,U4r,Jlt,Ylt,M4r,Opt,Rpt,c2,Zs,WJ,Xlt,Qlt,ept,xA,EA,GJ,JJ,V4r,K4r,W4r,G4r,J4r,Y4r,Z4r,u2,X4r,Q4r,kpt,e8r,t8r,d2,l2,r8r,n8r,i8r,o8r,tpt,c8r,Bpt,d8r,l8r,Npt,h8r,jpt,iY,eY,rpt,npt,J4e,Y4e,y8r,PA,g8r,ys,b8r,_8r,v8r,h2,uY,d8e,qpt,Upt,eh,ipt,Mpt,Dpt,w8r,l8e,x8r,oY,ow,Dn,opt,Ve,E8r,A8r,Lpt,Hpt,Z4e,r8e,Ok,IA,cw,S8r,zpt,Cm,T8r,spt,P8r,I8r,C8r,O8r,Fpt,R8r,$pt,k8r,Vpt,B8r,N8r,sY,j8r,Kpt,n8e,q8r,apt,cpt,U8r,H8r,z8r,Xs,YJ,dpt,lpt,ppt,AA,SA,ZJ,XJ,V8r,K8r,W8r,G8r,J8r,Y8r,Gpt,Z8r,X8r,p2,f2,Q8r,e3r,t3r,fpt,a3r,c3r,Ypt,Zpt=I(()=>{"use strict";z4e();z4e();F4e();m2=require("fs"),hpt=require("path");h4r=1e3,y4r=10,g4r=3e4,b4r=3e4,_4r=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??h4r,this.maxReconnectAttempts=e.maxReconnectAttempts??y4r,this.pingInterval=e.pingInterval??g4r}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=f4r();if(!r){t(new Ys('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 Ys(`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 Ys("WebSocket closed before connection established")))},this.ws.onerror=()=>{n||(n=!0,t(new Ys(`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 Ys("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=m4r(this.reconnectInterval*Math.pow(2,this.reconnectAttempt),this.reconnectInterval,b4r);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)}}},ypt=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:tY,n:QJ,Gx:$lt,Gy:Vlt,a:V4e,d:K4e,h:v4r}=ypt,aY=32,w4r=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},hs=(e="")=>{let t=new Error(e);throw w4r(t,hs),t},x4r=e=>typeof e=="bigint",E4r=e=>typeof e=="string",A4r=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,rh=(e,t,r="")=>{let n=A4r(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},cY=e=>new Uint8Array(e),o8e=e=>Uint8Array.from(e),gpt=(e,t)=>e.toString(16).padStart(t,"0"),s8e=e=>Array.from(rh(e)).map(t=>gpt(t,2)).join(""),X1={_0:48,_9:57,A:65,F:70,a:97,f:102},Klt=e=>{if(e>=X1._0&&e<=X1._9)return e-X1._0;if(e>=X1.A&&e<=X1.F)return e-(X1.A-10);if(e>=X1.a&&e<=X1.f)return e-(X1.a-10)},a8e=e=>{let t="hex invalid";if(!E4r(e))return hs(t);let r=e.length,n=r/2;if(r%2)return hs(t);let i=cY(n);for(let o=0,s=0;o<n;o++,s+=2){let a=Klt(e.charCodeAt(s)),c=Klt(e.charCodeAt(s+1));if(a===void 0||c===void 0)return hs(t);i[o]=a*16+c}return i},bpt=()=>globalThis?.crypto,S4r=()=>bpt()?.subtle??hs("crypto.subtle must be defined, consider polyfill"),TA=(...e)=>{let t=0;for(let i of e)t+=rh(i).length;let r=cY(t),n=0;return e.forEach(i=>{r.set(i,n),n+=i.length}),r},T4r=(e=aY)=>bpt().getRandomValues(cY(e)),rY=BigInt,nw=(e,t,r,n="bad number: out of range")=>{if(!x4r(e))throw new TypeError(n);if(t<=e&&e<r)return e;throw new RangeError(n)},En=(e,t=tY)=>{let r=e%t;return r>=0n?r:t+r},Wlt=(1n<<255n)-1n,$e=e=>{e<0n&&hs("negative coordinate");let t=(e>>255n)*19n+(e&Wlt);return t=(t>>255n)*19n+(t&Wlt),t%tY},_pt=e=>En(e,QJ),vpt=(e,t)=>{(e===0n||t<=0n)&&hs("no inverse n="+e+" mod="+t);let r=En(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?En(i,t):hs("no inverse")},wpt=e=>{let t=Tpt[e];return typeof t!="function"&&hs("hashes."+e+" not set"),t},xpt=e=>rh(e,64,"digest"),W4e=e=>e instanceof Ck?e:hs("Point expected"),Q4e=2n**256n,Ck=class iw{static BASE;static ZERO;X;Y;Z;T;constructor(t,r,n,i){let o=Q4e;this.X=nw(t,0n,o),this.Y=nw(r,0n,o),this.Z=nw(n,1n,o),this.T=nw(i,0n,o),Object.freeze(this)}static CURVE(){return ypt}static fromAffine(t){return new iw(t.x,t.y,1n,$e(t.x*t.y))}static fromBytes(t,r=!1){let n=K4e,i=o8e(rh(t,aY)),o=t[31];i[31]=o&-129;let s=Apt(i);nw(s,0n,r?Q4e:tY);let c=$e(s*s),u=En(c-1n),d=$e(n*c+1n),{isValid:l,value:p}=I4r(u,d);l||hs("bad point: y not sqrt");let f=(p&1n)===1n,m=(o&128)!==0;return!r&&p===0n&&m&&hs("bad point: x==0, isLastByteOdd"),m!==f&&(p=En(-p)),new iw(p,s,1n,$e(p*s))}static fromHex(t,r){return iw.fromBytes(a8e(t),r)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=V4e,r=K4e,n=this;if(n.is0())return hs("bad point: ZERO");let{X:i,Y:o,Z:s,T:a}=n,c=$e(i*i),u=$e(o*o),d=$e(s*s),l=$e(d*d),p=$e(c*t),f=$e(d*(p+u)),m=En(l+$e(r*$e(c*u)));if(f!==m)return hs("bad point: equation left != right (1)");let h=$e(i*o),y=$e(s*a);return h!==y?hs("bad point: equation left != right (2)"):this}equals(t){let{X:r,Y:n,Z:i}=this,{X:o,Y:s,Z:a}=W4e(t),c=$e(r*a),u=$e(o*i),d=$e(n*a),l=$e(s*i);return c===u&&d===l}is0(){return this.equals(aw)}negate(){return new iw(En(-this.X),this.Y,this.Z,En(-this.T))}double(){let{X:t,Y:r,Z:n}=this,i=V4e,o=$e(t*t),s=$e(r*r),a=$e(2n*n*n),c=$e(i*o),u=En(t+r),d=En($e(u*u)-o-s),l=En(c+s),p=En(l-a),f=En(c-s),m=$e(d*p),h=$e(l*f),y=$e(d*f),v=$e(p*l);return new iw(m,h,v,y)}add(t){let{X:r,Y:n,Z:i,T:o}=this,{X:s,Y:a,Z:c,T:u}=W4e(t),d=V4e,l=K4e,p=$e(r*s),f=$e(n*a),m=$e($e(o*l)*u),h=$e(i*c),y=En($e(En(r+n)*En(s+a))-p-f),v=En(h-m),x=En(h+m),_=En(f-$e(d*p)),w=$e(y*v),E=$e(x*_),A=$e(y*_),S=$e(v*x);return new iw(w,E,S,A)}subtract(t){return this.add(W4e(t).negate())}multiply(t,r=!0){if(!r&&t===0n||(nw(t,1n,QJ),!r&&this.is0()))return aw;if(t===1n)return this;if(this.equals(uw))return M4r(t).p;let n=aw,i=uw;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(aw))return{x:0n,y:1n};let i=vpt(n,tY);$e(n*i)!==1n&&hs("invalid inverse");let o=$e(t*i),s=$e(r*i);return{x:o,y:s}}toBytes(){let{x:t,y:r}=this.toAffine(),n=Ept(r);return n[31]|=t&1n?128:0,n}toHex(){return s8e(this.toBytes())}clearCofactor(){return this.multiply(rY(v4r),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(QJ/2n,!1).double();return QJ%2n&&(t=t.add(this)),t.is0()}},uw=new Ck($lt,Vlt,1n,En($lt*Vlt)),aw=new Ck(0n,1n,1n,0n);Ck.BASE=uw;Ck.ZERO=aw;Ept=e=>a8e(gpt(nw(e,0n,Q4e),64)).reverse(),Apt=e=>rY("0x"+s8e(o8e(rh(e)).reverse())),Pm=(e,t)=>{let r=e;for(;t-- >0n;)r=$e(r*r);return r},P4r=e=>{let t=$e(e*e),r=$e(t*e),n=$e(Pm(r,2n)*r),i=$e(Pm(n,1n)*e),o=$e(Pm(i,5n)*i),s=$e(Pm(o,10n)*o),a=$e(Pm(s,20n)*s),c=$e(Pm(a,40n)*a),u=$e(Pm(c,80n)*c),d=$e(Pm(u,80n)*c),l=$e(Pm(d,10n)*o);return{pow_p_5_8:$e(Pm(l,2n)*e),b2:r}},Glt=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,I4r=(e,t)=>{let r=$e(t*$e(t*t)),n=$e($e(r*r)*t),i=P4r($e(e*n)).pow_p_5_8,o=$e(e*$e(r*i)),s=$e(t*$e(o*o)),a=o,c=$e(o*Glt),u=s===e,d=s===En(-e),l=s===En(-e*Glt);return u&&(o=a),(d||l)&&(o=c),(En(o)&1n)===1n&&(o=En(-o)),{isValid:u||d,value:o}},e8e=e=>_pt(Apt(e)),c8e=(...e)=>Promise.resolve(wpt("sha512Async")(TA(...e))).then(xpt),C4r=(...e)=>xpt(wpt("sha512")(TA(...e))),Spt=e=>{let t=o8e(e),r=t.slice(0,32);r[0]&=248,r[31]&=127,r[31]|=64;let n=t.slice(32,64),i=e8e(r),o=uw.multiply(i),s=o.toBytes();return{head:r,prefix:n,scalar:i,point:o,pointBytes:s}},O4r=e=>c8e(rh(e,aY)).then(Spt),R4r=e=>Spt(C4r(rh(e,aY))),k4r=e=>R4r(e).pointBytes,B4r=e=>c8e(e.hashable).then(e.finish),N4r=(e,t,r)=>{let{pointBytes:n,scalar:i}=e,o=e8e(t),s=uw.multiply(o).toBytes();return{hashable:TA(s,n,r),finish:u=>{let d=_pt(o+e8e(u)*i);return rh(TA(s,Ept(d)),64)}}},j4r=async(e,t)=>{let r=rh(e),n=await O4r(t),i=await c8e(n.prefix,r);return B4r(N4r(n,i,r))},u8e=Object.freeze({bytesToHex:s8e,hexToBytes:a8e,concatBytes:TA,mod:En,invert:vpt,randomBytes:T4r}),Tpt={sha512Async:async e=>{let t=S4r(),r=TA(e);return cY(await t.digest("SHA-512",r.buffer))},sha512:void 0},nY=8,q4r=256,Ppt=Math.ceil(q4r/nY)+1,t8e=2**(nY-1),U4r=()=>{let e=[],t=uw,r=t;for(let n=0;n<Ppt;n++){r=t,e.push(r);for(let i=1;i<t8e;i++)r=r.add(t),e.push(r);t=r.double()}return e},Jlt=void 0,Ylt=(e,t)=>{let r=t.negate();return e?r:t},M4r=e=>{let t=Jlt||(Jlt=U4r()),r=aw,n=uw,i=2**nY,o=i,s=rY(i-1),a=rY(nY);for(let c=0;c<Ppt;c++){let u=Number(e&s);e>>=a,u>t8e&&(u-=o,e+=1n);let d=c*t8e,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&&hs("invalid wnaf"),{p:r,f:n}};Opt=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])});Rpt=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=G4e(this.buffer)}update(e){Zlt(this),Ipt(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=G4e(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){Zlt(this),L4r(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:i}=this,{pos:o}=this;t[o++]=128,Ik(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=G4e(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()}},c2=Uint32Array.from([1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225]),Zs=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),WJ=BigInt(2**32-1),Xlt=BigInt(32);Qlt=(e,t,r)=>e>>>r,ept=(e,t,r)=>e<<32-r|t>>>r,xA=(e,t,r)=>e>>>r|t<<32-r,EA=(e,t,r)=>e<<32-r|t>>>r,GJ=(e,t,r)=>e<<64-r|t>>>r-32,JJ=(e,t,r)=>e>>>r-32|t<<64-r;V4r=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),K4r=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,W4r=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),G4r=(e,t,r,n,i)=>t+r+n+i+(e/2**32|0)|0,J4r=(e,t,r,n,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(i>>>0),Y4r=(e,t,r,n,i,o)=>t+r+n+i+o+(e/2**32|0)|0,Z4r=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]),u2=new Uint32Array(64),X4r=class extends Rpt{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)u2[d]=e.getUint32(t,!1);for(let d=16;d<64;d++){let l=u2[d-15],p=u2[d-2],f=Im(l,7)^Im(l,18)^l>>>3,m=Im(p,17)^Im(p,19)^p>>>10;u2[d]=m+u2[d-7]+f+u2[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=Im(s,6)^Im(s,11)^Im(s,25),p=u+l+H4r(s,a,c)+Z4r[d]+u2[d]|0,m=(Im(r,2)^Im(r,13)^Im(r,22))+z4r(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(){Ik(u2)}destroy(){this.destroyed=!0,this.set(0,0,0,0,0,0,0,0),Ik(this.buffer)}},Q4r=class extends X4r{A=c2[0]|0;B=c2[1]|0;C=c2[2]|0;D=c2[3]|0;E=c2[4]|0;F=c2[5]|0;G=c2[6]|0;H=c2[7]|0;constructor(){super(32)}},kpt=$4r(["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))),e8r=kpt[0],t8r=kpt[1],d2=new Uint32Array(80),l2=new Uint32Array(80),r8r=class extends Rpt{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)d2[x]=e.getUint32(t),l2[x]=e.getUint32(t+=4);for(let x=16;x<80;x++){let _=d2[x-15]|0,w=l2[x-15]|0,E=xA(_,w,1)^xA(_,w,8)^Qlt(_,w,7),A=EA(_,w,1)^EA(_,w,8)^ept(_,w,7),S=d2[x-2]|0,T=l2[x-2]|0,O=xA(S,T,19)^GJ(S,T,61)^Qlt(S,T,6),R=EA(S,T,19)^JJ(S,T,61)^ept(S,T,6),U=W4r(A,R,l2[x-7],l2[x-16]),q=G4r(U,E,O,d2[x-7],d2[x-16]);d2[x]=q|0,l2[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:v}=this;for(let x=0;x<80;x++){let _=xA(d,l,14)^xA(d,l,18)^GJ(d,l,41),w=EA(d,l,14)^EA(d,l,18)^JJ(d,l,41),E=d&p^~d&m,A=l&f^~l&h,S=J4r(v,w,A,t8r[x],l2[x]),T=Y4r(S,y,_,E,e8r[x],d2[x]),O=S|0,R=xA(r,n,28)^GJ(r,n,34)^GJ(r,n,39),U=EA(r,n,28)^JJ(r,n,34)^JJ(r,n,39),q=r&i^r&s^i&s,j=n&o^n&a^o&a;y=m|0,v=h|0,m=p|0,h=f|0,p=d|0,f=l|0,{h:d,l}=Q1(c|0,u|0,T|0,O|0),c=s|0,u=a|0,s=i|0,a=o|0,i=r|0,o=n|0;let B=V4r(O,U,j);r=K4r(B,T,R,q),n=B|0}({h:r,l:n}=Q1(this.Ah|0,this.Al|0,r|0,n|0)),{h:i,l:o}=Q1(this.Bh|0,this.Bl|0,i|0,o|0),{h:s,l:a}=Q1(this.Ch|0,this.Cl|0,s|0,a|0),{h:c,l:u}=Q1(this.Dh|0,this.Dl|0,c|0,u|0),{h:d,l}=Q1(this.Eh|0,this.El|0,d|0,l|0),{h:p,l:f}=Q1(this.Fh|0,this.Fl|0,p|0,f|0),{h:m,l:h}=Q1(this.Gh|0,this.Gl|0,m|0,h|0),{h:y,l:v}=Q1(this.Hh|0,this.Hl|0,y|0,v|0),this.set(r,n,i,o,s,a,c,u,d,l,p,f,m,h,y,v)}roundClean(){Ik(d2,l2)}destroy(){this.destroyed=!0,Ik(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},n8r=class extends r8r{Ah=Zs[0]|0;Al=Zs[1]|0;Bh=Zs[2]|0;Bl=Zs[3]|0;Ch=Zs[4]|0;Cl=Zs[5]|0;Dh=Zs[6]|0;Dl=Zs[7]|0;Eh=Zs[8]|0;El=Zs[9]|0;Fh=Zs[10]|0;Fl=Zs[11]|0;Gh=Zs[12]|0;Gl=Zs[13]|0;Hh=Zs[14]|0;Hl=Zs[15]|0;constructor(){super(64)}},i8r=Cpt(()=>new Q4r,Opt(1)),o8r=Cpt(()=>new n8r,Opt(3)),tpt=Tpt;tpt.sha512||(tpt.sha512=e=>o8r(e));c8r=u8e.bytesToHex,Bpt=u8e.hexToBytes;u8e.concatBytes;d8r=new TextEncoder,l8r={subwayAgentMsgV1:"message_id;sender_peer_id;sender_name;timestamp_ms;message_type;payload_hash;nonce"};Bpt("302e020100300506032b657004220420");Bpt("302a300506032b6570032100");Npt="ABCDEFGHJKLMNPQRSTUVWXYZ23456789",h8r=Npt.length-1;if((Npt.length&h8r)!==0)throw new Error("agent pairing code alphabet must contain a power-of-two number of symbols");jpt=Object.freeze({p:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,n:0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,h:8n,a:0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,d:0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,Gx:0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,Gy:0x6666666666666666666666666666666666666666666666666666666666666658n}),{p:iY,n:eY,Gx:rpt,Gy:npt,a:J4e,d:Y4e,h:y8r}=jpt,PA=32,g8r=(...e)=>{"captureStackTrace"in Error&&typeof Error.captureStackTrace=="function"&&Error.captureStackTrace(...e)},ys=(e="")=>{let t=new Error(e);throw g8r(t,ys),t},b8r=e=>typeof e=="bigint",_8r=e=>typeof e=="string",v8r=e=>e instanceof Uint8Array||ArrayBuffer.isView(e)&&e.constructor.name==="Uint8Array"&&"BYTES_PER_ELEMENT"in e&&e.BYTES_PER_ELEMENT===1,h2=(e,t,r="")=>{let n=v8r(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},uY=e=>new Uint8Array(e),d8e=e=>Uint8Array.from(e),qpt=(e,t)=>e.toString(16).padStart(t,"0"),Upt=e=>Array.from(h2(e)).map(t=>qpt(t,2)).join(""),eh={_0:48,_9:57,A:65,F:70,a:97,f:102},ipt=e=>{if(e>=eh._0&&e<=eh._9)return e-eh._0;if(e>=eh.A&&e<=eh.F)return e-(eh.A-10);if(e>=eh.a&&e<=eh.f)return e-(eh.a-10)},Mpt=e=>{let t="hex invalid";if(!_8r(e))return ys(t);let r=e.length,n=r/2;if(r%2)return ys(t);let i=uY(n);for(let o=0,s=0;o<n;o++,s+=2){let a=ipt(e.charCodeAt(s)),c=ipt(e.charCodeAt(s+1));if(a===void 0||c===void 0)return ys(t);i[o]=a*16+c}return i},Dpt=()=>globalThis?.crypto,w8r=()=>Dpt()?.subtle??ys("crypto.subtle must be defined, consider polyfill"),l8e=(...e)=>{let t=0;for(let i of e)t+=h2(i).length;let r=uY(t),n=0;return e.forEach(i=>{r.set(i,n),n+=i.length}),r},x8r=(e=PA)=>Dpt().getRandomValues(uY(e)),oY=BigInt,ow=(e,t,r,n="bad number: out of range")=>{if(!b8r(e))throw new TypeError(n);if(t<=e&&e<r)return e;throw new RangeError(n)},Dn=(e,t=iY)=>{let r=e%t;return r>=0n?r:t+r},opt=(1n<<255n)-1n,Ve=e=>{e<0n&&ys("negative coordinate");let t=(e>>255n)*19n+(e&opt);return t=(t>>255n)*19n+(t&opt),t%iY},E8r=e=>Dn(e,eY),A8r=(e,t)=>{(e===0n||t<=0n)&&ys("no inverse n="+e+" mod="+t);let r=Dn(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?Dn(i,t):ys("no inverse")},Lpt=e=>{let t=Vpt[e];return typeof t!="function"&&ys("hashes."+e+" not set"),t},Hpt=e=>h2(e,64,"digest"),Z4e=e=>e instanceof Ok?e:ys("Point expected"),r8e=2n**256n,Ok=class sw{static BASE;static ZERO;X;Y;Z;T;constructor(t,r,n,i){let o=r8e;this.X=ow(t,0n,o),this.Y=ow(r,0n,o),this.Z=ow(n,1n,o),this.T=ow(i,0n,o),Object.freeze(this)}static CURVE(){return jpt}static fromAffine(t){return new sw(t.x,t.y,1n,Ve(t.x*t.y))}static fromBytes(t,r=!1){let n=Y4e,i=d8e(h2(t,PA)),o=t[31];i[31]=o&-129;let s=zpt(i);ow(s,0n,r?r8e:iY);let c=Ve(s*s),u=Dn(c-1n),d=Ve(n*c+1n),{isValid:l,value:p}=P8r(u,d);l||ys("bad point: y not sqrt");let f=(p&1n)===1n,m=(o&128)!==0;return!r&&p===0n&&m&&ys("bad point: x==0, isLastByteOdd"),m!==f&&(p=Dn(-p)),new sw(p,s,1n,Ve(p*s))}static fromHex(t,r){return sw.fromBytes(Mpt(t),r)}get x(){return this.toAffine().x}get y(){return this.toAffine().y}assertValidity(){let t=J4e,r=Y4e,n=this;if(n.is0())return ys("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=Dn(l+Ve(r*Ve(c*u)));if(f!==m)return ys("bad point: equation left != right (1)");let h=Ve(i*o),y=Ve(s*a);return h!==y?ys("bad point: equation left != right (2)"):this}equals(t){let{X:r,Y:n,Z:i}=this,{X:o,Y:s,Z:a}=Z4e(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(cw)}negate(){return new sw(Dn(-this.X),this.Y,this.Z,Dn(-this.T))}double(){let{X:t,Y:r,Z:n}=this,i=J4e,o=Ve(t*t),s=Ve(r*r),a=Ve(2n*n*n),c=Ve(i*o),u=Dn(t+r),d=Dn(Ve(u*u)-o-s),l=Dn(c+s),p=Dn(l-a),f=Dn(c-s),m=Ve(d*p),h=Ve(l*f),y=Ve(d*f),v=Ve(p*l);return new sw(m,h,v,y)}add(t){let{X:r,Y:n,Z:i,T:o}=this,{X:s,Y:a,Z:c,T:u}=Z4e(t),d=J4e,l=Y4e,p=Ve(r*s),f=Ve(n*a),m=Ve(Ve(o*l)*u),h=Ve(i*c),y=Dn(Ve(Dn(r+n)*Dn(s+a))-p-f),v=Dn(h-m),x=Dn(h+m),_=Dn(f-Ve(d*p)),w=Ve(y*v),E=Ve(x*_),A=Ve(y*_),S=Ve(v*x);return new sw(w,E,S,A)}subtract(t){return this.add(Z4e(t).negate())}multiply(t,r=!0){if(!r&&t===0n||(ow(t,1n,eY),!r&&this.is0()))return cw;if(t===1n)return this;if(this.equals(IA))return U8r(t).p;let n=cw,i=IA;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(cw))return{x:0n,y:1n};let i=A8r(n,iY);Ve(n*i)!==1n&&ys("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=S8r(r);return n[31]|=t&1n?128:0,n}toHex(){return Upt(this.toBytes())}clearCofactor(){return this.multiply(oY(y8r),!1)}isSmallOrder(){return this.clearCofactor().is0()}isTorsionFree(){let t=this.multiply(eY/2n,!1).double();return eY%2n&&(t=t.add(this)),t.is0()}},IA=new Ok(rpt,npt,1n,Dn(rpt*npt)),cw=new Ok(0n,1n,1n,0n);Ok.BASE=IA;Ok.ZERO=cw;S8r=e=>Mpt(qpt(ow(e,0n,r8e),64)).reverse(),zpt=e=>oY("0x"+Upt(d8e(h2(e)).reverse())),Cm=(e,t)=>{let r=e;for(;t-- >0n;)r=Ve(r*r);return r},T8r=e=>{let t=Ve(e*e),r=Ve(t*e),n=Ve(Cm(r,2n)*r),i=Ve(Cm(n,1n)*e),o=Ve(Cm(i,5n)*i),s=Ve(Cm(o,10n)*o),a=Ve(Cm(s,20n)*s),c=Ve(Cm(a,40n)*a),u=Ve(Cm(c,80n)*c),d=Ve(Cm(u,80n)*c),l=Ve(Cm(d,10n)*o);return{pow_p_5_8:Ve(Cm(l,2n)*e),b2:r}},spt=0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n,P8r=(e,t)=>{let r=Ve(t*Ve(t*t)),n=Ve(Ve(r*r)*t),i=T8r(Ve(e*n)).pow_p_5_8,o=Ve(e*Ve(r*i)),s=Ve(t*Ve(o*o)),a=o,c=Ve(o*spt),u=s===e,d=s===Dn(-e),l=s===Dn(-e*spt);return u&&(o=a),(d||l)&&(o=c),(Dn(o)&1n)===1n&&(o=Dn(-o)),{isValid:u||d,value:o}},I8r=e=>E8r(zpt(e)),C8r=(...e)=>Promise.resolve(Lpt("sha512Async")(l8e(...e))).then(Hpt),O8r=(...e)=>Hpt(Lpt("sha512")(l8e(...e))),Fpt=e=>{let t=d8e(e),r=t.slice(0,32);r[0]&=248,r[31]&=127,r[31]|=64;let n=t.slice(32,64),i=I8r(r),o=IA.multiply(i),s=o.toBytes();return{head:r,prefix:n,scalar:i,point:o,pointBytes:s}},R8r=e=>C8r(h2(e,PA)).then(Fpt),$pt=e=>Fpt(O8r(h2(e,PA))),k8r=e=>$pt(e).pointBytes,Vpt={sha512Async:async e=>{let t=w8r(),r=l8e(e);return uY(await t.digest("SHA-512",r.buffer))},sha512:void 0},B8r=e=>(e=e===void 0?x8r(PA):e,h2(e,PA)),N8r=Object.freeze({getExtendedPublicKeyAsync:R8r,getExtendedPublicKey:$pt,randomSecretKey:B8r}),sY=8,j8r=256,Kpt=Math.ceil(j8r/sY)+1,n8e=2**(sY-1),q8r=()=>{let e=[],t=IA,r=t;for(let n=0;n<Kpt;n++){r=t,e.push(r);for(let i=1;i<n8e;i++)r=r.add(t),e.push(r);t=r.double()}return e},apt=void 0,cpt=(e,t)=>{let r=t.negate();return e?r:t},U8r=e=>{let t=apt||(apt=q8r()),r=cw,n=IA,i=2**sY,o=i,s=oY(i-1),a=oY(sY);for(let c=0;c<Kpt;c++){let u=Number(e&s);e>>=a,u>n8e&&(u-=o,e+=1n);let d=c*n8e,l=d,p=d+Math.abs(u)-1,f=c%2!==0,m=u<0;u===0?n=n.add(cpt(f,t[l])):r=r.add(cpt(m,t[p]))}return e!==0n&&ys("invalid wnaf"),{p:r,f:n}};H8r=e=>({oid:Uint8Array.from([6,9,96,134,72,1,101,3,4,2,e])}),z8r=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=X4e(this.buffer)}update(e){upt(this),Wpt(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=X4e(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){upt(this),D8r(e,this),this.finished=!0;let{buffer:t,view:r,blockLen:n,isLE:i}=this,{pos:o}=this;t[o++]=128,i8e(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=X4e(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()}},Xs=Uint32Array.from([1779033703,4089235720,3144134277,2227873595,1013904242,4271175723,2773480762,1595750129,1359893119,2917565137,2600822924,725511199,528734635,4215389547,1541459225,327033209]),YJ=BigInt(2**32-1),dpt=BigInt(32);lpt=(e,t,r)=>e>>>r,ppt=(e,t,r)=>e<<32-r|t>>>r,AA=(e,t,r)=>e>>>r|t<<32-r,SA=(e,t,r)=>e<<32-r|t>>>r,ZJ=(e,t,r)=>e<<64-r|t>>>r-32,XJ=(e,t,r)=>e>>>r-32|t<<64-r;V8r=(e,t,r)=>(e>>>0)+(t>>>0)+(r>>>0),K8r=(e,t,r,n)=>t+r+n+(e/2**32|0)|0,W8r=(e,t,r,n)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0),G8r=(e,t,r,n,i)=>t+r+n+i+(e/2**32|0)|0,J8r=(e,t,r,n,i)=>(e>>>0)+(t>>>0)+(r>>>0)+(n>>>0)+(i>>>0),Y8r=(e,t,r,n,i,o)=>t+r+n+i+o+(e/2**32|0)|0,Gpt=$8r(["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))),Z8r=Gpt[0],X8r=Gpt[1],p2=new Uint32Array(80),f2=new Uint32Array(80),Q8r=class extends z8r{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)p2[x]=e.getUint32(t),f2[x]=e.getUint32(t+=4);for(let x=16;x<80;x++){let _=p2[x-15]|0,w=f2[x-15]|0,E=AA(_,w,1)^AA(_,w,8)^lpt(_,w,7),A=SA(_,w,1)^SA(_,w,8)^ppt(_,w,7),S=p2[x-2]|0,T=f2[x-2]|0,O=AA(S,T,19)^ZJ(S,T,61)^lpt(S,T,6),R=SA(S,T,19)^XJ(S,T,61)^ppt(S,T,6),U=W8r(A,R,f2[x-7],f2[x-16]),q=G8r(U,E,O,p2[x-7],p2[x-16]);p2[x]=q|0,f2[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:v}=this;for(let x=0;x<80;x++){let _=AA(d,l,14)^AA(d,l,18)^ZJ(d,l,41),w=SA(d,l,14)^SA(d,l,18)^XJ(d,l,41),E=d&p^~d&m,A=l&f^~l&h,S=J8r(v,w,A,X8r[x],f2[x]),T=Y8r(S,y,_,E,Z8r[x],p2[x]),O=S|0,R=AA(r,n,28)^ZJ(r,n,34)^ZJ(r,n,39),U=SA(r,n,28)^XJ(r,n,34)^XJ(r,n,39),q=r&i^r&s^i&s,j=n&o^n&a^o&a;y=m|0,v=h|0,m=p|0,h=f|0,p=d|0,f=l|0,{h:d,l}=th(c|0,u|0,T|0,O|0),c=s|0,u=a|0,s=i|0,a=o|0,i=r|0,o=n|0;let B=V8r(O,U,j);r=K8r(B,T,R,q),n=B|0}({h:r,l:n}=th(this.Ah|0,this.Al|0,r|0,n|0)),{h:i,l:o}=th(this.Bh|0,this.Bl|0,i|0,o|0),{h:s,l:a}=th(this.Ch|0,this.Cl|0,s|0,a|0),{h:c,l:u}=th(this.Dh|0,this.Dl|0,c|0,u|0),{h:d,l}=th(this.Eh|0,this.El|0,d|0,l|0),{h:p,l:f}=th(this.Fh|0,this.Fl|0,p|0,f|0),{h:m,l:h}=th(this.Gh|0,this.Gl|0,m|0,h|0),{h:y,l:v}=th(this.Hh|0,this.Hl|0,y|0,v|0),this.set(r,n,i,o,s,a,c,u,d,l,p,f,m,h,y,v)}roundClean(){i8e(p2,f2)}destroy(){this.destroyed=!0,i8e(this.buffer),this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0)}},e3r=class extends Q8r{Ah=Xs[0]|0;Al=Xs[1]|0;Bh=Xs[2]|0;Bl=Xs[3]|0;Ch=Xs[4]|0;Cl=Xs[5]|0;Dh=Xs[6]|0;Dl=Xs[7]|0;Eh=Xs[8]|0;El=Xs[9]|0;Fh=Xs[10]|0;Fl=Xs[11]|0;Gh=Xs[12]|0;Gl=Xs[13]|0;Hh=Xs[14]|0;Hl=Xs[15]|0;constructor(){super(64)}},t3r=L8r(()=>new e3r,H8r(3)),fpt=Vpt;fpt.sha512||(fpt.sha512=e=>t3r(e));a3r="ws://localhost:9001/ws",c3r=3e4,Ypt=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=Pk(e.name),e.keyPath)try{this._keypair=o3r(e.keyPath)}catch{}this.options={name:this._name,url:e.url??a3r,relay:e.relay??"",autoReconnect:e.autoReconnect??!0,reconnectInterval:e.reconnectInterval??1e3,maxReconnectAttempts:e.maxReconnectAttempts??10,rpcTimeout:e.rpcTimeout??c3r,pingInterval:e.pingInterval??3e4,binding:e.binding??""},this.transport=new _4r({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=m8r(new Uint8Array(t));r&&(this._keypair={privateKey:r,publicKey:s8r(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=mpt(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 Ys(String(n)))}})}disconnect(){for(let[,e]of this.pendingCalls)clearTimeout(e.timer),e.reject(new Ys("Client disconnected"));this.pendingCalls.clear();for(let[,e]of this.pendingSend)e.reject(new Ys("Client disconnected"));this.pendingSend.clear();for(let[,e]of this.pendingResolve)e.reject(new Ys("Client disconnected"));this.pendingResolve.clear(),this.registerPromise&&(this.registerPromise.reject(new Ys("Client disconnected")),this.registerPromise=null),this.transport.disconnect(),this._peerId=null,this.hasConnectedOnce=!1}async send(e,t,r,n){let i=Pk(e),o=$4e();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 Ys(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=Pk(e),o=$4e(),s=Date.now(),a=Math.floor(Math.random()*2**32),c=new TextEncoder().encode(r),{signature:u,signatureInput:d}=await s3r(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 Ys(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=Pk(e),o=n?.correlationId??$4e(),s=n?.timeout??this.options.rpcTimeout;return new Promise((a,c)=>{let u=setTimeout(()=>{this.pendingCalls.delete(o),c(new Tk(`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 Ys(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=Pk(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 Ys(String(i)))}setTimeout(()=>{this.pendingResolve.has(t)&&(this.pendingResolve.delete(t),n(new Tk(`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=H4e(e.code,e.message);this.registerPromise&&e.code==="register_failed"&&(this.registerPromise.reject(new KJ(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=mpt(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{}}};});function Rk(){return process.env.APPDATA||Qt.join(Ln,"AppData","Roaming")}function d3r(){return process.env.LOCALAPPDATA||Qt.join(Ln,"AppData","Local")}function p8e(e){return process.platform==="win32"?e.win32:e.posix}function Qpt(){if(process.platform!=="win32")return;let e=Qt.join(d3r(),"Packages");if(y2.existsSync(e))try{let t=y2.readdirSync(e,"utf-8");for(let r of u3r){let n=t.filter(i=>i.startsWith(r)).sort()[0];if(n)return Qt.join(e,n,"LocalCache","Roaming","Claude")}}catch{return}}function l3r(){if(process.platform==="win32"){let e=Qpt();return e?Qt.join(e,"claude_desktop_config.json"):Qt.join(Rk(),"Claude","claude_desktop_config.json")}return Qt.join(Ln,"Library","Application Support","Claude","claude_desktop_config.json")}function p3r(){if(process.platform!=="win32")return[Qt.join(Ln,"Library","Application Support","Claude")];let e=[Qt.join(Rk(),"Claude")],t=Qpt();return t&&e.push(t),e}var y2,Qt,Xpt,Ln,u3r,$4n,eft=I(()=>{"use strict";y2=qe(require("fs")),Qt=qe(require("path")),Xpt=qe(require("os")),Ln=Xpt.homedir(),u3r=["Claude_","Anthropic.ClaudeDesktop_"];$4n=[{id:"claude",displayName:"Claude Code",globalConfigPath:Qt.join(Ln,".claude.json"),configKey:"mcpServers",detectPaths:[Qt.join(Ln,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:l3r(),configKey:"mcpServers",detectPaths:p3r(),postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:Qt.join(Ln,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[Qt.join(Ln,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:Qt.join(Ln,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[Qt.join(Ln,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:Qt.join(Ln,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[Qt.join(Ln,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:p8e({win32:Qt.join(Rk(),"Roo","mcp_settings.json"),posix:Qt.join(Ln,".config","Roo","mcp_settings.json")}),configKey:"mcpServers",detectPaths:[Qt.join(Ln,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:Qt.join(Ln,".vscode","mcp.json"),configKey:"servers",detectPaths:[Qt.join(Ln,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:p8e({win32:Qt.join(Rk(),"Zed","settings.json"),posix:Qt.join(Ln,".config","zed","settings.json")}),configKey:"context_servers",detectPaths:p8e({win32:[Qt.join(Rk(),"Zed")],posix:[Qt.join(Ln,".config","zed")]}),postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})},{id:"codex",displayName:"Codex",globalConfigPath:Qt.join(Ln,".codex","config.toml"),configKey:"mcp_servers",configFormat:"toml",detectPaths:[Qt.join(Ln,".codex")],postInstallHint:"Restart Codex to connect."},{id:"openclaw",displayName:"OpenClaw",globalConfigPath:Qt.join(Ln,".openclaw","openclaw.json"),configKey:"mcp.servers",detectPaths:[Qt.join(Ln,".openclaw")],postInstallHint:"Restart OpenClaw (or reload its config) to connect."},{id:"hermes",displayName:"Hermes",globalConfigPath:Qt.join(Ln,".hermes","config.yaml"),configKey:"mcp_servers",configFormat:"yaml",detectPaths:[Qt.join(Ln,".hermes")],postInstallHint:"Restart Hermes to connect."}]});var tft=I(()=>{"use strict";eft()});var rft,nft,u8n,ift=I(()=>{"use strict";rft=qe(require("node:os")),nft=qe(require("node:path"));Uw();Dw();Qd();p4e();f8e();u8n=nft.join(rft.homedir(),".visa-cli","pairings")});function h3r(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.auth_url=="string"&&typeof t.created_at=="string"}function y3r(e=sft){return Kd.existsSync(e)?Kd.readdirSync(e).filter(t=>t.endsWith(".json")).map(t=>dY.join(e,t)):[]}function aft(e=sft){let t=y3r(e).sort((r,n)=>Kd.statSync(n).mtimeMs-Kd.statSync(r).mtimeMs)[0];if(!t)return null;try{let r=JSON.parse(Kd.readFileSync(t,"utf8"));return h3r(r)?r:null}catch{return null}}function cft(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}}var Kd,oft,dY,m3r,sft,f8e=I(()=>{"use strict";Kd=qe(require("fs")),oft=qe(require("os")),dY=qe(require("path")),m3r=require("node:readline/promises");Uw();Qd();xZ();nB();g4e();Dw();tft();ift();sft=dY.join(oft.homedir(),".visa-cli","agents")});var v8e={};Uo(v8e,{SUBWAY_PROTOCOL:()=>_ft,registerDirect:()=>C3r,resolveDirect:()=>O3r});function y8e(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 g8e(e,t){return e<<3|t}function kk(e,t,r){e.push(g8e(t,2)),y8e(e,r.length);for(let n of r)e.push(n)}function g3r(e,t){let r=[];return kk(r,1,h8e.encode(e)),t&&t.length>0&&kk(r,2,h8e.encode(t)),Uint8Array.from(r)}function b3r(e,t,r){let n=[];return r!==0n&&(n.push(g8e(1,0)),y8e(n,r)),kk(n,2,g3r(e,t)),Uint8Array.from(n)}function _3r(e){let t=[];return kk(t,1,h8e.encode(e)),Uint8Array.from(t)}function v3r(e,t){let r=[];return t!==0n&&(r.push(g8e(1,0)),y8e(r,t)),kk(r,3,_3r(e)),Uint8Array.from(r)}function w3r(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=gft.decode(e.subarray(u,d)),t=d}else t=b8e(e,t,s)}return r}function x3r(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=gft.decode(e.subarray(u,d)),t=d}else t=b8e(e,t,s)}return r}function b8e(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 bft(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=w3r(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=x3r(e.subarray(u,d)),t=d}else t=b8e(e,t,s)}return r}function E3r(e){let t=new Uint8Array(4+e.length);return new DataView(t.buffer).setUint32(0,e.length,!1),t.set(e,4),t}function _8e(e){return new DataView(e.buffer,e.byteOffset,4).getUint32(0,!1)}function A3r(e){if(e.length<4)return{success:!1,error:"short reply (no length prefix)"};let t=_8e(e.subarray(0,4));return e.length<4+t?{success:!1,error:`truncated frame (have ${e.length-4}, need ${t})`}:bft(e.subarray(4,4+t)).registerNameResponse??{success:!1,error:"reply carried no register_name_response"}}function S3r(e){if(e.length<4)return{peerId:new Uint8Array(0),error:"short reply (no length prefix)"};let t=_8e(e.subarray(0,4));return e.length<4+t?{peerId:new Uint8Array(0),error:`truncated frame (have ${e.length-4}, need ${t})`}:bft(e.subarray(4,4+t)).resolveNameResponse??{peerId:new Uint8Array(0),error:"reply carried no resolve_name_response"}}function m8e(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 I3r(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>uft)throw new Error("subway: reply exceeded max size");if(n<0&&r>=4&&(n=4+_8e(m8e(t).subarray(0,4)),n>uft))throw new Error("subway: declared frame exceeds max size");if(n>=0&&r>=n)return m8e(t).subarray(0,n)}return m8e(t)}async function vft(e){return(0,dft.createLibp2p)({...e?{privateKey:await(0,mft.generateKeyPairFromSeed)("Ed25519",e)}:{},transports:[(0,lft.tcp)()],connectionEncrypters:[(0,pft.noise)()],streamMuxers:[(0,fft.yamux)()],connectionGater:{denyDialMultiaddr:async()=>!1}})}async function wft(e,t,r){let n=await e.dialProtocol((0,hft.multiaddr)(t),_ft,{signal:AbortSignal.timeout(T3r)});n.send(E3r(r));let i;return Promise.race([I3r(n),new Promise((o,s)=>{i=setTimeout(()=>s(new Error("subway: request timed out")),P3r)})]).finally(()=>clearTimeout(i))}async function C3r(e){let t=await vft(e.seed);try{let r=await wft(t,e.relayMultiaddr,b3r(e.name,e.binding,e.requestId??1n)),n=A3r(r);return{success:n.success,error:n.error,peerId:t.peerId.toString()}}finally{await t.stop()}}async function O3r(e){let t=await vft(e.seed);try{let r=await wft(t,e.relayMultiaddr,v3r(e.name,e.requestId??1n)),n=S3r(r);return n.peerId.length===0?{found:!1,peerId:"",error:n.error||"name not found"}:{found:!0,peerId:(0,yft.toString)(n.peerId,"base58btc"),error:""}}finally{await t.stop()}}var dft,lft,pft,fft,mft,hft,yft,h8e,gft,_ft,T3r,P3r,uft,w8e=I(()=>{"use strict";F4e();dft=require("libp2p"),lft=require("@libp2p/tcp"),pft=require("@chainsafe/libp2p-noise"),fft=require("@chainsafe/libp2p-yamux"),mft=require("@libp2p/crypto/keys"),hft=require("@multiformats/multiaddr"),yft=require("uint8arrays/to-string"),h8e=new TextEncoder,gft=new TextDecoder;_ft="/subway/p2p/1.0.0",T3r=15e3,P3r=15e3,uft=1<<20});var Nk={};Uo(Nk,{DEFAULT_VISA_RELAY_MULTIADDR:()=>Eft,MESH:()=>gs,RELAY_URL:()=>P8e,connectOrThrow:()=>mY,ensureMailbox:()=>k8e,isSubwayEnabled:()=>I8e,listRegistered:()=>q3r,loadBindingFor:()=>R8e,loadRegistry:()=>dw,makeClient:()=>fY,maybeMintVisaBinding:()=>Sft,meshName:()=>yp,pairedVisaBinding:()=>Tft,readInbox:()=>M3r,registerName:()=>B3r,resolveActingName:()=>k3r,resolveMeshName:()=>N3r,seedSubwayKeyFromTapAgent:()=>Aft,sendMessage:()=>j3r,sendVia:()=>D3r,subwayKeyPath:()=>pY,visaRelayMultiaddr:()=>T8e});function T8e(e=process.env){return e.SUBWAY_RELAY_MULTIADDR??Eft}function yp(e){return e.includes(".")?e:`${e}.${gs}`}function I8e(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 O8e(){so.mkdirSync(C8e,{recursive:!0,mode:448})}function R3r(e){return e.replace(/[^a-zA-Z0-9_.-]/g,"_")}function pY(e){return CA.join(C8e,`${R3r(e)}.key`)}function dw(){if(!so.existsSync(S8e))return{};try{return JSON.parse(so.readFileSync(S8e,"utf8"))}catch{return{}}}function E8e(e){O8e(),so.writeFileSync(S8e,JSON.stringify(e,null,2),{mode:384})}function A8e(){try{return Bk.userInfo().username}catch{return"local"}}function Aft(e){if(so.existsSync(e)||!so.existsSync(x8e))return null;let t=so.readdirSync(x8e).filter(n=>n.endsWith(".json"));if(t.length===0)return null;let r=t.map(n=>CA.join(x8e,n)).sort((n,i)=>so.statSync(i).mtimeMs-so.statSync(n).mtimeMs)[0];try{let n=JSON.parse(so.readFileSync(r,"utf8"));if(!n.private_key_jwk)return null;let i=DZ(n.private_key_jwk);return O8e(),so.writeFileSync(e,Buffer.from(i),{mode:384}),n.agent_id??null}catch{return null}}function fY(e,t={}){return new Ypt({name:yp(e),url:P8e,keyPath:pY(e),autoReconnect:t.autoReconnect??!1,binding:t.binding})}function R8e(e){if(gs!=="visa")return;let t=dw()[e];if(t?.binding&&!(t.bindingExpiresAt&&Date.parse(t.bindingExpiresAt)<=Date.now()))return t.binding}async function mY(e,t=15e3){await Promise.race([e.connect(),new Promise((r,n)=>setTimeout(()=>n(new Error(`Subway relay connect timed out after ${t}ms (${P8e})`)),t))])}function k3r(e){if(e)return e;let t=Object.keys(dw());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 Sft(e){if(gs!=="visa")return null;let t=process.env.VISA_CLI_API_KEY?.trim();if(!t)throw new vh("No Visa Key configured \u2014 set VISA_CLI_API_KEY (a Visa Key with a card on file) to register on the trusted .visa mesh.",NB(ta()),"no_key");try{return await jB({authUrl:ta(),apiKey:t,seed:qB(pY(e)),name:yp(e)})}catch(r){if(r instanceof vh)throw r;return console.warn(`[subway] Visa binding not minted: ${r instanceof Error?r.message:String(r)}`),null}}function Tft(e=Date.now()){let t=aft();if(!t?.binding_jwt)return null;let r=cft(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 B3r(e){let t=pY(e),r=Aft(t),n=yp(e);gs==="visa"&&!so.existsSync(t)&&(O8e(),so.writeFileSync(t,(0,xft.randomBytes)(32),{mode:384}));let i=gs==="visa"?Tft():null,o,s={};if(i)o=i.binding,s={binding:i.binding,bindingExpiresAt:i.bindingExpiresAt};else{let u=await Sft(e);u&&(o=u.binding,s={binding:u.binding,bindingExpiresAt:new Date(Date.now()+u.expires_in*1e3).toISOString()})}let a=gs==="visa"?T8e():process.env.SUBWAY_RELAY_MULTIADDR;if(gs==="visa"&&a){let{registerDirect:u}=await Promise.resolve().then(()=>(w8e(),v8e)),d=await u({relayMultiaddr:a,seed:qB(t),name:n,binding:o});if(!d.success)throw new Error(`.visa relay admission failed: ${d.error||"unknown"}`);let l=dw();return l[e]={relayName:n,mesh:gs,peerId:d.peerId,owner:A8e(),tapAgentId:r,registeredAt:new Date().toISOString(),...s},E8e(l),{relayName:n,mesh:gs,peerId:d.peerId,tapAgentId:r,...o?{binding:o}:{}}}if(gs==="visa"&&!process.env.SUBWAY_RELAY){let u=dw();return u[e]={relayName:n,mesh:gs,peerId:null,owner:A8e(),tapAgentId:r,registeredAt:new Date().toISOString(),...s},E8e(u),{relayName:n,mesh:gs,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=fY(e,{autoReconnect:!1,binding:o});try{await mY(c);let u=dw();return u[e]={relayName:n,mesh:gs,peerId:c.peerId,owner:A8e(),tapAgentId:r,registeredAt:new Date().toISOString(),...s},E8e(u),{relayName:n,mesh:gs,peerId:c.peerId,tapAgentId:r,...o?{binding:o}:{}}}finally{c.disconnect()}}async function N3r(e){let t=yp(e),r=gs==="visa"?T8e():process.env.SUBWAY_RELAY_MULTIADDR;if(gs==="visa"&&r){let{resolveDirect:n}=await Promise.resolve().then(()=>(w8e(),v8e)),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 j3r(e,t,r){let n=fY(e,{autoReconnect:!1,binding:R8e(e)});try{await mY(n);let i=yp(t);return await n.sendSigned(i,"chat",r),{to:i,as:yp(e)}}finally{n.disconnect()}}function q3r(){let e=dw();return Object.entries(e).map(([t,r])=>({name:t,...r}))}async function k8e(e){let t=lY.get(e);if(t)return{relayName:yp(e),peerId:t.client.peerId};let r=fY(e,{autoReconnect:!0,binding:R8e(e)}),n=[];return r.onMessage(i=>{n.push({from:i.fromName,text:i.payload,ts:i.timestampMs,verified:!!i.verified}),n.length>U3r&&n.shift()}),lY.set(e,{client:r,buffer:n}),await mY(r),{relayName:yp(e),peerId:r.peerId}}async function M3r(e,t=20,r=!1){await k8e(e);let n=lY.get(e);if(!n)return[];let i=n.buffer.slice(-t);return r&&(n.buffer.length=0),i}async function D3r(e,t,r){await k8e(e);let n=lY.get(e);if(!n)throw new Error(`mailbox for ${e} unavailable`);let i=yp(t);return await n.client.sendSigned(i,"chat",r),{to:i,as:yp(e)}}var so,Bk,CA,xft,gs,Eft,P8e,C8e,S8e,x8e,lY,U3r,OA=I(()=>{"use strict";Zpt();Uw();so=qe(require("fs")),Bk=qe(require("os")),CA=qe(require("path")),xft=require("crypto");Qd();Dw();f8e();gs=process.env.SUBWAY_MESH??"relay",Eft="/dns4/subway-relay-visa.fly.dev/tcp/9100/p2p/12D3KooWM2q6SXgKFxj5wvnJ7gTD4XPjhvc5tHVVjDBrZRnJ3CKU";P8e=process.env.SUBWAY_RELAY??"wss://relay.subway.dev/ws";C8e=CA.join(Bk.homedir(),".visa-cli","subway"),S8e=CA.join(C8e,"registry.json"),x8e=CA.join(Bk.homedir(),".visa-cli","agents");lY=new Map,U3r=200});var CY={};Uo(CY,{initSentry:()=>AEr,isSentryConfigured:()=>EEr,reportFatal:()=>SEr});function EEr(){return!1}async function AEr(){return null}async function SEr(e,t){process.exit(t?.exitCode??1)}var OY=I(()=>{});var Hmt=require("@modelcontextprotocol/sdk/server/index.js"),zmt=require("@modelcontextprotocol/sdk/server/stdio.js"),Rm=require("@modelcontextprotocol/sdk/types.js");var ye={};Uo(ye,{BRAND:()=>O0t,DIRTY:()=>_2,EMPTY_PATH:()=>c0t,INVALID:()=>ft,NEVER:()=>m1t,OK:()=>bs,ParseStatus:()=>Mo,Schema:()=>Bt,ZodAny:()=>uh,ZodArray:()=>jm,ZodBigInt:()=>w2,ZodBoolean:()=>x2,ZodBranded:()=>UA,ZodCatch:()=>B2,ZodDate:()=>E2,ZodDefault:()=>k2,ZodDiscriminatedUnion:()=>Jk,ZodEffects:()=>ju,ZodEnum:()=>O2,ZodError:()=>Ua,ZodFirstPartyTypeKind:()=>_t,ZodFunction:()=>Zk,ZodIntersection:()=>P2,ZodIssueCode:()=>me,ZodLazy:()=>I2,ZodLiteral:()=>C2,ZodMap:()=>Sw,ZodNaN:()=>Pw,ZodNativeEnum:()=>R2,ZodNever:()=>Xd,ZodNull:()=>S2,ZodNullable:()=>xp,ZodNumber:()=>v2,ZodObject:()=>Ma,ZodOptional:()=>Bu,ZodParsedType:()=>Ce,ZodPipeline:()=>MA,ZodPromise:()=>dh,ZodReadonly:()=>N2,ZodRecord:()=>Yk,ZodSchema:()=>Bt,ZodSet:()=>Tw,ZodString:()=>ch,ZodSymbol:()=>Ew,ZodTransformer:()=>ju,ZodTuple:()=>wp,ZodType:()=>Bt,ZodUndefined:()=>A2,ZodUnion:()=>T2,ZodUnknown:()=>Nm,ZodVoid:()=>Aw,addIssueToContext:()=>Ee,any:()=>D0t,array:()=>F0t,bigint:()=>N0t,boolean:()=>l3e,coerce:()=>f1t,custom:()=>c3e,date:()=>j0t,datetimeRegex:()=>s3e,defaultErrorMap:()=>km,discriminatedUnion:()=>W0t,effect:()=>o1t,enum:()=>r1t,function:()=>Q0t,getErrorMap:()=>vw,getParsedType:()=>vp,instanceof:()=>k0t,intersection:()=>G0t,isAborted:()=>Wk,isAsync:()=>ww,isDirty:()=>Gk,isValid:()=>ah,late:()=>R0t,lazy:()=>e1t,literal:()=>t1t,makeIssue:()=>qA,map:()=>Z0t,nan:()=>B0t,nativeEnum:()=>n1t,never:()=>H0t,null:()=>M0t,nullable:()=>a1t,number:()=>d3e,object:()=>$0t,objectUtil:()=>BY,oboolean:()=>p1t,onumber:()=>l1t,optional:()=>s1t,ostring:()=>d1t,pipeline:()=>u1t,preprocess:()=>c1t,promise:()=>i1t,quotelessJson:()=>o0t,record:()=>Y0t,set:()=>X0t,setErrorMap:()=>a0t,strictObject:()=>V0t,string:()=>u3e,symbol:()=>q0t,transformer:()=>o1t,tuple:()=>J0t,undefined:()=>U0t,union:()=>K0t,unknown:()=>L0t,util:()=>Ft,void:()=>z0t});var Ft;(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})(Ft||(Ft={}));var BY;(function(e){e.mergeShapes=(t,r)=>({...t,...r})})(BY||(BY={}));var Ce=Ft.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),vp=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 me=Ft.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"]),o0t=e=>JSON.stringify(e,null,2).replace(/"([^"]+)":/g,"$1:"),Ua=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,Ft.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()}};Ua.create=e=>new Ua(e);var s0t=(e,t)=>{let r;switch(e.code){case me.invalid_type:e.received===Ce.undefined?r="Required":r=`Expected ${e.expected}, received ${e.received}`;break;case me.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(e.expected,Ft.jsonStringifyReplacer)}`;break;case me.unrecognized_keys:r=`Unrecognized key(s) in object: ${Ft.joinValues(e.keys,", ")}`;break;case me.invalid_union:r="Invalid input";break;case me.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${Ft.joinValues(e.options)}`;break;case me.invalid_enum_value:r=`Invalid enum value. Expected ${Ft.joinValues(e.options)}, received '${e.received}'`;break;case me.invalid_arguments:r="Invalid function arguments";break;case me.invalid_return_type:r="Invalid function return type";break;case me.invalid_date:r="Invalid date";break;case me.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}"`:Ft.assertNever(e.validation):e.validation!=="regex"?r=`Invalid ${e.validation}`:r="Invalid";break;case me.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 me.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 me.custom:r="Invalid input";break;case me.invalid_intersection_types:r="Intersection results could not be merged";break;case me.not_multiple_of:r=`Number must be a multiple of ${e.multipleOf}`;break;case me.not_finite:r="Number must be finite";break;default:r=t.defaultError,Ft.assertNever(e)}return{message:r}},km=s0t;var t3e=km;function a0t(e){t3e=e}function vw(){return t3e}var qA=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}},c0t=[];function Ee(e,t){let r=vw(),n=qA({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,r,r===km?void 0:km].filter(i=>!!i)});e.common.issues.push(n)}var Mo=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 ft;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 ft;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}}},ft=Object.freeze({status:"aborted"}),_2=e=>({status:"dirty",value:e}),bs=e=>({status:"valid",value:e}),Wk=e=>e.status==="aborted",Gk=e=>e.status==="dirty",ah=e=>e.status==="valid",ww=e=>typeof Promise<"u"&&e instanceof Promise;var Ye;(function(e){e.errToObj=t=>typeof t=="string"?{message:t}:t||{},e.toString=t=>typeof t=="string"?t:t?.message})(Ye||(Ye={}));var Nu=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}},r3e=(e,t)=>{if(ah(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 Ua(e.common.issues);return this._error=r,this._error}}};function Ot(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 Bt=class{get description(){return this._def.description}_getType(t){return vp(t.data)}_getOrReturnCtx(t,r){return r||{common:t.parent.common,data:t.data,parsedType:vp(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}_processInputParams(t){return{status:new Mo,ctx:{common:t.parent.common,data:t.data,parsedType:vp(t.data),schemaErrorMap:this._def.errorMap,path:t.path,parent:t.parent}}}_parseSync(t){let r=this._parse(t);if(ww(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:vp(t)},i=this._parseSync({data:t,path:n.path,parent:n});return r3e(n,i)}"~validate"(t){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:t,parsedType:vp(t)};if(!this["~standard"].async)try{let n=this._parseSync({data:t,path:[],parent:r});return ah(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=>ah(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:vp(t)},i=this._parse({data:t,path:n.path,parent:n}),o=await(ww(i)?i:Promise.resolve(i));return r3e(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:me.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 ju({schema:this,typeName:_t.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 Bu.create(this,this._def)}nullable(){return xp.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return jm.create(this)}promise(){return dh.create(this,this._def)}or(t){return T2.create([this,t],this._def)}and(t){return P2.create(this,t,this._def)}transform(t){return new ju({...Ot(this._def),schema:this,typeName:_t.ZodEffects,effect:{type:"transform",transform:t}})}default(t){let r=typeof t=="function"?t:()=>t;return new k2({...Ot(this._def),innerType:this,defaultValue:r,typeName:_t.ZodDefault})}brand(){return new UA({typeName:_t.ZodBranded,type:this,...Ot(this._def)})}catch(t){let r=typeof t=="function"?t:()=>t;return new B2({...Ot(this._def),innerType:this,catchValue:r,typeName:_t.ZodCatch})}describe(t){let r=this.constructor;return new r({...this._def,description:t})}pipe(t){return MA.create(this,t)}readonly(){return N2.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},u0t=/^c[^\s-]{8,}$/i,d0t=/^[0-9a-z]+$/,l0t=/^[0-9A-HJKMNP-TV-Z]{26}$/i,p0t=/^[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,f0t=/^[a-z0-9_-]{21}$/i,m0t=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,h0t=/^[-+]?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)?)??$/,y0t=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,g0t="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",NY,b0t=/^(?:(?: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])$/,_0t=/^(?:(?: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])$/,v0t=/^(([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]))$/,w0t=/^(([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])$/,x0t=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,E0t=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,i3e="((\\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])))",A0t=new RegExp(`^${i3e}$`);function o3e(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 S0t(e){return new RegExp(`^${o3e(e)}$`)}function s3e(e){let t=`${i3e}T${o3e(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 T0t(e,t){return!!((t==="v4"||!t)&&b0t.test(e)||(t==="v6"||!t)&&v0t.test(e))}function P0t(e,t){if(!m0t.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 I0t(e,t){return!!((t==="v4"||!t)&&_0t.test(e)||(t==="v6"||!t)&&w0t.test(e))}var ch=class e extends Bt{_parse(t){if(this._def.coerce&&(t.data=String(t.data)),this._getType(t)!==Ce.string){let o=this._getOrReturnCtx(t);return Ee(o,{code:me.invalid_type,expected:Ce.string,received:o.parsedType}),ft}let n=new Mo,i;for(let o of this._def.checks)if(o.kind==="min")t.data.length<o.value&&(i=this._getOrReturnCtx(t,i),Ee(i,{code:me.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),Ee(i,{code:me.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?Ee(i,{code:me.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}):a&&Ee(i,{code:me.too_small,minimum:o.value,type:"string",inclusive:!0,exact:!0,message:o.message}),n.dirty())}else if(o.kind==="email")y0t.test(t.data)||(i=this._getOrReturnCtx(t,i),Ee(i,{validation:"email",code:me.invalid_string,message:o.message}),n.dirty());else if(o.kind==="emoji")NY||(NY=new RegExp(g0t,"u")),NY.test(t.data)||(i=this._getOrReturnCtx(t,i),Ee(i,{validation:"emoji",code:me.invalid_string,message:o.message}),n.dirty());else if(o.kind==="uuid")p0t.test(t.data)||(i=this._getOrReturnCtx(t,i),Ee(i,{validation:"uuid",code:me.invalid_string,message:o.message}),n.dirty());else if(o.kind==="nanoid")f0t.test(t.data)||(i=this._getOrReturnCtx(t,i),Ee(i,{validation:"nanoid",code:me.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid")u0t.test(t.data)||(i=this._getOrReturnCtx(t,i),Ee(i,{validation:"cuid",code:me.invalid_string,message:o.message}),n.dirty());else if(o.kind==="cuid2")d0t.test(t.data)||(i=this._getOrReturnCtx(t,i),Ee(i,{validation:"cuid2",code:me.invalid_string,message:o.message}),n.dirty());else if(o.kind==="ulid")l0t.test(t.data)||(i=this._getOrReturnCtx(t,i),Ee(i,{validation:"ulid",code:me.invalid_string,message:o.message}),n.dirty());else if(o.kind==="url")try{new URL(t.data)}catch{i=this._getOrReturnCtx(t,i),Ee(i,{validation:"url",code:me.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),Ee(i,{validation:"regex",code:me.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),Ee(i,{code:me.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),Ee(i,{code:me.invalid_string,validation:{startsWith:o.value},message:o.message}),n.dirty()):o.kind==="endsWith"?t.data.endsWith(o.value)||(i=this._getOrReturnCtx(t,i),Ee(i,{code:me.invalid_string,validation:{endsWith:o.value},message:o.message}),n.dirty()):o.kind==="datetime"?s3e(o).test(t.data)||(i=this._getOrReturnCtx(t,i),Ee(i,{code:me.invalid_string,validation:"datetime",message:o.message}),n.dirty()):o.kind==="date"?A0t.test(t.data)||(i=this._getOrReturnCtx(t,i),Ee(i,{code:me.invalid_string,validation:"date",message:o.message}),n.dirty()):o.kind==="time"?S0t(o).test(t.data)||(i=this._getOrReturnCtx(t,i),Ee(i,{code:me.invalid_string,validation:"time",message:o.message}),n.dirty()):o.kind==="duration"?h0t.test(t.data)||(i=this._getOrReturnCtx(t,i),Ee(i,{validation:"duration",code:me.invalid_string,message:o.message}),n.dirty()):o.kind==="ip"?T0t(t.data,o.version)||(i=this._getOrReturnCtx(t,i),Ee(i,{validation:"ip",code:me.invalid_string,message:o.message}),n.dirty()):o.kind==="jwt"?P0t(t.data,o.alg)||(i=this._getOrReturnCtx(t,i),Ee(i,{validation:"jwt",code:me.invalid_string,message:o.message}),n.dirty()):o.kind==="cidr"?I0t(t.data,o.version)||(i=this._getOrReturnCtx(t,i),Ee(i,{validation:"cidr",code:me.invalid_string,message:o.message}),n.dirty()):o.kind==="base64"?x0t.test(t.data)||(i=this._getOrReturnCtx(t,i),Ee(i,{validation:"base64",code:me.invalid_string,message:o.message}),n.dirty()):o.kind==="base64url"?E0t.test(t.data)||(i=this._getOrReturnCtx(t,i),Ee(i,{validation:"base64url",code:me.invalid_string,message:o.message}),n.dirty()):Ft.assertNever(o);return{status:n.value,value:t.data}}_regex(t,r,n){return this.refinement(i=>t.test(i),{validation:r,code:me.invalid_string,...Ye.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(t){return this._addCheck({kind:"email",...Ye.errToObj(t)})}url(t){return this._addCheck({kind:"url",...Ye.errToObj(t)})}emoji(t){return this._addCheck({kind:"emoji",...Ye.errToObj(t)})}uuid(t){return this._addCheck({kind:"uuid",...Ye.errToObj(t)})}nanoid(t){return this._addCheck({kind:"nanoid",...Ye.errToObj(t)})}cuid(t){return this._addCheck({kind:"cuid",...Ye.errToObj(t)})}cuid2(t){return this._addCheck({kind:"cuid2",...Ye.errToObj(t)})}ulid(t){return this._addCheck({kind:"ulid",...Ye.errToObj(t)})}base64(t){return this._addCheck({kind:"base64",...Ye.errToObj(t)})}base64url(t){return this._addCheck({kind:"base64url",...Ye.errToObj(t)})}jwt(t){return this._addCheck({kind:"jwt",...Ye.errToObj(t)})}ip(t){return this._addCheck({kind:"ip",...Ye.errToObj(t)})}cidr(t){return this._addCheck({kind:"cidr",...Ye.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,...Ye.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,...Ye.errToObj(t?.message)})}duration(t){return this._addCheck({kind:"duration",...Ye.errToObj(t)})}regex(t,r){return this._addCheck({kind:"regex",regex:t,...Ye.errToObj(r)})}includes(t,r){return this._addCheck({kind:"includes",value:t,position:r?.position,...Ye.errToObj(r?.message)})}startsWith(t,r){return this._addCheck({kind:"startsWith",value:t,...Ye.errToObj(r)})}endsWith(t,r){return this._addCheck({kind:"endsWith",value:t,...Ye.errToObj(r)})}min(t,r){return this._addCheck({kind:"min",value:t,...Ye.errToObj(r)})}max(t,r){return this._addCheck({kind:"max",value:t,...Ye.errToObj(r)})}length(t,r){return this._addCheck({kind:"length",value:t,...Ye.errToObj(r)})}nonempty(t){return this.min(1,Ye.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}};ch.create=e=>new ch({checks:[],typeName:_t.ZodString,coerce:e?.coerce??!1,...Ot(e)});function C0t(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 v2=class e extends Bt{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 Ee(o,{code:me.invalid_type,expected:Ce.number,received:o.parsedType}),ft}let n,i=new Mo;for(let o of this._def.checks)o.kind==="int"?Ft.isInteger(t.data)||(n=this._getOrReturnCtx(t,n),Ee(n,{code:me.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),Ee(n,{code:me.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),Ee(n,{code:me.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?C0t(t.data,o.value)!==0&&(n=this._getOrReturnCtx(t,n),Ee(n,{code:me.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(t.data)||(n=this._getOrReturnCtx(t,n),Ee(n,{code:me.not_finite,message:o.message}),i.dirty()):Ft.assertNever(o);return{status:i.value,value:t.data}}gte(t,r){return this.setLimit("min",t,!0,Ye.toString(r))}gt(t,r){return this.setLimit("min",t,!1,Ye.toString(r))}lte(t,r){return this.setLimit("max",t,!0,Ye.toString(r))}lt(t,r){return this.setLimit("max",t,!1,Ye.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:Ye.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(t){return this._addCheck({kind:"int",message:Ye.toString(t)})}positive(t){return this._addCheck({kind:"min",value:0,inclusive:!1,message:Ye.toString(t)})}negative(t){return this._addCheck({kind:"max",value:0,inclusive:!1,message:Ye.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:0,inclusive:!0,message:Ye.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:0,inclusive:!0,message:Ye.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:Ye.toString(r)})}finite(t){return this._addCheck({kind:"finite",message:Ye.toString(t)})}safe(t){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:Ye.toString(t)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:Ye.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"&&Ft.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)}};v2.create=e=>new v2({checks:[],typeName:_t.ZodNumber,coerce:e?.coerce||!1,...Ot(e)});var w2=class e extends Bt{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 Mo;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),Ee(n,{code:me.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),Ee(n,{code:me.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),Ee(n,{code:me.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):Ft.assertNever(o);return{status:i.value,value:t.data}}_getInvalidInput(t){let r=this._getOrReturnCtx(t);return Ee(r,{code:me.invalid_type,expected:Ce.bigint,received:r.parsedType}),ft}gte(t,r){return this.setLimit("min",t,!0,Ye.toString(r))}gt(t,r){return this.setLimit("min",t,!1,Ye.toString(r))}lte(t,r){return this.setLimit("max",t,!0,Ye.toString(r))}lt(t,r){return this.setLimit("max",t,!1,Ye.toString(r))}setLimit(t,r,n,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:r,inclusive:n,message:Ye.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:Ye.toString(t)})}negative(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:Ye.toString(t)})}nonpositive(t){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:Ye.toString(t)})}nonnegative(t){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:Ye.toString(t)})}multipleOf(t,r){return this._addCheck({kind:"multipleOf",value:t,message:Ye.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}};w2.create=e=>new w2({checks:[],typeName:_t.ZodBigInt,coerce:e?.coerce??!1,...Ot(e)});var x2=class extends Bt{_parse(t){if(this._def.coerce&&(t.data=!!t.data),this._getType(t)!==Ce.boolean){let n=this._getOrReturnCtx(t);return Ee(n,{code:me.invalid_type,expected:Ce.boolean,received:n.parsedType}),ft}return bs(t.data)}};x2.create=e=>new x2({typeName:_t.ZodBoolean,coerce:e?.coerce||!1,...Ot(e)});var E2=class e extends Bt{_parse(t){if(this._def.coerce&&(t.data=new Date(t.data)),this._getType(t)!==Ce.date){let o=this._getOrReturnCtx(t);return Ee(o,{code:me.invalid_type,expected:Ce.date,received:o.parsedType}),ft}if(Number.isNaN(t.data.getTime())){let o=this._getOrReturnCtx(t);return Ee(o,{code:me.invalid_date}),ft}let n=new Mo,i;for(let o of this._def.checks)o.kind==="min"?t.data.getTime()<o.value&&(i=this._getOrReturnCtx(t,i),Ee(i,{code:me.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),Ee(i,{code:me.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):Ft.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:Ye.toString(r)})}max(t,r){return this._addCheck({kind:"max",value:t.getTime(),message:Ye.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}};E2.create=e=>new E2({checks:[],coerce:e?.coerce||!1,typeName:_t.ZodDate,...Ot(e)});var Ew=class extends Bt{_parse(t){if(this._getType(t)!==Ce.symbol){let n=this._getOrReturnCtx(t);return Ee(n,{code:me.invalid_type,expected:Ce.symbol,received:n.parsedType}),ft}return bs(t.data)}};Ew.create=e=>new Ew({typeName:_t.ZodSymbol,...Ot(e)});var A2=class extends Bt{_parse(t){if(this._getType(t)!==Ce.undefined){let n=this._getOrReturnCtx(t);return Ee(n,{code:me.invalid_type,expected:Ce.undefined,received:n.parsedType}),ft}return bs(t.data)}};A2.create=e=>new A2({typeName:_t.ZodUndefined,...Ot(e)});var S2=class extends Bt{_parse(t){if(this._getType(t)!==Ce.null){let n=this._getOrReturnCtx(t);return Ee(n,{code:me.invalid_type,expected:Ce.null,received:n.parsedType}),ft}return bs(t.data)}};S2.create=e=>new S2({typeName:_t.ZodNull,...Ot(e)});var uh=class extends Bt{constructor(){super(...arguments),this._any=!0}_parse(t){return bs(t.data)}};uh.create=e=>new uh({typeName:_t.ZodAny,...Ot(e)});var Nm=class extends Bt{constructor(){super(...arguments),this._unknown=!0}_parse(t){return bs(t.data)}};Nm.create=e=>new Nm({typeName:_t.ZodUnknown,...Ot(e)});var Xd=class extends Bt{_parse(t){let r=this._getOrReturnCtx(t);return Ee(r,{code:me.invalid_type,expected:Ce.never,received:r.parsedType}),ft}};Xd.create=e=>new Xd({typeName:_t.ZodNever,...Ot(e)});var Aw=class extends Bt{_parse(t){if(this._getType(t)!==Ce.undefined){let n=this._getOrReturnCtx(t);return Ee(n,{code:me.invalid_type,expected:Ce.void,received:n.parsedType}),ft}return bs(t.data)}};Aw.create=e=>new Aw({typeName:_t.ZodVoid,...Ot(e)});var jm=class e extends Bt{_parse(t){let{ctx:r,status:n}=this._processInputParams(t),i=this._def;if(r.parsedType!==Ce.array)return Ee(r,{code:me.invalid_type,expected:Ce.array,received:r.parsedType}),ft;if(i.exactLength!==null){let s=r.data.length>i.exactLength.value,a=r.data.length<i.exactLength.value;(s||a)&&(Ee(r,{code:s?me.too_big:me.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&&(Ee(r,{code:me.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&&(Ee(r,{code:me.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 Nu(r,s,r.path,a)))).then(s=>Mo.mergeArray(n,s));let o=[...r.data].map((s,a)=>i.type._parseSync(new Nu(r,s,r.path,a)));return Mo.mergeArray(n,o)}get element(){return this._def.type}min(t,r){return new e({...this._def,minLength:{value:t,message:Ye.toString(r)}})}max(t,r){return new e({...this._def,maxLength:{value:t,message:Ye.toString(r)}})}length(t,r){return new e({...this._def,exactLength:{value:t,message:Ye.toString(r)}})}nonempty(t){return this.min(1,t)}};jm.create=(e,t)=>new jm({type:e,minLength:null,maxLength:null,exactLength:null,typeName:_t.ZodArray,...Ot(t)});function xw(e){if(e instanceof Ma){let t={};for(let r in e.shape){let n=e.shape[r];t[r]=Bu.create(xw(n))}return new Ma({...e._def,shape:()=>t})}else return e instanceof jm?new jm({...e._def,type:xw(e.element)}):e instanceof Bu?Bu.create(xw(e.unwrap())):e instanceof xp?xp.create(xw(e.unwrap())):e instanceof wp?wp.create(e.items.map(t=>xw(t))):e}var Ma=class e extends Bt{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=Ft.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 Ee(u,{code:me.invalid_type,expected:Ce.object,received:u.parsedType}),ft}let{status:n,ctx:i}=this._processInputParams(t),{shape:o,keys:s}=this._getCached(),a=[];if(!(this._def.catchall instanceof Xd&&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 Nu(i,l,i.path,u)),alwaysSet:u in i.data})}if(this._def.catchall instanceof Xd){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&&(Ee(i,{code:me.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 Nu(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=>Mo.mergeObjectSync(n,u)):Mo.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(t){return Ye.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:Ye.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:_t.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 Ft.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 Ft.objectKeys(this.shape))t[n]||(r[n]=this.shape[n]);return new e({...this._def,shape:()=>r})}deepPartial(){return xw(this)}partial(t){let r={};for(let n of Ft.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 Ft.objectKeys(this.shape))if(t&&!t[n])r[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof Bu;)o=o._def.innerType;r[n]=o}return new e({...this._def,shape:()=>r})}keyof(){return a3e(Ft.objectKeys(this.shape))}};Ma.create=(e,t)=>new Ma({shape:()=>e,unknownKeys:"strip",catchall:Xd.create(),typeName:_t.ZodObject,...Ot(t)});Ma.strictCreate=(e,t)=>new Ma({shape:()=>e,unknownKeys:"strict",catchall:Xd.create(),typeName:_t.ZodObject,...Ot(t)});Ma.lazycreate=(e,t)=>new Ma({shape:e,unknownKeys:"strip",catchall:Xd.create(),typeName:_t.ZodObject,...Ot(t)});var T2=class extends Bt{_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 Ua(a.ctx.common.issues));return Ee(r,{code:me.invalid_union,unionErrors:s}),ft}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 Ua(c));return Ee(r,{code:me.invalid_union,unionErrors:a}),ft}}get options(){return this._def.options}};T2.create=(e,t)=>new T2({options:e,typeName:_t.ZodUnion,...Ot(t)});var Bm=e=>e instanceof I2?Bm(e.schema):e instanceof ju?Bm(e.innerType()):e instanceof C2?[e.value]:e instanceof O2?e.options:e instanceof R2?Ft.objectValues(e.enum):e instanceof k2?Bm(e._def.innerType):e instanceof A2?[void 0]:e instanceof S2?[null]:e instanceof Bu?[void 0,...Bm(e.unwrap())]:e instanceof xp?[null,...Bm(e.unwrap())]:e instanceof UA||e instanceof N2?Bm(e.unwrap()):e instanceof B2?Bm(e._def.innerType):[],Jk=class e extends Bt{_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Ce.object)return Ee(r,{code:me.invalid_type,expected:Ce.object,received:r.parsedType}),ft;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}):(Ee(r,{code:me.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),ft)}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=Bm(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:_t.ZodDiscriminatedUnion,discriminator:t,options:r,optionsMap:i,...Ot(n)})}};function jY(e,t){let r=vp(e),n=vp(t);if(e===t)return{valid:!0,data:e};if(r===Ce.object&&n===Ce.object){let i=Ft.objectKeys(t),o=Ft.objectKeys(e).filter(a=>i.indexOf(a)!==-1),s={...e,...t};for(let a of o){let c=jY(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=jY(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 P2=class extends Bt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t),i=(o,s)=>{if(Wk(o)||Wk(s))return ft;let a=jY(o.value,s.value);return a.valid?((Gk(o)||Gk(s))&&r.dirty(),{status:r.value,value:a.data}):(Ee(n,{code:me.invalid_intersection_types}),ft)};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}))}};P2.create=(e,t,r)=>new P2({left:e,right:t,typeName:_t.ZodIntersection,...Ot(r)});var wp=class e extends Bt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Ce.array)return Ee(n,{code:me.invalid_type,expected:Ce.array,received:n.parsedType}),ft;if(n.data.length<this._def.items.length)return Ee(n,{code:me.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),ft;!this._def.rest&&n.data.length>this._def.items.length&&(Ee(n,{code:me.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 Nu(n,s,n.path,a)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>Mo.mergeArray(r,s)):Mo.mergeArray(r,o)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};wp.create=(e,t)=>{if(!Array.isArray(e))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new wp({items:e,typeName:_t.ZodTuple,rest:null,...Ot(t)})};var Yk=class e extends Bt{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 Ee(n,{code:me.invalid_type,expected:Ce.object,received:n.parsedType}),ft;let i=[],o=this._def.keyType,s=this._def.valueType;for(let a in n.data)i.push({key:o._parse(new Nu(n,a,n.path,a)),value:s._parse(new Nu(n,n.data[a],n.path,a)),alwaysSet:a in n.data});return n.common.async?Mo.mergeObjectAsync(r,i):Mo.mergeObjectSync(r,i)}get element(){return this._def.valueType}static create(t,r,n){return r instanceof Bt?new e({keyType:t,valueType:r,typeName:_t.ZodRecord,...Ot(n)}):new e({keyType:ch.create(),valueType:t,typeName:_t.ZodRecord,...Ot(r)})}},Sw=class extends Bt{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 Ee(n,{code:me.invalid_type,expected:Ce.map,received:n.parsedType}),ft;let i=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([a,c],u)=>({key:i._parse(new Nu(n,a,n.path,[u,"key"])),value:o._parse(new Nu(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 ft;(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 ft;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),a.set(u.value,d.value)}return{status:r.value,value:a}}}};Sw.create=(e,t,r)=>new Sw({valueType:t,keyType:e,typeName:_t.ZodMap,...Ot(r)});var Tw=class e extends Bt{_parse(t){let{status:r,ctx:n}=this._processInputParams(t);if(n.parsedType!==Ce.set)return Ee(n,{code:me.invalid_type,expected:Ce.set,received:n.parsedType}),ft;let i=this._def;i.minSize!==null&&n.data.size<i.minSize.value&&(Ee(n,{code:me.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&&(Ee(n,{code:me.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 ft;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 Nu(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:Ye.toString(r)}})}max(t,r){return new e({...this._def,maxSize:{value:t,message:Ye.toString(r)}})}size(t,r){return this.min(t,r).max(t,r)}nonempty(t){return this.min(1,t)}};Tw.create=(e,t)=>new Tw({valueType:e,minSize:null,maxSize:null,typeName:_t.ZodSet,...Ot(t)});var Zk=class e extends Bt{constructor(){super(...arguments),this.validate=this.implement}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Ce.function)return Ee(r,{code:me.invalid_type,expected:Ce.function,received:r.parsedType}),ft;function n(a,c){return qA({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,vw(),km].filter(u=>!!u),issueData:{code:me.invalid_arguments,argumentsError:c}})}function i(a,c){return qA({data:a,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,vw(),km].filter(u=>!!u),issueData:{code:me.invalid_return_type,returnTypeError:c}})}let o={errorMap:r.common.contextualErrorMap},s=r.data;if(this._def.returns instanceof dh){let a=this;return bs(async function(...c){let u=new Ua([]),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 bs(function(...c){let u=a._def.args.safeParse(c,o);if(!u.success)throw new Ua([n(c,u.error)]);let d=Reflect.apply(s,this,u.data),l=a._def.returns.safeParse(d,o);if(!l.success)throw new Ua([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:wp.create(t).rest(Nm.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||wp.create([]).rest(Nm.create()),returns:r||Nm.create(),typeName:_t.ZodFunction,...Ot(n)})}},I2=class extends Bt{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})}};I2.create=(e,t)=>new I2({getter:e,typeName:_t.ZodLazy,...Ot(t)});var C2=class extends Bt{_parse(t){if(t.data!==this._def.value){let r=this._getOrReturnCtx(t);return Ee(r,{received:r.data,code:me.invalid_literal,expected:this._def.value}),ft}return{status:"valid",value:t.data}}get value(){return this._def.value}};C2.create=(e,t)=>new C2({value:e,typeName:_t.ZodLiteral,...Ot(t)});function a3e(e,t){return new O2({values:e,typeName:_t.ZodEnum,...Ot(t)})}var O2=class e extends Bt{_parse(t){if(typeof t.data!="string"){let r=this._getOrReturnCtx(t),n=this._def.values;return Ee(r,{expected:Ft.joinValues(n),received:r.parsedType,code:me.invalid_type}),ft}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 Ee(r,{received:r.data,code:me.invalid_enum_value,options:n}),ft}return bs(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})}};O2.create=a3e;var R2=class extends Bt{_parse(t){let r=Ft.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(t);if(n.parsedType!==Ce.string&&n.parsedType!==Ce.number){let i=Ft.objectValues(r);return Ee(n,{expected:Ft.joinValues(i),received:n.parsedType,code:me.invalid_type}),ft}if(this._cache||(this._cache=new Set(Ft.getValidEnumValues(this._def.values))),!this._cache.has(t.data)){let i=Ft.objectValues(r);return Ee(n,{received:n.data,code:me.invalid_enum_value,options:i}),ft}return bs(t.data)}get enum(){return this._def.values}};R2.create=(e,t)=>new R2({values:e,typeName:_t.ZodNativeEnum,...Ot(t)});var dh=class extends Bt{unwrap(){return this._def.type}_parse(t){let{ctx:r}=this._processInputParams(t);if(r.parsedType!==Ce.promise&&r.common.async===!1)return Ee(r,{code:me.invalid_type,expected:Ce.promise,received:r.parsedType}),ft;let n=r.parsedType===Ce.promise?r.data:Promise.resolve(r.data);return bs(n.then(i=>this._def.type.parseAsync(i,{path:r.path,errorMap:r.common.contextualErrorMap})))}};dh.create=(e,t)=>new dh({type:e,typeName:_t.ZodPromise,...Ot(t)});var ju=class extends Bt{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===_t.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=>{Ee(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 ft;let c=await this._def.schema._parseAsync({data:a,path:n.path,parent:n});return c.status==="aborted"?ft:c.status==="dirty"?_2(c.value):r.value==="dirty"?_2(c.value):c});{if(r.value==="aborted")return ft;let a=this._def.schema._parseSync({data:s,path:n.path,parent:n});return a.status==="aborted"?ft:a.status==="dirty"?_2(a.value):r.value==="dirty"?_2(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"?ft:(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"?ft:(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(!ah(s))return ft;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=>ah(s)?Promise.resolve(i.transform(s.value,o)).then(a=>({status:r.value,value:a})):ft);Ft.assertNever(i)}};ju.create=(e,t,r)=>new ju({schema:e,typeName:_t.ZodEffects,effect:t,...Ot(r)});ju.createWithPreprocess=(e,t,r)=>new ju({schema:t,effect:{type:"preprocess",transform:e},typeName:_t.ZodEffects,...Ot(r)});var Bu=class extends Bt{_parse(t){return this._getType(t)===Ce.undefined?bs(void 0):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};Bu.create=(e,t)=>new Bu({innerType:e,typeName:_t.ZodOptional,...Ot(t)});var xp=class extends Bt{_parse(t){return this._getType(t)===Ce.null?bs(null):this._def.innerType._parse(t)}unwrap(){return this._def.innerType}};xp.create=(e,t)=>new xp({innerType:e,typeName:_t.ZodNullable,...Ot(t)});var k2=class extends Bt{_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}};k2.create=(e,t)=>new k2({innerType:e,typeName:_t.ZodDefault,defaultValue:typeof t.default=="function"?t.default:()=>t.default,...Ot(t)});var B2=class extends Bt{_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 ww(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new Ua(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new Ua(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};B2.create=(e,t)=>new B2({innerType:e,typeName:_t.ZodCatch,catchValue:typeof t.catch=="function"?t.catch:()=>t.catch,...Ot(t)});var Pw=class extends Bt{_parse(t){if(this._getType(t)!==Ce.nan){let n=this._getOrReturnCtx(t);return Ee(n,{code:me.invalid_type,expected:Ce.nan,received:n.parsedType}),ft}return{status:"valid",value:t.data}}};Pw.create=e=>new Pw({typeName:_t.ZodNaN,...Ot(e)});var O0t=Symbol("zod_brand"),UA=class extends Bt{_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}},MA=class e extends Bt{_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"?ft:o.status==="dirty"?(r.dirty(),_2(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"?ft: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:_t.ZodPipeline})}},N2=class extends Bt{_parse(t){let r=this._def.innerType._parse(t),n=i=>(ah(i)&&(i.value=Object.freeze(i.value)),i);return ww(r)?r.then(i=>n(i)):n(r)}unwrap(){return this._def.innerType}};N2.create=(e,t)=>new N2({innerType:e,typeName:_t.ZodReadonly,...Ot(t)});function n3e(e,t){let r=typeof e=="function"?e(t):typeof e=="string"?{message:e}:e;return typeof r=="string"?{message:r}:r}function c3e(e,t={},r){return e?uh.create().superRefine((n,i)=>{let o=e(n);if(o instanceof Promise)return o.then(s=>{if(!s){let a=n3e(t,n),c=a.fatal??r??!0;i.addIssue({code:"custom",...a,fatal:c})}});if(!o){let s=n3e(t,n),a=s.fatal??r??!0;i.addIssue({code:"custom",...s,fatal:a})}}):uh.create()}var R0t={object:Ma.lazycreate},_t;(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"})(_t||(_t={}));var k0t=(e,t={message:`Input not instance of ${e.name}`})=>c3e(r=>r instanceof e,t),u3e=ch.create,d3e=v2.create,B0t=Pw.create,N0t=w2.create,l3e=x2.create,j0t=E2.create,q0t=Ew.create,U0t=A2.create,M0t=S2.create,D0t=uh.create,L0t=Nm.create,H0t=Xd.create,z0t=Aw.create,F0t=jm.create,$0t=Ma.create,V0t=Ma.strictCreate,K0t=T2.create,W0t=Jk.create,G0t=P2.create,J0t=wp.create,Y0t=Yk.create,Z0t=Sw.create,X0t=Tw.create,Q0t=Zk.create,e1t=I2.create,t1t=C2.create,r1t=O2.create,n1t=R2.create,i1t=dh.create,o1t=ju.create,s1t=Bu.create,a1t=xp.create,c1t=ju.createWithPreprocess,u1t=MA.create,d1t=()=>u3e().optional(),l1t=()=>d3e().optional(),p1t=()=>l3e().optional(),f1t={string:(e=>ch.create({...e,coerce:!0})),number:(e=>v2.create({...e,coerce:!0})),boolean:(e=>x2.create({...e,coerce:!0})),bigint:(e=>w2.create({...e,coerce:!0})),date:(e=>E2.create({...e,coerce:!0}))};var m1t=ft;var h1t=/^[A-Za-z0-9._-]+$/,y1t=/^[A-Za-z0-9._-]+(\|[A-Za-z0-9._-]+)*$/,p3e=new Set([".",".."]),Qs=class extends Error{pattern;constructor(t,r){super(`Invalid freeReadPathPattern ${JSON.stringify(r)}: ${t}`),this.pattern=r,this.name="FreePathPatternError"}};function g1t(e,t){if(e==="*")return{raw:e,kind:"single"};if(e==="**")return{raw:e,kind:"multi"};if(e.startsWith("(")){let r=e.endsWith(")?"),n=e.endsWith(")");if(!r&&!n)throw new Qs(`malformed alternation segment ${JSON.stringify(e)}`,t);let i=r?e.slice(1,-2):e.slice(1,-1);if(!y1t.test(i))throw new Qs(`malformed alternation segment ${JSON.stringify(e)}`,t);let o=i.split("|");if(o.some(s=>p3e.has(s)))throw new Qs(`alternation segment ${JSON.stringify(e)} may not contain '.' or '..'`,t);return{raw:e,kind:r?"alt-optional":"alt",alternatives:o}}if(h1t.test(e)){if(p3e.has(e))throw new Qs(`literal segment ${JSON.stringify(e)} is not permitted`,t);return{raw:e,kind:"literal"}}throw new Qs(`segment ${JSON.stringify(e)} must be '*', '**', a [A-Za-z0-9._-]+ literal, or (a|b) alternation`,t)}function b1t(e){if(typeof e!="string"||e.length===0)throw new Qs("must be a non-empty string",String(e));if(!e.startsWith("/"))throw new Qs("must start with '/'",e);if(e.slice(1).includes("//"))throw new Qs("empty segments ('//') are not permitted",e);if(e.length>1&&e.endsWith("/"))throw new Qs("must not end with '/'",e);let r=e.slice(1).split("/").map(o=>g1t(o,e));if(r.filter(o=>o.kind==="multi").length>1)throw new Qs("at most one '**' is permitted per pattern",e);if(r[0]?.kind==="multi")throw new Qs("'**' may not be the first segment (a literal prefix anchor is required)",e);let i=r.findIndex(o=>o.kind==="alt-optional");if(i!==-1&&i!==r.length-1)throw new Qs("optional alternation '(...)?' is only allowed as the final segment",e);return r}function qY(e){b1t(e)}var f3e=["tempo","mpp_self","merchant_self"],m3e=["catalog_static","fal_direct","fal_queue","openrouter_chat","openrouter_image","platform_proxy","tempo_gateway","x402_gateway"],h3e=["image","audio","queued_audio","video","queued_video","model_3d","llm","transcription","utility"],y3e=["images[0].url","image.url","audio.url","audio_file.url","audio_url","video.url","model_mesh.url","text","choices[0].message.content","choices[0].message.images[0].image_url.url","request_id"];var MY=ye.object({inputPerMillion:ye.number().positive(),outputPerMillion:ye.number().positive(),contextWindow:ye.number().int().positive().optional(),maxOutput:ye.number().int().positive().optional(),perRequestFeeCents:ye.number().nonnegative().optional()}),_1t=ye.object({strategy:ye.enum(["flat","token","band"]).optional(),pricingModel:ye.enum(["per-call","per-token","band"]).optional(),priceCents:ye.number().nonnegative().optional(),currency:ye.string().optional(),display:ye.string().optional(),estimate:ye.boolean().optional(),source:ye.string().optional(),priceBand:ye.record(ye.unknown()).optional(),tokenPricing:MY.optional()}).passthrough(),DY=ye.discriminatedUnion("type",[ye.object({type:ye.literal("shortcut"),routedPath:ye.string().min(1).startsWith("/")}),ye.object({type:ye.literal("custom"),merchantSlug:ye.string().min(1),subPath:ye.string().optional()}),ye.object({type:ye.literal("local"),fn:ye.string().min(1)}),ye.object({type:ye.literal("read")})]),LY=ye.object({amount:ye.number().nonnegative(),currency:ye.string().length(3).optional(),display:ye.string().optional(),free:ye.boolean().optional(),batchDiscount:ye.number().min(0).max(100).optional()}),g3e=ye.object({attestation:ye.boolean().optional(),rateLimitMs:ye.number().positive().optional()}),b3e=ye.object({displayName:ye.string().optional(),feedbackEligible:ye.boolean().optional(),suggestionEligible:ye.boolean().optional(),batchable:ye.boolean().optional()}),_3e=ye.object({enabled:ye.boolean().optional(),gatewayPath:ye.string().min(1).startsWith("/").optional(),method:ye.enum(["GET","POST","PUT","PATCH","DELETE"]).optional(),timeoutMs:ye.number().int().positive().max(12e4).optional()}).strict(),v3e=ye.enum(["image","video","audio","3d","llm","upscale","tts","transcription","utility","onchain"]),HY=v3e.options,v1t=120,w1t=120,x1t=1200,E1t=/^[^\u0000-\u001F\u007F]+$/;function UY(e,t){return ye.string().min(1).max(e).regex(E1t,`${t} must not contain control characters`)}var zY={id:ye.string().min(1),name:UY(v1t,"name"),description:UY(x1t,"description"),provider:ye.string().min(1),model:ye.string().min(1),category:v3e,priceCents:ye.number().nonnegative(),inputSchema:ye.record(ye.unknown()),gatewayUrl:ye.string().min(1),merchantName:UY(w1t,"merchantName"),isAsync:ye.boolean().optional(),pollUrl:ye.string().optional(),pollInterval:ye.number().positive().optional(),pollTimeout:ye.number().positive().optional(),tags:ye.array(ye.string()).optional(),tokenPricing:MY.optional(),priceDisplay:ye.string().optional(),pricingModel:ye.enum(["per-call","per-token","band"]).optional(),pricingInfo:_1t.optional(),status:ye.enum(["available","unavailable"]).optional(),handler:DY.optional(),pricing:LY.optional(),security:g3e.optional(),engagement:b3e.optional(),gatewayConfig:_3e.optional(),freeReadPathPattern:ye.string().optional().superRefine((e,t)=>{if(e!==void 0)try{qY(e)}catch(r){t.addIssue({code:ye.ZodIssueCode.custom,message:r instanceof Error?r.message:String(r)})}}),enabled:ye.boolean().optional(),beta:ye.boolean().optional(),deprecated:ye.boolean().optional(),internal:ye.boolean().optional(),employeeOnly:ye.boolean().optional(),employeeOnlyRolloutFlag:ye.string().min(1).max(100).optional(),replacementTool:ye.string().optional(),minCliVersion:ye.string().optional(),sunsetAt:ye.string().optional(),rail:ye.enum(f3e).optional(),executionKind:ye.enum(m3e).optional(),resultKind:ye.enum(h3e).optional(),extractionMode:ye.enum(y3e).optional(),pricingStrategy:ye.enum(["flat","token","band"]).optional()},w3e=ye.object({...zY,dispatch:ye.literal("routed"),routedPath:ye.string().min(1).startsWith("/")}).strict(),x3e=ye.object({...zY,dispatch:ye.literal("enveloped")}).strict(),E3e=ye.object({...zY,handler:DY,pricing:LY}).strict(),A3e=ye.union([ye.discriminatedUnion("dispatch",[w3e,x3e]),E3e]);var T1t="https://fal.run",I3e="https://openrouter.mpp.tempo.xyz",$Y=1024,Qk=8192,P1t=4096,I1t=10;function C1t(e){return e>=I1t?P1t:Qk}function C3e(e,t){let r=typeof e=="number"&&Number.isFinite(e)&&e>0?Math.floor(e):$Y;return Math.min(r,t)}var O1t=["num_images","num_outputs","num_samples","num_videos","batch_size","n"];function O3e(e){for(let t of O1t)delete e[t];return e}function R1t(e){let{attestation:t,tool_id:r,...n}=e;return O3e(n)}var S3e={"1:1":"square_hd","16:9":"landscape_16_9","9:16":"portrait_16_9","4:3":"landscape_4_3","3:4":"portrait_4_3"};function Xk(e){let{attestation:t,tool_id:r,aspect_ratio:n,image_size:i,...o}=e,s=O3e({...o});return typeof i=="string"&&i.length>0?(s.image_size=i,s):(typeof n=="string"&&S3e[n]&&(s.image_size=S3e[n]),s)}function k1t(e){let{attestation:t,tool_id:r,...n}=e;return n}function T3e(e){let t={chain:e.chain,token_address:e.token_address};if(e.start_timestamp){let r=e.end_timestamp||new Date().toISOString(),n=e.time_granularity;if(!n){let i=new Date(e.start_timestamp).getTime();(new Date(r).getTime()-i)/(1e3*60*60*24)<=2?n="1h":n="1d"}return{addresses:[t],start_timestamp:e.start_timestamp,end_timestamp:r,time_granularity:n}}return[t]}function B1t(e,t,r,n,i,o,s,a,c){return{id:e,name:t,description:r,provider:n,model:i.replace(/^\//,""),category:o,gatewayUrl:`https://${n}${i}`,merchantName:t,inputSchema:a,handler:{type:"custom",merchantSlug:n,subPath:i},pricing:{amount:s,currency:"USD",display:`$${(s/100).toFixed(2)}`},priceCents:s,tags:[],...c}}function N1t(e,t,r,n,i,o,s,a){return B1t(e,t,r,"suno-ai",n,i,o,s,{merchantName:"Suno AI",...a})}function Ci(e,t,r,n,i,o,s,a){return{dispatch:"routed",id:e,name:t,description:r,provider:"fal",model:n,category:i,priceCents:o,inputSchema:s,routedPath:`/api/v1/fal/${n}`,gatewayUrl:`${T1t}/${n}`,merchantName:"fal.ai",buildBody:R1t,tags:[],...a}}function R3e(e,t=Qk){return r=>{let{attestation:n,tool_id:i,model:o,prompt:s,system_prompt:a,max_tokens:c,max_completion_tokens:u,n:d,messages:l,temperature:p,...f}=r;return typeof o=="string"&&o.length>0&&o!==e&&console.warn("[catalog] openrouterBuildBody: caller model override ignored",{catalogModel:e,callerModel:o}),{messages:Array.isArray(l)?l:[...a?[{role:"system",content:a}]:[],{role:"user",content:s}],temperature:p??.7,...f,model:e,max_tokens:C3e(c??u,t),usage:{include:!0}}}}function k3e(e,t=Qk){return r=>{let{attestation:n,tool_id:i,prompt:o,image_url:s,aspect_ratio:a,max_tokens:c,max_completion_tokens:u,n:d,model:l,messages:p,image_config:f,temperature:m,...h}=r,y=[{type:"text",text:o}];return typeof s=="string"&&s.length>0&&y.push({type:"image_url",image_url:{url:s}}),{messages:Array.isArray(p)?p:[{role:"user",content:y}],temperature:m??.7,...h,model:e,...typeof a=="string"&&a.length>0?{image_config:{aspect_ratio:a}}:{},max_tokens:C3e(c??u,t),usage:{include:!0}}}}function Hn(e,t,r,n,i,o,s){let a=s?.maxOutputTokens??C1t(o),c=s?.perRequestFeeCents??0,u=500/1e6*i*100,d=500/1e6*o*100,l=Math.max(1,Math.ceil(u+d+c)),{perRequestFeeCents:p,maxOutputTokens:f,...m}=s??{};return{dispatch:"routed",id:e,name:t,description:r,provider:"openrouter",model:n,category:"llm",priceCents:l,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"The prompt or question to send to the model"},system_prompt:{type:"string",description:"Optional system prompt to set model behavior"},max_tokens:{type:"integer",description:`Maximum tokens in response (default: ${$Y}); values above ${a} are clamped to ${a}`,minimum:1,maximum:a},temperature:{type:"number",description:"Sampling temperature 0-2 (default: 0.7)",minimum:0,maximum:2}},required:["prompt"]},routedPath:"/api/v1/chat/completions",gatewayUrl:`${I3e}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:R3e(n,a),tags:["llm","chat","text"],tokenPricing:{inputPerMillion:i,outputPerMillion:o,...c>0?{perRequestFeeCents:c}:{}},...m}}function FY(e,t,r,n,i,o){let s=o?.maxOutputTokens??Qk,{maxOutputTokens:a,...c}=o??{};return{dispatch:"routed",id:e,name:t,description:r,provider:"openrouter",model:n,category:"image",pricingStrategy:"band",priceCents:i,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate or edit"},image_url:{type:"string",description:"Optional source image URL for edits"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"1:1"},max_tokens:{type:"integer",description:`Maximum text tokens in response metadata (default: ${$Y}); values above ${s} are clamped to ${s}`,minimum:1,maximum:s},temperature:{type:"number",description:"Sampling temperature 0-2 (default: 0.7)",minimum:0,maximum:2}},required:["prompt"]},routedPath:"/api/v1/chat/completions",gatewayUrl:`${I3e}/v1/chat/completions`,merchantName:"OpenRouter",buildBody:k3e(n,s),tags:["image","gemini","google","nano-banana","edit"],tokenPricing:{inputPerMillion:.3,outputPerMillion:2.5},...c}}var VY=[Ci("fal-flux-pro-ultra","FLUX Pro Ultra","Highest quality image generation. Best for detailed, photorealistic images.","fal-ai/flux-pro/v1.1-ultra","image",6,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"16:9"}},required:["prompt"]},{tags:["image","flux","photorealistic","high-quality"]}),Ci("fal-flux-pro","FLUX Pro","Fast, high-quality image generation. Good balance of speed and quality.","fal-ai/flux-pro/v1.1","image",4,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"16:9"}},required:["prompt"]},{tags:["image","flux","fast"],buildBody:Xk}),Ci("fal-flux-dev","FLUX Dev","Open-source image generation. Cheaper, good for experimentation.","fal-ai/flux/dev","image",3,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},{tags:["image","flux","open-source","cheap"],buildBody:Xk}),Ci("fal-flux-schnell","FLUX Schnell","Fastest image generation. Ultra-cheap, great for drafts and iteration.","fal-ai/flux/schnell","image",1,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},{tags:["image","flux","fast","cheap","draft"],buildBody:Xk}),Ci("fal-recraft-v3","Recraft V3","Design-focused image generation. Great for illustrations, icons, and graphic design.","fal-ai/recraft/v3/text-to-image","image",5,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},style:{type:"string",description:"Style preset: realistic_image, digital_illustration, vector_illustration, icon"}},required:["prompt"]},{tags:["image","design","illustration","icon","vector"]}),FY("or-gemini-nano-banana","Nano Banana","Google Gemini 2.5 Flash Image via OpenRouter for image generation and edits.","google/gemini-2.5-flash-image",4),FY("or-gemini-nano-banana-2","Nano Banana 2","Google Gemini 3.1 Flash Image Preview via OpenRouter for fast image generation and edits.","google/gemini-3.1-flash-image-preview",5,{tags:["image","gemini","google","nano-banana","edit","fast"],tokenPricing:{inputPerMillion:.5,outputPerMillion:3}}),FY("or-gemini-nano-banana-pro","Nano Banana Pro","Google Gemini 3 Pro Image Preview via OpenRouter for professional image generation, edits, and text rendering.","google/gemini-3-pro-image-preview",8,{tags:["image","gemini","google","nano-banana","pro","text-rendering"],tokenPricing:{inputPerMillion:2,outputPerMillion:12}}),Ci("fal-ideogram-v2","Ideogram V2","Excellent text rendering in images. Best for logos, posters, and text-heavy visuals.","fal-ai/ideogram/v2","image",8,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"1:1"}},required:["prompt"]},{tags:["image","text-rendering","logo","poster","typography"]}),Ci("fal-ideogram-v2-turbo","Ideogram V2 Turbo","Fast text rendering in images. Good balance of speed and text accuracy.","fal-ai/ideogram/v2/turbo","image",5,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"1:1"}},required:["prompt"]},{tags:["image","text-rendering","fast"]}),Ci("fal-fast-sdxl","Fast SDXL","Ultra-fast Stable Diffusion. 4-step inference, cheapest option.","fal-ai/fast-sdxl","image",1,{type:"object",properties:{prompt:{type:"string",description:"Text description of the image to generate"}},required:["prompt"]},{tags:["image","stable-diffusion","fast","cheap"]}),Ci("fal-wan-video","Wan Video","Text-to-video generation. Create short video clips from text descriptions.","fal-ai/wan/v2.1/1.3b/text-to-video","video",10,{type:"object",properties:{prompt:{type:"string",description:"Text description of the video to generate"},num_frames:{type:"number",description:"Number of frames (default: 81)"}},required:["prompt"]},{tags:["video","text-to-video","wan"]}),Ci("fal-minimax-video","MiniMax Video","High-quality video generation with excellent motion and coherence.","fal-ai/minimax-video/video-01-live","video",15,{type:"object",properties:{prompt:{type:"string",description:"Text description of the video to generate"}},required:["prompt"]},{tags:["video","text-to-video","high-quality"]}),Ci("fal-kling-video","Kling Video","Professional video generation with cinematic quality.","fal-ai/kling-video/v2/master/text-to-video","video",20,{type:"object",properties:{prompt:{type:"string",description:"Text description of the video to generate"},duration:{type:"string",description:"Duration: 5 or 10 seconds",default:"5"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},{tags:["video","text-to-video","cinematic","professional"]}),Ci("fal-kling-i2v","Kling Image-to-Video","Animate a still image into a 5\u201310s video clip. Cinematic motion quality.","fal-ai/kling-video/v1.6/standard/image-to-video","video",35,{type:"object",properties:{image_url:{type:"string",description:"URL of the source image (jpg, png, webp, gif, avif)"},prompt:{type:"string",description:"Text description of the motion to animate"},duration:{type:"string",description:"Duration: 5 or 10 seconds",default:"5"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 9:16, 1:1)",default:"16:9"},negative_prompt:{type:"string",description:"Elements to avoid in the generated motion"},cfg_scale:{type:"number",description:"Classifier-free guidance (default 0.5)",default:.5}},required:["image_url","prompt"]},{tags:["video","image-to-video","kling","cinematic"]}),Ci("fal-stable-audio","Stable Audio","Generate sound effects and ambient audio from text descriptions.","fal-ai/stable-audio","audio",4,{type:"object",properties:{prompt:{type:"string",description:"Description of the audio to generate"},seconds_total:{type:"number",description:"Duration in seconds (max 47)",default:30}},required:["prompt"]},{tags:["audio","sound-effects","ambient"]}),Ci("fal-ace-step-music","ACE-Step Music","Generate full music tracks from a prompt, with optional vocals or instrumentals.","fal-ai/ace-step/prompt-to-audio","audio",2,{type:"object",properties:{prompt:{type:"string",description:"Description of the song, genre, mood, instruments, and lyrics direction"},instrumental:{type:"boolean",description:"Generate instrumental music without vocals",default:!1},duration:{type:"number",description:"Duration in seconds",default:60}},required:["prompt"]},{tags:["music","song","vocals","instrumental","ace-step"]}),N1t("suno-music","Suno Music","AI music generation. Create full songs with vocals or instrumentals.","/suno/generate-music","audio",10,{type:"object",properties:{prompt:{type:"string",description:"Description of the song (genre, mood, instruments)"},instrumental:{type:"boolean",description:"Instrumental only, no vocals",default:!1}},required:["prompt"]},{isAsync:!0,pollUrl:"https://api.sunoapi.org/suno/get-music-status",deprecated:!0,tags:["music","song","vocals","instrumental"],buildBody:e=>{let{attestation:t,tool_id:r,prompt:n,instrumental:i,...o}=e;return{prompt:n,customMode:!1,instrumental:typeof i=="boolean"?i:!1,model:"V4",...o}}}),Ci("fal-trellis-3d","Trellis 3D","Generate 3D models from images. Upload a photo, get a 3D asset.","fal-ai/trellis","3d",8,{type:"object",properties:{image_url:{type:"string",description:"URL of the image to convert to 3D"}},required:["image_url"]},{tags:["3d","model","image-to-3d"]}),Ci("fal-aura-sr","Aura SR","Upscale images to higher resolution. 4x upscaling with detail enhancement.","fal-ai/aura-sr","upscale",3,{type:"object",properties:{image_url:{type:"string",description:"URL of the image to upscale"}},required:["image_url"]},{tags:["upscale","super-resolution","enhance"]}),Ci("fal-metavoice","MetaVoice Voice Cloning","Voice cloning TTS \u2014 clone any voice from an audio sample. Provide text and a voice sample URL.","fal-ai/metavoice-v1","tts",3,{type:"object",properties:{text:{type:"string",description:"Text to convert to speech"},audio_url:{type:"string",description:"URL of the voice sample to clone"}},required:["text","audio_url"]},{tags:["tts","voice","voice-cloning","speech"]}),Ci("fal-whisper","Whisper Transcription","Transcribe audio to text. Supports multiple languages.","fal-ai/whisper","transcription",2,{type:"object",properties:{audio_url:{type:"string",description:"URL of the audio to transcribe"},language:{type:"string",description:"Language code (e.g. en, es, fr)"}},required:["audio_url"]},{tags:["transcription","speech-to-text","whisper"]}),Hn("or-gpt-4o","GPT-4o","OpenAI's flagship multimodal model. Best for complex reasoning and analysis.","openai/gpt-4o",2.5,10,{tags:["llm","gpt","openai","multimodal","reasoning"]}),Hn("or-gpt-55","GPT-5.5","OpenAI frontier model for complex professional reasoning, coding, and long-context analysis.","openai/gpt-5.5",5,30,{tags:["llm","gpt","openai","frontier","reasoning","coding","long-context"]}),Hn("or-gpt-55-pro","GPT-5.5 Pro","OpenAI high-capability frontier model optimized for deep reasoning and high-stakes workloads.","openai/gpt-5.5-pro",30,180,{tags:["llm","gpt","openai","frontier","pro","deep-reasoning","coding","long-context"]}),Hn("or-gpt-4o-mini","GPT-4o Mini","Fast, affordable GPT-4o. Great for everyday tasks, chat, and simple analysis.","openai/gpt-4o-mini",.15,.6,{tags:["llm","gpt","openai","fast","cheap"]}),Hn("or-claude-opus-4-8","Claude Opus 4.8","Anthropic's newest flagship. 1M context, strongest reasoning + coding.","anthropic/claude-opus-4.8",15,75,{tags:["llm","claude","anthropic","reasoning","coding","newest"]}),Hn("or-claude-opus","Claude Opus 4.7","Anthropic's most capable model. 1M context, reasoning, best for complex tasks.","anthropic/claude-opus-4.7",15,75,{tags:["llm","claude","anthropic","reasoning","coding"]}),Hn("or-claude-sonnet","Claude Sonnet 4.6","Anthropic's best balance of intelligence and speed. Excellent for coding and analysis.","anthropic/claude-sonnet-4.6",3,15,{tags:["llm","claude","anthropic","coding","analysis"]}),Hn("or-claude-opus-fast","Claude Opus 4.8 Fast","Fast Opus variant with lower latency.","anthropic/claude-opus-4.8-fast",10,50,{tags:["llm","claude","anthropic","fast"]}),Hn("or-claude-haiku","Claude Haiku 4.5","Anthropic's fastest model. Great for quick tasks, chat, and simple reasoning.","anthropic/claude-haiku-4.5",1,5,{tags:["llm","claude","anthropic","fast"]}),Hn("or-gemini-pro","Gemini 2.5 Flash","Google's fast multimodal model. Good for general tasks with long context.","google/gemini-2.5-flash",.3,2.5,{tags:["llm","gemini","google","multimodal","fast","cheap"]}),Hn("or-gemini-3-flash","Gemini 3 Flash","Google's high-speed thinking model for agentic workflows, coding, and multimodal tasks.","google/gemini-3-flash-preview",.5,3,{tags:["llm","gemini","google","agentic","coding","fast"]}),Hn("or-gemini-3-pro","Gemini 3.1 Pro","Google's flagship frontier model for deep reasoning, multimodal analysis, and agentic coding.","google/gemini-3.1-pro-preview",2,12,{tags:["llm","gemini","google","reasoning","coding","multimodal"]}),Hn("or-gemini-35-flash","Gemini 3.5 Flash","Google frontier Flash model for multimodal reasoning, coding, and parallel agentic workflows.","google/gemini-3.5-flash",1.5,9,{tags:["llm","gemini","google","frontier","multimodal","reasoning","coding","fast"]}),Hn("or-gemini-3-lite","Gemini 3.1 Flash Lite","Google's efficient multimodal model optimized for low-latency, high-volume agent workloads.","google/gemini-3.1-flash-lite",.25,1.5,{tags:["llm","gemini","google","fast","cheap","multimodal"]}),Hn("or-llama-70b","Llama 3.3 70B","Meta's best open model. Strong reasoning, fully open-source.","meta-llama/llama-3.3-70b-instruct",.3,.4,{tags:["llm","llama","meta","open-source","reasoning"]}),Hn("or-llama-8b","Llama 3.1 8B","Fast, lightweight open model. Great for simple tasks at minimal cost.","meta-llama/llama-3.1-8b-instruct",.05,.08,{tags:["llm","llama","meta","open-source","fast","cheap"]}),Hn("or-mistral-large","Mistral Large","Mistral's flagship model. Strong at multilingual and European languages.","mistralai/mistral-large-2512",.5,1.5,{tags:["llm","mistral","multilingual","european"]}),Hn("or-mistral-small","Mistral Small","Fast, efficient Mistral model. Good for everyday tasks.","mistralai/mistral-small-3.1-24b-instruct",.1,.3,{tags:["llm","mistral","fast","cheap"]}),Hn("or-deepseek-chat","DeepSeek Chat V3","Strong reasoning model at very low cost. Excellent for coding and math.","deepseek/deepseek-chat-v3-0324",.3,.88,{tags:["llm","deepseek","coding","math","cheap","reasoning"]}),Hn("or-deepseek-r1","DeepSeek R1","Advanced reasoning model with chain-of-thought. Best for complex problems.","deepseek/deepseek-r1",.55,2.19,{tags:["llm","deepseek","reasoning","chain-of-thought","math"]}),Hn("or-qwen-72b","Qwen 2.5 72B","Alibaba's large model. Strong at coding, math, and multilingual tasks.","qwen/qwen-2.5-72b-instruct",.3,.4,{tags:["llm","qwen","alibaba","coding","multilingual"]}),Hn("or-phi-4","Phi-4","Microsoft's compact reasoning model. Punches above its weight for size.","microsoft/phi-4",.07,.14,{tags:["llm","phi","microsoft","compact","cheap","reasoning"]}),Hn("or-perplexity-sonar","Perplexity Sonar","Search-augmented LLM. Answers with real-time web sources and citations.","perplexity/sonar",1,1,{perRequestFeeCents:.5,tags:["llm","perplexity","search","web","citations","real-time"]}),{dispatch:"enveloped",id:"query_onchain_prices",name:"Query On-Chain Prices",description:"Query real-time or historical on-chain token prices via Allium. Use this for current prices, price history over any date range, price trends, comparisons between time periods, and analytics like monthly/weekly price charts. Supports hourly and daily granularity.",provider:"allium",model:"allium-prices",category:"onchain",priceCents:1,inputSchema:{type:"object",properties:{chain:{type:"string",description:"Chain name (e.g. ethereum, solana, base, polygon)"},token_address:{type:"string",description:"Token contract address. Use the native token address for chain-native assets (e.g. ETH, SOL)."},start_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range start (e.g. '2024-01-01T00:00:00Z'). Omit for current price only."},end_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range end. Defaults to now if start_timestamp is set."},time_granularity:{type:"string",description:"Data resolution: '1h' (hourly) or '1d' (daily). Auto-selected based on date range if omitted."}},required:["chain","token_address"]},gatewayUrl:"https://agents.allium.so/api/v1/developer/prices",merchantName:"Allium",internal:!0,executionKind:"x402_gateway",resultKind:"utility",gatewayConfig:{enabled:!1,gatewayPath:"/gateway",method:"POST",timeoutMs:3e4},buildUrl:e=>e.start_timestamp?"https://agents.allium.so/api/v1/developer/prices/history":"https://agents.allium.so/api/v1/developer/prices",buildBody:T3e,tags:["onchain","prices","allium","crypto"]},{dispatch:"enveloped",id:"parallel-search-tempo",name:"Parallel Search (Tempo)",description:"Internal Tempo gateway route for Parallel's paid search endpoint.",provider:"parallel",model:"search",category:"utility",priceCents:1,inputSchema:{type:"object",properties:{query:{type:"string",description:"Search query. Mapped by Parallel to objective when provided."},objective:{type:"string",description:"Search objective. Use with search_queries for advanced requests."},search_queries:{type:"array",items:{type:"string"},description:"Optional explicit search query list."},mode:{type:"string",enum:["one-shot","fast"],description:"Parallel search mode.",default:"one-shot"}},anyOf:[{required:["query"]},{required:["objective"]}]},gatewayUrl:"https://parallelmpp.dev/api/search",merchantName:"Parallel",internal:!0,rail:"tempo",executionKind:"tempo_gateway",resultKind:"utility",gatewayConfig:{enabled:!1,gatewayPath:"/gateway",method:"POST",timeoutMs:3e4},buildBody:k1t,tags:["search","parallel","tempo","internal"]},{dispatch:"enveloped",id:"generate_image_card",name:"Generate Image (Ultra)",description:"Generate a high-quality AI image (FLUX Pro Ultra, 2K, ~$0.06).",provider:"fal",model:"fal-ai/flux-pro/v1.1-ultra",category:"image",priceCents:6,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image"},aspect_ratio:{type:"string",description:"Aspect ratio (e.g. 16:9, 1:1, 9:16)",default:"16:9"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux-pro/v1.1-ultra",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-pro-ultra",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),t},tags:["image","flux","ultra","legacy"]},{dispatch:"enveloped",id:"generate_image_fast_card",name:"Generate Image (Fast)",description:"Generate an AI image (FLUX Pro v1.1, 1K, ~$0.04).",provider:"fal",model:"fal-ai/flux-pro/v1.1",category:"image",priceCents:4,inputSchema:{type:"object",properties:{prompt:{type:"string",description:"Text description of the image"},aspect_ratio:{type:"string",description:"Aspect ratio",default:"16:9"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux-pro/v1.1",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-pro",buildBody:e=>Xk({prompt:e.prompt,aspect_ratio:e.aspect_ratio}),tags:["image","flux","legacy"]},{dispatch:"enveloped",id:"generate_image_schnell_card",name:"Generate Image (Cheap)",description:"Cheap, fast FLUX image generation (~$0.01).",provider:"fal",model:"fal-ai/flux/schnell",category:"image",priceCents:1,inputSchema:{type:"object",properties:{prompt:{type:"string"},image_size:{type:"string"},num_inference_steps:{type:"number"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/flux/schnell",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-flux-schnell",buildBody:e=>{let t={prompt:e.prompt};return e.image_size&&(t.image_size=e.image_size),e.num_inference_steps!==void 0&&(t.num_inference_steps=e.num_inference_steps),e.seed!==void 0&&(t.seed=e.seed),t},tags:["image","flux","schnell","legacy"]},{dispatch:"enveloped",id:"generate_image_recraft_card",name:"Generate Image (Recraft)",description:"Recraft V3 image generation with style control.",provider:"fal",model:"fal-ai/recraft-v3",category:"image",priceCents:5,inputSchema:{type:"object",properties:{prompt:{type:"string"},style:{type:"string"},image_size:{type:"string"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/recraft-v3",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-recraft-v3",buildBody:e=>{let t={prompt:e.prompt};return e.style&&(t.style=e.style),e.image_size&&(t.image_size=e.image_size),t},tags:["image","recraft","legacy"]},{dispatch:"enveloped",id:"generate_image_ideogram_card",name:"Generate Image (Ideogram)",description:"Ideogram V2 image generation, strong with text rendering.",provider:"fal",model:"fal-ai/ideogram/v2",category:"image",priceCents:8,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},style_type:{type:"string"},negative_prompt:{type:"string"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/ideogram/v2",merchantName:"fal.ai",deprecated:!0,replacementTool:"fal-ideogram-v2",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.style_type&&(t.style_type=e.style_type),e.negative_prompt&&(t.negative_prompt=e.negative_prompt),t},tags:["image","ideogram","text","legacy"]},Ci("upscale_image_card","Upscale Image","Upscale an image using ESRGAN.","fal-ai/esrgan","upscale",2,{type:"object",properties:{image_url:{type:"string"},scale:{type:"number"}},required:["image_url"]},{buildBody:e=>{let t={image_url:e.image_url};return e.scale!==void 0&&(t.scale=e.scale),t},tags:["upscale","esrgan"],deprecated:!0,replacementTool:"fal-aura-sr"}),Ci("edit_image_seed_card","Edit Image (SeedEdit)","Inpaint/edit an image with a prompt using SeedEdit.","fal-ai/bytedance/seededit","image",5,{type:"object",properties:{image_url:{type:"string"},prompt:{type:"string"},seed:{type:"number"}},required:["image_url","prompt"]},{buildBody:e=>{let t={image_url:e.image_url,prompt:e.prompt};return e.seed!==void 0&&(t.seed=e.seed),t},tags:["image","edit","inpaint","seededit"],deprecated:!0,replacementTool:"or-gemini-nano-banana"}),{dispatch:"enveloped",id:"generate_video_tempo_card",name:"Generate Video (Grok)",description:"Generate a video from a text prompt using Grok Imagine Video.",provider:"fal",model:"xai/grok-imagine-video/text-to-video",category:"video",priceCents:30,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},duration:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/xai/grok-imagine-video/text-to-video",merchantName:"Grok Video via fal.ai",deprecated:!0,replacementTool:"fal-minimax-video",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.duration&&(t.duration=e.duration),t},tags:["video","grok","legacy"]},{dispatch:"enveloped",id:"generate_video_kling_card",name:"Generate Video (Kling)",description:"Generate a video using Kling v1.6 (async, ~$0.40).",provider:"fal",model:"fal-ai/kling-video/v1.6/standard/text-to-video",category:"video",priceCents:40,inputSchema:{type:"object",properties:{prompt:{type:"string"},negative_prompt:{type:"string"},aspect_ratio:{type:"string"},duration:{type:"number"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/kling-video/v1.6/standard/text-to-video",merchantName:"Kling via fal.ai",deprecated:!0,replacementTool:"fal-kling-video",buildBody:e=>{let t={prompt:e.prompt};return e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.duration&&(t.duration=e.duration),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","kling","legacy"]},{dispatch:"enveloped",id:"generate_video_wan_card",name:"Generate Video (Wan)",description:"Generate a video using Wan T2V (async, ~$0.25).",provider:"fal",model:"fal-ai/wan/t2v-1.3b",category:"video",priceCents:25,inputSchema:{type:"object",properties:{prompt:{type:"string"},negative_prompt:{type:"string"},aspect_ratio:{type:"string"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/wan/t2v-1.3b",merchantName:"Wan T2V via fal.ai",deprecated:!0,replacementTool:"fal-wan-video",buildBody:e=>{let t={prompt:e.prompt};return e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","wan","legacy"]},{dispatch:"enveloped",id:"generate_video_minimax_card",name:"Generate Video (MiniMax)",description:"Generate a video using MiniMax (async, ~$0.35).",provider:"fal",model:"fal-ai/minimax/video-01",category:"video",priceCents:35,inputSchema:{type:"object",properties:{prompt:{type:"string"},aspect_ratio:{type:"string"},seed:{type:"number"}},required:["prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/minimax/video-01",merchantName:"MiniMax via fal.ai",deprecated:!0,replacementTool:"fal-minimax-video",buildBody:e=>{let t={prompt:e.prompt};return e.aspect_ratio&&(t.aspect_ratio=e.aspect_ratio),e.seed!==void 0&&(t.seed=e.seed),t},tags:["video","minimax","legacy"]},{id:"check_fal_status",name:"Check fal Async Job Status",description:"Poll an async fal.ai queue job for completion. Free.",provider:"fal",model:"queue-status",category:"image",priceCents:0,inputSchema:{type:"object",properties:{model_path:{type:"string",description:"Model path (e.g. fal-ai/kling-video/v1.6/standard/text-to-video)"},request_id:{type:"string"}},required:["model_path","request_id"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue",merchantName:"fal.ai",handler:{type:"local",fn:"check_fal_status"},pricing:{amount:0,currency:"USD",display:"$0.00",free:!0},freeReadPathPattern:"/api/v1/fal/**/requests/*/(status)?",tags:["status","fal","async"]},{dispatch:"enveloped",id:"generate_3d_card",name:"Generate 3D Model",description:"Generate a 3D mesh from a text prompt using Meshy (async, ~$0.50).",provider:"fal",model:"fal-ai/meshy-ai/text-to-3d",category:"3d",priceCents:50,inputSchema:{type:"object",properties:{object_prompt:{type:"string"},style_prompt:{type:"string"},negative_prompt:{type:"string"},art_style:{type:"string"},seed:{type:"number"}},required:["object_prompt"]},gatewayUrl:"https://fal.mpp.tempo.xyz/queue/fal-ai/meshy-ai/text-to-3d",merchantName:"Meshy via fal.ai",deprecated:!0,replacementTool:"fal-trellis-3d",buildBody:e=>{let t={object_prompt:e.object_prompt};return e.style_prompt&&(t.style_prompt=e.style_prompt),e.negative_prompt&&(t.negative_prompt=e.negative_prompt),e.art_style&&(t.art_style=e.art_style),e.seed!==void 0&&(t.seed=e.seed),t},tags:["3d","mesh","meshy","legacy"]},{dispatch:"enveloped",id:"generate_speech_card",name:"Generate Speech",description:"Text-to-speech using F5-TTS with optional voice cloning.",provider:"fal",model:"fal-ai/f5-tts",category:"tts",priceCents:3,inputSchema:{type:"object",properties:{gen_text:{type:"string",description:"Text to synthesize"},ref_audio_url:{type:"string",description:"Reference audio URL (for voice cloning)"},ref_text:{type:"string",description:"Transcription of ref audio"},remove_silence:{type:"boolean"}},required:["gen_text"]},gatewayUrl:"https://fal.mpp.tempo.xyz/fal-ai/f5-tts",merchantName:"fal.ai",buildBody:e=>{let t={gen_text:e.gen_text};return e.ref_audio_url&&(t.ref_audio_url=e.ref_audio_url),e.ref_text&&(t.ref_text=e.ref_text),e.remove_silence!==void 0&&(t.remove_silence=e.remove_silence),t},deprecated:!0,replacementTool:"fal-metavoice",tags:["tts","speech","f5-tts","legacy"]},{dispatch:"enveloped",id:"generate_music_tempo_card",name:"Generate Music (Suno) \u2014 retired",description:"[Retired] Suno music generation. Use `generate_music` (ACE-Step) instead.",enabled:!1,sunsetAt:"2026-06-25",provider:"suno",model:"suno-v4",category:"audio",priceCents:50,inputSchema:{type:"object",properties:{prompt:{type:"string"},instrumental:{type:"boolean"},model:{type:"string",default:"V4"}},required:["prompt"]},gatewayUrl:"https://suno.mpp.paywithlocus.com/suno/generate-music",merchantName:"Suno via Tempo",buildBody:e=>({prompt:e.prompt,customMode:!1,instrumental:e.instrumental??!1,model:e.model||"V4"}),isAsync:!0,pollUrl:"https://suno.mpp.paywithlocus.com/suno/get-music-status",pollInterval:15e3,pollTimeout:3e5,deprecated:!0,replacementTool:"fal-ace-step-music",tags:["music","audio","suno","async","legacy"]},{dispatch:"enveloped",id:"check_music_status_tempo_card",name:"Check Music Status (Suno) \u2014 retired",description:"[Retired] Suno status poll. No replacement; ACE-Step jobs poll via `check_fal_status`.",enabled:!1,sunsetAt:"2026-06-25",provider:"suno",model:"suno-status",category:"audio",priceCents:0,inputSchema:{type:"object",properties:{taskId:{type:"string"}},required:["taskId"]},gatewayUrl:"https://suno.mpp.paywithlocus.com/suno/get-music-status",merchantName:"Suno Status",buildBody:e=>({taskId:e.taskId}),deprecated:!0,tags:["music","status","suno","legacy"]},{dispatch:"enveloped",id:"query_onchain_prices_card",name:"Query On-Chain Prices",description:"Query real-time or historical on-chain token prices via Allium. Use this for current prices, price history over any date range, price trends, comparisons between time periods, and analytics like monthly/weekly price charts. Supports hourly, daily, and weekly granularity.",provider:"allium",model:"allium-prices",category:"llm",priceCents:1,inputSchema:{type:"object",properties:{chain:{type:"string",description:"Chain name (e.g. ethereum, solana, base, polygon)"},token_address:{type:"string",description:"Token contract address. Use the native token address for chain-native assets (e.g. ETH, SOL)."},start_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range start (e.g. '2024-01-01T00:00:00Z'). Omit for current price only."},end_timestamp:{type:"string",description:"ISO 8601 timestamp for historical range end. Defaults to now if start_timestamp is set."},time_granularity:{type:"string",description:"Data resolution: '1h' (hourly), '1d' (daily), or '1w' (weekly). Auto-selected based on date range if omitted."}},required:["chain","token_address"]},gatewayUrl:"https://agents.allium.so/api/v1/developer/prices",merchantName:"Allium",deprecated:!0,replacementTool:"query_onchain_prices",buildUrl:e=>e.start_timestamp?"https://agents.allium.so/api/v1/developer/prices/history":"https://agents.allium.so/api/v1/developer/prices",buildBody:T3e,tags:["onchain","prices","allium","crypto","legacy"]}];function DA(e){return VY.find(t=>t.id===e)}function KY(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}function WY(e,t){return Array.isArray(e.type)?e.type.includes(t):e.type===t}function U1t(e){return!!e.properties&&Object.keys(e.properties).length>0}function GY(e){let t=KY(e);if(!t||t.type!==void 0&&!WY(t,"object"))return!0;let r=Array.isArray(t.required)?t.required:[];return!U1t(t)&&r.length===0&&t.additionalProperties!==!1}function JY(e,t,r){let n=KY(e);if(!n||n.type!==void 0&&!WY(n,"object"))return`Input schema is unavailable for ${r}.`;let i=n.properties??{};if(n.additionalProperties!==!0){for(let s of Object.keys(t))if(!Object.prototype.hasOwnProperty.call(i,s)){let a=Object.keys(i),c=a.length>0?` Expected: ${a.join(", ")}.`:"";return`Unknown parameter "${s}" for ${r}.${c}`}}let o=(n.required??[]).filter(s=>!Object.prototype.hasOwnProperty.call(t,s)||t[s]===void 0);if(o.length>1)return`${o.join(", ")} are required for ${r}.`;for(let s of n.required??[]){if(!Object.prototype.hasOwnProperty.call(t,s)||t[s]===void 0)return`${s} is required for ${r}.`;if(t[s]===null)return`${s} cannot be null.`;if(typeof t[s]=="string"&&t[s].trim()==="")return`${s} cannot be empty.`}for(let[s,a]of Object.entries(t)){let c=i[s];if(!c||a===void 0||a===null)continue;let u=LA(s,a,c);if(u)return u}return null}var M1t=[{type:"integer",matches:e=>typeof e=="number"&&Number.isInteger(e),phrase:"an integer"},{type:"number",matches:e=>typeof e=="number"&&Number.isFinite(e),phrase:"a number"},{type:"string",matches:e=>typeof e=="string",phrase:"a string"},{type:"boolean",matches:e=>typeof e=="boolean",phrase:"a boolean"},{type:"array",matches:e=>Array.isArray(e),phrase:"an array"},{type:"object",matches:e=>typeof e=="object"&&e!==null&&!Array.isArray(e),phrase:"an object"}];function D1t(e,t){let n=(Array.isArray(t.type)?t.type:t.type!==void 0?[t.type]:[]).flatMap(o=>M1t.filter(s=>s.type===o)),i=new Set(n.filter(o=>o.matches(e)).map(o=>o.type));return{declared:n,matched:i}}function LA(e,t,r){if(r.enum&&!r.enum.includes(t))return`${e} must be one of: ${r.enum.map(String).join(", ")}.`;let{declared:n,matched:i}=D1t(t,r);if(n.length>0&&i.size===0)return`${e} must be ${n.map(o=>o.phrase).join(" or ")}.`;if(i.has("string")&&typeof t=="string"){if(t.trim()==="")return`${e} cannot be empty.`;if(r.minLength!==void 0&&t.length<r.minLength)return`${e} is too short.`;if(r.maxLength!==void 0&&t.length>r.maxLength)return`${e} is too long.`}if(typeof t=="number"){if(r.minimum!==void 0&&t<r.minimum)return`${e} must be at least ${r.minimum}.`;if(r.maximum!==void 0&&t>r.maximum)return`${e} must be at most ${r.maximum}.`}return null}function B3e(e,t){let r={unknown_params:[],missing_required:[],invalid_params:[]},n=KY(e);if(!n||n.type!==void 0&&!WY(n,"object"))return r;let i=n.properties??{};if(n.additionalProperties!==!0)for(let s of Object.keys(t))Object.prototype.hasOwnProperty.call(i,s)||r.unknown_params.push(s);let o=new Set;for(let s of n.required??[])!Object.prototype.hasOwnProperty.call(t,s)||t[s]===void 0?r.missing_required.push(s):(t[s]===null||typeof t[s]=="string"&&t[s].trim()==="")&&o.add(s);for(let[s,a]of Object.entries(t)){let c=i[s];!c||a===void 0||a===null||LA(s,a,c)&&o.add(s)}return r.invalid_params=[...o],r}function eB(e,t,r){if(GY(e))return{success:!1,error_code:"SCHEMA_UNAVAILABLE",code:"SCHEMA_UNAVAILABLE",error:`Cannot run paid platform tool '${r}' because its input schema is unavailable. Ask the provider to publish a request schema before running this paid direct tool.`,tool_id:r};let n=JY(e,t,r);return n?{success:!1,error_code:"INVALID_TOOL_PARAMS",code:"INVALID_TOOL_PARAMS",error:n,message:n,tool_id:r,violations:B3e(e,t)}:null}async function Ep(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 tB=class extends Error{code="ATTESTATION_KEY_DRIFT";hint;constructor(t,r){super(t),this.name="AttestationDriftError",this.hint=r}},Iw=class extends Error{code;budgetId;status;constructor(t,r,n={}){super(t),this.name="SessionInvalidError",this.code=r,this.budgetId=n.budgetId,this.status=n.status}},qm=class extends Error{code="SESSION_LOCK_CONTENDED";retryAfterSecs;status;constructor(t,r=1,n){super(t),this.name="SessionLockContendedError",this.retryAfterSecs=r,this.status=n}},Ap=class extends Error{code="PARENTLESS_NOT_ENABLED";status;serverErrorCode;constructor(t,r={}){super(t),this.name="ParentlessNotEnabledError",this.status=r.status,this.serverErrorCode=r.serverErrorCode}},Oi=class extends Error{retryable;code;reason;paymentErrorClass;correlationId;transactionId;retryAfter;constructor(t,r,n,i,o,s,a,c){super(t),this.name="CardDeclinedError",this.retryable=r,this.code=n,this.reason=i,this.paymentErrorClass=o,this.correlationId=s,this.transactionId=a,this.retryAfter=c}},lh=class extends Error{code;transactionId;retryable;reconciliationRequired;constructor(t,r,n={}){super(t),this.name="TopupAmbiguousError",this.code=r,this.transactionId=n.transactionId,this.retryable=n.retryable??!1,this.reconciliationRequired=n.reconciliationRequired??!0}};var N3e={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 Cw(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&&N3e[r]?N3e[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.`}ea();nB();var V1t="visa-cli setup",K1t="visa-cli agent enroll";function QY(e=process.env){return Um(e)!==null}function eZ(e=QY()){return e?`Note: \`${V1t}\` signs in to your Visa CLI account \u2014 separate from your v4 agent + card, which you set up with \`${K1t}\`.`:""}var W1t=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function D3e(e,t){let r=M3e(e),n=M3e(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:G1t(r.pre,n.pre)>0}function M3e(e){if(typeof e!="string")return null;let r=e.trim().replace(/^v/,"").match(W1t);return r?{main:[Number(r[1]),Number(r[2]),Number(r[3])],pre:r[4]??null}:null}function G1t(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 iB(){return!!(L3e(process.env.VISA_CLI_NO_UPDATE_CHECK)||L3e(process.env.CI)||process.env.NODE_ENV==="test")}function L3e(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}Qd();var oht="CARD_REENROLLMENT_REQUIRED",sht="https://auth.visacli.sh/enroll-card";function aht(){try{return new URL("/enroll-card",ta()).toString()}catch{return sht}}function cht(e){let t=aht();if(typeof e!="string")return t;try{let r=new URL(e),n=new URL(t);if(r.origin===n.origin&&r.pathname==="/enroll-card")return r.toString()}catch{}return W.warn("card-reenroll:reenroll_url_rejected_fallback",{reason:"untrusted_or_malformed_reenroll_url",fallbackPath:"/enroll-card"}),t}var fh="4.1.0-rc.25",uht=/^(?:VisaKey_[A-Za-z0-9_-]{16,128}|visakey_[A-Za-z0-9_-]{16,128}|vk_[A-Za-z0-9_-]{32,128})$/;async function KA(e){let t=null;try{t=await e.json()}catch{}if(t&&(t.error_code==="TOOL_UPSTREAM_AUTH_FAILED"||typeof t.upstream_status=="number"))return new Error(typeof t.error=="string"&&t.error?t.error:"The tool upstream rejected the request credentials.");let r=eZ();return new Error("Your session has expired. Run: visa-cli setup"+(r?`
|
|
20654
20654
|
${r}`:""))}function WA(e,t){let r=typeof t?.error=="string"&&t.error||typeof t?.message=="string"&&t.message||"";return r?new Error(r):e>=500||e===408||e===425||e===429?new Error(`Request failed (${e}). Try again.`):e===404?new Error(`Request failed (${e}) \u2014 not found; check the identifier or slug.`):new Error(`Request failed (${e}).`)}function dht(e){if(typeof e!="string")return null;switch(e){case"BUDGET_CLOSED":case"BUDGET_NOT_FOUND":case"BUDGET_EXPIRED":return e;default:return null}}function aZ(e){return e==="TOPUP_CHARGE_AMBIGUOUS"||e==="TOPUP_RECONCILIATION_REQUIRED"?e:null}var lht="Visa CLI is temporarily unavailable. Try again, or report at https://github.com/Visa-Crypto-Labs/Visa-mono/issues if it persists.";function Rw(e){return typeof e=="string"?e.trim():""}function GA(e){let t=e&&typeof e=="object"?e:{},r=Rw(t.error)||Rw(t.message);if(!r)return lht;let n=Rw(t.error_code),i=[["surface",Rw(t.disabled_surface)],["flag",Rw(t.flag)],["correlation_id",Rw(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 JA(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();if(n)uht.test(n)?(r.push("VISA_CLI_API_KEY is set, but MCP bearer tools currently require a local session from visa-cli setup."),r.push("For headless API-key use, call the /v1/api/* HTTP routes with X-Api-Key instead of MCP bearer tools.")):(r.push("VISA_CLI_API_KEY is set but has invalid format (expected VisaKey_<...> or legacy vk_<...>)."),r.push("Create a new Visa Key with: visa-cli keys create <app-name>"));else{r.push("Run `visa-cli setup` in an interactive terminal to authenticate.");let i=eZ(QY(e));i&&r.push(i)}return t===!1&&r.push("This process appears to be running without a TTY; complete setup in a normal terminal, then restart the MCP client."),r.join(`
|
|
20655
20655
|
`)}var lB=class{constructor(t){this.getSessionToken=t;this.baseUrl=ta()}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!iB()){let n=t.headers.get("X-Latest-Version");n&&D3e(n,fh)&&(this.lastSignals.updateAvailable={currentVersion:fh,latestVersion:n})}let r=t.headers.get("X-Feedback-Prompt");if(r)try{this.lastSignals.feedbackPrompt=JSON.parse(r)}catch{}}getClientVersion(){return fh}throwIfAttestationDrift(t){if(t?.error_code==="ATTESTATION_KEY_DRIFT")throw new tB(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(GA(r))}async request(t,r,n,i,o,s){let a=await this.getSessionToken();if(!a)throw new Error(JA());let c={Authorization:`Bearer ${a}`};o&&(t==="GET"?c["X-User-Context"]=encodeURIComponent(o.replace(/[\r\n\0]/g," ").slice(0,1e3)):n={...n||{},user_context:o}),s&&(c["X-Visa-Meta-Tool"]=s),n&&(c["Content-Type"]="application/json");let u;try{u=await Ep(`${this.baseUrl}${r}`,{method:t,headers:{...c,"X-Visa-CLI-Version":fh,"X-Source":"cli"},body:n?JSON.stringify(n):void 0,timeoutMs:i})}catch(l){throw new Error(Cw(l))}if(this.parseServerSignals(u),u.status===401)throw await KA(u);if(u.status===429){let l=u.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${l}s. Tip: use the batch tool to combine multiple requests into one.`)}u.status===503&&await this.throwServerUnavailable(u);let d;try{d=await u.json()}catch{throw u.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(!u.ok){if(u.status===500)throw new Error(`Server error on ${r}. Try again or check https://visacli.sh for status.`);if(this.throwIfAttestationDrift(d),typeof d?.error_code=="string"&&d.error_code===oht){let p=typeof d?.last4=="string"?d.last4:"",f=typeof d?.brand=="string"?d.brand:"card",m=cht(d?.reenroll_url),h=p?`${f} ending in ${p}`:"your card";throw new Error(`Please re-add ${h} to keep payments running. Open: ${m}`)}let l=aZ(d?.error_code);if(l)throw new lh(d?.error||"Top-up status pending \u2014 check transaction_history in 5 minutes or contact support.",l,{transactionId:typeof d?.transactionId=="string"?d.transactionId:void 0,retryable:!!d?.retryable,reconciliationRequired:d?.reconciliation_required!==!1});if(d?.declined){let p=Number(d.retryAfter??u.headers.get("Retry-After"));throw new Oi(d.error||"Your card was declined.",!!d.retryable,d.code,d.reason,d.payment_error_class,d.correlation_id,d.transactionId,Number.isFinite(p)&&p>0?p:void 0)}if(u.status===402){let p=d?.error||"Gateway returned 402",f=typeof d?.error_code=="string"?d.error_code:"";throw f==="SPENDING_LIMIT_EXCEEDED"||f==="DAILY_LIMIT_EXCEEDED"||f==="PER_TXN_LIMIT_EXCEEDED"?new Error(`${p}. Check your limits with get_status or run: visa-cli update-spending-controls`):new Error(p)}throw WA(u.status,d)}return d}async shortcut(t,r,n,i,o){return this.request("POST",`/v1/shortcuts/${encodeURIComponent(t)}`,r,n,i,o)}async shortcutWithSession(t,r,n,i,o,s){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,c=await this.getSessionToken();if(!c)throw new Error(JA());let u={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":fh,"X-Source":"cli","Content-Type":"application/json"};s&&(u["X-Visa-Meta-Tool"]=s);let d={...r,...n};o&&(d.user_context=o.replace(/[\r\n\0]/g," ").slice(0,1e3));let l;try{l=await Ep(`${this.baseUrl}${a}`,{method:"POST",headers:u,body:JSON.stringify(d),timeoutMs:i})}catch(m){throw new Error(Cw(m))}if(this.parseServerSignals(l),l.status===401)throw await KA(l);if(l.status===429){let m=l.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${m}s. Tip: use the batch tool to combine multiple requests into one.`)}let p=l.headers.get("X-Voucher-Receipt"),f;try{f=await l.json()}catch{throw l.status===500?new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`):l.status===503?new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status."):new Error(`Unexpected response from ${a}. Try again.`)}if(!l.ok){if(l.status===500)throw new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`);if(this.throwIfAttestationDrift(f),l.status===503){if(f?.error_code==="SESSION_LOCK_CONTENDED"){let y=Number(l.headers.get("Retry-After"))||1;throw new qm(f?.message||f?.error||"Session budget is being modified by another request. Retry shortly.",y,l.status)}throw new Error(GA(f))}let m=dht(f?.error_code);if(m||l.status===410){let y=m??"BUDGET_CLOSED";throw new Iw(f?.message||f?.error||"Your session was invalidated by the server.",y,{budgetId:r.session_budget_id,status:l.status})}if(f?.declined){let y=Number(f.retryAfter??l.headers.get("Retry-After"));throw new Oi(f.error||"Your card was declined.",!!f.retryable,f.code,f.reason,f.payment_error_class,f.correlation_id,f.transactionId,Number.isFinite(y)&&y>0?y:void 0)}let h=aZ(f?.error_code);throw h?new lh(f?.error||"Top-up status pending \u2014 check transaction_history in 5 minutes or contact support.",h,{transactionId:typeof f?.transactionId=="string"?f.transactionId:void 0,retryable:!!f?.retryable,reconciliationRequired:f?.reconciliation_required!==!1}):WA(l.status,f)}return{data:f,voucherReceiptHeader:p}}async shortcutParentless(t,r,n,i,o,s){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,c=await this.getSessionToken();if(!c)throw new Error(JA());let u={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":fh,"X-Source":"cli","Content-Type":"application/json"};s&&(u["X-Visa-Meta-Tool"]=s);let d={...n,...r.attestation?{attestation:r.attestation}:{},nonce:r.nonce,approved_max_cents:r.approved_max_cents,idempotency_key:r.idempotency_key,...r.stream===!0?{stream:!0}:{}};o&&(d.user_context=o.replace(/[\r\n\0]/g," ").slice(0,1e3));let l;try{l=await Ep(`${this.baseUrl}${a}`,{method:"POST",headers:u,body:JSON.stringify(d),timeoutMs:i})}catch(m){throw new Error(Cw(m))}if(this.parseServerSignals(l),l.status===401)throw await KA(l);if(l.status===429){let m=l.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${m}s. Tip: use the batch tool to combine multiple requests into one.`)}let p=l.headers.get("X-Voucher-Receipt"),f;try{f=await l.json()}catch{throw l.status===500?new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`):l.status===503?new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status."):l.status===404?new Ap("Parentless single-call is not available on this server.",{status:404}):new Error(`Unexpected response from ${a}. Try again.`)}if(!l.ok){if(l.status===500)throw new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`);this.throwIfAttestationDrift(f);let m=typeof f?.error_code=="string"?f.error_code:void 0;if(l.status===410&&m==="DIRECT_SHORTCUT_CARD_SURFACE_RETIRED")throw new Ap(f?.error||"Parentless single-call is not enabled on this server.",{status:l.status,serverErrorCode:m});if(l.status===503){if(f?.error_code==="SESSION_LOCK_CONTENDED"){let y=Number(l.headers.get("Retry-After"))||1;throw new qm(f?.message||f?.error||"Session budget is being modified by another request. Retry shortly.",y,l.status)}throw new Error(GA(f))}if(f?.declined){let y=Number(f.retryAfter??l.headers.get("Retry-After"));throw new Oi(f.error||"Your card was declined.",!!f.retryable,f.code,f.reason,f.payment_error_class,f.correlation_id,f.transactionId,Number.isFinite(y)&&y>0?y:void 0)}let h=aZ(f?.error_code);throw h?new lh(f?.error||"Top-up status pending \u2014 check transaction_history in 5 minutes or contact support.",h,{transactionId:typeof f?.transactionId=="string"?f.transactionId:void 0,retryable:!!f?.retryable,reconciliationRequired:f?.reconciliation_required!==!1}):WA(l.status,f)}return{data:f,voucherReceiptHeader:p}}async batchOpen(t){let r="/v1/batch/open",n=await this.getSessionToken();if(!n)throw new Error(JA());let i={Authorization:`Bearer ${n}`,"X-Visa-CLI-Version":fh,"X-Source":"cli","Content-Type":"application/json"},o={...t.attestation?{attestation:t.attestation}:{},nonce:t.nonce,approved_total_cents:t.approved_total_cents,batch_id:t.batch_id},s;try{s=await Ep(`${this.baseUrl}${r}`,{method:"POST",headers:i,body:JSON.stringify(o),timeoutMs:void 0})}catch(d){throw new Error(Cw(d))}if(this.parseServerSignals(s),s.status===401)throw await KA(s);if(s.status===429){let d=s.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${d}s before opening another batch.`)}let a;try{a=await s.json()}catch{throw s.status===500?new Error(`Server error on ${r}. Try again or check https://visacli.sh for status.`):s.status===503?new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status."):s.status===404?new Ap("Parentless batch is not available on this server.",{status:404}):new Error(`Unexpected response from ${r}. Try again.`)}if(!s.ok){if(s.status===500)throw new Error(`Server error on ${r}. Try again or check https://visacli.sh for status.`);this.throwIfAttestationDrift(a);let d=typeof a?.error_code=="string"?a.error_code:void 0;if(s.status===410&&d==="DIRECT_SHORTCUT_CARD_SURFACE_RETIRED")throw new Ap(a?.error||"Parentless batch is not enabled on this server.",{status:s.status,serverErrorCode:d});if(s.status===503)throw new Error(GA(a));if(a?.declined){let l=Number(a.retryAfter??s.headers.get("Retry-After"));throw new Oi(a.error||"Your card was declined.",!!a.retryable,a.code,a.reason,a.payment_error_class,a.correlation_id,a.transactionId,Number.isFinite(l)&&l>0?l:void 0)}throw WA(s.status,a)}let c=a?.parent_spend_execution_id??a?.batch_parent_id??a?.parent_id??a?.spend_execution_id,u=a?.idempotency_scope??a?.idempotency_key_scope??t.batch_id;if(typeof c!="string"||c.length===0)throw new Error(`Batch open returned no parent id from ${r}. Try again.`);return{batch_parent_id:c,idempotency_scope:String(u)}}async shortcutParentlessBatchItem(t,r,n,i,o,s){let a=`/v1/shortcuts/${encodeURIComponent(t)}`,c=await this.getSessionToken();if(!c)throw new Error(JA());let u={Authorization:`Bearer ${c}`,"X-Visa-CLI-Version":fh,"X-Source":"cli","Content-Type":"application/json"};s&&(u["X-Visa-Meta-Tool"]=s);let d={...n,batch_parent_id:r.batch_parent_id,batch_id:r.batch_id,batch_index:r.batch_index,batch_request_hash:r.batch_request_hash,item_ceiling_cents:r.item_ceiling_cents,idempotency_key:r.idempotency_key,...r.stream===!0?{stream:!0}:{}};o&&(d.user_context=o.replace(/[\r\n\0]/g," ").slice(0,1e3));let l;try{l=await Ep(`${this.baseUrl}${a}`,{method:"POST",headers:u,body:JSON.stringify(d),timeoutMs:i})}catch(m){throw new Error(Cw(m))}if(this.parseServerSignals(l),l.status===401)throw await KA(l);if(l.status===429){let m=l.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${m}s. Tip: use the batch tool to combine multiple requests into one.`)}let p=l.headers.get("X-Voucher-Receipt"),f;try{f=await l.json()}catch{throw l.status===500?new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`):l.status===503?new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status."):new Error(`Unexpected response from ${a}. Try again.`)}if(!l.ok){if(l.status===500)throw new Error(`Server error on ${a}. Try again or check https://visacli.sh for status.`);if(this.throwIfAttestationDrift(f),l.status===503){if(f?.error_code==="SESSION_LOCK_CONTENDED"){let m=Number(l.headers.get("Retry-After"))||1;throw new qm(f?.message||f?.error||"Batch parent is being modified by another request. Retry shortly.",m,l.status)}throw new Error(GA(f))}if(f?.declined){let m=Number(f.retryAfter??l.headers.get("Retry-After"));throw new Oi(f.error||"Your card was declined.",!!f.retryable,f.code,f.reason,f.payment_error_class,f.correlation_id,f.transactionId,Number.isFinite(m)&&m>0?m:void 0)}throw WA(l.status,f)}return{data:f,voucherReceiptHeader:p}}async emitTelemetry(t){return this.request("POST","/v1/telemetry",{rows:t})}async catalogSearch(t,r,n,i){let o=n??"discover_tools",s=new URLSearchParams;t&&s.set("q",t),r&&s.set("category",r),i?.limit!=null&&s.set("limit",String(i.limit)),i?.offset!=null&&s.set("offset",String(i.offset));let a=s.toString();return this.request("GET",`/v1/catalog${a?`?${a}`:""}`,void 0,void 0,void 0,o)}async catalogTool(t,r){let n=r??"discover_tools";try{return await this.request("GET",`/v1/catalog/${encodeURIComponent(t)}`,void 0,void 0,void 0,n)}catch{return null}}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 discoverMerchantRoutes(t){try{return await this.request("GET",`/v1/platform/discover/${encodeURIComponent(t)}`)}catch{return null}}async listPublicMerchants(){try{let t=await Ep(`${this.baseUrl}/v1/platform/merchants/public`,{method:"GET",timeoutMs:8e3});if(!t.ok)return[];let r=await t.json();return Array.isArray(r.merchants)?r.merchants:[]}catch{return[]}}async getPublicMerchantDiscover(t){try{let r=await Ep(`${this.baseUrl}/v1/platform/discover/${encodeURIComponent(t)}`,{method:"GET",timeoutMs:8e3});return r.ok?await r.json():null}catch{return null}}async paymentPreview(t,r){return this.request("POST","/v1/payment-preview",t,void 0,r)}async getBalance(){return this.request("GET","/v1/balance")}async topupBalance(t){return this.request("POST","/v1/balance/topup",t)}async createEnrollCode(){return this.request("POST","/v1/enroll-code")}async getAutoTopup(){let t=await this.getBalance();return{success:t.success,targetCents:t.autoTopupCents??null,thresholdCents:t.autoTopupThresholdCents??0}}async disableAutoTopup(){return this.request("PATCH","/v1/balance/auto-topup",{auto_topup_cents:null})}async createSessionBudget(t){return this.request("POST","/v1/session-budget/create",{...t,mode:"prepaid"})}async closeSession(t){return this.request("POST","/v1/session/close",{session_budget_id:t})}async getSessionBudget(t){return this.request("GET",`/v1/session-budget/${encodeURIComponent(t)}`)}async getSessionLedger(t){return this.request("GET",`/v1/session/${encodeURIComponent(t)}/ledger`)}async getStatus(t){return this.request("GET","/v1/status",void 0,void 0,t)}async getFeatureFlags(){return this.request("GET","/v1/feature-flags")}async getVisaSmi(t,r){return this.request("POST","/v1/visa/smi",t,6e4,r)}async getTransactions(t,r){let n=new URLSearchParams;t?.limit!=null&&n.set("limit",String(t.limit)),t?.offset!=null&&n.set("offset",String(t.offset));let i=n.toString(),o=i?`/v1/transactions?${i}`:"/v1/transactions";return this.request("GET",o,void 0,void 0,r)}async updateSpendingControls(t,r){return this.request("POST","/v1/spending-controls",t,void 0,r)}async removeCard(t,r,n){return this.request("DELETE",`/v1/cards/${encodeURIComponent(String(t))}`,r,void 0,n)}async setDefaultCard(t,r,n){return this.request("POST",`/v1/cards/${encodeURIComponent(String(t))}/default`,r,void 0,n)}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","/v1/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 feedSubmit(t){return this.request("POST","/v1/feed",t)}async feedList(t){let r=new URLSearchParams;t?.tab&&r.set("tab",t.tab),t?.limit&&r.set("limit",String(t.limit)),t?.offset&&r.set("offset",String(t.offset));let n=r.toString();return this.request("GET",`/v1/feed${n?"?"+n:""}`)}async feedVote(t,r){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/vote`,{direction:r})}async feedApprove(t){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/approve`)}async feedDelete(t){return this.request("DELETE",`/v1/feed/${encodeURIComponent(t)}`)}async feedPending(){return this.request("GET","/v1/feed/pending")}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)}};nB();var bY=qe(Sp());var bZ=require("child_process"),S9e=require("util"),T9e=qe(require("crypto")),Hr=qe(require("fs")),P9e=qe(require("os")),_s=qe(require("path"));ea();fB();XA();var Pp=(0,S9e.promisify)(bZ.execFile),Jht=6e4,Yht=()=>process.platform==="darwin",M2=()=>process.platform==="win32",gh=_s.join(P9e.homedir(),".visa-mcp","bin"),U2=_s.join(gh,"Visa CLI"),zm=_s.join(gh,"visa-keychain-win.exe"),I9e=_s.join(__dirname,"..","native"),y9e="6",g9e=_s.join(gh,"visa-keychain.version"),b9e=_s.join(gh,"visa-keychain.sha256"),_9e="1",v9e=_s.join(gh,"visa-keychain-win.version"),w9e=_s.join(gh,"visa-keychain-win.sha256"),C9e=[_s.join(I9e,"bin","win32-x64","visa-keychain-win.exe"),_s.resolve(__dirname,"..","..","native","bin","win32-x64","visa-keychain-win.exe"),_s.resolve(__dirname,"..","native","bin","win32-x64","visa-keychain-win.exe")];function bB(e){let t=Hr.readFileSync(e);return T9e.createHash("sha256").update(t).digest("hex")}function Zht(e){let t=e.trim();if(t.startsWith("OK:"))return t.slice(3);if(t==="OK")return;let r=t.startsWith("ERROR:")?t.slice(6):"Unknown error";throw new Error(r)}function x9e(e){let t=typeof e?.message=="string"?e.message:"";return e?.code==="ETIMEDOUT"||e?.killed===!0||/timed out|timeout/i.test(t)}function E9e(e){let t=Math.max(1,Math.round(e/1e3));return new Error(`Timed out waiting for Touch ID/device approval after ${t}s.`)}async function O9e(){try{if(Hr.readFileSync(g9e,"utf-8").trim()===y9e&&Hr.existsSync(U2)){let n=Hr.readFileSync(b9e,"utf-8").trim();if(bB(U2)!==n)W.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),Hr.unlinkSync(U2);else return U2}}catch{}let e=_s.join(I9e,"visa-keychain.m");if(Hr.existsSync(e)||(e=_s.resolve(__dirname,"..","..","native","visa-keychain.m")),Hr.existsSync(e)||(e=_s.resolve(__dirname,"..","native","visa-keychain.m")),!Hr.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");Hr.mkdirSync(gh,{recursive:!0,mode:448});try{await Pp("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",U2,e],{timeout:3e4})}catch(r){throw r.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):r}let t=bB(U2);return Hr.writeFileSync(b9e,t,{mode:384}),Hr.writeFileSync(g9e,y9e,{mode:384}),U2}function R9e(){for(let e of C9e)if(Hr.existsSync(e))return e;return null}async function QA(){try{if(Hr.readFileSync(v9e,"utf-8").trim()===_9e&&Hr.existsSync(zm)){let n=Hr.readFileSync(w9e,"utf-8").trim();if(bB(zm)!==n)W.warn("binary:hash-mismatch:win32",{message:"Windows binary hash mismatch. Redeploying."}),Hr.unlinkSync(zm);else return zm}}catch{}let e=R9e();if(!e)throw new Error(`visa-keychain-win.exe not found in package. Reinstall @visa/cli.
|
|
20656
20656
|
If building from source, run native/build-win.bat first.`);Hr.mkdirSync(gh,{recursive:!0}),Hr.copyFileSync(e,zm);let t=bB(zm);return Hr.writeFileSync(w9e,t,{mode:384}),Hr.writeFileSync(v9e,_9e,{mode:384}),zm}async function Xht(){return M2()?QA():O9e()}var _B="visa-cli",vB="attestation-key";async function Qht(e){if(!await Tp())throw new Error("macOS Keychain is unavailable in this environment (no default keychain), so the Touch ID key cannot be stored. Run this command in a regular user session.");try{await Pp("security",["delete-generic-password","-s",_B,"-a",vB],{timeout:5e3})}catch{}try{await Pp("security",["add-generic-password","-s",_B,"-a",vB,"-w",e],{timeout:5e3})}catch(t){throw new Error(`Could not store the Touch ID key in the macOS Keychain (${eyt(t)}).`)}}function eyt(e){let t=e,r=[t?.stderr,t?.message].filter(n=>typeof n=="string").join(" ").toLowerCase();return/canceled|cancelled/.test(r)?"the Keychain authorization was canceled":/locked/.test(r)?"the Keychain is locked":/not permitted|permission denied|not authorized/.test(r)?"Keychain access was denied":/could not be found|no default keychain/.test(r)?"no default keychain was found":"the security tool reported an error"}function tyt(e){let t=typeof e?.code=="number"?e.code:void 0,r=typeof e?.stderr=="string"?e.stderr:"",n=typeof e?.stdout=="string"?e.stdout:"",i=[r,n,e?.message].filter(Boolean).join(" ").trim();return t===44||/could not be found|item(?: was)? not found|no such keychain item|not found/i.test(i)?{state:"absent",usable:!1,message:"No local attestation key was found."}:/user interaction is not allowed|user canceled|user cancelled|authorization failed|interaction not allowed|keychain.*locked|denied|not authorized/i.test(i)?{state:"denied",usable:!1,message:"The local attestation key exists but Keychain access was denied or unavailable."}:{state:"error",usable:!1,message:i||"Could not read the local attestation key from Keychain."}}async function ryt(){if(!await Tp())return{key:null,status:{state:"denied",usable:!1,message:"macOS Keychain is unavailable in this environment (no default keychain)."}};try{let{stdout:e}=await Pp("security",["find-generic-password","-s",_B,"-a",vB,"-w"],{timeout:5e3}),t=e.trim();return t?{key:t,status:{state:"present",usable:!0}}:{key:null,status:{state:"absent",usable:!1,message:"No local attestation key was found."}}}catch(e){return{key:null,status:tyt(e)}}}async function k9e(){let e=await ryt();if(e.key)return e.key;if(e.status.state==="absent")return null;throw new Error(e.status.message||"Could not read the local attestation key from Keychain.")}async function B9e(e){let t=await Xht(),r;try{r=(await Pp(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 Zht(r)}var A9e=!1;function nyt(){if(!M2())return!1;try{return Hr.existsSync(zm)||R9e()!==null?!0:(A9e||(A9e=!0,W.warn("binary:missing:win32",{message:"visa-keychain-win.exe not found; Windows Hello attestation unavailable on this install.",binPath:zm,searchedPrebuiltPaths:C9e})),!1)}catch{return!1}}function rl(){return YA()||Yht()?!0:M2()?nyt():!1}async function N9e(){if(M2()){let i=await QA(),{stdout:o}=await Pp(i,["generate-key"],{timeout:3e4}),s=o.trim();if(s.startsWith("OK:"))return s.slice(3);throw new Error(s.startsWith("ERROR:")?s.slice(6):"Key generation failed")}let e=await B9e(["generate-key"]);if(!e)throw new Error("Key generation returned no output");let t=e.indexOf(":");if(t<0)throw new Error("Unexpected generate-key output format");let r=e.slice(0,t),n=e.slice(t+1);return await Qht(r),n}async function j9e(){if(M2())try{let e=await QA(),{stdout:t}=await Pp(e,["public-key"],{timeout:1e4});return t.trim().startsWith("OK:")}catch{return!1}return await k9e()!==null}async function q9e(e,t,r={}){if(YA())return Promise.resolve(p9e());let n=r.timeoutMs??Jht;if(M2()){let a=await QA(),c=["sign",e];t&&c.push(t);let u;try{u=(await Pp(a,c,{timeout:n})).stdout}catch(l){throw x9e(l)?E9e(n):l}let d=u.trim();if(d.startsWith("OK:"))return d.slice(3);throw new Error(d.startsWith("ERROR:")?d.slice(6):"Unknown error")}let i=await k9e();if(!i)throw new Error("Attestation key not found. Run setup to generate a new key.");let o=await O9e(),s=["sign",e];return t&&s.push(t),new Promise((a,c)=>{let u=(0,bZ.execFile)(o,s,{timeout:n},(d,l)=>{let p=(l||"").trim();if(d){p.startsWith("ERROR:")?c(new Error(p.slice(6))):x9e(d)?c(E9e(n)):c(new Error(d.stderr?.toString().trim()||d.message||"Unknown error"));return}p.startsWith("OK:")?a(p.slice(3)):c(new Error(p.startsWith("ERROR:")?p.slice(6):"Unknown error"))});u.stdin.write(i),u.stdin.end()})}async function U9e(){if(M2()){try{let e=await QA();await Pp(e,["delete-key"],{timeout:1e4})}catch{}return}if(await Tp())try{await Pp("security",["delete-generic-password","-s",_B,"-a",vB],{timeout:5e3})}catch{}try{await B9e(["delete-key"])}catch{}}XA();ea();var iyt=["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card"],oyt=[...iyt.map(e=>({id:`legacy.${e}`,toolId:e,targetToolId:e,rail:"tempo",reason:"Preserve legacy Tempo _card target while the top-level MCP surface is opt-in."}))];function _Z(e,t=oyt){for(let r of t)if(r.toolId===e.requestedTool)return r.targetToolId;return null}xZ();g4e();function b4e(e=process.env){let t=e.VISA_DRY_RUN;return t==="true"||t==="1"||t==="mock"?"mock":t==="preflight"?"preflight":null}function Ydt(e=process.env){return b4e(e)!==null}var Iwr=new Set(["false","0","no","off","disable","disabled"]),Cwr=new Set(["true","1","yes","on","enable","enabled"]);function Zdt(e){let t=(e??"").trim().toLowerCase();return t?Iwr.has(t)?!1:!!Cwr.has(t):!0}function Xdt(e=process.env){return Zdt(e.VISA_CLI_PARENTLESS_SINGLE_CALL)}function Qdt(e=process.env){return Zdt(e.VISA_CLI_PARENTLESS_BATCH)}var Lft=require("child_process"),jo=qe(require("crypto")),bp=qe(require("fs")),Mk=qe(require("os")),_Y=qe(require("path"));var Am=qe(require("fs")),NJ=qe(require("os")),mp=qe(require("path"));var Owr="# >>> visa-cli shell hud v2 >>>",Rwr="# <<< visa-cli shell hud v2 <<<",kwr="# >>> visa-cli shell hud >>>",Bwr="# <<< visa-cli shell hud <<<";function Nwr(e){let t=e??process.env.SHELL;if(!t)return null;let r=mp.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 jwr(e){let t=Lwr();if(e==="zsh")return mp.join(t,".zshrc");if(e==="bash")return mp.join(t,".bashrc");let r=(process.platform==="win32","PowerShell");return mp.join(t,"Documents",r,"Microsoft.PowerShell_profile.ps1")}function qwr(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 Uwr(e,t,r){let n=new RegExp(`(^|\\n)([ \\t]*${elt(t)}[ \\t]*\\r?\\n)([\\s\\S]*?)(\\r?\\n[ \\t]*${elt(r)}[ \\t]*)(?=\\r?\\n|$)(\\r?\\n)?`,"g");return e.replace(n,(i,o,s,a,c,u,d)=>{if(!qwr(a))return i;let l=d>0?e[d-1]:"";return o===`
|
|
20657
20657
|
`&&l!==`
|
|
20658
20658
|
`?`
|
|
20659
|
-
`:""})}function Mwr(e){let t=e;for(let[r,n]of[[Owr,Rwr],[kwr,Bwr]])t=Uwr(t,r,n);return t.trimEnd()}function Dwr(e){return Mwr(e)!==e.trimEnd()}function jJ(e=Nwr()){if(!e)return!1;try{let t=jwr(e),r=Am.readFileSync(t,"utf-8");return Dwr(r)}catch{return!1}}function elt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Lwr(){let e=NJ.homedir();if(!e||!mp.isAbsolute(e))throw new Error("unable to determine a valid home directory");return mp.resolve(e)}var Mwn=1440*60*1e3;var Hwr="# visa-cli-hud-v1";function tlt(e){return typeof e!="string"?!1:e.includes(Hwr)?!0:e.includes("visa-cli")&&e.includes("statusline")}var qJ=qe(require("fs")),rlt=qe(require("os")),_4e=qe(require("path")),zwr=[{prefix:"iVBORw0KGgo",sig:{mime:"image/png",ext:"png"}},{prefix:"/9j/",sig:{mime:"image/jpeg",ext:"jpg"}},{prefix:"R0lGOD",sig:{mime:"image/gif",ext:"gif"}},{prefix:"UklGR",sig:{mime:"image/webp",ext:"webp"}}],Fwr=/^data:(image\/(png|jpeg|jpg|gif|webp));base64,([A-Za-z0-9+/=]+)$/;function v4e(e){if(typeof e!="string"||e.length===0)return null;let t=e.trim(),r=Fwr.exec(t);if(r){let i=r[2]==="jpg"?"jpeg":r[2],o=i==="png"?{mime:"image/png",ext:"png"}:i==="jpeg"?{mime:"image/jpeg",ext:"jpg"}:i==="gif"?{mime:"image/gif",ext:"gif"}:{mime:"image/webp",ext:"webp"};return{base64:r[3],sig:o}}if(!/^[A-Za-z0-9+/=\s]+$/.test(t)||t.length<64)return null;let n=t.replace(/\s+/g,"");for(let{prefix:i,sig:o}of zwr)if(n.startsWith(i))return{base64:n,sig:o};return null}function nlt(e,t={}){let r=t.outputDir??_4e.join(rlt.tmpdir(),"visa-cli");qJ.mkdirSync(r,{recursive:!0});let n=(t.tag??"media").toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"media",i=new Date().toISOString().replace(/[:.]/g,"-"),o=_4e.join(r,`${n}-${i}.${e.sig.ext}`),s=Buffer.from(e.base64,"base64");return qJ.writeFileSync(o,s,{mode:384}),{filePath:o,bytes:s.length,mime:e.sig.mime}}function Sm(e,t={}){if(!e||typeof e!="object")return e;let r=e,n=t.tag??(typeof r.merchantName=="string"?r.merchantName:"media"),i=r.content?.[0]?.text,o=typeof i=="string"?v4e(i):null,s=Array.isArray(r.urls)?r.urls[0]:void 0,c=typeof s=="string"&&s.startsWith("data:")?v4e(s):null;if(!o&&!c)return e;let u=o??c,d=o?"content":"urls",l;try{l=nlt(u,{tag:$wr(n,r)})}catch(f){return{...r,_inline_media_warning:`Failed to persist inline media to disk: ${f instanceof Error?f.message:String(f)}`}}let p={...r,filePath:l.filePath,mime:l.mime,bytes:l.bytes};return d==="urls"?p.urls=void 0:(p.content=Array.isArray(r.content)?[...r.content]:[{}],p.content[0]={...p.content[0]??{},text:`[inline media saved to ${l.filePath}]`}),p}function $wr(e,t){let r=typeof t.transactionId=="string"?t.transactionId:typeof t.transaction_id=="string"?t.transaction_id:null;return r?`${e}-${r}`:e}ea();var w4e=!1;async function ilt(e,t,r){try{return await t()}catch(n){if(!(n.message==="Invalid signature"||n.code==="ATTESTATION_KEY_DRIFT"||n.error_code==="ATTESTATION_KEY_DRIFT"||n.name==="AttestationDriftError")||!rl())throw n;if(W.warn("attestation:key-mismatch",{action:"browser-recovery"}),r){if(w4e)throw W.warn("attestation:browser-recovery-suppressed",{reason:"already-attempted-in-process"}),n;w4e=!0,W.info("attestation:starting-browser-recovery");try{let o=await r();if(!o.success)throw W.error("attestation:browser-recovery-failed",{message:o.message}),n;let s=await N9e();await e.registerAttestationKey(s),await e.setBiometricPreference({required:!0}),W.info("attestation:requirement-restored-after-recovery",{surface:"retry"}),W.info("attestation:key-reregistered-after-recovery");let a=await t();return w4e=!1,a}catch(o){throw W.error("attestation:recovery-failure",{error:o.message}),n}}throw n}}function wA(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}async function olt(e,t){if(!rl())return{ok:!1,code:"TOUCH_ID_UNAVAILABLE",message:"Touch ID is not available in this process. Run `visa-cli setup` from an interactive macOS terminal before enabling Touch ID."};if(!await j9e())return{ok:!1,code:"LOCAL_ATTESTATION_KEY_MISSING",message:"No local attestation key found on this device. Run `visa-cli setup` before enabling Touch ID; otherwise payments and biometric off can require a key this device cannot produce."};let r=await e.getStatus(t);return wA(r)?{ok:!0,status:r}:{ok:!1,code:"SERVER_ATTESTATION_KEY_MISSING",message:"No server attestation key is registered for this account. Run `visa-cli setup` before enabling Touch ID."}}function Vwr(e){return new Promise(t=>setTimeout(t,e))}function slt(e){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return e*1e3;if(typeof e!="string"||e.trim()==="")return null;let t=Number(e);if(Number.isFinite(t)&&t>0)return t*1e3;let r=Date.parse(e);return Number.isFinite(r)?Math.max(r-Date.now(),0):null}function alt(e){return!Number.isFinite(e)||e===null||e<=0?1e3:Math.min(Math.max(Math.ceil(e),1e3),3e4)}async function Kwr(e,t=Math.random()*250){let r=i=>Math.min(i+Math.max(0,Math.ceil(t)),3e4);if(!e||e.status!==429)return r(1e3);let n=slt(e.headers?.get("Retry-After"));if(n!==null)return r(alt(n));if(typeof e.json=="function")try{let i=await e.json();return r(alt(slt(i?.retryAfter)))}catch{return r(1e3)}return r(1e3)}async function x4e(e,t){let r=await Kwr(e);return t?.(r),await Vwr(r),r}Qd();fB();var clt="4.1.0-rc.24";function E4e(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function A4e(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=VA(t);return i!==void 0?{value:i,source:{kind:"settings"}}:{value:r!=="opt-in",source:{kind:"default"}}}function Vd(e){return e==null?"\u2014":e?"yes":"no"}function UJ(e){return e==null?"\u2014":`$${e.toFixed(2)}`}function Wwr(e){return e==null?"\u2014":`$${(e/100).toFixed(2)}`}function Gwr(){let e=process.env.VISA_CREDIT_SESSION_CAP_CENTS;if(e!==void 0){let r=Number(e);if(Number.isFinite(r)&&r>=10&&r<=1e4)return{value:Math.floor(r),source:{kind:"env",var:"VISA_CREDIT_SESSION_CAP_CENTS"}}}let t=sZ("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?{value:Math.floor(t),source:{kind:"settings"}}:{value:oZ,source:{kind:"default"}}}async function ult(e){let t=null,r=null;try{t=await e.api.getStatus()}catch(A){r=A?.message||"unknown error"}let n=[],i=process.env.VISA_AUTH_URL,o=cB("auth.serverUrl"),s=ta(),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:Vd(t?.enrolled),source:t?{kind:"server"}:{kind:"unknown",reason:r||"offline"}}),t?.githubUser&&n.push({key:"account.githubUser",value:t.githubUser,formatted:t.githubUser,source:{kind:"server"}}),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=t?t.attestationRequired!==!1:void 0;n.push({key:"biometric.required",value:c,formatted:Vd(c),source:t?{kind:"server"}:{kind:"unknown",reason:r||"offline"},hint:c===!1?"Touch ID prompts are suppressed. Re-enable with `visa-cli config biometric on`.":void 0}),n.push({key:"biometric.keyRegistered",value:t?.hasAttestationKey??null,formatted:Vd(t?.hasAttestationKey),source:t?{kind:"server"}:{kind:"unknown",reason:r||"offline"}}),n.push({key:"biometric.deviceAvailable",value:rl(),formatted:Vd(rl()),source:{kind:"device"}});let u=t?.spendingControls,d=u?u.max_transaction_amount??u.maxTransactionAmount??null:null,l=u?u.daily_limit??u.dailyLimit??null:null;n.push({key:"spending.maxPerTxn",value:d,formatted:UJ(d),source:t?{kind:"server"}:{kind:"unknown",reason:r||"offline"}}),n.push({key:"spending.dailyLimit",value:l,formatted:UJ(l),source:t?{kind:"server"}:{kind:"unknown",reason:r||"offline"}}),n.push({key:"spending.dailySpent",value:t?.dailySpent??null,formatted:UJ(t?.dailySpent),source:t?{kind:"server"}:{kind:"unknown",reason:r||"offline"}}),n.push({key:"spending.dailyRemaining",value:t?.dailyRemaining??null,formatted:UJ(t?.dailyRemaining),source:t?{kind:"server"}:{kind:"unknown",reason:r||"offline"}}),n.push({key:"cards.count",value:t?.cardCount??null,formatted:t?.cardCount!=null?String(t.cardCount):"\u2014",source:t?{kind:"server"}:{kind:"unknown",reason:r||"offline"}});let p=t?.cards?.find(A=>A.isDefault)??t?.cards?.[0];p&&n.push({key:"cards.default",value:{brand:p.brand??null,last4:p.last4},formatted:`${p.brand||"card"} \u2022\u2022\u2022\u2022 ${p.last4}`,source:{kind:"server"}});let f=Gwr();n.push({key:"credit.sessionCapCents",value:f.value,formatted:Wwr(f.value),source:f.source});let m=uB();m.length>0&&n.push({key:"settings.retired",value:m.map(A=>A.key),formatted:m.map(A=>A.key).join(", "),source:{kind:"settings"},hint:`Ignored retired settings found. Remove with: ${m.map(A=>`visa-cli config unset ${A.key}`).join(" && ")}`});let h=A4e("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");n.push({key:"ui.suppressBrowser",value:h.value,formatted:Vd(h.value),source:h.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let y=A4e("VISA_SUPPRESS_FEED","ui.suppressFeed","opt-in");n.push({key:"ui.suppressFeed",value:y.value,formatted:Vd(y.value),source:y.source});let v=iB(),x;process.env.VISA_CLI_NO_UPDATE_CHECK?x={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?x={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?x={kind:"env",var:"NODE_ENV"}:x={kind:"default"},n.push({key:"ui.updateCheck",value:!v,formatted:Vd(!v),source:x});let _=A4e("VISA_DISCOVER_TOOLS","tools.discover","opt-out");n.push({key:"tools.discover",value:_.value,formatted:Vd(_.value),source:_.source});let w=process.env.VISA_DRY_RUN,E=Ydt();if(n.push({key:"tools.dryRun",value:E,formatted:Vd(E),source:w===void 0?{kind:"default"}:{kind:"env",var:"VISA_DRY_RUN"},hint:"VISA_DRY_RUN=true|1|mock returns deterministic paid-tool fixtures (no card, no upstream). VISA_DRY_RUN=preflight makes a real zero-cost OpenRouter call for LLM tools (image/video still mocked)."}),n.push({key:"client.version",value:clt,formatted:clt,source:{kind:"default"}}),e.includeDev){let A=process.env.VISA_MOCK_KEYCHAIN,S=mh();n.push({key:"dev.mockKeychain",value:S,formatted:Vd(S),source:E4e("VISA_MOCK_KEYCHAIN",!!A),hint:dZ()});let T=process.env.VISA_MOCK_TOUCHID,O=YA();n.push({key:"dev.mockTouchid",value:O,formatted:Vd(O),source:E4e("VISA_MOCK_TOUCHID",!!T),hint:dZ()});let R=process.env.VISA_CLI_DEBUG;n.push({key:"dev.debug",value:!!R,formatted:Vd(!!R),source:E4e("VISA_CLI_DEBUG",!!R)})}return{entries:n,statusError:r}}function dlt(e){if(e<=0)return null;let t=(e/100).toFixed(2);return{_credits_prompt:{message:`You've got $${t} in free credits \u2014 enough for about ${Math.floor(e/1)} images. Try something now, or save them for later.`,balanceUsd:t,examples:[{tool:"fal-flux-schnell",cost:"$0.01",what:"an AI image"},{tool:"or-gpt-4o-mini",cost:"token-priced",what:"a quick model call"},{tool:"fal-ace-step-music",cost:"$0.02",what:"a music track"}]}}}Qd();ea();var i2=require("fs"),plt=require("os"),S4e=require("path"),Jwr=(0,S4e.join)((0,plt.homedir)(),".visa-mcp"),llt=(0,S4e.join)(Jwr,"mcp-session-budget.json");function MJ(){try{(0,i2.existsSync)(llt)&&(0,i2.unlinkSync)(llt)}catch{}}var P4e=require("crypto"),hp=qe(Sp()),ew=null,ku=0,s2=0,Mc=0,o2=null,I4e=null,C4e=null,Q5=Promise.resolve();function Ywr(e){return Number((0,hp.fromCents)(e))}function mlt(e){return(0,hp.toCents)((0,hp.micros)(BigInt(e)))}function flt(e){return(0,hp.toWire)((0,hp.fromCents)(e))}function T4e(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function DJ(e){return typeof e=="string"&&/^\d+$/.test(e)}var Zwr=43,Xwr=new RegExp(`^[A-Za-z0-9_-]{${Zwr}}$`);function Qwr(e){return typeof e=="string"&&Xwr.test(e)}function e4r(e){return!(e.status!=="accepted"||typeof e.session_id!="string"||e.session_id.length===0||ew&&e.session_id!==ew||typeof e.nonce!="string"||e.nonce.length===0||!Qwr(e.server_signature)||!T4e(e.cumulative)||!T4e(e.remaining)||!T4e(e.delta)||e.cumulative<ku||Mc>0&&e.cumulative>Mc||Mc>0&&e.remaining>Mc||e.cumulative_micros!==void 0&&!DJ(e.cumulative_micros)||e.remaining_micros!==void 0&&!DJ(e.remaining_micros)||e.delta_micros!==void 0&&!DJ(e.delta_micros)||e.reserved_micros!==void 0&&!DJ(e.reserved_micros))}function Z1(e){ew=e,ku=0,s2=0,Mc=0,o2=null,I4e=null,C4e=null,Q5=Promise.resolve()}function vk(e){Mc=Math.max(0,Math.floor(e))}function O4e(){return ew}function R4e(e){if(!ew)return null;let t=ku+s2;return Mc>0&&t>Mc&&(t=Mc),{session_budget_id:ew,cumulative_micros:Ywr(t),nonce:(0,P4e.randomUUID)(),idempotency_key:e||(0,P4e.randomUUID)()}}function wk(e){if(!e)return null;let t;try{t=Buffer.from(e,"base64").toString("utf-8")}catch{return null}let r;try{r=JSON.parse(t)}catch{return null}if(!r||typeof r!="object")return null;let n=r;return e4r(n)?(ku=Math.max(ku,n.cumulative),s2=0,o2=n,n):null}function hlt(){return o2}function k4e(e){let t=mlt(e.cumulative_micros);ku=Math.max(ku,t),s2=0;let r={status:"accepted",session_id:e.session_budget_id,cumulative:ku,remaining:Math.max(0,Mc-ku),delta:0,cumulative_micros:flt(ku),remaining_micros:flt(Math.max(0,Mc-ku)),delta_micros:"0",nonce:e.nonce};return o2=r,r}function xk(e){if(!e||typeof e!="object")return;let t=e.cumulative_micros;if(typeof t!="string"||!/^\d+$/.test(t))return;let r;try{r=BigInt(t)}catch{return}if(r<0n)return;let n=(0,hp.toCents)((0,hp.micros)(r));if(!Number.isFinite(n)||n<0)return;I4e=t;let i=e,o=typeof i.session_id=="string"?i.session_id:ew??"";o2?(typeof i.remaining_micros=="string"&&/^\d+$/.test(i.remaining_micros)&&(o2.remaining_micros=i.remaining_micros),typeof i.charged_micros=="string"&&/^\d+$/.test(i.charged_micros)&&(o2.delta_micros=i.charged_micros)):o2={session_id:o,cumulative:n,remaining:0,delta:0,nonce:typeof i.transaction_id=="string"?i.transaction_id:"",remaining_micros:typeof i.remaining_micros=="string"&&/^\d+$/.test(i.remaining_micros)?i.remaining_micros:void 0,delta_micros:typeof i.charged_micros=="string"&&/^\d+$/.test(i.charged_micros)?i.charged_micros:void 0}}function ylt(e){let t=e.receipt??null;C4e={toolName:e.toolName,resolvedToolId:e.resolvedToolId,estimatedAmountCents:Math.max(0,Math.ceil(e.estimatedAmountCents)),voucherCumulativeCents:mlt(e.voucher.cumulative_micros),estimatedCumulativeCents:LJ(),receiptDeltaCents:typeof t?.delta=="number"?t.delta:null,receiptCumulativeCents:typeof t?.cumulative=="number"?t.cumulative:null,receiptRemainingCents:typeof t?.remaining=="number"?t.remaining:null,receiptDeltaMicros:typeof t?.delta_micros=="string"?t.delta_micros:null,receiptCumulativeMicros:typeof t?.cumulative_micros=="string"?t.cumulative_micros:null,receiptRemainingMicros:typeof t?.remaining_micros=="string"?t.remaining_micros:null,recordedAt:new Date().toISOString()}}function glt(){return C4e}function blt(){return ku}function _lt(){return I4e}function LJ(){let e=ku+s2;return Mc>0&&e>Mc&&(e=Mc),e}function B4e(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return Q5=Q5.then(()=>{s2+=t}),Q5}function Ek(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return Q5=Q5.then(()=>{s2=Math.max(0,s2-t)}),Q5}var t4r=10,r4r=1,Ii=null,vlt=Promise.resolve();function N4e(e){let t=vlt.catch(()=>{}).then(e);return vlt=t.then(()=>{},()=>{}),t}var No=class extends Error{balanceCents;minRequiredCents;constructor(t,r){super(`Prepaid balance is $${(t/100).toFixed(2)}; at least $${(r/100).toFixed(2)} required to open a credit session. Top up via the buy_credits tool first.`),this.name="InsufficientBalanceError"}};async function j4e(e,t,r){return N4e(()=>wlt(e,t,r))}async function wlt(e,t,r){if(MJ(),Ii&&new Date(Ii.expiresAt).getTime()>Date.now())return O4e()!==Ii.budgetId&&(Z1(Ii.budgetId),vk(Ii.totalCents)),W.info("mcp-session:active-hit",{budgetId:Ii.budgetId,tool:r.toolName,remainingEstimatedCents:Ii.totalCents-LJ()}),{budgetId:Ii.budgetId,isFresh:!1,totalCents:Ii.totalCents,requestedCapCents:Ii.totalCents,appliedCapCents:Ii.totalCents,clampedReason:null};Ii&&(Ii=null,Z1(null));let n=await e.getBalance();if(!n.success)throw new Error(`Could not read balance: ${n.error||"unknown error"}`);let i=r.sessionKind??"explicit",o=i==="one_shot"?r4r:t4r,s=Math.max(o,Math.ceil(r.minRequiredCents??o));if(n.balanceCents<s)throw new No(n.balanceCents,s);let a=r.capCentsOverride??Q3e(),c=Math.min(a,n.balanceCents),u=c<a?"balance":null,d=await t("session_create",c,"Visa CLI Session",`open credit-model session with $${(c/100).toFixed(2)} cap`,r.userContext),l=await e.createSessionBudget({total_cents:c,session_kind:i,...d?{attestation:d}:{}});if(!l.success||!l.budget){let f=l.error||"unknown error";throw new Error(`Failed to open credit session: ${f}`)}let p={budgetId:l.budget.id,expiresAt:l.budget.expiresAt,totalCents:l.budget.totalCents,createdAt:l.budget.createdAt};return Ii=p,Z1(p.budgetId),vk(p.totalCents),W.info("mcp-session:opened",{budgetId:p.budgetId,capCents:p.totalCents,requestedCapCents:a,clampedReason:u,sessionKind:i,expiresAt:p.expiresAt,tool:r.toolName}),{budgetId:p.budgetId,isFresh:!0,totalCents:p.totalCents,requestedCapCents:a,appliedCapCents:p.totalCents,clampedReason:u}}async function xlt(e,t,r){return N4e(async()=>{let i=a2()?await Elt(e):null,o=await wlt(e,t,r);return{budgetId:o.budgetId,totalCents:o.totalCents,closedPrevious:i,requestedCapCents:o.requestedCapCents,appliedCapCents:o.appliedCapCents,clampedReason:o.clampedReason}})}async function Elt(e){let r=a2()?.budgetId??O4e(),n=!1,i,o;if(r)try{let s=await e.closeSession(r);n=!!s?.success,typeof s?.finalCumulativeCents=="number"&&(i=s.finalCumulativeCents),typeof s?.finalCumulativeMicros=="string"&&(o=s.finalCumulativeMicros)}catch(s){W.warn("mcp-session:close-server-failed",{budgetId:r,error:s?.message||String(s)})}return MJ(),Ii=null,Z1(null),{closedServerSide:n,budgetId:r,finalCumulativeCents:i,finalCumulativeMicros:o}}async function HJ(e){return N4e(()=>Elt(e))}function a2(){return MJ(),Ii?new Date(Ii.expiresAt).getTime()<=Date.now()?(Ii=null,Z1(null),null):{budgetId:Ii.budgetId,totalCents:Ii.totalCents,lastReceiptCumulative:blt(),lastReceiptCumulativeMicros:hlt()?.cumulative_micros??null,ledgerReceiptCumulativeMicros:_lt(),estimatedCumulative:LJ(),lastToolSpend:glt(),expiresAt:Ii.expiresAt}:null}var Slt=qe(Sp()),Alt=10000n;function n4r(e){return e<=0n?0:Number((e+Alt-1n)/Alt)}function Tlt(e){return n4r((0,Slt.fromUsd)(e))}var zJ=qe(Sp()),i4r=/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/;function Plt(e){if(typeof e!="string"||!i4r.test(e))return{ok:!1,error:"amount must be a USD amount with at most two decimal places"};let[t,r=""]=e.split("."),n=BigInt(t)*100n+BigInt(r.padEnd(2,"0"));if(n>BigInt(Number.MAX_SAFE_INTEGER))return{ok:!1,error:"amount is too large"};let i=Number(n);return i<=0?{ok:!1,error:"amount must be greater than $0.00"}:{ok:!0,cents:i,displayUsd:(0,zJ.toDisplay)((0,zJ.fromCents)(i),{symbol:""})}}var L4e=require("node:os"),Sk=require("node:path"),D4e=require("node:fs/promises"),klt=require("node:fs"),Blt=require("node:url");ea();var tw=class extends Error{constructor(t){super(t),this.name="PayValidationError"}};function Ilt(e){let t;try{t=new URL(e)}catch{throw new tw(`Invalid URL: ${e}. Expected a fully-qualified http(s) URL.`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new tw(`Unsupported URL scheme "${t.protocol}". Only http and https are allowed.`);return t}ea();var o4r={get_visa_smi:"get_visa_smi",pay_merchant:"checkout_agent_access"},Clt=300*1e3,q4e={},U4e=0,Ak=null;function M4e(){return Ak||(Ak=(async()=>{try{let e=await De.getFeatureFlags();q4e=e&&e.flags||{},U4e=Date.now()}catch(e){q4e={},W.warn("feature-flags:fetch-failed",{error:e instanceof Error?e.message:String(e)})}finally{Ak=null}})(),Ak)}async function Olt(){await M4e()}function Rlt(){Date.now()-U4e<Clt||M4e()}async function FJ(){Date.now()-U4e<Clt||await M4e()}function rw(e){let t=o4r[e];return t?q4e[t]!==!0:!1}function Nlt(e){return[(0,Sk.join)(e,"checkout-engine","index.js"),(0,Sk.join)(e,"..","checkout-engine","index.js")]}function s4r(e,t=klt.existsSync){return Nlt(e).find(r=>t(r))??null}var $J=null,a4r=async()=>{if($J)return $J;let e=s4r(__dirname);if(!e)throw new Error(`Cannot find module: the checkout engine was not packaged (looked in ${Nlt(__dirname).join(" and ")}).`);return $J=(await import((0,Blt.pathToFileURL)(e).href)).createCliCheckoutEngine(),$J};async function c4r(){return rw("pay_merchant")?(await FJ(),rw("pay_merchant")):!1}var u4r=(0,Sk.join)((0,L4e.homedir)(),".visa-mcp","agent-credential.json"),d4r=(0,Sk.join)((0,L4e.homedir)(),".visa-mcp","contact.json");function l4r(e){return e.replace(/https?:\/\/[^\s"')\]]+/gi,t=>{try{return new URL(t).origin}catch{return"[url]"}}).slice(0,300)}async function VJ(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}}),result_success:e.success,result_error:e.errorMessage?l4r(e.errorMessage):null,result_json:JSON.stringify({outcome:e.outcome,confirmationRef:e.confirmationRef??null}),payment_rail:e.action==="pay"?"card":null,payment_amount:e.action==="pay"?e.amountMinor:null,payment_currency:e.currency==="USD"?"USD":null,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){W.warn("pay_merchant:telemetry_failed",{action:e.action,error:t instanceof Error?t.message:String(t)})}}function p4r(e){if(typeof e!="string"||!/^\d+(\.\d{1,2})?$/.test(e)||Number(e)<=0)throw new tw(`Invalid amount ${JSON.stringify(e)}. Expected a positive decimal like "5.00".`);return e}async function jlt(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:Um();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??c4r)())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(o!=="review"&&o!=="pay")return{success:!1,message:`Unknown pay_merchant action ${JSON.stringify(o)}. Use "review" (default) or "pay".`};let s,a,c=(e.currency??"USD").toUpperCase();if(!/^[A-Z]{3}$/.test(c))return{success:!1,message:`Invalid currency ${JSON.stringify(e.currency)}. Expected a 3-letter ISO code like "USD".`};try{s=Ilt(e.url??"").toString(),a=p4r(e.amount)}catch(T){if(T instanceof tw)return{success:!1,message:T.message};throw T}let u=t.credentialPath??u4r,d=t.contactPath??d4r;try{await(0,D4e.readFile)(u,"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 l;try{l=JSON.parse(await(0,D4e.readFile)(d,"utf8"))}catch{return{success:!1,message:`No contact details at ${d}. Write your name/email/address there (chmod 600) first.`}}let p=null;if(o==="pay"){let T=typeof e.confirm=="string"?e.confirm.trim():"",O=/^PAY (\S+)$/.exec(T);if(!O)return{success:!1,action:"pay",message:'Confirmation required: pass confirm:"PAY <reviewId>" using the reviewId from a prior pay_merchant { action:"review" } call. Nothing was charged.'};p=O[1]}let f=t.loadEngine??a4r,m;try{m=await f()}catch(T){let O=T instanceof Error?T.message:String(T);if(/ERR_MODULE_NOT_FOUND|Cannot find (module|package)/.test(O))return{success:!1,message:/checkout engine was not packaged/.test(O)?"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 T}let h={url:s,amount:a,currency:c,credentialPath:u,contact:l,approvalBaseUrl:n},y=t.emitTelemetry??(T=>De.emitTelemetry(T)),v=new URL(s).hostname,x=Math.round(Number(a)*100),_=Date.now();if(o==="review"){W.info("pay_merchant:review",{host:v,currency:c});let T;try{T=await m.review(h)}catch(O){throw await VJ({emitTelemetry:y,action:"review",merchantHost:v,amountMinor:x,currency:c,outcome:"engine-error",success:!1,errorMessage:O instanceof Error?O.message:String(O),startedAt:_}),O}return await VJ({emitTelemetry:y,action:"review",merchantHost:v,amountMinor:x,currency:c,outcome:"reviewed",success:!0,startedAt:_}),{success:!0,action:"review",...T,message:`Review ${T.reviewId}: ${T.merchantHost} wants ${T.amountMinor} ${T.currency} (minor units). To authorize, call pay_merchant { action: "pay", url, amount, confirm: "PAY ${T.reviewId}" }. No charge yet.`}}let w=p,E=t.allowSubmit??process.env.CHECKOUT_AGENT_ALLOW_SUBMIT==="1";W.info("pay_merchant:pay",{reviewId:w,submit:E});let A;try{A=await m.pay({...h,reviewId:w,submit:E})}catch(T){throw await VJ({emitTelemetry:y,action:"pay",merchantHost:v,amountMinor:x,currency:c,outcome:"engine-error",success:!1,errorMessage:T instanceof Error?T.message:String(T),startedAt:_,submit:E}),T}let S=A.outcome==="confirmed"||A.outcome==="filled-dry-run";return await VJ({emitTelemetry:y,action:"pay",merchantHost:v,amountMinor:x,currency:c,outcome:A.outcome,confirmationRef:A.confirmationRef,success:S,errorMessage:S?null:A.detail??A.outcome,startedAt:_,submit:E}),{success:S,action:"pay",reviewId:w,...A,message:A.outcome==="confirmed"?`Paid. Confirmation ${A.confirmationRef??"(none captured)"} \xB7 receipt ${A.receiptPath??"(not written)"}.`:`Outcome: ${A.outcome}${A.detail?` \u2014 ${A.detail}`:""}. Do not retry blindly \u2014 verify with the merchant before any re-run.`}}var qlt="Buying credits requires local biometric attestation from a Touch ID-capable Mac or a Windows Hello-capable PC running the Visa CLI. This device cannot create the required attestation, so no card charge was attempted. Credits are account-level, so you can top up this account from any interactive biometric-capable CLI, then use the balance from this remote server.",Ult="Tell the user that buying credits requires a local CLI/MCP process with Touch ID (Mac) or Windows Hello (PC) today. Credits are account-level: suggest topping up the same account from any interactive biometric-capable CLI, then continuing on this remote server. Do not retry buy_credits from this process; it cannot produce the required card-charge attestation.";Qd();var Pft=Promise.resolve();function L3r(e,t){if(e)try{let r=(0,bY.fromWire)(e),n=r%10000n===0n?2:6;return(0,bY.toDisplay)(r,{decimals:n})}catch{}return`$${(t/100).toFixed(2)}`}var Ift=!1,Cft=!1,Oft=!1;function vY(e){let t=Pft.catch(()=>{}).then(e);return Pft=t.then(()=>{},()=>{}),t}async function Hft(e){let t=await qo(()=>j4e(De,Yd,{toolName:e.toolId,userContext:e.userContext}));await B4e(e.estimatedAmountCents);let r=R4e(e.idempotencyKey);if(!r)throw await Ek(e.estimatedAmountCents),new Error(`Internal: failed to mint voucher for active session ${t.budgetId}`);let n=await G3r(),i,o,s=async()=>De.shortcutWithSession(e.toolId,r,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);try{try{({data:i,voucherReceiptHeader:o}=await s())}catch(d){if(d instanceof qm){let l=Math.min(Math.max(d.retryAfterSecs,0),5)*1e3;W.warn("mcp-session:lock-contended-retrying",{tool:e.toolId,retryAfterSecs:d.retryAfterSecs}),await new Promise(p=>setTimeout(p,l)),{data:i,voucherReceiptHeader:o}=await s()}else throw d}}catch(d){if(await Ek(e.estimatedAmountCents),d instanceof Iw){if(W.warn("mcp-session:server-invalidated-budget",{code:d.code,budgetId:d.budgetId??t.budgetId,tool:e.toolId}),await HJ(De),process.env.VISA_REQUIRE_EXPLICIT_SESSION==="true")throw new Error(`Your session was closed by another process (${d.code}). Restart MCP or run start_session again.`);return Oft||(Oft=!0,console.error(`[visa-cli] Your session was closed by another process; reopened automatically as pay-as-you-go.
|
|
20660
|
-
To require an explicit session approval instead, set VISA_REQUIRE_EXPLICIT_SESSION=true.`)),W.info("mcp-session:falling-back-to-payg",{code:d.code,tool:e.toolId}),zft(e)}throw d instanceof qm?(W.warn("mcp-session:lock-contended-give-up",{tool:e.toolId}),new Error("Another paid call is currently in progress on this session. Wait a moment and try again.")):d}let a=wk(o)??(r?k4e(r):null);if(xk(i?.receipt_v2),ylt({toolName:e.metaTool??e.toolId,resolvedToolId:e.toolId,estimatedAmountCents:e.estimatedAmountCents,voucher:r,receipt:a}),M8e(i))return Sm(i);let c=await U8e();if(e.idempotencyKey&&D8e(i,c,e.idempotencyKey))return Sm(i);let u=c?qk(c):null;return Sm(L8e(i,n,u))}function Gd(e){return{success:!1,error:e.message,error_code:"INSUFFICIENT_BALANCE",balanceCents:e.balanceCents,suggestedTool:"buy_credits"}}function hY(e){if(e===null||typeof e!="object"){let r=JSON.stringify(e);return r===void 0?String(e):r}return Array.isArray(e)?`[${e.map(hY).join(",")}]`:`{${Object.entries(e).sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>`${JSON.stringify(r)}:${hY(n)}`).join(",")}}`}function q8e(e,t,r,n){let i=jo.createHash("sha256").update(`${r}:${hY(n)}`).digest("hex").slice(0,24);return`batch:${e}:${t}:${i}`}function H3r(e,t){return`${e}:${t}`}function z3r(e){if(e==null)return;let t=String(e);if(t.length!==0)return t.startsWith("ledger_")?t:/^\d+$/.test(t)?`ledger_${t}`:t}function yY(e,t,r){let n=r?.amountMicros??r?.amount_micros??r?.charged_micros??r?.receipt_v2?.charged_micros??r?.receipt_v2?.actual_micros,i=gp(n),o=i!==null?i.toString():void 0,s=r?.transaction_id??r?.transactionId??r?.receipt_v2?.transaction_id,a=z3r(r?.ledger_id??r?.ledgerId??r?.receipt_v2?.ledger_id),c=s!=null?String(s):a;return{batch_id:e,item_id:H3r(e,t),index:t,...c!==void 0?{transaction_id:c}:{},...a!==void 0?{ledger_id:a}:{},...o?{amountMicros:o,amount_micros:o,cost_micros:o}:{}}}async function zft(e){return qo(()=>$3r(e))}async function Fft(e,t,r){if(M8e(e))return Sm(e);let n=await U8e();if(r&&D8e(e,n,r))return Sm(e);let i=n?qk(n):null;return Sm(L8e(e,t,i))}async function F3r(e){let t=e.cap,r=`spend up to $${(e.estimatedAmountCents/100).toFixed(2)} on ${e.toolId} (call cap $${(t/100).toFixed(2)})`,n=await Yd("shortcut_call",t,e.toolId,r,e.userContext);W.info("parentless-single-call:attempt",{tool:e.toolId,approvedMaxCents:t,attested:!!n});let i=n?.nonce??(await De.getAttestationChallenge()).nonce,{data:o,voucherReceiptHeader:s}=await De.shortcutParentless(e.toolId,{...n?{attestation:n}:{},nonce:i,approved_max_cents:t,idempotency_key:e.idempotencyKey},e.toolParams,e.timeoutMs,e.userContext,e.metaTool);return wk(s),xk(o?.receipt_v2),W.info("parentless-single-call:completed",{tool:e.toolId}),Fft(o,e.beforeBalanceMicros,e.idempotencyKey)}async function $3r(e){let t=Math.max(1,Math.ceil(e.estimatedAmountCents)),r=await De.getBalance();if(!r.success)throw new Error(`Could not read balance: ${r.error||"unknown error"}`);if(r.balanceCents<t)throw new No(r.balanceCents,t);let n=t,i=qk(r);if(Xdt()&&!Ift){let d=e.idempotencyKey??jo.randomUUID();try{return await F3r({toolId:e.toolId,toolParams:e.toolParams,estimatedAmountCents:e.estimatedAmountCents,cap:n,beforeBalanceMicros:i,userContext:e.userContext,metaTool:e.metaTool,timeoutMs:e.timeoutMs,idempotencyKey:d})}catch(l){if(l instanceof Ap)Ift=!0,W.info("parentless-single-call:falling-back-to-session",{tool:e.toolId,status:l.status,serverErrorCode:l.serverErrorCode});else throw l}}let o=`spend up to $${(e.estimatedAmountCents/100).toFixed(2)} on ${e.toolId} (session cap $${(n/100).toFixed(2)})`,s=await Yd("session_create",n,"Visa CLI Session",o,e.userContext),a=await De.createSessionBudget({total_cents:n,session_kind:"one_shot",...s?{attestation:s}:{}});if(!a.success||!a.budget)throw new Error(`Failed to open on-demand session: ${a.error||"unknown error"}`);let c=a.budget.id;Z1(c),vk(a.budget.totalCents),W.info("on-demand-session:opened",{budgetId:c,capCents:a.budget.totalCents,tool:e.toolId});let u=!1;try{await B4e(e.estimatedAmountCents);let d=R4e(e.idempotencyKey);if(!d)throw await Ek(e.estimatedAmountCents),new Error(`Internal: mintVoucher returned null after on-demand session-open ${c}`);let{data:l,voucherReceiptHeader:p}=await De.shortcutWithSession(e.toolId,d,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);if(wk(p)||k4e(d),u=!0,xk(l?.receipt_v2),M8e(l))return Sm(l);let f=await U8e();if(e.idempotencyKey&&D8e(l,f,e.idempotencyKey))return Sm(l);let m=f?qk(f):null;return Sm(L8e(l,i,m))}catch(d){throw u||await Ek(e.estimatedAmountCents),d}finally{try{await De.closeSession(c)}catch(d){W.warn("on-demand-session:close-failed",{budgetId:c,error:d?.message||String(d)})}Z1(null),W.info("on-demand-session:closed",{budgetId:c,tool:e.toolId})}}async function b2(e){return vY(async()=>a2()?Hft(e):zft(e))}function wY(){return ta()}var De=new lB(()=>ra.getSessionToken());function gp(e){if(typeof e!="string"||!/^-?\d+$/.test(e))return null;try{return BigInt(e)}catch{return null}}function qk(e){return gp(e.balanceMicros)??BigInt(e.balanceCents)*10000n}function V3r(e){if(e<0n&&(e=0n),e>=1000000n){let n=(e+5000n)/10000n,i=n/100n,o=n%100n;return`$${i.toString()}.${o.toString().padStart(2,"0")}`}let t=e%1000000n;return t===0n?"$0.00":`$0.${t.toString().padStart(6,"0").replace(/0+$/,"")}`}function K3r(e){let t=gp(e.ledgerReceiptCumulativeMicros);if(t!==null)return{micros:t,source:"ledgerReceiptCumulativeMicros"};let r=gp(e.lastReceiptCumulativeMicros);if(r!==null)return{micros:r,source:"lastReceiptCumulativeMicros"};let n=gp(e.lastToolSpend?.receiptCumulativeMicros);return n!==null?{micros:n,source:"lastToolSpend.receiptCumulativeMicros"}:{micros:BigInt(Math.max(0,e.estimatedCumulative))*10000n,source:"estimatedCumulativeCents"}}function jk(e,t="INVALID_TOOL_PARAMS",r){return{success:!1,error_code:t,code:t,error:e,message:e,...r??{}}}function W3r(e){return{success:!1,error_code:"TOOL_EXECUTION_FAILED",code:"TOOL_EXECUTION_FAILED",error:e.message||"Tool execution failed.",message:e.message||"Tool execution failed.",tool_id:e.toolId,surface:e.surface,merchantName:e.merchantName,amount:e.amount,payment_finalized:!1,charged:!1}}async function G3r(){try{let e=await De.getBalance();return e.success?qk(e):null}catch{return null}}async function U8e(){try{let e=await De.getBalance();return e.success?e:null}catch{return null}}function M8e(e){if(!e||e.success===!1)return!1;let t=gp(e.receipt_v2?.charged_micros??e.receipt_v2?.actual_micros),r=gp(e.amountMicros??e.amount_micros??e.charged_micros),n=t??r;if(n===null||n<=0n)return!1;let i=n.toString();return e.amountMicros??=i,e.amount_micros??=i,e.charged_micros??=i,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(n)/1e6),!0}function D8e(e,t,r){if(!e||e.success===!1||!t||!Array.isArray(t.ledger))return!1;let n=t.ledger.find(a=>a.idempotencyKey===r);if(!n)return!1;let i=gp(n.deltaMicros)??BigInt(n.deltaCents)*10000n,o=i<0n?-i:i;if(o<=0n)return!1;let s=o.toString();return e.amountMicros??=s,e.amount_micros??=s,e.charged_micros??=s,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(o)/1e6),!0}function L8e(e,t,r){if(!e||e.success===!1||t===null||r===null)return e;let n=t-r;if(n<=0n)return e;let i=n.toString();return e.amountMicros??=i,e.amount_micros??=i,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(n)/1e6),e}var J3r="4.1.0-rc.
|
|
20659
|
+
`:""})}function Mwr(e){let t=e;for(let[r,n]of[[Owr,Rwr],[kwr,Bwr]])t=Uwr(t,r,n);return t.trimEnd()}function Dwr(e){return Mwr(e)!==e.trimEnd()}function jJ(e=Nwr()){if(!e)return!1;try{let t=jwr(e),r=Am.readFileSync(t,"utf-8");return Dwr(r)}catch{return!1}}function elt(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Lwr(){let e=NJ.homedir();if(!e||!mp.isAbsolute(e))throw new Error("unable to determine a valid home directory");return mp.resolve(e)}var Mwn=1440*60*1e3;var Hwr="# visa-cli-hud-v1";function tlt(e){return typeof e!="string"?!1:e.includes(Hwr)?!0:e.includes("visa-cli")&&e.includes("statusline")}var qJ=qe(require("fs")),rlt=qe(require("os")),_4e=qe(require("path")),zwr=[{prefix:"iVBORw0KGgo",sig:{mime:"image/png",ext:"png"}},{prefix:"/9j/",sig:{mime:"image/jpeg",ext:"jpg"}},{prefix:"R0lGOD",sig:{mime:"image/gif",ext:"gif"}},{prefix:"UklGR",sig:{mime:"image/webp",ext:"webp"}}],Fwr=/^data:(image\/(png|jpeg|jpg|gif|webp));base64,([A-Za-z0-9+/=]+)$/;function v4e(e){if(typeof e!="string"||e.length===0)return null;let t=e.trim(),r=Fwr.exec(t);if(r){let i=r[2]==="jpg"?"jpeg":r[2],o=i==="png"?{mime:"image/png",ext:"png"}:i==="jpeg"?{mime:"image/jpeg",ext:"jpg"}:i==="gif"?{mime:"image/gif",ext:"gif"}:{mime:"image/webp",ext:"webp"};return{base64:r[3],sig:o}}if(!/^[A-Za-z0-9+/=\s]+$/.test(t)||t.length<64)return null;let n=t.replace(/\s+/g,"");for(let{prefix:i,sig:o}of zwr)if(n.startsWith(i))return{base64:n,sig:o};return null}function nlt(e,t={}){let r=t.outputDir??_4e.join(rlt.tmpdir(),"visa-cli");qJ.mkdirSync(r,{recursive:!0});let n=(t.tag??"media").toLowerCase().replace(/[^a-z0-9-]+/g,"-").replace(/^-+|-+$/g,"").slice(0,48)||"media",i=new Date().toISOString().replace(/[:.]/g,"-"),o=_4e.join(r,`${n}-${i}.${e.sig.ext}`),s=Buffer.from(e.base64,"base64");return qJ.writeFileSync(o,s,{mode:384}),{filePath:o,bytes:s.length,mime:e.sig.mime}}function Sm(e,t={}){if(!e||typeof e!="object")return e;let r=e,n=t.tag??(typeof r.merchantName=="string"?r.merchantName:"media"),i=r.content?.[0]?.text,o=typeof i=="string"?v4e(i):null,s=Array.isArray(r.urls)?r.urls[0]:void 0,c=typeof s=="string"&&s.startsWith("data:")?v4e(s):null;if(!o&&!c)return e;let u=o??c,d=o?"content":"urls",l;try{l=nlt(u,{tag:$wr(n,r)})}catch(f){return{...r,_inline_media_warning:`Failed to persist inline media to disk: ${f instanceof Error?f.message:String(f)}`}}let p={...r,filePath:l.filePath,mime:l.mime,bytes:l.bytes};return d==="urls"?p.urls=void 0:(p.content=Array.isArray(r.content)?[...r.content]:[{}],p.content[0]={...p.content[0]??{},text:`[inline media saved to ${l.filePath}]`}),p}function $wr(e,t){let r=typeof t.transactionId=="string"?t.transactionId:typeof t.transaction_id=="string"?t.transaction_id:null;return r?`${e}-${r}`:e}ea();var w4e=!1;async function ilt(e,t,r){try{return await t()}catch(n){if(!(n.message==="Invalid signature"||n.code==="ATTESTATION_KEY_DRIFT"||n.error_code==="ATTESTATION_KEY_DRIFT"||n.name==="AttestationDriftError")||!rl())throw n;if(W.warn("attestation:key-mismatch",{action:"browser-recovery"}),r){if(w4e)throw W.warn("attestation:browser-recovery-suppressed",{reason:"already-attempted-in-process"}),n;w4e=!0,W.info("attestation:starting-browser-recovery");try{let o=await r();if(!o.success)throw W.error("attestation:browser-recovery-failed",{message:o.message}),n;let s=await N9e();await e.registerAttestationKey(s),await e.setBiometricPreference({required:!0}),W.info("attestation:requirement-restored-after-recovery",{surface:"retry"}),W.info("attestation:key-reregistered-after-recovery");let a=await t();return w4e=!1,a}catch(o){throw W.error("attestation:recovery-failure",{error:o.message}),n}}throw n}}function wA(e){return e?typeof e.hasAnyAttestationKey=="boolean"?e.hasAnyAttestationKey:typeof e.hasAttestationKey=="boolean"?e.hasAttestationKey:!0:!1}async function olt(e,t){if(!rl())return{ok:!1,code:"TOUCH_ID_UNAVAILABLE",message:"Touch ID is not available in this process. Run `visa-cli setup` from an interactive macOS terminal before enabling Touch ID."};if(!await j9e())return{ok:!1,code:"LOCAL_ATTESTATION_KEY_MISSING",message:"No local attestation key found on this device. Run `visa-cli setup` before enabling Touch ID; otherwise payments and biometric off can require a key this device cannot produce."};let r=await e.getStatus(t);return wA(r)?{ok:!0,status:r}:{ok:!1,code:"SERVER_ATTESTATION_KEY_MISSING",message:"No server attestation key is registered for this account. Run `visa-cli setup` before enabling Touch ID."}}function Vwr(e){return new Promise(t=>setTimeout(t,e))}function slt(e){if(typeof e=="number"&&Number.isFinite(e)&&e>0)return e*1e3;if(typeof e!="string"||e.trim()==="")return null;let t=Number(e);if(Number.isFinite(t)&&t>0)return t*1e3;let r=Date.parse(e);return Number.isFinite(r)?Math.max(r-Date.now(),0):null}function alt(e){return!Number.isFinite(e)||e===null||e<=0?1e3:Math.min(Math.max(Math.ceil(e),1e3),3e4)}async function Kwr(e,t=Math.random()*250){let r=i=>Math.min(i+Math.max(0,Math.ceil(t)),3e4);if(!e||e.status!==429)return r(1e3);let n=slt(e.headers?.get("Retry-After"));if(n!==null)return r(alt(n));if(typeof e.json=="function")try{let i=await e.json();return r(alt(slt(i?.retryAfter)))}catch{return r(1e3)}return r(1e3)}async function x4e(e,t){let r=await Kwr(e);return t?.(r),await Vwr(r),r}Qd();fB();var clt="4.1.0-rc.25";function E4e(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function A4e(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=VA(t);return i!==void 0?{value:i,source:{kind:"settings"}}:{value:r!=="opt-in",source:{kind:"default"}}}function Vd(e){return e==null?"\u2014":e?"yes":"no"}function UJ(e){return e==null?"\u2014":`$${e.toFixed(2)}`}function Wwr(e){return e==null?"\u2014":`$${(e/100).toFixed(2)}`}function Gwr(){let e=process.env.VISA_CREDIT_SESSION_CAP_CENTS;if(e!==void 0){let r=Number(e);if(Number.isFinite(r)&&r>=10&&r<=1e4)return{value:Math.floor(r),source:{kind:"env",var:"VISA_CREDIT_SESSION_CAP_CENTS"}}}let t=sZ("credit.sessionCapCents");return t!==void 0&&t>=10&&t<=1e4?{value:Math.floor(t),source:{kind:"settings"}}:{value:oZ,source:{kind:"default"}}}async function ult(e){let t=null,r=null;try{t=await e.api.getStatus()}catch(A){r=A?.message||"unknown error"}let n=[],i=process.env.VISA_AUTH_URL,o=cB("auth.serverUrl"),s=ta(),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:Vd(t?.enrolled),source:t?{kind:"server"}:{kind:"unknown",reason:r||"offline"}}),t?.githubUser&&n.push({key:"account.githubUser",value:t.githubUser,formatted:t.githubUser,source:{kind:"server"}}),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=t?t.attestationRequired!==!1:void 0;n.push({key:"biometric.required",value:c,formatted:Vd(c),source:t?{kind:"server"}:{kind:"unknown",reason:r||"offline"},hint:c===!1?"Touch ID prompts are suppressed. Re-enable with `visa-cli config biometric on`.":void 0}),n.push({key:"biometric.keyRegistered",value:t?.hasAttestationKey??null,formatted:Vd(t?.hasAttestationKey),source:t?{kind:"server"}:{kind:"unknown",reason:r||"offline"}}),n.push({key:"biometric.deviceAvailable",value:rl(),formatted:Vd(rl()),source:{kind:"device"}});let u=t?.spendingControls,d=u?u.max_transaction_amount??u.maxTransactionAmount??null:null,l=u?u.daily_limit??u.dailyLimit??null:null;n.push({key:"spending.maxPerTxn",value:d,formatted:UJ(d),source:t?{kind:"server"}:{kind:"unknown",reason:r||"offline"}}),n.push({key:"spending.dailyLimit",value:l,formatted:UJ(l),source:t?{kind:"server"}:{kind:"unknown",reason:r||"offline"}}),n.push({key:"spending.dailySpent",value:t?.dailySpent??null,formatted:UJ(t?.dailySpent),source:t?{kind:"server"}:{kind:"unknown",reason:r||"offline"}}),n.push({key:"spending.dailyRemaining",value:t?.dailyRemaining??null,formatted:UJ(t?.dailyRemaining),source:t?{kind:"server"}:{kind:"unknown",reason:r||"offline"}}),n.push({key:"cards.count",value:t?.cardCount??null,formatted:t?.cardCount!=null?String(t.cardCount):"\u2014",source:t?{kind:"server"}:{kind:"unknown",reason:r||"offline"}});let p=t?.cards?.find(A=>A.isDefault)??t?.cards?.[0];p&&n.push({key:"cards.default",value:{brand:p.brand??null,last4:p.last4},formatted:`${p.brand||"card"} \u2022\u2022\u2022\u2022 ${p.last4}`,source:{kind:"server"}});let f=Gwr();n.push({key:"credit.sessionCapCents",value:f.value,formatted:Wwr(f.value),source:f.source});let m=uB();m.length>0&&n.push({key:"settings.retired",value:m.map(A=>A.key),formatted:m.map(A=>A.key).join(", "),source:{kind:"settings"},hint:`Ignored retired settings found. Remove with: ${m.map(A=>`visa-cli config unset ${A.key}`).join(" && ")}`});let h=A4e("VISA_SUPPRESS_BROWSER","ui.suppressBrowser","opt-in");n.push({key:"ui.suppressBrowser",value:h.value,formatted:Vd(h.value),source:h.source,hint:"Persist with `visa-cli config set ui.suppressBrowser true` to stop auto-opening result URLs."});let y=A4e("VISA_SUPPRESS_FEED","ui.suppressFeed","opt-in");n.push({key:"ui.suppressFeed",value:y.value,formatted:Vd(y.value),source:y.source});let v=iB(),x;process.env.VISA_CLI_NO_UPDATE_CHECK?x={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?x={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?x={kind:"env",var:"NODE_ENV"}:x={kind:"default"},n.push({key:"ui.updateCheck",value:!v,formatted:Vd(!v),source:x});let _=A4e("VISA_DISCOVER_TOOLS","tools.discover","opt-out");n.push({key:"tools.discover",value:_.value,formatted:Vd(_.value),source:_.source});let w=process.env.VISA_DRY_RUN,E=Ydt();if(n.push({key:"tools.dryRun",value:E,formatted:Vd(E),source:w===void 0?{kind:"default"}:{kind:"env",var:"VISA_DRY_RUN"},hint:"VISA_DRY_RUN=true|1|mock returns deterministic paid-tool fixtures (no card, no upstream). VISA_DRY_RUN=preflight makes a real zero-cost OpenRouter call for LLM tools (image/video still mocked)."}),n.push({key:"client.version",value:clt,formatted:clt,source:{kind:"default"}}),e.includeDev){let A=process.env.VISA_MOCK_KEYCHAIN,S=mh();n.push({key:"dev.mockKeychain",value:S,formatted:Vd(S),source:E4e("VISA_MOCK_KEYCHAIN",!!A),hint:dZ()});let T=process.env.VISA_MOCK_TOUCHID,O=YA();n.push({key:"dev.mockTouchid",value:O,formatted:Vd(O),source:E4e("VISA_MOCK_TOUCHID",!!T),hint:dZ()});let R=process.env.VISA_CLI_DEBUG;n.push({key:"dev.debug",value:!!R,formatted:Vd(!!R),source:E4e("VISA_CLI_DEBUG",!!R)})}return{entries:n,statusError:r}}function dlt(e){if(e<=0)return null;let t=(e/100).toFixed(2);return{_credits_prompt:{message:`You've got $${t} in free credits \u2014 enough for about ${Math.floor(e/1)} images. Try something now, or save them for later.`,balanceUsd:t,examples:[{tool:"fal-flux-schnell",cost:"$0.01",what:"an AI image"},{tool:"or-gpt-4o-mini",cost:"token-priced",what:"a quick model call"},{tool:"fal-ace-step-music",cost:"$0.02",what:"a music track"}]}}}Qd();ea();var i2=require("fs"),plt=require("os"),S4e=require("path"),Jwr=(0,S4e.join)((0,plt.homedir)(),".visa-mcp"),llt=(0,S4e.join)(Jwr,"mcp-session-budget.json");function MJ(){try{(0,i2.existsSync)(llt)&&(0,i2.unlinkSync)(llt)}catch{}}var P4e=require("crypto"),hp=qe(Sp()),ew=null,ku=0,s2=0,Mc=0,o2=null,I4e=null,C4e=null,Q5=Promise.resolve();function Ywr(e){return Number((0,hp.fromCents)(e))}function mlt(e){return(0,hp.toCents)((0,hp.micros)(BigInt(e)))}function flt(e){return(0,hp.toWire)((0,hp.fromCents)(e))}function T4e(e){return typeof e=="number"&&Number.isSafeInteger(e)&&e>=0}function DJ(e){return typeof e=="string"&&/^\d+$/.test(e)}var Zwr=43,Xwr=new RegExp(`^[A-Za-z0-9_-]{${Zwr}}$`);function Qwr(e){return typeof e=="string"&&Xwr.test(e)}function e4r(e){return!(e.status!=="accepted"||typeof e.session_id!="string"||e.session_id.length===0||ew&&e.session_id!==ew||typeof e.nonce!="string"||e.nonce.length===0||!Qwr(e.server_signature)||!T4e(e.cumulative)||!T4e(e.remaining)||!T4e(e.delta)||e.cumulative<ku||Mc>0&&e.cumulative>Mc||Mc>0&&e.remaining>Mc||e.cumulative_micros!==void 0&&!DJ(e.cumulative_micros)||e.remaining_micros!==void 0&&!DJ(e.remaining_micros)||e.delta_micros!==void 0&&!DJ(e.delta_micros)||e.reserved_micros!==void 0&&!DJ(e.reserved_micros))}function Z1(e){ew=e,ku=0,s2=0,Mc=0,o2=null,I4e=null,C4e=null,Q5=Promise.resolve()}function vk(e){Mc=Math.max(0,Math.floor(e))}function O4e(){return ew}function R4e(e){if(!ew)return null;let t=ku+s2;return Mc>0&&t>Mc&&(t=Mc),{session_budget_id:ew,cumulative_micros:Ywr(t),nonce:(0,P4e.randomUUID)(),idempotency_key:e||(0,P4e.randomUUID)()}}function wk(e){if(!e)return null;let t;try{t=Buffer.from(e,"base64").toString("utf-8")}catch{return null}let r;try{r=JSON.parse(t)}catch{return null}if(!r||typeof r!="object")return null;let n=r;return e4r(n)?(ku=Math.max(ku,n.cumulative),s2=0,o2=n,n):null}function hlt(){return o2}function k4e(e){let t=mlt(e.cumulative_micros);ku=Math.max(ku,t),s2=0;let r={status:"accepted",session_id:e.session_budget_id,cumulative:ku,remaining:Math.max(0,Mc-ku),delta:0,cumulative_micros:flt(ku),remaining_micros:flt(Math.max(0,Mc-ku)),delta_micros:"0",nonce:e.nonce};return o2=r,r}function xk(e){if(!e||typeof e!="object")return;let t=e.cumulative_micros;if(typeof t!="string"||!/^\d+$/.test(t))return;let r;try{r=BigInt(t)}catch{return}if(r<0n)return;let n=(0,hp.toCents)((0,hp.micros)(r));if(!Number.isFinite(n)||n<0)return;I4e=t;let i=e,o=typeof i.session_id=="string"?i.session_id:ew??"";o2?(typeof i.remaining_micros=="string"&&/^\d+$/.test(i.remaining_micros)&&(o2.remaining_micros=i.remaining_micros),typeof i.charged_micros=="string"&&/^\d+$/.test(i.charged_micros)&&(o2.delta_micros=i.charged_micros)):o2={session_id:o,cumulative:n,remaining:0,delta:0,nonce:typeof i.transaction_id=="string"?i.transaction_id:"",remaining_micros:typeof i.remaining_micros=="string"&&/^\d+$/.test(i.remaining_micros)?i.remaining_micros:void 0,delta_micros:typeof i.charged_micros=="string"&&/^\d+$/.test(i.charged_micros)?i.charged_micros:void 0}}function ylt(e){let t=e.receipt??null;C4e={toolName:e.toolName,resolvedToolId:e.resolvedToolId,estimatedAmountCents:Math.max(0,Math.ceil(e.estimatedAmountCents)),voucherCumulativeCents:mlt(e.voucher.cumulative_micros),estimatedCumulativeCents:LJ(),receiptDeltaCents:typeof t?.delta=="number"?t.delta:null,receiptCumulativeCents:typeof t?.cumulative=="number"?t.cumulative:null,receiptRemainingCents:typeof t?.remaining=="number"?t.remaining:null,receiptDeltaMicros:typeof t?.delta_micros=="string"?t.delta_micros:null,receiptCumulativeMicros:typeof t?.cumulative_micros=="string"?t.cumulative_micros:null,receiptRemainingMicros:typeof t?.remaining_micros=="string"?t.remaining_micros:null,recordedAt:new Date().toISOString()}}function glt(){return C4e}function blt(){return ku}function _lt(){return I4e}function LJ(){let e=ku+s2;return Mc>0&&e>Mc&&(e=Mc),e}function B4e(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return Q5=Q5.then(()=>{s2+=t}),Q5}function Ek(e){if(!Number.isFinite(e)||e<=0)return Promise.resolve();let t=Math.ceil(e);return Q5=Q5.then(()=>{s2=Math.max(0,s2-t)}),Q5}var t4r=10,r4r=1,Ii=null,vlt=Promise.resolve();function N4e(e){let t=vlt.catch(()=>{}).then(e);return vlt=t.then(()=>{},()=>{}),t}var No=class extends Error{balanceCents;minRequiredCents;constructor(t,r){super(`Prepaid balance is $${(t/100).toFixed(2)}; at least $${(r/100).toFixed(2)} required to open a credit session. Top up via the buy_credits tool first.`),this.name="InsufficientBalanceError"}};async function j4e(e,t,r){return N4e(()=>wlt(e,t,r))}async function wlt(e,t,r){if(MJ(),Ii&&new Date(Ii.expiresAt).getTime()>Date.now())return O4e()!==Ii.budgetId&&(Z1(Ii.budgetId),vk(Ii.totalCents)),W.info("mcp-session:active-hit",{budgetId:Ii.budgetId,tool:r.toolName,remainingEstimatedCents:Ii.totalCents-LJ()}),{budgetId:Ii.budgetId,isFresh:!1,totalCents:Ii.totalCents,requestedCapCents:Ii.totalCents,appliedCapCents:Ii.totalCents,clampedReason:null};Ii&&(Ii=null,Z1(null));let n=await e.getBalance();if(!n.success)throw new Error(`Could not read balance: ${n.error||"unknown error"}`);let i=r.sessionKind??"explicit",o=i==="one_shot"?r4r:t4r,s=Math.max(o,Math.ceil(r.minRequiredCents??o));if(n.balanceCents<s)throw new No(n.balanceCents,s);let a=r.capCentsOverride??Q3e(),c=Math.min(a,n.balanceCents),u=c<a?"balance":null,d=await t("session_create",c,"Visa CLI Session",`open credit-model session with $${(c/100).toFixed(2)} cap`,r.userContext),l=await e.createSessionBudget({total_cents:c,session_kind:i,...d?{attestation:d}:{}});if(!l.success||!l.budget){let f=l.error||"unknown error";throw new Error(`Failed to open credit session: ${f}`)}let p={budgetId:l.budget.id,expiresAt:l.budget.expiresAt,totalCents:l.budget.totalCents,createdAt:l.budget.createdAt};return Ii=p,Z1(p.budgetId),vk(p.totalCents),W.info("mcp-session:opened",{budgetId:p.budgetId,capCents:p.totalCents,requestedCapCents:a,clampedReason:u,sessionKind:i,expiresAt:p.expiresAt,tool:r.toolName}),{budgetId:p.budgetId,isFresh:!0,totalCents:p.totalCents,requestedCapCents:a,appliedCapCents:p.totalCents,clampedReason:u}}async function xlt(e,t,r){return N4e(async()=>{let i=a2()?await Elt(e):null,o=await wlt(e,t,r);return{budgetId:o.budgetId,totalCents:o.totalCents,closedPrevious:i,requestedCapCents:o.requestedCapCents,appliedCapCents:o.appliedCapCents,clampedReason:o.clampedReason}})}async function Elt(e){let r=a2()?.budgetId??O4e(),n=!1,i,o;if(r)try{let s=await e.closeSession(r);n=!!s?.success,typeof s?.finalCumulativeCents=="number"&&(i=s.finalCumulativeCents),typeof s?.finalCumulativeMicros=="string"&&(o=s.finalCumulativeMicros)}catch(s){W.warn("mcp-session:close-server-failed",{budgetId:r,error:s?.message||String(s)})}return MJ(),Ii=null,Z1(null),{closedServerSide:n,budgetId:r,finalCumulativeCents:i,finalCumulativeMicros:o}}async function HJ(e){return N4e(()=>Elt(e))}function a2(){return MJ(),Ii?new Date(Ii.expiresAt).getTime()<=Date.now()?(Ii=null,Z1(null),null):{budgetId:Ii.budgetId,totalCents:Ii.totalCents,lastReceiptCumulative:blt(),lastReceiptCumulativeMicros:hlt()?.cumulative_micros??null,ledgerReceiptCumulativeMicros:_lt(),estimatedCumulative:LJ(),lastToolSpend:glt(),expiresAt:Ii.expiresAt}:null}var Slt=qe(Sp()),Alt=10000n;function n4r(e){return e<=0n?0:Number((e+Alt-1n)/Alt)}function Tlt(e){return n4r((0,Slt.fromUsd)(e))}var zJ=qe(Sp()),i4r=/^(?:0|[1-9]\d*)(?:\.\d{1,2})?$/;function Plt(e){if(typeof e!="string"||!i4r.test(e))return{ok:!1,error:"amount must be a USD amount with at most two decimal places"};let[t,r=""]=e.split("."),n=BigInt(t)*100n+BigInt(r.padEnd(2,"0"));if(n>BigInt(Number.MAX_SAFE_INTEGER))return{ok:!1,error:"amount is too large"};let i=Number(n);return i<=0?{ok:!1,error:"amount must be greater than $0.00"}:{ok:!0,cents:i,displayUsd:(0,zJ.toDisplay)((0,zJ.fromCents)(i),{symbol:""})}}var L4e=require("node:os"),Sk=require("node:path"),D4e=require("node:fs/promises"),klt=require("node:fs"),Blt=require("node:url");ea();var tw=class extends Error{constructor(t){super(t),this.name="PayValidationError"}};function Ilt(e){let t;try{t=new URL(e)}catch{throw new tw(`Invalid URL: ${e}. Expected a fully-qualified http(s) URL.`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new tw(`Unsupported URL scheme "${t.protocol}". Only http and https are allowed.`);return t}ea();var o4r={get_visa_smi:"get_visa_smi",pay_merchant:"checkout_agent_access"},Clt=300*1e3,q4e={},U4e=0,Ak=null;function M4e(){return Ak||(Ak=(async()=>{try{let e=await De.getFeatureFlags();q4e=e&&e.flags||{},U4e=Date.now()}catch(e){q4e={},W.warn("feature-flags:fetch-failed",{error:e instanceof Error?e.message:String(e)})}finally{Ak=null}})(),Ak)}async function Olt(){await M4e()}function Rlt(){Date.now()-U4e<Clt||M4e()}async function FJ(){Date.now()-U4e<Clt||await M4e()}function rw(e){let t=o4r[e];return t?q4e[t]!==!0:!1}function Nlt(e){return[(0,Sk.join)(e,"checkout-engine","index.js"),(0,Sk.join)(e,"..","checkout-engine","index.js")]}function s4r(e,t=klt.existsSync){return Nlt(e).find(r=>t(r))??null}var $J=null,a4r=async()=>{if($J)return $J;let e=s4r(__dirname);if(!e)throw new Error(`Cannot find module: the checkout engine was not packaged (looked in ${Nlt(__dirname).join(" and ")}).`);return $J=(await import((0,Blt.pathToFileURL)(e).href)).createCliCheckoutEngine(),$J};async function c4r(){return rw("pay_merchant")?(await FJ(),rw("pay_merchant")):!1}var u4r=(0,Sk.join)((0,L4e.homedir)(),".visa-mcp","agent-credential.json"),d4r=(0,Sk.join)((0,L4e.homedir)(),".visa-mcp","contact.json");function l4r(e){return e.replace(/https?:\/\/[^\s"')\]]+/gi,t=>{try{return new URL(t).origin}catch{return"[url]"}}).slice(0,300)}async function VJ(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}}),result_success:e.success,result_error:e.errorMessage?l4r(e.errorMessage):null,result_json:JSON.stringify({outcome:e.outcome,confirmationRef:e.confirmationRef??null}),payment_rail:e.action==="pay"?"card":null,payment_amount:e.action==="pay"?e.amountMinor:null,payment_currency:e.currency==="USD"?"USD":null,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){W.warn("pay_merchant:telemetry_failed",{action:e.action,error:t instanceof Error?t.message:String(t)})}}function p4r(e){if(typeof e!="string"||!/^\d+(\.\d{1,2})?$/.test(e)||Number(e)<=0)throw new tw(`Invalid amount ${JSON.stringify(e)}. Expected a positive decimal like "5.00".`);return e}async function jlt(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:Um();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??c4r)())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(o!=="review"&&o!=="pay")return{success:!1,message:`Unknown pay_merchant action ${JSON.stringify(o)}. Use "review" (default) or "pay".`};let s,a,c=(e.currency??"USD").toUpperCase();if(!/^[A-Z]{3}$/.test(c))return{success:!1,message:`Invalid currency ${JSON.stringify(e.currency)}. Expected a 3-letter ISO code like "USD".`};try{s=Ilt(e.url??"").toString(),a=p4r(e.amount)}catch(T){if(T instanceof tw)return{success:!1,message:T.message};throw T}let u=t.credentialPath??u4r,d=t.contactPath??d4r;try{await(0,D4e.readFile)(u,"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 l;try{l=JSON.parse(await(0,D4e.readFile)(d,"utf8"))}catch{return{success:!1,message:`No contact details at ${d}. Write your name/email/address there (chmod 600) first.`}}let p=null;if(o==="pay"){let T=typeof e.confirm=="string"?e.confirm.trim():"",O=/^PAY (\S+)$/.exec(T);if(!O)return{success:!1,action:"pay",message:'Confirmation required: pass confirm:"PAY <reviewId>" using the reviewId from a prior pay_merchant { action:"review" } call. Nothing was charged.'};p=O[1]}let f=t.loadEngine??a4r,m;try{m=await f()}catch(T){let O=T instanceof Error?T.message:String(T);if(/ERR_MODULE_NOT_FOUND|Cannot find (module|package)/.test(O))return{success:!1,message:/checkout engine was not packaged/.test(O)?"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 T}let h={url:s,amount:a,currency:c,credentialPath:u,contact:l,approvalBaseUrl:n},y=t.emitTelemetry??(T=>De.emitTelemetry(T)),v=new URL(s).hostname,x=Math.round(Number(a)*100),_=Date.now();if(o==="review"){W.info("pay_merchant:review",{host:v,currency:c});let T;try{T=await m.review(h)}catch(O){throw await VJ({emitTelemetry:y,action:"review",merchantHost:v,amountMinor:x,currency:c,outcome:"engine-error",success:!1,errorMessage:O instanceof Error?O.message:String(O),startedAt:_}),O}return await VJ({emitTelemetry:y,action:"review",merchantHost:v,amountMinor:x,currency:c,outcome:"reviewed",success:!0,startedAt:_}),{success:!0,action:"review",...T,message:`Review ${T.reviewId}: ${T.merchantHost} wants ${T.amountMinor} ${T.currency} (minor units). To authorize, call pay_merchant { action: "pay", url, amount, confirm: "PAY ${T.reviewId}" }. No charge yet.`}}let w=p,E=t.allowSubmit??process.env.CHECKOUT_AGENT_ALLOW_SUBMIT==="1";W.info("pay_merchant:pay",{reviewId:w,submit:E});let A;try{A=await m.pay({...h,reviewId:w,submit:E})}catch(T){throw await VJ({emitTelemetry:y,action:"pay",merchantHost:v,amountMinor:x,currency:c,outcome:"engine-error",success:!1,errorMessage:T instanceof Error?T.message:String(T),startedAt:_,submit:E}),T}let S=A.outcome==="confirmed"||A.outcome==="filled-dry-run";return await VJ({emitTelemetry:y,action:"pay",merchantHost:v,amountMinor:x,currency:c,outcome:A.outcome,confirmationRef:A.confirmationRef,success:S,errorMessage:S?null:A.detail??A.outcome,startedAt:_,submit:E}),{success:S,action:"pay",reviewId:w,...A,message:A.outcome==="confirmed"?`Paid. Confirmation ${A.confirmationRef??"(none captured)"} \xB7 receipt ${A.receiptPath??"(not written)"}.`:`Outcome: ${A.outcome}${A.detail?` \u2014 ${A.detail}`:""}. Do not retry blindly \u2014 verify with the merchant before any re-run.`}}var qlt="Buying credits requires local biometric attestation from a Touch ID-capable Mac or a Windows Hello-capable PC running the Visa CLI. This device cannot create the required attestation, so no card charge was attempted. Credits are account-level, so you can top up this account from any interactive biometric-capable CLI, then use the balance from this remote server.",Ult="Tell the user that buying credits requires a local CLI/MCP process with Touch ID (Mac) or Windows Hello (PC) today. Credits are account-level: suggest topping up the same account from any interactive biometric-capable CLI, then continuing on this remote server. Do not retry buy_credits from this process; it cannot produce the required card-charge attestation.";Qd();var Pft=Promise.resolve();function L3r(e,t){if(e)try{let r=(0,bY.fromWire)(e),n=r%10000n===0n?2:6;return(0,bY.toDisplay)(r,{decimals:n})}catch{}return`$${(t/100).toFixed(2)}`}var Ift=!1,Cft=!1,Oft=!1;function vY(e){let t=Pft.catch(()=>{}).then(e);return Pft=t.then(()=>{},()=>{}),t}async function Hft(e){let t=await qo(()=>j4e(De,Yd,{toolName:e.toolId,userContext:e.userContext}));await B4e(e.estimatedAmountCents);let r=R4e(e.idempotencyKey);if(!r)throw await Ek(e.estimatedAmountCents),new Error(`Internal: failed to mint voucher for active session ${t.budgetId}`);let n=await G3r(),i,o,s=async()=>De.shortcutWithSession(e.toolId,r,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);try{try{({data:i,voucherReceiptHeader:o}=await s())}catch(d){if(d instanceof qm){let l=Math.min(Math.max(d.retryAfterSecs,0),5)*1e3;W.warn("mcp-session:lock-contended-retrying",{tool:e.toolId,retryAfterSecs:d.retryAfterSecs}),await new Promise(p=>setTimeout(p,l)),{data:i,voucherReceiptHeader:o}=await s()}else throw d}}catch(d){if(await Ek(e.estimatedAmountCents),d instanceof Iw){if(W.warn("mcp-session:server-invalidated-budget",{code:d.code,budgetId:d.budgetId??t.budgetId,tool:e.toolId}),await HJ(De),process.env.VISA_REQUIRE_EXPLICIT_SESSION==="true")throw new Error(`Your session was closed by another process (${d.code}). Restart MCP or run start_session again.`);return Oft||(Oft=!0,console.error(`[visa-cli] Your session was closed by another process; reopened automatically as pay-as-you-go.
|
|
20660
|
+
To require an explicit session approval instead, set VISA_REQUIRE_EXPLICIT_SESSION=true.`)),W.info("mcp-session:falling-back-to-payg",{code:d.code,tool:e.toolId}),zft(e)}throw d instanceof qm?(W.warn("mcp-session:lock-contended-give-up",{tool:e.toolId}),new Error("Another paid call is currently in progress on this session. Wait a moment and try again.")):d}let a=wk(o)??(r?k4e(r):null);if(xk(i?.receipt_v2),ylt({toolName:e.metaTool??e.toolId,resolvedToolId:e.toolId,estimatedAmountCents:e.estimatedAmountCents,voucher:r,receipt:a}),M8e(i))return Sm(i);let c=await U8e();if(e.idempotencyKey&&D8e(i,c,e.idempotencyKey))return Sm(i);let u=c?qk(c):null;return Sm(L8e(i,n,u))}function Gd(e){return{success:!1,error:e.message,error_code:"INSUFFICIENT_BALANCE",balanceCents:e.balanceCents,suggestedTool:"buy_credits"}}function hY(e){if(e===null||typeof e!="object"){let r=JSON.stringify(e);return r===void 0?String(e):r}return Array.isArray(e)?`[${e.map(hY).join(",")}]`:`{${Object.entries(e).sort(([r],[n])=>r.localeCompare(n)).map(([r,n])=>`${JSON.stringify(r)}:${hY(n)}`).join(",")}}`}function q8e(e,t,r,n){let i=jo.createHash("sha256").update(`${r}:${hY(n)}`).digest("hex").slice(0,24);return`batch:${e}:${t}:${i}`}function H3r(e,t){return`${e}:${t}`}function z3r(e){if(e==null)return;let t=String(e);if(t.length!==0)return t.startsWith("ledger_")?t:/^\d+$/.test(t)?`ledger_${t}`:t}function yY(e,t,r){let n=r?.amountMicros??r?.amount_micros??r?.charged_micros??r?.receipt_v2?.charged_micros??r?.receipt_v2?.actual_micros,i=gp(n),o=i!==null?i.toString():void 0,s=r?.transaction_id??r?.transactionId??r?.receipt_v2?.transaction_id,a=z3r(r?.ledger_id??r?.ledgerId??r?.receipt_v2?.ledger_id),c=s!=null?String(s):a;return{batch_id:e,item_id:H3r(e,t),index:t,...c!==void 0?{transaction_id:c}:{},...a!==void 0?{ledger_id:a}:{},...o?{amountMicros:o,amount_micros:o,cost_micros:o}:{}}}async function zft(e){return qo(()=>$3r(e))}async function Fft(e,t,r){if(M8e(e))return Sm(e);let n=await U8e();if(r&&D8e(e,n,r))return Sm(e);let i=n?qk(n):null;return Sm(L8e(e,t,i))}async function F3r(e){let t=e.cap,r=`spend up to $${(e.estimatedAmountCents/100).toFixed(2)} on ${e.toolId} (call cap $${(t/100).toFixed(2)})`,n=await Yd("shortcut_call",t,e.toolId,r,e.userContext);W.info("parentless-single-call:attempt",{tool:e.toolId,approvedMaxCents:t,attested:!!n});let i=n?.nonce??(await De.getAttestationChallenge()).nonce,{data:o,voucherReceiptHeader:s}=await De.shortcutParentless(e.toolId,{...n?{attestation:n}:{},nonce:i,approved_max_cents:t,idempotency_key:e.idempotencyKey},e.toolParams,e.timeoutMs,e.userContext,e.metaTool);return wk(s),xk(o?.receipt_v2),W.info("parentless-single-call:completed",{tool:e.toolId}),Fft(o,e.beforeBalanceMicros,e.idempotencyKey)}async function $3r(e){let t=Math.max(1,Math.ceil(e.estimatedAmountCents)),r=await De.getBalance();if(!r.success)throw new Error(`Could not read balance: ${r.error||"unknown error"}`);if(r.balanceCents<t)throw new No(r.balanceCents,t);let n=t,i=qk(r);if(Xdt()&&!Ift){let d=e.idempotencyKey??jo.randomUUID();try{return await F3r({toolId:e.toolId,toolParams:e.toolParams,estimatedAmountCents:e.estimatedAmountCents,cap:n,beforeBalanceMicros:i,userContext:e.userContext,metaTool:e.metaTool,timeoutMs:e.timeoutMs,idempotencyKey:d})}catch(l){if(l instanceof Ap)Ift=!0,W.info("parentless-single-call:falling-back-to-session",{tool:e.toolId,status:l.status,serverErrorCode:l.serverErrorCode});else throw l}}let o=`spend up to $${(e.estimatedAmountCents/100).toFixed(2)} on ${e.toolId} (session cap $${(n/100).toFixed(2)})`,s=await Yd("session_create",n,"Visa CLI Session",o,e.userContext),a=await De.createSessionBudget({total_cents:n,session_kind:"one_shot",...s?{attestation:s}:{}});if(!a.success||!a.budget)throw new Error(`Failed to open on-demand session: ${a.error||"unknown error"}`);let c=a.budget.id;Z1(c),vk(a.budget.totalCents),W.info("on-demand-session:opened",{budgetId:c,capCents:a.budget.totalCents,tool:e.toolId});let u=!1;try{await B4e(e.estimatedAmountCents);let d=R4e(e.idempotencyKey);if(!d)throw await Ek(e.estimatedAmountCents),new Error(`Internal: mintVoucher returned null after on-demand session-open ${c}`);let{data:l,voucherReceiptHeader:p}=await De.shortcutWithSession(e.toolId,d,e.toolParams,e.timeoutMs,e.userContext,e.metaTool);if(wk(p)||k4e(d),u=!0,xk(l?.receipt_v2),M8e(l))return Sm(l);let f=await U8e();if(e.idempotencyKey&&D8e(l,f,e.idempotencyKey))return Sm(l);let m=f?qk(f):null;return Sm(L8e(l,i,m))}catch(d){throw u||await Ek(e.estimatedAmountCents),d}finally{try{await De.closeSession(c)}catch(d){W.warn("on-demand-session:close-failed",{budgetId:c,error:d?.message||String(d)})}Z1(null),W.info("on-demand-session:closed",{budgetId:c,tool:e.toolId})}}async function b2(e){return vY(async()=>a2()?Hft(e):zft(e))}function wY(){return ta()}var De=new lB(()=>ra.getSessionToken());function gp(e){if(typeof e!="string"||!/^-?\d+$/.test(e))return null;try{return BigInt(e)}catch{return null}}function qk(e){return gp(e.balanceMicros)??BigInt(e.balanceCents)*10000n}function V3r(e){if(e<0n&&(e=0n),e>=1000000n){let n=(e+5000n)/10000n,i=n/100n,o=n%100n;return`$${i.toString()}.${o.toString().padStart(2,"0")}`}let t=e%1000000n;return t===0n?"$0.00":`$0.${t.toString().padStart(6,"0").replace(/0+$/,"")}`}function K3r(e){let t=gp(e.ledgerReceiptCumulativeMicros);if(t!==null)return{micros:t,source:"ledgerReceiptCumulativeMicros"};let r=gp(e.lastReceiptCumulativeMicros);if(r!==null)return{micros:r,source:"lastReceiptCumulativeMicros"};let n=gp(e.lastToolSpend?.receiptCumulativeMicros);return n!==null?{micros:n,source:"lastToolSpend.receiptCumulativeMicros"}:{micros:BigInt(Math.max(0,e.estimatedCumulative))*10000n,source:"estimatedCumulativeCents"}}function jk(e,t="INVALID_TOOL_PARAMS",r){return{success:!1,error_code:t,code:t,error:e,message:e,...r??{}}}function W3r(e){return{success:!1,error_code:"TOOL_EXECUTION_FAILED",code:"TOOL_EXECUTION_FAILED",error:e.message||"Tool execution failed.",message:e.message||"Tool execution failed.",tool_id:e.toolId,surface:e.surface,merchantName:e.merchantName,amount:e.amount,payment_finalized:!1,charged:!1}}async function G3r(){try{let e=await De.getBalance();return e.success?qk(e):null}catch{return null}}async function U8e(){try{let e=await De.getBalance();return e.success?e:null}catch{return null}}function M8e(e){if(!e||e.success===!1)return!1;let t=gp(e.receipt_v2?.charged_micros??e.receipt_v2?.actual_micros),r=gp(e.amountMicros??e.amount_micros??e.charged_micros),n=t??r;if(n===null||n<=0n)return!1;let i=n.toString();return e.amountMicros??=i,e.amount_micros??=i,e.charged_micros??=i,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(n)/1e6),!0}function D8e(e,t,r){if(!e||e.success===!1||!t||!Array.isArray(t.ledger))return!1;let n=t.ledger.find(a=>a.idempotencyKey===r);if(!n)return!1;let i=gp(n.deltaMicros)??BigInt(n.deltaCents)*10000n,o=i<0n?-i:i;if(o<=0n)return!1;let s=o.toString();return e.amountMicros??=s,e.amount_micros??=s,e.charged_micros??=s,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(o)/1e6),!0}function L8e(e,t,r){if(!e||e.success===!1||t===null||r===null)return e;let n=t-r;if(n<=0n)return e;let i=n.toString();return e.amountMicros??=i,e.amount_micros??=i,(typeof e.amount!="number"||e.amount<=0)&&(e.amount=Number(n)/1e6),e}var J3r="4.1.0-rc.25",h3n=["","","You're ready to go! Try:","","Core:",'\u2022 "Show my account status" \u2192 get_status','\u2022 "List my enrolled cards" \u2192 get_cards','\u2022 "Show my paid tool use history" \u2192 transaction_history','\u2022 "Set my daily top-up limit to $50" \u2192 update_spending_controls','\u2022 "Generate 3 variations in parallel" \u2192 batch',"","Tool catalog:",'\u2022 "Find an image upscaler" \u2192 discover_tools','\u2022 "Generate an image of a sunset over Tokyo" \u2192 discover_tools \u2192 execute_tool','\u2022 "Make a 4-second video of a penguin juggling" \u2192 discover_tools \u2192 execute_tool','\u2022 "Make a song about coding late at night" \u2192 discover_tools \u2192 execute_tool','\u2022 "Run a reasoning model on this prompt" \u2192 discover_tools \u2192 execute_tool','\u2022 "Run fal-aura-sr on this URL" \u2192 execute_tool'].join(`
|
|
20661
20661
|
`);function Jd(e){if(!e||typeof e!="string")return{opened:!1,blockedReason:"invalid_url"};let t=xB(e);if(!t)return{opened:!1,blockedReason:"invalid_url"};if(Y3e())return{opened:!1,url:t,blockedReason:"suppressed"};let r=vZ();if(r.headless)return W.info(`Browser auto-open skipped (${r.reason}). URL: ${t}`),{opened:!1,url:t,blockedReason:"headless"};let i=[wY(),Um()].filter(s=>!!s).map(s=>M9e(t,s)).find(Boolean)??null;if(!i)return W.info(`Browser auto-open skipped (non-internal host). URL: ${t}`),{opened:!1,url:t,blockedReason:"non_internal_host"};let o=wZ(i);return o?((0,Lft.execFile)(o.cmd,o.args,s=>{s&&W.warn(`Browser open failed: ${s.message}. URL: ${i}`)}),{opened:!0,url:i}):(W.info(`No browser command for platform "${Mk.platform()}". URL: ${i}`),{opened:!1,url:i,blockedReason:"unsupported_platform"})}async function qo(e){return ilt(De,e,Xft)}var $ft="get_cards",Vft="set_default_card";function Y3r(e,t=60){return`The processor returned a transient decline (code ${e??"unknown"}). This is not a permanent failure \u2014 it usually clears within ~${t} seconds and is most often triggered by rapid successive charges on the same card. Tell the user the call was temporarily declined and that you will retry shortly, then wait at least ${t} seconds before retrying the SAME call exactly once. Do not retry more than once. Do not assume the user has run out of funds. IMPORTANT: If the retry also fails, do NOT retry again \u2014 instead tell the user their default card may be temporarily locked by the processor and suggest switching to a different card. They can run '${$ft}' to see enrolled cards and '${Vft}' to switch, then retry the original request.`}function Z3r(e,t){return`The processor returned a non-retryable decline (code ${e??"unknown"}). Stop the current task and tell the user their card was declined for ${t||"the merchant"}. Suggest they check their card status or available balance. If they want to try a different default card, they can run '${$ft}' to see enrolled cards and '${Vft}' to switch. Do not retry automatically.`}function _p(e,t){let r=e.retryable?Y3r(e.code,e.retryAfter):Z3r(e.code,t.merchantName);return{success:!1,declined:!0,retryable:e.retryable,code:e.code,reason:e.reason,payment_error_class:e.paymentErrorClass,correlation_id:e.correlationId,transactionId:e.transactionId,retryAfter:e.retryAfter,merchantName:t.merchantName,amount:t.amount,message:e.message,agent_guidance:r}}function X3r(e){return{success:!1,error:e.message,error_code:e.code,transactionId:e.transactionId,reconciliation_required:e.reconciliationRequired,retryable:e.retryable,agent_guidance:"The top-up charge outcome is ambiguous. Tell the user not to retry with a new idempotency key or start another top-up. They should check transaction_history in a few minutes or contact support with the transactionId."}}var kA=null,Q3r=3e4;function Kft(){kA=null}var g2=class extends Error{constructor(r){super(`${gY()} attestation is required for this action, but it is not available in this MCP process. `+H8e());this.context=r;this.name="AttestationUnavailableError"}context;code="BIOMETRIC_UNAVAILABLE"};function xY(e,t){return{success:!1,error:e.code,message:e.message,action:t,agent_guidance:`Biometric attestation is required for ${t}, but this MCP process cannot create a local attestation. `+H8e()+" Do not retry this MCP tool until the user has completed the interactive step or changed their biometric policy."}}function e9r(){return{success:!1,error:"BIOMETRIC_UNAVAILABLE",error_code:"BIOMETRIC_UNAVAILABLE",action:"buy_credits",message:qlt,agent_guidance:Ult}}function gY(){return process.platform==="darwin"?"Touch ID":"local biometric"}function H8e(){return process.platform==="darwin"?"Run the action from an interactive terminal with Touch ID access, or call auth_recovery to re-sync a drifted local attestation key, or use reset with confirm:true to clear stale server biometric state through GitHub re-authentication.":"This platform cannot create Visa CLI Touch ID attestations. Call auth_recovery to re-sync a drifted local attestation key, or use reset with confirm:true to clear stale server biometric state through GitHub re-authentication."}async function t9r(e){let t=Date.now();if(kA&&kA.expiresAt>t)return{required:kA.required,hasRegisteredKey:kA.hasRegisteredKey};try{let r=await De.getStatus(e),n=wA(r),i=r.attestationRequired!==!1;return kA={required:i,hasRegisteredKey:n,expiresAt:t+Q3r},{required:i,hasRegisteredKey:n}}catch{return{required:!0,hasRegisteredKey:!0}}}async function Yd(e,t,r,n,i,o){if(!o?.forceRequired){let s=await t9r(i);if(!s.required){W.info("attestation:skipped-by-server-policy",{context:e});return}if(!s.hasRegisteredKey){W.info("attestation:skipped-no-registered-key",{context:e});return}}if(!rl())throw W.warn("attestation:unavailable",{context:e}),new g2(e);W.info("attestation:attempt",{context:e,amount:t,merchant:r});try{let{nonce:s}=await De.getAttestationChallenge(),a=Buffer.from(JSON.stringify({nonce:s,amount:t,merchant:r,context:e})).toString("base64");W.info("touchid:prompt",{context:e,amount:t,merchant:r});let c=await q9e(a,n);return W.info("attestation:success",{context:e,amount:t,merchant:r}),{signature:c,nonce:s,amount:t,merchant:r}}catch(s){throw/cancel|dismiss/i.test(s.message??"")?(W.warn("attestation:cancelled",{context:e,merchant:r}),new Error("Touch ID was cancelled or dismissed. For automated environments (CI, scripts, MCP hooks without user present), run `visa-cli config biometric off` to enable paid calls without Touch ID.")):(W.error("attestation:failure",{context:e,amount:t,merchant:r,error:s.message}),s)}}var Rft="[dry-run] https://placeholder.visa-cli.dev/image.png",r9r=new Set(["generate_image_card","generate_image_fast_card","generate_image_schnell_card","generate_image_recraft_card","generate_image_ideogram_card","edit_image_seed_card","fal-flux-pro-ultra","fal-flux-pro","fal-flux-dev","fal-flux-schnell","fal-ideogram-v2","fal-ideogram-v2-turbo","fal-recraft-v3","fal-fast-sdxl"]),n9r=new Set(["generate_video_tempo_card","generate_video_kling_card","generate_video_wan_card","generate_video_minimax_card","fal-kling-video","fal-wan-video","fal-kling-i2v","fal-minimax-video"]);function i9r(e){return e.startsWith("or-")?"llm":r9r.has(e)?"image":n9r.has(e)?"video":o9r(e)?"media":null}function o9r(e){let t=DA(e);return t?!EY(t):!1}function s9r(e){return(typeof e.prompt=="string"?e.prompt:"").slice(0,100)}function a9r(e){return e==="llm"?"OpenRouter":"fal.ai"}function BA(e,t,r,n){let i={success:!0,transactionId:`dry-run:${n??t}`,amount:0,rail:"dry_run",merchantName:a9r(e),dry_run:!0,metadata:{dry_run:!0}};if(e==="llm"){let s=`[dry-run] echo: ${s9r(r)}`;return{...i,content:s,data:{content:s,model:t,dry_run:!0}}}return{...i,urls:[Rft],data:{[e==="video"?"videoUrl":e==="image"?"imageUrl":"url"]:Rft,metadata:{dry_run:!0}}}}async function B8e(e){let t=e.mode??"mock",r=t==="preflight"?"/v1/telemetry/preflight":"/v1/telemetry/dry-run",n=t==="preflight"?"preflight":null;try{await De.emitTelemetry([{id:jo.randomUUID(),timestamp:new Date().toISOString(),tool_name:e.toolName,user_prompt:e.userContext??"",tool_params:JSON.stringify(e.toolParams),result_success:!0,result_error:null,result_json:JSON.stringify(e.result),payment_rail:n,payment_amount:0,payment_currency:"USD",merchant_name:e.result.merchantName,transaction_id:e.result.transactionId,tx_hash:null,protocol:null,http_status:200,duration_ms:Math.max(0,Date.now()-e.startedAt),source:"cli",event_kind:"mcp_tool",endpoint:r,resolved_model:e.resolvedModel,session_budget_id:null}])}catch(i){W.warn("dry_run:telemetry_failed",{tool:e.toolName,error:i?.message||String(i),mode:t})}}var c9r="https://openrouter.ai/api/v1/chat/completions",u9r="openrouter/free",d9r=50,l9r=15e3;function p9r(e){let t=[e.prompt,e.user_prompt,e.input,e.text];for(let r of t)if(typeof r=="string"&&r.trim().length>0)return r;return"preflight"}async function f9r(e,t,r){let n=process.env.OPENROUTER_API_KEY;if(!n)return W.warn("preflight:no_openrouter_key_falling_back_to_mock",{tool:e}),{result:BA("llm",e,t,r),degraded:!0,resolvedModel:null};let i=p9r(t),o;try{o=await Ep(c9r,{method:"POST",headers:{Authorization:`Bearer ${n}`,"Content-Type":"application/json","HTTP-Referer":"https://visacli.sh/preflight","X-Title":"Visa CLI Preflight"},body:JSON.stringify({model:u9r,messages:[{role:"user",content:i}],max_tokens:d9r}),timeoutMs:l9r})}catch(d){return W.warn("preflight:openrouter_network_error_falling_back_to_mock",{tool:e,error:d?.message||String(d)}),{result:BA("llm",e,t,r),degraded:!0,resolvedModel:null}}if(!o.ok){let d=await o.text().catch(()=>"");return W.warn("preflight:openrouter_http_error_falling_back_to_mock",{tool:e,status:o.status,bodyExcerpt:d.slice(0,200)}),{result:BA("llm",e,t,r),degraded:!0,resolvedModel:null}}let s;try{s=await o.json()}catch(d){return W.warn("preflight:openrouter_invalid_json_falling_back_to_mock",{tool:e,error:d?.message||String(d)}),{result:BA("llm",e,t,r),degraded:!0,resolvedModel:null}}let a=typeof s?.choices?.[0]?.message?.content=="string"?s.choices[0].message.content:"",c=typeof s?.model=="string"?s.model:null;return{result:{success:!0,transactionId:`preflight:${r??e}`,amount:0,rail:"preflight",merchantName:"OpenRouter",dry_run:!0,preflight:!0,metadata:{dry_run:!0,preflight:!0,model_used:c},content:a,data:{content:a,model:c??e,dry_run:!0,preflight:!0}},degraded:!1,resolvedModel:c}}async function Dk(e,t,r,n){let i=b4e();if(!i)return null;let o=i9r(e);if(!o)return null;let s=Date.now();if(i==="mock"){let u=BA(o,e,t,n);return await B8e({toolName:n??e,resolvedModel:n&&n!==e?e:null,toolParams:t,result:u,userContext:r,startedAt:s,mode:"mock"}),W.info("dry_run:payment_intercepted",{tool:e,metaTool:n,kind:o,mode:i}),u}if(o!=="llm"){W.warn("preflight:not_supported_for_kind_falling_back_to_mock",{tool:e,kind:o});let u=BA(o,e,t,n);return await B8e({toolName:n??e,resolvedModel:n&&n!==e?e:null,toolParams:t,result:u,userContext:r,startedAt:s,mode:"preflight"}),u}let{result:a,resolvedModel:c}=await f9r(e,t,n);return await B8e({toolName:n??e,resolvedModel:c??(n&&n!==e?e:null),toolParams:t,result:a,userContext:r,startedAt:s,mode:"preflight"}),W.info("dry_run:payment_intercepted",{tool:e,metaTool:n,kind:o,mode:i}),a}async function nh(e,t,r,n){let i=await De.paymentPreview({tool:e,url:t,...n&&Object.keys(n).length>0?{params:n}:{}},r);if(!i||!i.merchantName||i.amount===void 0||i.amount===null||i.amount<0)throw new Error("Could not determine payment amount and merchant. Try again.");if(!Number.isFinite(i.amount)||i.amount<0||i.amount>999999)throw new Error(`Invalid payment amount: ${i.amount}. Payment rejected for safety.`);return i}function ih(e){return Tlt(e.amount)}function m9r(e,t,r){return r.has(e.resolvedTool)?0:Math.max(1,ih(t[e.resolvedTool]))}function h9r(){return _Y.join(Mk.homedir(),".visa-mcp","allium-results")}var y3n=16*1024,g3n=50*1024*1024;function y9r(){let e=h9r();try{if(!bp.existsSync(e))return{file_count:0,size_bytes:0,path:e};let t=bp.readdirSync(e),r=0,n=0;for(let i of t)try{let o=bp.statSync(_Y.join(e,i));o.isFile()&&(r+=o.size,n++)}catch{}return{file_count:n,size_bytes:r,path:e}}catch(t){return W.warn("allium:disk_usage_error",{error:t.message}),{file_count:0,size_bytes:0,path:e}}}var kft=3600*1e3,N8e=0;function g9r(e){let t=e instanceof Error?e.message:String(e);return/Unexpected response from \/v1\/feed/.test(t)}async function Lk(e){if(!Z3e()&&!(Date.now()<N8e))try{if(!await ra.getSessionToken())return;await De.feedSubmit({prompt:e.prompt,tool:e.tool,media_url:e.mediaUrl,media_type:e.mediaType,cost:e.cost,transaction_id:e.transactionId,auto:!0,...e.userContext&&{user_context:e.userContext}}),W.info("feed:submitted",{tool:e.tool,mediaType:e.mediaType,transactionId:e.transactionId})}catch(t){if(g9r(t)){let r=N8e===0;N8e=Date.now()+kft,r&&W.debug?.("feed:endpoint-unavailable",{tool:e.tool,backoff_ms:kft});return}W.warn("feed:submit-failed",{tool:e.tool,error:t?.message||String(t)})}}async function b9r(e,t){let r=(e.state||"").trim().toUpperCase(),n=(e.county||"").trim(),i=(e.start_date||"").trim(),o=(e.end_date||i).trim();if(!/^[A-Z]{2}$/.test(r))throw new Error('state must be a 2-letter US state code (e.g. "VA").');if(!n)throw new Error("county is required.");if(!/^\d{4}-\d{2}$/.test(i))throw new Error('start_date must be YYYY-MM (e.g. "2025-08").');if(o&&!/^\d{4}-\d{2}$/.test(o))throw new Error("end_date must be YYYY-MM.");let s="Visa SMI",a=.1,c=`Pay $0.10 to ${s} for SMI data (${r} / ${n})`;W.info("payment:attempt",{tool:"get_visa_smi",amount:a,merchant:s});try{return await qo(async()=>{let u=await Yd("get_visa_smi",a,s,c),d=await De.getVisaSmi({state:r,county:n,start_date:i,end_date:o,attestation:u,idempotencyKey:jo.randomUUID()},t);return d.success?W.info("payment:success",{tool:"get_visa_smi",merchant:s,charged_cents:d.charged_cents}):W.warn("payment:declined",{tool:"get_visa_smi",merchant:s,message:d.error}),d})}catch(u){if(u instanceof Oi)return W.warn("payment:declined",{tool:"get_visa_smi",merchant:s,code:u.code,retryable:u.retryable}),_p(u,{amount:a,merchantName:s,description:"Visa SMI data"});throw W.error("payment:failure",{tool:"get_visa_smi",merchant:s,error:u.message}),u}}async function _9r(e,t){if(!e.prompt||!e.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let r=await Dk("generate_image_card",e,t);if(r)return r;let n=await nh("generate_image_card",void 0,t),i=jo.randomUUID();W.info("payment:attempt",{tool:"generate_image_card",amount:n.amount,merchant:n.merchantName});try{return await qo(async()=>{let o;try{o=await b2({toolId:"generate_image_card",toolParams:e,estimatedAmountCents:ih(n),userContext:t,timeoutMs:12e4,idempotencyKey:i})}catch(s){if(s instanceof No)return Gd(s);throw s}return W.info("payment:success",{tool:"generate_image_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),o.urls?.length?(o.urls.forEach(s=>Jd(s)),Lk({prompt:e.prompt,tool:"generate_image_card",mediaUrl:o.urls[0],mediaType:"image",cost:o.amount??n.amount,transactionId:o.transactionId,userContext:t})):W.warn("generation:no-urls",{tool:"generate_image_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof Oi)return W.warn("payment:declined",{tool:"generate_image_card",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),_p(o,n);throw oh(o,{tool:"generate_image_card",amount:n.amount,merchant:n.merchantName}),o}}async function v9r(e,t){if(!e.prompt||!e.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let r=await Dk("generate_image_fast_card",e,t);if(r)return r;let n=await nh("generate_image_fast_card",void 0,t),i=jo.randomUUID();W.info("payment:attempt",{tool:"generate_image_fast_card",amount:n.amount,merchant:n.merchantName});try{return await qo(async()=>{let o;try{o=await b2({toolId:"generate_image_fast_card",toolParams:e,estimatedAmountCents:ih(n),userContext:t,timeoutMs:6e4,idempotencyKey:i})}catch(s){if(s instanceof No)return Gd(s);throw s}return W.info("payment:success",{tool:"generate_image_fast_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),o.urls?.length?(o.urls.forEach(s=>Jd(s)),Lk({prompt:e.prompt,tool:"generate_image_fast_card",mediaUrl:o.urls[0],mediaType:"image",cost:o.amount??n.amount,transactionId:o.transactionId,userContext:t})):W.warn("generation:no-urls",{tool:"generate_image_fast_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof Oi)return W.warn("payment:declined",{tool:"generate_image_fast_card",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),_p(o,n);throw oh(o,{tool:"generate_image_fast_card",amount:n.amount,merchant:n.merchantName}),o}}async function w9r(e,t){if(!e.prompt||!e.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let r=await Dk("generate_video_tempo_card",e,t);if(r)return r;let n=await nh("generate_video_tempo_card",void 0,t),i=jo.randomUUID();W.info("payment:attempt",{tool:"generate_video_tempo_card",amount:n.amount,merchant:n.merchantName});try{return await qo(async()=>{let o;try{o=await b2({toolId:"generate_video_tempo_card",toolParams:e,estimatedAmountCents:ih(n),userContext:t,timeoutMs:12e4,idempotencyKey:i})}catch(s){if(s instanceof No)return Gd(s);throw s}return W.info("payment:success",{tool:"generate_video_tempo_card",amount:n.amount,merchant:n.merchantName,mode:"session"}),o.urls?.length?(o.urls.forEach(s=>Jd(s)),Lk({prompt:e.prompt,tool:"generate_video_tempo_card",mediaUrl:o.urls[0],mediaType:"video",cost:o.amount??n.amount,transactionId:o.transactionId,userContext:t})):W.warn("generation:no-urls",{tool:"generate_video_tempo_card",resultKeys:Object.keys(o||{})}),o})}catch(o){if(o instanceof Oi)return W.warn("payment:declined",{tool:"generate_video_tempo_card",amount:n.amount,merchant:n.merchantName,code:o.code,retryable:o.retryable}),_p(o,n);throw oh(o,{tool:"generate_video_tempo_card",amount:n.amount,merchant:n.merchantName}),o}}async function x9r(e,t){if(!e.prompt||!e.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let r=await nh("generate_music_tempo_card",void 0,t),n=jo.randomUUID();W.info("payment:attempt",{tool:"generate_music_tempo_card",amount:r.amount,merchant:r.merchantName});try{return await qo(async()=>{let i;try{i=await b2({toolId:"generate_music_tempo_card",toolParams:e,estimatedAmountCents:ih(r),userContext:t,timeoutMs:36e4,idempotencyKey:n})}catch(o){if(o instanceof No)return Gd(o);throw o}return W.info("payment:success",{tool:"generate_music_tempo_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),i.urls?.length&&i.status!=="processing"?(i.urls.forEach(o=>Jd(o)),Lk({prompt:e.prompt,tool:"generate_music_tempo_card",mediaUrl:i.urls[0],mediaType:"audio",cost:i.amount??r.amount,transactionId:i.transactionId,userContext:t})):i.urls?.length&&i.status==="processing"?(i._preliminary_urls=i.urls,delete i.urls,W.info("generation:processing",{tool:"generate_music_tempo_card",note:"URLs withheld until status is completed"})):W.warn("generation:no-urls",{tool:"generate_music_tempo_card",resultKeys:Object.keys(i||{})}),i})}catch(i){if(i instanceof Oi)return W.warn("payment:declined",{tool:"generate_music_tempo_card",amount:r.amount,merchant:r.merchantName,code:i.code,retryable:i.retryable}),_p(i,r);throw oh(i,{tool:"generate_music_tempo_card",amount:r.amount,merchant:r.merchantName}),i}}async function E9r(e,t){let r=await nh("check_music_status_tempo_card",void 0,t),n=jo.randomUUID();W.info("payment:attempt",{tool:"check_music_status_tempo_card",amount:r.amount,merchant:r.merchantName});try{return await qo(async()=>{let i;try{i=await b2({toolId:"check_music_status_tempo_card",toolParams:e,estimatedAmountCents:ih(r),userContext:t,timeoutMs:3e4,idempotencyKey:n})}catch(o){if(o instanceof No)return Gd(o);throw o}return W.info("payment:success",{tool:"check_music_status_tempo_card",amount:r.amount,merchant:r.merchantName,mode:"session"}),i.urls?.length&&i.urls.forEach(o=>Jd(o)),i})}catch(i){if(i instanceof Oi)return W.warn("payment:declined",{tool:"check_music_status_tempo_card",amount:r.amount,merchant:r.merchantName,code:i.code,retryable:i.retryable}),_p(i,r);throw oh(i,{tool:"check_music_status_tempo_card",amount:r.amount,merchant:r.merchantName}),i}}async function A9r(e,t){if(!e.chain||!e.chain.trim())throw new Error('A chain is required (e.g., "ethereum", "solana").');if(!e.token_address||!e.token_address.trim())throw new Error("A token address is required. Provide the contract address for the token.");let r=await nh("query_onchain_prices",void 0,t),n=jo.randomUUID();W.info("payment:attempt",{tool:"query_onchain_prices",amount:r.amount,merchant:r.merchantName});try{return await qo(async()=>{let i;try{i=await b2({toolId:"query_onchain_prices",toolParams:e,estimatedAmountCents:ih(r),userContext:t,timeoutMs:3e4,idempotencyKey:n})}catch(o){if(o instanceof No)return Gd(o);throw o}if(W.info("payment:success",{tool:"query_onchain_prices",amount:r.amount,merchant:r.merchantName,mode:"session"}),Array.isArray(i?.data))i.data=i.data.map(o=>{if("mint"in o&&!("address"in o)){let{mint:s,...a}=o;return{address:s,...a}}return o});else if(i&&"mint"in i&&!("address"in i)){let{mint:o,...s}=i;return{address:o,...s}}return i})}catch(i){if(i instanceof Oi)return W.warn("payment:declined",{tool:"query_onchain_prices",amount:r.amount,merchant:r.merchantName,code:i.code,retryable:i.retryable}),_p(i,r);throw oh(i,{tool:"query_onchain_prices",amount:r.amount,merchant:r.merchantName}),i}}var S9r=["generate_music_tempo_card"],RA=10,Bft=5,Nft=new Map;function jft(e){let t=Nft.get(e);if(t!==void 0)return t;let n=DA(e)?.isAsync===!0||S9r.includes(e);return Nft.set(e,n),n}var T9r=36e4,P9r=18e4,I9r=15e3,C9r=12e4,O9r=2e3;function j8e(e,t){return{success:!1,error_code:e,code:e,error:t,message:t}}function R9r(e,t){return jo.createHash("sha256").update(`${e}:${hY(t)}`).digest("hex")}function k9r(e){let{results:t,batchId:r,index:n,item:i,itemResult:o,preview:s,isFree:a,catalogName:c}=e;a&&o&&typeof o=="object"&&!Array.isArray(o)&&o.merchantName==null&&(o.merchantName=c??i.resolvedTool),t.push({success:o?.success!==!1,tool:i.resolvedTool,...o,...yY(r,n,o)});let u=0,d=0n;if(o?.success!==!1){let l=gp(o?.amountMicros??o?.amount_micros),p=typeof o?.amount=="number"?o.amount:s?.amount??0;l!==null&&l>0n?d+=l:d+=BigInt(Math.round(p*1e6)),u+=p}return o?.urls&&o.urls.forEach(l=>Jd(l)),{deltaCharged:u,deltaMicros:d}}function B9r(e){let{results:t,resolvedItems:r,uniqueTools:n,isHomogeneous:i,primaryTool:o,merchantNames:s,totalAmount:a,totalCharged:c,totalChargedMicros:u,batchId:d,mode:l}=e,p=t.filter(v=>v?.success===!1).length,f=t.length-p,m=t.flatMap(v=>Array.isArray(v?.urls)?v.urls:[]),h=u>0n?Number(u)/1e6:Math.round((c+Number.EPSILON)*100)/100,y=f===0?"failure":p===0?"success":"partial";return W.info("payment:success",{tool:"batch",batchTool:o,count:r.length,totalAmount:a,totalCharged:h,merchant:s,successCount:f,failedCount:p,outcome:y,mode:l,batchId:d}),{success:f>0,outcome:y,batch_id:d,tool:i?n[0]:o,count:r.length,successCount:f,failedCount:p,totalCharged:h,...u>0n?{totalChargedMicros:u.toString(),amountMicros:u.toString(),amount_micros:u.toString()}:{},merchantName:s,results:t,...m.length?{urls:m}:{}}}async function N9r(e){let{resolvedItems:t,previews:r,freeTools:n,catalogEntries:i,itemCeilingCents:o,batchCeilingCents:s,uniqueTools:a,isHomogeneous:c,primaryTool:u,merchantNames:d,totalAmount:l,timeoutMs:p,batchId:f,userContext:m}=e,h=s,y=await De.getBalance();if(!y.success)throw new Error(`Could not read balance: ${y.error||"unknown error"}`);if(y.balanceCents<h)throw new No(y.balanceCents,h);let v=`batch-${f}`,x=`spend up to $${(h/100).toFixed(2)} across a batch of ${t.length}`,{batchParentId:_}=await qo(async()=>{let S=await Yd("batch_open",h,v,x,m,{forceRequired:!0}),T=S?.nonce??(await De.getAttestationChallenge()).nonce;W.info("parentless-batch:open-attempt",{batchTool:u,count:t.length,approvedTotalCents:h,attested:!!S});let{batch_parent_id:O}=await De.batchOpen({...S?{attestation:S}:{},nonce:T,approved_total_cents:h,batch_id:f});return{batchParentId:O}});W.info("parentless-batch:opened",{batchTool:u,count:t.length,batchParentId:_});let w=[],E=0,A=0n;try{for(let S=0;S<t.length;S+=1){let T=t[S],O=r[T.resolvedTool],R=n.has(T.resolvedTool);try{let U;if(R)U=await De.shortcut(T.resolvedTool,T.params,p,m,"batch");else{let{data:B,voucherReceiptHeader:P}=await De.shortcutParentlessBatchItem(T.resolvedTool,{batch_parent_id:_,batch_id:f,batch_index:S,batch_request_hash:R9r(T.resolvedTool,T.params),item_ceiling_cents:o[S],idempotency_key:q8e(f,S,T.resolvedTool,T.params)},T.params,p,m,"batch");wk(P),xk(B?.receipt_v2),U=await Fft(B,null,q8e(f,S,T.resolvedTool,T.params))}let{deltaCharged:q,deltaMicros:j}=k9r({results:w,batchId:f,index:S,item:T,itemResult:U,preview:O,isFree:R,catalogName:i[T.resolvedTool]?.name});E+=q,A+=j}catch(U){if(U instanceof No&&w.length===0)return Gd(U);W.warn("payment:batch-item-failed",{tool:T.resolvedTool,index:S,error:U?.message||String(U)}),w.push({success:!1,tool:T.resolvedTool,...yY(f,S),error:U?.message||String(U)})}}return B9r({results:w,resolvedItems:t,uniqueTools:a,isHomogeneous:c,primaryTool:u,merchantNames:d,totalAmount:l,totalCharged:E,totalChargedMicros:A,batchId:f,mode:"parentless"})}catch(S){if(S instanceof Oi)return W.warn("payment:declined",{tool:"batch",batchTool:u,count:t.length,totalAmount:l,merchant:d,code:S.code,retryable:S.retryable}),_p(S,{amount:l,merchantName:d});throw oh(S,{tool:"batch",batchTool:u,count:t.length,totalAmount:l,merchant:d}),S}}async function j9r(e,t){let r;if(Array.isArray(e.requests)&&e.requests.length>RA)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${RA} items. Please split into smaller batches.`};if(e.requests?.some(S=>S.tool||S.tool_id)&&e.requests)r=e.requests.map(S=>{let T=S.tool||S.tool_id||e.tool;if(!T)throw new Error("Each request must specify tool or tool_id, or set tool at the top level.");let O=_Z({requestedTool:T})??T,{tool:R,tool_id:U,tier:q,params:j,...B}=S,P=j&&typeof j=="object"?{...j,...B}:B;return{resolvedTool:O,params:P}});else if(e.tool){let S=_Z({requestedTool:e.tool})??e.tool;if(e.count!==void 0){if(!Number.isSafeInteger(e.count)||e.count<1)return j8e("BATCH_INVALID_COUNT","Batch count must be a positive integer.");if(e.count>RA)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${RA} items. Please split into smaller batches.`}}r=(e.requests||(e.count!==void 0&&e.params?Array.from({length:e.count},()=>({...e.params})):[])).map(O=>({resolvedTool:S,params:O}))}else return j8e("BATCH_MISSING_TOOL","Batch requires a top-level tool or per-request tool/tool_id.");if(r.length===0)return j8e("BATCH_EMPTY","Batch requires at least one item.");if(r.length>RA)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Batch limited to ${RA} items. Please split into smaller batches.`};if([...new Set(r.map(S=>S.resolvedTool))].some(jft)&&r.length>Bft)return{success:!1,error_code:"BATCH_TOO_LARGE",error:`Async batch limited to ${Bft} items. Please use multiple batches for more.`};let s=[...new Set(r.map(S=>S.resolvedTool))],a=s.length===1,c={};for(let S of s)c[S]=await Qft(S);let u=new Set(s.filter(S=>c[S]&&EY(c[S]))),d={};for(let S of s)u.has(S)||(d[S]=await nh(S,void 0,t));let l=0;for(let S of r)l+=d[S.resolvedTool]?.amount??0;let p=r.map(S=>m9r(S,d,u)),f=p.reduce((S,T)=>S+T,0),m=[...new Set([...Object.values(d).map(S=>S.merchantName),...s.filter(S=>u.has(S)).map(S=>c[S]?.name??S)])].join(", "),h=a?s[0]:"mixed";W.info("payment:attempt",{tool:"batch",batchTool:h,count:r.length,totalAmount:l,merchant:m,heterogeneous:!a});let y=r.some(S=>jft(S.resolvedTool)),v=r.some(S=>S.resolvedTool.startsWith("or-")||S.resolvedTool==="run_llm"||S.resolvedTool==="execute_tool"),x=y?T9r:v?P9r+r.length*I9r:C9r+r.length*O9r,_=jo.randomUUID(),w=[],E=0,A=0n;return vY(async()=>{let S=!a2();if(Qdt()&&!Cft&&S&&f>0)try{return await N9r({resolvedItems:r,previews:d,freeTools:u,catalogEntries:c,itemCeilingCents:p,batchCeilingCents:f,uniqueTools:s,isHomogeneous:a,primaryTool:h,merchantNames:m,totalAmount:l,timeoutMs:x,batchId:_,userContext:t})}catch(T){if(T instanceof Ap)Cft=!0,W.info("parentless-batch:falling-back-to-session",{batchTool:h,count:r.length,status:T.status,serverErrorCode:T.serverErrorCode});else{if(T instanceof No)return Gd(T);throw T}}if(S&&f>0)try{let T=f;await qo(()=>j4e(De,Yd,{toolName:"batch",userContext:t,sessionKind:"one_shot",minRequiredCents:T,capCentsOverride:T}))}catch(T){return T instanceof No?Gd(T):(W.warn("payment:batch-prewarm-failed",{batchTool:h,count:r.length,error:T?.message||String(T)}),{success:!1,error_code:"BATCH_AUTH_FAILED",error:T?.message||"Failed to authenticate batch session",tool:h,count:r.length,failedCount:r.length,results:[]})}try{for(let j=0;j<r.length;j+=1){let B=r[j],P=d[B.resolvedTool];try{let k=u.has(B.resolvedTool)?await De.shortcut(B.resolvedTool,B.params,x,t,"batch"):await Hft({toolId:B.resolvedTool,toolParams:B.params,estimatedAmountCents:p[j],userContext:t,metaTool:"batch",timeoutMs:x,idempotencyKey:q8e(_,j,B.resolvedTool,B.params)});if(u.has(B.resolvedTool)&&k&&typeof k=="object"&&!Array.isArray(k)&&k.merchantName==null&&(k.merchantName=c[B.resolvedTool]?.name??B.resolvedTool),w.push({success:k?.success!==!1,tool:B.resolvedTool,...k,...yY(_,j,k)}),k?.success!==!1){let N=gp(k?.amountMicros??k?.amount_micros),C=typeof k?.amount=="number"?k.amount:P?.amount??0;N!==null&&N>0n?A+=N:A+=BigInt(Math.round(C*1e6)),E+=C}k?.urls&&k.urls.forEach(N=>Jd(N))}catch(k){if(k instanceof No&&w.length===0)return Gd(k);W.warn("payment:batch-item-failed",{tool:B.resolvedTool,index:j,error:k?.message||String(k)}),w.push({success:!1,tool:B.resolvedTool,...yY(_,j),error:k?.message||String(k)})}}let T=w.filter(j=>j?.success===!1).length,O=w.length-T,R=w.flatMap(j=>Array.isArray(j?.urls)?j.urls:[]),U=A>0n?Number(A)/1e6:Math.round((E+Number.EPSILON)*100)/100,q=O===0?"failure":T===0?"success":"partial";return W.info("payment:success",{tool:"batch",batchTool:h,count:r.length,totalAmount:l,totalCharged:U,merchant:m,successCount:O,failedCount:T,outcome:q,mode:"session",batchId:_}),{success:O>0,outcome:q,batch_id:_,tool:a?s[0]:h,count:r.length,successCount:O,failedCount:T,totalCharged:U,...A>0n?{totalChargedMicros:A.toString(),amountMicros:A.toString(),amount_micros:A.toString()}:{},merchantName:m,results:w,...R.length?{urls:R}:{}}}catch(T){if(T instanceof Oi)return W.warn("payment:declined",{tool:"batch",batchTool:h,count:r.length,totalAmount:l,merchant:m,code:T.code,retryable:T.retryable}),_p(T,{amount:l,merchantName:m});throw oh(T,{tool:"batch",batchTool:h,count:r.length,totalAmount:l,merchant:m}),T}finally{if(S){let T=await HJ(De);W.info("batch-session:closed",{budgetId:T.budgetId,closedServerSide:T.closedServerSide})}}})}function q9r(){let e=!1,t;try{let n=_Y.join(Mk.homedir(),".claude","settings.json");if(bp.existsSync(n)){let i=JSON.parse(bp.readFileSync(n,"utf-8")),o=typeof i.statusLine=="object"?i.statusLine.command:"";e=tlt(o)}}catch{}let r=jJ();return r||(t="visa-cli config hud enable"),{statusLine:e,shellHud:r,...t?{shellHudSetup:t}:{}}}async function U9r(e){let[t,r]=await Promise.all([De.getStatus(e),De.getBalance().catch(o=>(W.warn("get_status:balance_fetch_failed",{error:o?.message||String(o)}),null))]);typeof t?.dailyRemaining=="number"&&(t.dailyRemaining=Math.round(t.dailyRemaining*100)/100);let n=y9r();n.file_count>0&&(t.alliumResultsOnDisk=n),t.hud=q9r(),!t.hud.statusLine&&!t.hud.shellHud&&(t._hud_nudge="The user has no HUD surfaces enabled. Mention once, naturally, that they can enable a live spend dashboard with `visa-cli config hud enable` \u2014 it shows balance, active tools, and spend on every prompt."),t.version=J3r,Array.isArray(t.cards)&&(t.cards=t.cards.map(o=>({...o,displayName:z8e(o)})),t.cardIdGuidance="cardId values are opaque tool parameters only; refer to cards by brand and last four digits."),r&&r.success&&(t.balanceCents=r.balanceCents,t.balanceMicros=r.balanceMicros,t.amountUsd=r.amountUsd);let i=a2();if(t.sessionMode=!!i,i){let o=Math.max(0,i.totalCents-i.estimatedCumulative);t.activeSession={budgetId:i.budgetId,capCents:i.totalCents,capUsd:i.totalCents/100,lastReceiptCumulativeCents:i.lastReceiptCumulative,estimatedCumulativeCents:i.estimatedCumulative,spentCents:i.estimatedCumulative,spentUsd:i.estimatedCumulative/100,estimatedRemainingCents:o,estimatedRemainingUsd:o/100,...i.lastToolSpend?{lastToolSpend:{toolName:i.lastToolSpend.toolName,resolvedToolId:i.lastToolSpend.resolvedToolId,estimatedAmountCents:i.lastToolSpend.estimatedAmountCents,estimatedAmountUsd:i.lastToolSpend.estimatedAmountCents/100,voucherCumulativeCents:i.lastToolSpend.voucherCumulativeCents,estimatedCumulativeCents:i.lastToolSpend.estimatedCumulativeCents,receiptDeltaCents:i.lastToolSpend.receiptDeltaCents,receiptCumulativeCents:i.lastToolSpend.receiptCumulativeCents,receiptRemainingCents:i.lastToolSpend.receiptRemainingCents,recordedAt:i.lastToolSpend.recordedAt}}:{},expiresAt:i.expiresAt}}return t}function z8e(e){let t=typeof e.brand=="string"&&e.brand.trim().length>0?e.brand.trim():"card",r=t.charAt(0).toUpperCase()+t.slice(1).toLowerCase(),n=typeof e.last4=="string"&&e.last4.trim().length>0?e.last4.trim():"unknown",i=e.isDefault===!0?" (default)":"";return`${r} ending in ${n}${i}`}async function Wft(e,t){try{let n=((await De.getStatus(t)).cards||[]).find(i=>i?.id===e);if(n)return z8e(n)}catch(r){W.warn("cards:display_name_lookup_failed",{cardId:e,error:r?.message||String(r)})}return"selected card"}async function M9r(e){let r=(await De.getStatus(e)).cards||[];return r.length===0?{cards:[],message:"No cards enrolled. Use the add_card tool to add a payment card."}:r.some(i=>!Number.isInteger(i?.id)||i.id<=0)?{success:!1,cards:[],message:"Card action handles are unavailable right now, so remove_card and set_default_card are temporarily disabled."}:{cards:r.map(i=>({...i,displayName:z8e(i)})),message:"Use cardId only as an opaque tool parameter. When speaking to the user, refer to cards by brand and last four digits, not by card id."}}async function D9r(e,t){return await De.getTransactions({limit:e.limit,offset:e.offset},t)}async function L9r(e,t){return await De.feedback(e.message,e.transaction_id,t)}async function H9r(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return lw("MISSING_CONFIRMATION","Please confirm by setting confirm: true to charge your enrolled card for credits.");if(!e.amount||!Number.isFinite(e.amount)||e.amount<=0)return{success:!1,error:"amount must be a positive number in USD (e.g. 5.00)"};let r=Plt(String(e.amount));if(r.ok===!1)return{success:!1,error:r.error};let n=r.cents,i=n/100,o=jo.randomUUID();W.info("buy_credits:attempt",{amountCents:n});try{return await qo(async()=>{let s=await Yd("balance-topup",i,"Visa CLI Balance",`top up balance with $${r.displayUsd}`,t,{forceRequired:!0}),a=await De.topupBalance({amount_cents:n,idempotency_key:o,attestation:s});if(a.success){W.info("buy_credits:success",{amountCents:n,balanceCents:a.balanceCents,balanceMicros:a.balanceMicros});let c=L3r(a.balanceMicros,a.balanceCents??0),u=(n/100).toFixed(2);return{...a,amount:n/100,amountMicros:String(n*1e4),merchantName:"Visa CLI Balance",message:`Added $${u} \u2014 balance is now ${c}`}}return W.warn("buy_credits:failed",{amountCents:n,error:a.error}),a})}catch(s){if(s instanceof g2)return e9r();if(s instanceof lh)return W.warn("buy_credits:ambiguous",{amountCents:n,code:s.code,transactionId:s.transactionId}),X3r(s);throw W.error("buy_credits:failure",{amountCents:n,error:s.message}),s}}function lw(e,t){return{success:!1,error:t,code:e,message:t}}async function z9r(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return lw("MISSING_CONFIRMATION","Please confirm by setting confirm: true to update spending controls.");if(e.maxTransactionAmount!==void 0&&(typeof e.maxTransactionAmount!="number"||!Number.isFinite(e.maxTransactionAmount)||e.maxTransactionAmount<.01))return lw("INVALID_VALUE","maxTransactionAmount must be at least $0.01");if(e.dailyLimit!==void 0&&(typeof e.dailyLimit!="number"||!Number.isFinite(e.dailyLimit)||e.dailyLimit<1))return lw("INVALID_VALUE","dailyLimit must be at least $1");if(e.maxTransactionAmount!==void 0&&e.dailyLimit!==void 0&&e.maxTransactionAmount>e.dailyLimit)return lw("INVALID_VALUE","maxTransactionAmount cannot exceed dailyLimit");W.info("spending_controls:update",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit});try{return await qo(async()=>{let r=await Yd("spending-controls",0,"","update spending controls"),n=await De.updateSpendingControls({maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit,confirm:!0,attestation:r},t);return W.info("spending_controls:success",{maxTransactionAmount:e.maxTransactionAmount,dailyLimit:e.dailyLimit}),n})}catch(r){if(W.error("spending_controls:failure",{error:r.message}),r instanceof g2)return xY(r,"update_spending_controls");if(String(r?.message||r).includes("Attestation required"))return lw("ATTESTATION_REQUIRED","Changing spending controls requires local attestation, even when payment biometric prompts are disabled.");throw r}}async function F9r(e){let t=await ult({api:De,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 F8e=new Set(["auth.serverUrl"]);function Uk(){return Object.keys($A).filter(e=>!F8e.has(e)).sort()}function Gft(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:Uk()}}async function $9r(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(F8e.has(e.key))return W.warn("config:set:rejected:mcp-forbidden",{key:e.key}),Gft(e.key,"set");W.info("config:set",{key:e.key});try{let t=G3e(e.key,e.value);return W.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 Mm?"UNKNOWN_KEY":t instanceof q2?"SERVER_CONTROLLED":t instanceof Ow?"RETIRED_KEY":"INVALID_VALUE",n=t instanceof Mm?`Unknown setting "${e.key}". MCP-settable keys: ${Uk().join(", ")}. For auth.serverUrl, use the shell command instead.`:t.message;return W.warn("config:set:rejected",{key:e.key,code:r,error:n}),{success:!1,error:n,code:r,settableKeys:Uk()}}}async function V9r(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(F8e.has(e.key))return W.warn("config:unset:rejected:mcp-forbidden",{key:e.key}),Gft(e.key,"unset");W.info("config:unset",{key:e.key});try{let t=J3e(e.key);return W.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 Mm?"UNKNOWN_KEY":t instanceof q2?"SERVER_CONTROLLED":t instanceof Ow?"RETIRED_KEY":"INVALID_VALUE",n=t instanceof Mm?`Unknown setting "${e.key}". MCP-settable keys: ${Uk().join(", ")}. For auth.serverUrl, use the shell command instead.`:t.message;return W.warn("config:unset:rejected",{key:e.key,code:r,error:n}),{success:!1,error:n,code:r,settableKeys:Uk()}}}async function K9r(e){let t=await De.getStatus(e),r=t.attestationRequired!==!1,n=wA(t),i=rl(),o=r?n?i?`${gY()} is REQUIRED for payments.`:`Biometric attestation is required and a key is registered, but ${gY()} is not available in this process. ${H8e()}`:"Biometric attestation is enabled on the account, but no attestation key is registered. Payments on this device proceed without a biometric signature; processor declines such as INVALID_OR_MISSING_CONFIG are card/account configuration issues, not something biometric setup fixes.":"Biometric attestation is NOT required for payments. Payments will proceed without biometric confirmation.";return{required:r,hasAttestationKey:!!t.hasAttestationKey,hasTelegramAttestationKey:!!t.hasTelegramAttestationKey,hasAnyAttestationKey:n,touchIdAvailable:i,platform:process.platform,effectiveRequiredOnThisDevice:r&&n&&i,canDisableFromThisDevice:!r||!n||i,message:o}}async function W9r(e){W.info("biometric:on");let t=await olt(De,e);if(t.ok===!1)return{success:!1,error:t.code,error_code:t.code,message:t.message,agent_guidance:`${t.message} Do not call biometric_on again until the user has completed setup in an interactive terminal.`};let r=await De.setBiometricPreference({required:!0},e);return r.success?(Kft(),{success:!0,required:!0,message:"Touch ID is now REQUIRED for payments."}):{success:!1,error:r.error||"unknown error"}}async function G9r(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return lw("MISSING_CONFIRMATION","Please confirm by setting confirm: true. Disabling Touch ID is a security downgrade \u2014 the user will be prompted for one final Touch ID confirmation before the change takes effect.");W.info("biometric:off");try{return await qo(async()=>{let r=await De.getStatus(t),n;if(wA(r)&&(n=await Yd("biometric-preference",0,"","disable Touch ID requirement"),!n))throw new Error(`${gY()} confirmation required to disable \u2014 not available on this device.`);let i=await De.setBiometricPreference({required:!1,attestation:n},t);if(!i.success)throw new Error(i.error||"unknown error");return Kft(),{success:!0,required:!1,message:"Touch ID is no longer required for payments."}})}catch(r){if(W.error("biometric:off:failure",{error:r.message}),r instanceof g2)return xY(r,"biometric_off");throw r}}var qft=3e4,J9r=3e5;async function Jft(e,t,r="login"){let n=jo.randomUUID(),i=`${e}${e.includes("?")?"&":"?"}state=${n}`,o=Jd(i);return!o.opened&&o.blockedReason!=="non_internal_host"&&o.blockedReason!=="invalid_url"?Yft(i,o,r):o.opened?{...await Zft(n,t,r),browserUrl:i}:{success:!1,browserUrl:i,message:`Could not open the browser URL safely. Please check the configured auth server and try again. URL: ${i}`}}function Yft(e,t,r){let n=r==="enrollment"?"card enrollment":r==="attestation-recovery"?"biometric reset":"login",i=t.blockedReason==="suppressed"?"browser auto-open is suppressed":t.blockedReason==="headless"?"this process appears to be headless":t.blockedReason==="unsupported_platform"?"this platform has no configured browser opener":"browser auto-open is unavailable";return{success:!1,requiresBrowser:!0,browserUrl:e,message:`Browser auto-open was skipped because ${i}. Open this URL to continue ${n}: ${e}`}}async function Zft(e,t,r="login"){let n=Date.now()+J9r;for(;Date.now()<n;)try{let o=await fetch(`${wY()}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json","X-Source":"cli"},body:JSON.stringify({state:e,timeout:qft,...t&&{user_context:t}}),signal:AbortSignal.timeout(qft+5e3)});if(!o.ok){await x4e(o,a=>{W.warn("auth_status:retry_after_http_error",{status:o.status,delayMs:a})});continue}let s=await o.json();if(s.status==="pending")continue;if(s.status==="expired")return{success:!1,message:"Session expired. Please try again."};if(s.status==="error")return{success:!1,message:s.error||"Authentication failed. Please try again."};if(s.status==="complete"){if(r==="attestation-recovery"||s.attestationCleared)return W.info("auth:attestation_recovery_complete",{user:s.user||""}),{success:!0,message:"Server-side biometric state cleared. Run visa-cli setup to register a fresh key before reenabling Touch ID."};let a=s.welcomeBonusCents??0,c=dlt(a);if(r!=="enrollment"&&s.sessionToken){await ra.saveSessionToken(s.sessionToken);let d=s.user||"",l=s.last4||"****";return W.info("auth:login_complete",{user:d,last4:l,bonusCents:a}),{success:!0,message:`Signed in as ${d}. Card ending in ${l} enrolled and ready for payments.`,...c||{}}}let u=s.last4||"****";return W.info("auth:card_added",{last4:u,bonusCents:a}),{success:!0,message:`Card ending in ${u} enrolled and ready for payments.`,...c||{}}}}catch{await x4e(void 0,o=>{W.warn("auth_status:retry_after_network_error",{delayMs:o})})}return{success:!1,message:r==="enrollment"?"Card enrollment timed out. Please try again.":r==="attestation-recovery"?"Biometric reset timed out. Please try reset again.":"Login timed out. Please try again."}}async function Xft(e){let t=jo.randomUUID(),r;try{r=await De.startAttestationRecovery(t,e)}catch(o){return{success:!1,message:`Could not start biometric reset: ${o?.message||"unknown error"}`}}if(!r.success||!r.recoveryUrl)return{success:!1,message:r.error||"Could not start biometric reset. Please try again."};let n=Jd(r.recoveryUrl);return!n.opened&&n.blockedReason!=="non_internal_host"&&n.blockedReason!=="invalid_url"?Yft(r.recoveryUrl,n,"attestation-recovery"):n.opened?{...await Zft(t,e,"attestation-recovery"),browserUrl:r.recoveryUrl}:{success:!1,browserUrl:r.recoveryUrl,message:`Could not open the browser URL safely. Please check the configured auth server and try again. URL: ${r.recoveryUrl}`}}async function Y9r(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return{success:!1,message:"Please confirm by setting confirm: true to remove this card."};let r=e.cardId;if(!Number.isInteger(r)||r<=0)return{success:!1,message:"cardId must be a positive integer. Call get_cards to get the opaque cardId for the card you want to remove."};W.info("cards:remove_attempt",{cardId:r});let n=`remove-card:${r}`,i=`remove ${await Wft(r,t)}`;try{return await qo(async()=>{let o=await Yd(n,0,"",i,t,{forceRequired:!0}),s=await De.removeCard(r,{attestation:o},t);return W.info("cards:remove_success",{cardId:r,promotedId:s?.promotedId??null}),s})}catch(o){if(W.error("cards:remove_failure",{cardId:r,error:o.message}),o instanceof g2)return xY(o,"remove_card");throw o}}async function Z9r(e,t){let r=e.cardId;if(!Number.isInteger(r)||r<=0)return{success:!1,message:"cardId must be a positive integer. Call get_cards to get the opaque cardId for the card you want to make default."};W.info("cards:set_default_attempt",{cardId:r});let n=`set-default-card:${r}`,i=`set ${await Wft(r,t)} as default`;try{return await qo(async()=>{let o=await Yd(n,0,"",i,t,{forceRequired:!0}),s=await De.setDefaultCard(r,{attestation:o},t);return W.info("cards:set_default_success",{cardId:r}),s})}catch(o){if(W.error("cards:set_default_failure",{cardId:r,error:o.message}),o instanceof g2)return xY(o,"set_default_card");throw o}}async function X9r(e){return W.info("auth:login_attempt"),Jft(`${wY()}/login`,e)}async function Q9r(e=Um()){if(!e)return{success:!1,message:"The Visa Verified Agent enrollment flow is not yet publicly available in stable builds. Set VISA_VERIFY_WEB_URL to a deployment URL to use enroll_agent."};let{challenge:t,confirmCode:r,agentPkX:n,walletPkHex:i}=h4e(),o=`${e}${e.includes("?")?"&":"?"}cli=${t}&cliPk=${n}${i?`&walletPk=${i}`:""}`;W.info("agent:enroll_open",{url:e});let s=Jd(o),a="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",c=`CONFIRMATION CODE: ${r} \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.`,u='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 s.opened?{success:!0,opened:!0,browserUrl:s.url,confirmCode:r,message:`Opened the Visa Verified Agent enrollment in your browser (${a}). ${c} ${u} 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:s.url??o,confirmCode:r,message:`Open this URL in a browser to enroll your agent (${a}): ${s.url??o} \u2014 ${c} ${u}`}}async function exr(e=Um()){if(!e)return{success:!1,message:"The Visa Verified Agent enrollment flow is not yet publicly available in stable builds. Set VISA_VERIFY_WEB_URL to a deployment URL to use enroll_agent."};let t=await y4e(e);switch(W.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?" You're signed in with this identity \u2014 no separate `visa-cli setup` needed.":"")+(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}}}function txr(e){if(e.capCents!==void 0){let t=Number(e.capCents);if(!Number.isFinite(t)||t<10||t>1e4)throw new Error("capCents must be between 10 ($0.10) and 10000 ($100)");return Math.floor(t)}if(e.capUsd!==void 0){let t=Number(e.capUsd);if(!Number.isFinite(t)||t<.1||t>100)throw new Error("capUsd must be between 0.10 and 100");return Math.floor(t*100)}}async function rxr(e={},t){let r;try{r=txr(e)}catch(n){return{success:!1,error:n?.message||String(n)}}return vY(async()=>{let n=await qo(()=>xlt(De,Yd,{toolName:"start_session",userContext:t,capCentsOverride:r}));W.info("session:started",{budgetId:n.budgetId,totalCents:n.totalCents,requestedCapCents:n.requestedCapCents,appliedCapCents:n.appliedCapCents,clampedReason:n.clampedReason,closedPrevious:n.closedPrevious});let i=(n.appliedCapCents/100).toFixed(2),o=(n.requestedCapCents/100).toFixed(2),s=`Session started with a $${i} cap. Paid calls will use this approval window until you close it, it expires, or this MCP process restarts.`,a=n.clampedReason==="balance"?`${s} Note: requested cap of $${o} was clamped to your prepaid balance of $${i}. Run buy_credits to top up if you need a larger session.`:s;return{success:!0,budgetId:n.budgetId,totalCents:n.totalCents,amountUsd:n.totalCents/100,requestedCapCents:n.requestedCapCents,appliedCapCents:n.appliedCapCents,clampedReason:n.clampedReason,closedPrevious:n.closedPrevious,message:a}})}async function nxr(){let e=a2();if(!e)return{success:!0,active:!1,message:"No active explicit approval window. Paid calls use a one-shot session in pay-as-you-go mode; see transaction_history for records."};let t=Math.max(0,e.totalCents-e.estimatedCumulative);return{success:!0,active:!0,budgetId:e.budgetId,totalCents:e.totalCents,estimatedCumulativeCents:e.estimatedCumulative,estimatedRemainingCents:t,expiresAt:e.expiresAt,lastToolSpend:e.lastToolSpend,message:`Active explicit approval window: about $${(t/100).toFixed(2)} remaining of $${(e.totalCents/100).toFixed(2)}.`}}async function ixr(){return vY(async()=>{let e=a2();if(!e)return{success:!0,message:"No active explicit approval window to close. Paid calls remain pay-as-you-go.",closed:!1};let t=await HJ(De);W.info("session:closed",{budgetId:t.budgetId,closedServerSide:t.closedServerSide});let r=K3r(e),n=gp(t.finalCumulativeMicros),i=n??(typeof t.finalCumulativeCents=="number"?BigInt(Math.max(0,t.finalCumulativeCents))*10000n:r.micros),o=Number(i/10000n);return W.info("session:closed:final-spend",{budgetId:t.budgetId,closedServerSide:t.closedServerSide,finalSpendMicros:i.toString(),finalSpendCents:o,finalSpendSource:n!==null?"server.finalCumulativeMicros":typeof t.finalCumulativeCents=="number"?"server.finalCumulativeCents":r.source,totalCents:e.totalCents}),{success:!0,closed:!0,closedServerSide:t.closedServerSide,budgetId:t.budgetId,finalEstimatedCumulativeCents:o,finalEstimatedCumulativeMicros:i.toString(),totalCents:e.totalCents,message:t.closedServerSide?`Explicit approval window closed. Spent ${V3r(i)} of $${(e.totalCents/100).toFixed(2)} cap. Future paid calls are pay-as-you-go until you start a new explicit approval window.`:"Explicit approval window cleared locally; server-side close call did not succeed (likely already closed). Future paid calls are pay-as-you-go until you start a new explicit approval window."}})}async function oxr(e){if(W.info("auth:add_card_attempt"),!await ra.getSessionToken())return{success:!1,message:"Not logged in. Sign up at https://visacli.sh or call the login tool first."};let{code:r}=await De.createEnrollCode();return Jft(`${wY()}/enroll-card?code=${encodeURIComponent(r)}`,e,"enrollment")}async function Uft(){if(await ra.clearAll(),rl())try{await U9e()}catch{}}async function sxr(e,t){if(typeof e.confirm!="boolean"||e.confirm!==!0)return{success:!1,message:"Please confirm by setting confirm: true to reset"};if(W.info("reset:attempt"),e.localOnly)return await Uft(),W.info("reset:success",{localOnly:!0}),{success:!0,message:"Device reset locally. Local credentials and keys have been removed; server-side session and biometric state were not changed. Use the login tool or visa-cli setup to sign in with the GitHub account you want to use."};let r=!1;try{let n=await De.getStatus(t);if(n&&wA(n)){let i=await Xft(t);if(!i.success)return i;r=!0}}catch(n){let i=n?.message||"unknown error";if(!/not logged in|session.*expired|no local credentials/i.test(i))return{success:!1,message:`Could not check server biometric state: ${i}`};W.warn("reset:server_attestation_status_unavailable",{error:i})}try{await De.logout(void 0,t)}catch{}return await Uft(),W.info("reset:success"),{success:!0,message:r?"Device reset. Server-side biometric state and local credentials have been cleared. Use the login tool or visa-cli setup to re-enroll.":"Device reset. Local credentials and keys have been removed. Use the login tool or visa-cli setup to re-enroll."}}async function axr(e){let t=e.query?.trim()||void 0,r=e.category?.trim()||void 0,n=!t&&!r;W.info("catalog:discover",{query:t,category:r,browseAll:n});try{let o=(await De.catalogSearch(t,r)).tools||[];if(o.length===0)return{content:[{type:"text",text:n?"The tool catalog is currently empty.":`No tools found for "${t||r}". Try a different search term.`}]};if(n){let a={};for(let u of o){let d=u.category||"other";(a[d]??=[]).push(u)}let c=Object.keys(a).sort().map(u=>{let d=a[u].map((p,f)=>`${f+1}. **${p.name}** (${p.id})
|
|
20662
20662
|
${p.description}
|
|
20663
20663
|
Provider: ${p.provider} | Price: ${Mft(p)}${Dft(p)}
|