@visa/cli 1.7.0-rc.1 → 1.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/cli.js +3 -3
- package/dist/mcp-server/index.js +4 -4
- package/package.json +1 -1
package/dist/cli.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var Kn=Object.create;var Ct=Object.defineProperty;var qn=Object.getOwnPropertyDescriptor;var Gn=Object.getOwnPropertyNames;var Wn=Object.getPrototypeOf,Jn=Object.prototype.hasOwnProperty;var zn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Yn=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Gn(t))!Jn.call(e,s)&&s!==n&&Ct(e,s,{get:()=>t[s],enumerable:!(r=qn(t,s))||r.enumerable});return e};var h=(e,t,n)=>(n=e!=null?Kn(Wn(e)):{},Yn(t||!e||!e.__esModule?Ct(n,"default",{value:e,enumerable:!0}):n,e));var Je=zn((ws,cr)=>{cr.exports={name:"@visa/cli",version:"1.7.0
|
|
1
|
+
"use strict";var Kn=Object.create;var Ct=Object.defineProperty;var qn=Object.getOwnPropertyDescriptor;var Gn=Object.getOwnPropertyNames;var Wn=Object.getPrototypeOf,Jn=Object.prototype.hasOwnProperty;var zn=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports);var Yn=(e,t,n,r)=>{if(t&&typeof t=="object"||typeof t=="function")for(let s of Gn(t))!Jn.call(e,s)&&s!==n&&Ct(e,s,{get:()=>t[s],enumerable:!(r=qn(t,s))||r.enumerable});return e};var h=(e,t,n)=>(n=e!=null?Kn(Wn(e)):{},Yn(t||!e||!e.__esModule?Ct(n,"default",{value:e,enumerable:!0}):n,e));var Je=zn((ws,cr)=>{cr.exports={name:"@visa/cli",version:"1.7.0",description:"AI-powered payments for Claude Code",bin:{"visa-cli":"./bin/visa-cli.js"},scripts:{build:"tsc --noEmit && node esbuild.config.js",dev:"tsc --watch",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"},devDependencies:{"@visa-cli/tools":"workspace:*","@changesets/changelog-git":"^0.2.1","@changesets/cli":"^2.30.0","@types/jest":"^30.0.0","@types/node":"^25.6.0","@typescript-eslint/eslint-plugin":"^8.59.0","@typescript-eslint/parser":"^8.59.0","@types/express":"^5.0.0",esbuild:"^0.27.4",express:"^4.21.0",eslint:"^10.0.2","eslint-config-prettier":"^10.1.8",jest:"^29.7.0",prettier:"^3.8.3","ts-jest":"^29.2.0",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","native/visa-keychain.m","server.json","README.md","LICENSE"]}});var Nn=require("commander"),He=h(require("crypto")),Dn=h(require("fs")),H=h(require("os")),ge=h(require("path")),Mn=h(require("readline")),Un=require("child_process"),jn=require("util");var Se=require("child_process"),kt=require("util"),Y=h(require("fs")),ve=h(require("os")),qe=h(require("path")),B=(0,kt.promisify)(Se.execFile),Ge=qe.join(ve.homedir(),".visa-mcp"),he=qe.join(Ge,"session-token"),U="visa-cli",z="session-token",ye="rc-access",Xn=5e3;async function Zn(){try{let{stdout:e}=await B("security",["find-generic-password","-s",U,"-a",z,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function Qn(e){try{try{await B("security",["delete-generic-password","-s",U,"-a",z],{timeout:5e3})}catch{}return await B("security",["add-generic-password","-s",U,"-a",z,"-w",e],{timeout:5e3}),!0}catch{return!1}}async function er(){try{await B("security",["delete-generic-password","-s",U,"-a",z],{timeout:5e3})}catch{}}async function tr(){if(!We())return null;try{let{stdout:e}=await B("secret-tool",["lookup","service",U,"account",z],{timeout:5e3});return e.trim()||null}catch{return null}}async function nr(e){if(!We())return!1;try{let t=(0,Se.execFile)("secret-tool",["store","--label",`${U} ${z}`,"service",U,"account",z]);return t.stdin?(t.stdin.write(e),t.stdin.end(),await Promise.race([new Promise((n,r)=>{t.on("exit",s=>s===0?n():r(new Error(`secret-tool exited ${s}`))),t.on("error",r)}),new Promise((n,r)=>setTimeout(()=>{t.kill(),r(new Error("secret-tool timed out"))},Xn))]),!0):!1}catch{return!1}}async function rr(){if(We())try{await B("secret-tool",["clear","service",U,"account",z],{timeout:5e3})}catch{}}function We(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function sr(){try{let{stdout:e}=await B("security",["find-generic-password","-s",U,"-a",ye,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function or(e){try{try{await B("security",["delete-generic-password","-s",U,"-a",ye],{timeout:5e3})}catch{}await B("security",["add-generic-password","-s",U,"-a",ye,"-w",e],{timeout:5e3})}catch{}}async function ir(){try{await B("security",["delete-generic-password","-s",U,"-a",ye],{timeout:5e3})}catch{}}function Be(){try{return Y.readFileSync(he,"utf-8").trim()||null}catch{return null}}function $t(e){Y.mkdirSync(Ge,{recursive:!0,mode:448}),Y.writeFileSync(he,e,{mode:384}),process.platform==="win32"&&ar(he)}function Ke(){try{Y.unlinkSync(he)}catch{}}function ar(e){try{let t=ve.userInfo().username;(0,Se.execFile)("icacls",[e,"/inheritance:r","/grant:r",`${t}:F`],{timeout:5e3},n=>{n&&console.error(`[visa-cli] icacls ACL restriction failed: ${n.message}`)})}catch(t){console.error(`[visa-cli] Failed to invoke icacls: ${t instanceof Error?t.message:String(t)}`)}}function Fe(){switch(process.platform){case"darwin":return{get:Zn,store:Qn,delete:er};case"linux":return{get:tr,store:nr,delete:rr};default:return{get:async()=>Be(),store:async e=>{try{return $t(e),!0}catch{return!1}},delete:async()=>Ke()}}}var C=class{static async getSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN==="true")return Promise.resolve("mock-session-token-for-testing");let t=Fe(),n=await t.get();if(n)return n;let r=Be();return r?(await t.store(r),r):null}static async saveSessionToken(t){if(process.env.VISA_MOCK_KEYCHAIN==="true")return;let n=Fe();if(await n.store(t)){if(await n.get()===t){Ke();return}await n.delete()}if($t(t),Be()!==t)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${Ge} is writable.`))}static async getRcAccessToken(){return process.env.VISA_MOCK_KEYCHAIN==="true"?"mock-rc-token-for-testing":sr()}static async saveRcAccessToken(t){process.env.VISA_MOCK_KEYCHAIN!=="true"&&await or(t)}static async deleteSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN==="true")return;await Fe().delete(),Ke()}static async clearAll(){await this.deleteSessionToken(),await ir()}};var be=h(require("crypto")),we=h(require("tty")),_e=h(require("fs"));var Q="0000000000000000000000000000000000000000000000000000000000000000";function lr(e){return/-rc\.|-beta\./.test(e)}function ze(e){return be.createHash("sha256").update(e.trim()).digest("hex")}function Et(e){return Q==="SKIP"?!0:be.timingSafeEqual(Buffer.from(ze(e)),Buffer.from(Q))}function ur(e){return new Promise((t,n)=>{let r=_e.openSync("/dev/tty","r+"),s=new we.ReadStream(r),o=new we.WriteStream(r),i=()=>{try{s.destroy()}catch{}try{o.destroy()}catch{}try{_e.closeSync(r)}catch{}};o.write(e),s.setRawMode(!0),s.resume(),s.setEncoding("utf8");let a="";s.on("data",c=>{c==="\r"||c===`
|
|
2
2
|
`?(o.write(`
|
|
3
3
|
`),i(),t(a)):c===""?(o.write(`
|
|
4
4
|
`),i(),n(new Error("Cancelled"))):c==="\x7F"||c==="\b"?a.length>0&&(a=a.slice(0,-1),o.write("\b \b")):(a+=c,o.write("\u2022"))})})}var dr=`
|
|
@@ -24,7 +24,7 @@
|
|
|
24
24
|
${P}`}function br(e){if(typeof e!="number"||e<=0)return"";let n=(e>1e12?e:e*1e3)-Date.now();if(n<=0||n>=10080*60*1e3)return"";let r=Math.floor(n/6e4),s=Math.floor(r/60),o=r%60;return s>0?`${s}h ${o}m`:`${o}m`}function jt(e,t){if(!e||typeof e.used_percentage!="number")return null;let n=Math.max(0,Math.min(100,e.used_percentage)),r=n/100,s=Vt(r),o=n>=90?"\x1B[38;5;196m":n>=70?S.visaGold:S.green,i=`${String(Math.round(n)).padStart(2," ")}%`,a=br(e.resets_at),c=a?` ${b(`(${a} / ${t})`,S.dim)}`:` ${b(`(${t})`,S.dim)}`;return`${s} ${b(i,o)}${c}`}function wr(e){if(!e)return null;let t=jt(e.five_hour,"5h"),n=typeof e.seven_day?.used_percentage=="number"?e.seven_day.used_percentage:null,r=n!==null&&n>=90?jt(e.seven_day,"7d"):null;if(!t&&!r)return null;let s=` ${b("\u2502",S.dim)} `,o=[t,r].filter(Boolean);return`${b("Usage",S.dim)} ${o.join(s)}`}function _r(e){let t;try{let n=G.statSync(e);if(!n.isFile())return null;let r=n.size;if(r===0)return null;let s=Math.min(r,yr),o=r-s;t=G.openSync(e,"r");let i=Buffer.alloc(s);G.readSync(t,i,0,s,o);let a=i.toString("utf-8");if(o>0){let c=Buffer.alloc(1);if(G.readSync(t,c,0,1,o-1),c[0]!==10){let l=a.indexOf(`
|
|
25
25
|
`);l>=0&&(a=a.slice(l+1))}}return a}catch{return null}finally{if(t!==void 0)try{G.closeSync(t)}catch{}}}function Cr(e){if(!e||typeof e!="object")return;let t=e,n=["file_path","path","notebook_path","pattern","command","url"];for(let r of n){let s=t[r];if(typeof s=="string"&&s.length>0){if(r.endsWith("_path")||r==="path"){let o=X.basename(X.dirname(s)),i=X.basename(s);return o&&o!=="."&&o!=="/"?`${o}/${i}`:i}return s}}}function kr(e){let t=e.split(`
|
|
26
26
|
`),n=[],r=new Set;for(let s=t.length-1;s>=0&&n.length<Dt*3;s-=1){let o=t[s].trim();if(!o)continue;let i;try{i=JSON.parse(o)}catch{continue}if(!i||typeof i!="object")continue;let c=i.message;if(!c||typeof c!="object")continue;let l=c.content;if(Array.isArray(l))for(let u of l){if(!u||typeof u!="object")continue;let f=u;if(f.type==="tool_result"&&typeof f.tool_use_id=="string")r.add(f.tool_use_id);else if(f.type==="tool_use"&&typeof f.name=="string"){let d=typeof f.id=="string"?f.id:"",m=d.length>0?!r.has(d):!1;n.push({name:f.name,target:Cr(f.input),running:m})}}}return n.reverse(),n.slice(Math.max(0,n.length-Dt))}function $r(e){let t=[];for(let n of e){let r=t[t.length-1];r&&!r.running&&!n.running&&r.name===n.name&&r.target===void 0&&n.target===void 0?r.count+=1:t.push({...n,count:1})}return t}function Er(e){let t=e.running?b("\u25D0",S.visaGold):b("\u2713",S.green),n=e.running?S.visaGold:S.visaBlueSoft,r=b(ee(e.name),n),s=e.target?ee(e.target):"",o=s?`${b(":",S.dim)} ${b(s,S.dim)}`:"",i=e.count>1?` ${b(`\xD7${e.count}`,S.dim)}`:"";return o?`${t} ${r}${o}${i}`:`${t} ${r}${i}`}function xr(e){let t=` ${b("\u2502",S.dim)} `,n=Mt(t),r=e.slice();for(;r.length>0;){let c=r.join(t);if(Mt(c)<=Xe)return c;r=r.slice(1)}if(e.length===0)return"";let s="\u2026",i=e[e.length-1].replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,""),a=i.length>Xe-n-1?i.slice(0,Xe-n-1)+s:i;return`${b(s,S.dim)}${t}${a}`}async function Pr(e){if(!e||typeof e!="string")return null;let t=_r(e);if(!t)return null;let n;try{n=kr(t)}catch{return null}if(n.length===0)return null;let s=$r(n).map(Er);return xr(s)||null}async function Ft(e,t){let n=[e];if(t){let r=vr(t);if(r&&n.push(r),t.transcript_path){let s=await Pr(t.transcript_path);s&&n.push(s)}}return n.join(`
|
|
27
|
-
`)}function ee(e){return e?e.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g,"").replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g,"").replace(/\s+/g," ").trim():""}function Rr(e){if(typeof e=="string")return ee(X.basename(e));if(!e||typeof e!="object")return"";let t=typeof e.current_dir=="string"?e.current_dir:typeof e.path=="string"?e.path:"";return ee(t?X.basename(t):e.name)}async function Bt(e,t){let n=t?.timeoutMs??3e4,r=new AbortController,s=setTimeout(()=>r.abort(),n);try{let{timeoutMs:o,...i}=t??{};return await fetch(e,{...i,signal:r.signal})}finally{clearTimeout(s)}}var Tr=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function qt(e,t){let n=Kt(e),r=Kt(t);if(!n||!r)return!1;for(let s=0;s<3;s++)if(n.main[s]!==r.main[s])return n.main[s]>r.main[s];return n.pre&&!r.pre?!1:!n.pre&&r.pre?!0:!n.pre&&!r.pre?!1:Ar(n.pre,r.pre)>0}function Kt(e){if(typeof e!="string")return null;let n=e.trim().replace(/^v/,"").match(Tr);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function Ar(e,t){let n=e.split("."),r=t.split("."),s=Math.max(n.length,r.length);for(let o=0;o<s;o++){if(o>=n.length)return-1;if(o>=r.length)return 1;let i=n[o],a=r[o],c=/^\d+$/.test(i),l=/^\d+$/.test(a);if(c&&l){let u=Number(i)-Number(a);if(u!==0)return u}else{if(c)return-1;if(l)return 1;if(i<a)return-1;if(i>a)return 1}}return 0}function K(){return!!(Gt(process.env.VISA_CLI_NO_UPDATE_CHECK)||Gt(process.env.CI)||process.env.NODE_ENV==="test")}function Gt(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}var Qe="1.7.0
|
|
27
|
+
`)}function ee(e){return e?e.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g,"").replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g,"").replace(/\s+/g," ").trim():""}function Rr(e){if(typeof e=="string")return ee(X.basename(e));if(!e||typeof e!="object")return"";let t=typeof e.current_dir=="string"?e.current_dir:typeof e.path=="string"?e.path:"";return ee(t?X.basename(t):e.name)}async function Bt(e,t){let n=t?.timeoutMs??3e4,r=new AbortController,s=setTimeout(()=>r.abort(),n);try{let{timeoutMs:o,...i}=t??{};return await fetch(e,{...i,signal:r.signal})}finally{clearTimeout(s)}}var Tr=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function qt(e,t){let n=Kt(e),r=Kt(t);if(!n||!r)return!1;for(let s=0;s<3;s++)if(n.main[s]!==r.main[s])return n.main[s]>r.main[s];return n.pre&&!r.pre?!1:!n.pre&&r.pre?!0:!n.pre&&!r.pre?!1:Ar(n.pre,r.pre)>0}function Kt(e){if(typeof e!="string")return null;let n=e.trim().replace(/^v/,"").match(Tr);return n?{main:[Number(n[1]),Number(n[2]),Number(n[3])],pre:n[4]??null}:null}function Ar(e,t){let n=e.split("."),r=t.split("."),s=Math.max(n.length,r.length);for(let o=0;o<s;o++){if(o>=n.length)return-1;if(o>=r.length)return 1;let i=n[o],a=r[o],c=/^\d+$/.test(i),l=/^\d+$/.test(a);if(c&&l){let u=Number(i)-Number(a);if(u!==0)return u}else{if(c)return-1;if(l)return 1;if(i<a)return-1;if(i>a)return 1}}return 0}function K(){return!!(Gt(process.env.VISA_CLI_NO_UPDATE_CHECK)||Gt(process.env.CI)||process.env.NODE_ENV==="test")}function Gt(e){if(e===void 0)return!1;let t=e.trim().toLowerCase();return!(t===""||t==="0"||t==="false"||t==="no"||t==="off")}var Qe="1.7.0",re=class{constructor(t){this.getSessionToken=t;this.baseUrl=process.env.VISA_AUTH_URL||"https://auth.visacli.sh"}getSessionToken;baseUrl;lastSignals={};parseServerSignals(t){if(this.lastSignals={},!K()){let r=t.headers.get("X-Latest-Version"),s=t.headers.get("X-Update-Message");r&&qt(r,Qe)&&(this.lastSignals.updateAvailable={version:r,message:s||`Update available: v${r}. Run: npm install -g @visa/cli && visa-cli setup`})}let n=t.headers.get("X-Feedback-Prompt");if(n)try{this.lastSignals.feedbackPrompt=JSON.parse(n)}catch{}}getClientVersion(){return Qe}async request(t,n,r,s,o){let i=await this.getSessionToken();if(!i)throw new Error("Not logged in. Sign up at https://visacli.sh or run: visa-cli setup");let a={Authorization:`Bearer ${i}`};o&&(t==="GET"?a["X-User-Context"]=o.replace(/[\r\n\0]/g," ").slice(0,1e3):r={...r||{},user_context:o}),r&&(a["Content-Type"]="application/json");let c;try{c=await Bt(`${this.baseUrl}${n}`,{method:t,headers:{...a,"X-Visa-CLI-Version":Qe},body:r?JSON.stringify(r):void 0,timeoutMs:s})}catch(u){throw u.name==="AbortError"||u.message?.includes("aborted")?new Error("The request timed out. The server may be under heavy load. Please try again."):new Error("Cannot reach the Visa CLI server. Check your internet connection and try again.")}if(this.parseServerSignals(c),c.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(c.status===429){let u=c.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${u}s. Tip: use the batch tool to combine multiple requests into one.`)}if(c.status===503)throw new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status.");let l;try{l=await c.json()}catch{throw c.status===500?new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`):new Error(`Unexpected response from ${n}. Try again.`)}if(!c.ok)throw c.status===500?new Error(`Server error on ${n}. Try again or check https://visacli.sh for status.`):new Error(l?.error||`Request failed (${c.status}). Try again.`);return l}async pay(t,n){return this.request("POST","/v1/pay",t,void 0,n)}async shortcut(t,n,r,s){return this.request("POST",`/v1/shortcuts/${encodeURIComponent(t)}`,n,r,s)}async batch(t,n,r){return this.request("POST","/v1/batch",t,n,r)}async catalogSearch(t,n){let r=new URLSearchParams;t&&r.set("q",t),n&&r.set("category",n);let s=r.toString();return this.request("GET",`/v1/catalog${s?`?${s}`:""}`)}async catalogTool(t){try{return await this.request("GET",`/v1/catalog/${encodeURIComponent(t)}`)}catch{return null}}async paymentPreview(t,n){return this.request("POST","/v1/payment-preview",t,void 0,n)}async getStatus(t){return this.request("GET","/v1/status",void 0,void 0,t)}async getTransactions(t){return this.request("GET","/v1/transactions",void 0,void 0,t)}async updateSpendingControls(t,n){return this.request("POST","/v1/spending-controls",t,void 0,n)}async removeCard(t,n,r){return this.request("DELETE",`/v1/cards/${encodeURIComponent(String(t))}`,n,void 0,r)}async setDefaultCard(t,n,r){return this.request("POST",`/v1/cards/${encodeURIComponent(String(t))}/default`,n,void 0,r)}async getAttestationChallenge(){return this.request("GET","/v1/attestation-challenge")}async registerAttestationKey(t){return this.request("POST","/v1/attestation-key",{publicKey:t})}async setBiometricPreference(t,n){return this.request("POST","/v1/biometric-preference",{...t,confirm:!0},void 0,n)}async logout(t,n){return this.request("POST","/v1/logout",t,void 0,n)}async feedback(t,n,r){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,r)}async feedSubmit(t){return this.request("POST","/v1/feed",t)}async feedList(t){let n=new URLSearchParams;t?.tab&&n.set("tab",t.tab),t?.limit&&n.set("limit",String(t.limit)),t?.offset&&n.set("offset",String(t.offset));let r=n.toString();return this.request("GET",`/v1/feed${r?"?"+r:""}`)}async feedVote(t,n){return this.request("POST",`/v1/feed/${encodeURIComponent(t)}/vote`,{direction:n})}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,n,r){return this.request("POST","/v1/feedback",{message:t,...n&&{transaction_id:n}},void 0,r)}async getFeedback(t,n){let r=new URLSearchParams;t&&r.set("limit",String(t));let s=r.toString();return this.request("GET",`/v1/feedback${s?"?"+s:""}`,void 0,void 0,n)}async submitRatedFeedback(t){return this.request("POST","/v1/feedback",t)}};var st=require("child_process"),Zt=require("util"),Qt=h(require("crypto")),E=h(require("fs")),en=h(require("os")),q=h(require("path"));var T=h(require("fs")),nt=h(require("path")),Wt=h(require("os")),tt=nt.join(Wt.homedir(),".visa-mcp"),ae=nt.join(tt,"mcp-server.log"),Ir=5*1024*1024,et=null;function Lr(){T.existsSync(tt)||T.mkdirSync(tt,{recursive:!0,mode:448})}function Or(){if(!et){if(Lr(),T.existsSync(ae)&&T.statSync(ae).size>Ir){let t=ae+".1";T.existsSync(t)&&T.unlinkSync(t),T.renameSync(ae,t)}et=T.createWriteStream(ae,{flags:"a"})}return et}function ke(e,...t){let n=new Date().toISOString(),r=t.map(o=>typeof o=="string"?o:JSON.stringify(o,null,2)).join(" "),s=`[${n}] [${e}] ${r}
|
|
28
28
|
`;process.stderr.write(s),Or().write(s)}var se={debug:(...e)=>ke("DEBUG",...e),info:(...e)=>ke("INFO",...e),warn:(...e)=>ke("WARN",...e),error:(...e)=>ke("ERROR",...e)};var oe=(0,Zt.promisify)(st.execFile),xe=q.join(en.homedir(),".visa-mcp","bin"),te=q.join(xe,"Visa CLI"),Nr=q.join(__dirname,"..","native"),Jt="5",zt=q.join(xe,"visa-keychain.version"),Yt=q.join(xe,"visa-keychain.sha256");function Xt(e){let t=E.readFileSync(e);return Qt.createHash("sha256").update(t).digest("hex")}async function tn(){try{if(E.readFileSync(zt,"utf-8").trim()===Jt&&E.existsSync(te)){let r=E.readFileSync(Yt,"utf-8").trim();if(Xt(te)!==r)se.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),E.unlinkSync(te);else return te}}catch{}let e=q.join(Nr,"visa-keychain.m");if(E.existsSync(e)||(e=q.resolve(__dirname,"..","..","native","visa-keychain.m")),E.existsSync(e)||(e=q.resolve(__dirname,"..","native","visa-keychain.m")),!E.existsSync(e))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");E.mkdirSync(xe,{recursive:!0,mode:448});try{await oe("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",te,e],{timeout:3e4})}catch(n){throw n.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):n}let t=Xt(te);return E.writeFileSync(Yt,t,{mode:384}),E.writeFileSync(zt,Jt,{mode:384}),te}async function nn(e){let t=await tn(),n;try{n=(await oe(t,e,{timeout:6e4})).stdout}catch(o){n=o.stdout||"";let i=n.trim();throw i.startsWith("ERROR:")?new Error(i.slice(6)):new Error(o.stderr?.trim()||o.message||"Unknown error")}let r=n.trim();if(r.startsWith("OK:"))return r.slice(3);if(r==="OK")return;let s=r.startsWith("ERROR:")?r.slice(6):"Unknown error";throw new Error(s)}var rt=null;function A(){return process.env.VISA_MOCK_TOUCHID==="true"?!0:process.platform!=="darwin"?!1:rt!==null?rt:(rt=!0,!0)}var $e="visa-cli",Ee="attestation-key";async function Dr(e){try{await oe("security",["delete-generic-password","-s",$e,"-a",Ee],{timeout:5e3})}catch{}await oe("security",["add-generic-password","-s",$e,"-a",Ee,"-w",e],{timeout:5e3})}async function Mr(){try{let{stdout:e}=await oe("security",["find-generic-password","-s",$e,"-a",Ee,"-w"],{timeout:5e3});return e.trim()||null}catch{return null}}async function Pe(){let e=await nn(["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 n=e.slice(0,t),r=e.slice(t+1);return await Dr(n),r}async function ot(e,t){if(process.env.VISA_MOCK_TOUCHID==="true")return Promise.resolve("mock-ecdsa-signature-for-testing");let n=await Mr();if(!n)throw new Error("Attestation key not found. Run setup to generate a new key.");let r=await tn(),s=["sign",e];return t&&s.push(t),new Promise((o,i)=>{let a=(0,st.execFile)(r,s,{timeout:6e4},(c,l)=>{let u=(l||"").trim();if(c){u.startsWith("ERROR:")?i(new Error(u.slice(6))):i(new Error(c.stderr?.trim()||c.message||"Unknown error"));return}u.startsWith("OK:")?o(u.slice(3)):i(new Error(u.startsWith("ERROR:")?u.slice(6):"Unknown error"))});a.stdin.write(n),a.stdin.end()})}async function rn(){try{await oe("security",["delete-generic-password","-s",$e,"-a",Ee],{timeout:5e3})}catch{}try{await nn(["delete-key"])}catch{}}function sn(e,t=process.stderr){if(K()||!e?.updateAvailable)return!1;let{message:n}=e.updateAvailable;return n?(t.write(`
|
|
29
29
|
\x1B[33m\u2191 ${n}\x1B[0m
|
|
30
30
|
`),!0):!1}function an(e,t,n,r){let o=Kr(e.spendingControls).dailyLimit,i=Math.max(0,ce(e.dailySpent)),a=o>0?Math.min(o,Math.max(0,ce(e.dailyRemaining??o-i))):0,c=o>0?Math.min(1,i/o):0,u=(Array.isArray(t)?t:[]).filter(Hr),f=u.slice(0,3),d=Vr(u,3),m=(e.cards??[]).slice(0,3),v=r.latestVersion?at(r.latestVersion):"",k=r.updateCheckDisabled?"update checks disabled":v?`update available: v${v}`:"up to date",L=Math.round(c*100),$=Z(e.status,e.enrolled?"approved":"not enrolled"),M=["VISA CLI",`Status: ${e.enrolled?"Visa ready":"Visa setup needed"} | account: ${$} | touch id: ${n?"ready":"unavailable"}`,`Version: v${r.currentVersion} | ${k}`,`Spend meter: ${on(c)} ${String(L).padStart(3," ")}% | remaining ${ie(a)}/day | daily cap ${ie(o)}`,"","Spend",` Remaining ${ie(a)} / ${ie(o)}`,` Usage ${on(c)} ${L}%`,` Spent today ${ie(i)}`,` Attestation key ${e.hasAttestationKey?"registered":"missing"}`,"","Cards",...m.length>0?m.map(P=>` ${Br(P)}`):[" No cards enrolled"],"","Last 3 services",...d.length>0?d.map((P,J)=>` ${J+1}. ${P}`):[" No paid services yet"],"","Recent receipts",...f.length>0?f.map(P=>` ${Fr(P)}`):[" No receipts yet"]];return r.updateMessage&&M.push("",`Update: ${at(r.updateMessage)}`),`${M.join(`
|
|
@@ -89,7 +89,7 @@ ${r}
|
|
|
89
89
|
`}function pn(e=Ne()){if(!e)return{installed:!1,changed:!1,shell:null,message:"Shell HUD auto-install skipped: supported shells are zsh, bash, and PowerShell."};let t;try{t=De(e);let n=y.existsSync(t)?y.readFileSync(t,"utf-8"):"",r=Xr(n,e),s=r!==n;return s&&Ie(t,r),{installed:!0,changed:s,shell:e,rcPath:t,message:s?`Persistent shell HUD installed in ${t}. Open a new terminal to start seeing it. Disable it any time with: visa-cli shell-hud disable`:`Persistent shell HUD already installed in ${t}. Disable it any time with: visa-cli shell-hud disable`}}catch(n){return{installed:!1,changed:!1,shell:e,rcPath:t,message:`Failed to install persistent shell HUD in ${t}: ${Sn(n)}`}}}function mn(e=Ne()){if(!e)return{removed:!1,shell:null,message:"Shell HUD uninstall skipped: supported shells are zsh, bash, and PowerShell."};let t;try{if(t=De(e),!y.existsSync(t))return{removed:!1,shell:e,rcPath:t,message:`No ${e} rc file found at ${t}.`};let n=y.readFileSync(t,"utf-8"),r=fn(n);return r===n.trimEnd()?{removed:!1,shell:e,rcPath:t,message:`Persistent shell HUD was not installed in ${t}.`}:(Ie(t,r.length>0?`${r}
|
|
90
90
|
`:""),{removed:!0,shell:e,rcPath:t,message:`Removed persistent shell HUD from ${t}.`})}catch(n){return{removed:!1,shell:e,rcPath:t,message:`Failed to remove persistent shell HUD from ${t}: ${Sn(n)}`}}}function ft(e,t){let n=Ae(t.currentVersion),r=` ${j("\u2502",O.dim)} `;if(!e.enrolled)return`${j("VISA CLI",O.visaBlue)} ${j(`v${n}`,O.visaBlueSoft)}${r}${j("setup needed",O.visaGold)}`;let s=ct(e.spendingControls?.daily_limit??e.spendingControls?.dailyLimit),o=Math.max(0,ct(e.dailySpent)),i=s>0?Math.min(s,Math.max(0,ct(e.dailyRemaining??s-o))):0,a=s>0?Math.max(0,Math.min(1,o/s)):0,c=es(e),l=s>0?`${Qr(a)} ${j(`${lt(i)} left today`,O.green)} ${j(`(${lt(o)}/${lt(s)}/day)`,O.dim)}`:j("no spend limit",O.dim);return`${j("VISA CLI",O.visaBlue)} ${j(`v${n}`,O.visaBlueSoft)}${r}${j(c,O.visaGold)}${r}${l}`}function gn(){let e=hn();return!!e&&Date.now()-e.renderedAt<=un}function pt(){let e=hn();if(e&&Date.now()-e.renderedAt<=un||(Zr(),e?.line))return e.line;try{let t=Oe();if(y.existsSync(t))return y.readFileSync(t,"utf-8").trimEnd()}catch{}return"VISA | loading spend HUD\u2026"}function mt(e){try{let t=w.dirname(ue());y.mkdirSync(t,{recursive:!0});let n=Ae(e),r={hudVersion:Gr,renderedAt:Date.now(),line:n};Ie(ue(),JSON.stringify(r)+`
|
|
91
91
|
`),Ie(Oe(),n+`
|
|
92
|
-
`)}catch{}}function le(){try{y.unlinkSync(dn())}catch{}}function hn(){let e=ue();if(!y.existsSync(e))return null;try{return JSON.parse(y.readFileSync(e,"utf-8"))}catch{return null}}function Zr(){let e=dn();try{if(y.mkdirSync(w.dirname(e),{recursive:!0}),!ss(e))return;let t=process.argv[1]?w.resolve(process.argv[1]):"";if(!t){le();return}let n=(0,ln.spawn)(process.execPath,[t,"shell-hud","refresh"],{detached:!0,stdio:"ignore",env:{...process.env,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});n.once("error",le),n.unref()}catch{le()}}function ct(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function Ae(e){return e.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g,"").replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/\u001B[P_^][^\u001B]*(?:\u001B\\|\u0007)/g,"").replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g,"").replace(/\s+/g," ").trim()}function Qr(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),s="\u2591".repeat(10-n);return`${j(r||"",O.green)}${j(s||"",O.dim)}`}function lt(e){return`$${e.toFixed(2)}`}function es(e){let t=e.cards?.find(a=>a.isDefault)??e.cards?.[0];if(!t)return"card none";let n=typeof t.brand=="string"?t.brand:"card",r=typeof t.last4=="string"?t.last4:"????",s=Ae(n.toUpperCase()),o=Ae(r);return`${t.isDefault?"default":"active"} ${s} ****${o}`}function ts(){let e=(process.env.COLORTERM??"").toLowerCase();if(e==="truecolor"||e==="24bit")return!0;let t=(process.env.TERM??"").toLowerCase();return t.includes("truecolor")||t.includes("24bit")}var ut=ts(),O={reset:"\x1B[0m",visaBlue:ut?"\x1B[38;2;20;52;203m":"\x1B[38;5;27m",visaBlueSoft:ut?"\x1B[38;2;97;126;229m":"\x1B[38;5;111m",visaGold:ut?"\x1B[38;2;247;182;0m":"\x1B[38;5;220m",green:"\x1B[38;5;48m",dim:"\x1B[2m"};function j(e,t){return e.length===0||process.env.NO_COLOR?e:`${t}${e}${O.reset}`}function cn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function yn(){let e=Le.homedir();if(!e||!w.isAbsolute(e))throw new Error("unable to determine a valid home directory");return w.resolve(e)}function ns(e){return e==="powershell"?"& visa-cli shell-hud refresh":"visa-cli shell-hud refresh"}function rs(e){return e==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function ss(e){for(let t=0;t<2;t+=1){let n;try{return n=y.openSync(e,"wx"),y.writeFileSync(n,String(Date.now())),!0}catch(r){if(r?.code!=="EEXIST")return!1;try{let s=y.statSync(e);if(Date.now()-s.mtimeMs<=zr)return!1;y.unlinkSync(e)}catch{}}finally{n!==void 0&&y.closeSync(n)}}return!1}function Sn(e){return e instanceof Error?e.message:"unknown file system error"}function Ie(e,t){y.mkdirSync(w.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;y.writeFileSync(n,t),y.renameSync(n,e)}async function gt(e,t){try{return await t()}catch(n){if(n.message==="Invalid signature"&&A()){se.warn("attestation:key-mismatch",{action:"reregistering"});try{let r=await Pe();await e.registerAttestationKey(r),se.info("attestation:key-reregistered")}catch(r){throw se.error("attestation:reregister-failure",{error:r.message}),n}return await t()}throw n}}var vn="1.7.0
|
|
92
|
+
`)}catch{}}function le(){try{y.unlinkSync(dn())}catch{}}function hn(){let e=ue();if(!y.existsSync(e))return null;try{return JSON.parse(y.readFileSync(e,"utf-8"))}catch{return null}}function Zr(){let e=dn();try{if(y.mkdirSync(w.dirname(e),{recursive:!0}),!ss(e))return;let t=process.argv[1]?w.resolve(process.argv[1]):"";if(!t){le();return}let n=(0,ln.spawn)(process.execPath,[t,"shell-hud","refresh"],{detached:!0,stdio:"ignore",env:{...process.env,VISA_CLI_SHELL_HUD_BACKGROUND:"1"}});n.once("error",le),n.unref()}catch{le()}}function ct(e){let t=Number(typeof e=="string"?e:e??0);return Number.isFinite(t)?t:0}function Ae(e){return e.replace(/\u001B\][^\u0007]*(?:\u0007|\u001B\\)/g,"").replace(/\u001B\[[0-?]*[ -/]*[@-~]/g,"").replace(/\u001B[P_^][^\u001B]*(?:\u001B\\|\u0007)/g,"").replace(/[\u0000-\u0008\u000B-\u001F\u007F-\u009F]/g,"").replace(/\s+/g," ").trim()}function Qr(e){let n=Math.round(Math.max(0,Math.min(1,e))*10),r="\u2588".repeat(n),s="\u2591".repeat(10-n);return`${j(r||"",O.green)}${j(s||"",O.dim)}`}function lt(e){return`$${e.toFixed(2)}`}function es(e){let t=e.cards?.find(a=>a.isDefault)??e.cards?.[0];if(!t)return"card none";let n=typeof t.brand=="string"?t.brand:"card",r=typeof t.last4=="string"?t.last4:"????",s=Ae(n.toUpperCase()),o=Ae(r);return`${t.isDefault?"default":"active"} ${s} ****${o}`}function ts(){let e=(process.env.COLORTERM??"").toLowerCase();if(e==="truecolor"||e==="24bit")return!0;let t=(process.env.TERM??"").toLowerCase();return t.includes("truecolor")||t.includes("24bit")}var ut=ts(),O={reset:"\x1B[0m",visaBlue:ut?"\x1B[38;2;20;52;203m":"\x1B[38;5;27m",visaBlueSoft:ut?"\x1B[38;2;97;126;229m":"\x1B[38;5;111m",visaGold:ut?"\x1B[38;2;247;182;0m":"\x1B[38;5;220m",green:"\x1B[38;5;48m",dim:"\x1B[2m"};function j(e,t){return e.length===0||process.env.NO_COLOR?e:`${t}${e}${O.reset}`}function cn(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function yn(){let e=Le.homedir();if(!e||!w.isAbsolute(e))throw new Error("unable to determine a valid home directory");return w.resolve(e)}function ns(e){return e==="powershell"?"& visa-cli shell-hud refresh":"visa-cli shell-hud refresh"}function rs(e){return e==="powershell"?"Get-Command visa-cli -ErrorAction SilentlyContinue -CommandType Application":"command -v visa-cli >/dev/null 2>&1"}function ss(e){for(let t=0;t<2;t+=1){let n;try{return n=y.openSync(e,"wx"),y.writeFileSync(n,String(Date.now())),!0}catch(r){if(r?.code!=="EEXIST")return!1;try{let s=y.statSync(e);if(Date.now()-s.mtimeMs<=zr)return!1;y.unlinkSync(e)}catch{}}finally{n!==void 0&&y.closeSync(n)}}return!1}function Sn(e){return e instanceof Error?e.message:"unknown file system error"}function Ie(e,t){y.mkdirSync(w.dirname(e),{recursive:!0});let n=`${e}.${process.pid}.${Date.now()}.tmp`;y.writeFileSync(n,t),y.renameSync(n,e)}async function gt(e,t){try{return await t()}catch(n){if(n.message==="Invalid signature"&&A()){se.warn("attestation:key-mismatch",{action:"reregistering"});try{let r=await Pe();await e.registerAttestationKey(r),se.info("attestation:key-reregistered")}catch(r){throw se.error("attestation:reregister-failure",{error:r.message}),n}return await t()}throw n}}var vn="1.7.0";function W(e,t){return t?{kind:"env",var:e}:{kind:"default"}}function N(e){return e==null?"\u2014":e?"yes":"no"}function Me(e){return e==null?"\u2014":`$${e.toFixed(2)}`}async function bn(e){let t=null,n=null;try{t=await e.api.getStatus()}catch($){n=$?.message||"unknown error"}let r=[],s=process.env.VISA_AUTH_URL;r.push({key:"auth.serverUrl",value:s||"https://auth.visacli.sh",formatted:s||"https://auth.visacli.sh",source:W("VISA_AUTH_URL",!!s),hint:s?void 0:"Set VISA_AUTH_URL to point at a staging or self-hosted auth server."}),r.push({key:"account.enrolled",value:t?.enrolled??null,formatted:N(t?.enrolled),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),t?.githubUser&&r.push({key:"account.githubUser",value:t.githubUser,formatted:t.githubUser,source:{kind:"server"}});let o=t?t.attestationRequired!==!1:void 0;r.push({key:"biometric.required",value:o,formatted:N(o),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"},hint:o===!1?"Touch ID prompts are suppressed. Re-enable with `visa-cli biometric on`.":void 0}),r.push({key:"biometric.keyRegistered",value:t?.hasAttestationKey??null,formatted:N(t?.hasAttestationKey),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"biometric.deviceAvailable",value:A(),formatted:N(A()),source:{kind:"device"}});let i=t?.spendingControls,a=i?i.max_transaction_amount??i.maxTransactionAmount??null:null,c=i?i.daily_limit??i.dailyLimit??null:null;r.push({key:"spending.maxPerTxn",value:a,formatted:Me(a),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyLimit",value:c,formatted:Me(c),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailySpent",value:t?.dailySpent??null,formatted:Me(t?.dailySpent),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"spending.dailyRemaining",value:t?.dailyRemaining??null,formatted:Me(t?.dailyRemaining),source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}}),r.push({key:"cards.count",value:t?.cardCount??null,formatted:t?.cardCount!=null?String(t.cardCount):"\u2014",source:t?{kind:"server"}:{kind:"unknown",reason:n||"offline"}});let l=t?.cards?.find($=>$.isDefault)??t?.cards?.[0];l&&r.push({key:"cards.default",value:{brand:l.brand??null,last4:l.last4},formatted:`${l.brand||"card"} \u2022\u2022\u2022\u2022 ${l.last4}`,source:{kind:"server"}});let u=process.env.VISA_SUPPRESS_BROWSER;r.push({key:"ui.suppressBrowser",value:u==="true",formatted:N(u==="true"),source:W("VISA_SUPPRESS_BROWSER",!!u),hint:"Set to `true` to stop the CLI from opening payment URLs in your browser."});let f=process.env.VISA_SUPPRESS_FEED;r.push({key:"ui.suppressFeed",value:f==="true",formatted:N(f==="true"),source:W("VISA_SUPPRESS_FEED",!!f)});let d=K(),m;process.env.VISA_CLI_NO_UPDATE_CHECK?m={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?m={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?m={kind:"env",var:"NODE_ENV"}:m={kind:"default"},r.push({key:"ui.updateCheck",value:!d,formatted:N(!d),source:m});let v=process.env.VISA_META_TOOLS;r.push({key:"tools.meta",value:v!=="false",formatted:N(v!=="false"),source:W("VISA_META_TOOLS",v!==void 0)});let k=process.env.VISA_SPECIFIC_TOOLS;r.push({key:"tools.specific",value:k!=="false",formatted:N(k!=="false"),source:W("VISA_SPECIFIC_TOOLS",k!==void 0)});let L=process.env.VISA_DISCOVER_TOOLS;if(r.push({key:"tools.discover",value:L!=="false",formatted:N(L!=="false"),source:W("VISA_DISCOVER_TOOLS",L!==void 0)}),r.push({key:"client.version",value:vn,formatted:vn,source:{kind:"default"}}),e.includeDev){let $=process.env.VISA_MOCK_KEYCHAIN;r.push({key:"dev.mockKeychain",value:$==="true",formatted:N($==="true"),source:W("VISA_MOCK_KEYCHAIN",!!$)});let D=process.env.VISA_MOCK_TOUCHID;r.push({key:"dev.mockTouchid",value:D==="true",formatted:N(D==="true"),source:W("VISA_MOCK_TOUCHID",!!D)});let M=process.env.VISA_CLI_DEBUG;r.push({key:"dev.debug",value:!!M,formatted:N(!!M),source:W("VISA_CLI_DEBUG",!!M)})}return{entries:r,statusError:n}}function os(e){switch(e.kind){case"default":return"default";case"env":return`env ${e.var}`;case"server":return"server";case"device":return"device";case"unset":return"unset";case"unknown":return`unknown (${e.reason})`}}function wn(e,t={}){if(e.length===0)return"";let n=Math.max(...e.map(o=>o.key.length)),r=Math.max(...e.map(o=>o.formatted.length)),s=[];for(let o of e){let i=o.key.padEnd(n+2),a=o.formatted.padEnd(r+2);s.push(`${i}${a}(${os(o.source)})`),t.verbose&&o.hint&&s.push(` ${"\u21B3".padStart(n)} ${o.hint}`)}return s.join(`
|
|
93
93
|
`)}function _n(e){return JSON.stringify({config:e.entries.map(t=>({key:t.key,value:t.value,source:t.source,hint:t.hint})),statusError:e.statusError},null,2)}var I=class extends Error{constructor(t){super(t),this.name="PayValidationError"}},Cn=["GET","POST"];function kn(e){let t;try{t=new URL(e)}catch{throw new I(`Invalid URL: ${e}. Expected a fully-qualified http(s) URL.`)}if(t.protocol!=="http:"&&t.protocol!=="https:")throw new I(`Unsupported URL scheme "${t.protocol}". Only http and https are allowed.`);return t}function $n(e){let t=(e??"GET").toUpperCase();if(!Cn.includes(t))throw new I(`Unsupported HTTP method "${e}". Supported: ${Cn.join(", ")}.`);return t}function En(e){if(e!==void 0){try{JSON.parse(e)}catch(t){throw new I(`--body is not valid JSON: ${t?.message??"parse error"}`)}return e}}function xn(e){if(!e||typeof e!="object")throw new I("Merchant returned no payment preview.");let t=e;if(typeof t.amount!="number"||!Number.isFinite(t.amount)||t.amount<=0)throw new I("Could not determine payment amount from merchant.");if(typeof t.merchantName!="string"||t.merchantName.trim().length===0)throw new I("Merchant returned an empty merchant name.");if(t.merchantName.length>200)throw new I(`Merchant name too long (${t.merchantName.length} chars).`);if(typeof t.currency!="string"||t.currency.trim().length===0)throw new I("Merchant returned an empty currency.");if(t.currency.length>10)throw new I(`Currency code too long (${t.currency.length} chars).`);return{amount:t.amount,currency:t.currency,merchantName:t.merchantName}}var g=h(require("fs")),p=h(require("path")),Pn=h(require("os")),_=Pn.homedir(),is=["Claude_","Anthropic.ClaudeDesktop_"];function Rn(){return process.env.APPDATA||p.join(_,"AppData","Roaming")}function as(){return process.env.LOCALAPPDATA||p.join(_,"AppData","Local")}function Tn(){if(process.platform!=="win32")return;let e=p.join(as(),"Packages");if(g.existsSync(e))try{let t=g.readdirSync(e,"utf-8");for(let n of is){let r=t.filter(s=>s.startsWith(n)).sort()[0];if(r)return p.join(e,r,"LocalCache","Roaming","Claude")}}catch{return}}function An(){if(process.platform==="win32"){let e=Tn();return e?p.join(e,"claude_desktop_config.json"):p.join(Rn(),"Claude","claude_desktop_config.json")}return p.join(_,"Library","Application Support","Claude","claude_desktop_config.json")}function In(){if(process.platform!=="win32")return[p.join(_,"Library","Application Support","Claude")];let e=[p.join(Rn(),"Claude")],t=Tn();return t&&e.push(t),e}function Ue(e){return e.id==="claude-desktop"?An():e.globalConfigPath}function cs(e){return e.id==="claude-desktop"?In():e.detectPaths}var V=[{id:"claude",displayName:"Claude Code",globalConfigPath:p.join(_,".claude.json"),configKey:"mcpServers",detectPaths:[p.join(_,".claude.json")],postInstallHint:"Restart Claude Code or run /mcp to connect."},{id:"claude-desktop",displayName:"Claude Desktop",globalConfigPath:An(),configKey:"mcpServers",detectPaths:In(),postInstallHint:"Restart the Claude desktop app to connect."},{id:"cursor",displayName:"Cursor",globalConfigPath:p.join(_,".cursor","mcp.json"),configKey:"mcpServers",detectPaths:[p.join(_,".cursor")],postInstallHint:"Restart Cursor to connect."},{id:"windsurf",displayName:"Windsurf",globalConfigPath:p.join(_,".codeium","windsurf","mcp_config.json"),configKey:"mcpServers",detectPaths:[p.join(_,".codeium","windsurf")],postInstallHint:"Restart Windsurf to connect."},{id:"cline",displayName:"Cline",globalConfigPath:p.join(_,".vscode","mcp.json"),configKey:"mcpServers",detectPaths:[p.join(_,".vscode","extensions","saoudrizwan.claude-dev-*")],postInstallHint:"Restart VS Code to connect."},{id:"roo-code",displayName:"Roo Code",globalConfigPath:p.join(_,".config","Roo","mcp_settings.json"),configKey:"mcpServers",detectPaths:[p.join(_,".vscode","extensions","RooVeterinaryInc.roo-cline-*")],postInstallHint:"Restart VS Code to connect."},{id:"copilot",displayName:"VS Code Copilot",globalConfigPath:p.join(_,".vscode","mcp.json"),configKey:"servers",detectPaths:[p.join(_,".vscode")],postInstallHint:"Restart VS Code to connect."},{id:"zed",displayName:"Zed",globalConfigPath:p.join(_,".config","zed","settings.json"),configKey:"context_servers",detectPaths:[p.join(_,".config","zed")],postInstallHint:"Restart Zed to connect.",buildEntry:e=>({source:"custom",...e})},{id:"codex",displayName:"Codex",globalConfigPath:p.join(_,".codex","config.toml"),configKey:"mcp_servers",configFormat:"toml",detectPaths:[p.join(_,".codex")],postInstallHint:"Restart Codex to connect."}];function ht(e){return V.find(t=>t.id===e)}function de(e){return cs(e).some(t=>{if(t.includes("*")){let n=p.dirname(t),r=p.basename(t).replaceAll("*","");if(!g.existsSync(n))return!1;try{return g.readdirSync(n).some(s=>s.startsWith(r))}catch{return!1}}return g.existsSync(t)})}function Ln(){return{command:"node",args:[p.resolve(__dirname,"mcp-server/index.js")]}}function yt(e,t){return t==="project"?"json":e.configFormat??"json"}function ls(e){if(e=e.trim(),e==="true")return!0;if(e==="false")return!1;if(e.startsWith('"')&&e.endsWith('"'))return e.slice(1,-1);if(e.startsWith("[")&&e.endsWith("]")){let n=e.slice(1,-1).trim();return n.length===0?[]:n.split(",").map(r=>r.trim()).filter(Boolean).map(r=>r.startsWith('"')&&r.endsWith('"')?r.slice(1,-1):r)}let t=Number(e);return isNaN(t)?e:t}function St(e,t){let n=`[mcp_servers.${t}]`,r=e.findIndex(o=>o.trim()===n);if(r===-1)return;let s=r+1;for(;s<e.length&&!e[s].trim().startsWith("[");)s++;return{start:r,end:s}}function vt(e,t){let n=e.split(`
|
|
94
94
|
`),r=St(n,t);if(!r)return;let s={};for(let o=r.start+1;o<r.end;o++){let i=n[o].trim().match(/^(\w+)\s*=\s*(.+)$/);i&&(s[i[1]]=ls(i[2]))}return Object.keys(s).length>0?s:void 0}function us(e,t,n){let r=`[${n.args.map(c=>`"${c}"`).join(", ")}]`,s=[`[mcp_servers.${t}]`,`command = "${n.command}"`,`args = ${r}`],o=e.split(`
|
|
95
95
|
`),i=St(o,t);if(i){o.splice(i.start,i.end-i.start,...s);let c=o.join(`
|
package/dist/mcp-server/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
"use strict";var On=Object.create;var Ft=Object.defineProperty;var Cn=Object.getOwnPropertyDescriptor;var Pn=Object.getOwnPropertyNames;var Nn=Object.getPrototypeOf,Ln=Object.prototype.hasOwnProperty;var $n=(r,e)=>()=>(r&&(e=r(r=0)),e);var Mn=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),yr=(r,e)=>{for(var t in e)Ft(r,t,{get:e[t],enumerable:!0})},jn=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Pn(e))!Ln.call(r,s)&&s!==t&&Ft(r,s,{get:()=>e[s],enumerable:!(n=Cn(e,s))||n.enumerable});return r};var A=(r,e,t)=>(t=r!=null?On(Nn(r)):{},jn(e||!r||!r.__esModule?Ft(t,"default",{value:r,enumerable:!0}):t,r));var _r={};yr(_r,{fetchWithTimeout:()=>Bt});async function Bt(r,e){let t=e?.timeoutMs??3e4,n=new AbortController,s=setTimeout(()=>n.abort(),t);try{let{timeoutMs:a,...i}=e??{};return await fetch(r,{...i,signal:n.signal})}finally{clearTimeout(s)}}var Wt=$n(()=>{"use strict"});var vn=Mn((Ko,Ti)=>{Ti.exports={name:"@visa/cli",version:"1.7.0
|
|
2
|
+
"use strict";var On=Object.create;var Ft=Object.defineProperty;var Cn=Object.getOwnPropertyDescriptor;var Pn=Object.getOwnPropertyNames;var Nn=Object.getPrototypeOf,Ln=Object.prototype.hasOwnProperty;var $n=(r,e)=>()=>(r&&(e=r(r=0)),e);var Mn=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports),yr=(r,e)=>{for(var t in e)Ft(r,t,{get:e[t],enumerable:!0})},jn=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Pn(e))!Ln.call(r,s)&&s!==t&&Ft(r,s,{get:()=>e[s],enumerable:!(n=Cn(e,s))||n.enumerable});return r};var A=(r,e,t)=>(t=r!=null?On(Nn(r)):{},jn(e||!r||!r.__esModule?Ft(t,"default",{value:r,enumerable:!0}):t,r));var _r={};yr(_r,{fetchWithTimeout:()=>Bt});async function Bt(r,e){let t=e?.timeoutMs??3e4,n=new AbortController,s=setTimeout(()=>n.abort(),t);try{let{timeoutMs:a,...i}=e??{};return await fetch(r,{...i,signal:n.signal})}finally{clearTimeout(s)}}var Wt=$n(()=>{"use strict"});var vn=Mn((Ko,Ti)=>{Ti.exports={name:"@visa/cli",version:"1.7.0",description:"AI-powered payments for Claude Code",bin:{"visa-cli":"./bin/visa-cli.js"},scripts:{build:"tsc --noEmit && node esbuild.config.js",dev:"tsc --watch",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"},devDependencies:{"@visa-cli/tools":"workspace:*","@changesets/changelog-git":"^0.2.1","@changesets/cli":"^2.30.0","@types/jest":"^30.0.0","@types/node":"^25.6.0","@typescript-eslint/eslint-plugin":"^8.59.0","@typescript-eslint/parser":"^8.59.0","@types/express":"^5.0.0",esbuild:"^0.27.4",express:"^4.21.0",eslint:"^10.0.2","eslint-config-prettier":"^10.1.8",jest:"^29.7.0",prettier:"^3.8.3","ts-jest":"^29.2.0",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","native/visa-keychain.m","server.json","README.md","LICENSE"]}});var Sn=require("@modelcontextprotocol/sdk/server/index.js"),Tn=require("@modelcontextprotocol/sdk/server/stdio.js"),ae=require("@modelcontextprotocol/sdk/types.js");Wt();var Dn=/^(\d+)\.(\d+)\.(\d+)(?:-([0-9A-Za-z.-]+))?(?:\+[0-9A-Za-z.-]+)?$/;function _t(r,e){let t=vr(r),n=vr(e);if(!t||!n)return!1;for(let s=0;s<3;s++)if(t.main[s]!==n.main[s])return t.main[s]>n.main[s];return t.pre&&!n.pre?!1:!t.pre&&n.pre?!0:!t.pre&&!n.pre?!1:Un(t.pre,n.pre)>0}function vr(r){if(typeof r!="string")return null;let t=r.trim().replace(/^v/,"").match(Dn);return t?{main:[Number(t[1]),Number(t[2]),Number(t[3])],pre:t[4]??null}:null}function Un(r,e){let t=r.split("."),n=e.split("."),s=Math.max(t.length,n.length);for(let a=0;a<s;a++){if(a>=t.length)return-1;if(a>=n.length)return 1;let i=t[a],o=n[a],c=/^\d+$/.test(i),u=/^\d+$/.test(o);if(c&&u){let d=Number(i)-Number(o);if(d!==0)return d}else{if(c)return-1;if(u)return 1;if(i<o)return-1;if(i>o)return 1}}return 0}function ze(){return!!(br(process.env.VISA_CLI_NO_UPDATE_CHECK)||br(process.env.CI)||process.env.NODE_ENV==="test")}function br(r){if(r===void 0)return!1;let e=r.trim().toLowerCase();return!(e===""||e==="0"||e==="false"||e==="no"||e==="off")}var zt="1.7.0",vt=class{constructor(e){this.getSessionToken=e;this.baseUrl=process.env.VISA_AUTH_URL||"https://auth.visacli.sh"}getSessionToken;baseUrl;lastSignals={};parseServerSignals(e){if(this.lastSignals={},!ze()){let n=e.headers.get("X-Latest-Version"),s=e.headers.get("X-Update-Message");n&&_t(n,zt)&&(this.lastSignals.updateAvailable={version:n,message:s||`Update available: v${n}. Run: npm install -g @visa/cli && visa-cli setup`})}let t=e.headers.get("X-Feedback-Prompt");if(t)try{this.lastSignals.feedbackPrompt=JSON.parse(t)}catch{}}getClientVersion(){return zt}async request(e,t,n,s,a){let i=await this.getSessionToken();if(!i)throw new Error("Not logged in. Sign up at https://visacli.sh or run: visa-cli setup");let o={Authorization:`Bearer ${i}`};a&&(e==="GET"?o["X-User-Context"]=a.replace(/[\r\n\0]/g," ").slice(0,1e3):n={...n||{},user_context:a}),n&&(o["Content-Type"]="application/json");let c;try{c=await Bt(`${this.baseUrl}${t}`,{method:e,headers:{...o,"X-Visa-CLI-Version":zt},body:n?JSON.stringify(n):void 0,timeoutMs:s})}catch(d){throw d.name==="AbortError"||d.message?.includes("aborted")?new Error("The request timed out. The server may be under heavy load. Please try again."):new Error("Cannot reach the Visa CLI server. Check your internet connection and try again.")}if(this.parseServerSignals(c),c.status===401)throw new Error("Your session has expired. Run: visa-cli setup");if(c.status===429){let d=c.headers.get("Retry-After")||"3";throw new Error(`Rate limited \u2014 wait ${d}s. Tip: use the batch tool to combine multiple requests into one.`)}if(c.status===503)throw new Error("Visa CLI is temporarily unavailable. Check https://visacli.sh for status.");let u;try{u=await c.json()}catch{throw c.status===500?new Error(`Server error on ${t}. Try again or check https://visacli.sh for status.`):new Error(`Unexpected response from ${t}. Try again.`)}if(!c.ok)throw c.status===500?new Error(`Server error on ${t}. Try again or check https://visacli.sh for status.`):new Error(u?.error||`Request failed (${c.status}). Try again.`);return u}async pay(e,t){return this.request("POST","/v1/pay",e,void 0,t)}async shortcut(e,t,n,s){return this.request("POST",`/v1/shortcuts/${encodeURIComponent(e)}`,t,n,s)}async batch(e,t,n){return this.request("POST","/v1/batch",e,t,n)}async catalogSearch(e,t){let n=new URLSearchParams;e&&n.set("q",e),t&&n.set("category",t);let s=n.toString();return this.request("GET",`/v1/catalog${s?`?${s}`:""}`)}async catalogTool(e){try{return await this.request("GET",`/v1/catalog/${encodeURIComponent(e)}`)}catch{return null}}async paymentPreview(e,t){return this.request("POST","/v1/payment-preview",e,void 0,t)}async getStatus(e){return this.request("GET","/v1/status",void 0,void 0,e)}async getTransactions(e){return this.request("GET","/v1/transactions",void 0,void 0,e)}async updateSpendingControls(e,t){return this.request("POST","/v1/spending-controls",e,void 0,t)}async removeCard(e,t,n){return this.request("DELETE",`/v1/cards/${encodeURIComponent(String(e))}`,t,void 0,n)}async setDefaultCard(e,t,n){return this.request("POST",`/v1/cards/${encodeURIComponent(String(e))}/default`,t,void 0,n)}async getAttestationChallenge(){return this.request("GET","/v1/attestation-challenge")}async registerAttestationKey(e){return this.request("POST","/v1/attestation-key",{publicKey:e})}async setBiometricPreference(e,t){return this.request("POST","/v1/biometric-preference",{...e,confirm:!0},void 0,t)}async logout(e,t){return this.request("POST","/v1/logout",e,void 0,t)}async feedback(e,t,n){return this.request("POST","/v1/feedback",{message:e,...t&&{transaction_id:t}},void 0,n)}async feedSubmit(e){return this.request("POST","/v1/feed",e)}async feedList(e){let t=new URLSearchParams;e?.tab&&t.set("tab",e.tab),e?.limit&&t.set("limit",String(e.limit)),e?.offset&&t.set("offset",String(e.offset));let n=t.toString();return this.request("GET",`/v1/feed${n?"?"+n:""}`)}async feedVote(e,t){return this.request("POST",`/v1/feed/${encodeURIComponent(e)}/vote`,{direction:t})}async feedApprove(e){return this.request("POST",`/v1/feed/${encodeURIComponent(e)}/approve`)}async feedDelete(e){return this.request("DELETE",`/v1/feed/${encodeURIComponent(e)}`)}async feedPending(){return this.request("GET","/v1/feed/pending")}async submitFeedback(e,t,n){return this.request("POST","/v1/feedback",{message:e,...t&&{transaction_id:t}},void 0,n)}async getFeedback(e,t){let n=new URLSearchParams;e&&n.set("limit",String(e));let s=n.toString();return this.request("GET",`/v1/feedback${s?"?"+s:""}`,void 0,void 0,t)}async submitRatedFeedback(e){return this.request("POST","/v1/feedback",e)}};var Jt=require("child_process"),Ir=require("util"),Er=A(require("crypto")),L=A(require("fs")),Rr=A(require("os")),X=A(require("path"));var q=A(require("fs")),Gt=A(require("path")),wr=A(require("os")),Kt=Gt.join(wr.homedir(),".visa-mcp"),nt=Gt.join(Kt,"mcp-server.log"),qn=5*1024*1024,Zt=null;function Vn(){q.existsSync(Kt)||q.mkdirSync(Kt,{recursive:!0,mode:448})}function Hn(){if(!Zt){if(Vn(),q.existsSync(nt)&&q.statSync(nt).size>qn){let e=nt+".1";q.existsSync(e)&&q.unlinkSync(e),q.renameSync(nt,e)}Zt=q.createWriteStream(nt,{flags:"a"})}return Zt}function bt(r,...e){let t=new Date().toISOString(),n=e.map(a=>typeof a=="string"?a:JSON.stringify(a,null,2)).join(" "),s=`[${t}] [${r}] ${n}
|
|
3
3
|
`;process.stderr.write(s),Hn().write(s)}var l={debug:(...r)=>bt("DEBUG",...r),info:(...r)=>bt("INFO",...r),warn:(...r)=>bt("WARN",...r),error:(...r)=>bt("ERROR",...r)};var Ze=(0,Ir.promisify)(Jt.execFile),kt=X.join(Rr.homedir(),".visa-mcp","bin"),Se=X.join(kt,"Visa CLI"),Fn=X.join(__dirname,"..","native"),xr="5",kr=X.join(kt,"visa-keychain.version"),Sr=X.join(kt,"visa-keychain.sha256");function Tr(r){let e=L.readFileSync(r);return Er.createHash("sha256").update(e).digest("hex")}async function Ar(){try{if(L.readFileSync(kr,"utf-8").trim()===xr&&L.existsSync(Se)){let n=L.readFileSync(Sr,"utf-8").trim();if(Tr(Se)!==n)l.warn("binary:hash-mismatch",{message:"Binary hash mismatch \u2014 possible tampering detected. Recompiling from source."}),L.unlinkSync(Se);else return Se}}catch{}let r=X.join(Fn,"visa-keychain.m");if(L.existsSync(r)||(r=X.resolve(__dirname,"..","..","native","visa-keychain.m")),L.existsSync(r)||(r=X.resolve(__dirname,"..","native","visa-keychain.m")),!L.existsSync(r))throw new Error("visa-keychain.m source not found. Reinstall Visa CLI.");L.mkdirSync(kt,{recursive:!0,mode:448});try{await Ze("clang",["-framework","Security","-framework","LocalAuthentication","-framework","Foundation","-framework","AppKit","-o",Se,r],{timeout:3e4})}catch(t){throw t.code==="ENOENT"?new Error("Xcode Command Line Tools required. Install: xcode-select --install"):t}let e=Tr(Se);return L.writeFileSync(Sr,e,{mode:384}),L.writeFileSync(kr,xr,{mode:384}),Se}async function Or(r){let e=await Ar(),t;try{t=(await Ze(e,r,{timeout:6e4})).stdout}catch(a){t=a.stdout||"";let i=t.trim();throw i.startsWith("ERROR:")?new Error(i.slice(6)):new Error(a.stderr?.trim()||a.message||"Unknown error")}let n=t.trim();if(n.startsWith("OK:"))return n.slice(3);if(n==="OK")return;let s=n.startsWith("ERROR:")?n.slice(6):"Unknown error";throw new Error(s)}var Yt=null;function ue(){return process.env.VISA_MOCK_TOUCHID==="true"?!0:process.platform!=="darwin"?!1:Yt!==null?Yt:(Yt=!0,!0)}var wt="visa-cli",xt="attestation-key";async function Bn(r){try{await Ze("security",["delete-generic-password","-s",wt,"-a",xt],{timeout:5e3})}catch{}await Ze("security",["add-generic-password","-s",wt,"-a",xt,"-w",r],{timeout:5e3})}async function Wn(){try{let{stdout:r}=await Ze("security",["find-generic-password","-s",wt,"-a",xt,"-w"],{timeout:5e3});return r.trim()||null}catch{return null}}async function Cr(){let r=await Or(["generate-key"]);if(!r)throw new Error("Key generation returned no output");let e=r.indexOf(":");if(e<0)throw new Error("Unexpected generate-key output format");let t=r.slice(0,e),n=r.slice(e+1);return await Bn(t),n}async function Pr(r,e){if(process.env.VISA_MOCK_TOUCHID==="true")return Promise.resolve("mock-ecdsa-signature-for-testing");let t=await Wn();if(!t)throw new Error("Attestation key not found. Run setup to generate a new key.");let n=await Ar(),s=["sign",r];return e&&s.push(e),new Promise((a,i)=>{let o=(0,Jt.execFile)(n,s,{timeout:6e4},(c,u)=>{let d=(u||"").trim();if(c){d.startsWith("ERROR:")?i(new Error(d.slice(6))):i(new Error(c.stderr?.trim()||c.message||"Unknown error"));return}d.startsWith("OK:")?a(d.slice(3)):i(new Error(d.startsWith("ERROR:")?d.slice(6):"Unknown error"))});o.stdin.write(t),o.stdin.end()})}async function Nr(){try{await Ze("security",["delete-generic-password","-s",wt,"-a",xt],{timeout:5e3})}catch{}try{await Or(["delete-key"])}catch{}}var It=require("child_process"),Lr=require("util"),ye=A(require("fs")),Et=A(require("os")),rr=A(require("path")),Q=(0,Lr.promisify)(It.execFile),nr=rr.join(Et.homedir(),".visa-mcp"),St=rr.join(nr,"session-token"),z="visa-cli",ge="session-token",Tt="rc-access",zn=5e3;async function Zn(){try{let{stdout:r}=await Q("security",["find-generic-password","-s",z,"-a",ge,"-w"],{timeout:5e3});return r.trim()||null}catch{return null}}async function Kn(r){try{try{await Q("security",["delete-generic-password","-s",z,"-a",ge],{timeout:5e3})}catch{}return await Q("security",["add-generic-password","-s",z,"-a",ge,"-w",r],{timeout:5e3}),!0}catch{return!1}}async function Gn(){try{await Q("security",["delete-generic-password","-s",z,"-a",ge],{timeout:5e3})}catch{}}async function Yn(){if(!sr())return null;try{let{stdout:r}=await Q("secret-tool",["lookup","service",z,"account",ge],{timeout:5e3});return r.trim()||null}catch{return null}}async function Jn(r){if(!sr())return!1;try{let e=(0,It.execFile)("secret-tool",["store","--label",`${z} ${ge}`,"service",z,"account",ge]);return e.stdin?(e.stdin.write(r),e.stdin.end(),await Promise.race([new Promise((t,n)=>{e.on("exit",s=>s===0?t():n(new Error(`secret-tool exited ${s}`))),e.on("error",n)}),new Promise((t,n)=>setTimeout(()=>{e.kill(),n(new Error("secret-tool timed out"))},zn))]),!0):!1}catch{return!1}}async function Xn(){if(sr())try{await Q("secret-tool",["clear","service",z,"account",ge],{timeout:5e3})}catch{}}function sr(){return!!process.env.DBUS_SESSION_BUS_ADDRESS}async function Qn(){try{let{stdout:r}=await Q("security",["find-generic-password","-s",z,"-a",Tt,"-w"],{timeout:5e3});return r.trim()||null}catch{return null}}async function es(r){try{try{await Q("security",["delete-generic-password","-s",z,"-a",Tt],{timeout:5e3})}catch{}await Q("security",["add-generic-password","-s",z,"-a",Tt,"-w",r],{timeout:5e3})}catch{}}async function ts(){try{await Q("security",["delete-generic-password","-s",z,"-a",Tt],{timeout:5e3})}catch{}}function er(){try{return ye.readFileSync(St,"utf-8").trim()||null}catch{return null}}function $r(r){ye.mkdirSync(nr,{recursive:!0,mode:448}),ye.writeFileSync(St,r,{mode:384}),process.platform==="win32"&&rs(St)}function tr(){try{ye.unlinkSync(St)}catch{}}function rs(r){try{let e=Et.userInfo().username;(0,It.execFile)("icacls",[r,"/inheritance:r","/grant:r",`${e}:F`],{timeout:5e3},t=>{t&&console.error(`[visa-cli] icacls ACL restriction failed: ${t.message}`)})}catch(e){console.error(`[visa-cli] Failed to invoke icacls: ${e instanceof Error?e.message:String(e)}`)}}function Qt(){switch(process.platform){case"darwin":return{get:Zn,store:Kn,delete:Gn};case"linux":return{get:Yn,store:Jn,delete:Xn};default:return{get:async()=>er(),store:async r=>{try{return $r(r),!0}catch{return!1}},delete:async()=>tr()}}}var M=class{static async getSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN==="true")return Promise.resolve("mock-session-token-for-testing");let e=Qt(),t=await e.get();if(t)return t;let n=er();return n?(await e.store(n),n):null}static async saveSessionToken(e){if(process.env.VISA_MOCK_KEYCHAIN==="true")return;let t=Qt();if(await t.store(e)){if(await t.get()===e){tr();return}await t.delete()}if($r(e),er()!==e)throw new Error("Failed to persist session token. "+(process.platform==="darwin"?'Check Keychain Access permissions for "visa-cli".':`Ensure ${nr} is writable.`))}static async getRcAccessToken(){return process.env.VISA_MOCK_KEYCHAIN==="true"?"mock-rc-token-for-testing":Qn()}static async saveRcAccessToken(e){process.env.VISA_MOCK_KEYCHAIN!=="true"&&await es(e)}static async deleteSessionToken(){if(process.env.VISA_MOCK_KEYCHAIN==="true")return;await Qt().delete(),tr()}static async clearAll(){await this.deleteSessionToken(),await ts()}};var Rt={generate_image:{intro:"Generate an AI image.",tiers:{balanced:{toolId:"fal-flux-pro",priceCents:4,notes:"FLUX Pro v1.1, 1K, ~10s (DEFAULT \u2014 good quality/speed tradeoff)"},fast:{toolId:"fal-flux-schnell",priceCents:1,notes:"FLUX Schnell, 1K, ~3s (drafts, iteration, cheapest)"},pro:{toolId:"fal-flux-pro-ultra",priceCents:6,notes:"FLUX Pro Ultra, 2K, ~30s (hero images, detail)"},text_heavy:{toolId:"fal-ideogram-v2",priceCents:8,notes:"Ideogram V2 \u2014 best when the image contains rendered text/logos"},vector:{toolId:"fal-recraft-v3",priceCents:5,notes:"Recraft V3 \u2014 vector/flat/illustration styles"}},guidance:"If the user didn't specify a tier, pick 'balanced' unless the prompt clearly signals otherwise (text \u2192 text_heavy, logo/icon \u2192 vector, quick test \u2192 fast, hero/print \u2192 pro).",inputProperties:{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"]},generate_video:{intro:"Generate an AI video from a text prompt.",tiers:{balanced:{toolId:"fal-minimax-video",priceCents:15,notes:"MiniMax \u2014 good quality/price balance (DEFAULT)"},fast:{toolId:"fal-wan-video",priceCents:10,notes:"Wan \u2014 cheapest, shorter clips"},pro:{toolId:"fal-kling-video",priceCents:20,notes:"Kling \u2014 highest quality, cinematic"}},guidance:"Show the tier menu with prices unless the user specified one. Videos take 60-180s to generate.",inputProperties:{prompt:{type:"string",description:"Text description of the video scene."},aspect_ratio:{type:"string",description:'Aspect ratio, e.g. "16:9" or "9:16".',default:"16:9"}},required:["prompt"]},generate_music:{intro:"Generate an original music track from a prompt.",tiers:{suno:{toolId:"suno-music",priceCents:10,notes:"Suno v4 \u2014 songs with vocals, lyrics, full arrangement"}},guidance:"Takes ~60-90s. Returns an audio URL the user can play.",inputProperties:{prompt:{type:"string",description:"Musical style / mood / lyrics hint."},instrumental:{type:"boolean",description:"True for instrumental (no vocals), false for vocal track.",default:!1}},required:["prompt"]},generate_audio:{intro:"Generate speech or sound effects.",tiers:{tts:{toolId:"fal-metavoice",priceCents:3,notes:"MetaVoice \u2014 high-quality TTS from text"},sfx:{toolId:"fal-stable-audio",priceCents:4,notes:"Stable Audio \u2014 sound effects and ambient from a prompt"}},guidance:'Pick "tts" for spoken words, "sfx" for music-beds/effects/ambient.',inputProperties:{prompt:{type:"string",description:"Text to speak (tts) or description of sound (sfx)."}},required:["prompt"]},generate_3d:{intro:"Generate a 3D model from a text description.",tiers:{trellis:{toolId:"fal-trellis-3d",priceCents:8,notes:"Trellis \u2014 fast text-to-3D, returns a GLB mesh URL"}},guidance:"Takes ~30-60s. Returns a downloadable 3D mesh URL.",inputProperties:{prompt:{type:"string",description:"Description of the 3D object."}},required:["prompt"]},upscale_image:{intro:"Upscale an image to higher resolution.",tiers:{aura:{toolId:"fal-aura-sr",priceCents:3,notes:"Aura SR \u2014 default; preserves detail without hallucination"}},guidance:"Pass the existing image URL. Returns an upscaled version.",inputProperties:{image_url:{type:"string",description:"URL of the image to upscale."}},required:["image_url"]},transcribe_audio:{intro:"Transcribe speech in an audio/video URL to text.",tiers:{whisper:{toolId:"fal-whisper",priceCents:2,notes:"OpenAI Whisper \u2014 fast, multilingual"}},guidance:"Pass the URL. Returns the transcript text.",inputProperties:{audio_url:{type:"string",description:"URL of the audio or video file to transcribe."}},required:["audio_url"]},run_llm:{intro:"Run a text prompt through an LLM (OpenRouter). Token-metered \u2014 prices below are per 1M input/output tokens. Typical 500-in/500-out prompts cost 1\u20139\xA2 depending on model.",tiers:{fast:{toolId:"or-gpt-4o-mini",priceCents:1,notes:"GPT-4o Mini \u2014 $0.15/M in \xB7 $0.60/M out. Fastest, cheapest, good general-purpose (DEFAULT)"},reasoning:{toolId:"or-claude-sonnet",priceCents:9,notes:"Claude 3.5 Sonnet \u2014 $3.00/M in \xB7 $15.00/M out. Strong reasoning, long-context. ~20x pricier than `fast`."},deep_reasoning:{toolId:"or-deepseek-r1",priceCents:2,notes:"DeepSeek R1 \u2014 $0.55/M in \xB7 $2.19/M out. Deep chain-of-thought reasoning, mid-range pricing."},search:{toolId:"or-perplexity-sonar",priceCents:1,notes:"Perplexity Sonar \u2014 $1.00/M in \xB7 $1.00/M out. Search-augmented, web-grounded with citations."},open_source:{toolId:"or-llama-70b",priceCents:1,notes:"Llama 3.3 70B \u2014 $0.30/M in \xB7 $0.40/M out. Open-source large model."},coding:{toolId:"or-deepseek-chat",priceCents:1,notes:"DeepSeek Chat V3 \u2014 $0.30/M in \xB7 $0.88/M out. Strong at code generation."}},guidance:"Pick based on the user's need: fast (most questions, cheapest), reasoning (complex analysis \u2014 WARN user it's ~$0.09/call), search (questions about current events), coding (code generation), deep_reasoning (hard math/logic problems).",inputProperties:{prompt:{type:"string",description:"The user query."},system_prompt:{type:"string",description:"Optional system prompt to set model behavior."},max_tokens:{type:"number",description:"Maximum output tokens.",default:1024,minimum:1,maximum:8192},temperature:{type:"number",description:"Sampling temperature \u2014 0 is deterministic, higher is more creative.",default:.7,minimum:0,maximum:2}},required:["prompt"]}};function st(){return process.env.VISA_SPECIFIC_TOOLS!=="false"}function at(){return process.env.VISA_META_TOOLS!=="false"}function it(){return process.env.VISA_DISCOVER_TOOLS!=="false"}function Mr(r){let e=Rt[r];if(!e)throw new Error(`Unknown meta-tool: ${r}`);let t=[e.intro,"","Tiers:"];for(let[n,s]of Object.entries(e.tiers)){let a=`$${(s.priceCents/100).toFixed(2)}`;t.push(` - ${n.padEnd(15)} ${a.padStart(6)} ${s.notes}`)}return t.push("",e.guidance),t.join(`
|
|
4
|
-
`)}function jr(r){let e=Rt[r];if(!e)throw new Error(`Unknown meta-tool: ${r}`);let t=Object.keys(e.tiers);return{type:"object",properties:{tier:{type:"string",enum:t,default:t[0],description:`Quality/style tier. Default: ${t[0]}.`},...e.inputProperties},required:e.required??[]}}function At(r,e){if(!Te.includes(r))return r;let t=Rt[r];if(!t)return r;let n=Object.keys(t.tiers),s=e||n[0],a=t.tiers[s];if(!a)throw new Error(`Unknown tier '${s}' for ${r}. Valid tiers: ${n.join(", ")}`);return a.toolId}async function Dr(r,e,t){let n=At(r,e.tier),{tier:s,...a}=e;return O.executeTool({tool_id:n,...a},t)}var Te=Object.keys(Rt);function Ur(r=process.env,e=process.platform){return r.VISA_CLI_NO_BROWSER==="1"||r.VISA_CLI_NO_BROWSER==="true"?{headless:!0,reason:"VISA_CLI_NO_BROWSER is set"}:r.CI==="true"||r.CI==="1"?{headless:!0,reason:"CI environment detected"}:r.SSH_CONNECTION||r.SSH_TTY?{headless:!0,reason:"SSH session detected"}:e==="linux"&&!r.DISPLAY&&!r.WAYLAND_DISPLAY?{headless:!0,reason:"Linux with no $DISPLAY or $WAYLAND_DISPLAY"}:{headless:!1}}function qr(r,e=process.platform){return e==="darwin"?{cmd:"open",args:[r]}:e==="win32"?{cmd:"cmd",args:["/c","start","",r]}:e==="linux"?{cmd:"xdg-open",args:[r]}:null}var ut=A(require("crypto")),zr=require("child_process"),W=A(require("fs")),lt=A(require("os")),dt=A(require("path"));var ns="# visa-cli-hud-v1";function Ot(r){return typeof r!="string"?!1:r.includes(ns)?!0:r.includes("visa-cli")&&r.includes("statusline")}async function Vr(r,e){try{return await e()}catch(t){if(t.message==="Invalid signature"&&ue()){l.warn("attestation:key-mismatch",{action:"reregistering"});try{let n=await Cr();await r.registerAttestationKey(n),l.info("attestation:key-reregistered")}catch(n){throw l.error("attestation:reregister-failure",{error:n.message}),t}return await e()}throw t}}var Hr="1.7.0
|
|
4
|
+
`)}function jr(r){let e=Rt[r];if(!e)throw new Error(`Unknown meta-tool: ${r}`);let t=Object.keys(e.tiers);return{type:"object",properties:{tier:{type:"string",enum:t,default:t[0],description:`Quality/style tier. Default: ${t[0]}.`},...e.inputProperties},required:e.required??[]}}function At(r,e){if(!Te.includes(r))return r;let t=Rt[r];if(!t)return r;let n=Object.keys(t.tiers),s=e||n[0],a=t.tiers[s];if(!a)throw new Error(`Unknown tier '${s}' for ${r}. Valid tiers: ${n.join(", ")}`);return a.toolId}async function Dr(r,e,t){let n=At(r,e.tier),{tier:s,...a}=e;return O.executeTool({tool_id:n,...a},t)}var Te=Object.keys(Rt);function Ur(r=process.env,e=process.platform){return r.VISA_CLI_NO_BROWSER==="1"||r.VISA_CLI_NO_BROWSER==="true"?{headless:!0,reason:"VISA_CLI_NO_BROWSER is set"}:r.CI==="true"||r.CI==="1"?{headless:!0,reason:"CI environment detected"}:r.SSH_CONNECTION||r.SSH_TTY?{headless:!0,reason:"SSH session detected"}:e==="linux"&&!r.DISPLAY&&!r.WAYLAND_DISPLAY?{headless:!0,reason:"Linux with no $DISPLAY or $WAYLAND_DISPLAY"}:{headless:!1}}function qr(r,e=process.platform){return e==="darwin"?{cmd:"open",args:[r]}:e==="win32"?{cmd:"cmd",args:["/c","start","",r]}:e==="linux"?{cmd:"xdg-open",args:[r]}:null}var ut=A(require("crypto")),zr=require("child_process"),W=A(require("fs")),lt=A(require("os")),dt=A(require("path"));var ns="# visa-cli-hud-v1";function Ot(r){return typeof r!="string"?!1:r.includes(ns)?!0:r.includes("visa-cli")&&r.includes("statusline")}async function Vr(r,e){try{return await e()}catch(t){if(t.message==="Invalid signature"&&ue()){l.warn("attestation:key-mismatch",{action:"reregistering"});try{let n=await Cr();await r.registerAttestationKey(n),l.info("attestation:key-reregistered")}catch(n){throw l.error("attestation:reregister-failure",{error:n.message}),t}return await e()}throw t}}var Hr="1.7.0";function le(r,e){return e?{kind:"env",var:r}:{kind:"default"}}function F(r){return r==null?"\u2014":r?"yes":"no"}function Ct(r){return r==null?"\u2014":`$${r.toFixed(2)}`}async function Fr(r){let e=null,t=null;try{e=await r.api.getStatus()}catch(R){t=R?.message||"unknown error"}let n=[],s=process.env.VISA_AUTH_URL;n.push({key:"auth.serverUrl",value:s||"https://auth.visacli.sh",formatted:s||"https://auth.visacli.sh",source:le("VISA_AUTH_URL",!!s),hint:s?void 0:"Set VISA_AUTH_URL to point at a staging or self-hosted auth server."}),n.push({key:"account.enrolled",value:e?.enrolled??null,formatted:F(e?.enrolled),source:e?{kind:"server"}:{kind:"unknown",reason:t||"offline"}}),e?.githubUser&&n.push({key:"account.githubUser",value:e.githubUser,formatted:e.githubUser,source:{kind:"server"}});let a=e?e.attestationRequired!==!1:void 0;n.push({key:"biometric.required",value:a,formatted:F(a),source:e?{kind:"server"}:{kind:"unknown",reason:t||"offline"},hint:a===!1?"Touch ID prompts are suppressed. Re-enable with `visa-cli biometric on`.":void 0}),n.push({key:"biometric.keyRegistered",value:e?.hasAttestationKey??null,formatted:F(e?.hasAttestationKey),source:e?{kind:"server"}:{kind:"unknown",reason:t||"offline"}}),n.push({key:"biometric.deviceAvailable",value:ue(),formatted:F(ue()),source:{kind:"device"}});let i=e?.spendingControls,o=i?i.max_transaction_amount??i.maxTransactionAmount??null:null,c=i?i.daily_limit??i.dailyLimit??null:null;n.push({key:"spending.maxPerTxn",value:o,formatted:Ct(o),source:e?{kind:"server"}:{kind:"unknown",reason:t||"offline"}}),n.push({key:"spending.dailyLimit",value:c,formatted:Ct(c),source:e?{kind:"server"}:{kind:"unknown",reason:t||"offline"}}),n.push({key:"spending.dailySpent",value:e?.dailySpent??null,formatted:Ct(e?.dailySpent),source:e?{kind:"server"}:{kind:"unknown",reason:t||"offline"}}),n.push({key:"spending.dailyRemaining",value:e?.dailyRemaining??null,formatted:Ct(e?.dailyRemaining),source:e?{kind:"server"}:{kind:"unknown",reason:t||"offline"}}),n.push({key:"cards.count",value:e?.cardCount??null,formatted:e?.cardCount!=null?String(e.cardCount):"\u2014",source:e?{kind:"server"}:{kind:"unknown",reason:t||"offline"}});let u=e?.cards?.find(R=>R.isDefault)??e?.cards?.[0];u&&n.push({key:"cards.default",value:{brand:u.brand??null,last4:u.last4},formatted:`${u.brand||"card"} \u2022\u2022\u2022\u2022 ${u.last4}`,source:{kind:"server"}});let d=process.env.VISA_SUPPRESS_BROWSER;n.push({key:"ui.suppressBrowser",value:d==="true",formatted:F(d==="true"),source:le("VISA_SUPPRESS_BROWSER",!!d),hint:"Set to `true` to stop the CLI from opening payment URLs in your browser."});let g=process.env.VISA_SUPPRESS_FEED;n.push({key:"ui.suppressFeed",value:g==="true",formatted:F(g==="true"),source:le("VISA_SUPPRESS_FEED",!!g)});let C=ze(),y;process.env.VISA_CLI_NO_UPDATE_CHECK?y={kind:"env",var:"VISA_CLI_NO_UPDATE_CHECK"}:process.env.CI?y={kind:"env",var:"CI"}:process.env.NODE_ENV==="test"?y={kind:"env",var:"NODE_ENV"}:y={kind:"default"},n.push({key:"ui.updateCheck",value:!C,formatted:F(!C),source:y});let he=process.env.VISA_META_TOOLS;n.push({key:"tools.meta",value:he!=="false",formatted:F(he!=="false"),source:le("VISA_META_TOOLS",he!==void 0)});let w=process.env.VISA_SPECIFIC_TOOLS;n.push({key:"tools.specific",value:w!=="false",formatted:F(w!=="false"),source:le("VISA_SPECIFIC_TOOLS",w!==void 0)});let I=process.env.VISA_DISCOVER_TOOLS;if(n.push({key:"tools.discover",value:I!=="false",formatted:F(I!=="false"),source:le("VISA_DISCOVER_TOOLS",I!==void 0)}),n.push({key:"client.version",value:Hr,formatted:Hr,source:{kind:"default"}}),r.includeDev){let R=process.env.VISA_MOCK_KEYCHAIN;n.push({key:"dev.mockKeychain",value:R==="true",formatted:F(R==="true"),source:le("VISA_MOCK_KEYCHAIN",!!R)});let U=process.env.VISA_MOCK_TOUCHID;n.push({key:"dev.mockTouchid",value:U==="true",formatted:F(U==="true"),source:le("VISA_MOCK_TOUCHID",!!U)});let ie=process.env.VISA_CLI_DEBUG;n.push({key:"dev.debug",value:!!ie,formatted:F(!!ie),source:le("VISA_CLI_DEBUG",!!ie)})}return{entries:n,statusError:t}}var Pt=process.env.VISA_AUTH_URL||"https://auth.visacli.sh",k=new vt(()=>M.getSessionToken()),ss=["generate_image","generate_video","generate_music","generate_audio","generate_3d","upscale_image","transcribe_audio","run_llm"],Br=["","","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 recent transactions" \u2192 transaction_history','\u2022 "Set my daily limit to $50" \u2192 update_spending_controls','\u2022 "Pay https://example.com/checkout" \u2192 pay','\u2022 "Generate 3 variations in parallel" \u2192 batch',"","Fast shortcuts:",'\u2022 "Generate an image of a sunset over Tokyo" \u2192 generate_image_card (~$0.06)','\u2022 "Make a fast thumbnail: minimalist cat logo" \u2192 generate_image_fast_card (~$0.04)','\u2022 "Make a 4-second video of a penguin juggling" \u2192 generate_video_tempo_card (~$0.30)','\u2022 "Make a song about coding late at night" \u2192 generate_music_tempo_card (~$0.10)','\u2022 "Check the status of my music job" \u2192 check_music_status_tempo_card','\u2022 "What is ETH on Base trading at?" \u2192 query_onchain_prices_card (~$0.02)','\u2022 "Explore stablecoin inflows on Base" \u2192 allium_explorer_card','\u2022 "Open the latest Allium result set" \u2192 allium_explorer_results_card','\u2022 "Show pxlwall campaign insights" \u2192 pxlwall_card',"","Category tools:",...ss.map(r=>`\u2022 "${r.replace(/_/g," ")}" \u2192 ${r}`),"","Tool catalog:",'\u2022 "Find an image upscaler" \u2192 discover_tools','\u2022 "Run fal-aura-sr on this URL" \u2192 execute_tool'].join(`
|
|
5
5
|
`);function B(r){if(!r||typeof r!="string"||process.env.VISA_SUPPRESS_BROWSER==="true")return;let e;try{e=new URL(r)}catch{return}if(e.protocol!=="https:"&&e.protocol!=="http:")return;let t=e.toString(),n=Ur();if(n.headless){l.info(`Browser auto-open skipped (${n.reason}). URL: ${t}`);return}let s=qr(t);if(!s){l.info(`No browser command for platform "${lt.platform()}". URL: ${t}`);return}(0,zr.execFile)(s.cmd,s.args,a=>{a&&l.warn(`Browser open failed: ${a.message}. URL: ${t}`)})}async function j(r){return Vr(k,r)}var ot=null,as=3e4;function Zr(){ot=null}async function is(r){let e=Date.now();if(ot&&ot.expiresAt>e)return ot.value;try{let n=(await k.getStatus(r)).attestationRequired!==!1;return ot={value:n,expiresAt:e+as},n}catch{return!0}}async function P(r,e,t,n,s){if(!ue()){l.warn("attestation:unavailable",{context:r});return}if(!await is(s)){l.info("attestation:skipped-by-server-policy",{context:r});return}l.info("attestation:attempt",{context:r,amount:e,merchant:t});try{let{nonce:i}=await k.getAttestationChallenge(),o=Buffer.from(JSON.stringify({nonce:i,amount:e,merchant:t,context:r})).toString("base64");l.info("touchid:prompt",{context:r,amount:e,merchant:t});let c=await Pr(o,n);return l.info("attestation:success",{context:r,amount:e,merchant:t}),{signature:c,nonce:i,amount:e,merchant:t}}catch(i){throw l.error("attestation:failure",{context:r,amount:e,merchant:t,error:i.message}),i}}async function Y(r,e,t){let n=await k.paymentPreview({tool:r,url:e},t);if(!n||!n.merchantName||!n.amount||n.amount<=0)throw new Error("Could not determine payment amount and merchant. Try again.");if(!Number.isFinite(n.amount)||n.amount<0||n.amount>999999)throw new Error(`Invalid payment amount: ${n.amount}. Payment rejected for safety.`);return n}function ee(r){if(r.pricingMode==="max-cap"){let e=typeof r.estimatedAmount=="number"&&r.estimatedAmount>0?` (estimated $${r.estimatedAmount.toFixed(2)})`:"";return`pay up to $${r.amount.toFixed(2)} to ${r.merchantName}${e}`}return`pay $${r.amount.toFixed(2)} to ${r.merchantName}`}function Kr(){return dt.join(lt.homedir(),".visa-mcp","allium-results")}var os=16*1024,cs=50*1024*1024,us=10;function ls(r){return r.replace(/[^A-Za-z0-9_\-]/g,"_").slice(0,128)}function ds(r,e){let t=Kr();W.mkdirSync(t,{recursive:!0});let n=ls(r),s=dt.join(t,`${n}.csv`);W.writeFileSync(s,e);let a=Buffer.byteLength(e),i=e.split(`
|
|
6
6
|
`),o=i[0]??"",c=i.slice(1).filter(g=>g.length>0),u=[o,...c.slice(0,us)].join(`
|
|
7
7
|
`),d={file_path:s,row_count:c.length,size_bytes:a,columns:o,preview:u,truncated:!0};if(a>cs){let g=(a/1048576).toFixed(1);l.warn("allium:large_csv_written",{sessionId:r,size_bytes:a,file_path:s}),d.warning=`Wrote ${g} MB to ${s}. Delete ~/.visa-mcp/allium-results/ files you no longer need \u2014 they are never auto-cleaned.`}return d}function ms(){let r=Kr();try{if(!W.existsSync(r))return{file_count:0,size_bytes:0,path:r};let e=W.readdirSync(r),t=0,n=0;for(let s of e)try{let a=W.statSync(dt.join(r,s));a.isFile()&&(t+=a.size,n++)}catch{}return{file_count:n,size_bytes:t,path:r}}catch(e){return l.warn("allium:disk_usage_error",{error:e.message}),{file_count:0,size_bytes:0,path:r}}}async function mt(r){if(process.env.VISA_SUPPRESS_FEED!=="true")try{let e=await M.getSessionToken();if(!e)return;await fetch(`${Pt}/v1/feed`,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${e}`},body:JSON.stringify({prompt:r.prompt,tool:r.tool,media_url:r.mediaUrl,media_type:r.mediaType,cost:r.cost,transaction_id:r.transactionId,auto:!0,...r.userContext&&{user_context:r.userContext}}),signal:AbortSignal.timeout(5e3)}),l.info("feed:submitted",{tool:r.tool,mediaType:r.mediaType})}catch{}}async function ps(r,e){if(!r.url||!r.url.trim())throw new Error("A URL is required for payments. Provide the merchant payment endpoint.");let t=await Y(void 0,r.url,e);l.info("payment:attempt",{tool:"pay",amount:t.amount,merchant:t.merchantName,url:r.url});try{return await j(async()=>{let n=await P(r.url||"pay",t.amount,t.merchantName,ee(t)),s=await k.pay({url:r.url||"",merchantName:r.merchantName||"Unknown",description:r.description||"",method:r.method,body:r.body,attestation:n,idempotencyKey:ut.randomUUID()},e);return s.success?(l.info("payment:success",{tool:"pay",amount:t.amount,merchant:t.merchantName,rail:s.receipt?.rail}),s.receipt&&Zs(s.receipt)):l.warn("payment:declined",{tool:"pay",amount:t.amount,merchant:t.merchantName,message:s.message}),s})}catch(n){throw l.error("payment:failure",{tool:"pay",amount:t.amount,merchant:t.merchantName,error:n.message}),n}}async function fs(r,e){if(!r.prompt||!r.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let t=await Y("generate_image_card",void 0,e);l.info("payment:attempt",{tool:"generate_image_card",amount:t.amount,merchant:t.merchantName});try{return await j(async()=>{let n=await P("generate_image_card",t.amount,t.merchantName,ee(t)),s=await k.shortcut("generate_image_card",{...r,attestation:n},12e4,e);return l.info("payment:success",{tool:"generate_image_card",amount:t.amount,merchant:t.merchantName}),s.urls?.length?(s.urls.forEach(a=>B(a)),mt({prompt:r.prompt,tool:"generate_image_card",mediaUrl:s.urls[0],mediaType:"image",cost:s.amount??t.amount,transactionId:s.transactionId,userContext:e})):l.warn("generation:no-urls",{tool:"generate_image_card",resultKeys:Object.keys(s||{})}),s})}catch(n){throw l.error("payment:failure",{tool:"generate_image_card",amount:t.amount,merchant:t.merchantName,error:n.message}),n}}async function hs(r,e){if(!r.prompt||!r.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let t=await Y("generate_image_fast_card",void 0,e);l.info("payment:attempt",{tool:"generate_image_fast_card",amount:t.amount,merchant:t.merchantName});try{return await j(async()=>{let n=await P("generate_image_fast_card",t.amount,t.merchantName,ee(t)),s=await k.shortcut("generate_image_fast_card",{...r,attestation:n},6e4,e);return l.info("payment:success",{tool:"generate_image_fast_card",amount:t.amount,merchant:t.merchantName}),s.urls?.length?(s.urls.forEach(a=>B(a)),mt({prompt:r.prompt,tool:"generate_image_fast_card",mediaUrl:s.urls[0],mediaType:"image",cost:s.amount??t.amount,transactionId:s.transactionId,userContext:e})):l.warn("generation:no-urls",{tool:"generate_image_fast_card",resultKeys:Object.keys(s||{})}),s})}catch(n){throw l.error("payment:failure",{tool:"generate_image_fast_card",amount:t.amount,merchant:t.merchantName,error:n.message}),n}}async function gs(r,e){if(!r.prompt||!r.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let t=await Y("generate_video_tempo_card",void 0,e);l.info("payment:attempt",{tool:"generate_video_tempo_card",amount:t.amount,merchant:t.merchantName});try{return await j(async()=>{let n=await P("generate_video_tempo_card",t.amount,t.merchantName,ee(t)),s=await k.shortcut("generate_video_tempo_card",{...r,attestation:n},12e4,e);return l.info("payment:success",{tool:"generate_video_tempo_card",amount:t.amount,merchant:t.merchantName}),s.urls?.length?(s.urls.forEach(a=>B(a)),mt({prompt:r.prompt,tool:"generate_video_tempo_card",mediaUrl:s.urls[0],mediaType:"image",cost:s.amount??t.amount,transactionId:s.transactionId,userContext:e})):l.warn("generation:no-urls",{tool:"generate_video_tempo_card",resultKeys:Object.keys(s||{})}),s})}catch(n){throw l.error("payment:failure",{tool:"generate_video_tempo_card",amount:t.amount,merchant:t.merchantName,error:n.message}),n}}async function ys(r,e){if(!r.prompt||!r.prompt.trim())throw new Error("A prompt is required. Provide a description of what you want to generate.");let t=await Y("generate_music_tempo_card",void 0,e);l.info("payment:attempt",{tool:"generate_music_tempo_card",amount:t.amount,merchant:t.merchantName});try{return await j(async()=>{let n=await P("generate_music_tempo_card",t.amount,t.merchantName,ee(t)),s=await k.shortcut("generate_music_tempo_card",{...r,attestation:n},36e4,e);return l.info("payment:success",{tool:"generate_music_tempo_card",amount:t.amount,merchant:t.merchantName}),s.urls?.length&&s.status!=="processing"?(s.urls.forEach(a=>B(a)),mt({prompt:r.prompt,tool:"generate_music_tempo_card",mediaUrl:s.urls[0],mediaType:"audio",cost:s.amount??t.amount,transactionId:s.transactionId,userContext:e})):s.urls?.length&&s.status==="processing"?(s._preliminary_urls=s.urls,delete s.urls,l.info("generation:processing",{tool:"generate_music_tempo_card",note:"URLs withheld until status is completed"})):l.warn("generation:no-urls",{tool:"generate_music_tempo_card",resultKeys:Object.keys(s||{})}),s})}catch(n){throw l.error("payment:failure",{tool:"generate_music_tempo_card",amount:t.amount,merchant:t.merchantName,error:n.message}),n}}async function _s(r,e){let t=await Y("check_music_status_tempo_card",void 0,e);l.info("payment:attempt",{tool:"check_music_status_tempo_card",amount:t.amount,merchant:t.merchantName});try{return await j(async()=>{let n=await P("check_music_status_tempo_card",t.amount,t.merchantName,ee(t)),s=await k.shortcut("check_music_status_tempo_card",{...r,attestation:n},void 0,e);return l.info("payment:success",{tool:"check_music_status_tempo_card",amount:t.amount,merchant:t.merchantName}),s.urls?.length&&s.urls.forEach(a=>B(a)),s})}catch(n){throw l.error("payment:failure",{tool:"check_music_status_tempo_card",amount:t.amount,merchant:t.merchantName,error:n.message}),n}}async function vs(r,e){if(!r.chain||!r.chain.trim())throw new Error('A chain is required (e.g., "ethereum", "solana").');if(!r.token_address||!r.token_address.trim())throw new Error("A token address is required. Provide the contract address for the token.");let t=await Y("query_onchain_prices_card",void 0,e);l.info("payment:attempt",{tool:"query_onchain_prices_card",amount:t.amount,merchant:t.merchantName});try{return await j(async()=>{let n=await P("query_onchain_prices_card",t.amount,t.merchantName,ee(t)),s=await k.shortcut("query_onchain_prices_card",{...r,attestation:n},void 0,e);if(l.info("payment:success",{tool:"query_onchain_prices_card",amount:t.amount,merchant:t.merchantName}),Array.isArray(s?.data))s.data=s.data.map(a=>{if("mint"in a&&!("address"in a)){let{mint:i,...o}=a;return{address:i,...o}}return a});else if(s&&"mint"in s&&!("address"in s)){let{mint:a,...i}=s;return{address:a,...i}}return s})}catch(n){throw l.error("payment:failure",{tool:"query_onchain_prices_card",amount:t.amount,merchant:t.merchantName,error:n.message}),n}}async function bs(r,e){if(!r.prompt||!r.prompt.trim())throw new Error("A prompt is required. Provide a natural language question about blockchain data.");let t=await Y("allium_explorer_card",void 0,e);l.info("payment:attempt",{tool:"allium_explorer_card",amount:t.amount,merchant:t.merchantName});try{return await j(async()=>{let n=await P("allium_explorer_card",t.amount,t.merchantName,ee(t)),s=await k.shortcut("allium_explorer_card",{...r,attestation:n},12e4,e);return l.info("payment:success",{tool:"allium_explorer_card",amount:t.amount,merchant:t.merchantName}),s})}catch(n){throw l.error("payment:failure",{tool:"allium_explorer_card",amount:t.amount,merchant:t.merchantName,error:n.message}),n}}async function ws(r,e){if(!r.session_id||!r.session_id.trim())throw new Error("A session_id is required. Use the session_id returned from allium_explorer_card.");let t=await Y("allium_explorer_results_card",void 0,e);l.info("payment:attempt",{tool:"allium_explorer_results_card",amount:t.amount,pricingMode:t.pricingMode,estimatedAmount:t.estimatedAmount,merchant:t.merchantName});try{return await j(async()=>{let n=await P("allium_explorer_results_card",t.amount,t.merchantName,ee(t)),s=await k.shortcut("allium_explorer_results_card",{...r,attestation:n},6e4,e);l.info("payment:success",{tool:"allium_explorer_results_card",amount:t.amount,actualCost:s?.actualCost,merchant:t.merchantName});let a=typeof s?.data?.results=="string"?s.data.results:void 0;if(a&&Buffer.byteLength(a)>os){let i=ds(r.session_id,a),{results:o,...c}=s.data;return{...s,data:{...c,...i}}}return s})}catch(n){throw l.error("payment:failure",{tool:"allium_explorer_results_card",amount:t.amount,merchant:t.merchantName,error:n.message}),n}}var ct="https://pxlwall.com";async function xs(r){if([r.shape,r.text,r.pixels].filter(Boolean).length>1)throw new Error("Provide only one of: shape, text, or pixels. Cannot combine modes.");let t,n,s=r.position||"cheapest";if(typeof s=="string"&&s.startsWith("{"))try{s=JSON.parse(s)}catch{}if(r.shape)t=`${ct}/api/agent/draw-shape`,n={shape:r.shape,color:r.color||"#ffffff",owner:r.owner,position:s},r.shape==="circle"?n.radius=r.size||10:r.shape==="rectangle"?(n.width=r.width||20,n.height=r.height||10):n.size=r.size||10;else if(r.text)t=`${ct}/api/agent/draw-text`,n={text:r.text,color:r.color||"#ffffff",owner:r.owner,position:s};else if(r.pixels){if(r.pixels.length<100)throw new Error(`Minimum 100 pixels per purchase. You requested ${r.pixels.length}.`);for(let i of r.pixels)if(i.x<0||i.x>499||i.y<0||i.y>499)throw new Error(`Pixel (${i.x},${i.y}) is out of bounds. Grid is 500x500 (coordinates 0-499).`);t=`${ct}/api/create-purchase-spec`,n={pixels:r.pixels,color:r.color||"#ffffff",owner:r.owner},r.colors&&(n.colors=r.colors)}else throw new Error("Provide one of: shape, text, or pixels.");let a=await fetch(t,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(15e3)});if(!a.ok){let i=await a.text().catch(()=>"");throw new Error(`pxlwall spec creation failed (${a.status}): ${i}`)}return a.json()}async function ks(r,e){let t=await xs(r),n=t.pixels?.length??r.pixels?.length??0,s="pxlwall";l.info("payment:attempt",{tool:"pxlwall_card",amount:t.totalUSD,pixelCount:n,merchant:s});try{let a=await P("pxlwall_card",t.totalUSD,s,`pay $${t.totalUSD.toFixed(2)} to ${s} for ${n} pixels`),i=await k.shortcut("pxlwall_card",{specId:t.specId,attestation:a},6e4,e);return l.info("payment:success",{tool:"pxlwall_card",merchant:s}),B(ct),i.urls?.length&&i.urls.forEach(o=>B(o)),{...i,specId:t.specId,pixelCount:n,totalUSD:t.totalUSD,canvasUrl:ct}}catch(a){throw l.error("payment:failure",{tool:"pxlwall_card",merchant:s,error:a.message}),a}}var Ss=["generate_music_tempo_card"],Ts=36e4,Is=18e4,Es=15e3,Rs=12e4,As=2e3;async function Os(r,e){let t;if(r.requests?.some(w=>w.tool||w.tool_id)&&r.requests)t=r.requests.map(w=>{let I=w.tool||w.tool_id||r.tool;if(!I)throw new Error("Each request must specify tool or tool_id, or set tool at the top level.");let R=At(I,w.tier||r.tier),{tool:U,tool_id:ie,tier:oe,...ce}=w;return{resolvedTool:R,params:ce}});else if(r.tool){let w=At(r.tool,r.tier);t=(r.requests||(r.count&&r.params?Array.from({length:r.count},()=>({...r.params})):[])).map(R=>({resolvedTool:w,params:R}))}else throw new Error("Batch requires a top-level tool or per-request tool/tool_id.");if(t.length===0)throw new Error("Batch requires at least one item.");let s=[...new Set(t.map(w=>w.resolvedTool))],a=s.length===1,i={};for(let w of s)i[w]=await Y(w,void 0,e);let o=0;for(let w of t)o+=i[w.resolvedTool].amount;let c=[...new Set(Object.values(i).map(w=>w.merchantName))].join(", "),u=a?s[0]:"mixed";l.info("payment:attempt",{tool:"batch",batchTool:u,count:t.length,totalAmount:o,merchant:c,heterogeneous:!a});let d=a?`pay $${o.toFixed(2)} to ${c} (${t.length} items, $${i[s[0]].amount.toFixed(2)} each)`:`pay $${o.toFixed(2)} to ${c} (${t.length} items across ${s.length} tools)`,g=a?t.map(w=>w.params):t.map(w=>({tool_id:w.resolvedTool,...w.params})),C=t.some(w=>Ss.includes(w.resolvedTool)),y=t.some(w=>w.resolvedTool.startsWith("or-")||w.resolvedTool==="run_llm"||w.resolvedTool==="execute_tool"),he=C?Ts:y?Is+t.length*Es:Rs+t.length*As;try{return await j(async()=>{let w=await P(`batch:${u}`,o,c,d),I=await k.batch({tool:a?s[0]:u,requests:g,attestation:w,idempotencyKey:ut.randomUUID()},he,e);return l.info("payment:success",{tool:"batch",batchTool:u,count:t.length,totalAmount:o,merchant:c}),I.results&&I.results.forEach(R=>{R.urls&&R.urls.forEach(U=>B(U))}),I})}catch(w){throw l.error("payment:failure",{tool:"batch",batchTool:u,count:t.length,totalAmount:o,merchant:c,error:w.message}),w}}function Cs(){try{let r=dt.join(lt.homedir(),".claude","settings.json");if(!W.existsSync(r))return{enabled:!1,setup:"visa-cli hud enable"};let e=JSON.parse(W.readFileSync(r,"utf-8")),t=typeof e.statusLine=="object"?e.statusLine.command:"";return Ot(t)?{enabled:!0}:e.statusLine?{enabled:!1,setup:"Another HUD is active. To switch: edit ~/.claude/settings.json \u2192 statusLine"}:{enabled:!1,setup:"visa-cli hud enable"}}catch{return{enabled:!1,setup:"visa-cli hud enable"}}}async function Ps(r){let e=await k.getStatus(r);typeof e?.dailyRemaining=="number"&&(e.dailyRemaining=Math.round(e.dailyRemaining*100)/100);let t=ms();return t.file_count>0&&(e.alliumResultsOnDisk=t),e.hud=Cs(),e}async function Ns(r){let t=(await k.getStatus(r)).cards||[];return t.length===0?{cards:[],message:"No cards enrolled. Use the add_card tool to add a payment card."}:t.some(s=>!Number.isInteger(s?.id)||s.id<=0)?{success:!1,cards:[],message:"Card ids are unavailable right now, so remove_card and set_default_card are temporarily disabled."}:{cards:t}}async function Ls(r){let e=await k.getTransactions(r);return Array.isArray(e?.transactions)&&(e.transactions=e.transactions.filter(t=>!(t.tool_name==null||t.amount===0&&t.status==="failed"))),e}async function $s(r,e){return await k.feedback(r.message,r.transaction_id,e)}async function Ms(r,e){if(!r.confirm)return{success:!1,message:"Please confirm by setting confirm: true to update spending controls."};l.info("spending_controls:update",{maxTransactionAmount:r.maxTransactionAmount,dailyLimit:r.dailyLimit});try{return await j(async()=>{let t=await P("spending-controls",0,"","update spending controls"),n=await k.updateSpendingControls({maxTransactionAmount:r.maxTransactionAmount,dailyLimit:r.dailyLimit,confirm:!0,attestation:t},e);return l.info("spending_controls:success",{maxTransactionAmount:r.maxTransactionAmount,dailyLimit:r.dailyLimit}),n})}catch(t){throw l.error("spending_controls:failure",{error:t.message}),t}}async function js(r){let e=await Fr({api:k,includeDev:!!r.includeDev});return{config:e.entries.map(t=>({key:t.key,value:t.value,source:t.source,hint:t.hint})),statusError:e.statusError}}async function Ds(r){let e=await k.getStatus(r),t=e.attestationRequired!==!1;return{required:t,hasAttestationKey:!!e.hasAttestationKey,touchIdAvailable:ue(),message:t?"Touch ID is REQUIRED for payments.":"Touch ID is NOT required for payments. Payments will proceed without biometric confirmation."}}async function Us(r){l.info("biometric:on");let e=await k.setBiometricPreference({required:!0},r);return e.success?(Zr(),{success:!0,required:!0,message:"Touch ID is now REQUIRED for payments."}):{success:!1,error:e.error||"unknown error"}}async function qs(r,e){if(!r.confirm)return{success:!1,message:"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."};l.info("biometric:off");try{return await j(async()=>{let t=await k.getStatus(e),n;if(t.hasAttestationKey&&(n=await P("biometric-preference",0,"","disable Touch ID requirement"),!n))throw new Error("Touch ID confirmation required to disable \u2014 not available on this device.");let s=await k.setBiometricPreference({required:!1,attestation:n},e);if(!s.success)throw new Error(s.error||"unknown error");return Zr(),{success:!0,required:!1,message:"Touch ID is no longer required for payments."}})}catch(t){throw l.error("biometric:off:failure",{error:t.message}),t}}var Wr=3e4,Vs=3e5;async function Gr(r,e){let t=ut.randomBytes(16).toString("hex"),n=`${r}${r.includes("?")?"&":"?"}state=${t}`;B(n);let s=Date.now()+Vs;for(;Date.now()<s;)try{let a=await fetch(`${Pt}/v1/auth-status`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({state:t,timeout:Wr,...e&&{user_context:e}}),signal:AbortSignal.timeout(Wr+5e3)});if(!a.ok)continue;let i=await a.json();if(i.status==="pending")continue;if(i.status==="expired")return{success:!1,message:"Session expired. Please try again."};if(i.status==="error")return{success:!1,message:i.error||"Authentication failed. Please try again."};if(i.status==="complete"){if(i.sessionToken){await M.saveSessionToken(i.sessionToken);let c=i.user||"",u=i.last4||"****";return l.info("auth:login_complete",{user:c,last4:u}),{success:!0,message:`Signed in as ${c}. Card ending in ${u} added.${Br}`}}let o=i.last4||"****";return l.info("auth:card_added",{last4:o}),{success:!0,message:`Card ending in ${o} enrolled.${Br}`}}}catch{}return{success:!1,message:"Login timed out. Please try again."}}async function Hs(r,e){if(!r.confirm)return{success:!1,message:"Please confirm by setting confirm: true to remove this card."};let t=r.cardId;if(!Number.isInteger(t)||t<=0)return{success:!1,message:"cardId must be a positive integer. Call get_cards to list enrolled cards and their ids."};l.info("cards:remove_attempt",{cardId:t});let n=`remove-card:${t}`,s=`remove enrolled card #${t}`;try{return await j(async()=>{let a=await P(n,0,"",s),i=await k.removeCard(t,{attestation:a},e);return l.info("cards:remove_success",{cardId:t,promotedId:i?.promotedId??null}),i})}catch(a){throw l.error("cards:remove_failure",{cardId:t,error:a.message}),a}}async function Fs(r,e){let t=r.cardId;if(!Number.isInteger(t)||t<=0)return{success:!1,message:"cardId must be a positive integer. Call get_cards to list enrolled cards and their ids."};l.info("cards:set_default_attempt",{cardId:t});let n=`set-default-card:${t}`,s=`set card #${t} as default`;try{return await j(async()=>{let a=await P(n,0,"",s),i=await k.setDefaultCard(t,{attestation:a},e);return l.info("cards:set_default_success",{cardId:t}),i})}catch(a){throw l.error("cards:set_default_failure",{cardId:t,error:a.message}),a}}async function Bs(r){return l.info("auth:login_attempt"),Gr(`${Pt}/login`,r)}async function Ws(r){return l.info("auth:add_card_attempt"),await M.getSessionToken()?Gr(`${Pt}/enroll`,r):{success:!1,message:"Not logged in. Sign up at https://visacli.sh or call the login tool first."}}async function zs(r,e){if(!r.confirm)return{success:!1,message:"Please confirm by setting confirm: true to reset"};l.info("reset:attempt");let t=await P("reset",0,"","reset device and remove all credentials");try{await k.logout({attestation:t},e)}catch{}if(await M.clearAll(),ue())try{await Nr()}catch{}return l.info("reset:success"),{success:!0,message:"Device reset. All credentials, cards, and keys have been removed. Use the login tool to re-enroll."}}function Zs(r){let e=["url","resultUrl","imageUrl","audioUrl","trackUrl"];for(let t of e){let n=r[t];n&&typeof n=="string"&&n.startsWith("http")&&B(n)}Array.isArray(r.urls)&&r.urls.forEach(t=>{t&&typeof t=="string"&&t.startsWith("http")&&B(t)})}async function Ks(r){if(!r.query&&!r.category)throw new Error("Provide a query (what you want to do) or category (image, video, audio, 3d, llm) to search the tool catalog.");l.info("catalog:discover",{query:r.query,category:r.category});try{let t=(await k.catalogSearch(r.query,r.category)).tools||[];if(t.length===0)return{content:[{type:"text",text:`No tools found for "${r.query||r.category}". Try a different search term.`}]};let n=t.map((s,a)=>`${a+1}. **${s.name}** (${s.id})
|
|
@@ -14,7 +14,7 @@
|
|
|
14
14
|
${n}
|
|
15
15
|
|
|
16
16
|
Use execute_tool with the tool id and required params to run any of these.`}],_tools:t}}catch(e){throw l.error("catalog:discover:error",{error:e.message}),new Error(`Failed to search tool catalog: ${e.message}`)}}async function Gs(r,e){let{tool_id:t,params:n,...s}=r,a=n||s;if(!t)throw new Error("tool_id is required. Use discover_tools first to find available tools.");l.info("catalog:execute",{tool:t});let i=await Y(t,void 0,e);l.info("payment:attempt",{tool:t,amount:i.amount,merchant:i.merchantName});try{return await j(async()=>{let o=await P(t,i.amount,i.merchantName,ee(i)),c=await k.shortcut(t,{...a,attestation:o},12e4,e);if(l.info("payment:success",{tool:t,amount:i.amount,merchant:i.merchantName}),c.urls?.length){c.urls.forEach(d=>B(d));let u=c.mediaType||(c.urls[0]?.match(/\.(mp4|webm|mov)/)?"video":"image");mt({prompt:a.prompt||`${t} execution`,tool:t,mediaUrl:c.urls[0],mediaType:u,cost:c.amount??i.amount,transactionId:c.transactionId,userContext:e})}return c})}catch(o){throw l.error("payment:failure",{tool:t,amount:i.amount,merchant:i.merchantName,error:o.message}),o}}var O=class{static async getStatus(e){return Ps(e)}static async pay(e,t){return ps(e,t)}static async getCards(e){return Ns(e)}static async transactionHistory(e){return Ls(e)}static async feedback(e,t){return $s(e,t)}static async updateSpendingControls(e,t){return Ms(e,t)}static async configList(e){return js(e||{})}static async biometricStatus(e){return Ds(e)}static async biometricOn(e){return Us(e)}static async biometricOff(e,t){return qs(e,t)}static async reset(e,t){return zs(e,t)}static async login(e){return Bs(e)}static async addCard(e){return Ws(e)}static async removeCard(e,t){return Hs(e,t)}static async setDefaultCard(e,t){return Fs(e,t)}static async batch(e,t){return Os(e,t)}static async discoverTools(e){return Ks(e)}static async executeTool(e,t){return Gs(e,t)}static async shortcut(e,t,n){switch(e){case"generate_image_card":return fs(t,n);case"generate_image_fast_card":return hs(t,n);case"generate_video_tempo_card":return gs(t,n);case"generate_music_tempo_card":return ys(t,n);case"check_music_status_tempo_card":return _s(t,n);case"query_onchain_prices_card":return vs(t,n);case"allium_explorer_card":return bs(t,n);case"allium_explorer_results_card":return ws(t,n);case"pxlwall_card":return ks(t,n);default:{l.info("payment:attempt",{tool:e});try{let s=await P(e,0,""),a=await k.shortcut(e,{...t,attestation:s},void 0,n);return l.info("payment:success",{tool:e}),a.urls?.length&&a.urls.forEach(i=>B(i)),a}catch(s){throw l.error("payment:failure",{tool:e,error:s.message}),s}}}}static async submitFeedback(e,t,n){l.info("feedback:submit",{length:e.length});try{let s=await k.submitFeedback(e,t,n);return l.info("feedback:submitted",{message:"Feedback received"}),s}catch(s){let a=s instanceof Error?s.message:"Unknown error";throw l.error("feedback:error",{error:a}),s}}static async getFeedback(e,t){l.info("feedback:list",{limit:e||20});try{let n=await k.getFeedback(e,t);return l.info("feedback:listed",{count:n?.feedback?.length||0}),n}catch(n){let s=n instanceof Error?n.message:"Unknown error";throw l.error("feedback:error",{error:s}),n}}};var ar=new Set(["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","check_music_status_tempo_card","query_onchain_prices_card","allium_explorer_card","allium_explorer_results_card","pxlwall_card"]),ir=new Set(["discover_tools","execute_tool"]),Ys=new Set(Te);function Yr(r){return ar.has(r)&&!st()?"VISA_SPECIFIC_TOOLS":ir.has(r)&&!it()?"VISA_DISCOVER_TOOLS":Ys.has(r)&&!at()?"VISA_META_TOOLS":null}var Nt=A(require("fs")),Jr=A(require("path")),Xr=A(require("os"));var or=Jr.join(Xr.homedir(),".visa-mcp"),_e=class{static ensureConfigDir(){Nt.existsSync(or)||Nt.mkdirSync(or,{recursive:!0,mode:448})}static getConfigDir(){return or}static TOOL_STATES={login:!0,get_status:!0,get_cards:!0,add_card:!0,pay:!0,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:!0,query_onchain_prices_card:!0,generate_music_tempo_card:!0,check_music_status_tempo_card:!0,generate_image_fast_card:!0,pxlwall_card:!1,generate_video_tempo_card:!0};static loadToolStates(){return{...this.TOOL_STATES}}static getDisabledTools(){let e=new Set;for(let[t,n]of Object.entries(this.TOOL_STATES))n||e.add(t);return e}static isToolDisabled(e){return this.TOOL_STATES[e]===!1}};var cr=["pay","generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","query_onchain_prices_card","allium_explorer_card","allium_explorer_results_card"],Js={generate_image_card:"image generation",generate_image_fast_card:"fast image generation",generate_music_tempo_card:"music generation",generate_video_tempo_card:"video generation",query_onchain_prices_card:"onchain price queries",allium_explorer_card:"blockchain data exploration",allium_explorer_results_card:"blockchain data results",pay:"payments"};function Xs(r){return Js[r]||r}var Ie=null;async function Lt(r){if(Ie!==null)return Ie;try{let{transactions:e}=await r.getTransactions();Ie={};for(let t of e)t.status==="completed"&&(Ie[t.tool_name]=(Ie[t.tool_name]||0)+1)}catch{l.warn("feedback-prompting:cache-error",{message:"Failed to fetch transaction history for feedback prompting"}),Ie={}}return Ie}function Qr(r,e,t){return cr.includes(r)?e===0?{_feedback_prompt:{message:`This was your first time using ${Xs(r)} \u2014 if you have any thoughts on the experience, I'd be happy to pass them along to the Visa CLI team.`,transaction_id:t}}:e%5===0?{_feedback_hint:{message:"Feedback? Just say how that went.",transaction_id:t}}:{}:{}}var pt=A(require("fs")),en=A(require("path"));var Qs=5,ea={shownCodes:[]},Ee=null;function tn(){return process.env.VISA_CLI_REFERRAL_NUDGE_FILE||en.join(_e.getConfigDir(),"referral-nudges.json")}function ta(){if(Ee)return Ee;try{let r=pt.readFileSync(tn(),"utf8"),e=JSON.parse(r);return Ee={shownCodes:Array.isArray(e.shownCodes)?e.shownCodes.filter(t=>typeof t=="string"):[]},Ee}catch{return Ee={...ea},Ee}}function ra(r){Ee=r;try{_e.ensureConfigDir(),pt.writeFileSync(tn(),JSON.stringify(r,null,2)+`
|
|
17
|
-
`,{mode:384})}catch{}}function na(r){return r.trim().toLowerCase()}function rn(r,e){if(e<Qs)return{};if(!r.referralCode||!r.referralLink)return{};let t=na(r.referralCode);if(!t)return{};let n=ta();return n.shownCodes.includes(t)?{}:(ra({shownCodes:[...n.shownCodes,t]}),{_referral_prompt:{message:`Thanks for giving Visa CLI a try. Know anyone who might want to try it too? Here's your referral code: ${r.referralCode}`,referral_code:r.referralCode,referral_link:r.referralLink}})}var T={};yr(T,{BRAND:()=>Aa,DIRTY:()=>Re,EMPTY_PATH:()=>oa,INVALID:()=>_,NEVER:()=>pi,OK:()=>$,ParseStatus:()=>N,Schema:()=>x,ZodAny:()=>we,ZodArray:()=>fe,ZodBigInt:()=>Oe,ZodBoolean:()=>Ce,ZodBranded:()=>ht,ZodCatch:()=>He,ZodDate:()=>Pe,ZodDefault:()=>Ve,ZodDiscriminatedUnion:()=>jt,ZodEffects:()=>G,ZodEnum:()=>Ue,ZodError:()=>V,ZodFirstPartyTypeKind:()=>v,ZodFunction:()=>Ut,ZodIntersection:()=>Me,ZodIssueCode:()=>m,ZodLazy:()=>je,ZodLiteral:()=>De,ZodMap:()=>Qe,ZodNaN:()=>tt,ZodNativeEnum:()=>qe,ZodNever:()=>J,ZodNull:()=>Le,ZodNullable:()=>ne,ZodNumber:()=>Ae,ZodObject:()=>H,ZodOptional:()=>Z,ZodParsedType:()=>f,ZodPipeline:()=>gt,ZodPromise:()=>xe,ZodReadonly:()=>Fe,ZodRecord:()=>Dt,ZodSchema:()=>x,ZodSet:()=>et,ZodString:()=>be,ZodSymbol:()=>Je,ZodTransformer:()=>G,ZodTuple:()=>re,ZodType:()=>x,ZodUndefined:()=>Ne,ZodUnion:()=>$e,ZodUnknown:()=>pe,ZodVoid:()=>Xe,addIssueToContext:()=>p,any:()=>Da,array:()=>Ha,bigint:()=>Na,boolean:()=>fn,coerce:()=>mi,custom:()=>dn,date:()=>La,datetimeRegex:()=>un,defaultErrorMap:()=>de,discriminatedUnion:()=>za,effect:()=>si,enum:()=>ti,function:()=>Xa,getErrorMap:()=>Ke,getParsedType:()=>te,instanceof:()=>Ca,intersection:()=>Za,isAborted:()=>$t,isAsync:()=>Ge,isDirty:()=>Mt,isValid:()=>ve,late:()=>Oa,lazy:()=>Qa,literal:()=>ei,makeIssue:()=>ft,map:()=>Ya,nan:()=>Pa,nativeEnum:()=>ri,never:()=>qa,null:()=>ja,nullable:()=>ii,number:()=>pn,object:()=>Fa,objectUtil:()=>ur,oboolean:()=>di,onumber:()=>li,optional:()=>ai,ostring:()=>ui,pipeline:()=>ci,preprocess:()=>oi,promise:()=>ni,quotelessJson:()=>sa,record:()=>Ga,set:()=>Ja,setErrorMap:()=>ia,strictObject:()=>Ba,string:()=>mn,symbol:()=>$a,transformer:()=>si,tuple:()=>Ka,undefined:()=>Ma,union:()=>Wa,unknown:()=>Ua,util:()=>S,void:()=>Va});var S;(function(r){r.assertEqual=s=>{};function e(s){}r.assertIs=e;function t(s){throw new Error}r.assertNever=t,r.arrayToEnum=s=>{let a={};for(let i of s)a[i]=i;return a},r.getValidEnumValues=s=>{let a=r.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),i={};for(let o of a)i[o]=s[o];return r.objectValues(i)},r.objectValues=s=>r.objectKeys(s).map(function(a){return s[a]}),r.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let a=[];for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&a.push(i);return a},r.find=(s,a)=>{for(let i of s)if(a(i))return i},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,a=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}r.joinValues=n,r.jsonStringifyReplacer=(s,a)=>typeof a=="bigint"?a.toString():a})(S||(S={}));var ur;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(ur||(ur={}));var f=S.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),te=r=>{switch(typeof r){case"undefined":return f.undefined;case"string":return f.string;case"number":return Number.isNaN(r)?f.nan:f.number;case"boolean":return f.boolean;case"function":return f.function;case"bigint":return f.bigint;case"symbol":return f.symbol;case"object":return Array.isArray(r)?f.array:r===null?f.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?f.promise:typeof Map<"u"&&r instanceof Map?f.map:typeof Set<"u"&&r instanceof Set?f.set:typeof Date<"u"&&r instanceof Date?f.date:f.object;default:return f.unknown}};var m=S.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"]),sa=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),V=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(a){return a.message},n={_errors:[]},s=a=>{for(let i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let o=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(t(i))):o[u]=o[u]||{_errors:[]},o=o[u],c++}}};return s(this),n}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,S.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},n=[];for(let s of this.issues)if(s.path.length>0){let a=s.path[0];t[a]=t[a]||[],t[a].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};V.create=r=>new V(r);var aa=(r,e)=>{let t;switch(r.code){case m.invalid_type:r.received===f.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case m.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,S.jsonStringifyReplacer)}`;break;case m.unrecognized_keys:t=`Unrecognized key(s) in object: ${S.joinValues(r.keys,", ")}`;break;case m.invalid_union:t="Invalid input";break;case m.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${S.joinValues(r.options)}`;break;case m.invalid_enum_value:t=`Invalid enum value. Expected ${S.joinValues(r.options)}, received '${r.received}'`;break;case m.invalid_arguments:t="Invalid function arguments";break;case m.invalid_return_type:t="Invalid function return type";break;case m.invalid_date:t="Invalid date";break;case m.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:S.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case m.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case m.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case m.custom:t="Invalid input";break;case m.invalid_intersection_types:t="Intersection results could not be merged";break;case m.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case m.not_finite:t="Number must be finite";break;default:t=e.defaultError,S.assertNever(r)}return{message:t}},de=aa;var nn=de;function ia(r){nn=r}function Ke(){return nn}var ft=r=>{let{data:e,path:t,errorMaps:n,issueData:s}=r,a=[...t,...s.path||[]],i={...s,path:a};if(s.message!==void 0)return{...s,path:a,message:s.message};let o="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)o=u(i,{data:e,defaultError:o}).message;return{...s,path:a,message:o}},oa=[];function p(r,e){let t=Ke(),n=ft({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===de?void 0:de].filter(s=>!!s)});r.common.issues.push(n)}var N=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let n=[];for(let s of t){if(s.status==="aborted")return _;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let s of t){let a=await s.key,i=await s.value;n.push({key:a,value:i})}return r.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let s of t){let{key:a,value:i}=s;if(a.status==="aborted"||i.status==="aborted")return _;a.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(n[a.value]=i.value)}return{status:e.value,value:n}}},_=Object.freeze({status:"aborted"}),Re=r=>({status:"dirty",value:r}),$=r=>({status:"valid",value:r}),$t=r=>r.status==="aborted",Mt=r=>r.status==="dirty",ve=r=>r.status==="valid",Ge=r=>typeof Promise<"u"&&r instanceof Promise;var h;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(h||(h={}));var K=class{constructor(e,t,n,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=s}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}},sn=(r,e)=>{if(ve(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new V(r.common.issues);return this._error=t,this._error}}};function b(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:n,description:s}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(i,o)=>{let{message:c}=r;return i.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??n??o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:c??t??o.defaultError}},description:s}}var x=class{get description(){return this._def.description}_getType(e){return te(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:te(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new N,ctx:{common:e.parent.common,data:e.data,parsedType:te(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Ge(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:te(e)},s=this._parseSync({data:e,path:n.path,parent:n});return sn(n,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:te(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return ve(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>ve(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:te(e)},s=this._parse({data:e,path:n.path,parent:n}),a=await(Ge(s)?s:Promise.resolve(s));return sn(n,a)}refine(e,t){let n=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,a)=>{let i=e(s),o=()=>a.addIssue({code:m.custom,...n(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(o(),!1)):i?!0:(o(),!1)})}refinement(e,t){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof t=="function"?t(n,s):t),!1))}_refinement(e){return new G({schema:this,typeName:v.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,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:t=>this["~validate"](t)}}optional(){return Z.create(this,this._def)}nullable(){return ne.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return fe.create(this)}promise(){return xe.create(this,this._def)}or(e){return $e.create([this,e],this._def)}and(e){return Me.create(this,e,this._def)}transform(e){return new G({...b(this._def),schema:this,typeName:v.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Ve({...b(this._def),innerType:this,defaultValue:t,typeName:v.ZodDefault})}brand(){return new ht({typeName:v.ZodBranded,type:this,...b(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new He({...b(this._def),innerType:this,catchValue:t,typeName:v.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return gt.create(this,e)}readonly(){return Fe.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},ca=/^c[^\s-]{8,}$/i,ua=/^[0-9a-z]+$/,la=/^[0-9A-HJKMNP-TV-Z]{26}$/i,da=/^[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,ma=/^[a-z0-9_-]{21}$/i,pa=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,fa=/^[-+]?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)?)??$/,ha=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ga="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",lr,ya=/^(?:(?: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])$/,_a=/^(?:(?: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])$/,va=/^(([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]))$/,ba=/^(([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])$/,wa=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,xa=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,on="((\\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])))",ka=new RegExp(`^${on}$`);function cn(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function Sa(r){return new RegExp(`^${cn(r)}$`)}function un(r){let e=`${on}T${cn(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Ta(r,e){return!!((e==="v4"||!e)&&ya.test(r)||(e==="v6"||!e)&&va.test(r))}function Ia(r,e){if(!pa.test(r))return!1;try{let[t]=r.split(".");if(!t)return!1;let n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function Ea(r,e){return!!((e==="v4"||!e)&&_a.test(r)||(e==="v6"||!e)&&ba.test(r))}var be=class r extends x{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==f.string){let a=this._getOrReturnCtx(e);return p(a,{code:m.invalid_type,expected:f.string,received:a.parsedType}),_}let n=new N,s;for(let a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(s=this._getOrReturnCtx(e,s),p(s,{code:m.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="max")e.data.length>a.value&&(s=this._getOrReturnCtx(e,s),p(s,{code:m.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="length"){let i=e.data.length>a.value,o=e.data.length<a.value;(i||o)&&(s=this._getOrReturnCtx(e,s),i?p(s,{code:m.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):o&&p(s,{code:m.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),n.dirty())}else if(a.kind==="email")ha.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"email",code:m.invalid_string,message:a.message}),n.dirty());else if(a.kind==="emoji")lr||(lr=new RegExp(ga,"u")),lr.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"emoji",code:m.invalid_string,message:a.message}),n.dirty());else if(a.kind==="uuid")da.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"uuid",code:m.invalid_string,message:a.message}),n.dirty());else if(a.kind==="nanoid")ma.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"nanoid",code:m.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid")ca.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"cuid",code:m.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid2")ua.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"cuid2",code:m.invalid_string,message:a.message}),n.dirty());else if(a.kind==="ulid")la.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"ulid",code:m.invalid_string,message:a.message}),n.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),p(s,{validation:"url",code:m.invalid_string,message:a.message}),n.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"regex",code:m.invalid_string,message:a.message}),n.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(s=this._getOrReturnCtx(e,s),p(s,{code:m.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),n.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(s=this._getOrReturnCtx(e,s),p(s,{code:m.invalid_string,validation:{startsWith:a.value},message:a.message}),n.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(s=this._getOrReturnCtx(e,s),p(s,{code:m.invalid_string,validation:{endsWith:a.value},message:a.message}),n.dirty()):a.kind==="datetime"?un(a).test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:m.invalid_string,validation:"datetime",message:a.message}),n.dirty()):a.kind==="date"?ka.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:m.invalid_string,validation:"date",message:a.message}),n.dirty()):a.kind==="time"?Sa(a).test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:m.invalid_string,validation:"time",message:a.message}),n.dirty()):a.kind==="duration"?fa.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"duration",code:m.invalid_string,message:a.message}),n.dirty()):a.kind==="ip"?Ta(e.data,a.version)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"ip",code:m.invalid_string,message:a.message}),n.dirty()):a.kind==="jwt"?Ia(e.data,a.alg)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"jwt",code:m.invalid_string,message:a.message}),n.dirty()):a.kind==="cidr"?Ea(e.data,a.version)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"cidr",code:m.invalid_string,message:a.message}),n.dirty()):a.kind==="base64"?wa.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"base64",code:m.invalid_string,message:a.message}),n.dirty()):a.kind==="base64url"?xa.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"base64url",code:m.invalid_string,message:a.message}),n.dirty()):S.assertNever(a);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(s=>e.test(s),{validation:t,code:m.invalid_string,...h.errToObj(n)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...h.errToObj(e)})}url(e){return this._addCheck({kind:"url",...h.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...h.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...h.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...h.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...h.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...h.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...h.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...h.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...h.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...h.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...h.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...h.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...h.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...h.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...h.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...h.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...h.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...h.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...h.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...h.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...h.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...h.errToObj(t)})}nonempty(e){return this.min(1,h.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};be.create=r=>new be({checks:[],typeName:v.ZodString,coerce:r?.coerce??!1,...b(r)});function Ra(r,e){let t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=t>n?t:n,a=Number.parseInt(r.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return a%i/10**s}var Ae=class r extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==f.number){let a=this._getOrReturnCtx(e);return p(a,{code:m.invalid_type,expected:f.number,received:a.parsedType}),_}let n,s=new N;for(let a of this._def.checks)a.kind==="int"?S.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:m.invalid_type,expected:"integer",received:"float",message:a.message}),s.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),p(n,{code:m.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),p(n,{code:m.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="multipleOf"?Ra(e.data,a.value)!==0&&(n=this._getOrReturnCtx(e,n),p(n,{code:m.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:m.not_finite,message:a.message}),s.dirty()):S.assertNever(a);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,h.toString(t))}gt(e,t){return this.setLimit("min",e,!1,h.toString(t))}lte(e,t){return this.setLimit("max",e,!0,h.toString(t))}lt(e,t){return this.setLimit("max",e,!1,h.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:h.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:h.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:h.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:h.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:h.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:h.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&S.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}};Ae.create=r=>new Ae({checks:[],typeName:v.ZodNumber,coerce:r?.coerce||!1,...b(r)});var Oe=class r extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==f.bigint)return this._getInvalidInput(e);let n,s=new N;for(let a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),p(n,{code:m.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),p(n,{code:m.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),p(n,{code:m.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):S.assertNever(a);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return p(t,{code:m.invalid_type,expected:f.bigint,received:t.parsedType}),_}gte(e,t){return this.setLimit("min",e,!0,h.toString(t))}gt(e,t){return this.setLimit("min",e,!1,h.toString(t))}lte(e,t){return this.setLimit("max",e,!0,h.toString(t))}lt(e,t){return this.setLimit("max",e,!1,h.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:h.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:h.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Oe.create=r=>new Oe({checks:[],typeName:v.ZodBigInt,coerce:r?.coerce??!1,...b(r)});var Ce=class extends x{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==f.boolean){let n=this._getOrReturnCtx(e);return p(n,{code:m.invalid_type,expected:f.boolean,received:n.parsedType}),_}return $(e.data)}};Ce.create=r=>new Ce({typeName:v.ZodBoolean,coerce:r?.coerce||!1,...b(r)});var Pe=class r extends x{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==f.date){let a=this._getOrReturnCtx(e);return p(a,{code:m.invalid_type,expected:f.date,received:a.parsedType}),_}if(Number.isNaN(e.data.getTime())){let a=this._getOrReturnCtx(e);return p(a,{code:m.invalid_date}),_}let n=new N,s;for(let a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(s=this._getOrReturnCtx(e,s),p(s,{code:m.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),n.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(s=this._getOrReturnCtx(e,s),p(s,{code:m.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),n.dirty()):S.assertNever(a);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:h.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:h.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};Pe.create=r=>new Pe({checks:[],coerce:r?.coerce||!1,typeName:v.ZodDate,...b(r)});var Je=class extends x{_parse(e){if(this._getType(e)!==f.symbol){let n=this._getOrReturnCtx(e);return p(n,{code:m.invalid_type,expected:f.symbol,received:n.parsedType}),_}return $(e.data)}};Je.create=r=>new Je({typeName:v.ZodSymbol,...b(r)});var Ne=class extends x{_parse(e){if(this._getType(e)!==f.undefined){let n=this._getOrReturnCtx(e);return p(n,{code:m.invalid_type,expected:f.undefined,received:n.parsedType}),_}return $(e.data)}};Ne.create=r=>new Ne({typeName:v.ZodUndefined,...b(r)});var Le=class extends x{_parse(e){if(this._getType(e)!==f.null){let n=this._getOrReturnCtx(e);return p(n,{code:m.invalid_type,expected:f.null,received:n.parsedType}),_}return $(e.data)}};Le.create=r=>new Le({typeName:v.ZodNull,...b(r)});var we=class extends x{constructor(){super(...arguments),this._any=!0}_parse(e){return $(e.data)}};we.create=r=>new we({typeName:v.ZodAny,...b(r)});var pe=class extends x{constructor(){super(...arguments),this._unknown=!0}_parse(e){return $(e.data)}};pe.create=r=>new pe({typeName:v.ZodUnknown,...b(r)});var J=class extends x{_parse(e){let t=this._getOrReturnCtx(e);return p(t,{code:m.invalid_type,expected:f.never,received:t.parsedType}),_}};J.create=r=>new J({typeName:v.ZodNever,...b(r)});var Xe=class extends x{_parse(e){if(this._getType(e)!==f.undefined){let n=this._getOrReturnCtx(e);return p(n,{code:m.invalid_type,expected:f.void,received:n.parsedType}),_}return $(e.data)}};Xe.create=r=>new Xe({typeName:v.ZodVoid,...b(r)});var fe=class r extends x{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==f.array)return p(t,{code:m.invalid_type,expected:f.array,received:t.parsedType}),_;if(s.exactLength!==null){let i=t.data.length>s.exactLength.value,o=t.data.length<s.exactLength.value;(i||o)&&(p(t,{code:i?m.too_big:m.too_small,minimum:o?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(p(t,{code:m.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(p(t,{code:m.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((i,o)=>s.type._parseAsync(new K(t,i,t.path,o)))).then(i=>N.mergeArray(n,i));let a=[...t.data].map((i,o)=>s.type._parseSync(new K(t,i,t.path,o)));return N.mergeArray(n,a)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:h.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:h.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:h.toString(t)}})}nonempty(e){return this.min(1,e)}};fe.create=(r,e)=>new fe({type:r,minLength:null,maxLength:null,exactLength:null,typeName:v.ZodArray,...b(e)});function Ye(r){if(r instanceof H){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=Z.create(Ye(n))}return new H({...r._def,shape:()=>e})}else return r instanceof fe?new fe({...r._def,type:Ye(r.element)}):r instanceof Z?Z.create(Ye(r.unwrap())):r instanceof ne?ne.create(Ye(r.unwrap())):r instanceof re?re.create(r.items.map(e=>Ye(e))):r}var H=class r extends x{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=S.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==f.object){let u=this._getOrReturnCtx(e);return p(u,{code:m.invalid_type,expected:f.object,received:u.parsedType}),_}let{status:n,ctx:s}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof J&&this._def.unknownKeys==="strip"))for(let u in s.data)i.includes(u)||o.push(u);let c=[];for(let u of i){let d=a[u],g=s.data[u];c.push({key:{status:"valid",value:u},value:d._parse(new K(s,g,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof J){let u=this._def.unknownKeys;if(u==="passthrough")for(let d of o)c.push({key:{status:"valid",value:d},value:{status:"valid",value:s.data[d]}});else if(u==="strict")o.length>0&&(p(s,{code:m.unrecognized_keys,keys:o}),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 o){let g=s.data[d];c.push({key:{status:"valid",value:d},value:u._parse(new K(s,g,s.path,d)),alwaysSet:d in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let u=[];for(let d of c){let g=await d.key,C=await d.value;u.push({key:g,value:C,alwaysSet:d.alwaysSet})}return u}).then(u=>N.mergeObjectSync(n,u)):N.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return h.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let s=this._def.errorMap?.(t,n).message??n.defaultError;return t.code==="unrecognized_keys"?{message:h.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:v.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let n of S.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let n of S.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}deepPartial(){return Ye(this)}partial(e){let t={};for(let n of S.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let n of S.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let a=this.shape[n];for(;a instanceof Z;)a=a._def.innerType;t[n]=a}return new r({...this._def,shape:()=>t})}keyof(){return ln(S.objectKeys(this.shape))}};H.create=(r,e)=>new H({shape:()=>r,unknownKeys:"strip",catchall:J.create(),typeName:v.ZodObject,...b(e)});H.strictCreate=(r,e)=>new H({shape:()=>r,unknownKeys:"strict",catchall:J.create(),typeName:v.ZodObject,...b(e)});H.lazycreate=(r,e)=>new H({shape:r,unknownKeys:"strip",catchall:J.create(),typeName:v.ZodObject,...b(e)});var $e=class extends x{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function s(a){for(let o of a)if(o.result.status==="valid")return o.result;for(let o of a)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;let i=a.map(o=>new V(o.ctx.common.issues));return p(t,{code:m.invalid_union,unionErrors:i}),_}if(t.common.async)return Promise.all(n.map(async a=>{let i={...t,common:{...t.common,issues:[]},parent:null};return{result:await a._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(s);{let a,i=[];for(let c of n){let u={...t,common:{...t.common,issues:[]},parent:null},d=c._parseSync({data:t.data,path:t.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!a&&(a={result:d,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(a)return t.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(c=>new V(c));return p(t,{code:m.invalid_union,unionErrors:o}),_}}get options(){return this._def.options}};$e.create=(r,e)=>new $e({options:r,typeName:v.ZodUnion,...b(e)});var me=r=>r instanceof je?me(r.schema):r instanceof G?me(r.innerType()):r instanceof De?[r.value]:r instanceof Ue?r.options:r instanceof qe?S.objectValues(r.enum):r instanceof Ve?me(r._def.innerType):r instanceof Ne?[void 0]:r instanceof Le?[null]:r instanceof Z?[void 0,...me(r.unwrap())]:r instanceof ne?[null,...me(r.unwrap())]:r instanceof ht||r instanceof Fe?me(r.unwrap()):r instanceof He?me(r._def.innerType):[],jt=class r extends x{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.object)return p(t,{code:m.invalid_type,expected:f.object,received:t.parsedType}),_;let n=this.discriminator,s=t.data[n],a=this.optionsMap.get(s);return a?t.common.async?a._parseAsync({data:t.data,path:t.path,parent:t}):a._parseSync({data:t.data,path:t.path,parent:t}):(p(t,{code:m.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),_)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let s=new Map;for(let a of t){let i=me(a.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let o of i){if(s.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);s.set(o,a)}}return new r({typeName:v.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...b(n)})}};function dr(r,e){let t=te(r),n=te(e);if(r===e)return{valid:!0,data:r};if(t===f.object&&n===f.object){let s=S.objectKeys(e),a=S.objectKeys(r).filter(o=>s.indexOf(o)!==-1),i={...r,...e};for(let o of a){let c=dr(r[o],e[o]);if(!c.valid)return{valid:!1};i[o]=c.data}return{valid:!0,data:i}}else if(t===f.array&&n===f.array){if(r.length!==e.length)return{valid:!1};let s=[];for(let a=0;a<r.length;a++){let i=r[a],o=e[a],c=dr(i,o);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return t===f.date&&n===f.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var Me=class extends x{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=(a,i)=>{if($t(a)||$t(i))return _;let o=dr(a.value,i.value);return o.valid?((Mt(a)||Mt(i))&&t.dirty(),{status:t.value,value:o.data}):(p(n,{code:m.invalid_intersection_types}),_)};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(([a,i])=>s(a,i)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Me.create=(r,e,t)=>new Me({left:r,right:e,typeName:v.ZodIntersection,...b(t)});var re=class r extends x{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.array)return p(n,{code:m.invalid_type,expected:f.array,received:n.parsedType}),_;if(n.data.length<this._def.items.length)return p(n,{code:m.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),_;!this._def.rest&&n.data.length>this._def.items.length&&(p(n,{code:m.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let a=[...n.data].map((i,o)=>{let c=this._def.items[o]||this._def.rest;return c?c._parse(new K(n,i,n.path,o)):null}).filter(i=>!!i);return n.common.async?Promise.all(a).then(i=>N.mergeArray(t,i)):N.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};re.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new re({items:r,typeName:v.ZodTuple,rest:null,...b(e)})};var Dt=class r extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.object)return p(n,{code:m.invalid_type,expected:f.object,received:n.parsedType}),_;let s=[],a=this._def.keyType,i=this._def.valueType;for(let o in n.data)s.push({key:a._parse(new K(n,o,n.path,o)),value:i._parse(new K(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?N.mergeObjectAsync(t,s):N.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof x?new r({keyType:e,valueType:t,typeName:v.ZodRecord,...b(n)}):new r({keyType:be.create(),valueType:e,typeName:v.ZodRecord,...b(t)})}},Qe=class extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.map)return p(n,{code:m.invalid_type,expected:f.map,received:n.parsedType}),_;let s=this._def.keyType,a=this._def.valueType,i=[...n.data.entries()].map(([o,c],u)=>({key:s._parse(new K(n,o,n.path,[u,"key"])),value:a._parse(new K(n,c,n.path,[u,"value"]))}));if(n.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,d=await c.value;if(u.status==="aborted"||d.status==="aborted")return _;(u.status==="dirty"||d.status==="dirty")&&t.dirty(),o.set(u.value,d.value)}return{status:t.value,value:o}})}else{let o=new Map;for(let c of i){let u=c.key,d=c.value;if(u.status==="aborted"||d.status==="aborted")return _;(u.status==="dirty"||d.status==="dirty")&&t.dirty(),o.set(u.value,d.value)}return{status:t.value,value:o}}}};Qe.create=(r,e,t)=>new Qe({valueType:e,keyType:r,typeName:v.ZodMap,...b(t)});var et=class r extends x{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.set)return p(n,{code:m.invalid_type,expected:f.set,received:n.parsedType}),_;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(p(n,{code:m.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(p(n,{code:m.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());let a=this._def.valueType;function i(c){let u=new Set;for(let d of c){if(d.status==="aborted")return _;d.status==="dirty"&&t.dirty(),u.add(d.value)}return{status:t.value,value:u}}let o=[...n.data.values()].map((c,u)=>a._parse(new K(n,c,n.path,u)));return n.common.async?Promise.all(o).then(c=>i(c)):i(o)}min(e,t){return new r({...this._def,minSize:{value:e,message:h.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:h.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};et.create=(r,e)=>new et({valueType:r,minSize:null,maxSize:null,typeName:v.ZodSet,...b(e)});var Ut=class r extends x{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.function)return p(t,{code:m.invalid_type,expected:f.function,received:t.parsedType}),_;function n(o,c){return ft({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Ke(),de].filter(u=>!!u),issueData:{code:m.invalid_arguments,argumentsError:c}})}function s(o,c){return ft({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Ke(),de].filter(u=>!!u),issueData:{code:m.invalid_return_type,returnTypeError:c}})}let a={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof xe){let o=this;return $(async function(...c){let u=new V([]),d=await o._def.args.parseAsync(c,a).catch(y=>{throw u.addIssue(n(c,y)),u}),g=await Reflect.apply(i,this,d);return await o._def.returns._def.type.parseAsync(g,a).catch(y=>{throw u.addIssue(s(g,y)),u})})}else{let o=this;return $(function(...c){let u=o._def.args.safeParse(c,a);if(!u.success)throw new V([n(c,u.error)]);let d=Reflect.apply(i,this,u.data),g=o._def.returns.safeParse(d,a);if(!g.success)throw new V([s(d,g.error)]);return g.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:re.create(e).rest(pe.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new r({args:e||re.create([]).rest(pe.create()),returns:t||pe.create(),typeName:v.ZodFunction,...b(n)})}},je=class extends x{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};je.create=(r,e)=>new je({getter:r,typeName:v.ZodLazy,...b(e)});var De=class extends x{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return p(t,{received:t.data,code:m.invalid_literal,expected:this._def.value}),_}return{status:"valid",value:e.data}}get value(){return this._def.value}};De.create=(r,e)=>new De({value:r,typeName:v.ZodLiteral,...b(e)});function ln(r,e){return new Ue({values:r,typeName:v.ZodEnum,...b(e)})}var Ue=class r extends x{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return p(t,{expected:S.joinValues(n),received:t.parsedType,code:m.invalid_type}),_}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return p(t,{received:t.data,code:m.invalid_enum_value,options:n}),_}return $(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};Ue.create=ln;var qe=class extends x{_parse(e){let t=S.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==f.string&&n.parsedType!==f.number){let s=S.objectValues(t);return p(n,{expected:S.joinValues(s),received:n.parsedType,code:m.invalid_type}),_}if(this._cache||(this._cache=new Set(S.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=S.objectValues(t);return p(n,{received:n.data,code:m.invalid_enum_value,options:s}),_}return $(e.data)}get enum(){return this._def.values}};qe.create=(r,e)=>new qe({values:r,typeName:v.ZodNativeEnum,...b(e)});var xe=class extends x{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.promise&&t.common.async===!1)return p(t,{code:m.invalid_type,expected:f.promise,received:t.parsedType}),_;let n=t.parsedType===f.promise?t.data:Promise.resolve(t.data);return $(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};xe.create=(r,e)=>new xe({type:r,typeName:v.ZodPromise,...b(e)});var G=class extends x{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===v.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,a={addIssue:i=>{p(n,i),i.fatal?t.abort():t.dirty()},get path(){return n.path}};if(a.addIssue=a.addIssue.bind(a),s.type==="preprocess"){let i=s.transform(n.data,a);if(n.common.async)return Promise.resolve(i).then(async o=>{if(t.value==="aborted")return _;let c=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return c.status==="aborted"?_:c.status==="dirty"?Re(c.value):t.value==="dirty"?Re(c.value):c});{if(t.value==="aborted")return _;let o=this._def.schema._parseSync({data:i,path:n.path,parent:n});return o.status==="aborted"?_:o.status==="dirty"?Re(o.value):t.value==="dirty"?Re(o.value):o}}if(s.type==="refinement"){let i=o=>{let c=s.refinement(o,a);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 o};if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?_:(o.status==="dirty"&&t.dirty(),i(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?_:(o.status==="dirty"&&t.dirty(),i(o.value).then(()=>({status:t.value,value:o.value}))))}if(s.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!ve(i))return _;let o=s.transform(i.value,a);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>ve(i)?Promise.resolve(s.transform(i.value,a)).then(o=>({status:t.value,value:o})):_);S.assertNever(s)}};G.create=(r,e,t)=>new G({schema:r,typeName:v.ZodEffects,effect:e,...b(t)});G.createWithPreprocess=(r,e,t)=>new G({schema:e,effect:{type:"preprocess",transform:r},typeName:v.ZodEffects,...b(t)});var Z=class extends x{_parse(e){return this._getType(e)===f.undefined?$(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Z.create=(r,e)=>new Z({innerType:r,typeName:v.ZodOptional,...b(e)});var ne=class extends x{_parse(e){return this._getType(e)===f.null?$(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ne.create=(r,e)=>new ne({innerType:r,typeName:v.ZodNullable,...b(e)});var Ve=class extends x{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===f.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Ve.create=(r,e)=>new Ve({innerType:r,typeName:v.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...b(e)});var He=class extends x{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Ge(s)?s.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new V(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new V(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};He.create=(r,e)=>new He({innerType:r,typeName:v.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...b(e)});var tt=class extends x{_parse(e){if(this._getType(e)!==f.nan){let n=this._getOrReturnCtx(e);return p(n,{code:m.invalid_type,expected:f.nan,received:n.parsedType}),_}return{status:"valid",value:e.data}}};tt.create=r=>new tt({typeName:v.ZodNaN,...b(r)});var Aa=Symbol("zod_brand"),ht=class extends x{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},gt=class r extends x{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let a=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?_:a.status==="dirty"?(t.dirty(),Re(a.value)):this._def.out._parseAsync({data:a.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?_:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,t){return new r({in:e,out:t,typeName:v.ZodPipeline})}},Fe=class extends x{_parse(e){let t=this._def.innerType._parse(e),n=s=>(ve(s)&&(s.value=Object.freeze(s.value)),s);return Ge(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}};Fe.create=(r,e)=>new Fe({innerType:r,typeName:v.ZodReadonly,...b(e)});function an(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function dn(r,e={},t){return r?we.create().superRefine((n,s)=>{let a=r(n);if(a instanceof Promise)return a.then(i=>{if(!i){let o=an(e,n),c=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:c})}});if(!a){let i=an(e,n),o=i.fatal??t??!0;s.addIssue({code:"custom",...i,fatal:o})}}):we.create()}var Oa={object:H.lazycreate},v;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(v||(v={}));var Ca=(r,e={message:`Input not instance of ${r.name}`})=>dn(t=>t instanceof r,e),mn=be.create,pn=Ae.create,Pa=tt.create,Na=Oe.create,fn=Ce.create,La=Pe.create,$a=Je.create,Ma=Ne.create,ja=Le.create,Da=we.create,Ua=pe.create,qa=J.create,Va=Xe.create,Ha=fe.create,Fa=H.create,Ba=H.strictCreate,Wa=$e.create,za=jt.create,Za=Me.create,Ka=re.create,Ga=Dt.create,Ya=Qe.create,Ja=et.create,Xa=Ut.create,Qa=je.create,ei=De.create,ti=Ue.create,ri=qe.create,ni=xe.create,si=G.create,ai=Z.create,ii=ne.create,oi=G.createWithPreprocess,ci=gt.create,ui=()=>mn().optional(),li=()=>pn().optional(),di=()=>fn().optional(),mi={string:(r=>be.create({...r,coerce:!0})),number:(r=>Ae.create({...r,coerce:!0})),boolean:(r=>Ce.create({...r,coerce:!0})),bigint:(r=>Oe.create({...r,coerce:!0})),date:(r=>Pe.create({...r,coerce:!0}))};var pi=_;var hn="1.7.0-rc.1",gn=T.object({name:T.string().max(100).nullable(),location:T.string().max(100).nullable(),member_since:T.string()}),yn=T.object({total_transactions:T.number(),total_spent:T.number(),tools_used:T.record(T.string(),T.number()),last_active:T.string().nullable(),themes:T.array(T.string().max(100)).max(20),recent_prompts:T.array(T.string().max(500)).max(50).optional().default([])}),_n=T.object({daily_remaining:T.number(),daily_limit:T.number()}),fi=T.object({message:T.string().max(500),tool:T.string(),reason:T.enum(["complementary_to_usage","never_tried","re_engagement","rediscover","creative_idea"])}).nullable(),hi=T.object({proactive:fi,reactive:T.record(T.string(),T.array(T.string().max(500)).nullable())}),gi=T.object({user:gn,usage:yn,budget:_n,suggestions:hi}),yi=T.object({user:gn,usage:yn,budget:_n});function _i(r){let e=gi.safeParse(r);if(e.success)return{full:e.data,partial:null};let t=yi.safeParse(r);return t.success?{full:null,partial:t.data}:{full:null,partial:null}}function Be(r){let e=r;for(let t=0;t<5;t++){let n=e.replace(/<[^>]*>/g,"");if(n===e)break;e=n}return e.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g,"").trim()}var vi=`You are a creative assistant with Visa CLI \u2014 a toolkit for AI images, music, videos, crypto prices, and payments. Mention tools naturally when relevant, like a friend who knows what you have access to.
|
|
17
|
+
`,{mode:384})}catch{}}function na(r){return r.trim().toLowerCase()}function rn(r,e){if(e<Qs)return{};if(!r.referralCode||!r.referralLink)return{};let t=na(r.referralCode);if(!t)return{};let n=ta();return n.shownCodes.includes(t)?{}:(ra({shownCodes:[...n.shownCodes,t]}),{_referral_prompt:{message:`Thanks for giving Visa CLI a try. Know anyone who might want to try it too? Here's your referral code: ${r.referralCode}`,referral_code:r.referralCode,referral_link:r.referralLink}})}var T={};yr(T,{BRAND:()=>Aa,DIRTY:()=>Re,EMPTY_PATH:()=>oa,INVALID:()=>_,NEVER:()=>pi,OK:()=>$,ParseStatus:()=>N,Schema:()=>x,ZodAny:()=>we,ZodArray:()=>fe,ZodBigInt:()=>Oe,ZodBoolean:()=>Ce,ZodBranded:()=>ht,ZodCatch:()=>He,ZodDate:()=>Pe,ZodDefault:()=>Ve,ZodDiscriminatedUnion:()=>jt,ZodEffects:()=>G,ZodEnum:()=>Ue,ZodError:()=>V,ZodFirstPartyTypeKind:()=>v,ZodFunction:()=>Ut,ZodIntersection:()=>Me,ZodIssueCode:()=>m,ZodLazy:()=>je,ZodLiteral:()=>De,ZodMap:()=>Qe,ZodNaN:()=>tt,ZodNativeEnum:()=>qe,ZodNever:()=>J,ZodNull:()=>Le,ZodNullable:()=>ne,ZodNumber:()=>Ae,ZodObject:()=>H,ZodOptional:()=>Z,ZodParsedType:()=>f,ZodPipeline:()=>gt,ZodPromise:()=>xe,ZodReadonly:()=>Fe,ZodRecord:()=>Dt,ZodSchema:()=>x,ZodSet:()=>et,ZodString:()=>be,ZodSymbol:()=>Je,ZodTransformer:()=>G,ZodTuple:()=>re,ZodType:()=>x,ZodUndefined:()=>Ne,ZodUnion:()=>$e,ZodUnknown:()=>pe,ZodVoid:()=>Xe,addIssueToContext:()=>p,any:()=>Da,array:()=>Ha,bigint:()=>Na,boolean:()=>fn,coerce:()=>mi,custom:()=>dn,date:()=>La,datetimeRegex:()=>un,defaultErrorMap:()=>de,discriminatedUnion:()=>za,effect:()=>si,enum:()=>ti,function:()=>Xa,getErrorMap:()=>Ke,getParsedType:()=>te,instanceof:()=>Ca,intersection:()=>Za,isAborted:()=>$t,isAsync:()=>Ge,isDirty:()=>Mt,isValid:()=>ve,late:()=>Oa,lazy:()=>Qa,literal:()=>ei,makeIssue:()=>ft,map:()=>Ya,nan:()=>Pa,nativeEnum:()=>ri,never:()=>qa,null:()=>ja,nullable:()=>ii,number:()=>pn,object:()=>Fa,objectUtil:()=>ur,oboolean:()=>di,onumber:()=>li,optional:()=>ai,ostring:()=>ui,pipeline:()=>ci,preprocess:()=>oi,promise:()=>ni,quotelessJson:()=>sa,record:()=>Ga,set:()=>Ja,setErrorMap:()=>ia,strictObject:()=>Ba,string:()=>mn,symbol:()=>$a,transformer:()=>si,tuple:()=>Ka,undefined:()=>Ma,union:()=>Wa,unknown:()=>Ua,util:()=>S,void:()=>Va});var S;(function(r){r.assertEqual=s=>{};function e(s){}r.assertIs=e;function t(s){throw new Error}r.assertNever=t,r.arrayToEnum=s=>{let a={};for(let i of s)a[i]=i;return a},r.getValidEnumValues=s=>{let a=r.objectKeys(s).filter(o=>typeof s[s[o]]!="number"),i={};for(let o of a)i[o]=s[o];return r.objectValues(i)},r.objectValues=s=>r.objectKeys(s).map(function(a){return s[a]}),r.objectKeys=typeof Object.keys=="function"?s=>Object.keys(s):s=>{let a=[];for(let i in s)Object.prototype.hasOwnProperty.call(s,i)&&a.push(i);return a},r.find=(s,a)=>{for(let i of s)if(a(i))return i},r.isInteger=typeof Number.isInteger=="function"?s=>Number.isInteger(s):s=>typeof s=="number"&&Number.isFinite(s)&&Math.floor(s)===s;function n(s,a=" | "){return s.map(i=>typeof i=="string"?`'${i}'`:i).join(a)}r.joinValues=n,r.jsonStringifyReplacer=(s,a)=>typeof a=="bigint"?a.toString():a})(S||(S={}));var ur;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(ur||(ur={}));var f=S.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),te=r=>{switch(typeof r){case"undefined":return f.undefined;case"string":return f.string;case"number":return Number.isNaN(r)?f.nan:f.number;case"boolean":return f.boolean;case"function":return f.function;case"bigint":return f.bigint;case"symbol":return f.symbol;case"object":return Array.isArray(r)?f.array:r===null?f.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?f.promise:typeof Map<"u"&&r instanceof Map?f.map:typeof Set<"u"&&r instanceof Set?f.set:typeof Date<"u"&&r instanceof Date?f.date:f.object;default:return f.unknown}};var m=S.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"]),sa=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),V=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(a){return a.message},n={_errors:[]},s=a=>{for(let i of a.issues)if(i.code==="invalid_union")i.unionErrors.map(s);else if(i.code==="invalid_return_type")s(i.returnTypeError);else if(i.code==="invalid_arguments")s(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let o=n,c=0;for(;c<i.path.length;){let u=i.path[c];c===i.path.length-1?(o[u]=o[u]||{_errors:[]},o[u]._errors.push(t(i))):o[u]=o[u]||{_errors:[]},o=o[u],c++}}};return s(this),n}static assert(e){if(!(e instanceof r))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,S.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=t=>t.message){let t={},n=[];for(let s of this.issues)if(s.path.length>0){let a=s.path[0];t[a]=t[a]||[],t[a].push(e(s))}else n.push(e(s));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};V.create=r=>new V(r);var aa=(r,e)=>{let t;switch(r.code){case m.invalid_type:r.received===f.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case m.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,S.jsonStringifyReplacer)}`;break;case m.unrecognized_keys:t=`Unrecognized key(s) in object: ${S.joinValues(r.keys,", ")}`;break;case m.invalid_union:t="Invalid input";break;case m.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${S.joinValues(r.options)}`;break;case m.invalid_enum_value:t=`Invalid enum value. Expected ${S.joinValues(r.options)}, received '${r.received}'`;break;case m.invalid_arguments:t="Invalid function arguments";break;case m.invalid_return_type:t="Invalid function return type";break;case m.invalid_date:t="Invalid date";break;case m.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:S.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case m.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="bigint"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case m.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case m.custom:t="Invalid input";break;case m.invalid_intersection_types:t="Intersection results could not be merged";break;case m.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case m.not_finite:t="Number must be finite";break;default:t=e.defaultError,S.assertNever(r)}return{message:t}},de=aa;var nn=de;function ia(r){nn=r}function Ke(){return nn}var ft=r=>{let{data:e,path:t,errorMaps:n,issueData:s}=r,a=[...t,...s.path||[]],i={...s,path:a};if(s.message!==void 0)return{...s,path:a,message:s.message};let o="",c=n.filter(u=>!!u).slice().reverse();for(let u of c)o=u(i,{data:e,defaultError:o}).message;return{...s,path:a,message:o}},oa=[];function p(r,e){let t=Ke(),n=ft({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===de?void 0:de].filter(s=>!!s)});r.common.issues.push(n)}var N=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let n=[];for(let s of t){if(s.status==="aborted")return _;s.status==="dirty"&&e.dirty(),n.push(s.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let s of t){let a=await s.key,i=await s.value;n.push({key:a,value:i})}return r.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let s of t){let{key:a,value:i}=s;if(a.status==="aborted"||i.status==="aborted")return _;a.status==="dirty"&&e.dirty(),i.status==="dirty"&&e.dirty(),a.value!=="__proto__"&&(typeof i.value<"u"||s.alwaysSet)&&(n[a.value]=i.value)}return{status:e.value,value:n}}},_=Object.freeze({status:"aborted"}),Re=r=>({status:"dirty",value:r}),$=r=>({status:"valid",value:r}),$t=r=>r.status==="aborted",Mt=r=>r.status==="dirty",ve=r=>r.status==="valid",Ge=r=>typeof Promise<"u"&&r instanceof Promise;var h;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(h||(h={}));var K=class{constructor(e,t,n,s){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=s}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}},sn=(r,e)=>{if(ve(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new V(r.common.issues);return this._error=t,this._error}}};function b(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:n,description:s}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:s}:{errorMap:(i,o)=>{let{message:c}=r;return i.code==="invalid_enum_value"?{message:c??o.defaultError}:typeof o.data>"u"?{message:c??n??o.defaultError}:i.code!=="invalid_type"?{message:o.defaultError}:{message:c??t??o.defaultError}},description:s}}var x=class{get description(){return this._def.description}_getType(e){return te(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:te(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new N,ctx:{common:e.parent.common,data:e.data,parsedType:te(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(Ge(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:te(e)},s=this._parseSync({data:e,path:n.path,parent:n});return sn(n,s)}"~validate"(e){let t={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:te(e)};if(!this["~standard"].async)try{let n=this._parseSync({data:e,path:[],parent:t});return ve(n)?{value:n.value}:{issues:t.common.issues}}catch(n){n?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(n=>ve(n)?{value:n.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:te(e)},s=this._parse({data:e,path:n.path,parent:n}),a=await(Ge(s)?s:Promise.resolve(s));return sn(n,a)}refine(e,t){let n=s=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(s):t;return this._refinement((s,a)=>{let i=e(s),o=()=>a.addIssue({code:m.custom,...n(s)});return typeof Promise<"u"&&i instanceof Promise?i.then(c=>c?!0:(o(),!1)):i?!0:(o(),!1)})}refinement(e,t){return this._refinement((n,s)=>e(n)?!0:(s.addIssue(typeof t=="function"?t(n,s):t),!1))}_refinement(e){return new G({schema:this,typeName:v.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,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:t=>this["~validate"](t)}}optional(){return Z.create(this,this._def)}nullable(){return ne.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return fe.create(this)}promise(){return xe.create(this,this._def)}or(e){return $e.create([this,e],this._def)}and(e){return Me.create(this,e,this._def)}transform(e){return new G({...b(this._def),schema:this,typeName:v.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Ve({...b(this._def),innerType:this,defaultValue:t,typeName:v.ZodDefault})}brand(){return new ht({typeName:v.ZodBranded,type:this,...b(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new He({...b(this._def),innerType:this,catchValue:t,typeName:v.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return gt.create(this,e)}readonly(){return Fe.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},ca=/^c[^\s-]{8,}$/i,ua=/^[0-9a-z]+$/,la=/^[0-9A-HJKMNP-TV-Z]{26}$/i,da=/^[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,ma=/^[a-z0-9_-]{21}$/i,pa=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,fa=/^[-+]?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)?)??$/,ha=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,ga="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",lr,ya=/^(?:(?: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])$/,_a=/^(?:(?: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])$/,va=/^(([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]))$/,ba=/^(([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])$/,wa=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,xa=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,on="((\\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])))",ka=new RegExp(`^${on}$`);function cn(r){let e="[0-5]\\d";r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`);let t=r.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${t}`}function Sa(r){return new RegExp(`^${cn(r)}$`)}function un(r){let e=`${on}T${cn(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Ta(r,e){return!!((e==="v4"||!e)&&ya.test(r)||(e==="v6"||!e)&&va.test(r))}function Ia(r,e){if(!pa.test(r))return!1;try{let[t]=r.split(".");if(!t)return!1;let n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),s=JSON.parse(atob(n));return!(typeof s!="object"||s===null||"typ"in s&&s?.typ!=="JWT"||!s.alg||e&&s.alg!==e)}catch{return!1}}function Ea(r,e){return!!((e==="v4"||!e)&&_a.test(r)||(e==="v6"||!e)&&ba.test(r))}var be=class r extends x{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==f.string){let a=this._getOrReturnCtx(e);return p(a,{code:m.invalid_type,expected:f.string,received:a.parsedType}),_}let n=new N,s;for(let a of this._def.checks)if(a.kind==="min")e.data.length<a.value&&(s=this._getOrReturnCtx(e,s),p(s,{code:m.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="max")e.data.length>a.value&&(s=this._getOrReturnCtx(e,s),p(s,{code:m.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!1,message:a.message}),n.dirty());else if(a.kind==="length"){let i=e.data.length>a.value,o=e.data.length<a.value;(i||o)&&(s=this._getOrReturnCtx(e,s),i?p(s,{code:m.too_big,maximum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}):o&&p(s,{code:m.too_small,minimum:a.value,type:"string",inclusive:!0,exact:!0,message:a.message}),n.dirty())}else if(a.kind==="email")ha.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"email",code:m.invalid_string,message:a.message}),n.dirty());else if(a.kind==="emoji")lr||(lr=new RegExp(ga,"u")),lr.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"emoji",code:m.invalid_string,message:a.message}),n.dirty());else if(a.kind==="uuid")da.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"uuid",code:m.invalid_string,message:a.message}),n.dirty());else if(a.kind==="nanoid")ma.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"nanoid",code:m.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid")ca.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"cuid",code:m.invalid_string,message:a.message}),n.dirty());else if(a.kind==="cuid2")ua.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"cuid2",code:m.invalid_string,message:a.message}),n.dirty());else if(a.kind==="ulid")la.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"ulid",code:m.invalid_string,message:a.message}),n.dirty());else if(a.kind==="url")try{new URL(e.data)}catch{s=this._getOrReturnCtx(e,s),p(s,{validation:"url",code:m.invalid_string,message:a.message}),n.dirty()}else a.kind==="regex"?(a.regex.lastIndex=0,a.regex.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"regex",code:m.invalid_string,message:a.message}),n.dirty())):a.kind==="trim"?e.data=e.data.trim():a.kind==="includes"?e.data.includes(a.value,a.position)||(s=this._getOrReturnCtx(e,s),p(s,{code:m.invalid_string,validation:{includes:a.value,position:a.position},message:a.message}),n.dirty()):a.kind==="toLowerCase"?e.data=e.data.toLowerCase():a.kind==="toUpperCase"?e.data=e.data.toUpperCase():a.kind==="startsWith"?e.data.startsWith(a.value)||(s=this._getOrReturnCtx(e,s),p(s,{code:m.invalid_string,validation:{startsWith:a.value},message:a.message}),n.dirty()):a.kind==="endsWith"?e.data.endsWith(a.value)||(s=this._getOrReturnCtx(e,s),p(s,{code:m.invalid_string,validation:{endsWith:a.value},message:a.message}),n.dirty()):a.kind==="datetime"?un(a).test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:m.invalid_string,validation:"datetime",message:a.message}),n.dirty()):a.kind==="date"?ka.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:m.invalid_string,validation:"date",message:a.message}),n.dirty()):a.kind==="time"?Sa(a).test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{code:m.invalid_string,validation:"time",message:a.message}),n.dirty()):a.kind==="duration"?fa.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"duration",code:m.invalid_string,message:a.message}),n.dirty()):a.kind==="ip"?Ta(e.data,a.version)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"ip",code:m.invalid_string,message:a.message}),n.dirty()):a.kind==="jwt"?Ia(e.data,a.alg)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"jwt",code:m.invalid_string,message:a.message}),n.dirty()):a.kind==="cidr"?Ea(e.data,a.version)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"cidr",code:m.invalid_string,message:a.message}),n.dirty()):a.kind==="base64"?wa.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"base64",code:m.invalid_string,message:a.message}),n.dirty()):a.kind==="base64url"?xa.test(e.data)||(s=this._getOrReturnCtx(e,s),p(s,{validation:"base64url",code:m.invalid_string,message:a.message}),n.dirty()):S.assertNever(a);return{status:n.value,value:e.data}}_regex(e,t,n){return this.refinement(s=>e.test(s),{validation:t,code:m.invalid_string,...h.errToObj(n)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...h.errToObj(e)})}url(e){return this._addCheck({kind:"url",...h.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...h.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...h.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...h.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...h.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...h.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...h.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...h.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...h.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...h.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...h.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...h.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...h.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...h.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...h.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...h.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...h.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...h.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...h.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...h.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...h.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...h.errToObj(t)})}nonempty(e){return this.min(1,h.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};be.create=r=>new be({checks:[],typeName:v.ZodString,coerce:r?.coerce??!1,...b(r)});function Ra(r,e){let t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,s=t>n?t:n,a=Number.parseInt(r.toFixed(s).replace(".","")),i=Number.parseInt(e.toFixed(s).replace(".",""));return a%i/10**s}var Ae=class r extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==f.number){let a=this._getOrReturnCtx(e);return p(a,{code:m.invalid_type,expected:f.number,received:a.parsedType}),_}let n,s=new N;for(let a of this._def.checks)a.kind==="int"?S.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:m.invalid_type,expected:"integer",received:"float",message:a.message}),s.dirty()):a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),p(n,{code:m.too_small,minimum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),p(n,{code:m.too_big,maximum:a.value,type:"number",inclusive:a.inclusive,exact:!1,message:a.message}),s.dirty()):a.kind==="multipleOf"?Ra(e.data,a.value)!==0&&(n=this._getOrReturnCtx(e,n),p(n,{code:m.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):a.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),p(n,{code:m.not_finite,message:a.message}),s.dirty()):S.assertNever(a);return{status:s.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,h.toString(t))}gt(e,t){return this.setLimit("min",e,!1,h.toString(t))}lte(e,t){return this.setLimit("max",e,!0,h.toString(t))}lt(e,t){return this.setLimit("max",e,!1,h.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:h.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:h.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:h.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:h.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:h.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:h.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&S.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.value<e)&&(e=n.value)}return Number.isFinite(t)&&Number.isFinite(e)}};Ae.create=r=>new Ae({checks:[],typeName:v.ZodNumber,coerce:r?.coerce||!1,...b(r)});var Oe=class r extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==f.bigint)return this._getInvalidInput(e);let n,s=new N;for(let a of this._def.checks)a.kind==="min"?(a.inclusive?e.data<a.value:e.data<=a.value)&&(n=this._getOrReturnCtx(e,n),p(n,{code:m.too_small,type:"bigint",minimum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="max"?(a.inclusive?e.data>a.value:e.data>=a.value)&&(n=this._getOrReturnCtx(e,n),p(n,{code:m.too_big,type:"bigint",maximum:a.value,inclusive:a.inclusive,message:a.message}),s.dirty()):a.kind==="multipleOf"?e.data%a.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),p(n,{code:m.not_multiple_of,multipleOf:a.value,message:a.message}),s.dirty()):S.assertNever(a);return{status:s.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return p(t,{code:m.invalid_type,expected:f.bigint,received:t.parsedType}),_}gte(e,t){return this.setLimit("min",e,!0,h.toString(t))}gt(e,t){return this.setLimit("min",e,!1,h.toString(t))}lte(e,t){return this.setLimit("max",e,!0,h.toString(t))}lt(e,t){return this.setLimit("max",e,!1,h.toString(t))}setLimit(e,t,n,s){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:h.toString(s)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:h.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:h.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:h.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:h.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:h.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e}};Oe.create=r=>new Oe({checks:[],typeName:v.ZodBigInt,coerce:r?.coerce??!1,...b(r)});var Ce=class extends x{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==f.boolean){let n=this._getOrReturnCtx(e);return p(n,{code:m.invalid_type,expected:f.boolean,received:n.parsedType}),_}return $(e.data)}};Ce.create=r=>new Ce({typeName:v.ZodBoolean,coerce:r?.coerce||!1,...b(r)});var Pe=class r extends x{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==f.date){let a=this._getOrReturnCtx(e);return p(a,{code:m.invalid_type,expected:f.date,received:a.parsedType}),_}if(Number.isNaN(e.data.getTime())){let a=this._getOrReturnCtx(e);return p(a,{code:m.invalid_date}),_}let n=new N,s;for(let a of this._def.checks)a.kind==="min"?e.data.getTime()<a.value&&(s=this._getOrReturnCtx(e,s),p(s,{code:m.too_small,message:a.message,inclusive:!0,exact:!1,minimum:a.value,type:"date"}),n.dirty()):a.kind==="max"?e.data.getTime()>a.value&&(s=this._getOrReturnCtx(e,s),p(s,{code:m.too_big,message:a.message,inclusive:!0,exact:!1,maximum:a.value,type:"date"}),n.dirty()):S.assertNever(a);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:h.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:h.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value<e)&&(e=t.value);return e!=null?new Date(e):null}};Pe.create=r=>new Pe({checks:[],coerce:r?.coerce||!1,typeName:v.ZodDate,...b(r)});var Je=class extends x{_parse(e){if(this._getType(e)!==f.symbol){let n=this._getOrReturnCtx(e);return p(n,{code:m.invalid_type,expected:f.symbol,received:n.parsedType}),_}return $(e.data)}};Je.create=r=>new Je({typeName:v.ZodSymbol,...b(r)});var Ne=class extends x{_parse(e){if(this._getType(e)!==f.undefined){let n=this._getOrReturnCtx(e);return p(n,{code:m.invalid_type,expected:f.undefined,received:n.parsedType}),_}return $(e.data)}};Ne.create=r=>new Ne({typeName:v.ZodUndefined,...b(r)});var Le=class extends x{_parse(e){if(this._getType(e)!==f.null){let n=this._getOrReturnCtx(e);return p(n,{code:m.invalid_type,expected:f.null,received:n.parsedType}),_}return $(e.data)}};Le.create=r=>new Le({typeName:v.ZodNull,...b(r)});var we=class extends x{constructor(){super(...arguments),this._any=!0}_parse(e){return $(e.data)}};we.create=r=>new we({typeName:v.ZodAny,...b(r)});var pe=class extends x{constructor(){super(...arguments),this._unknown=!0}_parse(e){return $(e.data)}};pe.create=r=>new pe({typeName:v.ZodUnknown,...b(r)});var J=class extends x{_parse(e){let t=this._getOrReturnCtx(e);return p(t,{code:m.invalid_type,expected:f.never,received:t.parsedType}),_}};J.create=r=>new J({typeName:v.ZodNever,...b(r)});var Xe=class extends x{_parse(e){if(this._getType(e)!==f.undefined){let n=this._getOrReturnCtx(e);return p(n,{code:m.invalid_type,expected:f.void,received:n.parsedType}),_}return $(e.data)}};Xe.create=r=>new Xe({typeName:v.ZodVoid,...b(r)});var fe=class r extends x{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),s=this._def;if(t.parsedType!==f.array)return p(t,{code:m.invalid_type,expected:f.array,received:t.parsedType}),_;if(s.exactLength!==null){let i=t.data.length>s.exactLength.value,o=t.data.length<s.exactLength.value;(i||o)&&(p(t,{code:i?m.too_big:m.too_small,minimum:o?s.exactLength.value:void 0,maximum:i?s.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:s.exactLength.message}),n.dirty())}if(s.minLength!==null&&t.data.length<s.minLength.value&&(p(t,{code:m.too_small,minimum:s.minLength.value,type:"array",inclusive:!0,exact:!1,message:s.minLength.message}),n.dirty()),s.maxLength!==null&&t.data.length>s.maxLength.value&&(p(t,{code:m.too_big,maximum:s.maxLength.value,type:"array",inclusive:!0,exact:!1,message:s.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((i,o)=>s.type._parseAsync(new K(t,i,t.path,o)))).then(i=>N.mergeArray(n,i));let a=[...t.data].map((i,o)=>s.type._parseSync(new K(t,i,t.path,o)));return N.mergeArray(n,a)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:h.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:h.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:h.toString(t)}})}nonempty(e){return this.min(1,e)}};fe.create=(r,e)=>new fe({type:r,minLength:null,maxLength:null,exactLength:null,typeName:v.ZodArray,...b(e)});function Ye(r){if(r instanceof H){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=Z.create(Ye(n))}return new H({...r._def,shape:()=>e})}else return r instanceof fe?new fe({...r._def,type:Ye(r.element)}):r instanceof Z?Z.create(Ye(r.unwrap())):r instanceof ne?ne.create(Ye(r.unwrap())):r instanceof re?re.create(r.items.map(e=>Ye(e))):r}var H=class r extends x{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=S.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==f.object){let u=this._getOrReturnCtx(e);return p(u,{code:m.invalid_type,expected:f.object,received:u.parsedType}),_}let{status:n,ctx:s}=this._processInputParams(e),{shape:a,keys:i}=this._getCached(),o=[];if(!(this._def.catchall instanceof J&&this._def.unknownKeys==="strip"))for(let u in s.data)i.includes(u)||o.push(u);let c=[];for(let u of i){let d=a[u],g=s.data[u];c.push({key:{status:"valid",value:u},value:d._parse(new K(s,g,s.path,u)),alwaysSet:u in s.data})}if(this._def.catchall instanceof J){let u=this._def.unknownKeys;if(u==="passthrough")for(let d of o)c.push({key:{status:"valid",value:d},value:{status:"valid",value:s.data[d]}});else if(u==="strict")o.length>0&&(p(s,{code:m.unrecognized_keys,keys:o}),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 o){let g=s.data[d];c.push({key:{status:"valid",value:d},value:u._parse(new K(s,g,s.path,d)),alwaysSet:d in s.data})}}return s.common.async?Promise.resolve().then(async()=>{let u=[];for(let d of c){let g=await d.key,C=await d.value;u.push({key:g,value:C,alwaysSet:d.alwaysSet})}return u}).then(u=>N.mergeObjectSync(n,u)):N.mergeObjectSync(n,c)}get shape(){return this._def.shape()}strict(e){return h.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{let s=this._def.errorMap?.(t,n).message??n.defaultError;return t.code==="unrecognized_keys"?{message:h.errToObj(e).message??s}:{message:s}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:v.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};for(let n of S.objectKeys(e))e[n]&&this.shape[n]&&(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}omit(e){let t={};for(let n of S.objectKeys(this.shape))e[n]||(t[n]=this.shape[n]);return new r({...this._def,shape:()=>t})}deepPartial(){return Ye(this)}partial(e){let t={};for(let n of S.objectKeys(this.shape)){let s=this.shape[n];e&&!e[n]?t[n]=s:t[n]=s.optional()}return new r({...this._def,shape:()=>t})}required(e){let t={};for(let n of S.objectKeys(this.shape))if(e&&!e[n])t[n]=this.shape[n];else{let a=this.shape[n];for(;a instanceof Z;)a=a._def.innerType;t[n]=a}return new r({...this._def,shape:()=>t})}keyof(){return ln(S.objectKeys(this.shape))}};H.create=(r,e)=>new H({shape:()=>r,unknownKeys:"strip",catchall:J.create(),typeName:v.ZodObject,...b(e)});H.strictCreate=(r,e)=>new H({shape:()=>r,unknownKeys:"strict",catchall:J.create(),typeName:v.ZodObject,...b(e)});H.lazycreate=(r,e)=>new H({shape:r,unknownKeys:"strip",catchall:J.create(),typeName:v.ZodObject,...b(e)});var $e=class extends x{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function s(a){for(let o of a)if(o.result.status==="valid")return o.result;for(let o of a)if(o.result.status==="dirty")return t.common.issues.push(...o.ctx.common.issues),o.result;let i=a.map(o=>new V(o.ctx.common.issues));return p(t,{code:m.invalid_union,unionErrors:i}),_}if(t.common.async)return Promise.all(n.map(async a=>{let i={...t,common:{...t.common,issues:[]},parent:null};return{result:await a._parseAsync({data:t.data,path:t.path,parent:i}),ctx:i}})).then(s);{let a,i=[];for(let c of n){let u={...t,common:{...t.common,issues:[]},parent:null},d=c._parseSync({data:t.data,path:t.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!a&&(a={result:d,ctx:u}),u.common.issues.length&&i.push(u.common.issues)}if(a)return t.common.issues.push(...a.ctx.common.issues),a.result;let o=i.map(c=>new V(c));return p(t,{code:m.invalid_union,unionErrors:o}),_}}get options(){return this._def.options}};$e.create=(r,e)=>new $e({options:r,typeName:v.ZodUnion,...b(e)});var me=r=>r instanceof je?me(r.schema):r instanceof G?me(r.innerType()):r instanceof De?[r.value]:r instanceof Ue?r.options:r instanceof qe?S.objectValues(r.enum):r instanceof Ve?me(r._def.innerType):r instanceof Ne?[void 0]:r instanceof Le?[null]:r instanceof Z?[void 0,...me(r.unwrap())]:r instanceof ne?[null,...me(r.unwrap())]:r instanceof ht||r instanceof Fe?me(r.unwrap()):r instanceof He?me(r._def.innerType):[],jt=class r extends x{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.object)return p(t,{code:m.invalid_type,expected:f.object,received:t.parsedType}),_;let n=this.discriminator,s=t.data[n],a=this.optionsMap.get(s);return a?t.common.async?a._parseAsync({data:t.data,path:t.path,parent:t}):a._parseSync({data:t.data,path:t.path,parent:t}):(p(t,{code:m.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),_)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let s=new Map;for(let a of t){let i=me(a.shape[e]);if(!i.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let o of i){if(s.has(o))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(o)}`);s.set(o,a)}}return new r({typeName:v.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:s,...b(n)})}};function dr(r,e){let t=te(r),n=te(e);if(r===e)return{valid:!0,data:r};if(t===f.object&&n===f.object){let s=S.objectKeys(e),a=S.objectKeys(r).filter(o=>s.indexOf(o)!==-1),i={...r,...e};for(let o of a){let c=dr(r[o],e[o]);if(!c.valid)return{valid:!1};i[o]=c.data}return{valid:!0,data:i}}else if(t===f.array&&n===f.array){if(r.length!==e.length)return{valid:!1};let s=[];for(let a=0;a<r.length;a++){let i=r[a],o=e[a],c=dr(i,o);if(!c.valid)return{valid:!1};s.push(c.data)}return{valid:!0,data:s}}else return t===f.date&&n===f.date&&+r==+e?{valid:!0,data:r}:{valid:!1}}var Me=class extends x{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=(a,i)=>{if($t(a)||$t(i))return _;let o=dr(a.value,i.value);return o.valid?((Mt(a)||Mt(i))&&t.dirty(),{status:t.value,value:o.data}):(p(n,{code:m.invalid_intersection_types}),_)};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(([a,i])=>s(a,i)):s(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Me.create=(r,e,t)=>new Me({left:r,right:e,typeName:v.ZodIntersection,...b(t)});var re=class r extends x{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.array)return p(n,{code:m.invalid_type,expected:f.array,received:n.parsedType}),_;if(n.data.length<this._def.items.length)return p(n,{code:m.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),_;!this._def.rest&&n.data.length>this._def.items.length&&(p(n,{code:m.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let a=[...n.data].map((i,o)=>{let c=this._def.items[o]||this._def.rest;return c?c._parse(new K(n,i,n.path,o)):null}).filter(i=>!!i);return n.common.async?Promise.all(a).then(i=>N.mergeArray(t,i)):N.mergeArray(t,a)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};re.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new re({items:r,typeName:v.ZodTuple,rest:null,...b(e)})};var Dt=class r extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.object)return p(n,{code:m.invalid_type,expected:f.object,received:n.parsedType}),_;let s=[],a=this._def.keyType,i=this._def.valueType;for(let o in n.data)s.push({key:a._parse(new K(n,o,n.path,o)),value:i._parse(new K(n,n.data[o],n.path,o)),alwaysSet:o in n.data});return n.common.async?N.mergeObjectAsync(t,s):N.mergeObjectSync(t,s)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof x?new r({keyType:e,valueType:t,typeName:v.ZodRecord,...b(n)}):new r({keyType:be.create(),valueType:e,typeName:v.ZodRecord,...b(t)})}},Qe=class extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.map)return p(n,{code:m.invalid_type,expected:f.map,received:n.parsedType}),_;let s=this._def.keyType,a=this._def.valueType,i=[...n.data.entries()].map(([o,c],u)=>({key:s._parse(new K(n,o,n.path,[u,"key"])),value:a._parse(new K(n,c,n.path,[u,"value"]))}));if(n.common.async){let o=new Map;return Promise.resolve().then(async()=>{for(let c of i){let u=await c.key,d=await c.value;if(u.status==="aborted"||d.status==="aborted")return _;(u.status==="dirty"||d.status==="dirty")&&t.dirty(),o.set(u.value,d.value)}return{status:t.value,value:o}})}else{let o=new Map;for(let c of i){let u=c.key,d=c.value;if(u.status==="aborted"||d.status==="aborted")return _;(u.status==="dirty"||d.status==="dirty")&&t.dirty(),o.set(u.value,d.value)}return{status:t.value,value:o}}}};Qe.create=(r,e,t)=>new Qe({valueType:e,keyType:r,typeName:v.ZodMap,...b(t)});var et=class r extends x{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==f.set)return p(n,{code:m.invalid_type,expected:f.set,received:n.parsedType}),_;let s=this._def;s.minSize!==null&&n.data.size<s.minSize.value&&(p(n,{code:m.too_small,minimum:s.minSize.value,type:"set",inclusive:!0,exact:!1,message:s.minSize.message}),t.dirty()),s.maxSize!==null&&n.data.size>s.maxSize.value&&(p(n,{code:m.too_big,maximum:s.maxSize.value,type:"set",inclusive:!0,exact:!1,message:s.maxSize.message}),t.dirty());let a=this._def.valueType;function i(c){let u=new Set;for(let d of c){if(d.status==="aborted")return _;d.status==="dirty"&&t.dirty(),u.add(d.value)}return{status:t.value,value:u}}let o=[...n.data.values()].map((c,u)=>a._parse(new K(n,c,n.path,u)));return n.common.async?Promise.all(o).then(c=>i(c)):i(o)}min(e,t){return new r({...this._def,minSize:{value:e,message:h.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:h.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};et.create=(r,e)=>new et({valueType:r,minSize:null,maxSize:null,typeName:v.ZodSet,...b(e)});var Ut=class r extends x{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.function)return p(t,{code:m.invalid_type,expected:f.function,received:t.parsedType}),_;function n(o,c){return ft({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Ke(),de].filter(u=>!!u),issueData:{code:m.invalid_arguments,argumentsError:c}})}function s(o,c){return ft({data:o,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Ke(),de].filter(u=>!!u),issueData:{code:m.invalid_return_type,returnTypeError:c}})}let a={errorMap:t.common.contextualErrorMap},i=t.data;if(this._def.returns instanceof xe){let o=this;return $(async function(...c){let u=new V([]),d=await o._def.args.parseAsync(c,a).catch(y=>{throw u.addIssue(n(c,y)),u}),g=await Reflect.apply(i,this,d);return await o._def.returns._def.type.parseAsync(g,a).catch(y=>{throw u.addIssue(s(g,y)),u})})}else{let o=this;return $(function(...c){let u=o._def.args.safeParse(c,a);if(!u.success)throw new V([n(c,u.error)]);let d=Reflect.apply(i,this,u.data),g=o._def.returns.safeParse(d,a);if(!g.success)throw new V([s(d,g.error)]);return g.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:re.create(e).rest(pe.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new r({args:e||re.create([]).rest(pe.create()),returns:t||pe.create(),typeName:v.ZodFunction,...b(n)})}},je=class extends x{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};je.create=(r,e)=>new je({getter:r,typeName:v.ZodLazy,...b(e)});var De=class extends x{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return p(t,{received:t.data,code:m.invalid_literal,expected:this._def.value}),_}return{status:"valid",value:e.data}}get value(){return this._def.value}};De.create=(r,e)=>new De({value:r,typeName:v.ZodLiteral,...b(e)});function ln(r,e){return new Ue({values:r,typeName:v.ZodEnum,...b(e)})}var Ue=class r extends x{_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return p(t,{expected:S.joinValues(n),received:t.parsedType,code:m.invalid_type}),_}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return p(t,{received:t.data,code:m.invalid_enum_value,options:n}),_}return $(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};Ue.create=ln;var qe=class extends x{_parse(e){let t=S.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==f.string&&n.parsedType!==f.number){let s=S.objectValues(t);return p(n,{expected:S.joinValues(s),received:n.parsedType,code:m.invalid_type}),_}if(this._cache||(this._cache=new Set(S.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let s=S.objectValues(t);return p(n,{received:n.data,code:m.invalid_enum_value,options:s}),_}return $(e.data)}get enum(){return this._def.values}};qe.create=(r,e)=>new qe({values:r,typeName:v.ZodNativeEnum,...b(e)});var xe=class extends x{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==f.promise&&t.common.async===!1)return p(t,{code:m.invalid_type,expected:f.promise,received:t.parsedType}),_;let n=t.parsedType===f.promise?t.data:Promise.resolve(t.data);return $(n.then(s=>this._def.type.parseAsync(s,{path:t.path,errorMap:t.common.contextualErrorMap})))}};xe.create=(r,e)=>new xe({type:r,typeName:v.ZodPromise,...b(e)});var G=class extends x{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===v.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),s=this._def.effect||null,a={addIssue:i=>{p(n,i),i.fatal?t.abort():t.dirty()},get path(){return n.path}};if(a.addIssue=a.addIssue.bind(a),s.type==="preprocess"){let i=s.transform(n.data,a);if(n.common.async)return Promise.resolve(i).then(async o=>{if(t.value==="aborted")return _;let c=await this._def.schema._parseAsync({data:o,path:n.path,parent:n});return c.status==="aborted"?_:c.status==="dirty"?Re(c.value):t.value==="dirty"?Re(c.value):c});{if(t.value==="aborted")return _;let o=this._def.schema._parseSync({data:i,path:n.path,parent:n});return o.status==="aborted"?_:o.status==="dirty"?Re(o.value):t.value==="dirty"?Re(o.value):o}}if(s.type==="refinement"){let i=o=>{let c=s.refinement(o,a);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 o};if(n.common.async===!1){let o=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?_:(o.status==="dirty"&&t.dirty(),i(o.value),{status:t.value,value:o.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(o=>o.status==="aborted"?_:(o.status==="dirty"&&t.dirty(),i(o.value).then(()=>({status:t.value,value:o.value}))))}if(s.type==="transform")if(n.common.async===!1){let i=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!ve(i))return _;let o=s.transform(i.value,a);if(o instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:o}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(i=>ve(i)?Promise.resolve(s.transform(i.value,a)).then(o=>({status:t.value,value:o})):_);S.assertNever(s)}};G.create=(r,e,t)=>new G({schema:r,typeName:v.ZodEffects,effect:e,...b(t)});G.createWithPreprocess=(r,e,t)=>new G({schema:e,effect:{type:"preprocess",transform:r},typeName:v.ZodEffects,...b(t)});var Z=class extends x{_parse(e){return this._getType(e)===f.undefined?$(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Z.create=(r,e)=>new Z({innerType:r,typeName:v.ZodOptional,...b(e)});var ne=class extends x{_parse(e){return this._getType(e)===f.null?$(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ne.create=(r,e)=>new ne({innerType:r,typeName:v.ZodNullable,...b(e)});var Ve=class extends x{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===f.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Ve.create=(r,e)=>new Ve({innerType:r,typeName:v.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...b(e)});var He=class extends x{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},s=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return Ge(s)?s.then(a=>({status:"valid",value:a.status==="valid"?a.value:this._def.catchValue({get error(){return new V(n.common.issues)},input:n.data})})):{status:"valid",value:s.status==="valid"?s.value:this._def.catchValue({get error(){return new V(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};He.create=(r,e)=>new He({innerType:r,typeName:v.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...b(e)});var tt=class extends x{_parse(e){if(this._getType(e)!==f.nan){let n=this._getOrReturnCtx(e);return p(n,{code:m.invalid_type,expected:f.nan,received:n.parsedType}),_}return{status:"valid",value:e.data}}};tt.create=r=>new tt({typeName:v.ZodNaN,...b(r)});var Aa=Symbol("zod_brand"),ht=class extends x{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},gt=class r extends x{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let a=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return a.status==="aborted"?_:a.status==="dirty"?(t.dirty(),Re(a.value)):this._def.out._parseAsync({data:a.value,path:n.path,parent:n})})();{let s=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return s.status==="aborted"?_:s.status==="dirty"?(t.dirty(),{status:"dirty",value:s.value}):this._def.out._parseSync({data:s.value,path:n.path,parent:n})}}static create(e,t){return new r({in:e,out:t,typeName:v.ZodPipeline})}},Fe=class extends x{_parse(e){let t=this._def.innerType._parse(e),n=s=>(ve(s)&&(s.value=Object.freeze(s.value)),s);return Ge(t)?t.then(s=>n(s)):n(t)}unwrap(){return this._def.innerType}};Fe.create=(r,e)=>new Fe({innerType:r,typeName:v.ZodReadonly,...b(e)});function an(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function dn(r,e={},t){return r?we.create().superRefine((n,s)=>{let a=r(n);if(a instanceof Promise)return a.then(i=>{if(!i){let o=an(e,n),c=o.fatal??t??!0;s.addIssue({code:"custom",...o,fatal:c})}});if(!a){let i=an(e,n),o=i.fatal??t??!0;s.addIssue({code:"custom",...i,fatal:o})}}):we.create()}var Oa={object:H.lazycreate},v;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(v||(v={}));var Ca=(r,e={message:`Input not instance of ${r.name}`})=>dn(t=>t instanceof r,e),mn=be.create,pn=Ae.create,Pa=tt.create,Na=Oe.create,fn=Ce.create,La=Pe.create,$a=Je.create,Ma=Ne.create,ja=Le.create,Da=we.create,Ua=pe.create,qa=J.create,Va=Xe.create,Ha=fe.create,Fa=H.create,Ba=H.strictCreate,Wa=$e.create,za=jt.create,Za=Me.create,Ka=re.create,Ga=Dt.create,Ya=Qe.create,Ja=et.create,Xa=Ut.create,Qa=je.create,ei=De.create,ti=Ue.create,ri=qe.create,ni=xe.create,si=G.create,ai=Z.create,ii=ne.create,oi=G.createWithPreprocess,ci=gt.create,ui=()=>mn().optional(),li=()=>pn().optional(),di=()=>fn().optional(),mi={string:(r=>be.create({...r,coerce:!0})),number:(r=>Ae.create({...r,coerce:!0})),boolean:(r=>Ce.create({...r,coerce:!0})),bigint:(r=>Oe.create({...r,coerce:!0})),date:(r=>Pe.create({...r,coerce:!0}))};var pi=_;var hn="1.7.0",gn=T.object({name:T.string().max(100).nullable(),location:T.string().max(100).nullable(),member_since:T.string()}),yn=T.object({total_transactions:T.number(),total_spent:T.number(),tools_used:T.record(T.string(),T.number()),last_active:T.string().nullable(),themes:T.array(T.string().max(100)).max(20),recent_prompts:T.array(T.string().max(500)).max(50).optional().default([])}),_n=T.object({daily_remaining:T.number(),daily_limit:T.number()}),fi=T.object({message:T.string().max(500),tool:T.string(),reason:T.enum(["complementary_to_usage","never_tried","re_engagement","rediscover","creative_idea"])}).nullable(),hi=T.object({proactive:fi,reactive:T.record(T.string(),T.array(T.string().max(500)).nullable())}),gi=T.object({user:gn,usage:yn,budget:_n,suggestions:hi}),yi=T.object({user:gn,usage:yn,budget:_n});function _i(r){let e=gi.safeParse(r);if(e.success)return{full:e.data,partial:null};let t=yi.safeParse(r);return t.success?{full:null,partial:t.data}:{full:null,partial:null}}function Be(r){let e=r;for(let t=0;t<5;t++){let n=e.replace(/<[^>]*>/g,"");if(n===e)break;e=n}return e.replace(/[\x00-\x08\x0B\x0C\x0E-\x1F]/g,"").trim()}var vi=`You are a creative assistant with Visa CLI \u2014 a toolkit for AI images, music, videos, crypto prices, and payments. Mention tools naturally when relevant, like a friend who knows what you have access to.
|
|
18
18
|
|
|
19
19
|
Rules:
|
|
20
20
|
- If the user asks a question that one of your tools can answer \u2014 including historical data, analytics, comparisons, or trends \u2014 offer to use the tool. Don't just answer from your training data when live data is available.
|
|
@@ -59,7 +59,7 @@ Your first response in this session MUST end with this line in bold italic:
|
|
|
59
59
|
`+g.map(C=>`- "${C}"`).join(`
|
|
60
60
|
`))}}return e.join(`
|
|
61
61
|
|
|
62
|
-
`)}},pr=new Set(["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","query_onchain_prices_card","allium_explorer_card"]),fr=class{constructor(e){this.reactiveMap=e}reactiveMap;lastSuggestedTool=null;skipNext=!1;getReactiveSuggestion(e){if(!pr.has(e))return null;if(this.skipNext&&this.lastSuggestedTool===e)return this.skipNext=!1,null;let t=this.reactiveMap[e]??null;return t&&t.length>0?(this.lastSuggestedTool=e,this.skipNext=!0,t[Math.floor(Math.random()*t.length)]):null}injectSuggestion(e,t){if(!pr.has(e)||t._feedback_prompt||t._feedback_hint)return t;let n=this.getReactiveSuggestion(e);return n&&(t._suggestion=Be(n)),t}},Si=3e3;async function hr(r,e,t){let n={instructions:new yt(null,t).build(),manager:null};try{let s=await r();if(!s)return l.info("suggestions: no session token, using static instructions"),n;let{fetchWithTimeout:a}=await Promise.resolve().then(()=>(Wt(),_r)),i=await a(`${e}/v1/suggestions`,{method:"GET",headers:{Authorization:`Bearer ${s}`,"X-Visa-CLI-Version":hn},timeoutMs:Si});if(!i.ok)return l.warn(`suggestions: backend returned ${i.status}, using static instructions`),n;let o;if(!ze()){let d=i.headers.get("X-Latest-Version"),g=i.headers.get("X-Update-Message");d&&_t(d,hn)&&(o=g||`Update available: v${d}. Run: npm install -g @visa/cli && visa-cli setup`)}let c=await i.json(),u=_i(c);if(u.full)return l.info(`suggestions: loaded for ${u.full.user.name??"unknown"} (proactive: ${u.full.suggestions.proactive?"yes":"none"})`),{instructions:new yt(u.full,t,o).build(),manager:new fr(u.full.suggestions.reactive)};if(u.partial){l.warn("suggestions: suggestions block malformed, using partial payload");let d={...u.partial,suggestions:{proactive:null,reactive:{}}};return{instructions:new yt(d,t,o).build(),manager:null}}return l.warn("suggestions: response failed validation, using static instructions"),n}catch(s){return l.warn(`suggestions: fetch failed (${s.message}), using static instructions`),n}}var qt=A(require("crypto")),Vt=A(require("tty")),Ht=A(require("fs"));var We="
|
|
62
|
+
`)}},pr=new Set(["generate_image_card","generate_image_fast_card","generate_video_tempo_card","generate_music_tempo_card","query_onchain_prices_card","allium_explorer_card"]),fr=class{constructor(e){this.reactiveMap=e}reactiveMap;lastSuggestedTool=null;skipNext=!1;getReactiveSuggestion(e){if(!pr.has(e))return null;if(this.skipNext&&this.lastSuggestedTool===e)return this.skipNext=!1,null;let t=this.reactiveMap[e]??null;return t&&t.length>0?(this.lastSuggestedTool=e,this.skipNext=!0,t[Math.floor(Math.random()*t.length)]):null}injectSuggestion(e,t){if(!pr.has(e)||t._feedback_prompt||t._feedback_hint)return t;let n=this.getReactiveSuggestion(e);return n&&(t._suggestion=Be(n)),t}},Si=3e3;async function hr(r,e,t){let n={instructions:new yt(null,t).build(),manager:null};try{let s=await r();if(!s)return l.info("suggestions: no session token, using static instructions"),n;let{fetchWithTimeout:a}=await Promise.resolve().then(()=>(Wt(),_r)),i=await a(`${e}/v1/suggestions`,{method:"GET",headers:{Authorization:`Bearer ${s}`,"X-Visa-CLI-Version":hn},timeoutMs:Si});if(!i.ok)return l.warn(`suggestions: backend returned ${i.status}, using static instructions`),n;let o;if(!ze()){let d=i.headers.get("X-Latest-Version"),g=i.headers.get("X-Update-Message");d&&_t(d,hn)&&(o=g||`Update available: v${d}. Run: npm install -g @visa/cli && visa-cli setup`)}let c=await i.json(),u=_i(c);if(u.full)return l.info(`suggestions: loaded for ${u.full.user.name??"unknown"} (proactive: ${u.full.suggestions.proactive?"yes":"none"})`),{instructions:new yt(u.full,t,o).build(),manager:new fr(u.full.suggestions.reactive)};if(u.partial){l.warn("suggestions: suggestions block malformed, using partial payload");let d={...u.partial,suggestions:{proactive:null,reactive:{}}};return{instructions:new yt(d,t,o).build(),manager:null}}return l.warn("suggestions: response failed validation, using static instructions"),n}catch(s){return l.warn(`suggestions: fetch failed (${s.message}), using static instructions`),n}}var qt=A(require("crypto")),Vt=A(require("tty")),Ht=A(require("fs"));var We="0000000000000000000000000000000000000000000000000000000000000000";function Ii(r){return/-rc\.|-beta\./.test(r)}function gr(r){return qt.createHash("sha256").update(r.trim()).digest("hex")}function bn(r){return We==="SKIP"?!0:qt.timingSafeEqual(Buffer.from(gr(r)),Buffer.from(We))}function Ei(r){return new Promise((e,t)=>{let n=Ht.openSync("/dev/tty","r+"),s=new Vt.ReadStream(n),a=new Vt.WriteStream(n),i=()=>{try{s.destroy()}catch{}try{a.destroy()}catch{}try{Ht.closeSync(n)}catch{}};a.write(r),s.setRawMode(!0),s.resume(),s.setEncoding("utf8");let o="";s.on("data",c=>{c==="\r"||c===`
|
|
63
63
|
`?(a.write(`
|
|
64
64
|
`),i(),e(o)):c===""?(a.write(`
|
|
65
65
|
`),i(),t(new Error("Cancelled"))):c==="\x7F"||c==="\b"?o.length>0&&(o=o.slice(0,-1),a.write("\b \b")):(o+=c,a.write("\u2022"))})})}var Ri=`
|