mppx 0.13.5 → 0.13.6

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.
Files changed (48) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/dist/Credential.d.ts +3 -0
  3. package/dist/Credential.js +9 -0
  4. package/dist/cli/cli.js +131 -131
  5. package/dist/cli/plugins/evm.js +2 -2
  6. package/dist/cli/plugins/index.js +11 -11
  7. package/dist/client/internal/MethodChallenge.d.ts +2 -0
  8. package/dist/client/internal/MethodChallenge.js +4 -0
  9. package/dist/internal/version.d.ts +2 -2
  10. package/dist/internal/version.js +1 -1
  11. package/dist/server/Mppx.js +31 -5
  12. package/dist/stripe/server/Methods.js +4 -1
  13. package/dist/tempo/client/Charge.js +1 -0
  14. package/dist/tempo/internal/auto-swap.d.ts +10 -0
  15. package/dist/tempo/internal/auto-swap.js +35 -8
  16. package/dist/tempo/internal/fee-payer.d.ts +8 -0
  17. package/dist/tempo/internal/fee-payer.js +20 -12
  18. package/dist/tempo/legacy/session/Chain.js +8 -2
  19. package/dist/tempo/server/Methods.js +12 -1
  20. package/dist/tempo/server/Relay.js +6 -22
  21. package/dist/tempo/server/Subscription.js +3 -0
  22. package/dist/tempo/server/internal/html.gen.js +1 -1
  23. package/dist/tempo/server/internal/transport.d.ts +3 -0
  24. package/dist/tempo/server/internal/transport.js +5 -1
  25. package/dist/tempo/session/client/ChannelOps.d.ts +2 -0
  26. package/dist/tempo/session/client/ChannelStore.d.ts +12 -1
  27. package/dist/tempo/session/client/ChannelStore.js +47 -0
  28. package/dist/tempo/session/client/CredentialState.js +8 -3
  29. package/dist/tempo/session/client/Session.js +50 -33
  30. package/dist/tempo/session/client/SessionManager.js +186 -65
  31. package/dist/tempo/session/client/Transports.d.ts +6 -0
  32. package/dist/tempo/session/client/Transports.js +52 -7
  33. package/dist/tempo/session/precompile/Chain.js +5 -2
  34. package/dist/tempo/session/server/ChannelStore.d.ts +34 -0
  35. package/dist/tempo/session/server/ChannelStore.js +69 -9
  36. package/dist/tempo/session/server/CredentialVerification.d.ts +7 -1
  37. package/dist/tempo/session/server/CredentialVerification.js +220 -48
  38. package/dist/tempo/session/server/MeteredStream.d.ts +6 -5
  39. package/dist/tempo/session/server/MeteredStream.js +10 -26
  40. package/dist/tempo/session/server/Session.d.ts +29 -2
  41. package/dist/tempo/session/server/Session.js +114 -33
  42. package/dist/tempo/session/server/Settlement.d.ts +9 -0
  43. package/dist/tempo/session/server/Settlement.js +12 -0
  44. package/dist/tempo/session/server/Sse.d.ts +4 -3
  45. package/dist/tempo/session/server/Sse.js +3 -3
  46. package/dist/tempo/session/server/Ws.d.ts +9 -1
  47. package/dist/tempo/session/server/Ws.js +1 -0
  48. package/package.json +1 -1
package/dist/cli/cli.js CHANGED
@@ -1,8 +1,8 @@
1
- import{once as e}from"node:events";import*as t from"node:fs";import n,{existsSync as r,mkdirSync as i,readFileSync as a,writeFileSync as o}from"node:fs";import{createRequire as s}from"node:module";import*as c from"node:path";import l,{dirname as u,join as d}from"node:path";import{z as f,z as p}from"zod";import*as m from"node:child_process";import{execFile as h}from"node:child_process";import{createHash as g,randomUUID as _}from"node:crypto";import*as v from"node:util";import*as y from"node:zlib";import*as b from"node:os";import x,{homedir as S}from"node:os";import*as C from"node:fs/promises";import w from"node:fs/promises";import{PassThrough as T}from"node:stream";import{fileURLToPath as ee,pathToFileURL as E}from"node:url";import*as D from"zod/v4";import{AbiParameters as O,Base64 as k,Bytes as te,Hash as ne,Hex as re,Json as A}from"ox";import{createClient as j,createTransport as ie,custom as ae,encodeFunctionData as oe,erc20Abi as se,formatUnits as ce,getAddress as M,hashTypedData as le,http as ue,isAddress as de,isAddressEqual as fe,keccak256 as pe,parseAbi as me,parseUnits as N,zeroAddress as he}from"viem";import{generatePrivateKey as ge,parseAccount as _e,privateKeyToAccount as ve}from"viem/accounts";import{tempo as ye,tempoModerato as be}from"viem/tempo/chains";import{z as xe}from"zod/mini";import{createParser as P}from"eventsource-parser";import*as Se from"node:readline";import{ousd as Ce,pathusd as we,usdce as Te}from"viem/tokens";import{call as Ee,prepareTransactionRequest as De,readContract as Oe,sendCallsSync as ke,sendTransactionSync as Ae,signTransaction as je,signTypedData as Me,waitForTransactionReceipt as Ne}from"viem/actions";import{Abis as Pe,Account as Fe,Actions as Ie,Addresses as Le,TokenId as Re,Transaction as ze,withFeePayer as Be}from"viem/tempo";import*as Ve from"viem/chains";import{tempo as He}from"viem/chains";import{Channel as Ue,KeyAuthorization as We,SignatureEnvelope as Ge,TempoAddress as Ke,TxEnvelopeTempo as qe}from"ox/tempo";var Je=Object.defineProperty,Ye=Object.getOwnPropertyDescriptor,Xe=Object.getOwnPropertyNames,Ze=Object.prototype.hasOwnProperty,F=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},Qe=(e,t)=>{let n={};for(var r in e)Je(n,r,{get:e[r],enumerable:!0});return t||Je(n,Symbol.toStringTag,{value:`Module`}),n},$e=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Xe(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Ze.call(e,s)&&s!==n&&Je(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Ye(t,s))||r.enumerable});return e},et=(e,t,n)=>($e(e,t,`default`),n&&$e(n,t,`default`));function tt(){let e=process.env.npm_config_user_agent??``,n=process.env.npm_execpath??``,r=(()=>{if(!process.argv[1])return``;try{return t.realpathSync(process.argv[1])}catch{return process.argv[1]}})();return e.includes(`pnpm`)?`pnpm`:e.includes(`bun`)?`bun`:e.startsWith(`npm/`)?`npm`:n.includes(`pnpm`)?`pnpm`:n.includes(`bun`)?`bun`:n.includes(`npm`)?`npm`:r.includes(`/.pnpm/`)||r.includes(`\\.pnpm\\`)?`pnpm`:r.includes(`/.bun/`)||r.includes(`\\bun\\`)?`bun`:`npm`}function nt(){let e=tt();return e===`pnpm`?`pnpx`:e===`bun`?`bunx`:`npx`}function rt(e){let t=tt();return t===`pnpm`?{args:[`add`,`--global`,`${e}@latest`],command:`pnpm`}:t===`bun`?{args:[`add`,`--global`,`${e}@latest`],command:`bun`}:{args:[`install`,`--global`,`${e}@latest`],command:`npm`}}var it=F((()=>{}));function at(e,t={}){if(xt())return;let n=lt(e,t);if(!n?.check||!n.current)return;let r=ht(n.key),i=gt(r),a=Date.now(),o=Math.max(0,t.interval??St);if((!i||a-i.checkedAt>=o)&&vt(r,a,i?.latest,t.binary),!(!i?.latest||!ct(i.latest,n.current)))return{current:n.current,latest:i.latest,name:n.name}}async function ot(e,t={}){let n=lt(e,t);if(!n?.check||!n.current)return;let r=await n.check({current:n.current,name:e,...n.package?{package:n.package}:void 0});!r||!pt(r)||_t(ht(n.key),{checkedAt:Date.now(),latest:r})}async function st(e,t={}){let n=lt(e,t);if(!n?.install)throw Error(`No update installer is configured for '${e}'.`);let r=gt(ht(n.key));return await n.install({...n.current?{current:n.current}:void 0,...r?.latest?{latest:r.latest}:void 0,name:e,...n.package?{package:n.package}:void 0}),{...n.command?{command:n.command}:void 0,...n.deferred?{deferred:!0}:void 0,name:n.name}}function ct(e,t){let n=pt(e),r=pt(t);if(!n||!r)return!1;for(let e of[`major`,`minor`,`patch`]){if(n[e]>r[e])return!0;if(n[e]<r[e])return!1}let i=n.prerelease,a=r.prerelease;if(i.length===0)return a.length>0;if(a.length===0)return!1;let o=Math.max(i.length,a.length);for(let e=0;e<o;e++){let t=i[e],n=a[e];if(t===void 0)return!1;if(n===void 0)return!0;if(t!==n)return typeof t==`bigint`&&typeof n==`string`?!1:typeof t==`string`&&typeof n==`bigint`||t>n}return!1}function lt(e,t){let n=ut(e),r=t.package??n?.name;if(r&&!mt(r))return;let i=t.version??n?.version,a=r?rt(r):void 0,o=t.check??(r?()=>ft(r):void 0),s=t.install??(a?()=>bt(a.command,a.args):void 0);if(!(!o&&!s))return{...o?{check:o}:void 0,...a&&!t.install?{command:`${a.command} ${a.args.join(` `)}`}:void 0,...i?{current:i}:void 0,...t.deferred?{deferred:!0}:void 0,...s?{install:s}:void 0,key:r??e,name:r??e,...r?{package:r}:void 0}}function ut(e){let n=(()=>{if(process.argv[1])try{return t.realpathSync(process.argv[1])}catch{return}})();if(!n)return;let r=c.dirname(n);for(;;){try{let n=JSON.parse(t.readFileSync(c.join(r,`package.json`),`utf8`));if(typeof n.name==`string`&&typeof n.version==`string`&&dt(n,e))return{name:n.name,version:n.version}}catch{}let n=c.dirname(r);if(n===r)return;r=n}}function dt(e,t){return e.name===t||typeof e.bin==`object`&&e.bin!==null&&t in e.bin?!0:typeof e.bin!=`string`||typeof e.name!=`string`?!1:e.name.split(`/`).pop()===t}async function ft(e){let t=process.env.npm_config_registry||`https://registry.npmjs.org`,n=t.endsWith(`/`)?t:`${t}/`,r=await fetch(new URL(encodeURIComponent(e),n),{headers:{accept:`application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*`},signal:AbortSignal.timeout(1e4)});if(!r.ok)return;let i=(await r.json())[`dist-tags`]?.latest;return typeof i==`string`?i:void 0}function pt(e){let t=e.match(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/);if(!t)return;let n=[];for(let e of t[4]?.split(`.`)??[]){if(!/^\d+$/.test(e)){n.push(e);continue}if(e.length>1&&e.startsWith(`0`))return;n.push(BigInt(e))}return{major:BigInt(t[1]),minor:BigInt(t[2]),patch:BigInt(t[3]),prerelease:n}}function mt(e){return/^(?:@[A-Za-z0-9][A-Za-z0-9._~-]*\/)?[A-Za-z0-9][A-Za-z0-9._~-]*$/.test(e)}function ht(e){let t=process.env.XDG_CACHE_HOME||c.join(b.homedir(),`.cache`);return c.join(t,`incur`,`updates`,`${encodeURIComponent(e)}.json`)}function gt(e){try{let n=JSON.parse(t.readFileSync(e,`utf8`));return typeof n.checkedAt!=`number`||n.latest!==void 0&&typeof n.latest!=`string`?void 0:n}catch{return}}function _t(e,n){t.mkdirSync(c.dirname(e),{recursive:!0}),t.writeFileSync(e,JSON.stringify(n)+`
2
- `)}function vt(e,t,n,r){let i=yt(r);if(i)try{_t(e,{checkedAt:t,...n?{latest:n}:void 0});let r=m.spawn(i.command,i.args,{detached:!0,stdio:`ignore`});r.once(`error`,()=>{}),r.unref()}catch{}}function yt(e){if(e)return{args:[Ct],command:process.execPath};let n=process.argv[1];if(n){if(n.startsWith(`/$bunfs/`))return{args:[Ct],command:process.execPath};try{if(t.realpathSync(n)===t.realpathSync(process.execPath))return{args:[Ct],command:process.execPath}}catch{}return{args:[...process.execArgv,n,Ct],command:process.execPath}}}function bt(e,t){return new Promise((n,r)=>{m.execFile(e,t,(e,t,i)=>{if(!e)return n();r(Error(i.trim()||t.trim()||e.message))})})}function xt(){return process.env.NO_UPDATE_NOTIFIER||process.env.npm_config_update_notifier===`false`?!0:!!(process.env.CI&&process.env.CI!==`false`)}var St,Ct,wt=F((()=>{it(),St=864e5,Ct=`--incur-update-check`}));async function Tt(e=process.argv.slice(2)){if(e[0]!==`--incur-binary-apply`)return process.platform===`win32`&&Lt&&Rt&&zt&&await jt(process.execPath),!1;if(process.platform!==`win32`)throw Error(`${It} is only supported on Windows.`);if(e.length!==2||!e[1])throw Error(`Invalid ${It} arguments.`);let t=Number(e[1]);if(!Number.isSafeInteger(t)||t<=0)throw Error(`Invalid ${It} arguments.`);return await Et(t),!0}async function Et(e){let n=Dt(process.execPath,e),r=!1;try{await Ot(e),await t.promises.rename(n.target,n.backup),r=!0,await t.promises.rename(n.staged,n.target)}catch(e){let i=e,a=`The installed executable remains at '${n.target}'.`;if(r)try{await t.promises.rename(n.backup,n.target),r=!1,a=`The previous executable was restored to '${n.target}'.`}catch(e){try{await t.promises.copyFile(n.backup,n.target,t.constants.COPYFILE_EXCL),a=`The previous executable was copied back to '${n.target}', and its backup remains at '${n.backup}'.`}catch(t){i=Error(`Binary update failed and '${n.target}' could not be restored. The previous executable remains at '${n.backup}': ${Pt(t)}`,{cause:e})}}throw await Mt(n,i,a),i}await Nt(n.backup),await Nt(n.error),await Nt(n.staged),await Nt(n.helper)}function Dt(e,t){let n=c.resolve(e),r=n.match(/^(.*)\.incur-handoff-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.exe$/i);if(!r?.[1]||!r[2])throw Error(`Invalid binary update handoff path.`);let i=r[1],a=i.toLowerCase().endsWith(`.exe`)?`.exe`:``;return{backup:`${i}.incur-backup-${r[2]}${a}`,error:`${i}.incur-error-${r[2]}.txt`,helper:n,parent:t,staged:`${i}.incur-new-${r[2]}${a}`,target:i}}async function Ot(e){let t=Date.now()+Ft;for(;kt(e);){if(Date.now()>=t)throw Error(`Timed out waiting for update process ${e} to exit.`);await At(100)}}function kt(e){try{return process.kill(e,0),!0}catch(e){return e.code!==`ESRCH`}}function At(e){return new Promise(t=>setTimeout(t,e))}async function jt(e){let n=c.dirname(e),r=`${c.basename(e)}.incur-handoff-`;try{let e=await t.promises.readdir(n);await Promise.all(e.filter(e=>e.startsWith(r)&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.exe$/i.test(e.slice(r.length))).map(e=>Nt(c.join(n,e))))}catch{}}async function Mt(e,n,r){let i=[`Binary update failed: ${Pt(n)}`,`Recovery: ${r}`,`Downloaded candidate: ${e.staged}`,`Previous executable backup: ${e.backup}`].join(`
3
- `);try{await t.promises.writeFile(e.error,`${i}\n`,{flag:`wx`,mode:384})}catch{}}async function Nt(e){try{await t.promises.unlink(e)}catch{}}function Pt(e){return e instanceof Error?e.message:String(e)}var Ft,It,Lt,Rt,zt,Bt=F((()=>{Ft=6e4,v.promisify(y.gunzip),It=`--incur-binary-apply`,Lt=typeof __INCUR_BINARY_NAME__==`string`&&__INCUR_BINARY_NAME__?__INCUR_BINARY_NAME__:void 0,Rt=typeof __INCUR_BINARY_TARGET__==`string`&&__INCUR_BINARY_TARGET__?__INCUR_BINARY_TARGET__:void 0,zt=typeof __INCUR_BINARY_VERSION__==`string`&&__INCUR_BINARY_VERSION__?__INCUR_BINARY_VERSION__:void 0}));function*Vt(e,t={}){if(!e)return;let n=Ht(t);for(let t of e.split(Zt))t&&(yield{segment:t,tokenCount:Ut(t,n)})}function Ht(e){return{defaultCharsPerToken:e.defaultCharsPerToken??Qt,languageConfigs:e.languageConfigs??tn}}function Ut(e,{languageConfigs:t,defaultCharsPerToken:n}){if(Xt.whitespace.test(e))return+!!Xt.structuredWhitespace.test(e);let r=Wt(e,t);return r===void 0?Xt.cjk.test(e)?Kt(e):Xt.numeric.test(e)?Math.ceil(e.length/3):e.length<=$t?1:Xt.punctuation.test(e)?Math.ceil(e.length/2):Math.ceil(e.length/n):Math.ceil(Gt(e)/r)}function Wt(e,t){for(let n of t)if(e.search(n.pattern)!==-1)return n.averageCharsPerToken}function Gt(e){return Array.from(e).length}function Kt(e){let t=0,n=0;for(let r of e){let e=r.codePointAt(0);e>=12352&&e<=12543?t++:n++}return n+Math.ceil(t/en)}function qt(e,t={}){if(!e)return 0;let n=0;for(let r of Vt(e,t))n+=r.tokenCount;return n}function Jt(e,t=0,n,r={}){if(!e)return``;let i=Vt(e,r),a=0;if(t<0||n!==void 0&&n<0){let e=Array.from(i);for(let{tokenCount:t}of e)a+=t;i=e}let o=t<0?Math.max(0,a+t):Math.max(0,t),s=n===void 0?1/0:n<0?Math.max(0,a+n):n;if(o>=s)return``;let c=[],l=0;for(let{segment:e,tokenCount:t}of i){if(l>=s)break;let n=Yt(e,l,t,o,s);n&&c.push(n),l+=t}return c.join(``)}function Yt(e,t,n,r,i){if(n===0)return t>=r&&t<i?e:``;let a=t+n;if(t>=i||a<=r)return``;let o=Math.max(0,r-t),s=Math.min(n,i-t);if(o===0&&s===n)return e;let c=Math.floor(o/n*e.length),l=Math.ceil(s/n*e.length);return e.slice(c,l)}var Xt,Zt,Qt,$t,en,tn,nn=F((()=>{Xt={whitespace:/^\s+$/,structuredWhitespace:/\n\s/,cjk:/[\u4E00-\u9FFF\u3400-\u4DBF\u3000-\u30FF\uFF00-\uFFEF\u2E80-\u2EFF\u31C0-\u31EF\u3200-\u32FF\u3300-\u33FF\uAC00-\uD7AF\u1100-\u11FF\u3130-\u318F\uA960-\uA97F\uD7B0-\uD7FF]/,numeric:/^\d+$/,punctuation:/[.,!?;(){}[\]<>:/\\|@#$%^&*+=`~_"-]/},Zt=RegExp(`(\\s+|${Xt.punctuation.source}+)`),Qt=6,$t=3,en=1.35,tn=[{pattern:/[äöüßẞ]/i,averageCharsPerToken:2.6},{pattern:/[éèêëàâîïôûùüÿçœæáíóúñ]/i,averageCharsPerToken:3},{pattern:/[ąćęłńóśźżěščřžýůúďťň]/i,averageCharsPerToken:2.5},{pattern:/[\u0430-\u044F\u0451]/i,averageCharsPerToken:4},{pattern:/[\u03AC-\u03CE]/i,averageCharsPerToken:2.75},{pattern:/^\p{Extended_Pictographic}[\p{Extended_Pictographic}\p{Emoji_Component}]*$/u,averageCharsPerToken:.75}]}));function rn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function an(e){return e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}function on(e,t){let n=e.length,r=t.length,i=Array.from({length:r+1},(e,t)=>t);for(let a=1;a<=n;a++){let n=i[0];i[0]=a;for(let o=1;o<=r;o++){let r=i[o];i[o]=e[a-1]===t[o-1]?n:1+Math.min(n,i[o],i[o-1]),n=r}}return i[r]}function sn(e,t){let n=e.length<=4?2:Math.floor(e.length/2),r=e.toLowerCase(),i=Array.isArray(t)?t:[...t],a,o=1/0;for(let e of i){let t=e.toLowerCase(),i=on(r,t),s;if(t.startsWith(r)&&t!==r)s=i;else if(t.includes(r))s=100+i;else if(i<=n)s=200+i;else continue;s<o&&(o=s,a=e)}return a}var cn=F((()=>{}));function ln(e,t){switch(e){case`bash`:return vn(t);case`zsh`:return yn(t);case`fish`:return bn(t);case`nushell`:return xn(t)}}function un(e,t,n,r,i){let a=n[r]??``,o={commands:e,leaf:t};for(let e=0;e<r;e++){let t=n[e];if(t.startsWith(`-`))continue;let r=o.commands.get(t);if(r&&(r._alias&&r.target&&(r=o.commands.get(r.target)),r)){if(r._group&&r.commands)o={commands:r.commands,leaf:r.root};else{o={commands:new Map,leaf:r};break}}}let s=[];if(a.startsWith(`-`)){let e=o.leaf;if(e?.options){let t=e.options.shape;for(let e of Object.keys(t)){let n=`--${an(e)}`;n.startsWith(a)&&s.push({value:n,description:gn(t[e])})}if(e.alias)for(let[n,r]of Object.entries(e.alias)){let e=`-${r}`;if(e.startsWith(a)){let r=gn(t[n]);s.push({value:e,description:r})}}}if(i){let e=i.schema.shape;for(let t of Object.keys(e)){let n=`--${an(t)}`;n.startsWith(a)&&!s.some(e=>e.value===n)&&s.push({value:n,description:gn(e[t])})}if(i.alias)for(let[t,n]of Object.entries(i.alias)){let r=`-${n}`;if(r.startsWith(a)&&!s.some(e=>e.value===r)){let n=gn(e[t]);s.push({value:r,description:n})}}}return s}if(r>0){let e=n[r-1],t=o.leaf;if(e.startsWith(`-`)){if(t?.options){let n=fn(e,t);if(n){let e=mn(n,t.options);if(e){for(let t of e)t.startsWith(a)&&s.push({value:t});return s}if(!pn(n,t.options))return s}}if(i){let t=fn(e,{options:i.schema,alias:i.alias});if(t){let e=mn(t,i.schema);if(e){for(let t of e)t.startsWith(a)&&s.push({value:t});return s}if(!pn(t,i.schema))return s}}}}for(let[e,t]of o.commands)t._alias||e.startsWith(a)&&s.push({value:e,description:t.description,...t._group?{noSpace:!0}:void 0});return s}function dn(e,t){switch(e){case`bash`:return t.map(e=>e.noSpace?`${e.value}\x01`:e.value).join(`\v`);case`zsh`:return t.map(e=>{let t=e.value.replaceAll(`:`,`\\:`);return e.description?`${t}:${e.description}`:t}).join(`
1
+ import{once as e}from"node:events";import*as t from"node:fs";import n,{existsSync as r,mkdirSync as i,readFileSync as a,writeFileSync as o}from"node:fs";import{createRequire as s}from"node:module";import*as c from"node:path";import l,{dirname as u,join as d}from"node:path";import{z as f,z as p}from"zod";import*as m from"node:child_process";import{execFile as h}from"node:child_process";import{createHash as g,randomUUID as _}from"node:crypto";import*as v from"node:util";import*as y from"node:zlib";import*as b from"node:os";import x,{homedir as S}from"node:os";import*as C from"node:fs/promises";import w from"node:fs/promises";import{PassThrough as T}from"node:stream";import{fileURLToPath as ee,pathToFileURL as E}from"node:url";import*as D from"zod/v4";import{AbiParameters as O,Base64 as k,Bytes as A,Hash as te,Hex as ne,Json as j}from"ox";import{createClient as M,createTransport as re,custom as ie,encodeFunctionData as ae,erc20Abi as oe,formatUnits as se,getAddress as N,hashTypedData as ce,http as le,isAddress as ue,isAddressEqual as de,keccak256 as fe,parseAbi as pe,parseUnits as P,zeroAddress as me}from"viem";import{generatePrivateKey as he,parseAccount as ge,privateKeyToAccount as _e}from"viem/accounts";import{tempo as ve,tempoModerato as ye}from"viem/tempo/chains";import{z as be}from"zod/mini";import{createParser as F}from"eventsource-parser";import*as xe from"node:readline";import{ousd as Se,pathusd as Ce,usdce as we}from"viem/tokens";import{call as Te,prepareTransactionRequest as Ee,readContract as De,sendCallsSync as Oe,sendTransactionSync as ke,signTransaction as Ae,signTypedData as je,waitForTransactionReceipt as Me}from"viem/actions";import{Abis as Ne,Account as Pe,Actions as Fe,Addresses as Ie,TokenId as Le,Transaction as Re,withFeePayer as ze}from"viem/tempo";import*as Be from"viem/chains";import{tempo as Ve}from"viem/chains";import{Channel as He,KeyAuthorization as Ue,SignatureEnvelope as We,TempoAddress as Ge,TxEnvelopeTempo as Ke}from"ox/tempo";var qe=Object.defineProperty,Je=Object.getOwnPropertyDescriptor,Ye=Object.getOwnPropertyNames,Xe=Object.prototype.hasOwnProperty,I=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},Ze=(e,t)=>{let n={};for(var r in e)qe(n,r,{get:e[r],enumerable:!0});return t||qe(n,Symbol.toStringTag,{value:`Module`}),n},Qe=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=Ye(t),a=0,o=i.length,s;a<o;a++)s=i[a],!Xe.call(e,s)&&s!==n&&qe(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=Je(t,s))||r.enumerable});return e},$e=(e,t,n)=>(Qe(e,t,`default`),n&&Qe(n,t,`default`));function et(){let e=process.env.npm_config_user_agent??``,n=process.env.npm_execpath??``,r=(()=>{if(!process.argv[1])return``;try{return t.realpathSync(process.argv[1])}catch{return process.argv[1]}})();return e.includes(`pnpm`)?`pnpm`:e.includes(`bun`)?`bun`:e.startsWith(`npm/`)?`npm`:n.includes(`pnpm`)?`pnpm`:n.includes(`bun`)?`bun`:n.includes(`npm`)?`npm`:r.includes(`/.pnpm/`)||r.includes(`\\.pnpm\\`)?`pnpm`:r.includes(`/.bun/`)||r.includes(`\\bun\\`)?`bun`:`npm`}function tt(){let e=et();return e===`pnpm`?`pnpx`:e===`bun`?`bunx`:`npx`}function nt(e){let t=et();return t===`pnpm`?{args:[`add`,`--global`,`${e}@latest`],command:`pnpm`}:t===`bun`?{args:[`add`,`--global`,`${e}@latest`],command:`bun`}:{args:[`install`,`--global`,`${e}@latest`],command:`npm`}}var rt=I((()=>{}));function it(e,t={}){if(bt())return;let n=ct(e,t);if(!n?.check||!n.current)return;let r=mt(n.key),i=ht(r),a=Date.now(),o=Math.max(0,t.interval??xt);if((!i||a-i.checkedAt>=o)&&_t(r,a,i?.latest,t.binary),!(!i?.latest||!st(i.latest,n.current)))return{current:n.current,latest:i.latest,name:n.name}}async function at(e,t={}){let n=ct(e,t);if(!n?.check||!n.current)return;let r=await n.check({current:n.current,name:e,...n.package?{package:n.package}:void 0});!r||!ft(r)||gt(mt(n.key),{checkedAt:Date.now(),latest:r})}async function ot(e,t={}){let n=ct(e,t);if(!n?.install)throw Error(`No update installer is configured for '${e}'.`);let r=ht(mt(n.key));return await n.install({...n.current?{current:n.current}:void 0,...r?.latest?{latest:r.latest}:void 0,name:e,...n.package?{package:n.package}:void 0}),{...n.command?{command:n.command}:void 0,...n.deferred?{deferred:!0}:void 0,name:n.name}}function st(e,t){let n=ft(e),r=ft(t);if(!n||!r)return!1;for(let e of[`major`,`minor`,`patch`]){if(n[e]>r[e])return!0;if(n[e]<r[e])return!1}let i=n.prerelease,a=r.prerelease;if(i.length===0)return a.length>0;if(a.length===0)return!1;let o=Math.max(i.length,a.length);for(let e=0;e<o;e++){let t=i[e],n=a[e];if(t===void 0)return!1;if(n===void 0)return!0;if(t!==n)return typeof t==`bigint`&&typeof n==`string`?!1:typeof t==`string`&&typeof n==`bigint`||t>n}return!1}function ct(e,t){let n=lt(e),r=t.package??n?.name;if(r&&!pt(r))return;let i=t.version??n?.version,a=r?nt(r):void 0,o=t.check??(r?()=>dt(r):void 0),s=t.install??(a?()=>yt(a.command,a.args):void 0);if(!(!o&&!s))return{...o?{check:o}:void 0,...a&&!t.install?{command:`${a.command} ${a.args.join(` `)}`}:void 0,...i?{current:i}:void 0,...t.deferred?{deferred:!0}:void 0,...s?{install:s}:void 0,key:r??e,name:r??e,...r?{package:r}:void 0}}function lt(e){let n=(()=>{if(process.argv[1])try{return t.realpathSync(process.argv[1])}catch{return}})();if(!n)return;let r=c.dirname(n);for(;;){try{let n=JSON.parse(t.readFileSync(c.join(r,`package.json`),`utf8`));if(typeof n.name==`string`&&typeof n.version==`string`&&ut(n,e))return{name:n.name,version:n.version}}catch{}let n=c.dirname(r);if(n===r)return;r=n}}function ut(e,t){return e.name===t||typeof e.bin==`object`&&e.bin!==null&&t in e.bin?!0:typeof e.bin!=`string`||typeof e.name!=`string`?!1:e.name.split(`/`).pop()===t}async function dt(e){let t=process.env.npm_config_registry||`https://registry.npmjs.org`,n=t.endsWith(`/`)?t:`${t}/`,r=await fetch(new URL(encodeURIComponent(e),n),{headers:{accept:`application/vnd.npm.install-v1+json; q=1.0, application/json; q=0.8, */*`},signal:AbortSignal.timeout(1e4)});if(!r.ok)return;let i=(await r.json())[`dist-tags`]?.latest;return typeof i==`string`?i:void 0}function ft(e){let t=e.match(/^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)(?:-([0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*))?(?:\+[0-9A-Za-z-]+(?:\.[0-9A-Za-z-]+)*)?$/);if(!t)return;let n=[];for(let e of t[4]?.split(`.`)??[]){if(!/^\d+$/.test(e)){n.push(e);continue}if(e.length>1&&e.startsWith(`0`))return;n.push(BigInt(e))}return{major:BigInt(t[1]),minor:BigInt(t[2]),patch:BigInt(t[3]),prerelease:n}}function pt(e){return/^(?:@[A-Za-z0-9][A-Za-z0-9._~-]*\/)?[A-Za-z0-9][A-Za-z0-9._~-]*$/.test(e)}function mt(e){let t=process.env.XDG_CACHE_HOME||c.join(b.homedir(),`.cache`);return c.join(t,`incur`,`updates`,`${encodeURIComponent(e)}.json`)}function ht(e){try{let n=JSON.parse(t.readFileSync(e,`utf8`));return typeof n.checkedAt!=`number`||n.latest!==void 0&&typeof n.latest!=`string`?void 0:n}catch{return}}function gt(e,n){t.mkdirSync(c.dirname(e),{recursive:!0}),t.writeFileSync(e,JSON.stringify(n)+`
2
+ `)}function _t(e,t,n,r){let i=vt(r);if(i)try{gt(e,{checkedAt:t,...n?{latest:n}:void 0});let r=m.spawn(i.command,i.args,{detached:!0,stdio:`ignore`});r.once(`error`,()=>{}),r.unref()}catch{}}function vt(e){if(e)return{args:[St],command:process.execPath};let n=process.argv[1];if(n){if(n.startsWith(`/$bunfs/`))return{args:[St],command:process.execPath};try{if(t.realpathSync(n)===t.realpathSync(process.execPath))return{args:[St],command:process.execPath}}catch{}return{args:[...process.execArgv,n,St],command:process.execPath}}}function yt(e,t){return new Promise((n,r)=>{m.execFile(e,t,(e,t,i)=>{if(!e)return n();r(Error(i.trim()||t.trim()||e.message))})})}function bt(){return process.env.NO_UPDATE_NOTIFIER||process.env.npm_config_update_notifier===`false`?!0:!!(process.env.CI&&process.env.CI!==`false`)}var xt,St,Ct=I((()=>{rt(),xt=864e5,St=`--incur-update-check`}));async function wt(e=process.argv.slice(2)){if(e[0]!==`--incur-binary-apply`)return process.platform===`win32`&&It&&Lt&&Rt&&await At(process.execPath),!1;if(process.platform!==`win32`)throw Error(`${Ft} is only supported on Windows.`);if(e.length!==2||!e[1])throw Error(`Invalid ${Ft} arguments.`);let t=Number(e[1]);if(!Number.isSafeInteger(t)||t<=0)throw Error(`Invalid ${Ft} arguments.`);return await Tt(t),!0}async function Tt(e){let n=Et(process.execPath,e),r=!1;try{await Dt(e),await t.promises.rename(n.target,n.backup),r=!0,await t.promises.rename(n.staged,n.target)}catch(e){let i=e,a=`The installed executable remains at '${n.target}'.`;if(r)try{await t.promises.rename(n.backup,n.target),r=!1,a=`The previous executable was restored to '${n.target}'.`}catch(e){try{await t.promises.copyFile(n.backup,n.target,t.constants.COPYFILE_EXCL),a=`The previous executable was copied back to '${n.target}', and its backup remains at '${n.backup}'.`}catch(t){i=Error(`Binary update failed and '${n.target}' could not be restored. The previous executable remains at '${n.backup}': ${Nt(t)}`,{cause:e})}}throw await jt(n,i,a),i}await Mt(n.backup),await Mt(n.error),await Mt(n.staged),await Mt(n.helper)}function Et(e,t){let n=c.resolve(e),r=n.match(/^(.*)\.incur-handoff-([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})\.exe$/i);if(!r?.[1]||!r[2])throw Error(`Invalid binary update handoff path.`);let i=r[1],a=i.toLowerCase().endsWith(`.exe`)?`.exe`:``;return{backup:`${i}.incur-backup-${r[2]}${a}`,error:`${i}.incur-error-${r[2]}.txt`,helper:n,parent:t,staged:`${i}.incur-new-${r[2]}${a}`,target:i}}async function Dt(e){let t=Date.now()+Pt;for(;Ot(e);){if(Date.now()>=t)throw Error(`Timed out waiting for update process ${e} to exit.`);await kt(100)}}function Ot(e){try{return process.kill(e,0),!0}catch(e){return e.code!==`ESRCH`}}function kt(e){return new Promise(t=>setTimeout(t,e))}async function At(e){let n=c.dirname(e),r=`${c.basename(e)}.incur-handoff-`;try{let e=await t.promises.readdir(n);await Promise.all(e.filter(e=>e.startsWith(r)&&/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\.exe$/i.test(e.slice(r.length))).map(e=>Mt(c.join(n,e))))}catch{}}async function jt(e,n,r){let i=[`Binary update failed: ${Nt(n)}`,`Recovery: ${r}`,`Downloaded candidate: ${e.staged}`,`Previous executable backup: ${e.backup}`].join(`
3
+ `);try{await t.promises.writeFile(e.error,`${i}\n`,{flag:`wx`,mode:384})}catch{}}async function Mt(e){try{await t.promises.unlink(e)}catch{}}function Nt(e){return e instanceof Error?e.message:String(e)}var Pt,Ft,It,Lt,Rt,zt=I((()=>{Pt=6e4,v.promisify(y.gunzip),Ft=`--incur-binary-apply`,It=typeof __INCUR_BINARY_NAME__==`string`&&__INCUR_BINARY_NAME__?__INCUR_BINARY_NAME__:void 0,Lt=typeof __INCUR_BINARY_TARGET__==`string`&&__INCUR_BINARY_TARGET__?__INCUR_BINARY_TARGET__:void 0,Rt=typeof __INCUR_BINARY_VERSION__==`string`&&__INCUR_BINARY_VERSION__?__INCUR_BINARY_VERSION__:void 0}));function*Bt(e,t={}){if(!e)return;let n=Vt(t);for(let t of e.split(Xt))t&&(yield{segment:t,tokenCount:Ht(t,n)})}function Vt(e){return{defaultCharsPerToken:e.defaultCharsPerToken??Zt,languageConfigs:e.languageConfigs??en}}function Ht(e,{languageConfigs:t,defaultCharsPerToken:n}){if(Yt.whitespace.test(e))return+!!Yt.structuredWhitespace.test(e);let r=Ut(e,t);return r===void 0?Yt.cjk.test(e)?Gt(e):Yt.numeric.test(e)?Math.ceil(e.length/3):e.length<=Qt?1:Yt.punctuation.test(e)?Math.ceil(e.length/2):Math.ceil(e.length/n):Math.ceil(Wt(e)/r)}function Ut(e,t){for(let n of t)if(e.search(n.pattern)!==-1)return n.averageCharsPerToken}function Wt(e){return Array.from(e).length}function Gt(e){let t=0,n=0;for(let r of e){let e=r.codePointAt(0);e>=12352&&e<=12543?t++:n++}return n+Math.ceil(t/$t)}function Kt(e,t={}){if(!e)return 0;let n=0;for(let r of Bt(e,t))n+=r.tokenCount;return n}function qt(e,t=0,n,r={}){if(!e)return``;let i=Bt(e,r),a=0;if(t<0||n!==void 0&&n<0){let e=Array.from(i);for(let{tokenCount:t}of e)a+=t;i=e}let o=t<0?Math.max(0,a+t):Math.max(0,t),s=n===void 0?1/0:n<0?Math.max(0,a+n):n;if(o>=s)return``;let c=[],l=0;for(let{segment:e,tokenCount:t}of i){if(l>=s)break;let n=Jt(e,l,t,o,s);n&&c.push(n),l+=t}return c.join(``)}function Jt(e,t,n,r,i){if(n===0)return t>=r&&t<i?e:``;let a=t+n;if(t>=i||a<=r)return``;let o=Math.max(0,r-t),s=Math.min(n,i-t);if(o===0&&s===n)return e;let c=Math.floor(o/n*e.length),l=Math.ceil(s/n*e.length);return e.slice(c,l)}var Yt,Xt,Zt,Qt,$t,en,tn=I((()=>{Yt={whitespace:/^\s+$/,structuredWhitespace:/\n\s/,cjk:/[\u4E00-\u9FFF\u3400-\u4DBF\u3000-\u30FF\uFF00-\uFFEF\u2E80-\u2EFF\u31C0-\u31EF\u3200-\u32FF\u3300-\u33FF\uAC00-\uD7AF\u1100-\u11FF\u3130-\u318F\uA960-\uA97F\uD7B0-\uD7FF]/,numeric:/^\d+$/,punctuation:/[.,!?;(){}[\]<>:/\\|@#$%^&*+=`~_"-]/},Xt=RegExp(`(\\s+|${Yt.punctuation.source}+)`),Zt=6,Qt=3,$t=1.35,en=[{pattern:/[äöüßẞ]/i,averageCharsPerToken:2.6},{pattern:/[éèêëàâîïôûùüÿçœæáíóúñ]/i,averageCharsPerToken:3},{pattern:/[ąćęłńóśźżěščřžýůúďťň]/i,averageCharsPerToken:2.5},{pattern:/[\u0430-\u044F\u0451]/i,averageCharsPerToken:4},{pattern:/[\u03AC-\u03CE]/i,averageCharsPerToken:2.75},{pattern:/^\p{Extended_Pictographic}[\p{Extended_Pictographic}\p{Emoji_Component}]*$/u,averageCharsPerToken:.75}]}));function nn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function rn(e){return e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`)}function an(e,t){let n=e.length,r=t.length,i=Array.from({length:r+1},(e,t)=>t);for(let a=1;a<=n;a++){let n=i[0];i[0]=a;for(let o=1;o<=r;o++){let r=i[o];i[o]=e[a-1]===t[o-1]?n:1+Math.min(n,i[o],i[o-1]),n=r}}return i[r]}function on(e,t){let n=e.length<=4?2:Math.floor(e.length/2),r=e.toLowerCase(),i=Array.isArray(t)?t:[...t],a,o=1/0;for(let e of i){let t=e.toLowerCase(),i=an(r,t),s;if(t.startsWith(r)&&t!==r)s=i;else if(t.includes(r))s=100+i;else if(i<=n)s=200+i;else continue;s<o&&(o=s,a=e)}return a}var sn=I((()=>{}));function cn(e,t){switch(e){case`bash`:return _n(t);case`zsh`:return vn(t);case`fish`:return yn(t);case`nushell`:return bn(t)}}function ln(e,t,n,r,i){let a=n[r]??``,o={commands:e,leaf:t};for(let e=0;e<r;e++){let t=n[e];if(t.startsWith(`-`))continue;let r=o.commands.get(t);if(r&&(r._alias&&r.target&&(r=o.commands.get(r.target)),r)){if(r._group&&r.commands)o={commands:r.commands,leaf:r.root};else{o={commands:new Map,leaf:r};break}}}let s=[];if(a.startsWith(`-`)){let e=o.leaf;if(e?.options){let t=e.options.shape;for(let e of Object.keys(t)){let n=`--${rn(e)}`;n.startsWith(a)&&s.push({value:n,description:hn(t[e])})}if(e.alias)for(let[n,r]of Object.entries(e.alias)){let e=`-${r}`;if(e.startsWith(a)){let r=hn(t[n]);s.push({value:e,description:r})}}}if(i){let e=i.schema.shape;for(let t of Object.keys(e)){let n=`--${rn(t)}`;n.startsWith(a)&&!s.some(e=>e.value===n)&&s.push({value:n,description:hn(e[t])})}if(i.alias)for(let[t,n]of Object.entries(i.alias)){let r=`-${n}`;if(r.startsWith(a)&&!s.some(e=>e.value===r)){let n=hn(e[t]);s.push({value:r,description:n})}}}return s}if(r>0){let e=n[r-1],t=o.leaf;if(e.startsWith(`-`)){if(t?.options){let n=dn(e,t);if(n){let e=pn(n,t.options);if(e){for(let t of e)t.startsWith(a)&&s.push({value:t});return s}if(!fn(n,t.options))return s}}if(i){let t=dn(e,{options:i.schema,alias:i.alias});if(t){let e=pn(t,i.schema);if(e){for(let t of e)t.startsWith(a)&&s.push({value:t});return s}if(!fn(t,i.schema))return s}}}}for(let[e,t]of o.commands)t._alias||e.startsWith(a)&&s.push({value:e,description:t.description,...t._group?{noSpace:!0}:void 0});return s}function un(e,t){switch(e){case`bash`:return t.map(e=>e.noSpace?`${e.value}\x01`:e.value).join(`\v`);case`zsh`:return t.map(e=>{let t=e.value.replaceAll(`:`,`\\:`);return e.description?`${t}:${e.description}`:t}).join(`
4
4
  `);case`fish`:return t.map(e=>e.description?`${e.value}\t${e.description}`:e.value).join(`
5
- `);case`nushell`:{let e=t.map(e=>{let t={value:e.value};return e.description&&(t.description=e.description),t});return JSON.stringify(e)}}}function fn(e,t){if(!t.options)return;let n=new Set(Object.keys(t.options.shape)),r=new Map;for(let e of n){let t=e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`);t!==e&&r.set(t,e)}if(e.startsWith(`--`)){let t=e.slice(2),i=r.get(t)??t;return n.has(i)?i:void 0}if(e.startsWith(`-`)&&e.length===2&&t.alias){let n=e.slice(1);for(let[e,r]of Object.entries(t.alias))if(r===n)return e}}function pn(e,t){let n=t.shape[e];return n?typeof n.meta==`function`&&n.meta()?.count===!0||hn(n).constructor.name===`ZodBoolean`:!1}function mn(e,t){let n=t.shape[e];if(!n)return;let r=hn(n);if(r.constructor.name===`ZodEnum`)return Object.values(r._zod.def.entries);if(r.constructor.name===`ZodNativeEnum`)return Object.keys(r._zod.def.values)}function hn(e){let t=e;for(;t._zod?.def?.innerType;)t=t._zod.def.innerType;return t}function gn(e){if(e)return e.description}function _n(e){return e.replace(/[^a-zA-Z0-9_]/g,`_`)}function vn(e){let t=_n(e);return`_incur_complete_${t}() {
5
+ `);case`nushell`:{let e=t.map(e=>{let t={value:e.value};return e.description&&(t.description=e.description),t});return JSON.stringify(e)}}}function dn(e,t){if(!t.options)return;let n=new Set(Object.keys(t.options.shape)),r=new Map;for(let e of n){let t=e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`);t!==e&&r.set(t,e)}if(e.startsWith(`--`)){let t=e.slice(2),i=r.get(t)??t;return n.has(i)?i:void 0}if(e.startsWith(`-`)&&e.length===2&&t.alias){let n=e.slice(1);for(let[e,r]of Object.entries(t.alias))if(r===n)return e}}function fn(e,t){let n=t.shape[e];return n?typeof n.meta==`function`&&n.meta()?.count===!0||mn(n).constructor.name===`ZodBoolean`:!1}function pn(e,t){let n=t.shape[e];if(!n)return;let r=mn(n);if(r.constructor.name===`ZodEnum`)return Object.values(r._zod.def.entries);if(r.constructor.name===`ZodNativeEnum`)return Object.keys(r._zod.def.values)}function mn(e){let t=e;for(;t._zod?.def?.innerType;)t=t._zod.def.innerType;return t}function hn(e){if(e)return e.description}function gn(e){return e.replace(/[^a-zA-Z0-9_]/g,`_`)}function _n(e){let t=gn(e);return`_incur_complete_${t}() {
6
6
  local IFS=$'\\013'
7
7
  local _COMPLETE_INDEX=\${COMP_CWORD}
8
8
  local _completions
@@ -29,7 +29,7 @@ import{once as e}from"node:events";import*as t from"node:fs";import n,{existsSyn
29
29
  compopt -o nospace
30
30
  fi
31
31
  }
32
- complete -o default -o bashdefault -o nosort -F _incur_complete_${t} ${e}`}function yn(e){let t=_n(e);return`#compdef ${e}
32
+ complete -o default -o bashdefault -o nosort -F _incur_complete_${t} ${e}`}function vn(e){let t=gn(e);return`#compdef ${e}
33
33
  _incur_complete_${t}() {
34
34
  local completions=("\${(@f)$(
35
35
  export _COMPLETE_INDEX=$(( CURRENT - 1 ))
@@ -40,64 +40,64 @@ _incur_complete_${t}() {
40
40
  _describe 'values' completions -S ''
41
41
  fi
42
42
  }
43
- compdef _incur_complete_${t} ${e}`}function bn(e){return`complete --keep-order --exclusive --command ${e} \\
44
- --arguments "(COMPLETE=fish ${e} -- (commandline --current-process --tokenize --cut-at-cursor) (commandline --current-token))"`}function xn(e){return`# External completer for ${e}
43
+ compdef _incur_complete_${t} ${e}`}function yn(e){return`complete --keep-order --exclusive --command ${e} \\
44
+ --arguments "(COMPLETE=fish ${e} -- (commandline --current-process --tokenize --cut-at-cursor) (commandline --current-token))"`}function bn(e){return`# External completer for ${e}
45
45
  # Add to $env.config.completions.external.completer or use in a dispatch completer.
46
- let _incur_complete_${_n(e)} = {|spans|
46
+ let _incur_complete_${gn(e)} = {|spans|
47
47
  COMPLETE=nushell ${e} -- ...$spans | from json
48
- }`}var Sn=F((()=>{cn()}));function Cn(e,t){if(t){let n=e?.cause;for(;n;){if(t(n))return n;n=n?.cause}return}let n=e;for(;n?.cause;)n=n.cause;return n}var wn,I,Tn,En,Dn=F((()=>{wn=class extends Error{name=`Incur.BaseError`;shortMessage;details;constructor(e,t={}){let n=t.cause instanceof Error?t.cause.message:void 0,r=n?`${e}\n\nDetails: ${n}`:e;super(r,t.cause?{cause:t.cause}:void 0),this.shortMessage=e,this.details=n}walk(e){return Cn(this,e)}},I=class extends wn{name=`Incur.IncurError`;code;hint;retryable;exitCode;constructor(e){super(e.message,e.cause?{cause:e.cause}:void 0),this.code=e.code,this.hint=e.hint,this.retryable=e.retryable??!1,this.exitCode=e.exitCode}},Tn=class extends wn{name=`Incur.ValidationError`;fieldErrors;constructor(e){super(e.message,e.cause?{cause:e.cause}:void 0),this.fieldErrors=e.fieldErrors??[]}},En=class extends wn{name=`Incur.ParseError`;constructor(e){super(e.message,e.cause?{cause:e.cause}:void 0)}}}));function On(e){let t=[],n=new Headers,r=new URLSearchParams,i,a,o=0;for(;o<e.length;){let n=e[o];if(n.startsWith(`--`)){let t=n.indexOf(`=`);if(t!==-1){let e=n.slice(2,t),i=n.slice(t+1);Nn.has(e)?s(e,i):r.set(e,i),o++}else{let t=n.slice(2),i=e[o+1];if(i===void 0)throw Error(`Missing value for --${t}`);Nn.has(t)?s(t,i):r.set(t,i),o+=2}}else if(n.startsWith(`-`)&&n.length===2){let t=n[1],r=Pn[t];if(r){let n=e[o+1];if(n===void 0)throw Error(`Missing value for -${t}`);s(r,n),o+=2}else o++}else t.push(n),o++}function s(e,t){if(e===`method`)i=t.toUpperCase();else if(e===`body`||e===`data`)a=t;else if(e===`header`){let e=t.indexOf(`:`);if(e!==-1){let r=t.slice(0,e).trim(),i=t.slice(e+1).trim();n.set(r,i)}}}return{path:t.length>0?`/${t.join(`/`)}`:`/`,method:i??(a===void 0?`GET`:`POST`),headers:n,body:a,query:r}}function kn(e){let t=new URL(e.path,`http://localhost`);e.query.forEach((e,n)=>t.searchParams.set(n,e));let n={method:e.method,headers:e.headers};return e.body!==void 0&&(n.body=e.body,e.headers.has(`content-type`)||e.headers.set(`content-type`,`application/json`)),new Request(t.toString(),n)}function An(e){return e.body!==null&&e.headers.get(`content-type`)===`application/x-ndjson`}async function*jn(e){let t=e.body.getReader(),n=new TextDecoder,r=``;for(;;){let{value:e,done:i}=await t.read();if(i)break;r+=n.decode(e,{stream:!0});let a;for(;(a=r.indexOf(`
49
- `))!==-1;){let e=r.slice(0,a).trim();if(r=r.slice(a+1),e.length!==0)try{yield JSON.parse(e)}catch{yield e}}}let i=r.trim();if(i.length>0)try{yield JSON.parse(i)}catch{yield i}}async function Mn(e){let t=await e.text(),n;try{n=JSON.parse(t)}catch{n=t}return{ok:e.ok,status:e.status,data:n,headers:e.headers}}var Nn,Pn,Fn=F((()=>{Nn=new Set([`method`,`body`,`data`,`header`]),Pn={X:`method`,d:`data`,H:`header`}}));function In(e){let t=[],n=[],r=``,i=0;for(let t=0;t<e.length;t++){let a=e[t];a===`[`?i++:a===`]`&&i--,a===`,`&&i===0?(n.push(r),r=``):r+=a}r&&n.push(r);for(let e of n){let n=[],r=e;for(;r.length>0;){let e=r.indexOf(`[`);if(e===-1){for(let e of r.split(`.`))e&&n.push({key:e});break}let t=r.slice(0,e);for(let e of t.split(`.`))e&&n.push({key:e});let i=r.indexOf(`]`,e),[a,o]=r.slice(e+1,i).split(`,`);n.push({start:Number(a),end:Number(o)}),r=r.slice(i+1),r.startsWith(`.`)&&(r=r.slice(1))}t.push(n)}return t}function Ln(e,t){if(t.length===0)return e;if(t.length===1&&t[0].length===1&&`key`in t[0][0]){let n=t[0][0].key;if(Array.isArray(e))return e.map(e=>Ln(e,t));if(typeof e==`object`&&e){let t=e[n];return typeof t!=`object`||!t?t:{[n]:t}}return}if(Array.isArray(e))return e.map(e=>Ln(e,t));let n={};for(let r of t)Rn(n,e,r,0);return n}function Rn(e,t,n,r){if(r>=n.length||typeof t!=`object`||!t)return;let i=n[r];if(`key`in i){let a=t[i.key];if(a===void 0)return;if(r+1>=n.length){e[i.key]=a;return}let o=n[r+1];if(`start`in o){if(!Array.isArray(a))return;let t=a.slice(o.start,o.end);if(r+2>=n.length){e[i.key]=t;return}e[i.key]=t.map(e=>{let t={};return Rn(t,e,n,r+2),t});return}if(typeof a!=`object`||!a)return;(!e[i.key]||typeof e[i.key]!=`object`)&&(e[i.key]={}),Rn(e[i.key],a,n,r+1);return}}var zn=F((()=>{}));function Bn(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\n/g,`\\n`).replace(/\r/g,`\\r`).replace(/\t/g,`\\t`).replace(/[\u0000-\u001F]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}function Vn(e){return e===`true`||e===`false`||e===`null`}function Hn(e,t,n){if(t===`__proto__`){Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0});return}e[t]=n}function Un(e){if(e===null)return null;if(typeof e==`object`&&e&&`toJSON`in e&&typeof e.toJSON==`function`){let t=e.toJSON();if(t!==e)return Un(t)}if(typeof e==`string`||typeof e==`boolean`)return e;if(typeof e==`number`)return Object.is(e,-0)?0:Number.isFinite(e)?e:null;if(typeof e==`bigint`)return e>=-(2**53-1)&&e<=2**53-1?Number(e):e.toString();if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(Un);if(e instanceof Set)return Array.from(e).map(Un);if(e instanceof Map)return Object.fromEntries(Array.from(e,([e,t])=>[String(e),Un(t)]));if(Jn(e)){let t={};for(let n in e)Object.hasOwn(e,n)&&Hn(t,n,Un(e[n]));return t}return null}function Wn(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function Gn(e){return Array.isArray(e)}function Kn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function qn(e){return Object.keys(e).length===0}function Jn(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function Yn(e){return e.length===0||e.every(e=>Wn(e))}function Xn(e){return e.length===0||e.every(e=>Gn(e))}function Zn(e){return e.length===0||e.every(e=>Kn(e))}function Qn(e){return/^[A-Z_][\w.]*$/i.test(e)}function $n(e){return/^[A-Z_]\w*$/i.test(e)}function er(e,t=Pr){return!(!e||e!==e.trim()||Vn(e)||tr(e)||e.includes(`:`)||e.includes(`"`)||e.includes(`\\`)||/[[\]{}]/.test(e)||/[\u0000-\u001F]/.test(e)||e.includes(t)||e.startsWith(`-`))}function tr(e){return Fr.test(e)||Ir.test(e)}function nr(e,t,n,r,i,a,o){if(r.keyFolding!==`safe`||!Kn(t))return;let{segments:s,tail:c,leafValue:l}=rr(e,t,o??r.flattenDepth);if(s.length<2||!s.every(e=>$n(e)))return;let u=ir(s),d=a?`${a}.${u}`:u;if(!n.includes(u)&&!(i&&i.has(d)))return{foldedKey:u,remainder:c,leafValue:l,segmentCount:s.length}}function rr(e,t,n){let r=[e],i=t;for(;r.length<n&&Kn(i);){let e=Object.keys(i);if(e.length!==1)break;let t=e[0],n=i[t];r.push(t),i=n}return!Kn(i)||qn(i)?{segments:r,tail:void 0,leafValue:i}:{segments:r,tail:i,leafValue:i}}function ir(e){return e.join(`.`)}function ar(e,t){return e===null?Mr:typeof e==`boolean`||typeof e==`number`?String(e):or(e,t)}function or(e,t=Pr){return er(e,t)?e:`"${Bn(e)}"`}function sr(e){return Qn(e)?e:`"${Bn(e)}"`}function cr(e,t=Pr){return e.map(e=>ar(e,t)).join(t)}function lr(e,t){let n=t?.key,r=t?.fields,i=t?.delimiter??`,`,a=``;if(n!=null&&(a+=sr(n)),a+=`[${e}${i===Pr?``:i}]`,r){let e=r.map(e=>sr(e));a+=`{${e.join(i)}}`}return a+=`:`,a}function*ur(e,t,n){if(Wn(e)){let n=ar(e,t.delimiter);n!==``&&(yield n);return}Gn(e)?yield*pr(void 0,e,n,t):Kn(e)&&(yield*dr(e,n,t))}function*dr(e,t,n,r,i,a){let o=Object.keys(e);t===0&&!r&&(r=new Set(o.filter(e=>e.includes(`.`))));let s=a??n.flattenDepth;for(let[a,c]of Object.entries(e))yield*fr(a,c,t,n,o,r,i,s)}function*fr(e,t,n,r,i,a,o,s){let c=o?`${o}.${e}`:e,l=s??r.flattenDepth;if(r.keyFolding===`safe`&&i){let s=nr(e,t,i,r,a,o,l);if(s){let{foldedKey:e,remainder:t,leafValue:i,segmentCount:c}=s,u=sr(e);if(t===void 0){if(Wn(i)){yield Cr(n,`${u}: ${ar(i,r.delimiter)}`,r.indent);return}if(Gn(i)){yield*pr(e,i,n,r);return}if(Kn(i)&&qn(i)){yield Cr(n,`${u}:`,r.indent);return}}if(Kn(t)){yield Cr(n,`${u}:`,r.indent);let i=l-c,s=o?`${o}.${e}`:e;yield*dr(t,n+1,r,a,s,i);return}}}let u=sr(e);Wn(t)?yield Cr(n,`${u}: ${ar(t,r.delimiter)}`,r.indent):Gn(t)?yield*pr(e,t,n,r):Kn(t)&&(yield Cr(n,`${u}:`,r.indent),qn(t)||(yield*dr(t,n+1,r,a,c,l)))}function*pr(e,t,n,r){if(t.length===0){yield Cr(n,e==null?`[]`:`${sr(e)}: []`,r.indent);return}if(Yn(t)){yield Cr(n,hr(t,r.delimiter,e),r.indent);return}if(Xn(t)&&t.every(e=>Yn(e))){yield*mr(e,t,n,r);return}if(Zn(t)){let i=_r(t);i?yield*gr(e,t,i,n,r):yield*br(e,t,n,r);return}yield*br(e,t,n,r)}function*mr(e,t,n,r){yield Cr(n,lr(t.length,{key:e,delimiter:r.delimiter}),r.indent);for(let e of t)if(Yn(e)){let t=hr(e,r.delimiter);yield wr(n+1,t,r.indent)}}function hr(e,t,n){let r=lr(e.length,{key:n,delimiter:t}),i=cr(e,t);return e.length===0?r:`${r} ${i}`}function*gr(e,t,n,r,i){yield Cr(r,lr(t.length,{key:e,fields:n,delimiter:i.delimiter}),i.indent),yield*yr(t,n,r+1,i)}function _r(e){if(e.length===0)return;let t=e[0],n=Object.keys(t);if(n.length!==0&&vr(e,n))return n}function vr(e,t){for(let n of e){if(Object.keys(n).length!==t.length)return!1;for(let e of t)if(!Object.hasOwn(n,e)||!Wn(n[e]))return!1}return!0}function*yr(e,t,n,r){for(let i of e)yield Cr(n,cr(t.map(e=>i[e]),r.delimiter),r.indent)}function*br(e,t,n,r){yield Cr(n,lr(t.length,{key:e,delimiter:r.delimiter}),r.indent);for(let e of t)yield*Sr(e,n+1,r)}function*xr(e,t,n){if(qn(e)){yield Cr(t,`-`,n.indent);return}let r=Object.entries(e),[i,a]=r[0],o=r.slice(1);if(Gn(a)&&Zn(a)){let e=_r(a);if(e){yield wr(t,lr(a.length,{key:i,fields:e,delimiter:n.delimiter}),n.indent),yield*yr(a,e,t+2,n),o.length>0&&(yield*dr(Object.fromEntries(o),t+1,n));return}}let s=sr(i);if(Wn(a))yield wr(t,`${s}: ${ar(a,n.delimiter)}`,n.indent);else if(Gn(a)){if(a.length===0)yield wr(t,`${s}: []`,n.indent);else if(Yn(a))yield wr(t,`${s}${hr(a,n.delimiter)}`,n.indent);else{yield wr(t,`${s}${lr(a.length,{delimiter:n.delimiter})}`,n.indent);for(let e of a)yield*Sr(e,t+2,n)}}else Kn(a)&&(yield wr(t,`${s}:`,n.indent),qn(a)||(yield*dr(a,t+2,n)));o.length>0&&(yield*dr(Object.fromEntries(o),t+1,n))}function*Sr(e,t,n){if(Wn(e))yield wr(t,ar(e,n.delimiter),n.indent);else if(Gn(e)){if(Yn(e))yield wr(t,hr(e,n.delimiter),n.indent);else{yield wr(t,lr(e.length,{delimiter:n.delimiter}),n.indent);for(let r of e)yield*Sr(r,t+1,n)}}else Kn(e)&&(yield*xr(e,t,n))}function Cr(e,t,n){return` `.repeat(n*e)+t}function wr(e,t,n){return Cr(e,`- `+t,n)}function Tr(e,t){let n=t(``,e,[]);return Er(n===void 0?e:Un(n),t,[])}function Er(e,t,n){return Kn(e)?Dr(e,t,n):Gn(e)?Or(e,t,n):e}function Dr(e,t,n){let r={};for(let[i,a]of Object.entries(e)){let e=[...n,i],o=t(i,a,e);o!==void 0&&Hn(r,i,Er(Un(o),t,e))}return r}function Or(e,t,n){let r=[];for(let i=0;i<e.length;i++){let a=e[i],o=[...n,i],s=t(String(i),a,o);if(s===void 0)continue;let c=Un(s);r.push(Er(c,t,o))}return r}function kr(e,t){return Array.from(Ar(e,t)).join(`
50
- `)}function Ar(e,t){let n=Un(e),r=jr(t);return ur(r.replacer?Tr(n,r.replacer):n,r,0)}function jr(e){return{indent:e?.indent??2,delimiter:e?.delimiter??Pr,keyFolding:e?.keyFolding??`off`,flattenDepth:e?.flattenDepth??1/0,replacer:e?.replacer}}var Mr,Nr,Pr,Fr,Ir,Lr=F((()=>{Mr=`null`,Nr={comma:`,`,tab:` `,pipe:`|`},Pr=Nr.comma,Fr=/^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i,Ir=/^0\d+$/}));function Rr(e,t){return JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t,t)}function zr(e){return JSON.parse(Rr(e))}var Br=F((()=>{}));function Vr(e){if(e&&typeof e==`object`)switch(e[Yr]){case Gr:case Jr:return!0}return!1}function Hr(e){if(e&&typeof e==`object`)switch(e[Yr]){case Ur:case Gr:case qr:case Jr:return!0}return!1}var Ur,Wr,Gr,Kr,qr,Jr,Yr,Xr,Zr,Qr,$r,ei,ti,ni,L=F((()=>{Ur=Symbol.for(`yaml.alias`),Wr=Symbol.for(`yaml.document`),Gr=Symbol.for(`yaml.map`),Kr=Symbol.for(`yaml.pair`),qr=Symbol.for(`yaml.scalar`),Jr=Symbol.for(`yaml.seq`),Yr=Symbol.for(`yaml.node.type`),Xr=e=>!!e&&typeof e==`object`&&e[Yr]===Ur,Zr=e=>!!e&&typeof e==`object`&&e[Yr]===Wr,Qr=e=>!!e&&typeof e==`object`&&e[Yr]===Gr,$r=e=>!!e&&typeof e==`object`&&e[Yr]===Kr,ei=e=>!!e&&typeof e==`object`&&e[Yr]===qr,ti=e=>!!e&&typeof e==`object`&&e[Yr]===Jr,ni=e=>(ei(e)||Vr(e))&&!!e.anchor}));function ri(e,t){let n=si(t);Zr(e)?ii(null,e.contents,n,Object.freeze([e]))===fi&&(e.contents=null):ii(null,e,n,Object.freeze([]))}function ii(e,t,n,r){let i=ci(e,t,n,r);if(Hr(i)||$r(i))return li(e,r,i),ii(e,i,n,r);if(typeof i!=`symbol`){if(Vr(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){let i=ii(e,t.items[e],n,r);if(typeof i==`number`)e=i-1;else if(i===ui)return ui;else i===fi&&(t.items.splice(e,1),--e)}}else if($r(t)){r=Object.freeze(r.concat(t));let e=ii(`key`,t.key,n,r);if(e===ui)return ui;e===fi&&(t.key=null);let i=ii(`value`,t.value,n,r);if(i===ui)return ui;i===fi&&(t.value=null)}}return i}async function ai(e,t){let n=si(t);Zr(e)?await oi(null,e.contents,n,Object.freeze([e]))===fi&&(e.contents=null):await oi(null,e,n,Object.freeze([]))}async function oi(e,t,n,r){let i=await ci(e,t,n,r);if(Hr(i)||$r(i))return li(e,r,i),oi(e,i,n,r);if(typeof i!=`symbol`){if(Vr(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){let i=await oi(e,t.items[e],n,r);if(typeof i==`number`)e=i-1;else if(i===ui)return ui;else i===fi&&(t.items.splice(e,1),--e)}}else if($r(t)){r=Object.freeze(r.concat(t));let e=await oi(`key`,t.key,n,r);if(e===ui)return ui;e===fi&&(t.key=null);let i=await oi(`value`,t.value,n,r);if(i===ui)return ui;i===fi&&(t.value=null)}}return i}function si(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function ci(e,t,n,r){if(typeof n==`function`)return n(e,t,r);if(Qr(t))return n.Map?.(e,t,r);if(ti(t))return n.Seq?.(e,t,r);if($r(t))return n.Pair?.(e,t,r);if(ei(t))return n.Scalar?.(e,t,r);if(Xr(t))return n.Alias?.(e,t,r)}function li(e,t,n){let r=t[t.length-1];if(Vr(r))r.items[e]=n;else if($r(r))e===`key`?r.key=n:r.value=n;else if(Zr(r))r.contents=n;else{let e=Xr(r)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}var ui,di,fi,pi=F((()=>{L(),ui=Symbol(`break visit`),di=Symbol(`skip children`),fi=Symbol(`remove node`),ri.BREAK=ui,ri.SKIP=di,ri.REMOVE=fi,ai.BREAK=ui,ai.SKIP=di,ai.REMOVE=fi})),mi,hi,gi,_i=F((()=>{L(),pi(),mi={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},hi=e=>e.replace(/[!,[\]{}]/g,e=>mi[e]),gi=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},e.defaultTags)}return t}add(t,n){this.atNextDocument&&=(this.yaml={explicit:e.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},e.defaultTags),!1);let r=t.trim().split(/[ \t]+/),i=r.shift();switch(i){case`%TAG`:{if(r.length!==2&&(n(0,`%TAG directive should contain exactly two parts`),r.length<2))return!1;let[e,t]=r;return this.tags[e]=t,!0}case`%YAML`:{if(this.yaml.explicit=!0,r.length!==1)return n(0,`%YAML directive should contain exactly one part`),!1;let[e]=r;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let t=/^\d+\.\d+$/.test(e);return n(6,`Unsupported YAML version ${e}`,t),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let n=e.slice(2,-1);return n===`!`||n===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),n)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return n===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+hi(e.substring(n.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let t=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],n=Object.entries(this.tags),r;if(e&&n.length>0&&Hr(e.contents)){let t={};ri(e.contents,(e,n)=>{Hr(n)&&n.tag&&(t[n.tag]=!0)}),r=Object.keys(t)}else r=[];for(let[i,a]of n)(i!==`!!`||a!==`tag:yaml.org,2002:`)&&(!e||r.some(e=>e.startsWith(a)))&&t.push(`%TAG ${i} ${a}`);return t.join(`
51
- `)}},gi.defaultYaml={explicit:!1,version:`1.2`},gi.defaultTags={"!!":`tag:yaml.org,2002:`}}));function vi(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw Error(t)}return!0}function yi(e){let t=new Set;return ri(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function bi(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function xi(e,t){let n=[],r=new Map,i=null;return{onAnchor:r=>{n.push(r),i??=yi(e);let a=bi(t,i);return i.add(a),a},setAnchors:()=>{for(let e of n){let t=r.get(e);if(typeof t==`object`&&t.anchor&&(ei(t.node)||Vr(t.node)))t.node.anchor=t.anchor;else{let t=Error(`Failed to resolve repeated object (this should not happen)`);throw t.source=e,t}}},sourceObjects:r}}var Si=F((()=>{L(),pi()}));function Ci(e,t,n,r){if(r&&typeof r==`object`){if(Array.isArray(r))for(let t=0,n=r.length;t<n;++t){let n=r[t],i=Ci(e,r,String(t),n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}else if(r instanceof Map)for(let t of Array.from(r.keys())){let n=r.get(t),i=Ci(e,r,t,n);i===void 0?r.delete(t):i!==n&&r.set(t,i)}else if(r instanceof Set)for(let t of Array.from(r)){let n=Ci(e,r,t,t);n===void 0?r.delete(t):n!==t&&(r.delete(t),r.add(n))}else for(let[t,n]of Object.entries(r)){let i=Ci(e,r,t,n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}}return e.call(t,n,r)}var wi=F((()=>{}));function Ti(e,t,n){if(Array.isArray(e))return e.map((e,t)=>Ti(e,String(t),n));if(e&&typeof e.toJSON==`function`){if(!n||!ni(e))return e.toJSON(t,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(e,r),n.onCreate=e=>{r.res=e,delete n.onCreate};let i=e.toJSON(t,n);return n.onCreate&&n.onCreate(i),i}return typeof e==`bigint`&&!n?.keep?Number(e):e}var Ei=F((()=>{L()})),Di,Oi=F((()=>{wi(),L(),Ei(),Di=class{constructor(e){Object.defineProperty(this,Yr,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:r,reviver:i}={}){if(!Zr(e))throw TypeError(`A document argument is required`);let a={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof n==`number`?n:100},o=Ti(this,``,a);if(typeof r==`function`)for(let{count:e,res:t}of a.anchors.values())r(t,e);return typeof i==`function`?Ci(i,{"":o},``,o):o}}}));function ki(e,t,n){if(Xr(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(Vr(t)){let r=0;for(let i of t.items){let t=ki(e,i,n);t>r&&(r=t)}return r}if($r(t)){let r=ki(e,t.key,n),i=ki(e,t.value,n);return Math.max(r,i)}return 1}var Ai,ji=F((()=>{Si(),pi(),L(),Oi(),Ei(),Ai=class extends Di{constructor(e){super(Ur),this.source=e,Object.defineProperty(this,"tag",{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){if(t?.maxAliasCount===0)throw ReferenceError(`Alias resolution is disabled`);let n;t?.aliasResolveCache?n=t.aliasResolveCache:(n=[],ri(e,{Node:(e,t)=>{(Xr(t)||ni(t))&&n.push(t)}}),t&&(t.aliasResolveCache=n));let r;for(let e of n){if(e===this)break;e.anchor===this.source&&(r=e)}return r}toJSON(e,t){if(!t)return{source:this.source};let{anchors:n,doc:r,maxAliasCount:i}=t,a=this.resolve(r,t);if(!a){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(e)}let o=n.get(a);if(o||=(Ti(a,null,t),n.get(a)),o?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(i>=0&&(o.count+=1,o.aliasCount===0&&(o.aliasCount=ki(r,a,n)),o.count*o.aliasCount>i))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`);return o.res}toString(e,t,n){let r=`*${this.source}`;if(e){if(vi(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(e)}if(e.implicitKey)return`${r} `}return r}}})),Mi,R,Ni=F((()=>{L(),Oi(),Ei(),Mi=e=>!e||typeof e!=`function`&&typeof e!=`object`,R=class extends Di{constructor(e){super(qr),this.value=e}toJSON(e,t){return t?.keep?this.value:Ti(this.value,e,t)}toString(){return String(this.value)}},R.BLOCK_FOLDED=`BLOCK_FOLDED`,R.BLOCK_LITERAL=`BLOCK_LITERAL`,R.PLAIN=`PLAIN`,R.QUOTE_DOUBLE=`QUOTE_DOUBLE`,R.QUOTE_SINGLE=`QUOTE_SINGLE`}));function Pi(e,t,n){if(t){let e=n.filter(e=>e.tag===t),r=e.find(e=>!e.format)??e[0];if(!r)throw Error(`Tag ${t} not found`);return r}return n.find(t=>t.identify?.(e)&&!t.format)}function Fi(e,t,n){if(Zr(e)&&(e=e.contents),Hr(e))return e;if($r(e)){let t=n.schema[Gr].createNode?.(n.schema,null,n);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<`u`&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:i,onTagObj:a,schema:o,sourceObjects:s}=n,c;if(r&&e&&typeof e==`object`){if(c=s.get(e),c)return c.anchor??(c.anchor=i(e)),new Ai(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith(`!!`)&&(t=Ii+t.slice(2));let l=Pi(e,t,o.tags);if(!l){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new R(e);return c&&(c.node=t),t}l=e instanceof Map?o[Gr]:Symbol.iterator in Object(e)?o[Jr]:o[Gr]}a&&(a(l),delete n.onTagObj);let u=l?.createNode?l.createNode(n.schema,e,n):typeof l?.nodeClass?.from==`function`?l.nodeClass.from(n.schema,e,n):new R(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}var Ii,Li=F((()=>{ji(),L(),Ni(),Ii=`tag:yaml.org,2002:`}));function Ri(e,t,n){let r=n;for(let e=t.length-1;e>=0;--e){let n=t[e];if(typeof n==`number`&&Number.isInteger(n)&&n>=0){let e=[];e[n]=r,r=e}else r=new Map([[n,r]])}return Fi(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:new Map})}var zi,Bi,Vi=F((()=>{Li(),L(),Oi(),zi=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done,Bi=class extends Di{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(t=>Hr(t)||$r(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(zi(e))this.add(t);else{let[n,...r]=e,i=this.get(n,!0);if(Vr(i))i.addIn(r,t);else if(i===void 0&&this.schema)this.set(n,Ri(this.schema,r,t));else throw Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}deleteIn(e){let[t,...n]=e;if(n.length===0)return this.delete(t);let r=this.get(t,!0);if(Vr(r))return r.deleteIn(n);throw Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){let[n,...r]=e,i=this.get(n,!0);return r.length===0?!t&&ei(i)?i.value:i:Vr(i)?i.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!$r(t))return!1;let n=t.value;return n==null||e&&ei(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){let[t,...n]=e;if(n.length===0)return this.has(t);let r=this.get(t,!0);return Vr(r)?r.hasIn(n):!1}setIn(e,t){let[n,...r]=e;if(r.length===0)this.set(n,t);else{let e=this.get(n,!0);if(Vr(e))e.setIn(r,t);else if(e===void 0&&this.schema)this.set(n,Ri(this.schema,r,t));else throw Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}}}));function Hi(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Ui,Wi,Gi=F((()=>{Ui=e=>e.replace(/^(?!$)(?: $)?/gm,`#`),Wi=(e,t,n)=>e.endsWith(`
52
- `)?Hi(n,t):n.includes(`
48
+ }`}var xn=I((()=>{sn()}));function Sn(e,t){if(t){let n=e?.cause;for(;n;){if(t(n))return n;n=n?.cause}return}let n=e;for(;n?.cause;)n=n.cause;return n}var Cn,L,wn,Tn,En=I((()=>{Cn=class extends Error{name=`Incur.BaseError`;shortMessage;details;constructor(e,t={}){let n=t.cause instanceof Error?t.cause.message:void 0,r=n?`${e}\n\nDetails: ${n}`:e;super(r,t.cause?{cause:t.cause}:void 0),this.shortMessage=e,this.details=n}walk(e){return Sn(this,e)}},L=class extends Cn{name=`Incur.IncurError`;code;hint;retryable;exitCode;constructor(e){super(e.message,e.cause?{cause:e.cause}:void 0),this.code=e.code,this.hint=e.hint,this.retryable=e.retryable??!1,this.exitCode=e.exitCode}},wn=class extends Cn{name=`Incur.ValidationError`;fieldErrors;constructor(e){super(e.message,e.cause?{cause:e.cause}:void 0),this.fieldErrors=e.fieldErrors??[]}},Tn=class extends Cn{name=`Incur.ParseError`;constructor(e){super(e.message,e.cause?{cause:e.cause}:void 0)}}}));function Dn(e){let t=[],n=new Headers,r=new URLSearchParams,i,a,o=0;for(;o<e.length;){let n=e[o];if(n.startsWith(`--`)){let t=n.indexOf(`=`);if(t!==-1){let e=n.slice(2,t),i=n.slice(t+1);Mn.has(e)?s(e,i):r.set(e,i),o++}else{let t=n.slice(2),i=e[o+1];if(i===void 0)throw Error(`Missing value for --${t}`);Mn.has(t)?s(t,i):r.set(t,i),o+=2}}else if(n.startsWith(`-`)&&n.length===2){let t=n[1],r=Nn[t];if(r){let n=e[o+1];if(n===void 0)throw Error(`Missing value for -${t}`);s(r,n),o+=2}else o++}else t.push(n),o++}function s(e,t){if(e===`method`)i=t.toUpperCase();else if(e===`body`||e===`data`)a=t;else if(e===`header`){let e=t.indexOf(`:`);if(e!==-1){let r=t.slice(0,e).trim(),i=t.slice(e+1).trim();n.set(r,i)}}}return{path:t.length>0?`/${t.join(`/`)}`:`/`,method:i??(a===void 0?`GET`:`POST`),headers:n,body:a,query:r}}function On(e){let t=new URL(e.path,`http://localhost`);e.query.forEach((e,n)=>t.searchParams.set(n,e));let n={method:e.method,headers:e.headers};return e.body!==void 0&&(n.body=e.body,e.headers.has(`content-type`)||e.headers.set(`content-type`,`application/json`)),new Request(t.toString(),n)}function kn(e){return e.body!==null&&e.headers.get(`content-type`)===`application/x-ndjson`}async function*An(e){let t=e.body.getReader(),n=new TextDecoder,r=``;for(;;){let{value:e,done:i}=await t.read();if(i)break;r+=n.decode(e,{stream:!0});let a;for(;(a=r.indexOf(`
49
+ `))!==-1;){let e=r.slice(0,a).trim();if(r=r.slice(a+1),e.length!==0)try{yield JSON.parse(e)}catch{yield e}}}let i=r.trim();if(i.length>0)try{yield JSON.parse(i)}catch{yield i}}async function jn(e){let t=await e.text(),n;try{n=JSON.parse(t)}catch{n=t}return{ok:e.ok,status:e.status,data:n,headers:e.headers}}var Mn,Nn,Pn=I((()=>{Mn=new Set([`method`,`body`,`data`,`header`]),Nn={X:`method`,d:`data`,H:`header`}}));function Fn(e){let t=[],n=[],r=``,i=0;for(let t=0;t<e.length;t++){let a=e[t];a===`[`?i++:a===`]`&&i--,a===`,`&&i===0?(n.push(r),r=``):r+=a}r&&n.push(r);for(let e of n){let n=[],r=e;for(;r.length>0;){let e=r.indexOf(`[`);if(e===-1){for(let e of r.split(`.`))e&&n.push({key:e});break}let t=r.slice(0,e);for(let e of t.split(`.`))e&&n.push({key:e});let i=r.indexOf(`]`,e),[a,o]=r.slice(e+1,i).split(`,`);n.push({start:Number(a),end:Number(o)}),r=r.slice(i+1),r.startsWith(`.`)&&(r=r.slice(1))}t.push(n)}return t}function In(e,t){if(t.length===0)return e;if(t.length===1&&t[0].length===1&&`key`in t[0][0]){let n=t[0][0].key;if(Array.isArray(e))return e.map(e=>In(e,t));if(typeof e==`object`&&e){let t=e[n];return typeof t!=`object`||!t?t:{[n]:t}}return}if(Array.isArray(e))return e.map(e=>In(e,t));let n={};for(let r of t)Ln(n,e,r,0);return n}function Ln(e,t,n,r){if(r>=n.length||typeof t!=`object`||!t)return;let i=n[r];if(`key`in i){let a=t[i.key];if(a===void 0)return;if(r+1>=n.length){e[i.key]=a;return}let o=n[r+1];if(`start`in o){if(!Array.isArray(a))return;let t=a.slice(o.start,o.end);if(r+2>=n.length){e[i.key]=t;return}e[i.key]=t.map(e=>{let t={};return Ln(t,e,n,r+2),t});return}if(typeof a!=`object`||!a)return;(!e[i.key]||typeof e[i.key]!=`object`)&&(e[i.key]={}),Ln(e[i.key],a,n,r+1);return}}var Rn=I((()=>{}));function zn(e){return e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/\n/g,`\\n`).replace(/\r/g,`\\r`).replace(/\t/g,`\\t`).replace(/[\u0000-\u001F]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}function Bn(e){return e===`true`||e===`false`||e===`null`}function Vn(e,t,n){if(t===`__proto__`){Object.defineProperty(e,t,{value:n,enumerable:!0,writable:!0,configurable:!0});return}e[t]=n}function Hn(e){if(e===null)return null;if(typeof e==`object`&&e&&`toJSON`in e&&typeof e.toJSON==`function`){let t=e.toJSON();if(t!==e)return Hn(t)}if(typeof e==`string`||typeof e==`boolean`)return e;if(typeof e==`number`)return Object.is(e,-0)?0:Number.isFinite(e)?e:null;if(typeof e==`bigint`)return e>=-(2**53-1)&&e<=2**53-1?Number(e):e.toString();if(e instanceof Date)return e.toISOString();if(Array.isArray(e))return e.map(Hn);if(e instanceof Set)return Array.from(e).map(Hn);if(e instanceof Map)return Object.fromEntries(Array.from(e,([e,t])=>[String(e),Hn(t)]));if(qn(e)){let t={};for(let n in e)Object.hasOwn(e,n)&&Vn(t,n,Hn(e[n]));return t}return null}function Un(e){return e===null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function Wn(e){return Array.isArray(e)}function Gn(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Kn(e){return Object.keys(e).length===0}function qn(e){if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return t===null||t===Object.prototype}function Jn(e){return e.length===0||e.every(e=>Un(e))}function Yn(e){return e.length===0||e.every(e=>Wn(e))}function Xn(e){return e.length===0||e.every(e=>Gn(e))}function Zn(e){return/^[A-Z_][\w.]*$/i.test(e)}function Qn(e){return/^[A-Z_]\w*$/i.test(e)}function $n(e,t=Nr){return!(!e||e!==e.trim()||Bn(e)||er(e)||e.includes(`:`)||e.includes(`"`)||e.includes(`\\`)||/[[\]{}]/.test(e)||/[\u0000-\u001F]/.test(e)||e.includes(t)||e.startsWith(`-`))}function er(e){return Pr.test(e)||Fr.test(e)}function tr(e,t,n,r,i,a,o){if(r.keyFolding!==`safe`||!Gn(t))return;let{segments:s,tail:c,leafValue:l}=nr(e,t,o??r.flattenDepth);if(s.length<2||!s.every(e=>Qn(e)))return;let u=rr(s),d=a?`${a}.${u}`:u;if(!n.includes(u)&&!(i&&i.has(d)))return{foldedKey:u,remainder:c,leafValue:l,segmentCount:s.length}}function nr(e,t,n){let r=[e],i=t;for(;r.length<n&&Gn(i);){let e=Object.keys(i);if(e.length!==1)break;let t=e[0],n=i[t];r.push(t),i=n}return!Gn(i)||Kn(i)?{segments:r,tail:void 0,leafValue:i}:{segments:r,tail:i,leafValue:i}}function rr(e){return e.join(`.`)}function ir(e,t){return e===null?jr:typeof e==`boolean`||typeof e==`number`?String(e):ar(e,t)}function ar(e,t=Nr){return $n(e,t)?e:`"${zn(e)}"`}function or(e){return Zn(e)?e:`"${zn(e)}"`}function sr(e,t=Nr){return e.map(e=>ir(e,t)).join(t)}function cr(e,t){let n=t?.key,r=t?.fields,i=t?.delimiter??`,`,a=``;if(n!=null&&(a+=or(n)),a+=`[${e}${i===Nr?``:i}]`,r){let e=r.map(e=>or(e));a+=`{${e.join(i)}}`}return a+=`:`,a}function*lr(e,t,n){if(Un(e)){let n=ir(e,t.delimiter);n!==``&&(yield n);return}Wn(e)?yield*fr(void 0,e,n,t):Gn(e)&&(yield*ur(e,n,t))}function*ur(e,t,n,r,i,a){let o=Object.keys(e);t===0&&!r&&(r=new Set(o.filter(e=>e.includes(`.`))));let s=a??n.flattenDepth;for(let[a,c]of Object.entries(e))yield*dr(a,c,t,n,o,r,i,s)}function*dr(e,t,n,r,i,a,o,s){let c=o?`${o}.${e}`:e,l=s??r.flattenDepth;if(r.keyFolding===`safe`&&i){let s=tr(e,t,i,r,a,o,l);if(s){let{foldedKey:e,remainder:t,leafValue:i,segmentCount:c}=s,u=or(e);if(t===void 0){if(Un(i)){yield Sr(n,`${u}: ${ir(i,r.delimiter)}`,r.indent);return}if(Wn(i)){yield*fr(e,i,n,r);return}if(Gn(i)&&Kn(i)){yield Sr(n,`${u}:`,r.indent);return}}if(Gn(t)){yield Sr(n,`${u}:`,r.indent);let i=l-c,s=o?`${o}.${e}`:e;yield*ur(t,n+1,r,a,s,i);return}}}let u=or(e);Un(t)?yield Sr(n,`${u}: ${ir(t,r.delimiter)}`,r.indent):Wn(t)?yield*fr(e,t,n,r):Gn(t)&&(yield Sr(n,`${u}:`,r.indent),Kn(t)||(yield*ur(t,n+1,r,a,c,l)))}function*fr(e,t,n,r){if(t.length===0){yield Sr(n,e==null?`[]`:`${or(e)}: []`,r.indent);return}if(Jn(t)){yield Sr(n,mr(t,r.delimiter,e),r.indent);return}if(Yn(t)&&t.every(e=>Jn(e))){yield*pr(e,t,n,r);return}if(Xn(t)){let i=gr(t);i?yield*hr(e,t,i,n,r):yield*yr(e,t,n,r);return}yield*yr(e,t,n,r)}function*pr(e,t,n,r){yield Sr(n,cr(t.length,{key:e,delimiter:r.delimiter}),r.indent);for(let e of t)if(Jn(e)){let t=mr(e,r.delimiter);yield Cr(n+1,t,r.indent)}}function mr(e,t,n){let r=cr(e.length,{key:n,delimiter:t}),i=sr(e,t);return e.length===0?r:`${r} ${i}`}function*hr(e,t,n,r,i){yield Sr(r,cr(t.length,{key:e,fields:n,delimiter:i.delimiter}),i.indent),yield*vr(t,n,r+1,i)}function gr(e){if(e.length===0)return;let t=e[0],n=Object.keys(t);if(n.length!==0&&_r(e,n))return n}function _r(e,t){for(let n of e){if(Object.keys(n).length!==t.length)return!1;for(let e of t)if(!Object.hasOwn(n,e)||!Un(n[e]))return!1}return!0}function*vr(e,t,n,r){for(let i of e)yield Sr(n,sr(t.map(e=>i[e]),r.delimiter),r.indent)}function*yr(e,t,n,r){yield Sr(n,cr(t.length,{key:e,delimiter:r.delimiter}),r.indent);for(let e of t)yield*xr(e,n+1,r)}function*br(e,t,n){if(Kn(e)){yield Sr(t,`-`,n.indent);return}let r=Object.entries(e),[i,a]=r[0],o=r.slice(1);if(Wn(a)&&Xn(a)){let e=gr(a);if(e){yield Cr(t,cr(a.length,{key:i,fields:e,delimiter:n.delimiter}),n.indent),yield*vr(a,e,t+2,n),o.length>0&&(yield*ur(Object.fromEntries(o),t+1,n));return}}let s=or(i);if(Un(a))yield Cr(t,`${s}: ${ir(a,n.delimiter)}`,n.indent);else if(Wn(a)){if(a.length===0)yield Cr(t,`${s}: []`,n.indent);else if(Jn(a))yield Cr(t,`${s}${mr(a,n.delimiter)}`,n.indent);else{yield Cr(t,`${s}${cr(a.length,{delimiter:n.delimiter})}`,n.indent);for(let e of a)yield*xr(e,t+2,n)}}else Gn(a)&&(yield Cr(t,`${s}:`,n.indent),Kn(a)||(yield*ur(a,t+2,n)));o.length>0&&(yield*ur(Object.fromEntries(o),t+1,n))}function*xr(e,t,n){if(Un(e))yield Cr(t,ir(e,n.delimiter),n.indent);else if(Wn(e)){if(Jn(e))yield Cr(t,mr(e,n.delimiter),n.indent);else{yield Cr(t,cr(e.length,{delimiter:n.delimiter}),n.indent);for(let r of e)yield*xr(r,t+1,n)}}else Gn(e)&&(yield*br(e,t,n))}function Sr(e,t,n){return` `.repeat(n*e)+t}function Cr(e,t,n){return Sr(e,`- `+t,n)}function wr(e,t){let n=t(``,e,[]);return Tr(n===void 0?e:Hn(n),t,[])}function Tr(e,t,n){return Gn(e)?Er(e,t,n):Wn(e)?Dr(e,t,n):e}function Er(e,t,n){let r={};for(let[i,a]of Object.entries(e)){let e=[...n,i],o=t(i,a,e);o!==void 0&&Vn(r,i,Tr(Hn(o),t,e))}return r}function Dr(e,t,n){let r=[];for(let i=0;i<e.length;i++){let a=e[i],o=[...n,i],s=t(String(i),a,o);if(s===void 0)continue;let c=Hn(s);r.push(Tr(c,t,o))}return r}function Or(e,t){return Array.from(kr(e,t)).join(`
50
+ `)}function kr(e,t){let n=Hn(e),r=Ar(t);return lr(r.replacer?wr(n,r.replacer):n,r,0)}function Ar(e){return{indent:e?.indent??2,delimiter:e?.delimiter??Nr,keyFolding:e?.keyFolding??`off`,flattenDepth:e?.flattenDepth??1/0,replacer:e?.replacer}}var jr,Mr,Nr,Pr,Fr,Ir=I((()=>{jr=`null`,Mr={comma:`,`,tab:` `,pipe:`|`},Nr=Mr.comma,Pr=/^-?\d+(?:\.\d+)?(?:e[+-]?\d+)?$/i,Fr=/^0\d+$/}));function Lr(e,t){return JSON.stringify(e,(e,t)=>typeof t==`bigint`?t.toString():t,t)}function Rr(e){return JSON.parse(Lr(e))}var zr=I((()=>{}));function Br(e){if(e&&typeof e==`object`)switch(e[Jr]){case Wr:case qr:return!0}return!1}function Vr(e){if(e&&typeof e==`object`)switch(e[Jr]){case Hr:case Wr:case Kr:case qr:return!0}return!1}var Hr,Ur,Wr,Gr,Kr,qr,Jr,Yr,Xr,Zr,Qr,$r,ei,ti,R=I((()=>{Hr=Symbol.for(`yaml.alias`),Ur=Symbol.for(`yaml.document`),Wr=Symbol.for(`yaml.map`),Gr=Symbol.for(`yaml.pair`),Kr=Symbol.for(`yaml.scalar`),qr=Symbol.for(`yaml.seq`),Jr=Symbol.for(`yaml.node.type`),Yr=e=>!!e&&typeof e==`object`&&e[Jr]===Hr,Xr=e=>!!e&&typeof e==`object`&&e[Jr]===Ur,Zr=e=>!!e&&typeof e==`object`&&e[Jr]===Wr,Qr=e=>!!e&&typeof e==`object`&&e[Jr]===Gr,$r=e=>!!e&&typeof e==`object`&&e[Jr]===Kr,ei=e=>!!e&&typeof e==`object`&&e[Jr]===qr,ti=e=>($r(e)||Br(e))&&!!e.anchor}));function ni(e,t){let n=oi(t);Xr(e)?ri(null,e.contents,n,Object.freeze([e]))===di&&(e.contents=null):ri(null,e,n,Object.freeze([]))}function ri(e,t,n,r){let i=si(e,t,n,r);if(Vr(i)||Qr(i))return ci(e,r,i),ri(e,i,n,r);if(typeof i!=`symbol`){if(Br(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){let i=ri(e,t.items[e],n,r);if(typeof i==`number`)e=i-1;else if(i===li)return li;else i===di&&(t.items.splice(e,1),--e)}}else if(Qr(t)){r=Object.freeze(r.concat(t));let e=ri(`key`,t.key,n,r);if(e===li)return li;e===di&&(t.key=null);let i=ri(`value`,t.value,n,r);if(i===li)return li;i===di&&(t.value=null)}}return i}async function ii(e,t){let n=oi(t);Xr(e)?await ai(null,e.contents,n,Object.freeze([e]))===di&&(e.contents=null):await ai(null,e,n,Object.freeze([]))}async function ai(e,t,n,r){let i=await si(e,t,n,r);if(Vr(i)||Qr(i))return ci(e,r,i),ai(e,i,n,r);if(typeof i!=`symbol`){if(Br(t)){r=Object.freeze(r.concat(t));for(let e=0;e<t.items.length;++e){let i=await ai(e,t.items[e],n,r);if(typeof i==`number`)e=i-1;else if(i===li)return li;else i===di&&(t.items.splice(e,1),--e)}}else if(Qr(t)){r=Object.freeze(r.concat(t));let e=await ai(`key`,t.key,n,r);if(e===li)return li;e===di&&(t.key=null);let i=await ai(`value`,t.value,n,r);if(i===li)return li;i===di&&(t.value=null)}}return i}function oi(e){return typeof e==`object`&&(e.Collection||e.Node||e.Value)?Object.assign({Alias:e.Node,Map:e.Node,Scalar:e.Node,Seq:e.Node},e.Value&&{Map:e.Value,Scalar:e.Value,Seq:e.Value},e.Collection&&{Map:e.Collection,Seq:e.Collection},e):e}function si(e,t,n,r){if(typeof n==`function`)return n(e,t,r);if(Zr(t))return n.Map?.(e,t,r);if(ei(t))return n.Seq?.(e,t,r);if(Qr(t))return n.Pair?.(e,t,r);if($r(t))return n.Scalar?.(e,t,r);if(Yr(t))return n.Alias?.(e,t,r)}function ci(e,t,n){let r=t[t.length-1];if(Br(r))r.items[e]=n;else if(Qr(r))e===`key`?r.key=n:r.value=n;else if(Xr(r))r.contents=n;else{let e=Yr(r)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}var li,ui,di,fi=I((()=>{R(),li=Symbol(`break visit`),ui=Symbol(`skip children`),di=Symbol(`remove node`),ni.BREAK=li,ni.SKIP=ui,ni.REMOVE=di,ii.BREAK=li,ii.SKIP=ui,ii.REMOVE=di})),pi,mi,hi,gi=I((()=>{R(),fi(),pi={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},mi=e=>e.replace(/[!,[\]{}]/g,e=>pi[e]),hi=class e{constructor(t,n){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},e.defaultYaml,t),this.tags=Object.assign({},e.defaultTags,n)}clone(){let t=new e(this.yaml,this.tags);return t.docStart=this.docStart,t}atDocument(){let t=new e(this.yaml,this.tags);switch(this.yaml.version){case`1.1`:this.atNextDocument=!0;break;case`1.2`:this.atNextDocument=!1,this.yaml={explicit:e.defaultYaml.explicit,version:`1.2`},this.tags=Object.assign({},e.defaultTags)}return t}add(t,n){this.atNextDocument&&=(this.yaml={explicit:e.defaultYaml.explicit,version:`1.1`},this.tags=Object.assign({},e.defaultTags),!1);let r=t.trim().split(/[ \t]+/),i=r.shift();switch(i){case`%TAG`:{if(r.length!==2&&(n(0,`%TAG directive should contain exactly two parts`),r.length<2))return!1;let[e,t]=r;return this.tags[e]=t,!0}case`%YAML`:{if(this.yaml.explicit=!0,r.length!==1)return n(0,`%YAML directive should contain exactly one part`),!1;let[e]=r;if(e===`1.1`||e===`1.2`)return this.yaml.version=e,!0;{let t=/^\d+\.\d+$/.test(e);return n(6,`Unsupported YAML version ${e}`,t),!1}}default:return n(0,`Unknown directive ${i}`,!0),!1}}tagName(e,t){if(e===`!`)return`!`;if(e[0]!==`!`)return t(`Not a valid tag: ${e}`),null;if(e[1]===`<`){let n=e.slice(2,-1);return n===`!`||n===`!!`?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==`>`&&t(`Verbatim tags must end with a >`),n)}let[,n,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let i=this.tags[n];if(i)try{return i+decodeURIComponent(r)}catch(e){return t(String(e)),null}return n===`!`?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,n]of Object.entries(this.tags))if(e.startsWith(n))return t+mi(e.substring(n.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let t=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],n=Object.entries(this.tags),r;if(e&&n.length>0&&Vr(e.contents)){let t={};ni(e.contents,(e,n)=>{Vr(n)&&n.tag&&(t[n.tag]=!0)}),r=Object.keys(t)}else r=[];for(let[i,a]of n)(i!==`!!`||a!==`tag:yaml.org,2002:`)&&(!e||r.some(e=>e.startsWith(a)))&&t.push(`%TAG ${i} ${a}`);return t.join(`
51
+ `)}},hi.defaultYaml={explicit:!1,version:`1.2`},hi.defaultTags={"!!":`tag:yaml.org,2002:`}}));function _i(e){if(/[\x00-\x19\s,[\]{}]/.test(e)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(e)}`;throw Error(t)}return!0}function vi(e){let t=new Set;return ni(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function yi(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function bi(e,t){let n=[],r=new Map,i=null;return{onAnchor:r=>{n.push(r),i??=vi(e);let a=yi(t,i);return i.add(a),a},setAnchors:()=>{for(let e of n){let t=r.get(e);if(typeof t==`object`&&t.anchor&&($r(t.node)||Br(t.node)))t.node.anchor=t.anchor;else{let t=Error(`Failed to resolve repeated object (this should not happen)`);throw t.source=e,t}}},sourceObjects:r}}var xi=I((()=>{R(),fi()}));function Si(e,t,n,r){if(r&&typeof r==`object`){if(Array.isArray(r))for(let t=0,n=r.length;t<n;++t){let n=r[t],i=Si(e,r,String(t),n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}else if(r instanceof Map)for(let t of Array.from(r.keys())){let n=r.get(t),i=Si(e,r,t,n);i===void 0?r.delete(t):i!==n&&r.set(t,i)}else if(r instanceof Set)for(let t of Array.from(r)){let n=Si(e,r,t,t);n===void 0?r.delete(t):n!==t&&(r.delete(t),r.add(n))}else for(let[t,n]of Object.entries(r)){let i=Si(e,r,t,n);i===void 0?delete r[t]:i!==n&&(r[t]=i)}}return e.call(t,n,r)}var Ci=I((()=>{}));function wi(e,t,n){if(Array.isArray(e))return e.map((e,t)=>wi(e,String(t),n));if(e&&typeof e.toJSON==`function`){if(!n||!ti(e))return e.toJSON(t,n);let r={aliasCount:0,count:1,res:void 0};n.anchors.set(e,r),n.onCreate=e=>{r.res=e,delete n.onCreate};let i=e.toJSON(t,n);return n.onCreate&&n.onCreate(i),i}return typeof e==`bigint`&&!n?.keep?Number(e):e}var Ti=I((()=>{R()})),Ei,Di=I((()=>{Ci(),R(),Ti(),Ei=class{constructor(e){Object.defineProperty(this,Jr,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:n,onAnchor:r,reviver:i}={}){if(!Xr(e))throw TypeError(`A document argument is required`);let a={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof n==`number`?n:100},o=wi(this,``,a);if(typeof r==`function`)for(let{count:e,res:t}of a.anchors.values())r(t,e);return typeof i==`function`?Si(i,{"":o},``,o):o}}}));function Oi(e,t,n){if(Yr(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(Br(t)){let r=0;for(let i of t.items){let t=Oi(e,i,n);t>r&&(r=t)}return r}if(Qr(t)){let r=Oi(e,t.key,n),i=Oi(e,t.value,n);return Math.max(r,i)}return 1}var ki,Ai=I((()=>{xi(),fi(),R(),Di(),Ti(),ki=class extends Ei{constructor(e){super(Hr),this.source=e,Object.defineProperty(this,"tag",{set(){throw Error(`Alias nodes cannot have tags`)}})}resolve(e,t){if(t?.maxAliasCount===0)throw ReferenceError(`Alias resolution is disabled`);let n;t?.aliasResolveCache?n=t.aliasResolveCache:(n=[],ni(e,{Node:(e,t)=>{(Yr(t)||ti(t))&&n.push(t)}}),t&&(t.aliasResolveCache=n));let r;for(let e of n){if(e===this)break;e.anchor===this.source&&(r=e)}return r}toJSON(e,t){if(!t)return{source:this.source};let{anchors:n,doc:r,maxAliasCount:i}=t,a=this.resolve(r,t);if(!a){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(e)}let o=n.get(a);if(o||=(wi(a,null,t),n.get(a)),o?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(i>=0&&(o.count+=1,o.aliasCount===0&&(o.aliasCount=Oi(r,a,n)),o.count*o.aliasCount>i))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`);return o.res}toString(e,t,n){let r=`*${this.source}`;if(e){if(_i(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw Error(e)}if(e.implicitKey)return`${r} `}return r}}})),ji,z,Mi=I((()=>{R(),Di(),Ti(),ji=e=>!e||typeof e!=`function`&&typeof e!=`object`,z=class extends Ei{constructor(e){super(Kr),this.value=e}toJSON(e,t){return t?.keep?this.value:wi(this.value,e,t)}toString(){return String(this.value)}},z.BLOCK_FOLDED=`BLOCK_FOLDED`,z.BLOCK_LITERAL=`BLOCK_LITERAL`,z.PLAIN=`PLAIN`,z.QUOTE_DOUBLE=`QUOTE_DOUBLE`,z.QUOTE_SINGLE=`QUOTE_SINGLE`}));function Ni(e,t,n){if(t){let e=n.filter(e=>e.tag===t),r=e.find(e=>!e.format)??e[0];if(!r)throw Error(`Tag ${t} not found`);return r}return n.find(t=>t.identify?.(e)&&!t.format)}function Pi(e,t,n){if(Xr(e)&&(e=e.contents),Vr(e))return e;if(Qr(e)){let t=n.schema[Wr].createNode?.(n.schema,null,n);return t.items.push(e),t}(e instanceof String||e instanceof Number||e instanceof Boolean||typeof BigInt<`u`&&e instanceof BigInt)&&(e=e.valueOf());let{aliasDuplicateObjects:r,onAnchor:i,onTagObj:a,schema:o,sourceObjects:s}=n,c;if(r&&e&&typeof e==`object`){if(c=s.get(e),c)return c.anchor??(c.anchor=i(e)),new ki(c.anchor);c={anchor:null,node:null},s.set(e,c)}t?.startsWith(`!!`)&&(t=Fi+t.slice(2));let l=Ni(e,t,o.tags);if(!l){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new z(e);return c&&(c.node=t),t}l=e instanceof Map?o[Wr]:Symbol.iterator in Object(e)?o[qr]:o[Wr]}a&&(a(l),delete n.onTagObj);let u=l?.createNode?l.createNode(n.schema,e,n):typeof l?.nodeClass?.from==`function`?l.nodeClass.from(n.schema,e,n):new z(e);return t?u.tag=t:l.default||(u.tag=l.tag),c&&(c.node=u),u}var Fi,Ii=I((()=>{Ai(),R(),Mi(),Fi=`tag:yaml.org,2002:`}));function Li(e,t,n){let r=n;for(let e=t.length-1;e>=0;--e){let n=t[e];if(typeof n==`number`&&Number.isInteger(n)&&n>=0){let e=[];e[n]=r,r=e}else r=new Map([[n,r]])}return Pi(r,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:new Map})}var Ri,zi,Bi=I((()=>{Ii(),R(),Di(),Ri=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done,zi=class extends Ei{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(t=>Vr(t)||Qr(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(Ri(e))this.add(t);else{let[n,...r]=e,i=this.get(n,!0);if(Br(i))i.addIn(r,t);else if(i===void 0&&this.schema)this.set(n,Li(this.schema,r,t));else throw Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}deleteIn(e){let[t,...n]=e;if(n.length===0)return this.delete(t);let r=this.get(t,!0);if(Br(r))return r.deleteIn(n);throw Error(`Expected YAML collection at ${t}. Remaining path: ${n}`)}getIn(e,t){let[n,...r]=e,i=this.get(n,!0);return r.length===0?!t&&$r(i)?i.value:i:Br(i)?i.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!Qr(t))return!1;let n=t.value;return n==null||e&&$r(n)&&n.value==null&&!n.commentBefore&&!n.comment&&!n.tag})}hasIn(e){let[t,...n]=e;if(n.length===0)return this.has(t);let r=this.get(t,!0);return Br(r)?r.hasIn(n):!1}setIn(e,t){let[n,...r]=e;if(r.length===0)this.set(n,t);else{let e=this.get(n,!0);if(Br(e))e.setIn(r,t);else if(e===void 0&&this.schema)this.set(n,Li(this.schema,r,t));else throw Error(`Expected YAML collection at ${n}. Remaining path: ${r}`)}}}}));function Vi(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}var Hi,Ui,Wi=I((()=>{Hi=e=>e.replace(/^(?!$)(?: $)?/gm,`#`),Ui=(e,t,n)=>e.endsWith(`
52
+ `)?Vi(n,t):n.includes(`
53
53
  `)?`
54
- `+Hi(n,t):(e.endsWith(` `)?``:` `)+n}));function Ki(e,t,n=`flow`,{indentAtStart:r,lineWidth:i=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!i||i<0)return e;i<a&&(a=0);let c=Math.max(1+a,1+i-t.length);if(e.length<=c)return e;let l=[],u={},d=i-t.length;typeof r==`number`&&(r>i-Math.max(2,a)?l.push(0):d=i-r);let f,p,m=!1,h=-1,g=-1,_=-1;n===`block`&&(h=qi(e,h,t.length),h!==-1&&(d=h+c));for(let r;r=e[h+=1];){if(n===`quoted`&&r===`\\`){switch(g=h,e[h+1]){case`x`:h+=3;break;case`u`:h+=5;break;case`U`:h+=9;break;default:h+=1}_=h}if(r===`
55
- `)n===`block`&&(h=qi(e,h,t.length)),d=h+t.length+c,f=void 0;else{if(r===` `&&p&&p!==` `&&p!==`
54
+ `+Vi(n,t):(e.endsWith(` `)?``:` `)+n}));function Gi(e,t,n=`flow`,{indentAtStart:r,lineWidth:i=80,minContentWidth:a=20,onFold:o,onOverflow:s}={}){if(!i||i<0)return e;i<a&&(a=0);let c=Math.max(1+a,1+i-t.length);if(e.length<=c)return e;let l=[],u={},d=i-t.length;typeof r==`number`&&(r>i-Math.max(2,a)?l.push(0):d=i-r);let f,p,m=!1,h=-1,g=-1,_=-1;n===`block`&&(h=Ki(e,h,t.length),h!==-1&&(d=h+c));for(let r;r=e[h+=1];){if(n===`quoted`&&r===`\\`){switch(g=h,e[h+1]){case`x`:h+=3;break;case`u`:h+=5;break;case`U`:h+=9;break;default:h+=1}_=h}if(r===`
55
+ `)n===`block`&&(h=Ki(e,h,t.length)),d=h+t.length+c,f=void 0;else{if(r===` `&&p&&p!==` `&&p!==`
56
56
  `&&p!==` `){let t=e[h+1];t&&t!==` `&&t!==`
57
- `&&t!==` `&&(f=h)}if(h>=d){if(f)l.push(f),d=f+c,f=void 0;else if(n===`quoted`){for(;p===` `||p===` `;)p=r,r=e[h+=1],m=!0;let t=h>_+1?h-2:g-1;if(u[t])return e;l.push(t),u[t]=!0,d=t+c,f=void 0}else m=!0}}p=r}if(m&&s&&s(),l.length===0)return e;o&&o();let v=e.slice(0,l[0]);for(let r=0;r<l.length;++r){let i=l[r],a=l[r+1]||e.length;i===0?v=`\n${t}${e.slice(0,a)}`:(n===`quoted`&&u[i]&&(v+=`${e[i]}\\`),v+=`\n${t}${e.slice(i+1,a)}`)}return v}function qi(e,t,n){let r=t,i=t+1,a=e[i];for(;a===` `||a===` `;)if(t<i+n)a=e[++t];else{do a=e[++t];while(a&&a!==`
58
- `);r=t,i=t+1,a=e[i]}return r}var Ji,Yi,Xi,Zi=F((()=>{Ji=`flow`,Yi=`block`,Xi=`quoted`}));function Qi(e,t,n){if(!t||t<0)return!1;let r=t-n,i=e.length;if(i<=r)return!1;for(let t=0,n=0;t<i;++t)if(e[t]===`
59
- `){if(t-n>r)return!0;if(n=t+1,i-n<=r)return!1}return!0}function $i(e,t){let n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=t,i=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(oa(e)?` `:``),o=``,s=0;for(let e=0,t=n[e];t;t=n[++e])if(t===` `&&n[e+1]===`\\`&&n[e+2]===`n`&&(o+=n.slice(s,e)+`\\ `,e+=1,s=e,t=`\\`),t===`\\`)switch(n[e+1]){case`u`:{o+=n.slice(s,e);let t=n.substr(e+2,4);switch(t){case`0000`:o+=`\\0`;break;case`0007`:o+=`\\a`;break;case`000b`:o+=`\\v`;break;case`001b`:o+=`\\e`;break;case`0085`:o+=`\\N`;break;case`00a0`:o+=`\\_`;break;case`2028`:o+=`\\L`;break;case`2029`:o+=`\\P`;break;default:t.substr(0,2)===`00`?o+=`\\x`+t.substr(2):o+=n.substr(e,6)}e+=5,s=e+1}break;case`n`:if(r||n[e+2]===`"`||n.length<i)e+=1;else{for(o+=n.slice(s,e)+`
57
+ `&&t!==` `&&(f=h)}if(h>=d){if(f)l.push(f),d=f+c,f=void 0;else if(n===`quoted`){for(;p===` `||p===` `;)p=r,r=e[h+=1],m=!0;let t=h>_+1?h-2:g-1;if(u[t])return e;l.push(t),u[t]=!0,d=t+c,f=void 0}else m=!0}}p=r}if(m&&s&&s(),l.length===0)return e;o&&o();let v=e.slice(0,l[0]);for(let r=0;r<l.length;++r){let i=l[r],a=l[r+1]||e.length;i===0?v=`\n${t}${e.slice(0,a)}`:(n===`quoted`&&u[i]&&(v+=`${e[i]}\\`),v+=`\n${t}${e.slice(i+1,a)}`)}return v}function Ki(e,t,n){let r=t,i=t+1,a=e[i];for(;a===` `||a===` `;)if(t<i+n)a=e[++t];else{do a=e[++t];while(a&&a!==`
58
+ `);r=t,i=t+1,a=e[i]}return r}var qi,Ji,Yi,Xi=I((()=>{qi=`flow`,Ji=`block`,Yi=`quoted`}));function Zi(e,t,n){if(!t||t<0)return!1;let r=t-n,i=e.length;if(i<=r)return!1;for(let t=0,n=0;t<i;++t)if(e[t]===`
59
+ `){if(t-n>r)return!0;if(n=t+1,i-n<=r)return!1}return!0}function Qi(e,t){let n=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return n;let{implicitKey:r}=t,i=t.options.doubleQuotedMinMultiLineLength,a=t.indent||(aa(e)?` `:``),o=``,s=0;for(let e=0,t=n[e];t;t=n[++e])if(t===` `&&n[e+1]===`\\`&&n[e+2]===`n`&&(o+=n.slice(s,e)+`\\ `,e+=1,s=e,t=`\\`),t===`\\`)switch(n[e+1]){case`u`:{o+=n.slice(s,e);let t=n.substr(e+2,4);switch(t){case`0000`:o+=`\\0`;break;case`0007`:o+=`\\a`;break;case`000b`:o+=`\\v`;break;case`001b`:o+=`\\e`;break;case`0085`:o+=`\\N`;break;case`00a0`:o+=`\\_`;break;case`2028`:o+=`\\L`;break;case`2029`:o+=`\\P`;break;default:t.substr(0,2)===`00`?o+=`\\x`+t.substr(2):o+=n.substr(e,6)}e+=5,s=e+1}break;case`n`:if(r||n[e+2]===`"`||n.length<i)e+=1;else{for(o+=n.slice(s,e)+`
60
60
 
61
61
  `;n[e+2]===`\\`&&n[e+3]===`n`&&n[e+4]!==`"`;)o+=`
62
- `,e+=2;o+=a,n[e+2]===` `&&(o+=`\\`),e+=1,s=e+1}break;default:e+=1}return o=s?o+n.slice(s):n,r?o:Ki(o,a,Xi,aa(t,!1))}function ea(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
63
- `)||/[ \t]\n|\n[ \t]/.test(e))return $i(e,t);let n=t.indent||(oa(e)?` `:``),r=`'`+e.replace(/'/g,`''`).replace(/\n+/g,`$&\n${n}`)+`'`;return t.implicitKey?r:Ki(r,n,Ji,aa(t,!1))}function ta(e,t){let{singleQuote:n}=t.options,r;if(n===!1)r=$i;else{let t=e.includes(`"`),i=e.includes(`'`);r=t&&!i?ea:i&&!t?$i:n?ea:$i}return r(e,t)}function na({comment:e,type:t,value:n},r,i,a){let{blockQuote:o,commentString:s,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(n))return ta(n,r);let l=r.indent||(r.forceBlockIndent||oa(n)?` `:``),u=o===`literal`?!0:o===`folded`||t===R.BLOCK_FOLDED?!1:t===R.BLOCK_LITERAL||!Qi(n,c,l.length);if(!n)return u?`|
62
+ `,e+=2;o+=a,n[e+2]===` `&&(o+=`\\`),e+=1,s=e+1}break;default:e+=1}return o=s?o+n.slice(s):n,r?o:Gi(o,a,Yi,ia(t,!1))}function $i(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
63
+ `)||/[ \t]\n|\n[ \t]/.test(e))return Qi(e,t);let n=t.indent||(aa(e)?` `:``),r=`'`+e.replace(/'/g,`''`).replace(/\n+/g,`$&\n${n}`)+`'`;return t.implicitKey?r:Gi(r,n,qi,ia(t,!1))}function ea(e,t){let{singleQuote:n}=t.options,r;if(n===!1)r=Qi;else{let t=e.includes(`"`),i=e.includes(`'`);r=t&&!i?$i:i&&!t?Qi:n?$i:Qi}return r(e,t)}function ta({comment:e,type:t,value:n},r,i,a){let{blockQuote:o,commentString:s,lineWidth:c}=r.options;if(!o||/\n[\t ]+$/.test(n))return ea(n,r);let l=r.indent||(r.forceBlockIndent||aa(n)?` `:``),u=o===`literal`?!0:o===`folded`||t===z.BLOCK_FOLDED?!1:t===z.BLOCK_LITERAL||!Zi(n,c,l.length);if(!n)return u?`|
64
64
  `:`>
65
65
  `;let d,f;for(f=n.length;f>0;--f){let e=n[f-1];if(e!==`
66
66
  `&&e!==` `&&e!==` `)break}let p=n.substring(f),m=p.indexOf(`
67
67
  `);m===-1?d=`-`:n===p||m!==p.length-1?(d=`+`,a&&a()):d=``,p&&=(n=n.slice(0,-p.length),p[p.length-1]===`
68
- `&&(p=p.slice(0,-1)),p.replace(sa,`$&${l}`));let h=!1,g,_=-1;for(g=0;g<n.length;++g){let e=n[g];if(e===` `)h=!0;else if(e===`
68
+ `&&(p=p.slice(0,-1)),p.replace(oa,`$&${l}`));let h=!1,g,_=-1;for(g=0;g<n.length;++g){let e=n[g];if(e===` `)h=!0;else if(e===`
69
69
  `)_=g;else break}let v=n.substring(0,_<g?_+1:g);v&&=(n=n.substring(v.length),v.replace(/\n+/g,`$&${l}`));let y=(h?l?`2`:`1`:``)+d;if(e&&(y+=` `+s(e.replace(/ ?[\r\n]+/g,` `)),i&&i()),!u){let e=n.replace(/\n+/g,`
70
- $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\n+/g,`$&${l}`),i=!1,a=aa(r,!0);o!==`folded`&&t!==R.BLOCK_FOLDED&&(a.onOverflow=()=>{i=!0});let s=Ki(`${v}${e}${p}`,l,Yi,a);if(!i)return`>${y}\n${l}${s}`}return n=n.replace(/\n+/g,`$&${l}`),`|${y}\n${l}${v}${n}${p}`}function ra(e,t,n,r){let{type:i,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
71
- `)||u&&/[[\]{},]/.test(a))return ta(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
72
- `)?ta(a,t):na(e,t,n,r);if(!s&&!u&&i!==R.PLAIN&&a.includes(`
73
- `))return na(e,t,n,r);if(oa(a)){if(c===``)return t.forceBlockIndent=!0,na(e,t,n,r);if(s&&c===l)return ta(a,t)}let d=a.replace(/\n+/g,`$&\n${c}`);if(o){let e=e=>e.default&&e.tag!==`tag:yaml.org,2002:str`&&e.test?.test(d),{compat:n,tags:r}=t.doc.schema;if(r.some(e)||n?.some(e))return ta(a,t)}return s?d:Ki(d,c,Ji,aa(t,!1))}function ia(e,t,n,r){let{implicitKey:i,inFlow:a}=t,o=typeof e.value==`string`?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==R.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=R.QUOTE_DOUBLE);let c=e=>{switch(e){case R.BLOCK_FOLDED:case R.BLOCK_LITERAL:return i||a?ta(o.value,t):na(o,t,n,r);case R.QUOTE_DOUBLE:return $i(o.value,t);case R.QUOTE_SINGLE:return ea(o.value,t);case R.PLAIN:return ra(o,t,n,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:e,defaultStringType:n}=t.options,r=i&&e||n;if(l=c(r),l===null)throw Error(`Unsupported default string type ${r}`)}return l}var aa,oa,sa,ca=F((()=>{Ni(),Zi(),aa=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),oa=e=>/^(%|---|\.\.\.)/m.test(e);try{sa=RegExp(`(^|(?<!
70
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\n+/g,`$&${l}`),i=!1,a=ia(r,!0);o!==`folded`&&t!==z.BLOCK_FOLDED&&(a.onOverflow=()=>{i=!0});let s=Gi(`${v}${e}${p}`,l,Ji,a);if(!i)return`>${y}\n${l}${s}`}return n=n.replace(/\n+/g,`$&${l}`),`|${y}\n${l}${v}${n}${p}`}function na(e,t,n,r){let{type:i,value:a}=e,{actualString:o,implicitKey:s,indent:c,indentStep:l,inFlow:u}=t;if(s&&a.includes(`
71
+ `)||u&&/[[\]{},]/.test(a))return ea(a,t);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(a))return s||u||!a.includes(`
72
+ `)?ea(a,t):ta(e,t,n,r);if(!s&&!u&&i!==z.PLAIN&&a.includes(`
73
+ `))return ta(e,t,n,r);if(aa(a)){if(c===``)return t.forceBlockIndent=!0,ta(e,t,n,r);if(s&&c===l)return ea(a,t)}let d=a.replace(/\n+/g,`$&\n${c}`);if(o){let e=e=>e.default&&e.tag!==`tag:yaml.org,2002:str`&&e.test?.test(d),{compat:n,tags:r}=t.doc.schema;if(r.some(e)||n?.some(e))return ea(a,t)}return s?d:Gi(d,c,qi,ia(t,!1))}function ra(e,t,n,r){let{implicitKey:i,inFlow:a}=t,o=typeof e.value==`string`?e:Object.assign({},e,{value:String(e.value)}),{type:s}=e;s!==z.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(o.value)&&(s=z.QUOTE_DOUBLE);let c=e=>{switch(e){case z.BLOCK_FOLDED:case z.BLOCK_LITERAL:return i||a?ea(o.value,t):ta(o,t,n,r);case z.QUOTE_DOUBLE:return Qi(o.value,t);case z.QUOTE_SINGLE:return $i(o.value,t);case z.PLAIN:return na(o,t,n,r);default:return null}},l=c(s);if(l===null){let{defaultKeyType:e,defaultStringType:n}=t.options,r=i&&e||n;if(l=c(r),l===null)throw Error(`Unsupported default string type ${r}`)}return l}var ia,aa,oa,sa=I((()=>{Mi(),Xi(),ia=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),aa=e=>/^(%|---|\.\.\.)/m.test(e);try{oa=RegExp(`(^|(?<!
74
74
  ))
75
75
  +(?!
76
- |$)`,`g`)}catch{sa=/\n+(?!\n|$)/g}}));function la(e,t){let n=Object.assign({blockQuote:!0,commentString:Ui,defaultKeyType:null,defaultStringType:`PLAIN`,directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:`false`,flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:`null`,simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:`true`,verifyAliasOrder:!0},e.schema.toStringOptions,t),r;switch(n.collectionStyle){case`block`:r=!1;break;case`flow`:r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?` `:``,indent:``,indentStep:typeof n.indent==`number`?` `.repeat(n.indent):` `,inFlow:r,options:n}}function ua(e,t){if(t.tag){let n=e.filter(e=>e.tag===t.tag);if(n.length>0)return n.find(e=>e.format===t.format)??n[0]}let n,r;if(ei(t)){r=t.value;let i=e.filter(e=>e.identify?.(r));if(i.length>1){let e=i.filter(e=>e.test);e.length>0&&(i=e)}n=i.find(e=>e.format===t.format)??i.find(e=>!e.format)}else r=t,n=e.find(e=>e.nodeClass&&r instanceof e.nodeClass);if(!n){let e=r?.constructor?.name??(r===null?`null`:typeof r);throw Error(`Tag not resolved for ${e} value`)}return n}function da(e,t,{anchors:n,doc:r}){if(!r.directives)return``;let i=[],a=(ei(e)||Vr(e))&&e.anchor;a&&vi(a)&&(n.add(a),i.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&i.push(r.directives.tagString(o)),i.join(` `)}function fa(e,t,n,r){if($r(e))return e.toString(t,n,r);if(Xr(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw TypeError(`Cannot stringify circular structure without alias nodes`);t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let i,a=Hr(e)?e:t.doc.createNode(e,{onTagObj:e=>i=e});i??=ua(t.doc.schema.tags,a);let o=da(a,i,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof i.stringify==`function`?i.stringify(a,t,n,r):ei(a)?ia(a,t,n,r):a.toString(t,n,r);return o?ei(a)||s[0]===`{`||s[0]===`[`?`${o} ${s}`:`${o}\n${t.indent}${s}`:s}var pa=F((()=>{Si(),L(),Gi(),ca()}));function ma({key:e,value:t},n,r,i){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=n,f=Hr(e)&&e.comment||null;if(d){if(f)throw Error(`With simple keys, key nodes cannot have comments`);if(Vr(e)||!Hr(e)&&typeof e==`object`)throw Error(`With simple keys, collection cannot be used as a key value`)}let p=!d&&(!e||f&&t==null&&!n.inFlow||Vr(e)||(ei(e)?e.type===R.BLOCK_FOLDED||e.type===R.BLOCK_LITERAL:typeof e==`object`));n=Object.assign({},n,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let m=!1,h=!1,g=fa(e,n,()=>m=!0,()=>h=!0);if(!p&&!n.inFlow&&g.length>1024){if(d)throw Error(`With simple keys, single line scalar must not span more than 1024 characters`);p=!0}if(n.inFlow){if(a||t==null)return m&&r&&r(),g===``?`?`:p?`? ${g}`:g}else if(a&&!d||t==null&&p)return g=`? ${g}`,f&&!m?g+=Wi(g,n.indent,l(f)):h&&i&&i(),g;m&&(f=null),p?(f&&(g+=Wi(g,n.indent,l(f))),g=`? ${g}\n${s}:`):(g=`${g}:`,f&&(g+=Wi(g,n.indent,l(f))));let _,v,y;Hr(t)?(_=!!t.spaceBefore,v=t.commentBefore,y=t.comment):(_=!1,v=null,y=null,t&&typeof t==`object`&&(t=o.createNode(t))),n.implicitKey=!1,!p&&!f&&ei(t)&&(n.indentAtStart=g.length+1),h=!1,!u&&c.length>=2&&!n.inFlow&&!p&&ti(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let b=!1,x=fa(t,n,()=>b=!0,()=>h=!0),S=` `;if(f||_||v){if(S=_?`
77
- `:``,v){let e=l(v);S+=`\n${Hi(e,n.indent)}`}x===``&&!n.inFlow?S===`
76
+ |$)`,`g`)}catch{oa=/\n+(?!\n|$)/g}}));function ca(e,t){let n=Object.assign({blockQuote:!0,commentString:Hi,defaultKeyType:null,defaultStringType:`PLAIN`,directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:`false`,flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:`null`,simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:`true`,verifyAliasOrder:!0},e.schema.toStringOptions,t),r;switch(n.collectionStyle){case`block`:r=!1;break;case`flow`:r=!0;break;default:r=null}return{anchors:new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?` `:``,indent:``,indentStep:typeof n.indent==`number`?` `.repeat(n.indent):` `,inFlow:r,options:n}}function la(e,t){if(t.tag){let n=e.filter(e=>e.tag===t.tag);if(n.length>0)return n.find(e=>e.format===t.format)??n[0]}let n,r;if($r(t)){r=t.value;let i=e.filter(e=>e.identify?.(r));if(i.length>1){let e=i.filter(e=>e.test);e.length>0&&(i=e)}n=i.find(e=>e.format===t.format)??i.find(e=>!e.format)}else r=t,n=e.find(e=>e.nodeClass&&r instanceof e.nodeClass);if(!n){let e=r?.constructor?.name??(r===null?`null`:typeof r);throw Error(`Tag not resolved for ${e} value`)}return n}function ua(e,t,{anchors:n,doc:r}){if(!r.directives)return``;let i=[],a=($r(e)||Br(e))&&e.anchor;a&&_i(a)&&(n.add(a),i.push(`&${a}`));let o=e.tag??(t.default?null:t.tag);return o&&i.push(r.directives.tagString(o)),i.join(` `)}function da(e,t,n,r){if(Qr(e))return e.toString(t,n,r);if(Yr(e)){if(t.doc.directives)return e.toString(t);if(t.resolvedAliases?.has(e))throw TypeError(`Cannot stringify circular structure without alias nodes`);t.resolvedAliases?t.resolvedAliases.add(e):t.resolvedAliases=new Set([e]),e=e.resolve(t.doc)}let i,a=Vr(e)?e:t.doc.createNode(e,{onTagObj:e=>i=e});i??=la(t.doc.schema.tags,a);let o=ua(a,i,t);o.length>0&&(t.indentAtStart=(t.indentAtStart??0)+o.length+1);let s=typeof i.stringify==`function`?i.stringify(a,t,n,r):$r(a)?ra(a,t,n,r):a.toString(t,n,r);return o?$r(a)||s[0]===`{`||s[0]===`[`?`${o} ${s}`:`${o}\n${t.indent}${s}`:s}var fa=I((()=>{xi(),R(),Wi(),sa()}));function pa({key:e,value:t},n,r,i){let{allNullValues:a,doc:o,indent:s,indentStep:c,options:{commentString:l,indentSeq:u,simpleKeys:d}}=n,f=Vr(e)&&e.comment||null;if(d){if(f)throw Error(`With simple keys, key nodes cannot have comments`);if(Br(e)||!Vr(e)&&typeof e==`object`)throw Error(`With simple keys, collection cannot be used as a key value`)}let p=!d&&(!e||f&&t==null&&!n.inFlow||Br(e)||($r(e)?e.type===z.BLOCK_FOLDED||e.type===z.BLOCK_LITERAL:typeof e==`object`));n=Object.assign({},n,{allNullValues:!1,implicitKey:!p&&(d||!a),indent:s+c});let m=!1,h=!1,g=da(e,n,()=>m=!0,()=>h=!0);if(!p&&!n.inFlow&&g.length>1024){if(d)throw Error(`With simple keys, single line scalar must not span more than 1024 characters`);p=!0}if(n.inFlow){if(a||t==null)return m&&r&&r(),g===``?`?`:p?`? ${g}`:g}else if(a&&!d||t==null&&p)return g=`? ${g}`,f&&!m?g+=Ui(g,n.indent,l(f)):h&&i&&i(),g;m&&(f=null),p?(f&&(g+=Ui(g,n.indent,l(f))),g=`? ${g}\n${s}:`):(g=`${g}:`,f&&(g+=Ui(g,n.indent,l(f))));let _,v,y;Vr(t)?(_=!!t.spaceBefore,v=t.commentBefore,y=t.comment):(_=!1,v=null,y=null,t&&typeof t==`object`&&(t=o.createNode(t))),n.implicitKey=!1,!p&&!f&&$r(t)&&(n.indentAtStart=g.length+1),h=!1,!u&&c.length>=2&&!n.inFlow&&!p&&ei(t)&&!t.flow&&!t.tag&&!t.anchor&&(n.indent=n.indent.substring(2));let b=!1,x=da(t,n,()=>b=!0,()=>h=!0),S=` `;if(f||_||v){if(S=_?`
77
+ `:``,v){let e=l(v);S+=`\n${Vi(e,n.indent)}`}x===``&&!n.inFlow?S===`
78
78
  `&&y&&(S=`
79
79
 
80
- `):S+=`\n${n.indent}`}else if(!p&&Vr(t)){let e=x[0],r=x.indexOf(`
80
+ `):S+=`\n${n.indent}`}else if(!p&&Br(t)){let e=x[0],r=x.indexOf(`
81
81
  `),i=r!==-1,a=n.inFlow??t.flow??t.items.length===0;if(i||!a){let t=!1;if(i&&(e===`&`||e===`!`)){let n=x.indexOf(` `);e===`&`&&n!==-1&&n<r&&x[n+1]===`!`&&(n=x.indexOf(` `,n+1)),(n===-1||r<n)&&(t=!0)}t||(S=`\n${n.indent}`)}}else(x===``||x[0]===`
82
- `)&&(S=``);return g+=S+x,n.inFlow?b&&r&&r():y&&!b?g+=Wi(g,n.indent,l(y)):h&&i&&i(),g}var ha=F((()=>{L(),Ni(),pa(),Gi()}));function ga(e,t){(e===`debug`||e===`warn`)&&console.warn(t)}var _a=F((()=>{}));function va(e,t,n){let r=ba(e,n);if(ti(r))for(let n of r.items)ya(e,t,n);else if(Array.isArray(r))for(let n of r)ya(e,t,n);else ya(e,t,r)}function ya(e,t,n){let r=ba(e,n);if(!Qr(r))throw Error(`Merge sources must be maps or map aliases`);let i=r.toJSON(null,e,Map);for(let[e,n]of i)t instanceof Map?t.has(e)||t.set(e,n):t instanceof Set?t.add(e):Object.prototype.hasOwnProperty.call(t,e)||Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0});return t}function ba(e,t){return e&&Xr(t)?t.resolve(e.doc,e):t}var xa,Sa,Ca,wa=F((()=>{L(),Ni(),xa=`<<`,Sa={identify:e=>e===xa||typeof e==`symbol`&&e.description===xa,default:`key`,tag:`tag:yaml.org,2002:merge`,test:/^<<$/,resolve:()=>Object.assign(new R(Symbol(xa)),{addToJSMap:va}),stringify:()=>xa},Ca=(e,t)=>(Sa.identify(t)||ei(t)&&(!t.type||t.type===R.PLAIN)&&Sa.identify(t.value))&&e?.doc.schema.tags.some(e=>e.tag===Sa.tag&&e.default)}));function Ta(e,t,{key:n,value:r}){if(Hr(n)&&n.addToJSMap)n.addToJSMap(e,t,r);else if(Ca(e,n))va(e,t,r);else{let i=Ti(n,``,e);if(t instanceof Map)t.set(i,Ti(r,i,e));else if(t instanceof Set)t.add(i);else{let a=Ea(n,i,e),o=Ti(r,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function Ea(e,t,n){if(t===null)return``;if(typeof t!=`object`)return String(t);if(Hr(e)&&n?.doc){let t=la(n.doc,{});t.anchors=new Set;for(let e of n.anchors.keys())t.anchors.add(e.anchor);t.inFlow=!0,t.inStringifyKey=!0;let r=e.toString(t);if(!n.mapKeyWarned){let e=JSON.stringify(r);e.length>40&&(e=e.substring(0,36)+`..."`),ga(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${e}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return r}return JSON.stringify(t)}var Da=F((()=>{_a(),wa(),pa(),L(),Ei()}));function Oa(e,t,n){let r=Fi(e,void 0,n),i=Fi(t,void 0,n);return new ka(r,i)}var ka,Aa=F((()=>{Li(),ha(),Da(),L(),ka=class e{constructor(e,t=null){Object.defineProperty(this,Yr,{value:Kr}),this.key=e,this.value=t}clone(t){let{key:n,value:r}=this;return Hr(n)&&(n=n.clone(t)),Hr(r)&&(r=r.clone(t)),new e(n,r)}toJSON(e,t){return Ta(t,t?.mapAsMap?new Map:{},this)}toString(e,t,n){return e?.doc?ma(this,e,t,n):JSON.stringify(this)}}}));function ja(e,t,n){return(t.inFlow??e.flow?Na:Ma)(e,t,n)}function Ma({comment:e,items:t},n,{blockItemPrefix:r,flowChars:i,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=n,u=Object.assign({},n,{indent:a,type:null}),d=!1,f=[];for(let e=0;e<t.length;++e){let i=t[e],o=null;if(Hr(i))!d&&i.spaceBefore&&f.push(``),Pa(n,f,i.commentBefore,d),i.comment&&(o=i.comment);else if($r(i)){let e=Hr(i.key)?i.key:null;e&&(!d&&e.spaceBefore&&f.push(``),Pa(n,f,e.commentBefore,d))}d=!1;let s=fa(i,u,()=>o=null,()=>d=!0);o&&(s+=Wi(s,a,l(o))),d&&o&&(d=!1),f.push(r+s)}let p;if(f.length===0)p=i.start+i.end;else{p=f[0];for(let e=1;e<f.length;++e){let t=f[e];p+=t?`\n${c}${t}`:`
82
+ `)&&(S=``);return g+=S+x,n.inFlow?b&&r&&r():y&&!b?g+=Ui(g,n.indent,l(y)):h&&i&&i(),g}var ma=I((()=>{R(),Mi(),fa(),Wi()}));function ha(e,t){(e===`debug`||e===`warn`)&&console.warn(t)}var ga=I((()=>{}));function _a(e,t,n){let r=ya(e,n);if(ei(r))for(let n of r.items)va(e,t,n);else if(Array.isArray(r))for(let n of r)va(e,t,n);else va(e,t,r)}function va(e,t,n){let r=ya(e,n);if(!Zr(r))throw Error(`Merge sources must be maps or map aliases`);let i=r.toJSON(null,e,Map);for(let[e,n]of i)t instanceof Map?t.has(e)||t.set(e,n):t instanceof Set?t.add(e):Object.prototype.hasOwnProperty.call(t,e)||Object.defineProperty(t,e,{value:n,writable:!0,enumerable:!0,configurable:!0});return t}function ya(e,t){return e&&Yr(t)?t.resolve(e.doc,e):t}var ba,xa,Sa,Ca=I((()=>{R(),Mi(),ba=`<<`,xa={identify:e=>e===ba||typeof e==`symbol`&&e.description===ba,default:`key`,tag:`tag:yaml.org,2002:merge`,test:/^<<$/,resolve:()=>Object.assign(new z(Symbol(ba)),{addToJSMap:_a}),stringify:()=>ba},Sa=(e,t)=>(xa.identify(t)||$r(t)&&(!t.type||t.type===z.PLAIN)&&xa.identify(t.value))&&e?.doc.schema.tags.some(e=>e.tag===xa.tag&&e.default)}));function wa(e,t,{key:n,value:r}){if(Vr(n)&&n.addToJSMap)n.addToJSMap(e,t,r);else if(Sa(e,n))_a(e,t,r);else{let i=wi(n,``,e);if(t instanceof Map)t.set(i,wi(r,i,e));else if(t instanceof Set)t.add(i);else{let a=Ta(n,i,e),o=wi(r,a,e);a in t?Object.defineProperty(t,a,{value:o,writable:!0,enumerable:!0,configurable:!0}):t[a]=o}}return t}function Ta(e,t,n){if(t===null)return``;if(typeof t!=`object`)return String(t);if(Vr(e)&&n?.doc){let t=ca(n.doc,{});t.anchors=new Set;for(let e of n.anchors.keys())t.anchors.add(e.anchor);t.inFlow=!0,t.inStringifyKey=!0;let r=e.toString(t);if(!n.mapKeyWarned){let e=JSON.stringify(r);e.length>40&&(e=e.substring(0,36)+`..."`),ha(n.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${e}. Set mapAsMap: true to use object keys.`),n.mapKeyWarned=!0}return r}return JSON.stringify(t)}var Ea=I((()=>{ga(),Ca(),fa(),R(),Ti()}));function Da(e,t,n){let r=Pi(e,void 0,n),i=Pi(t,void 0,n);return new Oa(r,i)}var Oa,ka=I((()=>{Ii(),ma(),Ea(),R(),Oa=class e{constructor(e,t=null){Object.defineProperty(this,Jr,{value:Gr}),this.key=e,this.value=t}clone(t){let{key:n,value:r}=this;return Vr(n)&&(n=n.clone(t)),Vr(r)&&(r=r.clone(t)),new e(n,r)}toJSON(e,t){return wa(t,t?.mapAsMap?new Map:{},this)}toString(e,t,n){return e?.doc?pa(this,e,t,n):JSON.stringify(this)}}}));function Aa(e,t,n){return(t.inFlow??e.flow?Ma:ja)(e,t,n)}function ja({comment:e,items:t},n,{blockItemPrefix:r,flowChars:i,itemIndent:a,onChompKeep:o,onComment:s}){let{indent:c,options:{commentString:l}}=n,u=Object.assign({},n,{indent:a,type:null}),d=!1,f=[];for(let e=0;e<t.length;++e){let i=t[e],o=null;if(Vr(i))!d&&i.spaceBefore&&f.push(``),Na(n,f,i.commentBefore,d),i.comment&&(o=i.comment);else if(Qr(i)){let e=Vr(i.key)?i.key:null;e&&(!d&&e.spaceBefore&&f.push(``),Na(n,f,e.commentBefore,d))}d=!1;let s=da(i,u,()=>o=null,()=>d=!0);o&&(s+=Ui(s,a,l(o))),d&&o&&(d=!1),f.push(r+s)}let p;if(f.length===0)p=i.start+i.end;else{p=f[0];for(let e=1;e<f.length;++e){let t=f[e];p+=t?`\n${c}${t}`:`
83
83
  `}}return e?(p+=`
84
- `+Hi(l(e),c),s&&s()):d&&o&&o(),p}function Na({items:e},t,{flowChars:n,itemIndent:r}){let{indent:i,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;r+=a;let c=Object.assign({},t,{indent:r,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let n=0;n<e.length;++n){let i=e[n],a=null;if(Hr(i))i.spaceBefore&&d.push(``),Pa(t,d,i.commentBefore,!1),i.comment&&(a=i.comment);else if($r(i)){let e=Hr(i.key)?i.key:null;e&&(e.spaceBefore&&d.push(``),Pa(t,d,e.commentBefore,!1),e.comment&&(l=!0));let n=Hr(i.value)?i.value:null;n?(n.comment&&(a=n.comment),n.commentBefore&&(l=!0)):i.value==null&&e?.comment&&(a=e.comment)}a&&(l=!0);let o=fa(i,c,()=>a=null);l||=d.length>u||o.includes(`
85
- `),n<e.length-1?o+=`,`:t.options.trailingComma&&(t.options.lineWidth>0&&(l||=d.reduce((e,t)=>e+t.length+2,2)+(o.length+2)>t.options.lineWidth),l&&(o+=`,`)),a&&(o+=Wi(o,r,s(a))),d.push(o),u=d.length}let{start:f,end:p}=n;if(d.length===0)return f+p;if(!l){let e=d.reduce((e,t)=>e+t.length+2,2);l=t.options.lineWidth>0&&e>t.options.lineWidth}if(l){let e=f;for(let t of d)e+=t?`\n${a}${i}${t}`:`
86
- `;return`${e}\n${i}${p}`}return`${f}${o}${d.join(` `)}${o}${p}`}function Pa({indent:e,options:{commentString:t}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,``)),r){let i=Hi(t(r),e);n.push(i.trimStart())}}var Fa=F((()=>{L(),pa(),Gi()}));function Ia(e,t){let n=ei(t)?t.value:t;for(let r of e)if($r(r)&&(r.key===t||r.key===n||ei(r.key)&&r.key.value===n))return r}var La,Ra=F((()=>{Fa(),Da(),Vi(),L(),Aa(),Ni(),La=class extends Bi{static get tagName(){return`tag:yaml.org,2002:map`}constructor(e){super(Gr,e),this.items=[]}static from(e,t,n){let{keepUndefined:r,replacer:i}=n,a=new this(e),o=(e,o)=>{if(typeof i==`function`)o=i.call(t,e,o);else if(Array.isArray(i)&&!i.includes(e))return;(o!==void 0||r)&&a.items.push(Oa(e,o,n))};if(t instanceof Map)for(let[e,n]of t)o(e,n);else if(t&&typeof t==`object`)for(let e of Object.keys(t))o(e,t[e]);return typeof e.sortMapEntries==`function`&&a.items.sort(e.sortMapEntries),a}add(e,t){let n;n=$r(e)?e:!e||typeof e!=`object`||!(`key`in e)?new ka(e,e?.value):new ka(e.key,e.value);let r=Ia(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw Error(`Key ${n.key} already set`);ei(r.value)&&Mi(n.value)?r.value.value=n.value:r.value=n.value}else if(i){let e=this.items.findIndex(e=>i(n,e)<0);e===-1?this.items.push(n):this.items.splice(e,0,n)}else this.items.push(n)}delete(e){let t=Ia(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let n=Ia(this.items,e)?.value;return(!t&&ei(n)?n.value:n)??void 0}has(e){return!!Ia(this.items,e)}set(e,t){this.add(new ka(e,t),!0)}toJSON(e,t,n){let r=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(r);for(let e of this.items)Ta(t,r,e);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(let e of this.items)if(!$r(e))throw Error(`Map items must all be pairs; found ${JSON.stringify(e)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),ja(this,e,{blockItemPrefix:``,flowChars:{start:`{`,end:`}`},itemIndent:e.indent||``,onChompKeep:n,onComment:t})}}})),za,Ba=F((()=>{L(),Ra(),za={collection:`map`,default:!0,nodeClass:La,tag:`tag:yaml.org,2002:map`,resolve(e,t){return Qr(e)||t(`Expected a mapping for this tag`),e},createNode:(e,t,n)=>La.from(e,t,n)}}));function Va(e){let t=ei(e)?e.value:e;return t&&typeof t==`string`&&(t=Number(t)),typeof t==`number`&&Number.isInteger(t)&&t>=0?t:null}var Ha,Ua=F((()=>{Li(),Fa(),Vi(),L(),Ni(),Ei(),Ha=class extends Bi{static get tagName(){return`tag:yaml.org,2002:seq`}constructor(e){super(Jr,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=Va(e);return typeof t==`number`&&this.items.splice(t,1).length>0}get(e,t){let n=Va(e);if(typeof n!=`number`)return;let r=this.items[n];return!t&&ei(r)?r.value:r}has(e){let t=Va(e);return typeof t==`number`&&t<this.items.length}set(e,t){let n=Va(e);if(typeof n!=`number`)throw Error(`Expected a valid index, not ${e}.`);let r=this.items[n];ei(r)&&Mi(t)?r.value=t:this.items[n]=t}toJSON(e,t){let n=[];t?.onCreate&&t.onCreate(n);let r=0;for(let e of this.items)n.push(Ti(e,String(r++),t));return n}toString(e,t,n){return e?ja(this,e,{blockItemPrefix:`- `,flowChars:{start:`[`,end:`]`},itemIndent:(e.indent||``)+` `,onChompKeep:n,onComment:t}):JSON.stringify(this)}static from(e,t,n){let{replacer:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t)){let e=0;for(let a of t){if(typeof r==`function`){let n=t instanceof Set?a:String(e++);a=r.call(t,n,a)}i.items.push(Fi(a,void 0,n))}}return i}}})),Wa,Ga=F((()=>{L(),Ua(),Wa={collection:`seq`,default:!0,nodeClass:Ha,tag:`tag:yaml.org,2002:seq`,resolve(e,t){return ti(e)||t(`Expected a sequence for this tag`),e},createNode:(e,t,n)=>Ha.from(e,t,n)}})),Ka,qa=F((()=>{ca(),Ka={identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify(e,t,n,r){return t=Object.assign({actualString:!0},t),ia(e,t,n,r)}}})),Ja,Ya=F((()=>{Ni(),Ja={identify:e=>e==null,createNode:()=>new R(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new R(null),stringify:({source:e},t)=>typeof e==`string`&&Ja.test.test(e)?e:t.options.nullStr}})),Xa,Za=F((()=>{Ni(),Xa={identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new R(e[0]===`t`||e[0]===`T`),stringify({source:e,value:t},n){return e&&Xa.test.test(e)&&t===(e[0]===`t`||e[0]===`T`)?e:t?n.options.trueStr:n.options.falseStr}}}));function Qa({format:e,minFractionDigits:t,tag:n,value:r}){if(typeof r==`bigint`)return String(r);let i=typeof r==`number`?r:Number(r);if(!isFinite(i))return isNaN(i)?`.nan`:i<0?`-.inf`:`.inf`;let a=Object.is(r,-0)?`-0`:JSON.stringify(r);if(!e&&t&&(!n||n===`tag:yaml.org,2002:float`)&&/^-?\d/.test(a)&&!a.includes(`e`)){let e=a.indexOf(`.`);e<0&&(e=a.length,a+=`.`);let n=t-(a.length-e-1);for(;n-->0;)a+=`0`}return a}var $a=F((()=>{})),eo,to,no,ro=F((()=>{Ni(),$a(),eo={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()===`nan`?NaN:e[0]===`-`?-1/0:1/0,stringify:Qa},to={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():Qa(e)}},no={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new R(parseFloat(e)),n=e.indexOf(`.`);return n!==-1&&e[e.length-1]===`0`&&(t.minFractionDigits=e.length-n-1),t},stringify:Qa}}));function io(e,t,n){let{value:r}=e;return ao(r)&&r>=0?n+r.toString(t):Qa(e)}var ao,oo,so,co,lo,uo=F((()=>{$a(),ao=e=>typeof e==`bigint`||Number.isInteger(e),oo=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n),so={identify:e=>ao(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^0o[0-7]+$/,resolve:(e,t,n)=>oo(e,2,8,n),stringify:e=>io(e,8,`0o`)},co={identify:ao,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>oo(e,0,10,n),stringify:Qa},lo={identify:e=>ao(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>oo(e,2,16,n),stringify:e=>io(e,16,`0x`)}})),fo,po=F((()=>{Ba(),Ya(),Ga(),qa(),Za(),ro(),uo(),fo=[za,Wa,Ka,Ja,Xa,so,co,lo,eo,to,no]}));function mo(e){return typeof e==`bigint`||Number.isInteger(e)}var ho,go,_o,vo=F((()=>{Ni(),Ba(),Ga(),ho=({value:e})=>JSON.stringify(e),go=[{identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify:ho},{identify:e=>e==null,createNode:()=>new R(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^null$/,resolve:()=>null,stringify:ho},{identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^true$|^false$/,resolve:e=>e===`true`,stringify:ho},{identify:mo,default:!0,tag:`tag:yaml.org,2002:int`,test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:n})=>n?BigInt(e):parseInt(e,10),stringify:({value:e})=>mo(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:ho}],_o=[za,Wa].concat(go,{default:!0,tag:``,test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}})})),yo,bo=F((()=>{Ni(),ca(),yo={identify:e=>e instanceof Uint8Array,default:!1,tag:`tag:yaml.org,2002:binary`,resolve(e,t){if(typeof atob==`function`){let t=atob(e.replace(/[\n\r]/g,``)),n=new Uint8Array(t.length);for(let e=0;e<t.length;++e)n[e]=t.charCodeAt(e);return n}return t(`This environment does not support reading binary tags; either Buffer or atob is required`),e},stringify({comment:e,type:t,value:n},r,i,a){if(!n)return``;let o=n,s;if(typeof btoa==`function`){let e=``;for(let t=0;t<o.length;++t)e+=String.fromCharCode(o[t]);s=btoa(e)}else throw Error(`This environment does not support writing binary tags; either Buffer or btoa is required`);if(t??=R.BLOCK_LITERAL,t!==R.QUOTE_DOUBLE){let e=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),n=Math.ceil(s.length/e),i=Array(n);for(let t=0,r=0;t<n;++t,r+=e)i[t]=s.substr(r,e);s=i.join(t===R.BLOCK_LITERAL?`
87
- `:` `)}return ia({comment:e,type:t,value:s},r,i,a)}}}));function xo(e,t){if(ti(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!$r(r)){if(Qr(r)){r.items.length>1&&t(`Each pair must have its own sequence indicator`);let e=r.items[0]||new ka(new R(null));if(r.commentBefore&&(e.key.commentBefore=e.key.commentBefore?`${r.commentBefore}\n${e.key.commentBefore}`:r.commentBefore),r.comment){let t=e.value??e.key;t.comment=t.comment?`${r.comment}\n${t.comment}`:r.comment}r=e}e.items[n]=$r(r)?r:new ka(r)}}else t(`Expected a sequence for this tag`);return e}function So(e,t,n){let{replacer:r}=n,i=new Ha(e);i.tag=`tag:yaml.org,2002:pairs`;let a=0;if(t&&Symbol.iterator in Object(t))for(let e of t){typeof r==`function`&&(e=r.call(t,String(a++),e));let o,s;if(Array.isArray(e)){if(e.length===2)o=e[0],s=e[1];else throw TypeError(`Expected [key, value] tuple: ${e}`)}else if(e&&e instanceof Object){let t=Object.keys(e);if(t.length===1)o=t[0],s=e[o];else throw TypeError(`Expected tuple with one key, not ${t.length} keys`)}else o=e;i.items.push(Oa(o,s,n))}return i}var Co,wo=F((()=>{L(),Aa(),Ni(),Ua(),Co={collection:`seq`,default:!1,tag:`tag:yaml.org,2002:pairs`,resolve:xo,createNode:So}})),To,Eo,Do=F((()=>{L(),Ei(),Ra(),Ua(),wo(),To=class e extends Ha{constructor(){super(),this.add=La.prototype.add.bind(this),this.delete=La.prototype.delete.bind(this),this.get=La.prototype.get.bind(this),this.has=La.prototype.has.bind(this),this.set=La.prototype.set.bind(this),this.tag=e.tag}toJSON(e,t){if(!t)return super.toJSON(e);let n=new Map;t?.onCreate&&t.onCreate(n);for(let e of this.items){let r,i;if($r(e)?(r=Ti(e.key,``,t),i=Ti(e.value,r,t)):r=Ti(e,``,t),n.has(r))throw Error(`Ordered maps must not include duplicate keys`);n.set(r,i)}return n}static from(e,t,n){let r=So(e,t,n),i=new this;return i.items=r.items,i}},To.tag=`tag:yaml.org,2002:omap`,Eo={collection:`seq`,identify:e=>e instanceof Map,nodeClass:To,default:!1,tag:`tag:yaml.org,2002:omap`,resolve(e,t){let n=xo(e,t),r=[];for(let{key:e}of n.items)ei(e)&&(r.includes(e.value)?t(`Ordered maps must not include duplicate keys: ${e.value}`):r.push(e.value));return Object.assign(new To,n)},createNode:(e,t,n)=>To.from(e,t,n)}}));function Oo({value:e,source:t},n){return t&&(e?ko:Ao).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var ko,Ao,jo=F((()=>{Ni(),ko={identify:e=>e===!0,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new R(!0),stringify:Oo},Ao={identify:e=>e===!1,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new R(!1),stringify:Oo}})),Mo,No,Po,Fo=F((()=>{Ni(),$a(),Mo={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()===`nan`?NaN:e[0]===`-`?-1/0:1/0,stringify:Qa},No={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,``)),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():Qa(e)}},Po={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new R(parseFloat(e.replace(/_/g,``))),n=e.indexOf(`.`);if(n!==-1){let r=e.substring(n+1).replace(/_/g,``);r[r.length-1]===`0`&&(t.minFractionDigits=r.length)}return t},stringify:Qa}}));function Io(e,t,n,{intAsBigInt:r}){let i=e[0];if((i===`-`||i===`+`)&&(t+=1),e=e.substring(t).replace(/_/g,``),r){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`}let t=BigInt(e);return i===`-`?BigInt(-1)*t:t}let a=parseInt(e,n);return i===`-`?-1*a:a}function Lo(e,t,n){let{value:r}=e;if(Ro(r)){let e=r.toString(t);return r<0?`-`+n+e.substr(1):n+e}return Qa(e)}var Ro,zo,Bo,Vo,Ho,Uo=F((()=>{$a(),Ro=e=>typeof e==`bigint`||Number.isInteger(e),zo={identify:Ro,default:!0,tag:`tag:yaml.org,2002:int`,format:`BIN`,test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>Io(e,2,2,n),stringify:e=>Lo(e,2,`0b`)},Bo={identify:Ro,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>Io(e,1,8,n),stringify:e=>Lo(e,8,`0`)},Vo={identify:Ro,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>Io(e,0,10,n),stringify:Qa},Ho={identify:Ro,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>Io(e,2,16,n),stringify:e=>Lo(e,16,`0x`)}})),Wo,Go,Ko=F((()=>{L(),Aa(),Ra(),Wo=class e extends La{constructor(t){super(t),this.tag=e.tag}add(e){let t;t=$r(e)?e:e&&typeof e==`object`&&`key`in e&&`value`in e&&e.value===null?new ka(e.key,null):new ka(e,null),Ia(this.items,t.key)||this.items.push(t)}get(e,t){let n=Ia(this.items,e);return!t&&$r(n)?ei(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!=`boolean`)throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let n=Ia(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new ka(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw Error(`Set items must all have null values`)}static from(e,t,n){let{replacer:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t))for(let e of t)typeof r==`function`&&(e=r.call(t,e,e)),i.items.push(Oa(e,null,n));return i}},Wo.tag=`tag:yaml.org,2002:set`,Go={collection:`map`,identify:e=>e instanceof Set,nodeClass:Wo,default:!1,tag:`tag:yaml.org,2002:set`,createNode:(e,t,n)=>Wo.from(e,t,n),resolve(e,t){if(Qr(e)){if(e.hasAllNullValues(!0))return Object.assign(new Wo,e);t(`Set items must all have null values`)}else t(`Expected a mapping for this tag`);return e}}}));function qo(e,t){let n=e[0],r=n===`-`||n===`+`?e.substring(1):e,i=e=>t?BigInt(e):Number(e),a=r.replace(/_/g,``).split(`:`).reduce((e,t)=>e*i(60)+i(t),i(0));return n===`-`?i(-1)*a:a}function Jo(e){let{value:t}=e,n=e=>e;if(typeof t==`bigint`)n=e=>BigInt(e);else if(isNaN(t)||!isFinite(t))return Qa(e);let r=``;t<0&&(r=`-`,t*=n(-1));let i=n(60),a=[t%i];return t<60?a.unshift(0):(t=(t-a[0])/i,a.unshift(t%i),t>=60&&(t=(t-a[0])/i,a.unshift(t))),r+a.map(e=>String(e).padStart(2,`0`)).join(`:`).replace(/000000\d*$/,``)}var Yo,Xo,Zo,Qo=F((()=>{$a(),Yo={identify:e=>typeof e==`bigint`||Number.isInteger(e),default:!0,tag:`tag:yaml.org,2002:int`,format:`TIME`,test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:n})=>qo(e,n),stringify:Jo},Xo={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`TIME`,test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>qo(e,!1),stringify:Jo},Zo={identify:e=>e instanceof Date,default:!0,tag:`tag:yaml.org,2002:timestamp`,test:RegExp(`^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$`),resolve(e){let t=e.match(Zo.test);if(!t)throw Error(`!!timestamp expects a date, starting with yyyy-mm-dd`);let[,n,r,i,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+`00`).substr(1,3)):0,l=Date.UTC(n,r-1,i,a||0,o||0,s||0,c),u=t[8];if(u&&u!==`Z`){let e=qo(u,!1);Math.abs(e)<30&&(e*=60),l-=6e4*e}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,``)??``}})),$o,es=F((()=>{Ba(),Ya(),Ga(),qa(),bo(),jo(),Fo(),Uo(),wa(),Do(),wo(),Ko(),Qo(),$o=[za,Wa,Ka,Ja,ko,Ao,zo,Bo,Vo,Ho,Mo,No,Po,yo,Sa,Eo,Co,Go,Yo,Xo,Zo]}));function ts(e,t,n){let r=ns.get(t);if(r&&!e)return n&&!r.includes(Sa)?r.concat(Sa):r.slice();let i=r;if(!i){if(Array.isArray(e))i=[];else{let e=Array.from(ns.keys()).filter(e=>e!==`yaml11`).map(e=>JSON.stringify(e)).join(`, `);throw Error(`Unknown schema "${t}"; use one of ${e} or define customTags array`)}}if(Array.isArray(e))for(let t of e)i=i.concat(t);else typeof e==`function`&&(i=e(i.slice()));return n&&(i=i.concat(Sa)),i.reduce((e,t)=>{let n=typeof t==`string`?rs[t]:t;if(!n){let e=JSON.stringify(t),n=Object.keys(rs).map(e=>JSON.stringify(e)).join(`, `);throw Error(`Unknown custom tag ${e}; use one of ${n}`)}return e.includes(n)||e.push(n),e},[])}var ns,rs,is,as=F((()=>{Ba(),Ya(),Ga(),qa(),Za(),ro(),uo(),po(),vo(),bo(),wa(),Do(),wo(),es(),Ko(),Qo(),ns=new Map([[`core`,fo],[`failsafe`,[za,Wa,Ka]],[`json`,_o],[`yaml11`,$o],[`yaml-1.1`,$o]]),rs={binary:yo,bool:Xa,float:no,floatExp:to,floatNaN:eo,floatTime:Xo,int:co,intHex:lo,intOct:so,intTime:Yo,map:za,merge:Sa,null:Ja,omap:Eo,pairs:Co,seq:Wa,set:Go,timestamp:Zo},is={"tag:yaml.org,2002:binary":yo,"tag:yaml.org,2002:merge":Sa,"tag:yaml.org,2002:omap":Eo,"tag:yaml.org,2002:pairs":Co,"tag:yaml.org,2002:set":Go,"tag:yaml.org,2002:timestamp":Zo}})),os,ss,cs=F((()=>{L(),Ba(),Ga(),qa(),as(),os=(e,t)=>e.key<t.key?-1:+(e.key>t.key),ss=class e{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:r,schema:i,sortMapEntries:a,toStringDefaults:o}){this.compat=Array.isArray(e)?ts(e,`compat`):e?ts(null,e):null,this.name=typeof i==`string`&&i||`core`,this.knownTags=r?is:{},this.tags=ts(t,this.name,n),this.toStringOptions=o??null,Object.defineProperty(this,Gr,{value:za}),Object.defineProperty(this,qr,{value:Ka}),Object.defineProperty(this,Jr,{value:Wa}),this.sortMapEntries=typeof a==`function`?a:a===!0?os:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}}}));function ls(e,t){let n=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let t=e.directives.toString(e);t?(n.push(t),r=!0):e.directives.docStart&&(r=!0)}r&&n.push(`---`);let i=la(e,t),{commentString:a}=i.options;if(e.commentBefore){n.length!==1&&n.unshift(``);let t=a(e.commentBefore);n.unshift(Hi(t,``))}let o=!1,s=null;if(e.contents){if(Hr(e.contents)){if(e.contents.spaceBefore&&r&&n.push(``),e.contents.commentBefore){let t=a(e.contents.commentBefore);n.push(Hi(t,``))}i.forceBlockIndent=!!e.comment,s=e.contents.comment}let t=s?void 0:()=>o=!0,c=fa(e.contents,i,()=>s=null,t);s&&(c+=Wi(c,``,a(s))),(c[0]===`|`||c[0]===`>`)&&n[n.length-1]===`---`?n[n.length-1]=`--- ${c}`:n.push(c)}else n.push(fa(e.contents,i));if(e.directives?.docEnd){if(e.comment){let t=a(e.comment);t.includes(`
88
- `)?(n.push(`...`),n.push(Hi(t,``))):n.push(`... ${t}`)}else n.push(`...`)}else{let t=e.comment;t&&o&&(t=t.replace(/^\n+/,``)),t&&((!o||s)&&n[n.length-1]!==``&&n.push(``),n.push(Hi(a(t),``)))}return n.join(`
84
+ `+Vi(l(e),c),s&&s()):d&&o&&o(),p}function Ma({items:e},t,{flowChars:n,itemIndent:r}){let{indent:i,indentStep:a,flowCollectionPadding:o,options:{commentString:s}}=t;r+=a;let c=Object.assign({},t,{indent:r,inFlow:!0,type:null}),l=!1,u=0,d=[];for(let n=0;n<e.length;++n){let i=e[n],a=null;if(Vr(i))i.spaceBefore&&d.push(``),Na(t,d,i.commentBefore,!1),i.comment&&(a=i.comment);else if(Qr(i)){let e=Vr(i.key)?i.key:null;e&&(e.spaceBefore&&d.push(``),Na(t,d,e.commentBefore,!1),e.comment&&(l=!0));let n=Vr(i.value)?i.value:null;n?(n.comment&&(a=n.comment),n.commentBefore&&(l=!0)):i.value==null&&e?.comment&&(a=e.comment)}a&&(l=!0);let o=da(i,c,()=>a=null);l||=d.length>u||o.includes(`
85
+ `),n<e.length-1?o+=`,`:t.options.trailingComma&&(t.options.lineWidth>0&&(l||=d.reduce((e,t)=>e+t.length+2,2)+(o.length+2)>t.options.lineWidth),l&&(o+=`,`)),a&&(o+=Ui(o,r,s(a))),d.push(o),u=d.length}let{start:f,end:p}=n;if(d.length===0)return f+p;if(!l){let e=d.reduce((e,t)=>e+t.length+2,2);l=t.options.lineWidth>0&&e>t.options.lineWidth}if(l){let e=f;for(let t of d)e+=t?`\n${a}${i}${t}`:`
86
+ `;return`${e}\n${i}${p}`}return`${f}${o}${d.join(` `)}${o}${p}`}function Na({indent:e,options:{commentString:t}},n,r,i){if(r&&i&&(r=r.replace(/^\n+/,``)),r){let i=Vi(t(r),e);n.push(i.trimStart())}}var Pa=I((()=>{R(),fa(),Wi()}));function Fa(e,t){let n=$r(t)?t.value:t;for(let r of e)if(Qr(r)&&(r.key===t||r.key===n||$r(r.key)&&r.key.value===n))return r}var Ia,La=I((()=>{Pa(),Ea(),Bi(),R(),ka(),Mi(),Ia=class extends zi{static get tagName(){return`tag:yaml.org,2002:map`}constructor(e){super(Wr,e),this.items=[]}static from(e,t,n){let{keepUndefined:r,replacer:i}=n,a=new this(e),o=(e,o)=>{if(typeof i==`function`)o=i.call(t,e,o);else if(Array.isArray(i)&&!i.includes(e))return;(o!==void 0||r)&&a.items.push(Da(e,o,n))};if(t instanceof Map)for(let[e,n]of t)o(e,n);else if(t&&typeof t==`object`)for(let e of Object.keys(t))o(e,t[e]);return typeof e.sortMapEntries==`function`&&a.items.sort(e.sortMapEntries),a}add(e,t){let n;n=Qr(e)?e:!e||typeof e!=`object`||!(`key`in e)?new Oa(e,e?.value):new Oa(e.key,e.value);let r=Fa(this.items,n.key),i=this.schema?.sortMapEntries;if(r){if(!t)throw Error(`Key ${n.key} already set`);$r(r.value)&&ji(n.value)?r.value.value=n.value:r.value=n.value}else if(i){let e=this.items.findIndex(e=>i(n,e)<0);e===-1?this.items.push(n):this.items.splice(e,0,n)}else this.items.push(n)}delete(e){let t=Fa(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let n=Fa(this.items,e)?.value;return(!t&&$r(n)?n.value:n)??void 0}has(e){return!!Fa(this.items,e)}set(e,t){this.add(new Oa(e,t),!0)}toJSON(e,t,n){let r=n?new n:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(r);for(let e of this.items)wa(t,r,e);return r}toString(e,t,n){if(!e)return JSON.stringify(this);for(let e of this.items)if(!Qr(e))throw Error(`Map items must all be pairs; found ${JSON.stringify(e)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),Aa(this,e,{blockItemPrefix:``,flowChars:{start:`{`,end:`}`},itemIndent:e.indent||``,onChompKeep:n,onComment:t})}}})),Ra,za=I((()=>{R(),La(),Ra={collection:`map`,default:!0,nodeClass:Ia,tag:`tag:yaml.org,2002:map`,resolve(e,t){return Zr(e)||t(`Expected a mapping for this tag`),e},createNode:(e,t,n)=>Ia.from(e,t,n)}}));function Ba(e){let t=$r(e)?e.value:e;return t&&typeof t==`string`&&(t=Number(t)),typeof t==`number`&&Number.isInteger(t)&&t>=0?t:null}var Va,Ha=I((()=>{Ii(),Pa(),Bi(),R(),Mi(),Ti(),Va=class extends zi{static get tagName(){return`tag:yaml.org,2002:seq`}constructor(e){super(qr,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=Ba(e);return typeof t==`number`&&this.items.splice(t,1).length>0}get(e,t){let n=Ba(e);if(typeof n!=`number`)return;let r=this.items[n];return!t&&$r(r)?r.value:r}has(e){let t=Ba(e);return typeof t==`number`&&t<this.items.length}set(e,t){let n=Ba(e);if(typeof n!=`number`)throw Error(`Expected a valid index, not ${e}.`);let r=this.items[n];$r(r)&&ji(t)?r.value=t:this.items[n]=t}toJSON(e,t){let n=[];t?.onCreate&&t.onCreate(n);let r=0;for(let e of this.items)n.push(wi(e,String(r++),t));return n}toString(e,t,n){return e?Aa(this,e,{blockItemPrefix:`- `,flowChars:{start:`[`,end:`]`},itemIndent:(e.indent||``)+` `,onChompKeep:n,onComment:t}):JSON.stringify(this)}static from(e,t,n){let{replacer:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t)){let e=0;for(let a of t){if(typeof r==`function`){let n=t instanceof Set?a:String(e++);a=r.call(t,n,a)}i.items.push(Pi(a,void 0,n))}}return i}}})),Ua,Wa=I((()=>{R(),Ha(),Ua={collection:`seq`,default:!0,nodeClass:Va,tag:`tag:yaml.org,2002:seq`,resolve(e,t){return ei(e)||t(`Expected a sequence for this tag`),e},createNode:(e,t,n)=>Va.from(e,t,n)}})),Ga,Ka=I((()=>{sa(),Ga={identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify(e,t,n,r){return t=Object.assign({actualString:!0},t),ra(e,t,n,r)}}})),qa,Ja=I((()=>{Mi(),qa={identify:e=>e==null,createNode:()=>new z(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new z(null),stringify:({source:e},t)=>typeof e==`string`&&qa.test.test(e)?e:t.options.nullStr}})),Ya,Xa=I((()=>{Mi(),Ya={identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new z(e[0]===`t`||e[0]===`T`),stringify({source:e,value:t},n){return e&&Ya.test.test(e)&&t===(e[0]===`t`||e[0]===`T`)?e:t?n.options.trueStr:n.options.falseStr}}}));function Za({format:e,minFractionDigits:t,tag:n,value:r}){if(typeof r==`bigint`)return String(r);let i=typeof r==`number`?r:Number(r);if(!isFinite(i))return isNaN(i)?`.nan`:i<0?`-.inf`:`.inf`;let a=Object.is(r,-0)?`-0`:JSON.stringify(r);if(!e&&t&&(!n||n===`tag:yaml.org,2002:float`)&&/^-?\d/.test(a)&&!a.includes(`e`)){let e=a.indexOf(`.`);e<0&&(e=a.length,a+=`.`);let n=t-(a.length-e-1);for(;n-->0;)a+=`0`}return a}var Qa=I((()=>{})),$a,eo,to,no=I((()=>{Mi(),Qa(),$a={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()===`nan`?NaN:e[0]===`-`?-1/0:1/0,stringify:Za},eo={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():Za(e)}},to={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let t=new z(parseFloat(e)),n=e.indexOf(`.`);return n!==-1&&e[e.length-1]===`0`&&(t.minFractionDigits=e.length-n-1),t},stringify:Za}}));function ro(e,t,n){let{value:r}=e;return io(r)&&r>=0?n+r.toString(t):Za(e)}var io,ao,oo,so,co,lo=I((()=>{Qa(),io=e=>typeof e==`bigint`||Number.isInteger(e),ao=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n),oo={identify:e=>io(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^0o[0-7]+$/,resolve:(e,t,n)=>ao(e,2,8,n),stringify:e=>ro(e,8,`0o`)},so={identify:io,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>ao(e,0,10,n),stringify:Za},co={identify:e=>io(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>ao(e,2,16,n),stringify:e=>ro(e,16,`0x`)}})),uo,fo=I((()=>{za(),Ja(),Wa(),Ka(),Xa(),no(),lo(),uo=[Ra,Ua,Ga,qa,Ya,oo,so,co,$a,eo,to]}));function po(e){return typeof e==`bigint`||Number.isInteger(e)}var mo,ho,go,_o=I((()=>{Mi(),za(),Wa(),mo=({value:e})=>JSON.stringify(e),ho=[{identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify:mo},{identify:e=>e==null,createNode:()=>new z(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^null$/,resolve:()=>null,stringify:mo},{identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^true$|^false$/,resolve:e=>e===`true`,stringify:mo},{identify:po,default:!0,tag:`tag:yaml.org,2002:int`,test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(e,t,{intAsBigInt:n})=>n?BigInt(e):parseInt(e,10),stringify:({value:e})=>po(e)?e.toString():JSON.stringify(e)},{identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:e=>parseFloat(e),stringify:mo}],go=[Ra,Ua].concat(ho,{default:!0,tag:``,test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}})})),vo,yo=I((()=>{Mi(),sa(),vo={identify:e=>e instanceof Uint8Array,default:!1,tag:`tag:yaml.org,2002:binary`,resolve(e,t){if(typeof atob==`function`){let t=atob(e.replace(/[\n\r]/g,``)),n=new Uint8Array(t.length);for(let e=0;e<t.length;++e)n[e]=t.charCodeAt(e);return n}return t(`This environment does not support reading binary tags; either Buffer or atob is required`),e},stringify({comment:e,type:t,value:n},r,i,a){if(!n)return``;let o=n,s;if(typeof btoa==`function`){let e=``;for(let t=0;t<o.length;++t)e+=String.fromCharCode(o[t]);s=btoa(e)}else throw Error(`This environment does not support writing binary tags; either Buffer or btoa is required`);if(t??=z.BLOCK_LITERAL,t!==z.QUOTE_DOUBLE){let e=Math.max(r.options.lineWidth-r.indent.length,r.options.minContentWidth),n=Math.ceil(s.length/e),i=Array(n);for(let t=0,r=0;t<n;++t,r+=e)i[t]=s.substr(r,e);s=i.join(t===z.BLOCK_LITERAL?`
87
+ `:` `)}return ra({comment:e,type:t,value:s},r,i,a)}}}));function bo(e,t){if(ei(e))for(let n=0;n<e.items.length;++n){let r=e.items[n];if(!Qr(r)){if(Zr(r)){r.items.length>1&&t(`Each pair must have its own sequence indicator`);let e=r.items[0]||new Oa(new z(null));if(r.commentBefore&&(e.key.commentBefore=e.key.commentBefore?`${r.commentBefore}\n${e.key.commentBefore}`:r.commentBefore),r.comment){let t=e.value??e.key;t.comment=t.comment?`${r.comment}\n${t.comment}`:r.comment}r=e}e.items[n]=Qr(r)?r:new Oa(r)}}else t(`Expected a sequence for this tag`);return e}function xo(e,t,n){let{replacer:r}=n,i=new Va(e);i.tag=`tag:yaml.org,2002:pairs`;let a=0;if(t&&Symbol.iterator in Object(t))for(let e of t){typeof r==`function`&&(e=r.call(t,String(a++),e));let o,s;if(Array.isArray(e)){if(e.length===2)o=e[0],s=e[1];else throw TypeError(`Expected [key, value] tuple: ${e}`)}else if(e&&e instanceof Object){let t=Object.keys(e);if(t.length===1)o=t[0],s=e[o];else throw TypeError(`Expected tuple with one key, not ${t.length} keys`)}else o=e;i.items.push(Da(o,s,n))}return i}var So,Co=I((()=>{R(),ka(),Mi(),Ha(),So={collection:`seq`,default:!1,tag:`tag:yaml.org,2002:pairs`,resolve:bo,createNode:xo}})),wo,To,Eo=I((()=>{R(),Ti(),La(),Ha(),Co(),wo=class e extends Va{constructor(){super(),this.add=Ia.prototype.add.bind(this),this.delete=Ia.prototype.delete.bind(this),this.get=Ia.prototype.get.bind(this),this.has=Ia.prototype.has.bind(this),this.set=Ia.prototype.set.bind(this),this.tag=e.tag}toJSON(e,t){if(!t)return super.toJSON(e);let n=new Map;t?.onCreate&&t.onCreate(n);for(let e of this.items){let r,i;if(Qr(e)?(r=wi(e.key,``,t),i=wi(e.value,r,t)):r=wi(e,``,t),n.has(r))throw Error(`Ordered maps must not include duplicate keys`);n.set(r,i)}return n}static from(e,t,n){let r=xo(e,t,n),i=new this;return i.items=r.items,i}},wo.tag=`tag:yaml.org,2002:omap`,To={collection:`seq`,identify:e=>e instanceof Map,nodeClass:wo,default:!1,tag:`tag:yaml.org,2002:omap`,resolve(e,t){let n=bo(e,t),r=[];for(let{key:e}of n.items)$r(e)&&(r.includes(e.value)?t(`Ordered maps must not include duplicate keys: ${e.value}`):r.push(e.value));return Object.assign(new wo,n)},createNode:(e,t,n)=>wo.from(e,t,n)}}));function Do({value:e,source:t},n){return t&&(e?Oo:ko).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}var Oo,ko,Ao=I((()=>{Mi(),Oo={identify:e=>e===!0,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new z(!0),stringify:Do},ko={identify:e=>e===!1,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new z(!1),stringify:Do}})),jo,Mo,No,Po=I((()=>{Mi(),Qa(),jo={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:e=>e.slice(-3).toLowerCase()===`nan`?NaN:e[0]===`-`?-1/0:1/0,stringify:Za},Mo={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`EXP`,test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:e=>parseFloat(e.replace(/_/g,``)),stringify(e){let t=Number(e.value);return isFinite(t)?t.toExponential():Za(e)}},No={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let t=new z(parseFloat(e.replace(/_/g,``))),n=e.indexOf(`.`);if(n!==-1){let r=e.substring(n+1).replace(/_/g,``);r[r.length-1]===`0`&&(t.minFractionDigits=r.length)}return t},stringify:Za}}));function Fo(e,t,n,{intAsBigInt:r}){let i=e[0];if((i===`-`||i===`+`)&&(t+=1),e=e.substring(t).replace(/_/g,``),r){switch(n){case 2:e=`0b${e}`;break;case 8:e=`0o${e}`;break;case 16:e=`0x${e}`}let t=BigInt(e);return i===`-`?BigInt(-1)*t:t}let a=parseInt(e,n);return i===`-`?-1*a:a}function Io(e,t,n){let{value:r}=e;if(Lo(r)){let e=r.toString(t);return r<0?`-`+n+e.substr(1):n+e}return Za(e)}var Lo,Ro,zo,Bo,Vo,Ho=I((()=>{Qa(),Lo=e=>typeof e==`bigint`||Number.isInteger(e),Ro={identify:Lo,default:!0,tag:`tag:yaml.org,2002:int`,format:`BIN`,test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>Fo(e,2,2,n),stringify:e=>Io(e,2,`0b`)},zo={identify:Lo,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>Fo(e,1,8,n),stringify:e=>Io(e,8,`0`)},Bo={identify:Lo,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>Fo(e,0,10,n),stringify:Za},Vo={identify:Lo,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>Fo(e,2,16,n),stringify:e=>Io(e,16,`0x`)}})),Uo,Wo,Go=I((()=>{R(),ka(),La(),Uo=class e extends Ia{constructor(t){super(t),this.tag=e.tag}add(e){let t;t=Qr(e)?e:e&&typeof e==`object`&&`key`in e&&`value`in e&&e.value===null?new Oa(e.key,null):new Oa(e,null),Fa(this.items,t.key)||this.items.push(t)}get(e,t){let n=Fa(this.items,e);return!t&&Qr(n)?$r(n.key)?n.key.value:n.key:n}set(e,t){if(typeof t!=`boolean`)throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let n=Fa(this.items,e);n&&!t?this.items.splice(this.items.indexOf(n),1):!n&&t&&this.items.push(new Oa(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,n){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,n);throw Error(`Set items must all have null values`)}static from(e,t,n){let{replacer:r}=n,i=new this(e);if(t&&Symbol.iterator in Object(t))for(let e of t)typeof r==`function`&&(e=r.call(t,e,e)),i.items.push(Da(e,null,n));return i}},Uo.tag=`tag:yaml.org,2002:set`,Wo={collection:`map`,identify:e=>e instanceof Set,nodeClass:Uo,default:!1,tag:`tag:yaml.org,2002:set`,createNode:(e,t,n)=>Uo.from(e,t,n),resolve(e,t){if(Zr(e)){if(e.hasAllNullValues(!0))return Object.assign(new Uo,e);t(`Set items must all have null values`)}else t(`Expected a mapping for this tag`);return e}}}));function Ko(e,t){let n=e[0],r=n===`-`||n===`+`?e.substring(1):e,i=e=>t?BigInt(e):Number(e),a=r.replace(/_/g,``).split(`:`).reduce((e,t)=>e*i(60)+i(t),i(0));return n===`-`?i(-1)*a:a}function qo(e){let{value:t}=e,n=e=>e;if(typeof t==`bigint`)n=e=>BigInt(e);else if(isNaN(t)||!isFinite(t))return Za(e);let r=``;t<0&&(r=`-`,t*=n(-1));let i=n(60),a=[t%i];return t<60?a.unshift(0):(t=(t-a[0])/i,a.unshift(t%i),t>=60&&(t=(t-a[0])/i,a.unshift(t))),r+a.map(e=>String(e).padStart(2,`0`)).join(`:`).replace(/000000\d*$/,``)}var Jo,Yo,Xo,Zo=I((()=>{Qa(),Jo={identify:e=>typeof e==`bigint`||Number.isInteger(e),default:!0,tag:`tag:yaml.org,2002:int`,format:`TIME`,test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(e,t,{intAsBigInt:n})=>Ko(e,n),stringify:qo},Yo={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,format:`TIME`,test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:e=>Ko(e,!1),stringify:qo},Xo={identify:e=>e instanceof Date,default:!0,tag:`tag:yaml.org,2002:timestamp`,test:RegExp(`^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$`),resolve(e){let t=e.match(Xo.test);if(!t)throw Error(`!!timestamp expects a date, starting with yyyy-mm-dd`);let[,n,r,i,a,o,s]=t.map(Number),c=t[7]?Number((t[7]+`00`).substr(1,3)):0,l=Date.UTC(n,r-1,i,a||0,o||0,s||0,c),u=t[8];if(u&&u!==`Z`){let e=Ko(u,!1);Math.abs(e)<30&&(e*=60),l-=6e4*e}return new Date(l)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,``)??``}})),Qo,$o=I((()=>{za(),Ja(),Wa(),Ka(),yo(),Ao(),Po(),Ho(),Ca(),Eo(),Co(),Go(),Zo(),Qo=[Ra,Ua,Ga,qa,Oo,ko,Ro,zo,Bo,Vo,jo,Mo,No,vo,xa,To,So,Wo,Jo,Yo,Xo]}));function es(e,t,n){let r=ts.get(t);if(r&&!e)return n&&!r.includes(xa)?r.concat(xa):r.slice();let i=r;if(!i){if(Array.isArray(e))i=[];else{let e=Array.from(ts.keys()).filter(e=>e!==`yaml11`).map(e=>JSON.stringify(e)).join(`, `);throw Error(`Unknown schema "${t}"; use one of ${e} or define customTags array`)}}if(Array.isArray(e))for(let t of e)i=i.concat(t);else typeof e==`function`&&(i=e(i.slice()));return n&&(i=i.concat(xa)),i.reduce((e,t)=>{let n=typeof t==`string`?ns[t]:t;if(!n){let e=JSON.stringify(t),n=Object.keys(ns).map(e=>JSON.stringify(e)).join(`, `);throw Error(`Unknown custom tag ${e}; use one of ${n}`)}return e.includes(n)||e.push(n),e},[])}var ts,ns,rs,is=I((()=>{za(),Ja(),Wa(),Ka(),Xa(),no(),lo(),fo(),_o(),yo(),Ca(),Eo(),Co(),$o(),Go(),Zo(),ts=new Map([[`core`,uo],[`failsafe`,[Ra,Ua,Ga]],[`json`,go],[`yaml11`,Qo],[`yaml-1.1`,Qo]]),ns={binary:vo,bool:Ya,float:to,floatExp:eo,floatNaN:$a,floatTime:Yo,int:so,intHex:co,intOct:oo,intTime:Jo,map:Ra,merge:xa,null:qa,omap:To,pairs:So,seq:Ua,set:Wo,timestamp:Xo},rs={"tag:yaml.org,2002:binary":vo,"tag:yaml.org,2002:merge":xa,"tag:yaml.org,2002:omap":To,"tag:yaml.org,2002:pairs":So,"tag:yaml.org,2002:set":Wo,"tag:yaml.org,2002:timestamp":Xo}})),as,os,ss=I((()=>{R(),za(),Wa(),Ka(),is(),as=(e,t)=>e.key<t.key?-1:+(e.key>t.key),os=class e{constructor({compat:e,customTags:t,merge:n,resolveKnownTags:r,schema:i,sortMapEntries:a,toStringDefaults:o}){this.compat=Array.isArray(e)?es(e,`compat`):e?es(null,e):null,this.name=typeof i==`string`&&i||`core`,this.knownTags=r?rs:{},this.tags=es(t,this.name,n),this.toStringOptions=o??null,Object.defineProperty(this,Wr,{value:Ra}),Object.defineProperty(this,Kr,{value:Ga}),Object.defineProperty(this,qr,{value:Ua}),this.sortMapEntries=typeof a==`function`?a:a===!0?as:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}}}));function cs(e,t){let n=[],r=t.directives===!0;if(t.directives!==!1&&e.directives){let t=e.directives.toString(e);t?(n.push(t),r=!0):e.directives.docStart&&(r=!0)}r&&n.push(`---`);let i=ca(e,t),{commentString:a}=i.options;if(e.commentBefore){n.length!==1&&n.unshift(``);let t=a(e.commentBefore);n.unshift(Vi(t,``))}let o=!1,s=null;if(e.contents){if(Vr(e.contents)){if(e.contents.spaceBefore&&r&&n.push(``),e.contents.commentBefore){let t=a(e.contents.commentBefore);n.push(Vi(t,``))}i.forceBlockIndent=!!e.comment,s=e.contents.comment}let t=s?void 0:()=>o=!0,c=da(e.contents,i,()=>s=null,t);s&&(c+=Ui(c,``,a(s))),(c[0]===`|`||c[0]===`>`)&&n[n.length-1]===`---`?n[n.length-1]=`--- ${c}`:n.push(c)}else n.push(da(e.contents,i));if(e.directives?.docEnd){if(e.comment){let t=a(e.comment);t.includes(`
88
+ `)?(n.push(`...`),n.push(Vi(t,``))):n.push(`... ${t}`)}else n.push(`...`)}else{let t=e.comment;t&&o&&(t=t.replace(/^\n+/,``)),t&&((!o||s)&&n[n.length-1]!==``&&n.push(``),n.push(Vi(a(t),``)))}return n.join(`
89
89
  `)+`
90
- `}var us=F((()=>{L(),pa(),Gi()}));function ds(e){if(Vr(e))return!0;throw Error(`Expected a YAML collection as document contents`)}var fs,ps=F((()=>{ji(),Vi(),L(),Aa(),Ei(),cs(),us(),Si(),wi(),Li(),_i(),fs=class e{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Yr,{value:Wr});let r=null;typeof t==`function`||Array.isArray(t)?r=t:n===void 0&&t&&(n=t,t=void 0);let i=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:`warn`,prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:`1.2`},n);this.options=i;let{version:a}=i;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(a=this.directives.yaml.version)):this.directives=new gi({version:a}),this.setSchema(a,n),this.contents=e===void 0?null:this.createNode(e,r,n)}clone(){let t=Object.create(e.prototype,{[Yr]:{value:Wr}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=Hr(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(e){ds(this.contents)&&this.contents.add(e)}addIn(e,t){ds(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=yi(this);e.anchor=!t||n.has(t)?bi(t||`a`,n):t}return new Ai(e.anchor)}createNode(e,t,n){let r;if(typeof t==`function`)e=t.call({"":e},``,e),r=t;else if(Array.isArray(t)){let e=t.filter(e=>typeof e==`number`||e instanceof String||e instanceof Number).map(String);e.length>0&&(t=t.concat(e)),r=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:i,anchorPrefix:a,flow:o,keepUndefined:s,onTagObj:c,tag:l}=n??{},{onAnchor:u,setAnchors:d,sourceObjects:f}=xi(this,a||`a`),p={aliasDuplicateObjects:i??!0,keepUndefined:s??!1,onAnchor:u,onTagObj:c,replacer:r,schema:this.schema,sourceObjects:f},m=Fi(e,l,p);return o&&Vr(m)&&(m.flow=!0),d(),m}createPair(e,t,n={}){let r=this.createNode(e,null,n),i=this.createNode(t,null,n);return new ka(r,i)}delete(e){return ds(this.contents)?this.contents.delete(e):!1}deleteIn(e){return zi(e)?this.contents!=null&&(this.contents=null,!0):ds(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return Vr(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return zi(e)?!t&&ei(this.contents)?this.contents.value:this.contents:Vr(this.contents)?this.contents.getIn(e,t):void 0}has(e){return Vr(this.contents)?this.contents.has(e):!1}hasIn(e){return zi(e)?this.contents!==void 0:Vr(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Ri(this.schema,[e],t):ds(this.contents)&&this.contents.set(e,t)}setIn(e,t){zi(e)?this.contents=t:this.contents==null?this.contents=Ri(this.schema,Array.from(e),t):ds(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e==`number`&&(e=String(e));let n;switch(e){case`1.1`:this.directives?this.directives.yaml.version=`1.1`:this.directives=new gi({version:`1.1`}),n={resolveKnownTags:!1,schema:`yaml-1.1`};break;case`1.2`:case`next`:this.directives?this.directives.yaml.version=e:this.directives=new gi({version:e}),n={resolveKnownTags:!0,schema:`core`};break;case null:this.directives&&delete this.directives,n=null;break;default:{let t=JSON.stringify(e);throw Error(`Expected '1.1', '1.2' or null as first argument, but found: ${t}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new ss(Object.assign(n,t));else throw Error(`With a null YAML version, the { schema: Schema } option is required`)}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:r,onAnchor:i,reviver:a}={}){let o={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r==`number`?r:100},s=Ti(this.contents,t??``,o);if(typeof i==`function`)for(let{count:e,res:t}of o.anchors.values())i(t,e);return typeof a==`function`?Ci(a,{"":s},``,s):s}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw Error(`Document with errors cannot be stringified`);if(`indent`in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw Error(`"indent" option must be a positive integer, not ${t}`)}return ls(this,e)}}})),ms,hs,gs,_s,vs=F((()=>{ms=class extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}},hs=class extends ms{constructor(e,t,n){super(`YAMLParseError`,e,t,n)}},gs=class extends ms{constructor(e,t,n){super(`YAMLWarning`,e,t,n)}},_s=(e,t)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(e=>t.linePos(e));let{line:r,col:i}=n.linePos[0];n.message+=` at line ${r}, column ${i}`;let a=i-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,``);if(a>=60&&o.length>80){let e=Math.min(a-39,o.length-79);o=`…`+o.substring(e),a-=e-1}if(o.length>80&&(o=o.substring(0,79)+`…`),r>1&&/^ *$/.test(o.substring(0,a))){let n=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);n.length>80&&(n=n.substring(0,79)+`…
91
- `),o=n+o}if(/[^ ]/.test(o)){let e=1,t=n.linePos[1];t?.line===r&&t.col>i&&(e=Math.max(1,Math.min(t.col-i,80-a)));let s=` `.repeat(a)+`^`.repeat(e);n.message+=`:\n\n${o}\n${s}\n`}}}));function ys(e,{flow:t,indicator:n,next:r,offset:i,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d=``,f=``,p=!1,m=!1,h=null,g=null,_=null,v=null,y=null,b=null,x=null;for(let i of e)switch(m&&=(i.type!==`space`&&i.type!==`newline`&&i.type!==`comma`&&a(i.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),!1),h&&=(l&&i.type!==`comment`&&i.type!==`newline`&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),null),i.type){case`space`:!t&&(n!==`doc-start`||r?.type!==`flow-collection`)&&i.source.includes(` `)&&(h=i),u=!0;break;case`comment`:{u||a(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let e=i.source.substring(1)||` `;d?d+=f+e:d=e,f=``,l=!1;break}case`newline`:l?d?d+=i.source:(!b||n!==`seq-item-ind`)&&(c=!0):f+=i.source,l=!0,p=!0,(g||_)&&(v=i),u=!0;break;case`anchor`:g&&a(i,`MULTIPLE_ANCHORS`,`A node can have at most one anchor`),i.source.endsWith(`:`)&&a(i.offset+i.source.length-1,`BAD_ALIAS`,`Anchor ending in : is ambiguous`,!0),g=i,x??=i.offset,l=!1,u=!1,m=!0;break;case`tag`:_&&a(i,`MULTIPLE_TAGS`,`A node can have at most one tag`),_=i,x??=i.offset,l=!1,u=!1,m=!0;break;case n:(g||_)&&a(i,`BAD_PROP_ORDER`,`Anchors and tags must be after the ${i.source} indicator`),b&&a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.source} in ${t??`collection`}`),b=i,l=n===`seq-item-ind`||n===`explicit-key-ind`,u=!1;break;case`comma`:if(t){y&&a(i,`UNEXPECTED_TOKEN`,`Unexpected , in ${t}`),y=i,l=!1,u=!1;break}default:a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.type} token`),l=!1,u=!1}let S=e[e.length-1],C=S?S.offset+S.source.length:i;return m&&r&&r.type!==`space`&&r.type!==`newline`&&r.type!==`comma`&&(r.type!==`scalar`||r.source!==``)&&a(r.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),h&&(l&&h.indent<=o||r?.type===`block-map`||r?.type===`block-seq`)&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),{comma:y,found:b,spaceBefore:c,comment:d,hasNewline:p,anchor:g,tag:_,newlineAfterProp:v,end:C,start:x??C}}var bs=F((()=>{}));function xs(e){if(!e)return null;switch(e.type){case`alias`:case`scalar`:case`double-quoted-scalar`:case`single-quoted-scalar`:if(e.source.includes(`
92
- `))return!0;if(e.end){for(let t of e.end)if(t.type===`newline`)return!0}return!1;case`flow-collection`:for(let t of e.items){for(let e of t.start)if(e.type===`newline`)return!0;if(t.sep){for(let e of t.sep)if(e.type===`newline`)return!0}if(xs(t.key)||xs(t.value))return!0}return!1;default:return!0}}var Ss=F((()=>{}));function Cs(e,t,n){if(t?.type===`flow-collection`){let r=t.end[0];r.indent===e&&(r.source===`]`||r.source===`}`)&&xs(t)&&n(r,`BAD_INDENT`,`Flow end indicator should be more indented than parent`,!0)}}var ws=F((()=>{Ss()}));function Ts(e,t,n){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let i=typeof r==`function`?r:(e,t)=>e===t||ei(e)&&ei(t)&&e.value===t.value;return t.some(e=>i(e.key,n))}var Es=F((()=>{L()}));function Ds({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??La)(n.schema);n.atRoot&&=!1;let s=r.offset,c=null;for(let a of r.items){let{start:l,key:u,sep:d,value:f}=a,p=ys(l,{indicator:`explicit-key-ind`,next:u??d?.[0],offset:s,onError:i,parentIndent:r.indent,startOnNewline:!0}),m=!p.found;if(m){if(u&&(u.type===`block-seq`?i(s,`BLOCK_AS_IMPLICIT_KEY`,`A block sequence may not be used as an implicit map key`):`indent`in u&&u.indent!==r.indent&&i(s,`BAD_INDENT`,Os)),!p.anchor&&!p.tag&&!d){c=p.end,p.comment&&(o.comment?o.comment+=`
93
- `+p.comment:o.comment=p.comment);continue}(p.newlineAfterProp||xs(u))&&i(u??l[l.length-1],`MULTILINE_IMPLICIT_KEY`,`Implicit keys need to be on a single line`)}else p.found?.indent!==r.indent&&i(s,`BAD_INDENT`,Os);n.atKey=!0;let h=p.end,g=u?e(n,u,p,i):t(n,h,l,null,p,i);n.schema.compat&&Cs(r.indent,u,i),n.atKey=!1,Ts(n,o.items,g)&&i(h,`DUPLICATE_KEY`,`Map keys must be unique`);let _=ys(d??[],{indicator:`map-value-ind`,next:f,offset:g.range[2],onError:i,parentIndent:r.indent,startOnNewline:!u||u.type===`block-scalar`});if(s=_.end,_.found){m&&(f?.type===`block-map`&&!_.hasNewline&&i(s,`BLOCK_AS_IMPLICIT_KEY`,`Nested mappings are not allowed in compact mappings`),n.options.strict&&p.start<_.found.offset-1024&&i(g.range,`KEY_OVER_1024_CHARS`,`The : indicator must be at most 1024 chars after the start of an implicit block mapping key`));let c=f?e(n,f,_,i):t(n,s,d,null,_,i);n.schema.compat&&Cs(r.indent,f,i),s=c.range[2];let l=new ka(g,c);n.options.keepSourceTokens&&(l.srcToken=a),o.items.push(l)}else{m&&i(g.range,`MISSING_CHAR`,`Implicit map keys need to be followed by map values`),_.comment&&(g.comment?g.comment+=`
94
- `+_.comment:g.comment=_.comment);let e=new ka(g);n.options.keepSourceTokens&&(e.srcToken=a),o.items.push(e)}}return c&&c<s&&i(c,`IMPOSSIBLE`,`Map comment with trailing content`),o.range=[r.offset,s,c??s],o}var Os,ks=F((()=>{Aa(),Ra(),bs(),Ss(),ws(),Es(),Os=`All mapping items must start at the same column`}));function As({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??Ha)(n.schema);n.atRoot&&=!1,n.atKey&&=!1;let s=r.offset,c=null;for(let{start:a,value:l}of r.items){let u=ys(a,{indicator:`seq-item-ind`,next:l,offset:s,onError:i,parentIndent:r.indent,startOnNewline:!0});if(!u.found){if(u.anchor||u.tag||l)l?.type===`block-seq`?i(u.end,`BAD_INDENT`,`All sequence items must start at the same column`):i(s,`MISSING_CHAR`,`Sequence item without - indicator`);else{c=u.end,u.comment&&(o.comment=u.comment);continue}}let d=l?e(n,l,u,i):t(n,u.end,a,null,u,i);n.schema.compat&&Cs(r.indent,l,i),s=d.range[2],o.items.push(d)}return o.range=[r.offset,s,c??s],o}var js=F((()=>{Ua(),bs(),ws()}));function Ms(e,t,n,r){let i=``;if(e){let a=!1,o=``;for(let s of e){let{source:e,type:c}=s;switch(c){case`space`:a=!0;break;case`comment`:{n&&!a&&r(s,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let t=e.substring(1)||` `;i?i+=o+t:i=t,o=``;break}case`newline`:i&&(o+=e),a=!0;break;default:r(s,`UNEXPECTED_TOKEN`,`Unexpected ${c} at node end`)}t+=e.length}}return{comment:i,offset:t}}var Ns=F((()=>{}));function Ps({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=r.start.source===`{`,s=o?`flow map`:`flow sequence`,c=new((a?.nodeClass)??(o?La:Ha))(n.schema);c.flow=!0;let l=n.atRoot;l&&(n.atRoot=!1),n.atKey&&=!1;let u=r.offset+r.start.source.length;for(let a=0;a<r.items.length;++a){let l=r.items[a],{start:d,key:f,sep:p,value:m}=l,h=ys(d,{flow:s,indicator:`explicit-key-ind`,next:f??p?.[0],offset:u,onError:i,parentIndent:r.indent,startOnNewline:!1});if(!h.found){if(!h.anchor&&!h.tag&&!p&&!m){a===0&&h.comma?i(h.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${s}`):a<r.items.length-1&&i(h.start,`UNEXPECTED_TOKEN`,`Unexpected empty item in ${s}`),h.comment&&(c.comment?c.comment+=`
95
- `+h.comment:c.comment=h.comment),u=h.end;continue}!o&&n.options.strict&&xs(f)&&i(f,`MULTILINE_IMPLICIT_KEY`,`Implicit keys of flow sequence pairs need to be on a single line`)}if(a===0)h.comma&&i(h.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${s}`);else if(h.comma||i(h.start,`MISSING_CHAR`,`Missing , between ${s} items`),h.comment){let e=``;loop:for(let t of d)switch(t.type){case`comma`:case`space`:break;case`comment`:e=t.source.substring(1);break loop;default:break loop}if(e){let t=c.items[c.items.length-1];$r(t)&&(t=t.value??t.key),t.comment?t.comment+=`
96
- `+e:t.comment=e,h.comment=h.comment.substring(e.length+1)}}if(!o&&!p&&!h.found){let r=m?e(n,m,h,i):t(n,h.end,p,null,h,i);c.items.push(r),u=r.range[2],Is(m)&&i(r.range,`BLOCK_IN_FLOW`,Fs)}else{n.atKey=!0;let a=h.end,g=f?e(n,f,h,i):t(n,a,d,null,h,i);Is(f)&&i(g.range,`BLOCK_IN_FLOW`,Fs),n.atKey=!1;let _=ys(p??[],{flow:s,indicator:`map-value-ind`,next:m,offset:g.range[2],onError:i,parentIndent:r.indent,startOnNewline:!1});if(_.found){if(!o&&!h.found&&n.options.strict){if(p)for(let e of p){if(e===_.found)break;if(e.type===`newline`){i(e,`MULTILINE_IMPLICIT_KEY`,`Implicit keys of flow sequence pairs need to be on a single line`);break}}h.start<_.found.offset-1024&&i(_.found,`KEY_OVER_1024_CHARS`,`The : indicator must be at most 1024 chars after the start of an implicit flow sequence key`)}}else m&&(`source`in m&&m.source?.[0]===`:`?i(m,`MISSING_CHAR`,`Missing space after : in ${s}`):i(_.start,`MISSING_CHAR`,`Missing , or : between ${s} items`));let v=m?e(n,m,_,i):_.found?t(n,_.end,p,null,_,i):null;v?Is(m)&&i(v.range,`BLOCK_IN_FLOW`,Fs):_.comment&&(g.comment?g.comment+=`
97
- `+_.comment:g.comment=_.comment);let y=new ka(g,v);if(n.options.keepSourceTokens&&(y.srcToken=l),o){let e=c;Ts(n,e.items,g)&&i(a,`DUPLICATE_KEY`,`Map keys must be unique`),e.items.push(y)}else{let e=new La(n.schema);e.flow=!0,e.items.push(y);let t=(v??g).range;e.range=[g.range[0],t[1],t[2]],c.items.push(e)}u=v?v.range[2]:_.end}}let d=o?`}`:`]`,[f,...p]=r.end,m=u;if(f?.source===d)m=f.offset+f.source.length;else{let e=s[0].toUpperCase()+s.substring(1),t=l?`${e} must end with a ${d}`:`${e} in block collection must be sufficiently indented and end with a ${d}`;i(u,l?`MISSING_CHAR`:`BAD_INDENT`,t),f&&f.source.length!==1&&p.unshift(f)}if(p.length>0){let e=Ms(p,m,n.options.strict,i);e.comment&&(c.comment?c.comment+=`
98
- `+e.comment:c.comment=e.comment),c.range=[r.offset,m,e.offset]}else c.range=[r.offset,m,m];return c}var Fs,Is,Ls=F((()=>{L(),Aa(),Ra(),Ua(),Ns(),bs(),Ss(),Es(),Fs=`Block collections are not allowed within flow collections`,Is=e=>e&&(e.type===`block-map`||e.type===`block-seq`)}));function Rs(e,t,n,r,i,a){let o=n.type===`block-map`?Ds(e,t,n,r,a):n.type===`block-seq`?As(e,t,n,r,a):Ps(e,t,n,r,a),s=o.constructor;return i===`!`||i===s.tagName?(o.tag=s.tagName,o):(i&&(o.tag=i),o)}function zs(e,t,n,r,i){let a=r.tag,o=a?t.directives.tagName(a.source,e=>i(a,`TAG_RESOLVE_FAILED`,e)):null;if(n.type===`block-seq`){let{anchor:e,newlineAfterProp:t}=r,n=e&&a?e.offset>a.offset?e:a:e??a;n&&(!t||t.offset<n.offset)&&i(n,`MISSING_CHAR`,`Missing newline after block sequence props`)}let s=n.type===`block-map`?`map`:n.type===`block-seq`?`seq`:n.start.source===`{`?`map`:`seq`;if(!a||!o||o===`!`||o===La.tagName&&s===`map`||o===Ha.tagName&&s===`seq`)return Rs(e,t,n,i,o);let c=t.schema.tags.find(e=>e.tag===o&&e.collection===s);if(!c){let r=t.schema.knownTags[o];if(r?.collection===s)t.schema.tags.push(Object.assign({},r,{default:!1})),c=r;else return r?i(a,`BAD_COLLECTION_TYPE`,`${r.tag} used for ${s} collection, but expects ${r.collection??`scalar`}`,!0):i(a,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${o}`,!0),Rs(e,t,n,i,o)}let l=Rs(e,t,n,i,o,c),u=c.resolve?.(l,e=>i(a,`TAG_RESOLVE_FAILED`,e),t.options)??l,d=Hr(u)?u:new R(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}var Bs=F((()=>{L(),Ni(),Ra(),Ua(),ks(),js(),Ls()}));function Vs(e,t,n){let r=t.offset,i=Hs(t,e.options.strict,n);if(!i)return{value:``,type:null,comment:``,range:[r,r,r]};let a=i.mode===`>`?R.BLOCK_FOLDED:R.BLOCK_LITERAL,o=t.source?Us(t.source):[],s=o.length;for(let e=o.length-1;e>=0;--e){let t=o[e][1];if(t===``||t===`\r`)s=e;else break}if(s===0){let e=i.chomp===`+`&&o.length>0?`
90
+ `}var ls=I((()=>{R(),fa(),Wi()}));function us(e){if(Br(e))return!0;throw Error(`Expected a YAML collection as document contents`)}var ds,fs=I((()=>{Ai(),Bi(),R(),ka(),Ti(),ss(),ls(),xi(),Ci(),Ii(),gi(),ds=class e{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Jr,{value:Ur});let r=null;typeof t==`function`||Array.isArray(t)?r=t:n===void 0&&t&&(n=t,t=void 0);let i=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:`warn`,prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:`1.2`},n);this.options=i;let{version:a}=i;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(a=this.directives.yaml.version)):this.directives=new hi({version:a}),this.setSchema(a,n),this.contents=e===void 0?null:this.createNode(e,r,n)}clone(){let t=Object.create(e.prototype,{[Jr]:{value:Ur}});return t.commentBefore=this.commentBefore,t.comment=this.comment,t.errors=this.errors.slice(),t.warnings=this.warnings.slice(),t.options=Object.assign({},this.options),this.directives&&(t.directives=this.directives.clone()),t.schema=this.schema.clone(),t.contents=Vr(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(e){us(this.contents)&&this.contents.add(e)}addIn(e,t){us(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let n=vi(this);e.anchor=!t||n.has(t)?yi(t||`a`,n):t}return new ki(e.anchor)}createNode(e,t,n){let r;if(typeof t==`function`)e=t.call({"":e},``,e),r=t;else if(Array.isArray(t)){let e=t.filter(e=>typeof e==`number`||e instanceof String||e instanceof Number).map(String);e.length>0&&(t=t.concat(e)),r=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:i,anchorPrefix:a,flow:o,keepUndefined:s,onTagObj:c,tag:l}=n??{},{onAnchor:u,setAnchors:d,sourceObjects:f}=bi(this,a||`a`),p={aliasDuplicateObjects:i??!0,keepUndefined:s??!1,onAnchor:u,onTagObj:c,replacer:r,schema:this.schema,sourceObjects:f},m=Pi(e,l,p);return o&&Br(m)&&(m.flow=!0),d(),m}createPair(e,t,n={}){let r=this.createNode(e,null,n),i=this.createNode(t,null,n);return new Oa(r,i)}delete(e){return us(this.contents)?this.contents.delete(e):!1}deleteIn(e){return Ri(e)?this.contents!=null&&(this.contents=null,!0):us(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return Br(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return Ri(e)?!t&&$r(this.contents)?this.contents.value:this.contents:Br(this.contents)?this.contents.getIn(e,t):void 0}has(e){return Br(this.contents)?this.contents.has(e):!1}hasIn(e){return Ri(e)?this.contents!==void 0:Br(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=Li(this.schema,[e],t):us(this.contents)&&this.contents.set(e,t)}setIn(e,t){Ri(e)?this.contents=t:this.contents==null?this.contents=Li(this.schema,Array.from(e),t):us(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e==`number`&&(e=String(e));let n;switch(e){case`1.1`:this.directives?this.directives.yaml.version=`1.1`:this.directives=new hi({version:`1.1`}),n={resolveKnownTags:!1,schema:`yaml-1.1`};break;case`1.2`:case`next`:this.directives?this.directives.yaml.version=e:this.directives=new hi({version:e}),n={resolveKnownTags:!0,schema:`core`};break;case null:this.directives&&delete this.directives,n=null;break;default:{let t=JSON.stringify(e);throw Error(`Expected '1.1', '1.2' or null as first argument, but found: ${t}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(n)this.schema=new os(Object.assign(n,t));else throw Error(`With a null YAML version, the { schema: Schema } option is required`)}toJS({json:e,jsonArg:t,mapAsMap:n,maxAliasCount:r,onAnchor:i,reviver:a}={}){let o={anchors:new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r==`number`?r:100},s=wi(this.contents,t??``,o);if(typeof i==`function`)for(let{count:e,res:t}of o.anchors.values())i(t,e);return typeof a==`function`?Si(a,{"":s},``,s):s}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw Error(`Document with errors cannot be stringified`);if(`indent`in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw Error(`"indent" option must be a positive integer, not ${t}`)}return cs(this,e)}}})),ps,ms,hs,gs,_s=I((()=>{ps=class extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}},ms=class extends ps{constructor(e,t,n){super(`YAMLParseError`,e,t,n)}},hs=class extends ps{constructor(e,t,n){super(`YAMLWarning`,e,t,n)}},gs=(e,t)=>n=>{if(n.pos[0]===-1)return;n.linePos=n.pos.map(e=>t.linePos(e));let{line:r,col:i}=n.linePos[0];n.message+=` at line ${r}, column ${i}`;let a=i-1,o=e.substring(t.lineStarts[r-1],t.lineStarts[r]).replace(/[\n\r]+$/,``);if(a>=60&&o.length>80){let e=Math.min(a-39,o.length-79);o=`…`+o.substring(e),a-=e-1}if(o.length>80&&(o=o.substring(0,79)+`…`),r>1&&/^ *$/.test(o.substring(0,a))){let n=e.substring(t.lineStarts[r-2],t.lineStarts[r-1]);n.length>80&&(n=n.substring(0,79)+`…
91
+ `),o=n+o}if(/[^ ]/.test(o)){let e=1,t=n.linePos[1];t?.line===r&&t.col>i&&(e=Math.max(1,Math.min(t.col-i,80-a)));let s=` `.repeat(a)+`^`.repeat(e);n.message+=`:\n\n${o}\n${s}\n`}}}));function vs(e,{flow:t,indicator:n,next:r,offset:i,onError:a,parentIndent:o,startOnNewline:s}){let c=!1,l=s,u=s,d=``,f=``,p=!1,m=!1,h=null,g=null,_=null,v=null,y=null,b=null,x=null;for(let i of e)switch(m&&=(i.type!==`space`&&i.type!==`newline`&&i.type!==`comma`&&a(i.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),!1),h&&=(l&&i.type!==`comment`&&i.type!==`newline`&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),null),i.type){case`space`:!t&&(n!==`doc-start`||r?.type!==`flow-collection`)&&i.source.includes(` `)&&(h=i),u=!0;break;case`comment`:{u||a(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let e=i.source.substring(1)||` `;d?d+=f+e:d=e,f=``,l=!1;break}case`newline`:l?d?d+=i.source:(!b||n!==`seq-item-ind`)&&(c=!0):f+=i.source,l=!0,p=!0,(g||_)&&(v=i),u=!0;break;case`anchor`:g&&a(i,`MULTIPLE_ANCHORS`,`A node can have at most one anchor`),i.source.endsWith(`:`)&&a(i.offset+i.source.length-1,`BAD_ALIAS`,`Anchor ending in : is ambiguous`,!0),g=i,x??=i.offset,l=!1,u=!1,m=!0;break;case`tag`:_&&a(i,`MULTIPLE_TAGS`,`A node can have at most one tag`),_=i,x??=i.offset,l=!1,u=!1,m=!0;break;case n:(g||_)&&a(i,`BAD_PROP_ORDER`,`Anchors and tags must be after the ${i.source} indicator`),b&&a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.source} in ${t??`collection`}`),b=i,l=n===`seq-item-ind`||n===`explicit-key-ind`,u=!1;break;case`comma`:if(t){y&&a(i,`UNEXPECTED_TOKEN`,`Unexpected , in ${t}`),y=i,l=!1,u=!1;break}default:a(i,`UNEXPECTED_TOKEN`,`Unexpected ${i.type} token`),l=!1,u=!1}let S=e[e.length-1],C=S?S.offset+S.source.length:i;return m&&r&&r.type!==`space`&&r.type!==`newline`&&r.type!==`comma`&&(r.type!==`scalar`||r.source!==``)&&a(r.offset,`MISSING_CHAR`,`Tags and anchors must be separated from the next token by white space`),h&&(l&&h.indent<=o||r?.type===`block-map`||r?.type===`block-seq`)&&a(h,`TAB_AS_INDENT`,`Tabs are not allowed as indentation`),{comma:y,found:b,spaceBefore:c,comment:d,hasNewline:p,anchor:g,tag:_,newlineAfterProp:v,end:C,start:x??C}}var ys=I((()=>{}));function bs(e){if(!e)return null;switch(e.type){case`alias`:case`scalar`:case`double-quoted-scalar`:case`single-quoted-scalar`:if(e.source.includes(`
92
+ `))return!0;if(e.end){for(let t of e.end)if(t.type===`newline`)return!0}return!1;case`flow-collection`:for(let t of e.items){for(let e of t.start)if(e.type===`newline`)return!0;if(t.sep){for(let e of t.sep)if(e.type===`newline`)return!0}if(bs(t.key)||bs(t.value))return!0}return!1;default:return!0}}var xs=I((()=>{}));function Ss(e,t,n){if(t?.type===`flow-collection`){let r=t.end[0];r.indent===e&&(r.source===`]`||r.source===`}`)&&bs(t)&&n(r,`BAD_INDENT`,`Flow end indicator should be more indented than parent`,!0)}}var Cs=I((()=>{xs()}));function ws(e,t,n){let{uniqueKeys:r}=e.options;if(r===!1)return!1;let i=typeof r==`function`?r:(e,t)=>e===t||$r(e)&&$r(t)&&e.value===t.value;return t.some(e=>i(e.key,n))}var Ts=I((()=>{R()}));function Es({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??Ia)(n.schema);n.atRoot&&=!1;let s=r.offset,c=null;for(let a of r.items){let{start:l,key:u,sep:d,value:f}=a,p=vs(l,{indicator:`explicit-key-ind`,next:u??d?.[0],offset:s,onError:i,parentIndent:r.indent,startOnNewline:!0}),m=!p.found;if(m){if(u&&(u.type===`block-seq`?i(s,`BLOCK_AS_IMPLICIT_KEY`,`A block sequence may not be used as an implicit map key`):`indent`in u&&u.indent!==r.indent&&i(s,`BAD_INDENT`,Ds)),!p.anchor&&!p.tag&&!d){c=p.end,p.comment&&(o.comment?o.comment+=`
93
+ `+p.comment:o.comment=p.comment);continue}(p.newlineAfterProp||bs(u))&&i(u??l[l.length-1],`MULTILINE_IMPLICIT_KEY`,`Implicit keys need to be on a single line`)}else p.found?.indent!==r.indent&&i(s,`BAD_INDENT`,Ds);n.atKey=!0;let h=p.end,g=u?e(n,u,p,i):t(n,h,l,null,p,i);n.schema.compat&&Ss(r.indent,u,i),n.atKey=!1,ws(n,o.items,g)&&i(h,`DUPLICATE_KEY`,`Map keys must be unique`);let _=vs(d??[],{indicator:`map-value-ind`,next:f,offset:g.range[2],onError:i,parentIndent:r.indent,startOnNewline:!u||u.type===`block-scalar`});if(s=_.end,_.found){m&&(f?.type===`block-map`&&!_.hasNewline&&i(s,`BLOCK_AS_IMPLICIT_KEY`,`Nested mappings are not allowed in compact mappings`),n.options.strict&&p.start<_.found.offset-1024&&i(g.range,`KEY_OVER_1024_CHARS`,`The : indicator must be at most 1024 chars after the start of an implicit block mapping key`));let c=f?e(n,f,_,i):t(n,s,d,null,_,i);n.schema.compat&&Ss(r.indent,f,i),s=c.range[2];let l=new Oa(g,c);n.options.keepSourceTokens&&(l.srcToken=a),o.items.push(l)}else{m&&i(g.range,`MISSING_CHAR`,`Implicit map keys need to be followed by map values`),_.comment&&(g.comment?g.comment+=`
94
+ `+_.comment:g.comment=_.comment);let e=new Oa(g);n.options.keepSourceTokens&&(e.srcToken=a),o.items.push(e)}}return c&&c<s&&i(c,`IMPOSSIBLE`,`Map comment with trailing content`),o.range=[r.offset,s,c??s],o}var Ds,Os=I((()=>{ka(),La(),ys(),xs(),Cs(),Ts(),Ds=`All mapping items must start at the same column`}));function ks({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=new((a?.nodeClass)??Va)(n.schema);n.atRoot&&=!1,n.atKey&&=!1;let s=r.offset,c=null;for(let{start:a,value:l}of r.items){let u=vs(a,{indicator:`seq-item-ind`,next:l,offset:s,onError:i,parentIndent:r.indent,startOnNewline:!0});if(!u.found){if(u.anchor||u.tag||l)l?.type===`block-seq`?i(u.end,`BAD_INDENT`,`All sequence items must start at the same column`):i(s,`MISSING_CHAR`,`Sequence item without - indicator`);else{c=u.end,u.comment&&(o.comment=u.comment);continue}}let d=l?e(n,l,u,i):t(n,u.end,a,null,u,i);n.schema.compat&&Ss(r.indent,l,i),s=d.range[2],o.items.push(d)}return o.range=[r.offset,s,c??s],o}var As=I((()=>{Ha(),ys(),Cs()}));function js(e,t,n,r){let i=``;if(e){let a=!1,o=``;for(let s of e){let{source:e,type:c}=s;switch(c){case`space`:a=!0;break;case`comment`:{n&&!a&&r(s,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`);let t=e.substring(1)||` `;i?i+=o+t:i=t,o=``;break}case`newline`:i&&(o+=e),a=!0;break;default:r(s,`UNEXPECTED_TOKEN`,`Unexpected ${c} at node end`)}t+=e.length}}return{comment:i,offset:t}}var Ms=I((()=>{}));function Ns({composeNode:e,composeEmptyNode:t},n,r,i,a){let o=r.start.source===`{`,s=o?`flow map`:`flow sequence`,c=new((a?.nodeClass)??(o?Ia:Va))(n.schema);c.flow=!0;let l=n.atRoot;l&&(n.atRoot=!1),n.atKey&&=!1;let u=r.offset+r.start.source.length;for(let a=0;a<r.items.length;++a){let l=r.items[a],{start:d,key:f,sep:p,value:m}=l,h=vs(d,{flow:s,indicator:`explicit-key-ind`,next:f??p?.[0],offset:u,onError:i,parentIndent:r.indent,startOnNewline:!1});if(!h.found){if(!h.anchor&&!h.tag&&!p&&!m){a===0&&h.comma?i(h.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${s}`):a<r.items.length-1&&i(h.start,`UNEXPECTED_TOKEN`,`Unexpected empty item in ${s}`),h.comment&&(c.comment?c.comment+=`
95
+ `+h.comment:c.comment=h.comment),u=h.end;continue}!o&&n.options.strict&&bs(f)&&i(f,`MULTILINE_IMPLICIT_KEY`,`Implicit keys of flow sequence pairs need to be on a single line`)}if(a===0)h.comma&&i(h.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${s}`);else if(h.comma||i(h.start,`MISSING_CHAR`,`Missing , between ${s} items`),h.comment){let e=``;loop:for(let t of d)switch(t.type){case`comma`:case`space`:break;case`comment`:e=t.source.substring(1);break loop;default:break loop}if(e){let t=c.items[c.items.length-1];Qr(t)&&(t=t.value??t.key),t.comment?t.comment+=`
96
+ `+e:t.comment=e,h.comment=h.comment.substring(e.length+1)}}if(!o&&!p&&!h.found){let r=m?e(n,m,h,i):t(n,h.end,p,null,h,i);c.items.push(r),u=r.range[2],Fs(m)&&i(r.range,`BLOCK_IN_FLOW`,Ps)}else{n.atKey=!0;let a=h.end,g=f?e(n,f,h,i):t(n,a,d,null,h,i);Fs(f)&&i(g.range,`BLOCK_IN_FLOW`,Ps),n.atKey=!1;let _=vs(p??[],{flow:s,indicator:`map-value-ind`,next:m,offset:g.range[2],onError:i,parentIndent:r.indent,startOnNewline:!1});if(_.found){if(!o&&!h.found&&n.options.strict){if(p)for(let e of p){if(e===_.found)break;if(e.type===`newline`){i(e,`MULTILINE_IMPLICIT_KEY`,`Implicit keys of flow sequence pairs need to be on a single line`);break}}h.start<_.found.offset-1024&&i(_.found,`KEY_OVER_1024_CHARS`,`The : indicator must be at most 1024 chars after the start of an implicit flow sequence key`)}}else m&&(`source`in m&&m.source?.[0]===`:`?i(m,`MISSING_CHAR`,`Missing space after : in ${s}`):i(_.start,`MISSING_CHAR`,`Missing , or : between ${s} items`));let v=m?e(n,m,_,i):_.found?t(n,_.end,p,null,_,i):null;v?Fs(m)&&i(v.range,`BLOCK_IN_FLOW`,Ps):_.comment&&(g.comment?g.comment+=`
97
+ `+_.comment:g.comment=_.comment);let y=new Oa(g,v);if(n.options.keepSourceTokens&&(y.srcToken=l),o){let e=c;ws(n,e.items,g)&&i(a,`DUPLICATE_KEY`,`Map keys must be unique`),e.items.push(y)}else{let e=new Ia(n.schema);e.flow=!0,e.items.push(y);let t=(v??g).range;e.range=[g.range[0],t[1],t[2]],c.items.push(e)}u=v?v.range[2]:_.end}}let d=o?`}`:`]`,[f,...p]=r.end,m=u;if(f?.source===d)m=f.offset+f.source.length;else{let e=s[0].toUpperCase()+s.substring(1),t=l?`${e} must end with a ${d}`:`${e} in block collection must be sufficiently indented and end with a ${d}`;i(u,l?`MISSING_CHAR`:`BAD_INDENT`,t),f&&f.source.length!==1&&p.unshift(f)}if(p.length>0){let e=js(p,m,n.options.strict,i);e.comment&&(c.comment?c.comment+=`
98
+ `+e.comment:c.comment=e.comment),c.range=[r.offset,m,e.offset]}else c.range=[r.offset,m,m];return c}var Ps,Fs,Is=I((()=>{R(),ka(),La(),Ha(),Ms(),ys(),xs(),Ts(),Ps=`Block collections are not allowed within flow collections`,Fs=e=>e&&(e.type===`block-map`||e.type===`block-seq`)}));function Ls(e,t,n,r,i,a){let o=n.type===`block-map`?Es(e,t,n,r,a):n.type===`block-seq`?ks(e,t,n,r,a):Ns(e,t,n,r,a),s=o.constructor;return i===`!`||i===s.tagName?(o.tag=s.tagName,o):(i&&(o.tag=i),o)}function Rs(e,t,n,r,i){let a=r.tag,o=a?t.directives.tagName(a.source,e=>i(a,`TAG_RESOLVE_FAILED`,e)):null;if(n.type===`block-seq`){let{anchor:e,newlineAfterProp:t}=r,n=e&&a?e.offset>a.offset?e:a:e??a;n&&(!t||t.offset<n.offset)&&i(n,`MISSING_CHAR`,`Missing newline after block sequence props`)}let s=n.type===`block-map`?`map`:n.type===`block-seq`?`seq`:n.start.source===`{`?`map`:`seq`;if(!a||!o||o===`!`||o===Ia.tagName&&s===`map`||o===Va.tagName&&s===`seq`)return Ls(e,t,n,i,o);let c=t.schema.tags.find(e=>e.tag===o&&e.collection===s);if(!c){let r=t.schema.knownTags[o];if(r?.collection===s)t.schema.tags.push(Object.assign({},r,{default:!1})),c=r;else return r?i(a,`BAD_COLLECTION_TYPE`,`${r.tag} used for ${s} collection, but expects ${r.collection??`scalar`}`,!0):i(a,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${o}`,!0),Ls(e,t,n,i,o)}let l=Ls(e,t,n,i,o,c),u=c.resolve?.(l,e=>i(a,`TAG_RESOLVE_FAILED`,e),t.options)??l,d=Vr(u)?u:new z(u);return d.range=l.range,d.tag=o,c?.format&&(d.format=c.format),d}var zs=I((()=>{R(),Mi(),La(),Ha(),Os(),As(),Is()}));function Bs(e,t,n){let r=t.offset,i=Vs(t,e.options.strict,n);if(!i)return{value:``,type:null,comment:``,range:[r,r,r]};let a=i.mode===`>`?z.BLOCK_FOLDED:z.BLOCK_LITERAL,o=t.source?Hs(t.source):[],s=o.length;for(let e=o.length-1;e>=0;--e){let t=o[e][1];if(t===``||t===`\r`)s=e;else break}if(s===0){let e=i.chomp===`+`&&o.length>0?`
99
99
  `.repeat(Math.max(1,o.length-1)):``,n=r+i.length;return t.source&&(n+=t.source.length),{value:e,type:a,comment:i.comment,range:[r,n,n]}}let c=t.indent+i.indent,l=t.offset+i.length,u=0;for(let t=0;t<s;++t){let[r,a]=o[t];if(a===``||a===`\r`)i.indent===0&&r.length>c&&(c=r.length);else{r.length<c&&n(l+r.length,`MISSING_CHAR`,`Block scalars with more-indented leading empty lines must use an explicit indentation indicator`),i.indent===0&&(c=r.length),u=t,c===0&&!e.atRoot&&n(l,`BAD_INDENT`,`Block scalar values in collections must be indented`);break}l+=r.length+a.length+1}for(let e=o.length-1;e>=s;--e)o[e][0].length>c&&(s=e+1);let d=``,f=``,p=!1;for(let e=0;e<u;++e)d+=o[e][0].slice(c)+`
100
- `;for(let e=u;e<s;++e){let[t,r]=o[e];l+=t.length+r.length+1;let s=r[r.length-1]===`\r`;if(s&&(r=r.slice(0,-1)),r&&t.length<c){let e=`Block scalar lines must not be less indented than their ${i.indent?`explicit indentation indicator`:`first line`}`;n(l-r.length-(s?2:1),`BAD_INDENT`,e),t=``}a===R.BLOCK_LITERAL?(d+=f+t.slice(c)+r,f=`
100
+ `;for(let e=u;e<s;++e){let[t,r]=o[e];l+=t.length+r.length+1;let s=r[r.length-1]===`\r`;if(s&&(r=r.slice(0,-1)),r&&t.length<c){let e=`Block scalar lines must not be less indented than their ${i.indent?`explicit indentation indicator`:`first line`}`;n(l-r.length-(s?2:1),`BAD_INDENT`,e),t=``}a===z.BLOCK_LITERAL?(d+=f+t.slice(c)+r,f=`
101
101
  `):t.length>c||r[0]===` `?(f===` `?f=`
102
102
  `:!p&&f===`
103
103
  `&&(f=`
@@ -110,149 +110,149 @@ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\
110
110
  `+o[e][0].slice(c);d[d.length-1]!==`
111
111
  `&&(d+=`
112
112
  `);break;default:d+=`
113
- `}let m=r+i.length+t.source.length;return{value:d,type:a,comment:i.comment,range:[r,m,m]}}function Hs({offset:e,props:t},n,r){if(t[0].type!==`block-scalar-header`)return r(t[0],`IMPOSSIBLE`,`Block scalar header not found`),null;let{source:i}=t[0],a=i[0],o=0,s=``,c=-1;for(let t=1;t<i.length;++t){let n=i[t];if(!s&&(n===`-`||n===`+`))s=n;else{let r=Number(n);!o&&r?o=r:c===-1&&(c=e+t)}}c!==-1&&r(c,`UNEXPECTED_TOKEN`,`Block scalar header includes extra characters: ${i}`);let l=!1,u=``,d=i.length;for(let e=1;e<t.length;++e){let i=t[e];switch(i.type){case`space`:l=!0;case`newline`:d+=i.source.length;break;case`comment`:n&&!l&&r(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`),d+=i.source.length,u=i.source.substring(1);break;case`error`:r(i,`UNEXPECTED_TOKEN`,i.message),d+=i.source.length;break;default:{r(i,`UNEXPECTED_TOKEN`,`Unexpected token in block scalar header: ${i.type}`);let e=i.source;e&&typeof e==`string`&&(d+=e.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function Us(e){let t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),i=[r?.[1]?[r[1],n.slice(r[1].length)]:[``,n]];for(let e=1;e<t.length;e+=2)i.push([t[e],t[e+1]]);return i}var Ws=F((()=>{Ni()}));function Gs(e,t,n){let{offset:r,type:i,source:a,end:o}=e,s,c,l=(e,t,i)=>n(r+e,t,i);switch(i){case`scalar`:s=R.PLAIN,c=Ks(a,l);break;case`single-quoted-scalar`:s=R.QUOTE_SINGLE,c=qs(a,l);break;case`double-quoted-scalar`:s=R.QUOTE_DOUBLE,c=Ys(a,l);break;default:return n(e,`UNEXPECTED_TOKEN`,`Expected a flow scalar value, but found: ${i}`),{value:``,type:null,comment:``,range:[r,r+a.length,r+a.length]}}let u=r+a.length,d=Ms(o,u,t,n);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function Ks(e,t){let n=``;switch(e[0]){case` `:n=`a tab character`;break;case`,`:n=`flow indicator character ,`;break;case`%`:n=`directive indicator character %`;break;case`|`:case`>`:n=`block scalar indicator ${e[0]}`;break;case`@`:case"`":n=`reserved character ${e[0]}`}return n&&t(0,`BAD_SCALAR_START`,`Plain value cannot start with ${n}`),Js(e)}function qs(e,t){return(e[e.length-1]!==`'`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing 'quote`),Js(e.slice(1,-1)).replace(/''/g,`'`)}function Js(e){let t,n;try{t=RegExp(`(.*?)(?<![ ])[ ]*\r?
113
+ `}let m=r+i.length+t.source.length;return{value:d,type:a,comment:i.comment,range:[r,m,m]}}function Vs({offset:e,props:t},n,r){if(t[0].type!==`block-scalar-header`)return r(t[0],`IMPOSSIBLE`,`Block scalar header not found`),null;let{source:i}=t[0],a=i[0],o=0,s=``,c=-1;for(let t=1;t<i.length;++t){let n=i[t];if(!s&&(n===`-`||n===`+`))s=n;else{let r=Number(n);!o&&r?o=r:c===-1&&(c=e+t)}}c!==-1&&r(c,`UNEXPECTED_TOKEN`,`Block scalar header includes extra characters: ${i}`);let l=!1,u=``,d=i.length;for(let e=1;e<t.length;++e){let i=t[e];switch(i.type){case`space`:l=!0;case`newline`:d+=i.source.length;break;case`comment`:n&&!l&&r(i,`MISSING_CHAR`,`Comments must be separated from other tokens by white space characters`),d+=i.source.length,u=i.source.substring(1);break;case`error`:r(i,`UNEXPECTED_TOKEN`,i.message),d+=i.source.length;break;default:{r(i,`UNEXPECTED_TOKEN`,`Unexpected token in block scalar header: ${i.type}`);let e=i.source;e&&typeof e==`string`&&(d+=e.length)}}}return{mode:a,indent:o,chomp:s,comment:u,length:d}}function Hs(e){let t=e.split(/\n( *)/),n=t[0],r=n.match(/^( *)/),i=[r?.[1]?[r[1],n.slice(r[1].length)]:[``,n]];for(let e=1;e<t.length;e+=2)i.push([t[e],t[e+1]]);return i}var Us=I((()=>{Mi()}));function Ws(e,t,n){let{offset:r,type:i,source:a,end:o}=e,s,c,l=(e,t,i)=>n(r+e,t,i);switch(i){case`scalar`:s=z.PLAIN,c=Gs(a,l);break;case`single-quoted-scalar`:s=z.QUOTE_SINGLE,c=Ks(a,l);break;case`double-quoted-scalar`:s=z.QUOTE_DOUBLE,c=Js(a,l);break;default:return n(e,`UNEXPECTED_TOKEN`,`Expected a flow scalar value, but found: ${i}`),{value:``,type:null,comment:``,range:[r,r+a.length,r+a.length]}}let u=r+a.length,d=js(o,u,t,n);return{value:c,type:s,comment:d.comment,range:[r,u,d.offset]}}function Gs(e,t){let n=``;switch(e[0]){case` `:n=`a tab character`;break;case`,`:n=`flow indicator character ,`;break;case`%`:n=`directive indicator character %`;break;case`|`:case`>`:n=`block scalar indicator ${e[0]}`;break;case`@`:case"`":n=`reserved character ${e[0]}`}return n&&t(0,`BAD_SCALAR_START`,`Plain value cannot start with ${n}`),qs(e)}function Ks(e,t){return(e[e.length-1]!==`'`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing 'quote`),qs(e.slice(1,-1)).replace(/''/g,`'`)}function qs(e){let t,n;try{t=RegExp(`(.*?)(?<![ ])[ ]*\r?
114
114
  `,`sy`),n=RegExp(`[ ]*(.*?)(?:(?<![ ])[ ]*)?\r?
115
115
  `,`sy`)}catch{t=/(.*?)[ \t]*\r?\n/sy,n=/[ \t]*(.*?)[ \t]*\r?\n/sy}let r=t.exec(e);if(!r)return e;let i=r[1],a=` `,o=t.lastIndex;for(n.lastIndex=o;r=n.exec(e);)r[1]===``?a===`
116
116
  `?i+=a:a=`
117
- `:(i+=a+r[1],a=` `),o=n.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,r=s.exec(e),i+a+(r?.[1]??``)}function Ys(e,t){let n=``;for(let r=1;r<e.length-1;++r){let i=e[r];if(i!==`\r`||e[r+1]!==`
117
+ `:(i+=a+r[1],a=` `),o=n.lastIndex;let s=/[ \t]*(.*)/sy;return s.lastIndex=o,r=s.exec(e),i+a+(r?.[1]??``)}function Js(e,t){let n=``;for(let r=1;r<e.length-1;++r){let i=e[r];if(i!==`\r`||e[r+1]!==`
118
118
  `){if(i===`
119
- `){let{fold:t,offset:i}=Xs(e,r);n+=t,r=i}else if(i===`\\`){let i=e[++r],a=Qs[i];if(a)n+=a;else if(i===`
119
+ `){let{fold:t,offset:i}=Ys(e,r);n+=t,r=i}else if(i===`\\`){let i=e[++r],a=Zs[i];if(a)n+=a;else if(i===`
120
120
  `)for(i=e[r+1];i===` `||i===` `;)i=e[++r+1];else if(i===`\r`&&e[r+1]===`
121
- `)for(i=e[++r+1];i===` `||i===` `;)i=e[++r+1];else if(i===`x`||i===`u`||i===`U`){let a=i===`x`?2:i===`u`?4:8;n+=Zs(e,r+1,a,t),r+=a}else{let i=e.substr(r-1,2);t(r-1,`BAD_DQ_ESCAPE`,`Invalid escape sequence ${i}`),n+=i}}else if(i===` `||i===` `){let t=r,a=e[r+1];for(;a===` `||a===` `;)a=e[++r+1];a!==`
121
+ `)for(i=e[++r+1];i===` `||i===` `;)i=e[++r+1];else if(i===`x`||i===`u`||i===`U`){let a=i===`x`?2:i===`u`?4:8;n+=Xs(e,r+1,a,t),r+=a}else{let i=e.substr(r-1,2);t(r-1,`BAD_DQ_ESCAPE`,`Invalid escape sequence ${i}`),n+=i}}else if(i===` `||i===` `){let t=r,a=e[r+1];for(;a===` `||a===` `;)a=e[++r+1];a!==`
122
122
  `&&(a!==`\r`||e[r+2]!==`
123
- `)&&(n+=r>t?e.slice(t,r+1):i)}else n+=i}}return(e[e.length-1]!==`"`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing "quote`),n}function Xs(e,t){let n=``,r=e[t+1];for(;(r===` `||r===` `||r===`
123
+ `)&&(n+=r>t?e.slice(t,r+1):i)}else n+=i}}return(e[e.length-1]!==`"`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing "quote`),n}function Ys(e,t){let n=``,r=e[t+1];for(;(r===` `||r===` `||r===`
124
124
  `||r===`\r`)&&(r!==`\r`||e[t+2]===`
125
125
  `);)r===`
126
126
  `&&(n+=`
127
- `),t+=1,r=e[t+1];return n||=` `,{fold:n,offset:t}}function Zs(e,t,n,r){let i=e.substr(t,n),a=i.length===n&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(a)}catch{let i=e.substr(t-2,n+2);return r(t-2,`BAD_DQ_ESCAPE`,`Invalid escape sequence ${i}`),i}}var Qs,$s=F((()=>{Ni(),Ns(),Qs={0:`\0`,a:`\x07`,b:`\b`,e:`\x1B`,f:`\f`,n:`
128
- `,r:`\r`,t:` `,v:`\v`,N:`…`,_:`\xA0`,L:`\u2028`,P:`\u2029`," ":` `,'"':`"`,"/":`/`,"\\":`\\`," ":` `}}));function ec(e,t,n,r){let{value:i,type:a,comment:o,range:s}=t.type===`block-scalar`?Vs(e,t,r):Gs(t,e.options.strict,r),c=n?e.directives.tagName(n.source,e=>r(n,`TAG_RESOLVE_FAILED`,e)):null,l;l=e.options.stringKeys&&e.atKey?e.schema[qr]:c?tc(e.schema,i,c,n,r):t.type===`scalar`?nc(e,i,t,r):e.schema[qr];let u;try{let a=l.resolve(i,e=>r(n??t,`TAG_RESOLVE_FAILED`,e),e.options);u=ei(a)?a:new R(a)}catch(e){let a=e instanceof Error?e.message:String(e);r(n??t,`TAG_RESOLVE_FAILED`,a),u=new R(i)}return u.range=s,u.source=i,a&&(u.type=a),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function tc(e,t,n,r,i){if(n===`!`)return e[qr];let a=[];for(let t of e.tags)if(!t.collection&&t.tag===n){if(t.default&&t.test)a.push(t);else return t}for(let e of a)if(e.test?.test(t))return e;let o=e.knownTags[n];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(r,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${n}`,n!==`tag:yaml.org,2002:str`),e[qr])}function nc({atKey:e,directives:t,schema:n},r,i,a){let o=n.tags.find(t=>(t.default===!0||e&&t.default===`key`)&&t.test?.test(r))||n[qr];if(n.compat){let e=n.compat.find(e=>e.default&&e.test?.test(r))??n[qr];o.tag!==e.tag&&a(i,`TAG_RESOLVE_FAILED`,`Value may be parsed as either ${t.tagString(o.tag)} or ${t.tagString(e.tag)}`,!0)}return o}var rc=F((()=>{L(),Ni(),Ws(),$s()}));function ic(e,t,n){if(t){n??=t.length;for(let r=n-1;r>=0;--r){let n=t[r];switch(n.type){case`space`:case`comment`:case`newline`:e-=n.source.length;continue}for(n=t[++r];n?.type===`space`;)e+=n.source.length,n=t[++r];break}}return e}var ac=F((()=>{}));function oc(e,t,n,r){let i=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=n,l,u=!0;switch(t.type){case`alias`:l=cc(e,t,r),(s||c)&&r(t,`ALIAS_PROPS`,`An alias node must not specify any properties`);break;case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:case`block-scalar`:l=ec(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case`block-map`:case`block-seq`:case`flow-collection`:try{l=zs(lc,e,t,n,r),s&&(l.anchor=s.source.substring(1))}catch(e){r(t,`RESOURCE_EXHAUSTION`,e instanceof Error?e.message:String(e))}break;default:r(t,`UNEXPECTED_TOKEN`,t.type===`error`?t.message:`Unsupported token (type: ${t.type})`),u=!1}return l??=sc(e,t.offset,void 0,null,n,r),s&&l.anchor===``&&r(s,`BAD_ALIAS`,`Anchor cannot be an empty string`),i&&e.options.stringKeys&&(!ei(l)||typeof l.value!=`string`||l.tag&&l.tag!==`tag:yaml.org,2002:str`)&&r(c??t,`NON_STRING_KEY`,`With stringKeys, all keys must be strings`),a&&(l.spaceBefore=!0),o&&(t.type===`scalar`&&t.source===``?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function sc(e,t,n,r,{spaceBefore:i,comment:a,anchor:o,tag:s,end:c},l){let u=ec(e,{type:`scalar`,offset:ic(t,n,r),indent:-1,source:``},s,l);return o&&(u.anchor=o.source.substring(1),u.anchor===``&&l(o,`BAD_ALIAS`,`Anchor cannot be an empty string`)),i&&(u.spaceBefore=!0),a&&(u.comment=a,u.range[2]=c),u}function cc({options:e},{offset:t,source:n,end:r},i){let a=new Ai(n.substring(1));a.source===``&&i(t,`BAD_ALIAS`,`Alias cannot be an empty string`),a.source.endsWith(`:`)&&i(t+n.length-1,`BAD_ALIAS`,`Alias ending in : is ambiguous`,!0);let o=t+n.length,s=Ms(r,o,e.strict,i);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}var lc,uc=F((()=>{ji(),L(),Bs(),rc(),Ns(),ac(),lc={composeNode:oc,composeEmptyNode:sc}}));function dc(e,t,{offset:n,start:r,value:i,end:a},o){let s=Object.assign({_directives:t},e),c=new fs(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=ys(r,{indicator:`doc-start`,next:i??a?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,i&&(i.type===`block-map`||i.type===`block-seq`)&&!u.hasNewline&&o(u.end,`MISSING_CHAR`,`Block collection cannot start on same line with directives-end marker`)),c.contents=i?oc(l,i,u,o):sc(l,u.end,r,null,u,o);let d=c.contents.range[2],f=Ms(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[n,d,f.offset],c}var fc=F((()=>{ps(),uc(),Ns(),bs()}));function pc(e){if(typeof e==`number`)return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:n}=e;return[t,t+(typeof n==`string`?n.length:1)]}function mc(e){let t=``,n=!1,r=!1;for(let i=0;i<e.length;++i){let a=e[i];switch(a[0]){case`#`:t+=(t===``?``:r?`
127
+ `),t+=1,r=e[t+1];return n||=` `,{fold:n,offset:t}}function Xs(e,t,n,r){let i=e.substr(t,n),a=i.length===n&&/^[0-9a-fA-F]+$/.test(i)?parseInt(i,16):NaN;try{return String.fromCodePoint(a)}catch{let i=e.substr(t-2,n+2);return r(t-2,`BAD_DQ_ESCAPE`,`Invalid escape sequence ${i}`),i}}var Zs,Qs=I((()=>{Mi(),Ms(),Zs={0:`\0`,a:`\x07`,b:`\b`,e:`\x1B`,f:`\f`,n:`
128
+ `,r:`\r`,t:` `,v:`\v`,N:`…`,_:`\xA0`,L:`\u2028`,P:`\u2029`," ":` `,'"':`"`,"/":`/`,"\\":`\\`," ":` `}}));function $s(e,t,n,r){let{value:i,type:a,comment:o,range:s}=t.type===`block-scalar`?Bs(e,t,r):Ws(t,e.options.strict,r),c=n?e.directives.tagName(n.source,e=>r(n,`TAG_RESOLVE_FAILED`,e)):null,l;l=e.options.stringKeys&&e.atKey?e.schema[Kr]:c?ec(e.schema,i,c,n,r):t.type===`scalar`?tc(e,i,t,r):e.schema[Kr];let u;try{let a=l.resolve(i,e=>r(n??t,`TAG_RESOLVE_FAILED`,e),e.options);u=$r(a)?a:new z(a)}catch(e){let a=e instanceof Error?e.message:String(e);r(n??t,`TAG_RESOLVE_FAILED`,a),u=new z(i)}return u.range=s,u.source=i,a&&(u.type=a),c&&(u.tag=c),l.format&&(u.format=l.format),o&&(u.comment=o),u}function ec(e,t,n,r,i){if(n===`!`)return e[Kr];let a=[];for(let t of e.tags)if(!t.collection&&t.tag===n){if(t.default&&t.test)a.push(t);else return t}for(let e of a)if(e.test?.test(t))return e;let o=e.knownTags[n];return o&&!o.collection?(e.tags.push(Object.assign({},o,{default:!1,test:void 0})),o):(i(r,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${n}`,n!==`tag:yaml.org,2002:str`),e[Kr])}function tc({atKey:e,directives:t,schema:n},r,i,a){let o=n.tags.find(t=>(t.default===!0||e&&t.default===`key`)&&t.test?.test(r))||n[Kr];if(n.compat){let e=n.compat.find(e=>e.default&&e.test?.test(r))??n[Kr];o.tag!==e.tag&&a(i,`TAG_RESOLVE_FAILED`,`Value may be parsed as either ${t.tagString(o.tag)} or ${t.tagString(e.tag)}`,!0)}return o}var nc=I((()=>{R(),Mi(),Us(),Qs()}));function rc(e,t,n){if(t){n??=t.length;for(let r=n-1;r>=0;--r){let n=t[r];switch(n.type){case`space`:case`comment`:case`newline`:e-=n.source.length;continue}for(n=t[++r];n?.type===`space`;)e+=n.source.length,n=t[++r];break}}return e}var ic=I((()=>{}));function ac(e,t,n,r){let i=e.atKey,{spaceBefore:a,comment:o,anchor:s,tag:c}=n,l,u=!0;switch(t.type){case`alias`:l=sc(e,t,r),(s||c)&&r(t,`ALIAS_PROPS`,`An alias node must not specify any properties`);break;case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:case`block-scalar`:l=$s(e,t,c,r),s&&(l.anchor=s.source.substring(1));break;case`block-map`:case`block-seq`:case`flow-collection`:try{l=Rs(cc,e,t,n,r),s&&(l.anchor=s.source.substring(1))}catch(e){r(t,`RESOURCE_EXHAUSTION`,e instanceof Error?e.message:String(e))}break;default:r(t,`UNEXPECTED_TOKEN`,t.type===`error`?t.message:`Unsupported token (type: ${t.type})`),u=!1}return l??=oc(e,t.offset,void 0,null,n,r),s&&l.anchor===``&&r(s,`BAD_ALIAS`,`Anchor cannot be an empty string`),i&&e.options.stringKeys&&(!$r(l)||typeof l.value!=`string`||l.tag&&l.tag!==`tag:yaml.org,2002:str`)&&r(c??t,`NON_STRING_KEY`,`With stringKeys, all keys must be strings`),a&&(l.spaceBefore=!0),o&&(t.type===`scalar`&&t.source===``?l.comment=o:l.commentBefore=o),e.options.keepSourceTokens&&u&&(l.srcToken=t),l}function oc(e,t,n,r,{spaceBefore:i,comment:a,anchor:o,tag:s,end:c},l){let u=$s(e,{type:`scalar`,offset:rc(t,n,r),indent:-1,source:``},s,l);return o&&(u.anchor=o.source.substring(1),u.anchor===``&&l(o,`BAD_ALIAS`,`Anchor cannot be an empty string`)),i&&(u.spaceBefore=!0),a&&(u.comment=a,u.range[2]=c),u}function sc({options:e},{offset:t,source:n,end:r},i){let a=new ki(n.substring(1));a.source===``&&i(t,`BAD_ALIAS`,`Alias cannot be an empty string`),a.source.endsWith(`:`)&&i(t+n.length-1,`BAD_ALIAS`,`Alias ending in : is ambiguous`,!0);let o=t+n.length,s=js(r,o,e.strict,i);return a.range=[t,o,s.offset],s.comment&&(a.comment=s.comment),a}var cc,lc=I((()=>{Ai(),R(),zs(),nc(),Ms(),ic(),cc={composeNode:ac,composeEmptyNode:oc}}));function uc(e,t,{offset:n,start:r,value:i,end:a},o){let s=Object.assign({_directives:t},e),c=new ds(void 0,s),l={atKey:!1,atRoot:!0,directives:c.directives,options:c.options,schema:c.schema},u=vs(r,{indicator:`doc-start`,next:i??a?.[0],offset:n,onError:o,parentIndent:0,startOnNewline:!0});u.found&&(c.directives.docStart=!0,i&&(i.type===`block-map`||i.type===`block-seq`)&&!u.hasNewline&&o(u.end,`MISSING_CHAR`,`Block collection cannot start on same line with directives-end marker`)),c.contents=i?ac(l,i,u,o):oc(l,u.end,r,null,u,o);let d=c.contents.range[2],f=js(a,d,!1,o);return f.comment&&(c.comment=f.comment),c.range=[n,d,f.offset],c}var dc=I((()=>{fs(),lc(),Ms(),ys()}));function fc(e){if(typeof e==`number`)return[e,e+1];if(Array.isArray(e))return e.length===2?e:[e[0],e[1]];let{offset:t,source:n}=e;return[t,t+(typeof n==`string`?n.length:1)]}function pc(e){let t=``,n=!1,r=!1;for(let i=0;i<e.length;++i){let a=e[i];switch(a[0]){case`#`:t+=(t===``?``:r?`
129
129
 
130
130
  `:`
131
- `)+(a.substring(1)||` `),n=!0,r=!1;break;case`%`:e[i+1]?.[0]!==`#`&&(i+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:t,afterEmptyLine:r}}var hc,gc=F((()=>{_i(),ps(),vs(),L(),fc(),Ns(),hc=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{let i=pc(e);r?this.warnings.push(new gs(i,t,n)):this.errors.push(new hs(i,t,n))},this.directives=new gi({version:e.version||`1.2`}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:r}=mc(this.prelude);if(n){let i=e.contents;if(t)e.comment=e.comment?`${e.comment}\n${n}`:n;else if(r||e.directives.docStart||!i)e.commentBefore=n;else if(Vr(i)&&!i.flow&&i.items.length>0){let e=i.items[0];$r(e)&&(e=e.key);let t=e.commentBefore;e.commentBefore=t?`${n}\n${t}`:n}else{let e=i.commentBefore;i.commentBefore=e?`${n}\n${e}`:n}}if(t){for(let t=0;t<this.errors.length;++t)e.errors.push(this.errors[t]);for(let t=0;t<this.warnings.length;++t)e.warnings.push(this.warnings[t])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:mc(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,n=-1){for(let t of e)yield*this.next(t);yield*this.end(t,n)}*next(e){switch(e.type){case`directive`:this.directives.add(e.source,(t,n,r)=>{let i=pc(e);i[0]+=t,this.onError(i,`BAD_DIRECTIVE`,n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case`document`:{let t=dc(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,`MISSING_CHAR`,`Missing directives-end/doc-start indicator line`),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case`byte-order-mark`:case`space`:break;case`comment`:case`newline`:this.prelude.push(e.source);break;case`error`:{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new hs(pc(e),`UNEXPECTED_TOKEN`,t);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case`doc-end`:{if(!this.doc){this.errors.push(new hs(pc(e),`UNEXPECTED_TOKEN`,`Unexpected doc-end without preceding document`));break}this.doc.directives.docEnd=!0;let t=Ms(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let e=this.doc.comment;this.doc.comment=e?`${e}\n${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new hs(pc(e),`UNEXPECTED_TOKEN`,`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let e=Object.assign({_directives:this.directives},this.options),n=new fs(void 0,e);this.atDirectives&&this.onError(t,`MISSING_CHAR`,`Missing directives-end indicator line`),n.range=[0,t,t],this.decorate(n,!1),yield n}}}}));function _c(e,t=!0,n){if(e){let r=(e,t,r)=>{let i=typeof e==`number`?e:Array.isArray(e)?e[0]:e.offset;if(n)n(i,t,r);else throw new hs([i,i+1],t,r)};switch(e.type){case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return Gs(e,t,r);case`block-scalar`:return Vs({options:{strict:t}},e,r)}}return null}function vc(e,t){let{implicitKey:n=!1,indent:r,inFlow:i=!1,offset:a=-1,type:o=`PLAIN`}=t,s=ia({type:o,value:e},{implicitKey:n,indent:r>0?` `.repeat(r):``,inFlow:i,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:`newline`,offset:-1,indent:r,source:`
131
+ `)+(a.substring(1)||` `),n=!0,r=!1;break;case`%`:e[i+1]?.[0]!==`#`&&(i+=1),n=!1;break;default:n||(r=!0),n=!1}}return{comment:t,afterEmptyLine:r}}var mc,hc=I((()=>{gi(),fs(),_s(),R(),dc(),Ms(),mc=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{let i=fc(e);r?this.warnings.push(new hs(i,t,n)):this.errors.push(new ms(i,t,n))},this.directives=new hi({version:e.version||`1.2`}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:r}=pc(this.prelude);if(n){let i=e.contents;if(t)e.comment=e.comment?`${e.comment}\n${n}`:n;else if(r||e.directives.docStart||!i)e.commentBefore=n;else if(Br(i)&&!i.flow&&i.items.length>0){let e=i.items[0];Qr(e)&&(e=e.key);let t=e.commentBefore;e.commentBefore=t?`${n}\n${t}`:n}else{let e=i.commentBefore;i.commentBefore=e?`${n}\n${e}`:n}}if(t){for(let t=0;t<this.errors.length;++t)e.errors.push(this.errors[t]);for(let t=0;t<this.warnings.length;++t)e.warnings.push(this.warnings[t])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:pc(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,n=-1){for(let t of e)yield*this.next(t);yield*this.end(t,n)}*next(e){switch(e.type){case`directive`:this.directives.add(e.source,(t,n,r)=>{let i=fc(e);i[0]+=t,this.onError(i,`BAD_DIRECTIVE`,n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case`document`:{let t=uc(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,`MISSING_CHAR`,`Missing directives-end/doc-start indicator line`),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case`byte-order-mark`:case`space`:break;case`comment`:case`newline`:this.prelude.push(e.source);break;case`error`:{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,n=new ms(fc(e),`UNEXPECTED_TOKEN`,t);this.atDirectives||!this.doc?this.errors.push(n):this.doc.errors.push(n);break}case`doc-end`:{if(!this.doc){this.errors.push(new ms(fc(e),`UNEXPECTED_TOKEN`,`Unexpected doc-end without preceding document`));break}this.doc.directives.docEnd=!0;let t=js(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let e=this.doc.comment;this.doc.comment=e?`${e}\n${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new ms(fc(e),`UNEXPECTED_TOKEN`,`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let e=Object.assign({_directives:this.directives},this.options),n=new ds(void 0,e);this.atDirectives&&this.onError(t,`MISSING_CHAR`,`Missing directives-end indicator line`),n.range=[0,t,t],this.decorate(n,!1),yield n}}}}));function gc(e,t=!0,n){if(e){let r=(e,t,r)=>{let i=typeof e==`number`?e:Array.isArray(e)?e[0]:e.offset;if(n)n(i,t,r);else throw new ms([i,i+1],t,r)};switch(e.type){case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return Ws(e,t,r);case`block-scalar`:return Bs({options:{strict:t}},e,r)}}return null}function _c(e,t){let{implicitKey:n=!1,indent:r,inFlow:i=!1,offset:a=-1,type:o=`PLAIN`}=t,s=ra({type:o,value:e},{implicitKey:n,indent:r>0?` `.repeat(r):``,inFlow:i,options:{blockQuote:!0,lineWidth:-1}}),c=t.end??[{type:`newline`,offset:-1,indent:r,source:`
132
132
  `}];switch(s[0]){case`|`:case`>`:{let e=s.indexOf(`
133
133
  `),t=s.substring(0,e),n=s.substring(e+1)+`
134
- `,i=[{type:`block-scalar-header`,offset:a,indent:r,source:t}];return xc(i,c)||i.push({type:`newline`,offset:-1,indent:r,source:`
135
- `}),{type:`block-scalar`,offset:a,indent:r,props:i,source:n}}case`"`:return{type:`double-quoted-scalar`,offset:a,indent:r,source:s,end:c};case`'`:return{type:`single-quoted-scalar`,offset:a,indent:r,source:s,end:c};default:return{type:`scalar`,offset:a,indent:r,source:s,end:c}}}function yc(e,t,n={}){let{afterKey:r=!1,implicitKey:i=!1,inFlow:a=!1,type:o}=n,s=`indent`in e?e.indent:null;if(r&&typeof s==`number`&&(s+=2),!o)switch(e.type){case`single-quoted-scalar`:o=`QUOTE_SINGLE`;break;case`double-quoted-scalar`:o=`QUOTE_DOUBLE`;break;case`block-scalar`:{let t=e.props[0];if(t.type!==`block-scalar-header`)throw Error(`Invalid block scalar header`);o=t.source[0]===`>`?`BLOCK_FOLDED`:`BLOCK_LITERAL`;break}default:o=`PLAIN`}let c=ia({type:o,value:t},{implicitKey:i||s===null,indent:s!==null&&s>0?` `.repeat(s):``,inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case`|`:case`>`:bc(e,c);break;case`"`:Sc(e,c,`double-quoted-scalar`);break;case`'`:Sc(e,c,`single-quoted-scalar`);break;default:Sc(e,c,`scalar`)}}function bc(e,t){let n=t.indexOf(`
134
+ `,i=[{type:`block-scalar-header`,offset:a,indent:r,source:t}];return bc(i,c)||i.push({type:`newline`,offset:-1,indent:r,source:`
135
+ `}),{type:`block-scalar`,offset:a,indent:r,props:i,source:n}}case`"`:return{type:`double-quoted-scalar`,offset:a,indent:r,source:s,end:c};case`'`:return{type:`single-quoted-scalar`,offset:a,indent:r,source:s,end:c};default:return{type:`scalar`,offset:a,indent:r,source:s,end:c}}}function vc(e,t,n={}){let{afterKey:r=!1,implicitKey:i=!1,inFlow:a=!1,type:o}=n,s=`indent`in e?e.indent:null;if(r&&typeof s==`number`&&(s+=2),!o)switch(e.type){case`single-quoted-scalar`:o=`QUOTE_SINGLE`;break;case`double-quoted-scalar`:o=`QUOTE_DOUBLE`;break;case`block-scalar`:{let t=e.props[0];if(t.type!==`block-scalar-header`)throw Error(`Invalid block scalar header`);o=t.source[0]===`>`?`BLOCK_FOLDED`:`BLOCK_LITERAL`;break}default:o=`PLAIN`}let c=ra({type:o,value:t},{implicitKey:i||s===null,indent:s!==null&&s>0?` `.repeat(s):``,inFlow:a,options:{blockQuote:!0,lineWidth:-1}});switch(c[0]){case`|`:case`>`:yc(e,c);break;case`"`:xc(e,c,`double-quoted-scalar`);break;case`'`:xc(e,c,`single-quoted-scalar`);break;default:xc(e,c,`scalar`)}}function yc(e,t){let n=t.indexOf(`
136
136
  `),r=t.substring(0,n),i=t.substring(n+1)+`
137
- `;if(e.type===`block-scalar`){let t=e.props[0];if(t.type!==`block-scalar-header`)throw Error(`Invalid block scalar header`);t.source=r,e.source=i}else{let{offset:t}=e,n=`indent`in e?e.indent:-1,a=[{type:`block-scalar-header`,offset:t,indent:n,source:r}];xc(a,`end`in e?e.end:void 0)||a.push({type:`newline`,offset:-1,indent:n,source:`
138
- `});for(let t of Object.keys(e))t!==`type`&&t!==`offset`&&delete e[t];Object.assign(e,{type:`block-scalar`,indent:n,props:a,source:i})}}function xc(e,t){if(t)for(let n of t)switch(n.type){case`space`:case`comment`:e.push(n);break;case`newline`:return e.push(n),!0}return!1}function Sc(e,t,n){switch(e.type){case`scalar`:case`double-quoted-scalar`:case`single-quoted-scalar`:e.type=n,e.source=t;break;case`block-scalar`:{let r=e.props.slice(1),i=t.length;e.props[0].type===`block-scalar-header`&&(i-=e.props[0].source.length);for(let e of r)e.offset+=i;delete e.props,Object.assign(e,{type:n,source:t,end:r});break}case`block-map`:case`block-seq`:{let r={type:`newline`,offset:e.offset+t.length,indent:e.indent,source:`
139
- `};delete e.items,Object.assign(e,{type:n,source:t,end:[r]});break}default:{let r=`indent`in e?e.indent:-1,i=`end`in e&&Array.isArray(e.end)?e.end.filter(e=>e.type===`space`||e.type===`comment`||e.type===`newline`):[];for(let t of Object.keys(e))t!==`type`&&t!==`offset`&&delete e[t];Object.assign(e,{type:n,indent:r,source:t,end:i})}}}var Cc=F((()=>{Ws(),$s(),vs(),ca()}));function wc(e){switch(e.type){case`block-scalar`:{let t=``;for(let n of e.props)t+=wc(n);return t+e.source}case`block-map`:case`block-seq`:{let t=``;for(let n of e.items)t+=Tc(n);return t}case`flow-collection`:{let t=e.start.source;for(let n of e.items)t+=Tc(n);for(let n of e.end)t+=n.source;return t}case`document`:{let t=Tc(e);if(e.end)for(let n of e.end)t+=n.source;return t}default:{let t=e.source;if(`end`in e&&e.end)for(let n of e.end)t+=n.source;return t}}}function Tc({start:e,key:t,sep:n,value:r}){let i=``;for(let t of e)i+=t.source;if(t&&(i+=wc(t)),n)for(let e of n)i+=e.source;return r&&(i+=wc(r)),i}var Ec,Dc=F((()=>{Ec=e=>`type`in e?wc(e):Tc(e)}));function Oc(e,t){`type`in e&&e.type===`document`&&(e={start:e.start,value:e.value}),kc(Object.freeze([]),e,t)}function kc(e,t,n){let r=n(t,e);if(typeof r==`symbol`)return r;for(let i of[`key`,`value`]){let a=t[i];if(a&&`items`in a){for(let t=0;t<a.items.length;++t){let r=kc(Object.freeze(e.concat([[i,t]])),a.items[t],n);if(typeof r==`number`)t=r-1;else if(r===Ac)return Ac;else r===Mc&&(a.items.splice(t,1),--t)}typeof r==`function`&&i===`key`&&(r=r(t,e))}}return typeof r==`function`?r(t,e):r}var Ac,jc,Mc,Nc=F((()=>{Ac=Symbol(`break visit`),jc=Symbol(`skip children`),Mc=Symbol(`remove item`),Oc.BREAK=Ac,Oc.SKIP=jc,Oc.REMOVE=Mc,Oc.itemAtPath=(e,t)=>{let n=e;for(let[e,r]of t){let t=n?.[e];if(t&&`items`in t)n=t.items[r];else return}return n},Oc.parentCollection=(e,t)=>{let n=Oc.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],i=n?.[r];if(i&&`items`in i)return i;throw Error(`Parent collection not found`)}})),Pc=Qe({BOM:()=>``,DOCUMENT:()=>``,FLOW_END:()=>``,SCALAR:()=>``,createScalarToken:()=>vc,isCollection:()=>Lc,isScalar:()=>Rc,prettyToken:()=>Fc,resolveAsScalar:()=>_c,setScalarValue:()=>yc,stringify:()=>Ec,tokenType:()=>Ic,visit:()=>Oc});function Fc(e){switch(e){case``:return`<BOM>`;case``:return`<DOC>`;case``:return`<FLOW_END>`;case``:return`<SCALAR>`;default:return JSON.stringify(e)}}function Ic(e){switch(e){case``:return`byte-order-mark`;case``:return`doc-mode`;case``:return`flow-error-end`;case``:return`scalar`;case`---`:return`doc-start`;case`...`:return`doc-end`;case``:case`
137
+ `;if(e.type===`block-scalar`){let t=e.props[0];if(t.type!==`block-scalar-header`)throw Error(`Invalid block scalar header`);t.source=r,e.source=i}else{let{offset:t}=e,n=`indent`in e?e.indent:-1,a=[{type:`block-scalar-header`,offset:t,indent:n,source:r}];bc(a,`end`in e?e.end:void 0)||a.push({type:`newline`,offset:-1,indent:n,source:`
138
+ `});for(let t of Object.keys(e))t!==`type`&&t!==`offset`&&delete e[t];Object.assign(e,{type:`block-scalar`,indent:n,props:a,source:i})}}function bc(e,t){if(t)for(let n of t)switch(n.type){case`space`:case`comment`:e.push(n);break;case`newline`:return e.push(n),!0}return!1}function xc(e,t,n){switch(e.type){case`scalar`:case`double-quoted-scalar`:case`single-quoted-scalar`:e.type=n,e.source=t;break;case`block-scalar`:{let r=e.props.slice(1),i=t.length;e.props[0].type===`block-scalar-header`&&(i-=e.props[0].source.length);for(let e of r)e.offset+=i;delete e.props,Object.assign(e,{type:n,source:t,end:r});break}case`block-map`:case`block-seq`:{let r={type:`newline`,offset:e.offset+t.length,indent:e.indent,source:`
139
+ `};delete e.items,Object.assign(e,{type:n,source:t,end:[r]});break}default:{let r=`indent`in e?e.indent:-1,i=`end`in e&&Array.isArray(e.end)?e.end.filter(e=>e.type===`space`||e.type===`comment`||e.type===`newline`):[];for(let t of Object.keys(e))t!==`type`&&t!==`offset`&&delete e[t];Object.assign(e,{type:n,indent:r,source:t,end:i})}}}var Sc=I((()=>{Us(),Qs(),_s(),sa()}));function Cc(e){switch(e.type){case`block-scalar`:{let t=``;for(let n of e.props)t+=Cc(n);return t+e.source}case`block-map`:case`block-seq`:{let t=``;for(let n of e.items)t+=wc(n);return t}case`flow-collection`:{let t=e.start.source;for(let n of e.items)t+=wc(n);for(let n of e.end)t+=n.source;return t}case`document`:{let t=wc(e);if(e.end)for(let n of e.end)t+=n.source;return t}default:{let t=e.source;if(`end`in e&&e.end)for(let n of e.end)t+=n.source;return t}}}function wc({start:e,key:t,sep:n,value:r}){let i=``;for(let t of e)i+=t.source;if(t&&(i+=Cc(t)),n)for(let e of n)i+=e.source;return r&&(i+=Cc(r)),i}var Tc,Ec=I((()=>{Tc=e=>`type`in e?Cc(e):wc(e)}));function Dc(e,t){`type`in e&&e.type===`document`&&(e={start:e.start,value:e.value}),Oc(Object.freeze([]),e,t)}function Oc(e,t,n){let r=n(t,e);if(typeof r==`symbol`)return r;for(let i of[`key`,`value`]){let a=t[i];if(a&&`items`in a){for(let t=0;t<a.items.length;++t){let r=Oc(Object.freeze(e.concat([[i,t]])),a.items[t],n);if(typeof r==`number`)t=r-1;else if(r===kc)return kc;else r===jc&&(a.items.splice(t,1),--t)}typeof r==`function`&&i===`key`&&(r=r(t,e))}}return typeof r==`function`?r(t,e):r}var kc,Ac,jc,Mc=I((()=>{kc=Symbol(`break visit`),Ac=Symbol(`skip children`),jc=Symbol(`remove item`),Dc.BREAK=kc,Dc.SKIP=Ac,Dc.REMOVE=jc,Dc.itemAtPath=(e,t)=>{let n=e;for(let[e,r]of t){let t=n?.[e];if(t&&`items`in t)n=t.items[r];else return}return n},Dc.parentCollection=(e,t)=>{let n=Dc.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],i=n?.[r];if(i&&`items`in i)return i;throw Error(`Parent collection not found`)}})),Nc=Ze({BOM:()=>``,DOCUMENT:()=>``,FLOW_END:()=>``,SCALAR:()=>``,createScalarToken:()=>_c,isCollection:()=>Ic,isScalar:()=>Lc,prettyToken:()=>Pc,resolveAsScalar:()=>gc,setScalarValue:()=>vc,stringify:()=>Tc,tokenType:()=>Fc,visit:()=>Dc});function Pc(e){switch(e){case``:return`<BOM>`;case``:return`<DOC>`;case``:return`<FLOW_END>`;case``:return`<SCALAR>`;default:return JSON.stringify(e)}}function Fc(e){switch(e){case``:return`byte-order-mark`;case``:return`doc-mode`;case``:return`flow-error-end`;case``:return`scalar`;case`---`:return`doc-start`;case`...`:return`doc-end`;case``:case`
140
140
  `:case`\r
141
- `:return`newline`;case`-`:return`seq-item-ind`;case`?`:return`explicit-key-ind`;case`:`:return`map-value-ind`;case`{`:return`flow-map-start`;case`}`:return`flow-map-end`;case`[`:return`flow-seq-start`;case`]`:return`flow-seq-end`;case`,`:return`comma`}switch(e[0]){case` `:case` `:return`space`;case`#`:return`comment`;case`%`:return`directive-line`;case`*`:return`alias`;case`&`:return`anchor`;case`!`:return`tag`;case`'`:return`single-quoted-scalar`;case`"`:return`double-quoted-scalar`;case`|`:case`>`:return`block-scalar-header`}return null}var Lc,Rc,zc=F((()=>{Cc(),Dc(),Nc(),Lc=e=>!!e&&`items`in e,Rc=e=>!!e&&(e.type===`scalar`||e.type===`single-quoted-scalar`||e.type===`double-quoted-scalar`||e.type===`block-scalar`)}));function Bc(e){switch(e){case void 0:case` `:case`
142
- `:case`\r`:case` `:return!0;default:return!1}}var Vc,Hc,Uc,Wc,Gc,Kc,qc=F((()=>{zc(),Vc=new Set(`0123456789ABCDEFabcdef`),Hc=new Set(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()`),Uc=new Set(`,[]{}`),Wc=new Set(` ,[]{}
143
- \r `),Gc=e=>!e||Wc.has(e),Kc=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer=``,this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!=`string`)throw TypeError(`source is not a string`);this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??`stream`;for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===` `||t===` `;)t=this.buffer[++e];return!t||t===`#`||t===`
141
+ `:return`newline`;case`-`:return`seq-item-ind`;case`?`:return`explicit-key-ind`;case`:`:return`map-value-ind`;case`{`:return`flow-map-start`;case`}`:return`flow-map-end`;case`[`:return`flow-seq-start`;case`]`:return`flow-seq-end`;case`,`:return`comma`}switch(e[0]){case` `:case` `:return`space`;case`#`:return`comment`;case`%`:return`directive-line`;case`*`:return`alias`;case`&`:return`anchor`;case`!`:return`tag`;case`'`:return`single-quoted-scalar`;case`"`:return`double-quoted-scalar`;case`|`:case`>`:return`block-scalar-header`}return null}var Ic,Lc,Rc=I((()=>{Sc(),Ec(),Mc(),Ic=e=>!!e&&`items`in e,Lc=e=>!!e&&(e.type===`scalar`||e.type===`single-quoted-scalar`||e.type===`double-quoted-scalar`||e.type===`block-scalar`)}));function zc(e){switch(e){case void 0:case` `:case`
142
+ `:case`\r`:case` `:return!0;default:return!1}}var Bc,Vc,Hc,Uc,Wc,Gc,Kc=I((()=>{Rc(),Bc=new Set(`0123456789ABCDEFabcdef`),Vc=new Set(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()`),Hc=new Set(`,[]{}`),Uc=new Set(` ,[]{}
143
+ \r `),Wc=e=>!e||Uc.has(e),Gc=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer=``,this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!=`string`)throw TypeError(`source is not a string`);this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let n=this.next??`stream`;for(;n&&(t||this.hasChars(1));)n=yield*this.parseNext(n)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===` `||t===` `;)t=this.buffer[++e];return!t||t===`#`||t===`
144
144
  `||t===`\r`&&this.buffer[e+1]===`
145
145
  `}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let n=0;for(;t===` `;)t=this.buffer[++n+e];if(t===`\r`){let t=this.buffer[n+e+1];if(t===`
146
146
  `||!t&&!this.atEnd)return e+n+1}return t===`
147
- `||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t===`-`||t===`.`){let t=this.buffer.substr(e,3);if((t===`---`||t===`...`)&&Bc(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!=`number`||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
148
- `,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]===`\r`&&--e,this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case`stream`:return yield*this.parseStream();case`line-start`:return yield*this.parseLineStart();case`block-start`:return yield*this.parseBlockStart();case`doc`:return yield*this.parseDocument();case`flow`:return yield*this.parseFlowCollection();case`quoted-scalar`:return yield*this.parseQuotedScalar();case`block-scalar`:return yield*this.parseBlockScalar();case`plain-scalar`:return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext(`stream`);if(e[0]===``&&(yield*this.pushCount(1),e=e.substring(1)),e[0]===`%`){let t=e.length,n=e.indexOf(`#`);for(;n!==-1;){let r=e[n-1];if(r===` `||r===` `){t=n-1;break}n=e.indexOf(`#`,n+1)}for(;;){let n=e[t-1];if(n===` `||n===` `)--t;else break}let r=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-r),this.pushNewline(),`stream`}if(this.atLineEnd()){let t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),`stream`}return yield``,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext(`line-start`);if(e===`-`||e===`.`){if(!this.atEnd&&!this.hasChars(4))return this.setNext(`line-start`);let e=this.peek(3);if((e===`---`||e===`...`)&&Bc(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,e===`---`?`doc`:`stream`}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!Bc(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext(`block-start`);if((e===`-`||e===`?`||e===`:`)&&Bc(t)){let e=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=e,`block-start`}return`doc`}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext(`doc`);let t=yield*this.pushIndicators();switch(e[t]){case`#`:yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case`{`:case`[`:return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,`flow`;case`}`:case`]`:return yield*this.pushCount(1),`doc`;case`*`:return yield*this.pushUntil(Gc),`doc`;case`"`:case`'`:return yield*this.parseQuotedScalar();case`|`:case`>`:return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,n=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=n=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);let r=this.getLine();if(r===null)return this.setNext(`flow`);if((n!==-1&&n<this.indentNext&&r[0]!==`#`||n===0&&(r.startsWith(`---`)||r.startsWith(`...`))&&Bc(r[3]))&&(n!==this.indentNext-1||this.flowLevel!==1||r[0]!==`]`&&r[0]!==`}`))return this.flowLevel=0,yield``,yield*this.parseLineStart();let i=0;for(;r[i]===`,`;)i+=yield*this.pushCount(1),i+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(i+=yield*this.pushIndicators(),r[i]){case void 0:return`flow`;case`#`:return yield*this.pushCount(r.length-i),`flow`;case`{`:case`[`:return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,`flow`;case`}`:case`]`:return yield*this.pushCount(1),this.flowKey=!0,--this.flowLevel,this.flowLevel?`flow`:`doc`;case`*`:return yield*this.pushUntil(Gc),`flow`;case`"`:case`'`:return this.flowKey=!0,yield*this.parseQuotedScalar();case`:`:{let e=this.charAt(1);if(this.flowKey||Bc(e)||e===`,`)return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),`flow`}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),t=this.buffer.indexOf(e,this.pos+1);if(e===`'`)for(;t!==-1&&this.buffer[t+1]===`'`;)t=this.buffer.indexOf(`'`,t+2);else for(;t!==-1;){let e=0;for(;this.buffer[t-1-e]===`\\`;)e+=1;if(e%2==0)break;t=this.buffer.indexOf(`"`,t+1)}let n=this.buffer.substring(0,t),r=n.indexOf(`
147
+ `||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t===`-`||t===`.`){let t=this.buffer.substr(e,3);if((t===`---`||t===`...`)&&zc(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!=`number`||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
148
+ `,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]===`\r`&&--e,this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case`stream`:return yield*this.parseStream();case`line-start`:return yield*this.parseLineStart();case`block-start`:return yield*this.parseBlockStart();case`doc`:return yield*this.parseDocument();case`flow`:return yield*this.parseFlowCollection();case`quoted-scalar`:return yield*this.parseQuotedScalar();case`block-scalar`:return yield*this.parseBlockScalar();case`plain-scalar`:return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext(`stream`);if(e[0]===``&&(yield*this.pushCount(1),e=e.substring(1)),e[0]===`%`){let t=e.length,n=e.indexOf(`#`);for(;n!==-1;){let r=e[n-1];if(r===` `||r===` `){t=n-1;break}n=e.indexOf(`#`,n+1)}for(;;){let n=e[t-1];if(n===` `||n===` `)--t;else break}let r=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-r),this.pushNewline(),`stream`}if(this.atLineEnd()){let t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),`stream`}return yield``,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext(`line-start`);if(e===`-`||e===`.`){if(!this.atEnd&&!this.hasChars(4))return this.setNext(`line-start`);let e=this.peek(3);if((e===`---`||e===`...`)&&zc(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,e===`---`?`doc`:`stream`}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!zc(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext(`block-start`);if((e===`-`||e===`?`||e===`:`)&&zc(t)){let e=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=e,`block-start`}return`doc`}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext(`doc`);let t=yield*this.pushIndicators();switch(e[t]){case`#`:yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case`{`:case`[`:return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,`flow`;case`}`:case`]`:return yield*this.pushCount(1),`doc`;case`*`:return yield*this.pushUntil(Wc),`doc`;case`"`:case`'`:return yield*this.parseQuotedScalar();case`|`:case`>`:return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,n=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=n=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);let r=this.getLine();if(r===null)return this.setNext(`flow`);if((n!==-1&&n<this.indentNext&&r[0]!==`#`||n===0&&(r.startsWith(`---`)||r.startsWith(`...`))&&zc(r[3]))&&(n!==this.indentNext-1||this.flowLevel!==1||r[0]!==`]`&&r[0]!==`}`))return this.flowLevel=0,yield``,yield*this.parseLineStart();let i=0;for(;r[i]===`,`;)i+=yield*this.pushCount(1),i+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(i+=yield*this.pushIndicators(),r[i]){case void 0:return`flow`;case`#`:return yield*this.pushCount(r.length-i),`flow`;case`{`:case`[`:return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,`flow`;case`}`:case`]`:return yield*this.pushCount(1),this.flowKey=!0,--this.flowLevel,this.flowLevel?`flow`:`doc`;case`*`:return yield*this.pushUntil(Wc),`flow`;case`"`:case`'`:return this.flowKey=!0,yield*this.parseQuotedScalar();case`:`:{let e=this.charAt(1);if(this.flowKey||zc(e)||e===`,`)return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),`flow`}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),t=this.buffer.indexOf(e,this.pos+1);if(e===`'`)for(;t!==-1&&this.buffer[t+1]===`'`;)t=this.buffer.indexOf(`'`,t+2);else for(;t!==-1;){let e=0;for(;this.buffer[t-1-e]===`\\`;)e+=1;if(e%2==0)break;t=this.buffer.indexOf(`"`,t+1)}let n=this.buffer.substring(0,t),r=n.indexOf(`
149
149
  `,this.pos);if(r!==-1){for(;r!==-1;){let e=this.continueScalar(r+1);if(e===-1)break;r=n.indexOf(`
150
- `,e)}r!==-1&&(t=r-(n[r-1]===`\r`?2:1))}if(t===-1){if(!this.atEnd)return this.setNext(`quoted-scalar`);t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?`flow`:`doc`}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let t=this.buffer[++e];if(t===`+`)this.blockScalarKeep=!0;else if(t>`0`&&t<=`9`)this.blockScalarIndent=Number(t)-1;else if(t!==`-`)break}return yield*this.pushUntil(e=>Bc(e)||e===`#`)}*parseBlockScalar(){let e=this.pos-1,t=0,n;loop:for(let r=this.pos;n=this.buffer[r];++r)switch(n){case` `:t+=1;break;case`
150
+ `,e)}r!==-1&&(t=r-(n[r-1]===`\r`?2:1))}if(t===-1){if(!this.atEnd)return this.setNext(`quoted-scalar`);t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?`flow`:`doc`}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let t=this.buffer[++e];if(t===`+`)this.blockScalarKeep=!0;else if(t>`0`&&t<=`9`)this.blockScalarIndent=Number(t)-1;else if(t!==`-`)break}return yield*this.pushUntil(e=>zc(e)||e===`#`)}*parseBlockScalar(){let e=this.pos-1,t=0,n;loop:for(let r=this.pos;n=this.buffer[r];++r)switch(n){case` `:t+=1;break;case`
151
151
  `:e=r,t=0;break;case`\r`:{let e=this.buffer[r+1];if(!e&&!this.atEnd)return this.setNext(`block-scalar`);if(e===`
152
152
  `)break}default:break loop}if(!n&&!this.atEnd)return this.setNext(`block-scalar`);if(t>=this.indentNext){this.indentNext=this.blockScalarIndent===-1?t:this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let t=this.continueScalar(e+1);if(t===-1)break;e=this.buffer.indexOf(`
153
153
  `,t)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext(`block-scalar`);e=this.buffer.length}}let r=e+1;for(n=this.buffer[r];n===` `;)n=this.buffer[++r];if(n===` `){for(;n===` `||n===` `||n===`\r`||n===`
154
154
  `;)n=this.buffer[++r];e=r-1}else if(!this.blockScalarKeep)do{let n=e-1,r=this.buffer[n];r===`\r`&&(r=this.buffer[--n]);let i=n;for(;r===` `;)r=this.buffer[--n];if(r===`
155
- `&&n>=this.pos&&n+1+t>i)e=n;else break}while(!0);return yield``,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,t=this.pos-1,n=this.pos-1,r;for(;r=this.buffer[++n];)if(r===`:`){let r=this.buffer[n+1];if(Bc(r)||e&&Uc.has(r))break;t=n}else if(Bc(r)){let i=this.buffer[n+1];if(r===`\r`&&(i===`
155
+ `&&n>=this.pos&&n+1+t>i)e=n;else break}while(!0);return yield``,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,t=this.pos-1,n=this.pos-1,r;for(;r=this.buffer[++n];)if(r===`:`){let r=this.buffer[n+1];if(zc(r)||e&&Hc.has(r))break;t=n}else if(zc(r)){let i=this.buffer[n+1];if(r===`\r`&&(i===`
156
156
  `?(n+=1,r=`
157
- `,i=this.buffer[n+1]):t=n),i===`#`||e&&Uc.has(i))break;if(r===`
158
- `){let e=this.continueScalar(n+1);if(e===-1)break;n=Math.max(n,e-2)}}else{if(e&&Uc.has(r))break;t=n}return!r&&!this.atEnd?this.setNext(`plain-scalar`):(yield``,yield*this.pushToIndex(t+1,!0),e?`flow`:`doc`)}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){let n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(t&&(yield``),0)}*pushIndicators(){let e=0;loop:for(;;){switch(this.charAt(0)){case`!`:e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue loop;case`&`:e+=yield*this.pushUntil(Gc),e+=yield*this.pushSpaces(!0);continue loop;case`-`:case`?`:case`:`:{let t=this.flowLevel>0,n=this.charAt(1);if(Bc(n)||t&&Uc.has(n)){t?this.flowKey&&=!1:this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue loop}}}break loop}return e}*pushTag(){if(this.charAt(1)===`<`){let e=this.pos+2,t=this.buffer[e];for(;!Bc(t)&&t!==`>`;)t=this.buffer[++e];return yield*this.pushToIndex(t===`>`?e+1:e,!1)}{let e=this.pos+1,t=this.buffer[e];for(;t;)if(Hc.has(t))t=this.buffer[++e];else if(t===`%`&&Vc.has(this.buffer[e+1])&&Vc.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
157
+ `,i=this.buffer[n+1]):t=n),i===`#`||e&&Hc.has(i))break;if(r===`
158
+ `){let e=this.continueScalar(n+1);if(e===-1)break;n=Math.max(n,e-2)}}else{if(e&&Hc.has(r))break;t=n}return!r&&!this.atEnd?this.setNext(`plain-scalar`):(yield``,yield*this.pushToIndex(t+1,!0),e?`flow`:`doc`)}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){let n=this.buffer.slice(this.pos,e);return n?(yield n,this.pos+=n.length,n.length):(t&&(yield``),0)}*pushIndicators(){let e=0;loop:for(;;){switch(this.charAt(0)){case`!`:e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue loop;case`&`:e+=yield*this.pushUntil(Wc),e+=yield*this.pushSpaces(!0);continue loop;case`-`:case`?`:case`:`:{let t=this.flowLevel>0,n=this.charAt(1);if(zc(n)||t&&Hc.has(n)){t?this.flowKey&&=!1:this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue loop}}}break loop}return e}*pushTag(){if(this.charAt(1)===`<`){let e=this.pos+2,t=this.buffer[e];for(;!zc(t)&&t!==`>`;)t=this.buffer[++e];return yield*this.pushToIndex(t===`>`?e+1:e,!1)}{let e=this.pos+1,t=this.buffer[e];for(;t;)if(Vc.has(t))t=this.buffer[++e];else if(t===`%`&&Bc.has(this.buffer[e+1])&&Bc.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
159
159
  `?yield*this.pushCount(1):e===`\r`&&this.charAt(1)===`
160
- `?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===` `||e&&n===` `);let r=t-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=t),r}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}}})),Jc,Yc=F((()=>{Jc=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t<n;){let r=t+n>>1;this.lineStarts[r]<e?t=r+1:n=r}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};let r=this.lineStarts[t-1];return{line:t,col:e-r+1}}}}}));function Xc(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function Zc(e){for(let t=0;t<e.length;++t)switch(e[t].type){case`space`:case`comment`:case`newline`:break;default:return t}return-1}function Qc(e){switch(e?.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:case`flow-collection`:return!0;default:return!1}}function $c(e){switch(e.type){case`document`:return e.start;case`block-map`:{let t=e.items[e.items.length-1];return t.sep??t.start}case`block-seq`:return e.items[e.items.length-1].start;default:return[]}}function el(e){if(e.length===0)return[];let t=e.length;loop:for(;--t>=0;)switch(e[t].type){case`doc-start`:case`explicit-key-ind`:case`map-value-ind`:case`seq-item-ind`:case`newline`:break loop}for(;e[++t]?.type===`space`;);return e.splice(t,e.length)}function tl(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let n=0;n<t.length;++n)e.push(t[n])}function nl(e){if(e.start.type===`flow-seq-start`)for(let t of e.items)t.sep&&!t.value&&!Xc(t.start,`explicit-key-ind`)&&!Xc(t.sep,`map-value-ind`)&&(t.key&&(t.value=t.key),delete t.key,Qc(t.value)?t.value.end?tl(t.value.end,t.sep):t.value.end=t.sep:tl(t.start,t.sep),delete t.sep)}var rl,il=F((()=>{zc(),qc(),rl=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source=``,this.type=``,this.lexer=new Kc,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let n of this.lexer.lex(e,t))yield*this.next(n);t||(yield*this.end())}*next(e){if(this.source=e,this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=Ic(e);if(!t){let t=`Not a YAML token: ${e}`;yield*this.pop({type:`error`,offset:this.offset,message:t,source:e}),this.offset+=e.length}else if(t===`scalar`)this.atNewLine=!1,this.atScalar=!0,this.type=`scalar`;else{switch(this.type=t,yield*this.step(),t){case`newline`:this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case`space`:this.atNewLine&&e[0]===` `&&(this.indent+=e.length);break;case`explicit-key-ind`:case`map-value-ind`:case`seq-item-ind`:this.atNewLine&&(this.indent+=e.length);break;case`doc-mode`:case`flow-error-end`:return;default:this.atNewLine=!1}this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type===`doc-end`&&e?.type!==`doc-end`){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:`doc-end`,offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case`document`:return yield*this.document(e);case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return yield*this.scalar(e);case`block-scalar`:return yield*this.blockScalar(e);case`block-map`:return yield*this.blockMap(e);case`block-seq`:return yield*this.blockSequence(e);case`flow-collection`:return yield*this.flowCollection(e);case`doc-end`:return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e??this.stack.pop();if(!t)yield{type:`error`,offset:this.offset,source:``,message:`Tried to pop an empty stack`};else if(this.stack.length===0)yield t;else{let e=this.peek(1);switch(t.type===`block-scalar`?t.indent=`indent`in e?e.indent:0:t.type===`flow-collection`&&e.type===`document`&&(t.indent=0),t.type===`flow-collection`&&nl(t),e.type){case`document`:e.value=t;break;case`block-scalar`:e.props.push(t);break;case`block-map`:{let n=e.items[e.items.length-1];if(n.value){e.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}if(n.sep)n.value=t;else{Object.assign(n,{key:t,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case`block-seq`:{let n=e.items[e.items.length-1];n.value?e.items.push({start:[],value:t}):n.value=t;break}case`flow-collection`:{let n=e.items[e.items.length-1];!n||n.value?e.items.push({start:[],key:t,sep:[]}):n.sep?n.value=t:Object.assign(n,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((e.type===`document`||e.type===`block-map`||e.type===`block-seq`)&&(t.type===`block-map`||t.type===`block-seq`)){let n=t.items[t.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&Zc(n.start)===-1&&(t.indent===0||n.start.every(e=>e.type!==`comment`||e.indent<t.indent))&&(e.type===`document`?e.end=n.start:e.items.push({start:n.start}),t.items.splice(-1,1))}}}*stream(){switch(this.type){case`directive-line`:yield{type:`directive`,offset:this.offset,source:this.source};return;case`byte-order-mark`:case`space`:case`comment`:case`newline`:yield this.sourceToken;return;case`doc-mode`:case`doc-start`:{let e={type:`document`,offset:this.offset,start:[]};this.type===`doc-start`&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:`error`,offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case`doc-start`:Zc(e.start)===-1?e.start.push(this.sourceToken):(yield*this.pop(),yield*this.step());return;case`anchor`:case`tag`:case`space`:case`comment`:case`newline`:e.start.push(this.sourceToken);return}let t=this.startBlockValue(e);t?this.stack.push(t):yield{type:`error`,offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type===`map-value-ind`){let t=el($c(this.peek(2))),n;e.end?(n=e.end,n.push(this.sourceToken),delete e.end):n=[this.sourceToken];let r={type:`block-map`,offset:e.offset,indent:e.indent,items:[{start:t,key:e,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=r}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case`space`:case`comment`:case`newline`:e.props.push(this.sourceToken);return;case`scalar`:if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let e=this.source.indexOf(`
160
+ `?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,n;do n=this.buffer[++t];while(n===` `||e&&n===` `);let r=t-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=t),r}*pushUntil(e){let t=this.pos,n=this.buffer[t];for(;!e(n);)n=this.buffer[++t];return yield*this.pushToIndex(t,!1)}}})),qc,Jc=I((()=>{qc=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,n=this.lineStarts.length;for(;t<n;){let r=t+n>>1;this.lineStarts[r]<e?t=r+1:n=r}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};let r=this.lineStarts[t-1];return{line:t,col:e-r+1}}}}}));function Yc(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function Xc(e){for(let t=0;t<e.length;++t)switch(e[t].type){case`space`:case`comment`:case`newline`:break;default:return t}return-1}function Zc(e){switch(e?.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:case`flow-collection`:return!0;default:return!1}}function Qc(e){switch(e.type){case`document`:return e.start;case`block-map`:{let t=e.items[e.items.length-1];return t.sep??t.start}case`block-seq`:return e.items[e.items.length-1].start;default:return[]}}function $c(e){if(e.length===0)return[];let t=e.length;loop:for(;--t>=0;)switch(e[t].type){case`doc-start`:case`explicit-key-ind`:case`map-value-ind`:case`seq-item-ind`:case`newline`:break loop}for(;e[++t]?.type===`space`;);return e.splice(t,e.length)}function el(e,t){if(t.length<1e5)Array.prototype.push.apply(e,t);else for(let n=0;n<t.length;++n)e.push(t[n])}function tl(e){if(e.start.type===`flow-seq-start`)for(let t of e.items)t.sep&&!t.value&&!Yc(t.start,`explicit-key-ind`)&&!Yc(t.sep,`map-value-ind`)&&(t.key&&(t.value=t.key),delete t.key,Zc(t.value)?t.value.end?el(t.value.end,t.sep):t.value.end=t.sep:el(t.start,t.sep),delete t.sep)}var nl,rl=I((()=>{Rc(),Kc(),nl=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source=``,this.type=``,this.lexer=new Gc,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let n of this.lexer.lex(e,t))yield*this.next(n);t||(yield*this.end())}*next(e){if(this.source=e,this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=Fc(e);if(!t){let t=`Not a YAML token: ${e}`;yield*this.pop({type:`error`,offset:this.offset,message:t,source:e}),this.offset+=e.length}else if(t===`scalar`)this.atNewLine=!1,this.atScalar=!0,this.type=`scalar`;else{switch(this.type=t,yield*this.step(),t){case`newline`:this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case`space`:this.atNewLine&&e[0]===` `&&(this.indent+=e.length);break;case`explicit-key-ind`:case`map-value-ind`:case`seq-item-ind`:this.atNewLine&&(this.indent+=e.length);break;case`doc-mode`:case`flow-error-end`:return;default:this.atNewLine=!1}this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type===`doc-end`&&e?.type!==`doc-end`){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:`doc-end`,offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case`document`:return yield*this.document(e);case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return yield*this.scalar(e);case`block-scalar`:return yield*this.blockScalar(e);case`block-map`:return yield*this.blockMap(e);case`block-seq`:return yield*this.blockSequence(e);case`flow-collection`:return yield*this.flowCollection(e);case`doc-end`:return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e??this.stack.pop();if(!t)yield{type:`error`,offset:this.offset,source:``,message:`Tried to pop an empty stack`};else if(this.stack.length===0)yield t;else{let e=this.peek(1);switch(t.type===`block-scalar`?t.indent=`indent`in e?e.indent:0:t.type===`flow-collection`&&e.type===`document`&&(t.indent=0),t.type===`flow-collection`&&tl(t),e.type){case`document`:e.value=t;break;case`block-scalar`:e.props.push(t);break;case`block-map`:{let n=e.items[e.items.length-1];if(n.value){e.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}if(n.sep)n.value=t;else{Object.assign(n,{key:t,sep:[]}),this.onKeyLine=!n.explicitKey;return}break}case`block-seq`:{let n=e.items[e.items.length-1];n.value?e.items.push({start:[],value:t}):n.value=t;break}case`flow-collection`:{let n=e.items[e.items.length-1];!n||n.value?e.items.push({start:[],key:t,sep:[]}):n.sep?n.value=t:Object.assign(n,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((e.type===`document`||e.type===`block-map`||e.type===`block-seq`)&&(t.type===`block-map`||t.type===`block-seq`)){let n=t.items[t.items.length-1];n&&!n.sep&&!n.value&&n.start.length>0&&Xc(n.start)===-1&&(t.indent===0||n.start.every(e=>e.type!==`comment`||e.indent<t.indent))&&(e.type===`document`?e.end=n.start:e.items.push({start:n.start}),t.items.splice(-1,1))}}}*stream(){switch(this.type){case`directive-line`:yield{type:`directive`,offset:this.offset,source:this.source};return;case`byte-order-mark`:case`space`:case`comment`:case`newline`:yield this.sourceToken;return;case`doc-mode`:case`doc-start`:{let e={type:`document`,offset:this.offset,start:[]};this.type===`doc-start`&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:`error`,offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case`doc-start`:Xc(e.start)===-1?e.start.push(this.sourceToken):(yield*this.pop(),yield*this.step());return;case`anchor`:case`tag`:case`space`:case`comment`:case`newline`:e.start.push(this.sourceToken);return}let t=this.startBlockValue(e);t?this.stack.push(t):yield{type:`error`,offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type===`map-value-ind`){let t=$c(Qc(this.peek(2))),n;e.end?(n=e.end,n.push(this.sourceToken),delete e.end):n=[this.sourceToken];let r={type:`block-map`,offset:e.offset,indent:e.indent,items:[{start:t,key:e,sep:n}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=r}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case`space`:case`comment`:case`newline`:e.props.push(this.sourceToken);return;case`scalar`:if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let e=this.source.indexOf(`
161
161
  `)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
162
- `,e)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(this.onKeyLine=!1,t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){tl(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,r=n&&(t.sep||t.explicitKey)&&this.type!==`seq-item-ind`,i=[];if(r&&t.sep&&!t.value){let n=[];for(let r=0;r<t.sep.length;++r){let i=t.sep[r];switch(i.type){case`newline`:n.push(r);break;case`space`:break;case`comment`:i.indent>e.indent&&(n.length=0);break;default:n.length=0}}n.length>=2&&(i=t.sep.splice(n[1]))}switch(this.type){case`anchor`:case`tag`:r||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`explicit-key-ind`:!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):r||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case`map-value-ind`:if(t.explicitKey){if(!t.sep){if(Xc(t.start,`newline`))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let e=el(t.start);this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:null,sep:[this.sourceToken]}]})}}else if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Xc(t.sep,`map-value-ind`))this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(Qc(t.key)&&!Xc(t.sep,`newline`)){let e=el(t.start),n=t.key,r=t.sep;r.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:n,sep:r}]})}else i.length>0?t.sep=t.sep.concat(i,this.sourceToken):t.sep.push(this.sourceToken)}else t.sep?t.value||r?e.items.push({start:i,key:null,sep:[this.sourceToken]}):Xc(t.sep,`map-value-ind`)?this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);r||t.value?(e.items.push({start:i,key:n,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(n):(Object.assign(t,{key:n,sep:[]}),this.onKeyLine=!0);return}default:{let r=this.startBlockValue(e);if(r){if(r.type===`block-seq`){if(!t.explicitKey&&t.sep&&!Xc(t.sep,`newline`)){yield*this.pop({type:`error`,offset:this.offset,message:`Unexpected block-seq-ind on same line with key`,source:this.source});return}}else n&&e.items.push({start:i});this.stack.push(r);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){tl(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case`anchor`:case`tag`:if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case`seq-item-ind`:if(this.indent!==e.indent)break;t.value||Xc(t.start,`seq-item-ind`)?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let t=this.startBlockValue(e);if(t){this.stack.push(t);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type===`flow-error-end`){let e;do yield*this.pop(),e=this.peek(1);while(e?.type===`flow-collection`)}else if(e.end.length===0){switch(this.type){case`comma`:case`explicit-key-ind`:!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case`map-value-ind`:!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case`space`:case`comment`:case`newline`:case`anchor`:case`tag`:!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:n,sep:[]}):t.sep?this.stack.push(n):Object.assign(t,{key:n,sep:[]});return}case`flow-map-end`:case`flow-seq-end`:e.end.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let t=this.peek(2);if(t.type===`block-map`&&(this.type===`map-value-ind`&&t.indent===e.indent||this.type===`newline`&&!t.items[t.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type===`map-value-ind`&&t.type!==`flow-collection`){let n=el($c(t));nl(e);let r=e.end.splice(1,e.end.length);r.push(this.sourceToken);let i={type:`block-map`,offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let e=this.source.indexOf(`
162
+ `,e)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(this.onKeyLine=!1,t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){el(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let n=!this.onKeyLine&&this.indent===e.indent,r=n&&(t.sep||t.explicitKey)&&this.type!==`seq-item-ind`,i=[];if(r&&t.sep&&!t.value){let n=[];for(let r=0;r<t.sep.length;++r){let i=t.sep[r];switch(i.type){case`newline`:n.push(r);break;case`space`:break;case`comment`:i.indent>e.indent&&(n.length=0);break;default:n.length=0}}n.length>=2&&(i=t.sep.splice(n[1]))}switch(this.type){case`anchor`:case`tag`:r||t.value?(i.push(this.sourceToken),e.items.push({start:i}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`explicit-key-ind`:!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):r||t.value?(i.push(this.sourceToken),e.items.push({start:i,explicitKey:!0})):this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case`map-value-ind`:if(t.explicitKey){if(!t.sep){if(Yc(t.start,`newline`))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let e=$c(t.start);this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:null,sep:[this.sourceToken]}]})}}else if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Yc(t.sep,`map-value-ind`))this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]});else if(Zc(t.key)&&!Yc(t.sep,`newline`)){let e=$c(t.start),n=t.key,r=t.sep;r.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:e,key:n,sep:r}]})}else i.length>0?t.sep=t.sep.concat(i,this.sourceToken):t.sep.push(this.sourceToken)}else t.sep?t.value||r?e.items.push({start:i,key:null,sep:[this.sourceToken]}):Yc(t.sep,`map-value-ind`)?this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);r||t.value?(e.items.push({start:i,key:n,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(n):(Object.assign(t,{key:n,sep:[]}),this.onKeyLine=!0);return}default:{let r=this.startBlockValue(e);if(r){if(r.type===`block-seq`){if(!t.explicitKey&&t.sep&&!Yc(t.sep,`newline`)){yield*this.pop({type:`error`,offset:this.offset,message:`Unexpected block-seq-ind on same line with key`,source:this.source});return}}else n&&e.items.push({start:i});this.stack.push(r);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case`newline`:if(t.value){let n=`end`in t.value?t.value.end:void 0;(Array.isArray(n)?n[n.length-1]:void 0)?.type===`comment`?n?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case`space`:case`comment`:if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let n=e.items[e.items.length-2]?.value?.end;if(Array.isArray(n)){el(n,t.start),n.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case`anchor`:case`tag`:if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case`seq-item-ind`:if(this.indent!==e.indent)break;t.value||Yc(t.start,`seq-item-ind`)?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let t=this.startBlockValue(e);if(t){this.stack.push(t);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type===`flow-error-end`){let e;do yield*this.pop(),e=this.peek(1);while(e?.type===`flow-collection`)}else if(e.end.length===0){switch(this.type){case`comma`:case`explicit-key-ind`:!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case`map-value-ind`:!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case`space`:case`comment`:case`newline`:case`anchor`:case`tag`:!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:{let n=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:n,sep:[]}):t.sep?this.stack.push(n):Object.assign(t,{key:n,sep:[]});return}case`flow-map-end`:case`flow-seq-end`:e.end.push(this.sourceToken);return}let n=this.startBlockValue(e);n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let t=this.peek(2);if(t.type===`block-map`&&(this.type===`map-value-ind`&&t.indent===e.indent||this.type===`newline`&&!t.items[t.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type===`map-value-ind`&&t.type!==`flow-collection`){let n=$c(Qc(t));tl(e);let r=e.end.splice(1,e.end.length);r.push(this.sourceToken);let i={type:`block-map`,offset:e.offset,indent:e.indent,items:[{start:n,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=i}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let e=this.source.indexOf(`
163
163
  `)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
164
- `,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=el($c(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=el($c(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}}}));function al(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new Jc||null,prettyErrors:t}}function ol(e,t={}){let{lineCounter:n,prettyErrors:r}=al(t),i=new rl(n?.addNewLine),a=new hc(t),o=Array.from(a.compose(i.parse(e)));if(r&&n)for(let t of o)t.errors.forEach(_s(e,n)),t.warnings.forEach(_s(e,n));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function sl(e,t={}){let{lineCounter:n,prettyErrors:r}=al(t),i=new rl(n?.addNewLine),a=new hc(t),o=null;for(let t of a.compose(i.parse(e),!0,e.length))if(!o)o=t;else if(o.options.logLevel!==`silent`){o.errors.push(new hs(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return r&&n&&(o.errors.forEach(_s(e,n)),o.warnings.forEach(_s(e,n))),o}function cl(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let i=sl(e,n);if(!i)return null;if(i.warnings.forEach(e=>ga(i.options.logLevel,e)),i.errors.length>0){if(i.options.logLevel!==`silent`)throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:r},n))}function ll(e,t,n){let r=null;if(typeof t==`function`||Array.isArray(t)?r=t:n===void 0&&t&&(n=t),typeof n==`string`&&(n=n.length),typeof n==`number`){let e=Math.round(n);n=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=n??t??{};if(!e)return}return Zr(e)&&!r?e.toString(n):new fs(e,r,n).toString(n)}var ul=F((()=>{gc(),ps(),vs(),_a(),L(),Yc(),il()})),dl=Qe({Alias:()=>Ai,CST:()=>Pc,Composer:()=>hc,Document:()=>fs,Lexer:()=>Kc,LineCounter:()=>Jc,Pair:()=>ka,Parser:()=>rl,Scalar:()=>R,Schema:()=>ss,YAMLError:()=>ms,YAMLMap:()=>La,YAMLParseError:()=>hs,YAMLSeq:()=>Ha,YAMLWarning:()=>gs,isAlias:()=>Xr,isCollection:()=>Vr,isDocument:()=>Zr,isMap:()=>Qr,isNode:()=>Hr,isPair:()=>$r,isScalar:()=>ei,isSeq:()=>ti,parse:()=>cl,parseAllDocuments:()=>ol,parseDocument:()=>sl,stringify:()=>ll,visit:()=>ri,visitAsync:()=>ai}),fl=F((()=>{gc(),ps(),cs(),vs(),ji(),L(),Aa(),Ni(),Ra(),Ua(),zc(),qc(),Yc(),il(),ul(),pi()})),pl=Qe({Alias:()=>Ai,CST:()=>Pc,Composer:()=>hc,Document:()=>fs,Lexer:()=>Kc,LineCounter:()=>Jc,Pair:()=>ka,Parser:()=>rl,Scalar:()=>R,Schema:()=>ss,YAMLError:()=>ms,YAMLMap:()=>La,YAMLParseError:()=>hs,YAMLSeq:()=>Ha,YAMLWarning:()=>gs,default:()=>ml,isAlias:()=>Xr,isCollection:()=>Vr,isDocument:()=>Zr,isMap:()=>Qr,isNode:()=>Hr,isPair:()=>$r,isScalar:()=>ei,isSeq:()=>ti,parse:()=>cl,parseAllDocuments:()=>ol,parseDocument:()=>sl,stringify:()=>ll,visit:()=>ri,visitAsync:()=>ai}),ml,hl=F((()=>{fl(),fl(),ml=dl}));async function gl(){return vl??=await Promise.resolve().then(()=>(hl(),pl)),vl}function _l(){return vl??=s(import.meta.url)(`yaml`),vl}var vl,yl=F((()=>{}));function bl(e,t=`toon`){if(e==null)return``;if(t===`json`){if(typeof e==`string`){let t=e.trim();if(t.startsWith(`{`)||t.startsWith(`[`))try{return JSON.stringify(JSON.parse(e),null,2)}catch{}}return Rr(e,2)}return t===`yaml`?_l().stringify(e):t===`md`?Dl(e):t===`jsonl`?Array.isArray(e)?e.map(e=>Rr(e)).join(`
165
- `):Rr(e):xl(e)?String(e):kr(e)}function xl(e){return typeof e!=`object`||!e}function Sl(e){return Object.values(e).every(xl)}function Cl(e){return Array.isArray(e)&&e.length>0&&e.every(e=>typeof e==`object`&&!!e&&!Array.isArray(e))}function wl(e,t){let n=e.map((e,n)=>Math.max(e.length,...t.map(e=>(e[n]??``).length))),r=(e,t)=>e.padEnd(n[t]);return`${`| ${e.map(r).join(` | `)} |`}\n${`|${n.map(e=>`-`.repeat(e+2)).join(`|`)}|`}\n${t.map(t=>`| ${e.map((e,n)=>r(t[n]??``,n)).join(` | `)} |`).join(`
166
- `)}`}function Tl(e){return wl([`Key`,`Value`],Object.entries(e).map(([e,t])=>[e,String(t)]))}function El(e){let t=[...new Set(e.flatMap(Object.keys))];return wl(t,e.map(e=>t.map(t=>String(e[t]??``))))}function Dl(e,t=[]){if(xl(e))return t.length===0?String(e):`## ${t.join(`.`)}\n\n${String(e)}`;if(Array.isArray(e)){if(Cl(e)){let n=El(e);return t.length===0?n:`## ${t.join(`.`)}\n\n${n}`}return Dl(String(e),t)}let n=e,r=Object.entries(n);return t.length===0&&Sl(n)?Tl(n):t.length>0||r.length>1||r.some(([,e])=>!xl(e))?r.map(([e,n])=>{let r=[...t,e];if(xl(n))return`## ${r.join(`.`)}\n\n${String(n)}`;if(Cl(n))return`## ${r.join(`.`)}\n\n${El(n)}`;if(typeof n==`object`&&n&&!Array.isArray(n)){let e=n;return Sl(e)?`## ${r.join(`.`)}\n\n${Tl(e)}`:Dl(e,r)}return`## ${r.join(`.`)}\n\n${String(n)}`}).join(`
164
+ `,e)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case`alias`:case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return this.flowScalar(this.type);case`block-scalar-header`:return{type:`block-scalar`,offset:this.offset,indent:this.indent,props:[this.sourceToken],source:``};case`flow-map-start`:case`flow-seq-start`:return{type:`flow-collection`,offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case`seq-item-ind`:return{type:`block-seq`,offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case`explicit-key-ind`:{this.onKeyLine=!0;let t=$c(Qc(e));return t.push(this.sourceToken),{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,explicitKey:!0}]}}case`map-value-ind`:{this.onKeyLine=!0;let t=$c(Qc(e));return{type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:t,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!==`comment`||this.indent<=t?!1:e.every(e=>e.type===`newline`||e.type===`space`)}*documentEnd(e){this.type!==`doc-mode`&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case`comma`:case`doc-start`:case`doc-end`:case`flow-seq-end`:case`flow-map-end`:case`map-value-ind`:yield*this.pop(),yield*this.step();break;case`newline`:this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type===`newline`&&(yield*this.pop())}}}}));function il(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new qc||null,prettyErrors:t}}function al(e,t={}){let{lineCounter:n,prettyErrors:r}=il(t),i=new nl(n?.addNewLine),a=new mc(t),o=Array.from(a.compose(i.parse(e)));if(r&&n)for(let t of o)t.errors.forEach(gs(e,n)),t.warnings.forEach(gs(e,n));return o.length>0?o:Object.assign([],{empty:!0},a.streamInfo())}function ol(e,t={}){let{lineCounter:n,prettyErrors:r}=il(t),i=new nl(n?.addNewLine),a=new mc(t),o=null;for(let t of a.compose(i.parse(e),!0,e.length))if(!o)o=t;else if(o.options.logLevel!==`silent`){o.errors.push(new ms(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return r&&n&&(o.errors.forEach(gs(e,n)),o.warnings.forEach(gs(e,n))),o}function sl(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let i=ol(e,n);if(!i)return null;if(i.warnings.forEach(e=>ha(i.options.logLevel,e)),i.errors.length>0){if(i.options.logLevel!==`silent`)throw i.errors[0];i.errors=[]}return i.toJS(Object.assign({reviver:r},n))}function cl(e,t,n){let r=null;if(typeof t==`function`||Array.isArray(t)?r=t:n===void 0&&t&&(n=t),typeof n==`string`&&(n=n.length),typeof n==`number`){let e=Math.round(n);n=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=n??t??{};if(!e)return}return Xr(e)&&!r?e.toString(n):new ds(e,r,n).toString(n)}var ll=I((()=>{hc(),fs(),_s(),ga(),R(),Jc(),rl()})),ul=Ze({Alias:()=>ki,CST:()=>Nc,Composer:()=>mc,Document:()=>ds,Lexer:()=>Gc,LineCounter:()=>qc,Pair:()=>Oa,Parser:()=>nl,Scalar:()=>z,Schema:()=>os,YAMLError:()=>ps,YAMLMap:()=>Ia,YAMLParseError:()=>ms,YAMLSeq:()=>Va,YAMLWarning:()=>hs,isAlias:()=>Yr,isCollection:()=>Br,isDocument:()=>Xr,isMap:()=>Zr,isNode:()=>Vr,isPair:()=>Qr,isScalar:()=>$r,isSeq:()=>ei,parse:()=>sl,parseAllDocuments:()=>al,parseDocument:()=>ol,stringify:()=>cl,visit:()=>ni,visitAsync:()=>ii}),dl=I((()=>{hc(),fs(),ss(),_s(),Ai(),R(),ka(),Mi(),La(),Ha(),Rc(),Kc(),Jc(),rl(),ll(),fi()})),fl=Ze({Alias:()=>ki,CST:()=>Nc,Composer:()=>mc,Document:()=>ds,Lexer:()=>Gc,LineCounter:()=>qc,Pair:()=>Oa,Parser:()=>nl,Scalar:()=>z,Schema:()=>os,YAMLError:()=>ps,YAMLMap:()=>Ia,YAMLParseError:()=>ms,YAMLSeq:()=>Va,YAMLWarning:()=>hs,default:()=>pl,isAlias:()=>Yr,isCollection:()=>Br,isDocument:()=>Xr,isMap:()=>Zr,isNode:()=>Vr,isPair:()=>Qr,isScalar:()=>$r,isSeq:()=>ei,parse:()=>sl,parseAllDocuments:()=>al,parseDocument:()=>ol,stringify:()=>cl,visit:()=>ni,visitAsync:()=>ii}),pl,ml=I((()=>{dl(),dl(),pl=ul}));async function hl(){return _l??=await Promise.resolve().then(()=>(ml(),fl)),_l}function gl(){return _l??=s(import.meta.url)(`yaml`),_l}var _l,vl=I((()=>{}));function yl(e,t=`toon`){if(e==null)return``;if(t===`json`){if(typeof e==`string`){let t=e.trim();if(t.startsWith(`{`)||t.startsWith(`[`))try{return JSON.stringify(JSON.parse(e),null,2)}catch{}}return Lr(e,2)}return t===`yaml`?gl().stringify(e):t===`md`?El(e):t===`jsonl`?Array.isArray(e)?e.map(e=>Lr(e)).join(`
165
+ `):Lr(e):bl(e)?String(e):Or(e)}function bl(e){return typeof e!=`object`||!e}function xl(e){return Object.values(e).every(bl)}function Sl(e){return Array.isArray(e)&&e.length>0&&e.every(e=>typeof e==`object`&&!!e&&!Array.isArray(e))}function Cl(e,t){let n=e.map((e,n)=>Math.max(e.length,...t.map(e=>(e[n]??``).length))),r=(e,t)=>e.padEnd(n[t]);return`${`| ${e.map(r).join(` | `)} |`}\n${`|${n.map(e=>`-`.repeat(e+2)).join(`|`)}|`}\n${t.map(t=>`| ${e.map((e,n)=>r(t[n]??``,n)).join(` | `)} |`).join(`
166
+ `)}`}function wl(e){return Cl([`Key`,`Value`],Object.entries(e).map(([e,t])=>[e,String(t)]))}function Tl(e){let t=[...new Set(e.flatMap(Object.keys))];return Cl(t,e.map(e=>t.map(t=>String(e[t]??``))))}function El(e,t=[]){if(bl(e))return t.length===0?String(e):`## ${t.join(`.`)}\n\n${String(e)}`;if(Array.isArray(e)){if(Sl(e)){let n=Tl(e);return t.length===0?n:`## ${t.join(`.`)}\n\n${n}`}return El(String(e),t)}let n=e,r=Object.entries(n);return t.length===0&&xl(n)?wl(n):t.length>0||r.length>1||r.some(([,e])=>!bl(e))?r.map(([e,n])=>{let r=[...t,e];if(bl(n))return`## ${r.join(`.`)}\n\n${String(n)}`;if(Sl(n))return`## ${r.join(`.`)}\n\n${Tl(n)}`;if(typeof n==`object`&&n&&!Array.isArray(n)){let e=n;return xl(e)?`## ${r.join(`.`)}\n\n${wl(e)}`:El(e,r)}return`## ${r.join(`.`)}\n\n${String(n)}`}).join(`
167
167
 
168
- `):Tl(n)}var Ol=F((()=>{Lr(),Br(),yl()}));function kl(e,t={}){let{args:n,options:r,alias:i,defaults:a}=t,o=Al(r,i),s=[],c={},l=0;for(;l<e.length;){let t=e[l];if(t.startsWith(`--no-`)&&t.length>5){let e=jl(t.slice(5),o);if(!e)throw new En({message:`Unknown flag: ${t}`});c[e]=!1,l++}else if(t.startsWith(`--`)){let n=t.indexOf(`=`);if(n!==-1){let e=t.slice(2,n),i=jl(e,o);if(!i)throw new En({message:`Unknown flag: --${e}`});Ll(c,i,t.slice(n+1),r),l++}else{let n=jl(t.slice(2),o);if(!n)throw new En({message:`Unknown flag: ${t}`});if(Fl(n,r))c[n]=(c[n]??0)+1,l++;else if(Pl(n,r))c[n]=!0,l++;else{let i=e[l+1];if(i===void 0)throw new En({message:`Missing value for flag: ${t}`});Ll(c,n,i,r),l+=2}}}else if(t.startsWith(`-`)&&!t.startsWith(`--`)&&t.length>=2){let n=t.slice(1);for(let t=0;t<n.length;t++){let i=n[t],a=o.aliasToName.get(i);if(!a)throw new En({message:`Unknown flag: -${i}`});if(t!==n.length-1){if(Fl(a,r))c[a]=(c[a]??0)+1;else if(Pl(a,r))c[a]=!0;else throw new En({message:`Non-boolean flag -${i} must be last in a stacked alias`})}else if(Fl(a,r))c[a]=(c[a]??0)+1;else if(Pl(a,r))c[a]=!0;else{let t=e[l+1];if(t===void 0)throw new En({message:`Missing value for flag: -${i}`});Ll(c,a,t,r),l++}}l++}else s.push(t),l++}let u={};if(n){let e=Object.keys(n.shape);for(let t=0;t<e.length;t++){let r=e[t];if(Il(r,n)){if(t!==e.length-1)throw Error(`Variadic arg "${r}" must be the last key in the args schema`);let n=s.slice(t);n.length>0&&(u[r]=n)}else s[t]!==void 0&&(u[r]=s[t])}}let d=n?Rl(n,u):{},f=Ml(a,r,o);if(r)for(let[e,t]of Object.entries(c))c[e]=Hl(t,e,r);let p={...f,...c};return{args:d,options:r?Rl(r,p):{}}}function Al(e,t){let n=new Map;if(t)for(let[e,r]of Object.entries(t))n.set(r,e);let r=new Set(e?Object.keys(e.shape):[]),i=new Map;for(let e of r){let t=an(e);t!==e&&i.set(t,e)}return{aliasToName:n,kebabToCamel:i,knownOptions:r}}function jl(e,t){let n=t.kebabToCamel.get(e)??e;return t.knownOptions.has(n)?n:void 0}function Ml(e,t,n){if(e===void 0)return{};if(!rn(e))throw new En({message:`Invalid config section: expected an object of option defaults`});if(!t){let[t]=Object.keys(e);if(t)throw new En({message:`Unknown config option: ${t}`});return{}}let r={};for(let[t,i]of Object.entries(e)){let e=jl(t,n);if(!e)throw new En({message:`Unknown config option: ${t}`});r[e]=i}return r}function Nl(e){let t=e;for(;t.def?.innerType;)t=t.def.innerType;return t}function Pl(e,t){if(!t)return!1;let n=t.shape[e];return n?Nl(n).constructor.name===`ZodBoolean`:!1}function Fl(e,t){if(!t)return!1;let n=t.shape[e];return n?typeof n.meta==`function`&&n.meta()?.count===!0:!1}function Il(e,t){if(!t)return!1;let n=t.shape[e];return n?Nl(n).constructor.name===`ZodArray`:!1}function Ll(e,t,n,r){if(Il(t,r)){let r=e[t];Array.isArray(r)?r.push(n):e[t]=[n]}else e[t]=n}function Rl(e,t){try{return e.parse(t)}catch(e){let n=e?.issues??e?.error?.issues??[],r=n.map(e=>({code:e.code,missing:!zl(t,e.path??[]),path:(e.path??[]).join(`.`),expected:e.expected??``,received:e.received??``,message:e.message??``}));throw new Tn({message:n.map(e=>e.message).join(`; `)||`Validation failed`,fieldErrors:r,cause:e instanceof Error?e:void 0})}}function zl(e,t){if(t.length===0)return!0;let n=e;for(let e of t){if(!rn(n)&&!Array.isArray(n)||!(e in n))return!1;n=n[e]}return!0}function Bl(e,t=Wl()){let n={};for(let[r,i]of Object.entries(e.shape)){let e=t[r];e!==void 0&&(n[r]=Vl(e,i))}return Rl(e,n)}function Vl(e,t){let n=Nl(t).constructor.name;return n===`ZodNumber`?Number(e):n===`ZodBoolean`?e===`true`||e===`1`:e}function Hl(e,t,n){let r=n.shape[t];if(!r)return e;let i=Nl(r).constructor.name;return i===`ZodNumber`&&typeof e==`string`?Number(e):i===`ZodBoolean`&&typeof e==`string`?e===`true`:e}function Ul(e,t,n,r={}){let i=Al(t,n),a=[],o={},s=0;for(;s<e.length;){let n=e[s];if(n===`--`){for(let t=s;t<e.length;t++)a.push(e[t]);break}if(n.startsWith(`--no-`)&&n.length>5){let e=jl(n.slice(5),i);e?o[e]=!1:a.push(n),s++}else if(n.startsWith(`--`)){let r=n.indexOf(`=`);if(r!==-1){let e=jl(n.slice(2,r),i);e?Ll(o,e,n.slice(r+1),t):a.push(n),s++}else{let r=jl(n.slice(2),i);if(!r)a.push(n),s++;else if(Fl(r,t))o[r]=(o[r]??0)+1,s++;else if(Pl(r,t))o[r]=!0,s++;else{let i=e[s+1];if(i===void 0)throw new En({message:`Missing value for flag: ${n}`});Ll(o,r,i,t),s+=2}}}else if(n.startsWith(`-`)&&!n.startsWith(`--`)&&n.length>=2){let r=n.slice(1),c=!0;for(let e=0;e<r.length;e++)if(!i.aliasToName.has(r[e])){c=!1;break}if(!c)a.push(n),s++;else{for(let n=0;n<r.length;n++){let a=r[n],c=i.aliasToName.get(a);if(n!==r.length-1){if(Fl(c,t))o[c]=(o[c]??0)+1;else if(Pl(c,t))o[c]=!0;else throw new En({message:`Non-boolean flag -${a} must be last in a stacked alias`})}else if(Fl(c,t))o[c]=(o[c]??0)+1;else if(Pl(c,t))o[c]=!0;else{let n=e[s+1];if(n===void 0)throw new En({message:`Missing value for flag: -${a}`});Ll(o,c,n,t),s++}}s++}}else a.push(n),s++}if(r.validate===!1)return{parsed:o,rest:a};for(let[e,n]of Object.entries(o))o[e]=Hl(n,e,t);return{parsed:Rl(t,o),rest:a}}function Wl(){if(typeof globalThis<`u`){let e=globalThis;if(e.process?.env)return e.process.env;if(e.Deno?.env)return new Proxy({},{get:(t,n)=>e.Deno.env.get(n)})}return{}}var Gl=F((()=>{Dn(),cn()}));async function Kl(e,t){let{argv:n,inputOptions:r,agent:i,format:a,formatExplicit:o,name:s,path:c,version:l,envSource:u=process.env,env:d,globals:f={},vars:p,middlewares:m=[],request:h}=t,g=t.displayName??s,_=t.parseMode??`argv`,v=p?p.parse({}):{},y,b,x,S,C=new Promise(e=>{S=e}),w=async()=>{let c,d;if(_===`argv`){let r=kl(n,{alias:e.alias,args:e.args,defaults:t.defaults,options:e.options});c=r.args,d=r.options}else if(_===`split`)c=kl(n,{args:e.args}).args,d=e.options?Rl(e.options,r):{};else{let t=ql(r,e);c=e.args?Rl(e.args,t.args):{},d=e.options?Rl(e.options,t.options):{}}let p=e.env?Bl(e.env,u):{},C=e.run({agent:i,args:c,displayName:g,env:p,error:e=>({[$l]:`error`,...e}),format:a,formatExplicit:o,globals:f,name:s,ok:(e,t={})=>({[$l]:`ok`,data:e,cta:t.cta}),options:d,request:h,var:v,version:l});if(Yl(C)){if(m.length>0){b=new Promise(e=>{x=e});async function*e(){try{return yield*C}finally{x()}}y={stream:e()},S(),await b}else y={stream:C};return}let w=await C;if(Jl(w)){if(w[$l]===`ok`){let e=w;y={ok:!0,data:e.data,...e.cta?{cta:e.cta}:void 0}}else{let e=w;y={ok:!1,error:{code:e.code,message:e.message,...e.retryable===void 0?void 0:{retryable:e.retryable}},...e.cta?{cta:e.cta}:void 0,...e.exitCode===void 0?void 0:{exitCode:e.exitCode}}}return}y={ok:!0,data:w}};try{let e=d?Bl(d,u):{};if(m.length>0){let t={agent:i,command:c,displayName:g,env:e,error:e=>{y={ok:!1,error:{code:e.code,message:e.message,...e.retryable===void 0?void 0:{retryable:e.retryable}},...e.cta?{cta:e.cta}:void 0,...e.exitCode===void 0?void 0:{exitCode:e.exitCode}}},format:a,formatExplicit:o,globals:f,name:s,request:h,set(e,t){v[e]=t},var:v,version:l},n=m.reduceRight((e,n)=>async()=>{await n(t,e)},w)();if(await Promise.race([n,C]),b)return y;await n}else await w()}catch(e){return e instanceof Tn?{ok:!1,error:{code:`VALIDATION_ERROR`,message:e.message,fieldErrors:e.fieldErrors}}:{ok:!1,error:{code:e instanceof I?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e),...e instanceof I?{retryable:e.retryable}:void 0},...e instanceof I&&e.exitCode!==void 0?{exitCode:e.exitCode}:void 0}}return y??{ok:!0,data:void 0}}function ql(e,t){let n=new Set(t.args?Object.keys(t.args.shape):[]),r={},i={};for(let[t,a]of Object.entries(e))n.has(t)?r[t]=a:i[t]=a;return{args:r,options:i}}function Jl(e){return typeof e==`object`&&!!e&&$l in e}function Yl(e){return typeof e==`object`&&!!e&&Symbol.asyncIterator in e&&typeof e.next==`function`}function Xl(e){return e}function Zl(e){return tu.find(t=>t.name===e||t.aliases?.includes(e))}function Ql(e,t){return e.subcommands?.find(e=>e.name===t||e.aliases?.includes(t))}var $l,eu,tu,nu=F((()=>{Dn(),Gl(),$l=Symbol.for(`incur.sentinel`),eu=[`bash`,`fish`,`nushell`,`zsh`],tu=[{name:`completions`,description:`Generate shell completion script`,args:f.object({shell:f.enum(eu).describe(`Shell to generate completions for`)}),hint(e){let t=[[`bash`,`eval "$(${e} completions bash)"`,`# add to ~/.bashrc`],[`fish`,`${e} completions fish | source`,`# add to ~/.config/fish/config.fish`],[`nushell`,`see \`${e} completions nushell\``,`# add to config.nu`],[`zsh`,`eval "$(${e} completions zsh)"`,`# add to ~/.zshrc`]],n=Math.max(...t.map(e=>e[0].length)),r=Math.max(...t.map(e=>e[1].length));return`Setup:
168
+ `):wl(n)}var Dl=I((()=>{Ir(),zr(),vl()}));function Ol(e,t={}){let{args:n,options:r,alias:i,defaults:a}=t,o=kl(r,i),s=[],c={},l=0;for(;l<e.length;){let t=e[l];if(t.startsWith(`--no-`)&&t.length>5){let e=Al(t.slice(5),o);if(!e)throw new Tn({message:`Unknown flag: ${t}`});c[e]=!1,l++}else if(t.startsWith(`--`)){let n=t.indexOf(`=`);if(n!==-1){let e=t.slice(2,n),i=Al(e,o);if(!i)throw new Tn({message:`Unknown flag: --${e}`});Il(c,i,t.slice(n+1),r),l++}else{let n=Al(t.slice(2),o);if(!n)throw new Tn({message:`Unknown flag: ${t}`});if(Pl(n,r))c[n]=(c[n]??0)+1,l++;else if(Nl(n,r))c[n]=!0,l++;else{let i=e[l+1];if(i===void 0)throw new Tn({message:`Missing value for flag: ${t}`});Il(c,n,i,r),l+=2}}}else if(t.startsWith(`-`)&&!t.startsWith(`--`)&&t.length>=2){let n=t.slice(1);for(let t=0;t<n.length;t++){let i=n[t],a=o.aliasToName.get(i);if(!a)throw new Tn({message:`Unknown flag: -${i}`});if(t!==n.length-1){if(Pl(a,r))c[a]=(c[a]??0)+1;else if(Nl(a,r))c[a]=!0;else throw new Tn({message:`Non-boolean flag -${i} must be last in a stacked alias`})}else if(Pl(a,r))c[a]=(c[a]??0)+1;else if(Nl(a,r))c[a]=!0;else{let t=e[l+1];if(t===void 0)throw new Tn({message:`Missing value for flag: -${i}`});Il(c,a,t,r),l++}}l++}else s.push(t),l++}let u={};if(n){let e=Object.keys(n.shape);for(let t=0;t<e.length;t++){let r=e[t];if(Fl(r,n)){if(t!==e.length-1)throw Error(`Variadic arg "${r}" must be the last key in the args schema`);let n=s.slice(t);n.length>0&&(u[r]=n)}else s[t]!==void 0&&(u[r]=s[t])}}let d=n?Ll(n,u):{},f=jl(a,r,o);if(r)for(let[e,t]of Object.entries(c))c[e]=Vl(t,e,r);let p={...f,...c};return{args:d,options:r?Ll(r,p):{}}}function kl(e,t){let n=new Map;if(t)for(let[e,r]of Object.entries(t))n.set(r,e);let r=new Set(e?Object.keys(e.shape):[]),i=new Map;for(let e of r){let t=rn(e);t!==e&&i.set(t,e)}return{aliasToName:n,kebabToCamel:i,knownOptions:r}}function Al(e,t){let n=t.kebabToCamel.get(e)??e;return t.knownOptions.has(n)?n:void 0}function jl(e,t,n){if(e===void 0)return{};if(!nn(e))throw new Tn({message:`Invalid config section: expected an object of option defaults`});if(!t){let[t]=Object.keys(e);if(t)throw new Tn({message:`Unknown config option: ${t}`});return{}}let r={};for(let[t,i]of Object.entries(e)){let e=Al(t,n);if(!e)throw new Tn({message:`Unknown config option: ${t}`});r[e]=i}return r}function Ml(e){let t=e;for(;t.def?.innerType;)t=t.def.innerType;return t}function Nl(e,t){if(!t)return!1;let n=t.shape[e];return n?Ml(n).constructor.name===`ZodBoolean`:!1}function Pl(e,t){if(!t)return!1;let n=t.shape[e];return n?typeof n.meta==`function`&&n.meta()?.count===!0:!1}function Fl(e,t){if(!t)return!1;let n=t.shape[e];return n?Ml(n).constructor.name===`ZodArray`:!1}function Il(e,t,n,r){if(Fl(t,r)){let r=e[t];Array.isArray(r)?r.push(n):e[t]=[n]}else e[t]=n}function Ll(e,t){try{return e.parse(t)}catch(e){let n=e?.issues??e?.error?.issues??[],r=n.map(e=>({code:e.code,missing:!Rl(t,e.path??[]),path:(e.path??[]).join(`.`),expected:e.expected??``,received:e.received??``,message:e.message??``}));throw new wn({message:n.map(e=>e.message).join(`; `)||`Validation failed`,fieldErrors:r,cause:e instanceof Error?e:void 0})}}function Rl(e,t){if(t.length===0)return!0;let n=e;for(let e of t){if(!nn(n)&&!Array.isArray(n)||!(e in n))return!1;n=n[e]}return!0}function zl(e,t=Ul()){let n={};for(let[r,i]of Object.entries(e.shape)){let e=t[r];e!==void 0&&(n[r]=Bl(e,i))}return Ll(e,n)}function Bl(e,t){let n=Ml(t).constructor.name;return n===`ZodNumber`?Number(e):n===`ZodBoolean`?e===`true`||e===`1`:e}function Vl(e,t,n){let r=n.shape[t];if(!r)return e;let i=Ml(r).constructor.name;return i===`ZodNumber`&&typeof e==`string`?Number(e):i===`ZodBoolean`&&typeof e==`string`?e===`true`:e}function Hl(e,t,n,r={}){let i=kl(t,n),a=[],o={},s=0;for(;s<e.length;){let n=e[s];if(n===`--`){for(let t=s;t<e.length;t++)a.push(e[t]);break}if(n.startsWith(`--no-`)&&n.length>5){let e=Al(n.slice(5),i);e?o[e]=!1:a.push(n),s++}else if(n.startsWith(`--`)){let r=n.indexOf(`=`);if(r!==-1){let e=Al(n.slice(2,r),i);e?Il(o,e,n.slice(r+1),t):a.push(n),s++}else{let r=Al(n.slice(2),i);if(!r)a.push(n),s++;else if(Pl(r,t))o[r]=(o[r]??0)+1,s++;else if(Nl(r,t))o[r]=!0,s++;else{let i=e[s+1];if(i===void 0)throw new Tn({message:`Missing value for flag: ${n}`});Il(o,r,i,t),s+=2}}}else if(n.startsWith(`-`)&&!n.startsWith(`--`)&&n.length>=2){let r=n.slice(1),c=!0;for(let e=0;e<r.length;e++)if(!i.aliasToName.has(r[e])){c=!1;break}if(!c)a.push(n),s++;else{for(let n=0;n<r.length;n++){let a=r[n],c=i.aliasToName.get(a);if(n!==r.length-1){if(Pl(c,t))o[c]=(o[c]??0)+1;else if(Nl(c,t))o[c]=!0;else throw new Tn({message:`Non-boolean flag -${a} must be last in a stacked alias`})}else if(Pl(c,t))o[c]=(o[c]??0)+1;else if(Nl(c,t))o[c]=!0;else{let n=e[s+1];if(n===void 0)throw new Tn({message:`Missing value for flag: -${a}`});Il(o,c,n,t),s++}}s++}}else a.push(n),s++}if(r.validate===!1)return{parsed:o,rest:a};for(let[e,n]of Object.entries(o))o[e]=Vl(n,e,t);return{parsed:Ll(t,o),rest:a}}function Ul(){if(typeof globalThis<`u`){let e=globalThis;if(e.process?.env)return e.process.env;if(e.Deno?.env)return new Proxy({},{get:(t,n)=>e.Deno.env.get(n)})}return{}}var Wl=I((()=>{En(),sn()}));async function Gl(e,t){let{argv:n,inputOptions:r,agent:i,format:a,formatExplicit:o,name:s,path:c,version:l,envSource:u=process.env,env:d,globals:f={},vars:p,middlewares:m=[],request:h}=t,g=t.displayName??s,_=t.parseMode??`argv`,v=p?p.parse({}):{},y,b,x,S,C=new Promise(e=>{S=e}),w=async()=>{let c,d;if(_===`argv`){let r=Ol(n,{alias:e.alias,args:e.args,defaults:t.defaults,options:e.options});c=r.args,d=r.options}else if(_===`split`)c=Ol(n,{args:e.args}).args,d=e.options?Ll(e.options,r):{};else{let t=Kl(r,e);c=e.args?Ll(e.args,t.args):{},d=e.options?Ll(e.options,t.options):{}}let p=e.env?zl(e.env,u):{},C=e.run({agent:i,args:c,displayName:g,env:p,error:e=>({[Ql]:`error`,...e}),format:a,formatExplicit:o,globals:f,name:s,ok:(e,t={})=>({[Ql]:`ok`,data:e,cta:t.cta}),options:d,request:h,var:v,version:l});if(Jl(C)){if(m.length>0){b=new Promise(e=>{x=e});async function*e(){try{return yield*C}finally{x()}}y={stream:e()},S(),await b}else y={stream:C};return}let w=await C;if(ql(w)){if(w[Ql]===`ok`){let e=w;y={ok:!0,data:e.data,...e.cta?{cta:e.cta}:void 0}}else{let e=w;y={ok:!1,error:{code:e.code,message:e.message,...e.retryable===void 0?void 0:{retryable:e.retryable}},...e.cta?{cta:e.cta}:void 0,...e.exitCode===void 0?void 0:{exitCode:e.exitCode}}}return}y={ok:!0,data:w}};try{let e=d?zl(d,u):{};if(m.length>0){let t={agent:i,command:c,displayName:g,env:e,error:e=>{y={ok:!1,error:{code:e.code,message:e.message,...e.retryable===void 0?void 0:{retryable:e.retryable}},...e.cta?{cta:e.cta}:void 0,...e.exitCode===void 0?void 0:{exitCode:e.exitCode}}},format:a,formatExplicit:o,globals:f,name:s,request:h,set(e,t){v[e]=t},var:v,version:l},n=m.reduceRight((e,n)=>async()=>{await n(t,e)},w)();if(await Promise.race([n,C]),b)return y;await n}else await w()}catch(e){return e instanceof wn?{ok:!1,error:{code:`VALIDATION_ERROR`,message:e.message,fieldErrors:e.fieldErrors}}:{ok:!1,error:{code:e instanceof L?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e),...e instanceof L?{retryable:e.retryable}:void 0},...e instanceof L&&e.exitCode!==void 0?{exitCode:e.exitCode}:void 0}}return y??{ok:!0,data:void 0}}function Kl(e,t){let n=new Set(t.args?Object.keys(t.args.shape):[]),r={},i={};for(let[t,a]of Object.entries(e))n.has(t)?r[t]=a:i[t]=a;return{args:r,options:i}}function ql(e){return typeof e==`object`&&!!e&&Ql in e}function Jl(e){return typeof e==`object`&&!!e&&Symbol.asyncIterator in e&&typeof e.next==`function`}function Yl(e){return e}function Xl(e){return eu.find(t=>t.name===e||t.aliases?.includes(e))}function Zl(e,t){return e.subcommands?.find(e=>e.name===t||e.aliases?.includes(t))}var Ql,$l,eu,tu=I((()=>{En(),Wl(),Ql=Symbol.for(`incur.sentinel`),$l=[`bash`,`fish`,`nushell`,`zsh`],eu=[{name:`completions`,description:`Generate shell completion script`,args:f.object({shell:f.enum($l).describe(`Shell to generate completions for`)}),hint(e){let t=[[`bash`,`eval "$(${e} completions bash)"`,`# add to ~/.bashrc`],[`fish`,`${e} completions fish | source`,`# add to ~/.config/fish/config.fish`],[`nushell`,`see \`${e} completions nushell\``,`# add to config.nu`],[`zsh`,`eval "$(${e} completions zsh)"`,`# add to ~/.zshrc`]],n=Math.max(...t.map(e=>e[0].length)),r=Math.max(...t.map(e=>e[1].length));return`Setup:
169
169
  `+t.map(([e,t,i])=>` ${e.padEnd(n)} ${t.padEnd(r)} ${i}`).join(`
170
- `)}},{name:`mcp`,description:`Register as MCP server`,subcommands:[Xl({name:`add`,description:`Register as MCP server`,alias:{command:`c`},options:f.object({agent:f.string().optional().describe(`Target a specific agent (e.g. claude-code, cursor)`),command:f.string().optional().describe(`Override the command agents will run (e.g. "pnpm my-cli --mcp")`),noGlobal:f.boolean().optional().describe(`Install to project instead of globally`)})}),Xl({name:`doctor`,description:`Validate MCP server startup and tool listing`})]},{name:`skills`,aliases:[`skill`],description:`Sync skill files to agents`,subcommands:[Xl({name:`add`,description:`Sync skill files to agents`,options:f.object({depth:f.number().optional().describe(`Grouping depth for skill files (default: 1)`),noGlobal:f.boolean().optional().describe(`Install to project instead of globally`)})}),Xl({name:`list`,aliases:[`ls`],description:`List skills`})]}]}));function ru(e,t={}){let{aliases:n,configFlag:r,description:i,globals:a,version:o,commands:s=[],root:c=!1}=t,l=[],u=o?`${e}@${o}`:e;if(l.push(i?`${u} \u2014 ${i}`:u),l.push(``),l.push(`Usage: ${e} <command>`),n?.length&&l.push(`Aliases: ${n.join(`, `)}`),s.length>0){l.push(``),l.push(`Commands:`);let e=Math.max(...s.map(e=>e.name.length));for(let t of s)if(t.description){let n=` `.repeat(e-t.name.length);l.push(` ${t.name}${n} ${t.description}`)}else l.push(` ${t.name}`)}return l.push(...mu(c,r,a)),l.join(`
171
- `)}function iu(e,t={}){let{alias:n,aliases:r,configFlag:i,description:a,globals:o,version:s,args:c,env:l,envSource:u,hint:d,root:f=!1,options:p,examples:m}=t,h=[],g=s?`${e}@${s}`:e;h.push(a?`${g} \u2014 ${a}`:g),h.push(``);let{usage:_}=t;if(_&&_.length>0){let t=_.map(t=>{let n=[];if(t.prefix&&n.push(t.prefix),n.push(e),t.args)for(let e of Object.keys(t.args))n.push(`<${e}>`);if(t.options)for(let e of Object.keys(t.options))n.push(`--${e} <${e}>`);return t.suffix&&n.push(t.suffix),n.join(` `)}),n=` `.repeat(7);h.push(`Usage: ${t[0]}`);for(let e of t.slice(1))h.push(`${n}${e}`)}else{let n=au(e,c),r=t.commands&&t.commands.length>0?` | <command>`:``;h.push(`Usage: ${n}${p?` [options]`:``}${r}`)}if(r?.length&&h.push(`Aliases: ${r.join(`, `)}`),c){let e=ou(c);if(e.length>0){h.push(``),h.push(`Arguments:`);let t=Math.max(...e.map(e=>e.name.length));for(let n of e)h.push(` ${n.name}${` `.repeat(t-n.name.length)} ${n.description}`)}}if(p){let e=cu(p,n);if(e.length>0){h.push(``),h.push(`Options:`);let t=Math.max(...e.map(e=>e.flag.length));for(let n of e){let e=` `.repeat(t-n.flag.length),r=n.deprecated?`[deprecated] `:``,i=n.defaultValue===void 0?`${r}${n.description}`:`${r}${n.description} (default: ${n.defaultValue})`;h.push(` ${n.flag}${e} ${i}`)}}}if(m&&m.length>0){h.push(``),h.push(`Examples:`);let t=Math.max(...m.map(t=>(t.command?`${e} ${t.command}`:e).length));for(let n of m){let r=n.command?`${e} ${n.command}`:e;n.description?h.push(` ${r}${` `.repeat(t-r.length)} # ${n.description}`):h.push(` ${r}`)}}d&&(h.push(``),h.push(d));let{commands:v}=t;if(v&&v.length>0){h.push(``),h.push(`Commands:`);let e=Math.max(...v.map(e=>e.name.length));for(let t of v)if(t.description){let n=` `.repeat(e-t.name.length);h.push(` ${t.name}${n} ${t.description}`)}else h.push(` ${t.name}`)}if(t.hideGlobalOptions||h.push(...mu(f,i,o)),l){let e=su(l);if(e.length>0){h.push(``),h.push(`Environment Variables:`);let t=Math.max(...e.map(e=>e.name.length));for(let n of e){let e=` `.repeat(t-n.name.length),r=[n.description],i=u??Wl();n.name in i&&r.push(`set: ${hu(i[n.name])}`),n.defaultValue!==void 0&&r.push(`default: ${n.defaultValue}`);let a=r.length>1?`${r[0]} (${r.slice(1).join(`, `)})`:r[0];h.push(` ${n.name}${e} ${a}`)}}}return h.join(`
172
- `)}function au(e,t){if(!t)return e;let n=[e];for(let[e,r]of Object.entries(t.shape)){let t=lu(r),i=(t.includes(`|`)?t:e)+(t===`array`?`...`:``);n.push(r._zod.optout===`optional`?`[${i}]`:`<${i}>`)}return n.join(` `)}function ou(e){let t=[];for(let[n,r]of Object.entries(e.shape))t.push({name:n,description:r.description??``});return t}function su(e){let t=[];for(let[n,r]of Object.entries(e.shape)){let e=fu(r);t.push({name:n,description:r.description??``,defaultValue:e})}return t}function cu(e,t){let n=[];for(let[r,i]of Object.entries(e.shape)){let e=lu(i),a=t?.[r],o=an(r),s=e===`boolean`?``:` <${e}>`,c=a?`--${o}, -${a}${s}`:`--${o}${s}`,l=fu(i);e===`boolean`&&l===!1&&(l=void 0);let u=pu(i);n.push({flag:c,description:i.description??``,defaultValue:l,deprecated:u})}return n}function lu(e){if(uu(e))return`count`;let t=du(e);if(t instanceof f.ZodString)return`string`;if(t instanceof f.ZodNumber)return`number`;if(t instanceof f.ZodBoolean)return`boolean`;if(t instanceof f.ZodArray)return`array`;if(t instanceof f.ZodEnum)return Object.values(t._zod.def.entries).join(`|`);if(t instanceof f.ZodUnion){let e=t._zod?.def?.options;if(e?.every(e=>e instanceof f.ZodLiteral))return e.map(e=>String(e._zod.def.values[0])).join(`|`)}return`value`}function uu(e){let t=e;return typeof t?.meta==`function`&&t.meta()?.count===!0}function du(e){return e instanceof f.ZodOptional?du(e.unwrap()):e instanceof f.ZodDefault?du(e.removeDefault()):e instanceof f.ZodNullable?du(e.unwrap()):e}function fu(e){if(e instanceof f.ZodDefault){let t=e._def.defaultValue,n=typeof t==`function`?t():t;return Array.isArray(n)&&n.length===0?void 0:n}if(e instanceof f.ZodOptional)return fu(e.unwrap())}function pu(e){return e?.meta?.()?.deprecated===!0||void 0}function mu(e=!1,t,n){let r=[];if(e){let e=tu.flatMap(e=>{if(!e.subcommands)return[{name:e.name,desc:e.description}];if(e.subcommands.length===1)return[{name:`${e.name} ${e.subcommands[0].name}`,desc:e.subcommands[0].description}];let t=e.subcommands.map(e=>e.name).join(`, `);return[{name:e.name,desc:`${e.description} (${t})`}]}),t=Math.max(...e.map(e=>e.name.length));r.push(``,`Integrations:`,...e.map(e=>` ${e.name}${` `.repeat(t-e.name.length)} ${e.desc}`))}if(n){let e=cu(n.schema,n.alias);if(e.length>0){let t=Math.max(...e.map(e=>e.flag.length));r.push(``,`Custom Global Options:`,...e.map(e=>{let n=` `.repeat(t-e.flag.length),r=e.deprecated?`[deprecated] `:``,i=e.defaultValue===void 0?`${r}${e.description}`:`${r}${e.description} (default: ${e.defaultValue})`;return` ${e.flag}${n} ${i}`}))}}let i=[...t?[{flag:`--${t} <path>`,desc:`Load JSON option defaults from a file`}]:[],{flag:`--filter-output <keys>`,desc:`Filter output by key paths (e.g. foo,bar.baz,a[0,3])`},{flag:`--format <toon|json|yaml|md|jsonl>`,desc:`Output format`},{flag:`--help`,desc:`Show help`},{flag:`--llms, --llms-full`,desc:`Print LLM-readable manifest`},...e?[{flag:`--mcp`,desc:`Start as MCP stdio server`}]:[],...t?[{flag:`--no-${t}`,desc:`Disable JSON option defaults for this run`}]:[],{flag:`--schema`,desc:`Show JSON Schema for command`},{flag:`--token-count`,desc:`Print token count of output (instead of output)`},{flag:`--token-limit <n>`,desc:`Limit output to n tokens`},{flag:`--token-offset <n>`,desc:`Skip first n tokens of output`},{flag:`--full-output`,desc:`Show full output envelope`},...e?[{flag:`--update`,desc:`Update to latest version`}]:[],...e?[{flag:`--version`,desc:`Show version`}]:[]].sort((e,t)=>e.flag.localeCompare(t.flag)),a=Math.max(...i.map(e=>e.flag.length));return r.push(``,`Global Options:`,...i.map(e=>` ${e.flag}${` `.repeat(a-e.flag.length)} ${e.desc}`)),r}function hu(e){return e.length<=4?`****`:`****${e.slice(-4)}`}var gu=F((()=>{nu(),cn(),Gl()}));function _u(e,t){if(!(!t||t.commands.length===0))return{description:t.description??(t.commands.length===1?`Suggested command:`:`Suggested commands:`),commands:t.commands.map(t=>yu(e,t))}}function vu(e){let t=[e.description];for(let n of e.commands)t.push(` ${n.command}${n.description?` - ${n.description}`:``}`);return t.join(`
173
- `)}function yu(e,t){if(typeof t==`string`)return{command:`${e} ${t}`};let n=`${t.command===e||t.command.startsWith(`${e} `)?``:`${e} `}${t.command}`;if(t.args)for(let[e,r]of Object.entries(t.args))n+=r===!0?` <${e}>`:` ${r}`;if(t.options)for(let[e,r]of Object.entries(t.options))n+=r===!0?` --${e} <${e}>`:` --${e} ${r}`;return{command:n,...t.description?{description:t.description}:void 0}}var bu=F((()=>{}));async function xu(e,t={}){let n=[],r=t.exclude?c.resolve(t.exclude):void 0;async function i(e,t){let a=await C.readdir(e,{withFileTypes:!0});a.sort((e,t)=>e.name.localeCompare(t.name));for(let o of a){if(o.name.startsWith(`.`)||o.name.startsWith(`_`))continue;let a=c.join(e,o.name);if(o.isDirectory()){wu(o.name,a),await i(a,[...t,o.name]);continue}if(!o.isFile()||a===r)continue;let s=Tu.find(e=>o.name.endsWith(e));if(!s)continue;let l=o.name.slice(0,-s.length);if(!(l.endsWith(`.d`)||l.endsWith(`.test`)||l.endsWith(`.test-d`)||l.endsWith(`.spec`))){if(l===`index`){t.length>0&&n.push({file:a,segments:t});continue}wu(l,a),n.push({file:a,segments:[...t,l]})}}}await i(e,[]);let a=new Map;for(let e of n){let t=e.segments.join(` `),n=a.get(t);if(n)throw Error(`Duplicate filesystem command '${t}' from '${n}' and '${e.file}'.`);a.set(t,e.file)}return n}function Su(){return globalThis[Symbol.for(Du)]?.shift()}async function Cu(e){return Promise.all(e.map(async({load:e,...t})=>({...t,command:await e()})))}function wu(e,t){if(!Eu.test(e))throw Error(`Invalid filesystem command segment '${e}' from '${t}'. Use lowercase kebab-case names.`)}var Tu,Eu,Du,Ou=F((()=>{Tu=[`.cts`,`.cjs`,`.mts`,`.mjs`,`.ts`,`.js`],Eu=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Du=`incur.fs.manifests`}));function ku(e){let t=f.toJSONSchema(e,{unrepresentable:`any`,override:e=>{let t=e.zodSchema._zod?.def?.type;(t===`bigint`||t===`date`)&&(e.jsonSchema.type=`string`)}});return delete t.$schema,t}var Au=F((()=>{}));function ju(e,t){let n=typeof e;if(n!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let n=e.length;if(n!==t.length)return!1;for(let r=0;r<n;r++)if(!ju(e[r],t[r]))return!1;return!0}if(n===`object`){if(!e||!t)return e===t;let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(!ju(e[r],t[r]))return!1;return!0}return e===t}var Mu=F((()=>{}));function Nu(e){return encodeURI(Pu(e))}function Pu(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}var Fu=F((()=>{}));function Iu(e,t=Object.create(null),n=Bu,r=``){if(e&&typeof e==`object`&&!Array.isArray(e)){let i=e.$id||e.id;if(i){let a=new URL(i,n.href);a.hash.length>1?t[a.href]=e:(a.hash=``,r===``?n=a:Iu(e,t,n))}}else if(e!==!0&&e!==!1)return t;let i=n.href+(r?`#`+r:``);if(t[i]!==void 0)throw Error(`Duplicate schema URI "${i}".`);if(t[i]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:i}),e.$ref&&e.__absolute_ref__===void 0){let t=new URL(e.$ref,n.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:t.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let t=new URL(e.$recursiveRef,n.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:t.href})}if(e.$anchor){let r=new URL(`#`+e.$anchor,n.href);t[r.href]=e}for(let i in e){if(zu[i])continue;let a=`${r}/${Nu(i)}`,o=e[i];if(Array.isArray(o)){if(Lu[i]){let e=o.length;for(let r=0;r<e;r++)Iu(o[r],t,n,`${a}/${r}`)}}else if(Ru[i])for(let e in o)Iu(o[e],t,n,`${a}/${Nu(e)}`);else Iu(o,t,n,a)}return t}var Lu,Ru,zu,Bu,Vu=F((()=>{Fu(),Lu={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Ru={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},zu={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},Bu=typeof self<`u`&&self.location&&self.location.origin!==`null`?new URL(self.location.origin+self.location.pathname+location.search):new URL(`https://github.com/cfworker`)}));function Hu(e){return e.test.bind(e)}function Uu(e){return e%4==0&&(e%100!=0||e%400==0)}function Wu(e){let t=e.match(Yu);if(!t)return!1;let n=+t[1],r=+t[2],i=+t[3];return r>=1&&r<=12&&i>=1&&i<=(r==2&&Uu(n)?29:Xu[r])}function Gu(e,t){let n=t.match(Zu);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=!!n[5];return(r<=23&&i<=59&&a<=59||r==23&&i==59&&a==60)&&(!e||o)}function Ku(e){let t=e.split(dd);return t.length==2&&Wu(t[0])&&Gu(!0,t[1])}function qu(e){return fd.test(e)&&pd.test(e)}function Ju(e){if(md.test(e))return!1;try{return new RegExp(e,`u`),!0}catch{return!1}}var Yu,Xu,Zu,Qu,$u,ed,td,nd,rd,id,ad,od,sd,cd,ld,ud,dd,fd,pd,md,hd=F((()=>{Yu=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Xu=[0,31,28,31,30,31,30,31,31,30,31,30,31],Zu=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,Qu=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,$u=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,ed=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,td=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,nd=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,rd=/^(?:\/(?:[^~/]|~0|~1)*)*$/,id=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,ad=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,od=e=>{if(e[0]===`"`)return!1;let[t,n,...r]=e.split(`@`);return!t||!n||r.length!==0||t.length>64||n.length>253||t[0]===`.`||t.endsWith(`.`)||t.includes(`..`)||!/^[a-z0-9.-]+$/i.test(n)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:n.split(`.`).every(e=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(e))},sd=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,cd=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,ld=e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e)),ud={date:Wu,time:Gu.bind(void 0,!1),"date-time":Ku,duration:ld,uri:qu,"uri-reference":Hu($u),"uri-template":Hu(ed),url:Hu(td),email:od,hostname:Hu(Qu),ipv4:Hu(sd),ipv6:Hu(cd),regex:Ju,uuid:Hu(nd),"json-pointer":Hu(rd),"json-pointer-uri-fragment":Hu(id),"relative-json-pointer":Hu(ad)},dd=/t|\s/i,fd=/\/|:/,pd=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,md=/[^\\]\\Z/})),gd=F((()=>{}));function _d(e){let t=0,n=e.length,r=0,i;for(;r<n;)t++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<n&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return t}var vd=F((()=>{}));function yd(e,t,n=`2019-09`,r=Iu(t),i=!0,a=null,o=`#`,s=`#`,c=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:o,keyword:`false`,keywordLocation:o,error:`False boolean schema.`}]};let l=typeof e,u;switch(l){case`boolean`:case`number`:case`string`:u=l;break;case`object`:u=e===null?`null`:Array.isArray(e)?`array`:`object`;break;default:throw Error(`Instances of "${l}" type are not supported.`)}let{$ref:d,$recursiveRef:f,$recursiveAnchor:p,type:m,const:h,enum:g,required:_,not:v,anyOf:y,allOf:b,oneOf:x,if:S,then:C,else:w,format:T,properties:ee,patternProperties:E,additionalProperties:D,unevaluatedProperties:O,minProperties:k,maxProperties:te,propertyNames:ne,dependentRequired:re,dependentSchemas:A,dependencies:j,prefixItems:ie,items:ae,additionalItems:oe,unevaluatedItems:se,contains:ce,minContains:M,maxContains:le,minItems:ue,maxItems:de,uniqueItems:fe,minimum:pe,maximum:me,exclusiveMinimum:N,exclusiveMaximum:he,multipleOf:ge,minLength:_e,maxLength:ve,pattern:ye,__absolute_ref__:be,__absolute_recursive_ref__:xe}=t,P=[];if(p===!0&&a===null&&(a=t),f===`#`){let l=a===null?r[xe]:a,u=`${s}/$recursiveRef`,d=yd(e,a===null?t:a,n,r,i,l,o,u,c);d.valid||P.push({instanceLocation:o,keyword:`$recursiveRef`,keywordLocation:u,error:`A subschema had errors.`},...d.errors)}if(d!==void 0){let t=r[be||d];if(t===void 0){let e=`Unresolved $ref "${d}".`;throw be&&be!==d&&(e+=` Absolute URI "${be}".`),e+=`\nKnown schemas:\n- ${Object.keys(r).join(`
174
- - `)}`,Error(e)}let l=`${s}/$ref`,u=yd(e,t,n,r,i,a,o,l,c);if(u.valid||P.push({instanceLocation:o,keyword:`$ref`,keywordLocation:l,error:`A subschema had errors.`},...u.errors),n===`4`||n===`7`)return{valid:P.length===0,errors:P}}if(Array.isArray(m)){let t=m.length,n=!1;for(let r=0;r<t;r++)if(u===m[r]||m[r]===`integer`&&u===`number`&&e%1==0&&e===e){n=!0;break}n||P.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m.join(`", "`)}".`})}else m===`integer`?(u!==`number`||e%1||e!==e)&&P.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}):m!==void 0&&u!==m&&P.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`});if(h!==void 0&&(u===`object`||u===`array`?ju(e,h)||P.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):e!==h&&P.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`})),g!==void 0&&(u===`object`||u===`array`?g.some(t=>ju(e,t))||P.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some(t=>e===t)||P.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`})),v!==void 0){let t=`${s}/not`;yd(e,v,n,r,i,a,o,t).valid&&P.push({instanceLocation:o,keyword:`not`,keywordLocation:t,error:`Instance matched "not" schema.`})}let Se=[];if(y!==void 0){let t=`${s}/anyOf`,l=P.length,u=!1;for(let s=0;s<y.length;s++){let l=y[s],d=Object.create(c),f=yd(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);P.push(...f.errors),u||=f.valid,f.valid&&Se.push(d)}u?P.length=l:P.splice(l,0,{instanceLocation:o,keyword:`anyOf`,keywordLocation:t,error:`Instance does not match any subschemas.`})}if(b!==void 0){let t=`${s}/allOf`,l=P.length,u=!0;for(let s=0;s<b.length;s++){let l=b[s],d=Object.create(c),f=yd(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);P.push(...f.errors),u&&=f.valid,f.valid&&Se.push(d)}u?P.length=l:P.splice(l,0,{instanceLocation:o,keyword:`allOf`,keywordLocation:t,error:`Instance does not match every subschema.`})}if(x!==void 0){let t=`${s}/oneOf`,l=P.length,u=x.filter((s,l)=>{let u=Object.create(c),d=yd(e,s,n,r,i,p===!0?a:null,o,`${t}/${l}`,u);return P.push(...d.errors),d.valid&&Se.push(u),d.valid}).length;u===1?P.length=l:P.splice(l,0,{instanceLocation:o,keyword:`oneOf`,keywordLocation:t,error:`Instance does not match exactly one subschema (${u} matches).`})}if((u===`object`||u===`array`)&&Object.assign(c,...Se),S!==void 0){let t=`${s}/if`;if(yd(e,S,n,r,i,a,o,t,c).valid){if(C!==void 0){let l=yd(e,C,n,r,i,a,o,`${s}/then`,c);l.valid||P.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "then" schema.`},...l.errors)}}else if(w!==void 0){let l=yd(e,w,n,r,i,a,o,`${s}/else`,c);l.valid||P.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "else" schema.`},...l.errors)}}if(u===`object`){if(_!==void 0)for(let t of _)t in e||P.push({instanceLocation:o,keyword:`required`,keywordLocation:`${s}/required`,error:`Instance does not have required property "${t}".`});let t=Object.keys(e);if(k!==void 0&&t.length<k&&P.push({instanceLocation:o,keyword:`minProperties`,keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${k} properties.`}),te!==void 0&&t.length>te&&P.push({instanceLocation:o,keyword:`maxProperties`,keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${te} properties.`}),ne!==void 0){let t=`${s}/propertyNames`;for(let s in e){let e=`${o}/${Nu(s)}`,c=yd(s,ne,n,r,i,a,e,t);c.valid||P.push({instanceLocation:o,keyword:`propertyNames`,keywordLocation:t,error:`Property name "${s}" does not match schema.`},...c.errors)}}if(re!==void 0){let t=`${s}/dependantRequired`;for(let n in re)if(n in e){let r=re[n];for(let i of r)i in e||P.push({instanceLocation:o,keyword:`dependentRequired`,keywordLocation:t,error:`Instance has "${n}" but does not have "${i}".`})}}if(A!==void 0)for(let t in A){let l=`${s}/dependentSchemas`;if(t in e){let s=yd(e,A[t],n,r,i,a,o,`${l}/${Nu(t)}`,c);s.valid||P.push({instanceLocation:o,keyword:`dependentSchemas`,keywordLocation:l,error:`Instance has "${t}" but does not match dependant schema.`},...s.errors)}}if(j!==void 0){let t=`${s}/dependencies`;for(let s in j)if(s in e){let c=j[s];if(Array.isArray(c))for(let n of c)n in e||P.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not have "${n}".`});else{let l=yd(e,c,n,r,i,a,o,`${t}/${Nu(s)}`);l.valid||P.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not match dependant schema.`},...l.errors)}}}let l=Object.create(null),u=!1;if(ee!==void 0){let t=`${s}/properties`;for(let s in ee){if(!(s in e))continue;let d=`${o}/${Nu(s)}`,f=yd(e[s],ee[s],n,r,i,a,d,`${t}/${Nu(s)}`);if(f.valid)c[s]=l[s]=!0;else if(u=i,P.push({instanceLocation:o,keyword:`properties`,keywordLocation:t,error:`Property "${s}" does not match schema.`},...f.errors),u)break}}if(!u&&E!==void 0){let t=`${s}/patternProperties`;for(let s in E){let d=new RegExp(s,`u`),f=E[s];for(let p in e){if(!d.test(p))continue;let m=`${o}/${Nu(p)}`,h=yd(e[p],f,n,r,i,a,m,`${t}/${Nu(s)}`);h.valid?c[p]=l[p]=!0:(u=i,P.push({instanceLocation:o,keyword:`patternProperties`,keywordLocation:t,error:`Property "${p}" matches pattern "${s}" but does not match associated schema.`},...h.errors))}}}if(!u&&D!==void 0){let t=`${s}/additionalProperties`;for(let s in e){if(l[s])continue;let d=`${o}/${Nu(s)}`,f=yd(e[s],D,n,r,i,a,d,t);f.valid?c[s]=!0:(u=i,P.push({instanceLocation:o,keyword:`additionalProperties`,keywordLocation:t,error:`Property "${s}" does not match additional properties schema.`},...f.errors))}}else if(!u&&O!==void 0){let t=`${s}/unevaluatedProperties`;for(let s in e)if(!c[s]){let l=`${o}/${Nu(s)}`,u=yd(e[s],O,n,r,i,a,l,t);u.valid?c[s]=!0:P.push({instanceLocation:o,keyword:`unevaluatedProperties`,keywordLocation:t,error:`Property "${s}" does not match unevaluated properties schema.`},...u.errors)}}}else if(u===`array`){de!==void 0&&e.length>de&&P.push({instanceLocation:o,keyword:`maxItems`,keywordLocation:`${s}/maxItems`,error:`Array has too many items (${e.length} > ${de}).`}),ue!==void 0&&e.length<ue&&P.push({instanceLocation:o,keyword:`minItems`,keywordLocation:`${s}/minItems`,error:`Array has too few items (${e.length} < ${ue}).`});let t=e.length,l=0,u=!1;if(ie!==void 0){let d=`${s}/prefixItems`,f=Math.min(ie.length,t);for(;l<f;l++){let t=yd(e[l],ie[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,P.push({instanceLocation:o,keyword:`prefixItems`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}if(ae!==void 0){let d=`${s}/items`;if(Array.isArray(ae)){let s=Math.min(ae.length,t);for(;l<s;l++){let t=yd(e[l],ae[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,P.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}else for(;l<t;l++){let t=yd(e[l],ae,n,r,i,a,`${o}/${l}`,d);if(c[l]=!0,!t.valid&&(u=i,P.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}if(!u&&oe!==void 0){let d=`${s}/additionalItems`;for(;l<t;l++){let t=yd(e[l],oe,n,r,i,a,`${o}/${l}`,d);c[l]=!0,t.valid||(u=i,P.push({instanceLocation:o,keyword:`additionalItems`,keywordLocation:d,error:`Items did not match additional items schema.`},...t.errors))}}}if(ce!==void 0){if(t===0&&M===void 0)P.push({instanceLocation:o,keyword:`contains`,keywordLocation:`${s}/contains`,error:`Array is empty. It must contain at least one item matching the schema.`});else if(M!==void 0&&t<M)P.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array has less items (${t}) than minContains (${M}).`});else{let l=`${s}/contains`,u=P.length,d=0;for(let s=0;s<t;s++){let t=yd(e[s],ce,n,r,i,a,`${o}/${s}`,l);t.valid?(c[s]=!0,d++):P.push(...t.errors)}d>=(M||0)&&(P.length=u),M===void 0&&le===void 0&&d===0?P.splice(u,0,{instanceLocation:o,keyword:`contains`,keywordLocation:l,error:`Array does not contain item matching schema.`}):M!==void 0&&d<M?P.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array must contain at least ${M} items matching schema. Only ${d} items were found.`}):le!==void 0&&d>le&&P.push({instanceLocation:o,keyword:`maxContains`,keywordLocation:`${s}/maxContains`,error:`Array may contain at most ${le} items matching schema. ${d} items were found.`})}}if(!u&&se!==void 0){let u=`${s}/unevaluatedItems`;for(;l<t;l++){if(c[l])continue;let t=yd(e[l],se,n,r,i,a,`${o}/${l}`,u);c[l]=!0,t.valid||P.push({instanceLocation:o,keyword:`unevaluatedItems`,keywordLocation:u,error:`Items did not match unevaluated items schema.`},...t.errors)}}if(fe)for(let n=0;n<t;n++){let r=e[n],i=typeof r==`object`&&!!r;for(let a=0;a<t;a++){if(n===a)continue;let t=e[a];(r===t||i&&typeof t==`object`&&t&&ju(r,t))&&(P.push({instanceLocation:o,keyword:`uniqueItems`,keywordLocation:`${s}/uniqueItems`,error:`Duplicate items at indexes ${n} and ${a}.`}),n=2**53-1,a=2**53-1)}}}else if(u===`number`){if(n===`4`?(pe!==void 0&&(N===!0&&e<=pe||e<pe)&&P.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${N?`or equal to `:``} ${pe}.`}),me!==void 0&&(he===!0&&e>=me||e>me)&&P.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${he?`or equal to `:``} ${me}.`})):(pe!==void 0&&e<pe&&P.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${pe}.`}),me!==void 0&&e>me&&P.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${me}.`}),N!==void 0&&e<=N&&P.push({instanceLocation:o,keyword:`exclusiveMinimum`,keywordLocation:`${s}/exclusiveMinimum`,error:`${e} is less than ${N}.`}),he!==void 0&&e>=he&&P.push({instanceLocation:o,keyword:`exclusiveMaximum`,keywordLocation:`${s}/exclusiveMaximum`,error:`${e} is greater than or equal to ${he}.`})),ge!==void 0){let t=e%ge;Math.abs(0-t)>=1.1920929e-7&&Math.abs(ge-t)>=1.1920929e-7&&P.push({instanceLocation:o,keyword:`multipleOf`,keywordLocation:`${s}/multipleOf`,error:`${e} is not a multiple of ${ge}.`})}}else if(u===`string`){let t=_e===void 0&&ve===void 0?0:_d(e);_e!==void 0&&t<_e&&P.push({instanceLocation:o,keyword:`minLength`,keywordLocation:`${s}/minLength`,error:`String is too short (${t} < ${_e}).`}),ve!==void 0&&t>ve&&P.push({instanceLocation:o,keyword:`maxLength`,keywordLocation:`${s}/maxLength`,error:`String is too long (${t} > ${ve}).`}),ye!==void 0&&!new RegExp(ye,`u`).test(e)&&P.push({instanceLocation:o,keyword:`pattern`,keywordLocation:`${s}/pattern`,error:`String does not match pattern.`}),T!==void 0&&ud[T]&&!ud[T](e)&&P.push({instanceLocation:o,keyword:`format`,keywordLocation:`${s}/format`,error:`String does not match format "${T}".`})}return{valid:P.length===0,errors:P}}var bd=F((()=>{Mu(),Vu(),hd(),Fu(),vd()})),xd,Sd=F((()=>{Vu(),bd(),xd=class{schema;draft;shortCircuit;lookup;constructor(e,t=`2019-09`,n=!0){this.schema=e,this.draft=t,this.shortCircuit=n,this.lookup=Iu(e)}validate(e){return yd(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),Iu(e,this.lookup)}}})),Cd=F((()=>{Mu(),Vu(),hd(),Fu(),gd(),vd(),bd(),Sd()}));function wd(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function Td({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;let i=n.pathname.endsWith(`/`)?n.pathname:n.pathname+`/`,a=r.pathname.endsWith(`/`)?r.pathname:r.pathname+`/`;return i.startsWith(a)}function Ed(e){return e.title!==void 0&&e.title!==``?e.title:`annotations`in e&&e.annotations?.title?e.annotations.title:e.name}function Dd(e){return _h[e]}function Od(e){let t={};for(let n of e){let e=n.shape.method.value;t[e]=n}return t}function kd(e){return vh[e]}function Ad(e){return yh[e]}function jd(e){return Gf.parse(e)}function Md(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function Nd(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}function Pd(e,t){return D.safeParse(e,t)}function Fd(e){return e===`completed`||e===`failed`||e===`cancelled`}function Id(e){if(!e)return;let{taskStore:t,taskMessageQueue:n,defaultTaskPollInterval:r,maxTaskQueueSize:i}=e;return{taskStore:t,taskMessageQueue:n,defaultTaskPollInterval:r,maxTaskQueueSize:i}}function Ld(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Rd(e,t){let n={...e};for(let e in t){let r=e,i=t[r];if(i===void 0)continue;let a=n[r];n[r]=Ld(a)&&Ld(i)?{...a,...i}:i}return n}async function zd(e){let t=[];for await(let n of e)t.push(n);return t}async function Bd(e){for await(let t of e)if(t.type===`result`)return t.result;else if(t.type===`error`)throw t.error;throw Error(`No result in stream.`)}function Vd(e){return Gf.parse(JSON.parse(e))}function Hd(e){return JSON.stringify(e)+`
175
- `}function Ud(e){let t=[];if(e.length===0)return{isValid:!1,warnings:[`Tool name cannot be empty`]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(` `)&&t.push(`Tool name contains spaces, which may cause parsing issues`),e.includes(`,`)&&t.push(`Tool name contains commas, which may cause parsing issues`),(e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`Tool name starts or ends with a dash, which may cause parsing issues in some contexts`),(e.startsWith(`.`)||e.endsWith(`.`))&&t.push(`Tool name starts or ends with a dot, which may cause parsing issues in some contexts`),!Mh.test(e)){let n=[...e].filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,n)=>n.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${n.map(e=>`"${e}"`).join(`, `)}`,`Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)`),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function Wd(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);console.warn(`Tool registration will proceed, but this may cause compatibility issues.`),console.warn(`Consider updating the tool name to conform to the MCP tool naming standard.`),console.warn(`See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.`)}}function Gd(e){let t=Ud(e);return Wd(e,t.warnings),t.isValid}function Kd(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function qd(e=fetch,t){return t?async(n,r)=>e(n,{...t,...r,headers:r?.headers?{...Kd(t.headers),...Kd(r.headers)}:t.headers}):e}function Jd(e,t=`input`){let n=e[`~standard`].jsonSchema[t]({target:`draft-2020-12`});if(n.type!==void 0&&n.type!==`object`)throw Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(n.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:`object`,...n}}function Yd(e){return e.path?.length?`${e.path.map(e=>String(typeof e==`object`?e.key:e)).join(`.`)}: ${e.message}`:e.message}async function Xd(e,t){let n=await e[`~standard`].validate(t);return n.issues&&n.issues.length>0?{success:!1,error:n.issues.map(e=>Yd(e)).join(`, `)}:{success:!0,data:n.value}}function Zd(e){let t=Jd(e,`input`),n=t.properties||{},r=t.required||[];return Object.entries(n).map(([e,t])=>({name:e,description:t?.description,required:r.includes(e)}))}function Qd(){let e=new $g.Ajv({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,e_.default)(e),e}function $d(e,t){let n=t.getValidator(e);return{"~standard":{version:1,vendor:`mcp`,jsonSchema:{input:()=>e,output:()=>e},validate:e=>{let t=n(e);return t.valid?{value:t.data}:{issues:[{message:t.errorMessage}]}}}}}var ef,tf,nf,rf,af,of,z,sf,cf,lf,uf,B,V,df,ff,pf,mf,hf,gf,_f,vf,yf,bf,xf,Sf,Cf,wf,Tf,H,U,Ef,Df,Of,kf,Af,jf,Mf,Nf,Pf,Ff,If,Lf,Rf,zf,Bf,Vf,Hf,Uf,Wf,Gf,Kf,qf,Jf,Yf,Xf,Zf,Qf,$f,ep,tp,np,rp,ip,ap,op,sp,cp,lp,up,dp,fp,pp,mp,hp,gp,_p,vp,yp,bp,xp,Sp,Cp,wp,Tp,Ep,Dp,Op,kp,Ap,jp,Mp,Np,Pp,Fp,Ip,Lp,Rp,zp,Bp,Vp,Hp,Up,Wp,Gp,Kp,qp,Jp,Yp,Xp,Zp,Qp,$p,em,tm,nm,rm,im,am,om,sm,cm,lm,um,dm,fm,pm,mm,hm,gm,_m,vm,ym,bm,xm,Sm,Cm,wm,Tm,Em,Dm,Om,km,Am,jm,Mm,Nm,Pm,Fm,Im,Lm,Rm,zm,Bm,Vm,Hm,Um,Wm,Gm,Km,qm,Jm,Ym,Xm,Zm,Qm,$m,eh,th,nh,rh,ih,ah,oh,sh,ch,lh,uh,dh,fh,ph,mh,hh,gh,_h,vh,yh,bh,xh,Sh,Ch,wh,Th,Eh,Dh,Oh,kh,Ah,jh,Mh,Nh,Ph,Fh,Ih,Lh,Rh,zh,W,G,Bh,Vh,Hh,Uh,Wh,Gh,Kh,qh,Jh,Yh,Xh,Zh,Qh,$h,eg,tg,ng,rg,ig,ag,og,sg,cg,lg,ug,dg,fg,pg,mg,hg,gg,_g,vg,yg,bg,xg,Sg,Cg,wg,Tg,Eg,Dg,Og,kg,Ag,jg,Mg,Ng,Pg,Fg,Ig,Lg,Rg,zg,Bg,Vg,Hg,Ug,Wg,Gg,Kg,qg,Jg,Yg,Xg,Zg,Qg,$g,e_,t_,n_,r_=F((()=>{Cd(),ef=Object.create,tf=Object.defineProperty,nf=Object.getOwnPropertyDescriptor,rf=Object.getOwnPropertyNames,af=Object.getPrototypeOf,of=Object.prototype.hasOwnProperty,z=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),sf=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=rf(t),a=0,o=i.length,s;a<o;a++)s=i[a],!of.call(e,s)&&s!==n&&tf(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=nf(t,s))||r.enumerable});return e},cf=(e,t,n)=>(n=e==null?{}:ef(af(e)),sf(t||!e||!e.__esModule?tf(n,`default`,{value:e,enumerable:!0}):n,e)),lf=function(e){return e.InvalidRequest=`invalid_request`,e.InvalidClient=`invalid_client`,e.InvalidGrant=`invalid_grant`,e.UnauthorizedClient=`unauthorized_client`,e.UnsupportedGrantType=`unsupported_grant_type`,e.InvalidScope=`invalid_scope`,e.AccessDenied=`access_denied`,e.ServerError=`server_error`,e.TemporarilyUnavailable=`temporarily_unavailable`,e.UnsupportedResponseType=`unsupported_response_type`,e.UnsupportedTokenType=`unsupported_token_type`,e.InvalidToken=`invalid_token`,e.MethodNotAllowed=`method_not_allowed`,e.TooManyRequests=`too_many_requests`,e.InvalidClientMetadata=`invalid_client_metadata`,e.InsufficientScope=`insufficient_scope`,e.InvalidTarget=`invalid_target`,e}({}),uf=class e extends Error{constructor(e,t,n){super(t),this.code=e,this.errorUri=n,this.name=`OAuthError`}toResponseObject(){let e={error:this.code,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}static fromResponse(t){return new e(t.error,t.error_description??t.error,t.error_uri)}},B=function(e){return e.NotConnected=`NOT_CONNECTED`,e.AlreadyConnected=`ALREADY_CONNECTED`,e.NotInitialized=`NOT_INITIALIZED`,e.CapabilityNotSupported=`CAPABILITY_NOT_SUPPORTED`,e.RequestTimeout=`REQUEST_TIMEOUT`,e.ConnectionClosed=`CONNECTION_CLOSED`,e.SendFailed=`SEND_FAILED`,e.ClientHttpNotImplemented=`CLIENT_HTTP_NOT_IMPLEMENTED`,e.ClientHttpAuthentication=`CLIENT_HTTP_AUTHENTICATION`,e.ClientHttpForbidden=`CLIENT_HTTP_FORBIDDEN`,e.ClientHttpUnexpectedContent=`CLIENT_HTTP_UNEXPECTED_CONTENT`,e.ClientHttpFailedToOpenStream=`CLIENT_HTTP_FAILED_TO_OPEN_STREAM`,e.ClientHttpFailedToTerminateSession=`CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION`,e}({}),V=class extends Error{constructor(e,t,n){super(t),this.code=e,this.data=n,this.name=`SdkError`}},df=D.url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:D.ZodIssueCode.custom,message:`URL must be parseable`,fatal:!0}),D.NEVER}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),D.looseObject({resource:D.string().url(),authorization_servers:D.array(df).optional(),jwks_uri:D.string().url().optional(),scopes_supported:D.array(D.string()).optional(),bearer_methods_supported:D.array(D.string()).optional(),resource_signing_alg_values_supported:D.array(D.string()).optional(),resource_name:D.string().optional(),resource_documentation:D.string().optional(),resource_policy_uri:D.string().url().optional(),resource_tos_uri:D.string().url().optional(),tls_client_certificate_bound_access_tokens:D.boolean().optional(),authorization_details_types_supported:D.array(D.string()).optional(),dpop_signing_alg_values_supported:D.array(D.string()).optional(),dpop_bound_access_tokens_required:D.boolean().optional()}),ff=D.looseObject({issuer:D.string(),authorization_endpoint:df,token_endpoint:df,registration_endpoint:df.optional(),scopes_supported:D.array(D.string()).optional(),response_types_supported:D.array(D.string()),response_modes_supported:D.array(D.string()).optional(),grant_types_supported:D.array(D.string()).optional(),token_endpoint_auth_methods_supported:D.array(D.string()).optional(),token_endpoint_auth_signing_alg_values_supported:D.array(D.string()).optional(),service_documentation:df.optional(),revocation_endpoint:df.optional(),revocation_endpoint_auth_methods_supported:D.array(D.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:D.array(D.string()).optional(),introspection_endpoint:D.string().optional(),introspection_endpoint_auth_methods_supported:D.array(D.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:D.array(D.string()).optional(),code_challenge_methods_supported:D.array(D.string()).optional(),client_id_metadata_document_supported:D.boolean().optional()}),pf=D.looseObject({issuer:D.string(),authorization_endpoint:df,token_endpoint:df,userinfo_endpoint:df.optional(),jwks_uri:df,registration_endpoint:df.optional(),scopes_supported:D.array(D.string()).optional(),response_types_supported:D.array(D.string()),response_modes_supported:D.array(D.string()).optional(),grant_types_supported:D.array(D.string()).optional(),acr_values_supported:D.array(D.string()).optional(),subject_types_supported:D.array(D.string()),id_token_signing_alg_values_supported:D.array(D.string()),id_token_encryption_alg_values_supported:D.array(D.string()).optional(),id_token_encryption_enc_values_supported:D.array(D.string()).optional(),userinfo_signing_alg_values_supported:D.array(D.string()).optional(),userinfo_encryption_alg_values_supported:D.array(D.string()).optional(),userinfo_encryption_enc_values_supported:D.array(D.string()).optional(),request_object_signing_alg_values_supported:D.array(D.string()).optional(),request_object_encryption_alg_values_supported:D.array(D.string()).optional(),request_object_encryption_enc_values_supported:D.array(D.string()).optional(),token_endpoint_auth_methods_supported:D.array(D.string()).optional(),token_endpoint_auth_signing_alg_values_supported:D.array(D.string()).optional(),display_values_supported:D.array(D.string()).optional(),claim_types_supported:D.array(D.string()).optional(),claims_supported:D.array(D.string()).optional(),service_documentation:D.string().optional(),claims_locales_supported:D.array(D.string()).optional(),ui_locales_supported:D.array(D.string()).optional(),claims_parameter_supported:D.boolean().optional(),request_parameter_supported:D.boolean().optional(),request_uri_parameter_supported:D.boolean().optional(),require_request_uri_registration:D.boolean().optional(),op_policy_uri:df.optional(),op_tos_uri:df.optional(),client_id_metadata_document_supported:D.boolean().optional()}),D.object({...pf.shape,...ff.pick({code_challenge_methods_supported:!0}).shape}),D.object({access_token:D.string(),id_token:D.string().optional(),token_type:D.string(),expires_in:D.coerce.number().optional(),scope:D.string().optional(),refresh_token:D.string().optional()}).strip(),D.object({issued_token_type:D.literal(`urn:ietf:params:oauth:token-type:id-jag`),access_token:D.string(),token_type:D.string().optional(),expires_in:D.number().optional(),scope:D.string().optional()}).strip(),D.object({error:D.string(),error_description:D.string().optional(),error_uri:D.string().optional()}),mf=df.optional().or(D.literal(``).transform(()=>void 0)),hf=D.object({redirect_uris:D.array(df),token_endpoint_auth_method:D.string().optional(),grant_types:D.array(D.string()).optional(),response_types:D.array(D.string()).optional(),client_name:D.string().optional(),client_uri:df.optional(),logo_uri:mf,scope:D.string().optional(),contacts:D.array(D.string()).optional(),tos_uri:mf,policy_uri:D.string().optional(),jwks_uri:df.optional(),jwks:D.any().optional(),software_id:D.string().optional(),software_version:D.string().optional(),software_statement:D.string().optional()}).strip(),gf=D.object({client_id:D.string(),client_secret:D.string().optional(),client_id_issued_at:D.number().optional(),client_secret_expires_at:D.number().optional()}).strip(),hf.merge(gf),D.object({error:D.string(),error_description:D.string().optional()}).strip(),D.object({token:D.string(),token_type_hint:D.string().optional()}).strip(),_f=`2025-11-25`,vf=`2025-03-26`,yf=[_f,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],bf=`io.modelcontextprotocol/related-task`,xf=-32700,Sf=-32600,Cf=-32601,wf=-32602,Tf=-32603,H=function(e){return e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.ResourceNotFound=-32002]=`ResourceNotFound`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`,e}({}),U=class e extends Error{constructor(e,t,n){super(t),this.code=e,this.data=n,this.name=`ProtocolError`}static fromError(t,n,r){if(t===H.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new Ef(e.elicitations,n)}return new e(t,n,r)}},Ef=class extends U{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(H.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},Df=D.lazy(()=>D.union([D.string(),D.number(),D.boolean(),D.null(),D.record(D.string(),Df),D.array(Df)])),Of=D.record(D.string(),Df),D.array(Df),kf=D.union([D.string(),D.number().int()]),Af=D.string(),D.looseObject({ttl:D.number().optional(),pollInterval:D.number().optional()}),jf=D.object({ttl:D.number().optional()}),Mf=D.object({taskId:D.string()}),Nf=D.looseObject({progressToken:kf.optional(),[bf]:Mf.optional()}),Pf=D.object({_meta:Nf.optional()}),Ff=Pf.extend({task:jf.optional()}),If=D.object({method:D.string(),params:Pf.loose().optional()}),Lf=D.object({_meta:Nf.optional()}),Rf=D.object({method:D.string(),params:Lf.loose().optional()}),zf=D.looseObject({_meta:Nf.optional()}),Bf=D.union([D.string(),D.number().int()]),Vf=D.object({jsonrpc:D.literal(`2.0`),id:Bf,...If.shape}).strict(),Hf=D.object({jsonrpc:D.literal(`2.0`),...Rf.shape}).strict(),Uf=D.object({jsonrpc:D.literal(`2.0`),id:Bf,result:zf}).strict(),Wf=D.object({jsonrpc:D.literal(`2.0`),id:Bf.optional(),error:D.object({code:D.number().int(),message:D.string(),data:D.unknown().optional()})}).strict(),Gf=D.union([Vf,Hf,Uf,Wf]),D.union([Uf,Wf]),Kf=zf.strict(),qf=Lf.extend({requestId:Bf.optional(),reason:D.string().optional()}),Jf=Rf.extend({method:D.literal(`notifications/cancelled`),params:qf}),Yf=D.object({src:D.string(),mimeType:D.string().optional(),sizes:D.array(D.string()).optional(),theme:D.enum([`light`,`dark`]).optional()}),Xf=D.object({icons:D.array(Yf).optional()}),Zf=D.object({name:D.string(),title:D.string().optional()}),Qf=Zf.extend({...Zf.shape,...Xf.shape,version:D.string(),websiteUrl:D.string().optional(),description:D.string().optional()}),$f=D.intersection(D.object({applyDefaults:D.boolean().optional()}),Of),ep=D.preprocess(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,D.intersection(D.object({form:$f.optional(),url:Of.optional()}),Of.optional())),tp=D.looseObject({list:Of.optional(),cancel:Of.optional(),requests:D.looseObject({sampling:D.looseObject({createMessage:Of.optional()}).optional(),elicitation:D.looseObject({create:Of.optional()}).optional()}).optional()}),np=D.looseObject({list:Of.optional(),cancel:Of.optional(),requests:D.looseObject({tools:D.looseObject({call:Of.optional()}).optional()}).optional()}),rp=D.object({experimental:D.record(D.string(),Of).optional(),sampling:D.object({context:Of.optional(),tools:Of.optional()}).optional(),elicitation:ep.optional(),roots:D.object({listChanged:D.boolean().optional()}).optional(),tasks:tp.optional(),extensions:D.record(D.string(),Of).optional()}),ip=Pf.extend({protocolVersion:D.string(),capabilities:rp,clientInfo:Qf}),ap=If.extend({method:D.literal(`initialize`),params:ip}),op=D.object({experimental:D.record(D.string(),Of).optional(),logging:Of.optional(),completions:Of.optional(),prompts:D.object({listChanged:D.boolean().optional()}).optional(),resources:D.object({subscribe:D.boolean().optional(),listChanged:D.boolean().optional()}).optional(),tools:D.object({listChanged:D.boolean().optional()}).optional(),tasks:np.optional(),extensions:D.record(D.string(),Of).optional()}),sp=zf.extend({protocolVersion:D.string(),capabilities:op,serverInfo:Qf,instructions:D.string().optional()}),cp=Rf.extend({method:D.literal(`notifications/initialized`),params:Lf.optional()}),lp=If.extend({method:D.literal(`ping`),params:Pf.optional()}),up=D.object({progress:D.number(),total:D.optional(D.number()),message:D.optional(D.string())}),dp=D.object({...Lf.shape,...up.shape,progressToken:kf}),fp=Rf.extend({method:D.literal(`notifications/progress`),params:dp}),pp=Pf.extend({cursor:Af.optional()}),mp=If.extend({params:pp.optional()}),hp=zf.extend({nextCursor:Af.optional()}),gp=D.enum([`working`,`input_required`,`completed`,`failed`,`cancelled`]),_p=D.object({taskId:D.string(),status:gp,ttl:D.union([D.number(),D.null()]),createdAt:D.string(),lastUpdatedAt:D.string(),pollInterval:D.optional(D.number()),statusMessage:D.optional(D.string())}),vp=zf.extend({task:_p}),yp=Lf.merge(_p),bp=Rf.extend({method:D.literal(`notifications/tasks/status`),params:yp}),xp=If.extend({method:D.literal(`tasks/get`),params:Pf.extend({taskId:D.string()})}),Sp=zf.merge(_p),Cp=If.extend({method:D.literal(`tasks/result`),params:Pf.extend({taskId:D.string()})}),wp=zf.loose(),Tp=mp.extend({method:D.literal(`tasks/list`)}),Ep=hp.extend({tasks:D.array(_p)}),Dp=If.extend({method:D.literal(`tasks/cancel`),params:Pf.extend({taskId:D.string()})}),Op=zf.merge(_p),kp=D.object({uri:D.string(),mimeType:D.optional(D.string()),_meta:D.record(D.string(),D.unknown()).optional()}),Ap=kp.extend({text:D.string()}),jp=D.string().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),Mp=kp.extend({blob:jp}),Np=D.enum([`user`,`assistant`]),Pp=D.object({audience:D.array(Np).optional(),priority:D.number().min(0).max(1).optional(),lastModified:D.iso.datetime({offset:!0}).optional()}),Fp=D.object({...Zf.shape,...Xf.shape,uri:D.string(),description:D.optional(D.string()),mimeType:D.optional(D.string()),size:D.optional(D.number()),annotations:Pp.optional(),_meta:D.optional(D.looseObject({}))}),Ip=D.object({...Zf.shape,...Xf.shape,uriTemplate:D.string(),description:D.optional(D.string()),mimeType:D.optional(D.string()),annotations:Pp.optional(),_meta:D.optional(D.looseObject({}))}),Lp=mp.extend({method:D.literal(`resources/list`)}),Rp=hp.extend({resources:D.array(Fp)}),zp=mp.extend({method:D.literal(`resources/templates/list`)}),Bp=hp.extend({resourceTemplates:D.array(Ip)}),Vp=Pf.extend({uri:D.string()}),Hp=Vp,Up=If.extend({method:D.literal(`resources/read`),params:Hp}),Wp=zf.extend({contents:D.array(D.union([Ap,Mp]))}),Gp=Rf.extend({method:D.literal(`notifications/resources/list_changed`),params:Lf.optional()}),Kp=Vp,qp=If.extend({method:D.literal(`resources/subscribe`),params:Kp}),Jp=Vp,Yp=If.extend({method:D.literal(`resources/unsubscribe`),params:Jp}),Xp=Lf.extend({uri:D.string()}),Zp=Rf.extend({method:D.literal(`notifications/resources/updated`),params:Xp}),Qp=D.object({name:D.string(),description:D.optional(D.string()),required:D.optional(D.boolean())}),$p=D.object({...Zf.shape,...Xf.shape,description:D.optional(D.string()),arguments:D.optional(D.array(Qp)),_meta:D.optional(D.looseObject({}))}),em=mp.extend({method:D.literal(`prompts/list`)}),tm=hp.extend({prompts:D.array($p)}),nm=Pf.extend({name:D.string(),arguments:D.record(D.string(),D.string()).optional()}),rm=If.extend({method:D.literal(`prompts/get`),params:nm}),im=D.object({type:D.literal(`text`),text:D.string(),annotations:Pp.optional(),_meta:D.record(D.string(),D.unknown()).optional()}),am=D.object({type:D.literal(`image`),data:jp,mimeType:D.string(),annotations:Pp.optional(),_meta:D.record(D.string(),D.unknown()).optional()}),om=D.object({type:D.literal(`audio`),data:jp,mimeType:D.string(),annotations:Pp.optional(),_meta:D.record(D.string(),D.unknown()).optional()}),sm=D.object({type:D.literal(`tool_use`),name:D.string(),id:D.string(),input:D.record(D.string(),D.unknown()),_meta:D.record(D.string(),D.unknown()).optional()}),cm=D.object({type:D.literal(`resource`),resource:D.union([Ap,Mp]),annotations:Pp.optional(),_meta:D.record(D.string(),D.unknown()).optional()}),lm=Fp.extend({type:D.literal(`resource_link`)}),um=D.union([im,am,om,lm,cm]),dm=D.object({role:Np,content:um}),fm=zf.extend({description:D.string().optional(),messages:D.array(dm)}),pm=Rf.extend({method:D.literal(`notifications/prompts/list_changed`),params:Lf.optional()}),mm=D.object({title:D.string().optional(),readOnlyHint:D.boolean().optional(),destructiveHint:D.boolean().optional(),idempotentHint:D.boolean().optional(),openWorldHint:D.boolean().optional()}),hm=D.object({taskSupport:D.enum([`required`,`optional`,`forbidden`]).optional()}),gm=D.object({...Zf.shape,...Xf.shape,description:D.string().optional(),inputSchema:D.object({type:D.literal(`object`),properties:D.record(D.string(),Df).optional(),required:D.array(D.string()).optional()}).catchall(D.unknown()),outputSchema:D.object({type:D.literal(`object`),properties:D.record(D.string(),Df).optional(),required:D.array(D.string()).optional()}).catchall(D.unknown()).optional(),annotations:mm.optional(),execution:hm.optional(),_meta:D.record(D.string(),D.unknown()).optional()}),_m=mp.extend({method:D.literal(`tools/list`)}),vm=hp.extend({tools:D.array(gm)}),ym=zf.extend({content:D.array(um).default([]),structuredContent:D.record(D.string(),D.unknown()).optional(),isError:D.boolean().optional()}),ym.or(zf.extend({toolResult:D.unknown()})),bm=Ff.extend({name:D.string(),arguments:D.record(D.string(),D.unknown()).optional()}),xm=If.extend({method:D.literal(`tools/call`),params:bm}),Sm=Rf.extend({method:D.literal(`notifications/tools/list_changed`),params:Lf.optional()}),D.object({autoRefresh:D.boolean().default(!0),debounceMs:D.number().int().nonnegative().default(300)}),Cm=D.enum([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),wm=Pf.extend({level:Cm}),Tm=If.extend({method:D.literal(`logging/setLevel`),params:wm}),Em=Lf.extend({level:Cm,logger:D.string().optional(),data:D.unknown()}),Dm=Rf.extend({method:D.literal(`notifications/message`),params:Em}),Om=D.object({name:D.string().optional()}),km=D.object({hints:D.array(Om).optional(),costPriority:D.number().min(0).max(1).optional(),speedPriority:D.number().min(0).max(1).optional(),intelligencePriority:D.number().min(0).max(1).optional()}),Am=D.object({mode:D.enum([`auto`,`required`,`none`]).optional()}),jm=D.object({type:D.literal(`tool_result`),toolUseId:D.string().describe(`The unique identifier for the corresponding tool call.`),content:D.array(um).default([]),structuredContent:D.object({}).loose().optional(),isError:D.boolean().optional(),_meta:D.record(D.string(),D.unknown()).optional()}),Mm=D.discriminatedUnion(`type`,[im,am,om]),Nm=D.discriminatedUnion(`type`,[im,am,om,sm,jm]),Pm=D.object({role:Np,content:D.union([Nm,D.array(Nm)]),_meta:D.record(D.string(),D.unknown()).optional()}),Fm=Ff.extend({messages:D.array(Pm),modelPreferences:km.optional(),systemPrompt:D.string().optional(),includeContext:D.enum([`none`,`thisServer`,`allServers`]).optional(),temperature:D.number().optional(),maxTokens:D.number().int(),stopSequences:D.array(D.string()).optional(),metadata:Of.optional(),tools:D.array(gm).optional(),toolChoice:Am.optional()}),Im=If.extend({method:D.literal(`sampling/createMessage`),params:Fm}),Lm=zf.extend({model:D.string(),stopReason:D.optional(D.enum([`endTurn`,`stopSequence`,`maxTokens`]).or(D.string())),role:Np,content:Mm}),Rm=zf.extend({model:D.string(),stopReason:D.optional(D.enum([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(D.string())),role:Np,content:D.union([Nm,D.array(Nm)])}),zm=D.object({type:D.literal(`boolean`),title:D.string().optional(),description:D.string().optional(),default:D.boolean().optional()}),Bm=D.object({type:D.literal(`string`),title:D.string().optional(),description:D.string().optional(),minLength:D.number().optional(),maxLength:D.number().optional(),format:D.enum([`email`,`uri`,`date`,`date-time`]).optional(),default:D.string().optional()}),Vm=D.object({type:D.enum([`number`,`integer`]),title:D.string().optional(),description:D.string().optional(),minimum:D.number().optional(),maximum:D.number().optional(),default:D.number().optional()}),Hm=D.object({type:D.literal(`string`),title:D.string().optional(),description:D.string().optional(),enum:D.array(D.string()),default:D.string().optional()}),Um=D.object({type:D.literal(`string`),title:D.string().optional(),description:D.string().optional(),oneOf:D.array(D.object({const:D.string(),title:D.string()})),default:D.string().optional()}),Wm=D.object({type:D.literal(`string`),title:D.string().optional(),description:D.string().optional(),enum:D.array(D.string()),enumNames:D.array(D.string()).optional(),default:D.string().optional()}),Gm=D.union([Hm,Um]),Km=D.object({type:D.literal(`array`),title:D.string().optional(),description:D.string().optional(),minItems:D.number().optional(),maxItems:D.number().optional(),items:D.object({type:D.literal(`string`),enum:D.array(D.string())}),default:D.array(D.string()).optional()}),qm=D.object({type:D.literal(`array`),title:D.string().optional(),description:D.string().optional(),minItems:D.number().optional(),maxItems:D.number().optional(),items:D.object({anyOf:D.array(D.object({const:D.string(),title:D.string()}))}),default:D.array(D.string()).optional()}),Jm=D.union([Km,qm]),Ym=D.union([Wm,Gm,Jm]),Xm=D.union([Ym,zm,Bm,Vm]),Zm=Ff.extend({mode:D.literal(`form`).optional(),message:D.string(),requestedSchema:D.object({type:D.literal(`object`),properties:D.record(D.string(),Xm),required:D.array(D.string()).optional()})}),Qm=Ff.extend({mode:D.literal(`url`),message:D.string(),elicitationId:D.string(),url:D.string().url()}),$m=D.union([Zm,Qm]),eh=If.extend({method:D.literal(`elicitation/create`),params:$m}),th=Lf.extend({elicitationId:D.string()}),nh=Rf.extend({method:D.literal(`notifications/elicitation/complete`),params:th}),rh=zf.extend({action:D.enum([`accept`,`decline`,`cancel`]),content:D.preprocess(e=>e===null?void 0:e,D.record(D.string(),D.union([D.string(),D.number(),D.boolean(),D.array(D.string())])).optional())}),ih=D.object({type:D.literal(`ref/resource`),uri:D.string()}),ah=D.object({type:D.literal(`ref/prompt`),name:D.string()}),oh=Pf.extend({ref:D.union([ah,ih]),argument:D.object({name:D.string(),value:D.string()}),context:D.object({arguments:D.record(D.string(),D.string()).optional()}).optional()}),sh=If.extend({method:D.literal(`completion/complete`),params:oh}),ch=zf.extend({completion:D.looseObject({values:D.array(D.string()).max(100),total:D.optional(D.number().int()),hasMore:D.optional(D.boolean())})}),lh=D.object({uri:D.string().startsWith(`file://`),name:D.string().optional(),_meta:D.record(D.string(),D.unknown()).optional()}),uh=If.extend({method:D.literal(`roots/list`),params:Pf.optional()}),dh=zf.extend({roots:D.array(lh)}),fh=Rf.extend({method:D.literal(`notifications/roots/list_changed`),params:Lf.optional()}),ph=D.union([lp,ap,sh,Tm,rm,em,Lp,zp,Up,qp,Yp,xm,_m,xp,Cp,Tp,Dp]),mh=D.union([Jf,fp,cp,fh,bp]),D.union([Kf,Lm,Rm,rh,dh,Sp,Ep,vp]),hh=D.union([lp,Im,eh,uh,xp,Cp,Tp,Dp]),gh=D.union([Jf,fp,Dm,Zp,Gp,Sm,pm,bp,nh]),D.union([Kf,sp,ch,fm,tm,Rp,Bp,Wp,ym,vm,Sp,Ep,vp]),_h={ping:Kf,initialize:sp,"completion/complete":ch,"logging/setLevel":Kf,"prompts/get":fm,"prompts/list":tm,"resources/list":Rp,"resources/templates/list":Bp,"resources/read":Wp,"resources/subscribe":Kf,"resources/unsubscribe":Kf,"tools/call":D.union([ym,vp]),"tools/list":vm,"sampling/createMessage":D.union([Rm,vp]),"elicitation/create":D.union([rh,vp]),"roots/list":dh,"tasks/get":Sp,"tasks/result":zf,"tasks/list":Ep,"tasks/cancel":Op},vh=Od([...ph.options,...hh.options]),yh=Od([...mh.options,...gh.options]),bh=e=>Vf.safeParse(e).success,xh=e=>Hf.safeParse(e).success,Sh=e=>Uf.safeParse(e).success,Ch=e=>Wf.safeParse(e).success,wh=e=>Ff.safeParse(e).success,Th=e=>ap.safeParse(e).success,Eh=e=>cp.safeParse(e).success,Dh=class{_taskStore;_taskMessageQueue;_taskProgressTokens=new Map;_requestResolvers=new Map;_options;_host;constructor(e){this._options=e,this._taskStore=e.taskStore,this._taskMessageQueue=e.taskMessageQueue}bind(e){this._host=e,this._taskStore&&(e.registerHandler(`tasks/get`,async(e,t)=>{let n=e.params;return{...await this.handleGetTask(n.taskId,t.sessionId)}}),e.registerHandler(`tasks/result`,async(t,n)=>{let r=t.params;return await this.handleGetTaskPayload(r.taskId,n.sessionId,n.mcpReq.signal,async t=>{await e.sendOnResponseStream(t,n.mcpReq.id)})}),e.registerHandler(`tasks/list`,async(e,t)=>{let n=e.params;return await this.handleListTasks(n?.cursor,t.sessionId)}),e.registerHandler(`tasks/cancel`,async(e,t)=>{let n=e.params;return await this.handleCancelTask(n.taskId,t.sessionId)}))}get _requireHost(){if(!this._host)throw new U(H.InternalError,`TaskManager is not bound to a Protocol host — call bind() first`);return this._host}get taskStore(){return this._taskStore}get _requireTaskStore(){if(!this._taskStore)throw new U(H.InternalError,`TaskStore is not configured`);return this._taskStore}get taskMessageQueue(){return this._taskMessageQueue}async*requestStream(e,t,n){let r=this._requireHost,{task:i}=n??{};if(!i){try{yield{type:`result`,result:await r.request(e,t,n)}}catch(e){yield{type:`error`,error:e instanceof Error?e:Error(String(e))}}return}let a;try{let i=await r.request(e,vp,n);if(i.task)a=i.task.taskId,yield{type:`taskCreated`,task:i.task};else throw new U(H.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:a},n);if(yield{type:`taskStatus`,task:e},Fd(e.status)){switch(e.status){case`completed`:yield{type:`result`,result:await this.getTaskResult({taskId:a},t,n)};break;case`failed`:yield{type:`error`,error:new U(H.InternalError,`Task ${a} failed`)};break;case`cancelled`:yield{type:`error`,error:new U(H.InternalError,`Task ${a} was cancelled`)}}return}if(e.status===`input_required`){yield{type:`result`,result:await this.getTaskResult({taskId:a},t,n)};return}let r=e.pollInterval??this._options.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,r)),n?.signal?.throwIfAborted()}}catch(e){yield{type:`error`,error:e instanceof Error?e:Error(String(e))}}}async getTask(e,t){return this._requireHost.request({method:`tasks/get`,params:e},Sp,t)}async getTaskResult(e,t,n){return this._requireHost.request({method:`tasks/result`,params:e},t,n)}async listTasks(e,t){return this._requireHost.request({method:`tasks/list`,params:e},Ep,t)}async cancelTask(e,t){return this._requireHost.request({method:`tasks/cancel`,params:e},Op,t)}async handleGetTask(e,t){let n=await this._requireTaskStore.getTask(e,t);if(!n)throw new U(H.InvalidParams,`Failed to retrieve task: Task not found`);return n}async handleGetTaskPayload(e,t,n,r){let i=async()=>{if(this._taskMessageQueue){let n;for(;n=await this._taskMessageQueue.dequeue(e,t);){if(n.type===`response`||n.type===`error`){let e=n.message,t=e.id,r=this._requestResolvers.get(t);if(r){if(this._requestResolvers.delete(t),n.type===`response`)r(e);else{let t=e;r(new U(t.error.code,t.error.message,t.error.data))}}else{let e=n.type===`response`?`Response`:`Error`;this._host?.reportError(Error(`${e} handler missing for request ${t}`))}continue}await r(n.message)}}let a=await this._requireTaskStore.getTask(e,t);if(!a)throw new U(H.InvalidParams,`Task not found: ${e}`);if(!Fd(a.status))return await this._waitForTaskUpdate(a.pollInterval,n),await i();let o=await this._requireTaskStore.getTaskResult(e,t);return await this._clearTaskQueue(e),{...o,_meta:{...o._meta,[bf]:{taskId:e}}}};return await i()}async handleListTasks(e,t){try{let{tasks:n,nextCursor:r}=await this._requireTaskStore.listTasks(e,t);return{tasks:n,nextCursor:r,_meta:{}}}catch(e){throw new U(H.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}async handleCancelTask(e,t){try{let n=await this._requireTaskStore.getTask(e,t);if(!n)throw new U(H.InvalidParams,`Task not found: ${e}`);if(Fd(n.status))throw new U(H.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._requireTaskStore.updateTaskStatus(e,`cancelled`,`Client cancelled task execution.`,t),await this._clearTaskQueue(e);let r=await this._requireTaskStore.getTask(e,t);if(!r)throw new U(H.InvalidParams,`Task not found after cancellation: ${e}`);return{_meta:{},...r}}catch(e){throw e instanceof U?e:new U(H.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}prepareOutboundRequest(e,t,n,r,i){let{task:a,relatedTask:o}=t??{};a&&(e.params={...e.params,task:a}),o&&(e.params={...e.params,_meta:{...e.params?._meta,[bf]:o}});let s=o?.taskId;return s?(this._requestResolvers.set(n,r),this._enqueueTaskMessage(s,{type:`request`,message:e,timestamp:Date.now()}).catch(e=>{i(e)}),!0):!1}extractInboundTaskContext(e,t){let n=(e.params?._meta)?.[bf]?.taskId,r=wh(e.params)?e.params.task:void 0,i;return this._taskStore&&(i={id:n,store:this.createRequestTaskStore(e,t),requestedTtl:r?.ttl}),!n&&!r&&!i?{}:{relatedTaskId:n,taskCreationParams:r,taskContext:i}}wrapSendNotification(e,t){return async n=>{await t(n,{relatedTask:{taskId:e}})}}wrapSendRequest(e,t,n){return async(r,i,a)=>{let o={...a};e&&!o.relatedTask&&(o.relatedTask={taskId:e});let s=o.relatedTask?.taskId??e;return s&&t&&await t.updateTaskStatus(s,`input_required`),await n(r,i,o)}}handleResponse(e){let t=Number(e.id),n=this._requestResolvers.get(t);return n?(this._requestResolvers.delete(t),Sh(e)?n(e):n(new U(e.error.code,e.error.message,e.error.data)),!0):!1}shouldPreserveProgressHandler(e,t){if(Sh(e)&&e.result&&typeof e.result==`object`){let n=e.result;if(n.task&&typeof n.task==`object`){let e=n.task;if(typeof e.taskId==`string`)return this._taskProgressTokens.set(e.taskId,t),!0}}return!1}async routeNotification(e,t){let n=t?.relatedTask?.taskId;if(!n)return!1;let r={...e,jsonrpc:`2.0`,params:{...e.params,_meta:{...e.params?._meta,[bf]:t.relatedTask}}};return await this._enqueueTaskMessage(n,{type:`notification`,message:r,timestamp:Date.now()}),!0}async routeResponse(e,t,n){return!e||!this._taskMessageQueue?!1:(await(Ch(t)?this._enqueueTaskMessage(e,{type:`error`,message:t,timestamp:Date.now()},n):this._enqueueTaskMessage(e,{type:`response`,message:t,timestamp:Date.now()},n)),!0)}createRequestTaskStore(e,t){let n=this._requireTaskStore,r=this._host;return{createTask:async r=>{if(!e)throw Error(`No request provided`);return await n.createTask(r,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{let r=await n.getTask(e,t);if(!r)throw new U(H.InvalidParams,`Failed to retrieve task: Task not found`);return r},storeTaskResult:async(e,i,a)=>{await n.storeTaskResult(e,i,a,t);let o=await n.getTask(e,t);if(o){let t=bp.parse({method:`notifications/tasks/status`,params:o});await r?.notification(t),Fd(o.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>n.getTaskResult(e,t),updateTaskStatus:async(e,i,a)=>{let o=await n.getTask(e,t);if(!o)throw new U(H.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(Fd(o.status))throw new U(H.InvalidParams,`Cannot update task "${e}" from terminal status "${o.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(e,i,a,t);let s=await n.getTask(e,t);if(s){let t=bp.parse({method:`notifications/tasks/status`,params:s});await r?.notification(t),Fd(s.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}processInboundRequest(e,t){let n=this.extractInboundTaskContext(e,t.sessionId),r=n?.relatedTaskId,i=r?this.wrapSendNotification(r,t.sendNotification):e=>t.sendNotification(e),a=r?this.wrapSendRequest(r,n?.taskContext?.store,t.sendRequest):n?.taskContext?this.wrapSendRequest(``,n.taskContext.store,t.sendRequest):t.sendRequest,o=!!n?.taskCreationParams;return{taskContext:n?.taskContext,sendNotification:i,sendRequest:a,routeResponse:async e=>r?this.routeResponse(r,e,t.sessionId):!1,hasTaskCreationParams:o,validateInbound:o?()=>this._requireHost.assertTaskHandlerCapability(e.method):void 0}}processOutboundRequest(e,t,n,r,i){return this._requireHost.enforceStrictCapabilities&&t?.task&&this._requireHost.assertTaskCapability(e.method),{queued:this.prepareOutboundRequest(e,t,n,r,i)}}processInboundResponse(e,t){return this.handleResponse(e)?{consumed:!0,preserveProgress:!1}:{consumed:!1,preserveProgress:this.shouldPreserveProgressHandler(e,t)}}async processOutboundNotification(e,t){if(await this.routeNotification(e,t))return{queued:!0};let n={...e,jsonrpc:`2.0`};return t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta,[bf]:t.relatedTask}}}),{queued:!1,jsonrpcNotification:n}}onClose(){this._taskProgressTokens.clear(),this._requestResolvers.clear()}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw Error(`Cannot enqueue task message: taskStore and taskMessageQueue are not configured`);await this._taskMessageQueue.enqueue(e,t,n,this._options.maxTaskQueueSize)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,t);for(let t of n)if(t.type===`request`&&bh(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new U(H.InternalError,`Task cancelled or completed`)),this._requestResolvers.delete(n)):this._host?.reportError(Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let n=e??this._options.defaultTaskPollInterval??1e3;return new Promise((e,r)=>{if(t.aborted){r(new U(H.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new U(H.InvalidRequest,`Request cancelled`))},{once:!0})})}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);t!==void 0&&(this._host?.removeProgressHandler(t),this._taskProgressTokens.delete(e))}},Oh=class extends Dh{constructor(){super({})}processInboundRequest(e,t){let n=wh(e.params)&&!!e.params.task;return{taskContext:void 0,sendNotification:e=>t.sendNotification(e),sendRequest:t.sendRequest,routeResponse:async()=>!1,hasTaskCreationParams:n,validateInbound:n?()=>this._requireHost.assertTaskHandlerCapability(e.method):void 0}}async processOutboundNotification(e,t){return{queued:!1,jsonrpcNotification:{...e,jsonrpc:`2.0`}}}},kh=6e4,Ah=class{_transport;_requestMessageId=0;_requestHandlers=new Map;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_taskManager;_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??yf,this._taskManager=e?.tasks?new Dh(e.tasks):new Oh,this._bindTaskManager(),this.setNotificationHandler(`notifications/cancelled`,e=>{this._oncancel(e)}),this.setNotificationHandler(`notifications/progress`,e=>{this._onprogress(e)}),this.setRequestHandler(`ping`,e=>({}))}get taskManager(){return this._taskManager}_bindTaskManager(){let e=this._taskManager,t={request:(e,t,n)=>this._requestWithSchema(e,t,n),notification:(e,t)=>this.notification(e,t),reportError:e=>this._onerror(e),removeProgressHandler:e=>this._progressHandlers.delete(e),registerHandler:(e,t)=>{let n=kd(e);this._requestHandlers.set(e,(e,r)=>(n.parse(e),t(e,r)))},sendOnResponseStream:async(e,t)=>{await this._transport?.send(e,{relatedRequestId:t})},enforceStrictCapabilities:this._options?.enforceStrictCapabilities===!0,assertTaskCapability:e=>this.assertTaskCapability(e),assertTaskHandlerCapability:e=>this.assertTaskHandlerCapability(e)};e.bind(t)}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new V(B.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{try{t?.()}finally{this._onclose()}};let n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{r?.(e,t),Sh(e)||Ch(e)?this._onresponse(e):bh(e)?this._onrequest(e,t):xh(e)?this._onnotification(e):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},e.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskManager.onClose(),this._pendingDebouncedNotifications.clear();for(let e of this._timeoutInfo.values())clearTimeout(e.timeoutId);this._timeoutInfo.clear();let t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let n=new V(B.ConnectionClosed,`Connection closed`);this._transport=void 0;try{this.onclose?.()}finally{for(let t of e.values())t(n);for(let e of t.values())e.abort(n)}}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,r=this._transport,i={sessionId:r?.sessionId,sendNotification:(t,n)=>this.notification(t,{...n,relatedRequestId:e.id}),sendRequest:(t,n,r)=>this._requestWithSchema(t,n,{...r,relatedRequestId:e.id})},a=this._taskManager.processInboundRequest(e,i),o=a.sendNotification,s=a.sendRequest,c=a.taskContext,l=a.routeResponse,u=[];if(a.validateInbound&&u.push(a.validateInbound),n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:H.MethodNotFound,message:`Method not found`}};l(t).then(e=>{e||r?.send(t).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)))}).catch(e=>this._onerror(Error(`Failed to enqueue error response: ${e}`)));return}let d=new AbortController;this._requestHandlerAbortControllers.set(e.id,d);let f={sessionId:r?.sessionId,mcpReq:{id:e.id,method:e.method,_meta:e.params?._meta,signal:d.signal,send:(e,t)=>s(e,Dd(e.method),t),notify:o},http:t?.authInfo?{authInfo:t.authInfo}:void 0,task:c},p=this.buildContext(f,t);Promise.resolve().then(()=>{for(let e of u)e()}).then(()=>n(e,p)).then(async t=>{if(d.signal.aborted)return;let n={result:t,jsonrpc:`2.0`,id:e.id};await l(n)||await r?.send(n)},async t=>{if(d.signal.aborted)return;let n={jsonrpc:`2.0`,id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:H.InternalError,message:t.message??`Internal error`,...t.data!==void 0&&{data:t.data}}};await l(n)||await r?.send(n)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===d&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),o=this._timeoutInfo.get(r);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(e);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._taskManager.processInboundResponse(e,t);if(n.consumed)return;let r=n.preserveProgress,i=this._responseHandlers.get(t);if(i===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t),r||this._progressHandlers.delete(t),Sh(e)?i(e):i(U.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(e,t){let n=Dd(e.method);return this._requestWithSchema(e,n,t)}_requestWithSchema(e,t,n){let{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}=n??{},o,s;return new Promise((c,l)=>{let u=e=>{l(e)};if(!this._transport){u(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method)}catch(e){u(e);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++;s=d;let f={...e,jsonrpc:`2.0`,id:d};n?.onprogress&&(this._progressHandlers.set(d,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta,progressToken:d}});let p=e=>{this._progressHandlers.delete(d),this._transport?.send({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:d,reason:String(e)}},{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))),l(e instanceof V?e:new V(B.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=Pd(t,e.result);n.success?c(n.data):l(n.error)}catch(e){l(e)}}}),o=()=>p(n?.signal?.reason),n?.signal?.addEventListener(`abort`,o,{once:!0});let m=n?.timeout??6e4;this._setupTimeout(d,m,n?.maxTotalTimeout,()=>p(new V(B.RequestTimeout,`Request timed out`,{timeout:m})),n?.resetTimeoutOnProgress??!1);let h=e=>{let t=this._responseHandlers.get(d);t?t(e):this._onerror(Error(`Response handler missing for side-channeled request ${d}`))},g=!1;try{this._taskManager.processOutboundRequest(f,n,d,h,e=>{this._progressHandlers.delete(d),l(e)}).queued&&(g=!0)}catch(e){this._progressHandlers.delete(d),l(e);return}g||this._transport.send(f,{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>{this._progressHandlers.delete(d),l(e)})}).finally(()=>{o&&n?.signal?.removeEventListener(`abort`,o),s!==void 0&&(this._responseHandlers.delete(s),this._cleanupTimeout(s))})}async notification(e,t){if(!this._transport)throw new V(B.NotConnected,`Not connected`);this.assertNotificationCapability(e.method);let n=await this._taskManager.processOutboundNotification(e,t),r=n.queued,i=n.queued?void 0:n.jsonrpcNotification;if(!r){if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(e.method),this._transport&&this._transport?.send(i,t).catch(e=>this._onerror(e))});return}await this._transport.send(i,t)}}setRequestHandler(e,t){this.assertRequestHandlerCapability(e);let n=kd(e);this._requestHandlers.set(e,(e,r)=>{let i=n.parse(e);return Promise.resolve(t(i,r))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let n=Ad(e);this._notificationHandlers.set(e,e=>{let r=n.parse(e);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}},jh=class{_buffer;append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){for(;this._buffer;){let e=this._buffer.indexOf(`
176
- `);if(e===-1)return null;let t=this._buffer.toString(`utf8`,0,e).replace(/\r$/,``);this._buffer=this._buffer.subarray(e+1);try{return Vd(t)}catch(e){if(e instanceof SyntaxError)continue;throw e}}return null}clear(){this._buffer=void 0}},Mh=/^[A-Za-z0-9._-]{1,128}$/,Nh=1e6,Ph=1e6,Fh=1e4,Ih=1e6,Lh=class e{static isTemplate(e){return/\{[^}\s]+\}/.test(e)}static validateLength(e,t,n){if(e.length>t)throw Error(`${n} exceeds maximum length of ${t} characters (got ${e.length})`)}template;parts;get variableNames(){return this.parts.flatMap(e=>typeof e==`string`?[]:e.names)}constructor(t){e.validateLength(t,Nh,`Template`),this.template=t,this.parts=this.parse(t)}toString(){return this.template}parse(t){let n=[],r=``,i=0,a=0;for(;i<t.length;)if(t[i]===`{`){r&&=(n.push(r),``);let o=t.indexOf(`}`,i);if(o===-1)throw Error(`Unclosed template expression`);if(a++,a>Fh)throw Error(`Template contains too many expressions (max ${Fh})`);let s=t.slice(i+1,o),c=this.getOperator(s),l=s.includes(`*`),u=this.getNames(s),d=u[0];for(let t of u)e.validateLength(t,Ph,`Variable name`);n.push({name:d,operator:c,names:u,exploded:l}),i=o+1}else r+=t[i],i++;return r&&n.push(r),n}getOperator(e){return[`+`,`#`,`.`,`/`,`?`,`&`].find(t=>e.startsWith(t))||``}getNames(e){let t=this.getOperator(e);return e.slice(t.length).split(`,`).map(e=>e.replace(`*`,``).trim()).filter(e=>e.length>0)}encodeValue(t,n){return e.validateLength(t,Ph,`Variable value`),n===`+`||n===`#`?encodeURI(t):encodeURIComponent(t)}expandPart(e,t){if(e.operator===`?`||e.operator===`&`){let n=e.names.map(n=>{let r=t[n];return r===void 0?``:`${n}=${Array.isArray(r)?r.map(t=>this.encodeValue(t,e.operator)).join(`,`):this.encodeValue(r.toString(),e.operator)}`}).filter(e=>e.length>0);return n.length===0?``:(e.operator===`?`?`?`:`&`)+n.join(`&`)}if(e.names.length>1){let n=e.names.map(e=>t[e]).filter(e=>e!==void 0);return n.length===0?``:n.map(e=>Array.isArray(e)?e[0]:e).join(`,`)}let n=t[e.name];if(n===void 0)return``;let r=(Array.isArray(n)?n:[n]).map(t=>this.encodeValue(t,e.operator));switch(e.operator){case``:return r.join(`,`);case`+`:return r.join(`,`);case`#`:return`#`+r.join(`,`);case`.`:return`.`+r.join(`.`);case`/`:return`/`+r.join(`/`);default:return r.join(`,`)}}expand(e){let t=``,n=!1;for(let r of this.parts){if(typeof r==`string`){t+=r;continue}let i=this.expandPart(r,e);i&&(t+=(r.operator===`?`||r.operator===`&`)&&n?i.replace(`?`,`&`):i,(r.operator===`?`||r.operator===`&`)&&(n=!0))}return t}escapeRegExp(e){return e.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`)}partToRegExp(t){let n=[];for(let n of t.names)e.validateLength(n,Ph,`Variable name`);if(t.operator===`?`||t.operator===`&`){for(let e=0;e<t.names.length;e++){let r=t.names[e],i=e===0?`\\`+t.operator:`&`;n.push({pattern:i+this.escapeRegExp(r)+`=([^&]+)`,name:r})}return n}let r,i=t.name;switch(t.operator){case``:r=t.exploded?`([^/,]+(?:,[^/,]+)*)`:`([^/,]+)`;break;case`+`:case`#`:r=`(.+)`;break;case`.`:r=String.raw`\.([^/,]+)`;break;case`/`:r=`/`+(t.exploded?`([^/,]+(?:,[^/,]+)*)`:`([^/,]+)`);break;default:r=`([^/]+)`}return n.push({pattern:r,name:i}),n}match(t){e.validateLength(t,Nh,`URI`);let n=`^`,r=[];for(let e of this.parts)if(typeof e==`string`)n+=this.escapeRegExp(e);else{let t=this.partToRegExp(e);for(let{pattern:i,name:a}of t)n+=i,r.push({name:a,exploded:e.exploded})}n+=`$`,e.validateLength(n,Ih,`Generated regex pattern`);let i=new RegExp(n),a=t.match(i);if(!a)return null;let o={};for(let[e,t]of r.entries()){let{name:n,exploded:r}=t,i=a[e+1],s=n.replace(`*`,``);o[s]=r&&i.includes(`,`)?i.split(`,`):i}return o}},Rh=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var n=class extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw Error(`CodeGen: name must be a valid identifier`);this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=n;var r=class extends t{constructor(e){super(),this._items=typeof e==`string`?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===``||e===`""`}get str(){return this._str??=this._items.reduce((e,t)=>`${e}${t}`,``)}get names(){return this._names??=this._items.reduce((e,t)=>(t instanceof n&&(e[t.str]=(e[t.str]||0)+1),e),{})}};e._Code=r,e.nil=new r(``);function i(e,...t){let n=[e[0]],i=0;for(;i<t.length;)s(n,t[i]),n.push(e[++i]);return new r(n)}e._=i;let a=new r(`+`);function o(e,...t){let n=[p(e[0])],i=0;for(;i<t.length;)n.push(a),s(n,t[i]),n.push(a,p(e[++i]));return c(n),new r(n)}e.str=o;function s(e,t){t instanceof r?e.push(...t._items):t instanceof n?e.push(t):e.push(d(t))}e.addCodeArg=s;function c(e){let t=1;for(;t<e.length-1;){if(e[t]===a){let n=l(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]=`+`}t++}}function l(e,t){if(t===`""`)return e;if(e===`""`)return t;if(typeof e==`string`)return t instanceof n||e[e.length-1]!==`"`?void 0:typeof t==`string`?t[0]===`"`?e.slice(0,-1)+t.slice(1):void 0:`${e.slice(0,-1)}${t}"`;if(typeof t==`string`&&t[0]===`"`&&!(e instanceof n))return`"${e}${t.slice(1)}`}function u(e,t){return t.emptyStr()?e:e.emptyStr()?t:o`${e}${t}`}e.strConcat=u;function d(e){return typeof e==`number`||typeof e==`boolean`||e===null?e:p(Array.isArray(e)?e.join(`,`):e)}function f(e){return new r(p(e))}e.stringify=f;function p(e){return JSON.stringify(e).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}e.safeStringify=p;function m(t){return typeof t==`string`&&e.IDENTIFIER.test(t)?new r(`.${t}`):i`[${t}]`}e.getProperty=m;function h(t){if(typeof t==`string`&&e.IDENTIFIER.test(t))return new r(`${t}`);throw Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}e.getEsmExportName=h;function g(e){return new r(e.toString())}e.regexpCode=g})),zh=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=Rh();var n=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},r;(function(e){e[e.Started=0]=`Started`,e[e.Completed=1]=`Completed`})(r||(e.UsedValueState=r={})),e.varKinds={const:new t.Name(`const`),let:new t.Name(`let`),var:new t.Name(`var`)};var i=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){if((this._parent?._prefixes)?.has(e)||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};e.Scope=i;var a=class extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,t._)`.${new t.Name(n)}[${r}]`}};e.ValueScopeName=a;let o=(0,t._)`\n`;e.ValueScope=class extends i{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?o:t.nil}}get(){return this._scope}name(e){return new a(e,this._newName(e))}value(e,t){if(t.ref===void 0)throw Error(`CodeGen: ref must be passed in value`);let n=this.toName(e),{prefix:r}=n,i=t.key??t.ref,a=this._values[r];if(a){let e=a.get(i);if(e)return e}else a=this._values[r]=new Map;a.set(i,n);let o=this._scope[r]||(this._scope[r]=[]),s=o.length;return o[s]=t.ref,n.setValue(t,{property:r,itemIndex:s}),n}getValue(e,t){let n=this._values[e];if(n)return n.get(t)}scopeRefs(e,n=this._values){return this._reduceValues(n,n=>{if(n.scopePath===void 0)throw Error(`CodeGen: name "${n}" has no value`);return(0,t._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,e=>{if(e.value===void 0)throw Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,n)}_reduceValues(i,a,o={},s){let c=t.nil;for(let l in i){let u=i[l];if(!u)continue;let d=o[l]=o[l]||new Map;u.forEach(i=>{if(d.has(i))return;d.set(i,r.Started);let o=a(i);if(o){let n=this.opts.es5?e.varKinds.var:e.varKinds.const;c=(0,t._)`${c}${n} ${i} = ${o};${this.opts._n}`}else if(o=s?.(i))c=(0,t._)`${c}${o}${this.opts._n}`;else throw new n(i);d.set(i,r.Completed)})}return c}}})),W=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;let t=Rh(),n=zh();var r=Rh();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}});var i=zh();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return i.varKinds}}),e.operators={GT:new t._Code(`>`),GTE:new t._Code(`>=`),LT:new t._Code(`<`),LTE:new t._Code(`<=`),EQ:new t._Code(`===`),NEQ:new t._Code(`!==`),NOT:new t._Code(`!`),OR:new t._Code(`||`),AND:new t._Code(`&&`),ADD:new t._Code(`+`)};var a=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},o=class extends a{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let r=e?n.varKinds.var:this.varKind,i=this.rhs===void 0?``:` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=O(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},s=class extends a{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof t.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=O(this.rhs,e,n),this}get names(){return D(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},c=class extends s{constructor(e,t,n,r){super(e,n,r),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},l=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},u=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},d=class extends a{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},f=class extends a{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=O(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},p=class extends a{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),``)}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,r=n.length;for(;r--;){let i=n[r];i.optimizeNames(e,t)||(k(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>E(e,t.names),{})}},m=class extends p{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},h=class extends p{},g=class extends m{};g.kind=`else`;var _=class e extends m{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+=`else `+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let n=this.else;if(n){let e=n.optimizeNodes();n=this.else=Array.isArray(e)?new g(e):e}if(n)return t===!1?n instanceof e?n:n.nodes:this.nodes.length?this:new e(te(t),n instanceof e?[n]:n.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(e,t){if(this.else=this.else?.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=O(this.condition,e,t),this}get names(){let e=super.names;return D(e,this.condition),this.else&&E(e,this.else.names),e}};_.kind=`if`;var v=class extends m{};v.kind=`for`;var y=class extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=O(this.iteration,e,t),this}get names(){return E(super.names,this.iteration.names)}},b=class extends v{constructor(e,t,n,r){super(),this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){let t=e.es5?n.varKinds.var:this.varKind,{name:r,from:i,to:a}=this;return`for(${t} ${r}=${i}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){return D(D(super.names,this.from),this.to)}},x=class extends v{constructor(e,t,n,r){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=O(this.iterable,e,t),this}get names(){return E(super.names,this.iterable.names)}},S=class extends m{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?`async `:``}function ${this.name}(${this.args})`+super.render(e)}};S.kind=`func`;var C=class extends p{render(e){return`return `+super.render(e)}};C.kind=`return`;var w=class extends m{render(e){let t=`try`+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)==null||e.optimizeNodes(),(t=this.finally)==null||t.optimizeNodes(),this}optimizeNames(e,t){var n,r;return super.optimizeNames(e,t),(n=this.catch)==null||n.optimizeNames(e,t),(r=this.finally)==null||r.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&E(e,this.catch.names),this.finally&&E(e,this.finally.names),e}},T=class extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};T.kind=`catch`;var ee=class extends m{render(e){return`finally`+super.render(e)}};ee.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
177
- `:``},this._extScope=e,this._scope=new n.Scope({parent:e}),this._nodes=[new h]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,r){let i=this._scope.toName(t);return n!==void 0&&r&&(this._constants[i.str]=n),this._leafNode(new o(e,i,n)),i}const(e,t,r){return this._def(n.varKinds.const,e,t,r)}let(e,t,r){return this._def(n.varKinds.let,e,t,r)}var(e,t,r){return this._def(n.varKinds.var,e,t,r)}assign(e,t,n){return this._leafNode(new s(e,t,n))}add(t,n){return this._leafNode(new c(t,e.operators.ADD,n))}code(e){return typeof e==`function`?e():e!==t.nil&&this._leafNode(new f(e)),this}object(...e){let n=[`{`];for(let[r,i]of e)n.length>1&&n.push(`,`),n.push(r),(r!==i||this.opts.es5)&&(n.push(`:`),(0,t.addCodeArg)(n,i));return n.push(`}`),new t._Code(n)}if(e,t,n){if(this._blockNode(new _(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw Error(`CodeGen: "else" body without "then" body`);return this}elseIf(e){return this._elseNode(new _(e))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(_,g)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new y(e),t)}forRange(e,t,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.let){let o=this._scope.toName(e);return this._for(new b(a,o,t,r),()=>i(o))}forOf(e,r,i,a=n.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let e=r instanceof t.Name?r:this.var(`_arr`,r);return this.forRange(`_i`,0,(0,t._)`${e}.length`,n=>{this.var(o,(0,t._)`${e}[${n}]`),i(o)})}return this._for(new x(`of`,a,o,r),()=>i(o))}forIn(e,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,t._)`Object.keys(${r})`,i);let o=this._scope.toName(e);return this._for(new x(`in`,a,o,r),()=>i(o))}endFor(){return this._endBlockNode(v)}label(e){return this._leafNode(new l(e))}break(e){return this._leafNode(new u(e))}return(e){let t=new C;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error(`CodeGen: "return" should have one node`);return this._endBlockNode(C)}try(e,t,n){if(!t&&!n)throw Error(`CodeGen: "try" without "catch" and "finally"`);let r=new w;if(this._blockNode(r),this.code(e),t){let e=this.name(`e`);this._currNode=r.catch=new T(e),t(e)}return n&&(this._currNode=r.finally=new ee,this.code(n)),this._endBlockNode(T,ee)}throw(e){return this._leafNode(new d(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error(`CodeGen: not in self-balancing block`);let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,n=t.nil,r,i){return this._blockNode(new S(e,n,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(S)}optimize(e=1){for(;e-->0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof _))throw Error(`CodeGen: "else" without "if"`);return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};function E(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function D(e,n){return n instanceof t._CodeOrName?E(e,n.names):e}function O(e,n,r){if(e instanceof t.Name)return i(e);if(!a(e))return e;return new t._Code(e._items.reduce((e,n)=>(n instanceof t.Name&&(n=i(n)),n instanceof t._Code?e.push(...n._items):e.push(n),e),[]));function i(e){let t=r[e.str];return t===void 0||n[e.str]!==1?e:(delete n[e.str],t)}function a(e){return e instanceof t._Code&&e._items.some(e=>e instanceof t.Name&&n[e.str]===1&&r[e.str]!==void 0)}}function k(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function te(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${ae(e)}`}e.not=te;let ne=ie(e.operators.AND);function re(...e){return e.reduce(ne)}e.and=re;let A=ie(e.operators.OR);function j(...e){return e.reduce(A)}e.or=j;function ie(e){return(n,r)=>n===t.nil?r:r===t.nil?n:(0,t._)`${ae(n)} ${e} ${ae(r)}`}function ae(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),G=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.checkStrictMode=e.getErrorPath=e.Type=e.useFunc=e.setEvaluated=e.evaluatedPropsToName=e.mergeEvaluated=e.eachItem=e.unescapeJsonPointer=e.escapeJsonPointer=e.escapeFragment=e.unescapeFragment=e.schemaRefOrVal=e.schemaHasRulesButRef=e.schemaHasRules=e.checkUnknownRules=e.alwaysValidSchema=e.toHash=void 0;let t=W(),n=Rh();function r(e){let t={};for(let n of e)t[n]=!0;return t}e.toHash=r;function i(e,t){return typeof t==`boolean`?t:Object.keys(t).length===0||(a(e,t),!o(t,e.self.RULES.all))}e.alwaysValidSchema=i;function a(e,t=e.schema){let{opts:n,self:r}=e;if(!n.strictSchema||typeof t==`boolean`)return;let i=r.RULES.keywords;for(let n in t)i[n]||x(e,`unknown keyword: "${n}"`)}e.checkUnknownRules=a;function o(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(t[n])return!0;return!1}e.schemaHasRules=o;function s(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(n!==`$ref`&&t.all[n])return!0;return!1}e.schemaHasRulesButRef=s;function c({topSchemaRef:e,schemaPath:n},r,i,a){if(!a){if(typeof r==`number`||typeof r==`boolean`)return r;if(typeof r==`string`)return(0,t._)`${r}`}return(0,t._)`${e}${n}${(0,t.getProperty)(i)}`}e.schemaRefOrVal=c;function l(e){return f(decodeURIComponent(e))}e.unescapeFragment=l;function u(e){return encodeURIComponent(d(e))}e.escapeFragment=u;function d(e){return typeof e==`number`?`${e}`:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}e.escapeJsonPointer=d;function f(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}e.unescapeJsonPointer=f;function p(e,t){if(Array.isArray(e))for(let n of e)t(n);else t(e)}e.eachItem=p;function m({mergeNames:e,mergeToName:n,mergeValues:r,resultToName:i}){return(a,o,s,c)=>{let l=s===void 0?o:s instanceof t.Name?(o instanceof t.Name?e(a,o,s):n(a,o,s),s):o instanceof t.Name?(n(a,s,o),o):r(o,s);return c===t.Name&&!(l instanceof t.Name)?i(a,l):l}}e.mergeEvaluated={props:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>{e.if((0,t._)`${n} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,t._)`${r} || {}`).code((0,t._)`Object.assign(${r}, ${n})`))}),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>{n===!0?e.assign(r,!0):(e.assign(r,(0,t._)`${r} || {}`),g(e,r,n))}),mergeValues:(e,t)=>e===!0||{...e,...t},resultToName:h}),items:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>e.assign(r,(0,t._)`${n} === true ? true : ${r} > ${n} ? ${r} : ${n}`)),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>e.assign(r,n===!0||(0,t._)`${r} > ${n} ? ${r} : ${n}`)),mergeValues:(e,t)=>e===!0||Math.max(e,t),resultToName:(e,t)=>e.var(`items`,t)})};function h(e,n){if(n===!0)return e.var(`props`,!0);let r=e.var(`props`,(0,t._)`{}`);return n!==void 0&&g(e,r,n),r}e.evaluatedPropsToName=h;function g(e,n,r){Object.keys(r).forEach(r=>e.assign((0,t._)`${n}${(0,t.getProperty)(r)}`,!0))}e.setEvaluated=g;let _={};function v(e,t){return e.scopeValue(`func`,{ref:t,code:_[t.code]||(_[t.code]=new n._Code(t.code))})}e.useFunc=v;var y;(function(e){e[e.Num=0]=`Num`,e[e.Str=1]=`Str`})(y||(e.Type=y={}));function b(e,n,r){if(e instanceof t.Name){let i=n===y.Num;return r?i?(0,t._)`"[" + ${e} + "]"`:(0,t._)`"['" + ${e} + "']"`:i?(0,t._)`"/" + ${e}`:(0,t._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,t.getProperty)(e).toString():`/`+d(e)}e.getErrorPath=b;function x(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw Error(t);e.self.logger.warn(t)}}e.checkStrictMode=x})),Bh=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W();e.default={data:new t.Name(`data`),valCxt:new t.Name(`valCxt`),instancePath:new t.Name(`instancePath`),parentData:new t.Name(`parentData`),parentDataProperty:new t.Name(`parentDataProperty`),rootData:new t.Name(`rootData`),dynamicAnchors:new t.Name(`dynamicAnchors`),vErrors:new t.Name(`vErrors`),errors:new t.Name(`errors`),this:new t.Name(`this`),self:new t.Name(`self`),scope:new t.Name(`scope`),json:new t.Name(`json`),jsonPos:new t.Name(`jsonPos`),jsonLen:new t.Name(`jsonLen`),jsonPart:new t.Name(`jsonPart`)}})),Vh=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;let t=W(),n=G(),r=Bh();e.keywordError={message:({keyword:e})=>(0,t.str)`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:n})=>n?(0,t.str)`"${e}" keyword must be ${n} ($data)`:(0,t.str)`"${e}" keyword is invalid ($data)`};function i(n,r=e.keywordError,i,a){let{it:o}=n,{gen:s,compositeRule:u,allErrors:f}=o,p=d(n,r,i);a??(u||f)?c(s,p):l(o,(0,t._)`[${p}]`)}e.reportError=i;function a(t,n=e.keywordError,i){let{it:a}=t,{gen:o,compositeRule:s,allErrors:u}=a;c(o,d(t,n,i)),s||u||l(a,r.default.vErrors)}e.reportExtraError=a;function o(e,n){e.assign(r.default.errors,n),e.if((0,t._)`${r.default.vErrors} !== null`,()=>e.if(n,()=>e.assign((0,t._)`${r.default.vErrors}.length`,n),()=>e.assign(r.default.vErrors,null)))}e.resetErrorsCount=o;function s({gen:e,keyword:n,schemaValue:i,data:a,errsCount:o,it:s}){if(o===void 0)throw Error(`ajv implementation error`);let c=e.name(`err`);e.forRange(`i`,o,r.default.errors,o=>{e.const(c,(0,t._)`${r.default.vErrors}[${o}]`),e.if((0,t._)`${c}.instancePath === undefined`,()=>e.assign((0,t._)`${c}.instancePath`,(0,t.strConcat)(r.default.instancePath,s.errorPath))),e.assign((0,t._)`${c}.schemaPath`,(0,t.str)`${s.errSchemaPath}/${n}`),s.opts.verbose&&(e.assign((0,t._)`${c}.schema`,i),e.assign((0,t._)`${c}.data`,a))})}e.extendErrors=s;function c(e,n){let i=e.const(`err`,n);e.if((0,t._)`${r.default.vErrors} === null`,()=>e.assign(r.default.vErrors,(0,t._)`[${i}]`),(0,t._)`${r.default.vErrors}.push(${i})`),e.code((0,t._)`${r.default.errors}++`)}function l(e,n){let{gen:r,validateName:i,schemaEnv:a}=e;a.$async?r.throw((0,t._)`new ${e.ValidationError}(${n})`):(r.assign((0,t._)`${i}.errors`,n),r.return(!1))}let u={keyword:new t.Name(`keyword`),schemaPath:new t.Name(`schemaPath`),params:new t.Name(`params`),propertyName:new t.Name(`propertyName`),message:new t.Name(`message`),schema:new t.Name(`schema`),parentSchema:new t.Name(`parentSchema`)};function d(e,n,r){let{createErrors:i}=e.it;return i===!1?(0,t._)`{}`:f(e,n,r)}function f(e,t,n={}){let{gen:r,it:i}=e,a=[p(i,n),m(e,n)];return h(e,t,a),r.object(...a)}function p({errorPath:e},{instancePath:i}){let a=i?(0,t.str)`${e}${(0,n.getErrorPath)(i,n.Type.Str)}`:e;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,a)]}function m({keyword:e,it:{errSchemaPath:r}},{schemaPath:i,parentSchema:a}){let o=a?r:(0,t.str)`${r}/${e}`;return i&&(o=(0,t.str)`${o}${(0,n.getErrorPath)(i,n.Type.Str)}`),[u.schemaPath,o]}function h(e,{params:n,message:i},a){let{keyword:o,data:s,schemaValue:c,it:l}=e,{opts:d,propertyName:f,topSchemaRef:p,schemaPath:m}=l;a.push([u.keyword,o],[u.params,typeof n==`function`?n(e):n||(0,t._)`{}`]),d.messages&&a.push([u.message,typeof i==`function`?i(e):i]),d.verbose&&a.push([u.schema,c],[u.parentSchema,(0,t._)`${p}${m}`],[r.default.data,s]),f&&a.push([u.propertyName,f])}})),Hh=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=Vh(),n=W(),r=Bh(),i={message:`boolean schema is false`};function a(e){let{gen:t,schema:i,validateName:a}=e;i===!1?s(e,!1):typeof i==`object`&&i.$async===!0?t.return(r.default.data):(t.assign((0,n._)`${a}.errors`,null),t.return(!0))}e.topBoolOrEmptySchema=a;function o(e,t){let{gen:n,schema:r}=e;r===!1?(n.var(t,!1),s(e)):n.var(t,!0)}e.boolOrEmptySchema=o;function s(e,n){let{gen:r,data:a}=e,o={gen:r,keyword:`false schema`,data:a,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,t.reportError)(o,i,void 0,n)}})),Uh=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getRules=e.isJSONType=void 0;let t=new Set([`string`,`number`,`integer`,`boolean`,`null`,`object`,`array`]);function n(e){return typeof e==`string`&&t.has(e)}e.isJSONType=n;function r(){let e={number:{type:`number`,rules:[]},string:{type:`string`,rules:[]},array:{type:`array`,rules:[]},object:{type:`object`,rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}e.getRules=r})),Wh=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.shouldUseRule=e.shouldUseGroup=e.schemaHasRulesForType=void 0;function t({schema:e,self:t},r){let i=t.RULES.types[r];return i&&i!==!0&&n(e,i)}e.schemaHasRulesForType=t;function n(e,t){return t.rules.some(t=>r(e,t))}e.shouldUseGroup=n;function r(e,t){return e[t.keyword]!==void 0||t.definition.implements?.some(t=>e[t]!==void 0)}e.shouldUseRule=r})),Gh=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.reportTypeError=e.checkDataTypes=e.checkDataType=e.coerceAndCheckDataType=e.getJSONTypes=e.getSchemaTypes=e.DataType=void 0;let t=Uh(),n=Wh(),r=Vh(),i=W(),a=G();var o;(function(e){e[e.Correct=0]=`Correct`,e[e.Wrong=1]=`Wrong`})(o||(e.DataType=o={}));function s(e){let t=c(e.type);if(t.includes(`null`)){if(e.nullable===!1)throw Error(`type: null contradicts nullable: false`)}else{if(!t.length&&e.nullable!==void 0)throw Error(`"nullable" cannot be used without "type"`);e.nullable===!0&&t.push(`null`)}return t}e.getSchemaTypes=s;function c(e){let n=Array.isArray(e)?e:e?[e]:[];if(n.every(t.isJSONType))return n;throw Error(`type must be JSONType or JSONType[]: `+n.join(`,`))}e.getJSONTypes=c;function l(e,t){let{gen:r,data:i,opts:a}=e,s=d(t,a.coerceTypes),c=t.length>0&&!(s.length===0&&t.length===1&&(0,n.schemaHasRulesForType)(e,t[0]));if(c){let n=h(t,i,a.strictNumbers,o.Wrong);r.if(n,()=>{s.length?f(e,t,s):_(e)})}return c}e.coerceAndCheckDataType=l;let u=new Set([`string`,`number`,`integer`,`boolean`,`null`]);function d(e,t){return t?e.filter(e=>u.has(e)||t===`array`&&e===`array`):[]}function f(e,t,n){let{gen:r,data:a,opts:o}=e,s=r.let(`dataType`,(0,i._)`typeof ${a}`),c=r.let(`coerced`,(0,i._)`undefined`);o.coerceTypes===`array`&&r.if((0,i._)`${s} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>r.assign(a,(0,i._)`${a}[0]`).assign(s,(0,i._)`typeof ${a}`).if(h(t,a,o.strictNumbers),()=>r.assign(c,a))),r.if((0,i._)`${c} !== undefined`);for(let e of n)(u.has(e)||e===`array`&&o.coerceTypes===`array`)&&l(e);r.else(),_(e),r.endIf(),r.if((0,i._)`${c} !== undefined`,()=>{r.assign(a,c),p(e,c)});function l(e){switch(e){case`string`:r.elseIf((0,i._)`${s} == "number" || ${s} == "boolean"`).assign(c,(0,i._)`"" + ${a}`).elseIf((0,i._)`${a} === null`).assign(c,(0,i._)`""`);return;case`number`:r.elseIf((0,i._)`${s} == "boolean" || ${a} === null
170
+ `)}},{name:`mcp`,description:`Register as MCP server`,subcommands:[Yl({name:`add`,description:`Register as MCP server`,alias:{command:`c`},options:f.object({agent:f.string().optional().describe(`Target a specific agent (e.g. claude-code, cursor)`),command:f.string().optional().describe(`Override the command agents will run (e.g. "pnpm my-cli --mcp")`),noGlobal:f.boolean().optional().describe(`Install to project instead of globally`)})}),Yl({name:`doctor`,description:`Validate MCP server startup and tool listing`})]},{name:`skills`,aliases:[`skill`],description:`Sync skill files to agents`,subcommands:[Yl({name:`add`,description:`Sync skill files to agents`,options:f.object({depth:f.number().optional().describe(`Grouping depth for skill files (default: 1)`),noGlobal:f.boolean().optional().describe(`Install to project instead of globally`)})}),Yl({name:`list`,aliases:[`ls`],description:`List skills`})]}]}));function nu(e,t={}){let{aliases:n,configFlag:r,description:i,globals:a,version:o,commands:s=[],root:c=!1}=t,l=[],u=o?`${e}@${o}`:e;if(l.push(i?`${u} \u2014 ${i}`:u),l.push(``),l.push(`Usage: ${e} <command>`),n?.length&&l.push(`Aliases: ${n.join(`, `)}`),s.length>0){l.push(``),l.push(`Commands:`);let e=Math.max(...s.map(e=>e.name.length));for(let t of s)if(t.description){let n=` `.repeat(e-t.name.length);l.push(` ${t.name}${n} ${t.description}`)}else l.push(` ${t.name}`)}return l.push(...pu(c,r,a)),l.join(`
171
+ `)}function ru(e,t={}){let{alias:n,aliases:r,configFlag:i,description:a,globals:o,version:s,args:c,env:l,envSource:u,hint:d,root:f=!1,options:p,examples:m}=t,h=[],g=s?`${e}@${s}`:e;h.push(a?`${g} \u2014 ${a}`:g),h.push(``);let{usage:_}=t;if(_&&_.length>0){let t=_.map(t=>{let n=[];if(t.prefix&&n.push(t.prefix),n.push(e),t.args)for(let e of Object.keys(t.args))n.push(`<${e}>`);if(t.options)for(let e of Object.keys(t.options))n.push(`--${e} <${e}>`);return t.suffix&&n.push(t.suffix),n.join(` `)}),n=` `.repeat(7);h.push(`Usage: ${t[0]}`);for(let e of t.slice(1))h.push(`${n}${e}`)}else{let n=iu(e,c),r=t.commands&&t.commands.length>0?` | <command>`:``;h.push(`Usage: ${n}${p?` [options]`:``}${r}`)}if(r?.length&&h.push(`Aliases: ${r.join(`, `)}`),c){let e=au(c);if(e.length>0){h.push(``),h.push(`Arguments:`);let t=Math.max(...e.map(e=>e.name.length));for(let n of e)h.push(` ${n.name}${` `.repeat(t-n.name.length)} ${n.description}`)}}if(p){let e=su(p,n);if(e.length>0){h.push(``),h.push(`Options:`);let t=Math.max(...e.map(e=>e.flag.length));for(let n of e){let e=` `.repeat(t-n.flag.length),r=n.deprecated?`[deprecated] `:``,i=n.defaultValue===void 0?`${r}${n.description}`:`${r}${n.description} (default: ${n.defaultValue})`;h.push(` ${n.flag}${e} ${i}`)}}}if(m&&m.length>0){h.push(``),h.push(`Examples:`);let t=Math.max(...m.map(t=>(t.command?`${e} ${t.command}`:e).length));for(let n of m){let r=n.command?`${e} ${n.command}`:e;n.description?h.push(` ${r}${` `.repeat(t-r.length)} # ${n.description}`):h.push(` ${r}`)}}d&&(h.push(``),h.push(d));let{commands:v}=t;if(v&&v.length>0){h.push(``),h.push(`Commands:`);let e=Math.max(...v.map(e=>e.name.length));for(let t of v)if(t.description){let n=` `.repeat(e-t.name.length);h.push(` ${t.name}${n} ${t.description}`)}else h.push(` ${t.name}`)}if(t.hideGlobalOptions||h.push(...pu(f,i,o)),l){let e=ou(l);if(e.length>0){h.push(``),h.push(`Environment Variables:`);let t=Math.max(...e.map(e=>e.name.length));for(let n of e){let e=` `.repeat(t-n.name.length),r=[n.description],i=u??Ul();n.name in i&&r.push(`set: ${mu(i[n.name])}`),n.defaultValue!==void 0&&r.push(`default: ${n.defaultValue}`);let a=r.length>1?`${r[0]} (${r.slice(1).join(`, `)})`:r[0];h.push(` ${n.name}${e} ${a}`)}}}return h.join(`
172
+ `)}function iu(e,t){if(!t)return e;let n=[e];for(let[e,r]of Object.entries(t.shape)){let t=cu(r),i=(t.includes(`|`)?t:e)+(t===`array`?`...`:``);n.push(r._zod.optout===`optional`?`[${i}]`:`<${i}>`)}return n.join(` `)}function au(e){let t=[];for(let[n,r]of Object.entries(e.shape))t.push({name:n,description:r.description??``});return t}function ou(e){let t=[];for(let[n,r]of Object.entries(e.shape)){let e=du(r);t.push({name:n,description:r.description??``,defaultValue:e})}return t}function su(e,t){let n=[];for(let[r,i]of Object.entries(e.shape)){let e=cu(i),a=t?.[r],o=rn(r),s=e===`boolean`?``:` <${e}>`,c=a?`--${o}, -${a}${s}`:`--${o}${s}`,l=du(i);e===`boolean`&&l===!1&&(l=void 0);let u=fu(i);n.push({flag:c,description:i.description??``,defaultValue:l,deprecated:u})}return n}function cu(e){if(lu(e))return`count`;let t=uu(e);if(t instanceof f.ZodString)return`string`;if(t instanceof f.ZodNumber)return`number`;if(t instanceof f.ZodBoolean)return`boolean`;if(t instanceof f.ZodArray)return`array`;if(t instanceof f.ZodEnum)return Object.values(t._zod.def.entries).join(`|`);if(t instanceof f.ZodUnion){let e=t._zod?.def?.options;if(e?.every(e=>e instanceof f.ZodLiteral))return e.map(e=>String(e._zod.def.values[0])).join(`|`)}return`value`}function lu(e){let t=e;return typeof t?.meta==`function`&&t.meta()?.count===!0}function uu(e){return e instanceof f.ZodOptional?uu(e.unwrap()):e instanceof f.ZodDefault?uu(e.removeDefault()):e instanceof f.ZodNullable?uu(e.unwrap()):e}function du(e){if(e instanceof f.ZodDefault){let t=e._def.defaultValue,n=typeof t==`function`?t():t;return Array.isArray(n)&&n.length===0?void 0:n}if(e instanceof f.ZodOptional)return du(e.unwrap())}function fu(e){return e?.meta?.()?.deprecated===!0||void 0}function pu(e=!1,t,n){let r=[];if(e){let e=eu.flatMap(e=>{if(!e.subcommands)return[{name:e.name,desc:e.description}];if(e.subcommands.length===1)return[{name:`${e.name} ${e.subcommands[0].name}`,desc:e.subcommands[0].description}];let t=e.subcommands.map(e=>e.name).join(`, `);return[{name:e.name,desc:`${e.description} (${t})`}]}),t=Math.max(...e.map(e=>e.name.length));r.push(``,`Integrations:`,...e.map(e=>` ${e.name}${` `.repeat(t-e.name.length)} ${e.desc}`))}if(n){let e=su(n.schema,n.alias);if(e.length>0){let t=Math.max(...e.map(e=>e.flag.length));r.push(``,`Custom Global Options:`,...e.map(e=>{let n=` `.repeat(t-e.flag.length),r=e.deprecated?`[deprecated] `:``,i=e.defaultValue===void 0?`${r}${e.description}`:`${r}${e.description} (default: ${e.defaultValue})`;return` ${e.flag}${n} ${i}`}))}}let i=[...t?[{flag:`--${t} <path>`,desc:`Load JSON option defaults from a file`}]:[],{flag:`--filter-output <keys>`,desc:`Filter output by key paths (e.g. foo,bar.baz,a[0,3])`},{flag:`--format <toon|json|yaml|md|jsonl>`,desc:`Output format`},{flag:`--help`,desc:`Show help`},{flag:`--llms, --llms-full`,desc:`Print LLM-readable manifest`},...e?[{flag:`--mcp`,desc:`Start as MCP stdio server`}]:[],...t?[{flag:`--no-${t}`,desc:`Disable JSON option defaults for this run`}]:[],{flag:`--schema`,desc:`Show JSON Schema for command`},{flag:`--token-count`,desc:`Print token count of output (instead of output)`},{flag:`--token-limit <n>`,desc:`Limit output to n tokens`},{flag:`--token-offset <n>`,desc:`Skip first n tokens of output`},{flag:`--full-output`,desc:`Show full output envelope`},...e?[{flag:`--update`,desc:`Update to latest version`}]:[],...e?[{flag:`--version`,desc:`Show version`}]:[]].sort((e,t)=>e.flag.localeCompare(t.flag)),a=Math.max(...i.map(e=>e.flag.length));return r.push(``,`Global Options:`,...i.map(e=>` ${e.flag}${` `.repeat(a-e.flag.length)} ${e.desc}`)),r}function mu(e){return e.length<=4?`****`:`****${e.slice(-4)}`}var hu=I((()=>{tu(),sn(),Wl()}));function gu(e,t){if(!(!t||t.commands.length===0))return{description:t.description??(t.commands.length===1?`Suggested command:`:`Suggested commands:`),commands:t.commands.map(t=>vu(e,t))}}function _u(e){let t=[e.description];for(let n of e.commands)t.push(` ${n.command}${n.description?` - ${n.description}`:``}`);return t.join(`
173
+ `)}function vu(e,t){if(typeof t==`string`)return{command:`${e} ${t}`};let n=`${t.command===e||t.command.startsWith(`${e} `)?``:`${e} `}${t.command}`;if(t.args)for(let[e,r]of Object.entries(t.args))n+=r===!0?` <${e}>`:` ${r}`;if(t.options)for(let[e,r]of Object.entries(t.options))n+=r===!0?` --${e} <${e}>`:` --${e} ${r}`;return{command:n,...t.description?{description:t.description}:void 0}}var yu=I((()=>{}));async function bu(e,t={}){let n=[],r=t.exclude?c.resolve(t.exclude):void 0;async function i(e,t){let a=await C.readdir(e,{withFileTypes:!0});a.sort((e,t)=>e.name.localeCompare(t.name));for(let o of a){if(o.name.startsWith(`.`)||o.name.startsWith(`_`))continue;let a=c.join(e,o.name);if(o.isDirectory()){Cu(o.name,a),await i(a,[...t,o.name]);continue}if(!o.isFile()||a===r)continue;let s=wu.find(e=>o.name.endsWith(e));if(!s)continue;let l=o.name.slice(0,-s.length);if(!(l.endsWith(`.d`)||l.endsWith(`.test`)||l.endsWith(`.test-d`)||l.endsWith(`.spec`))){if(l===`index`){t.length>0&&n.push({file:a,segments:t});continue}Cu(l,a),n.push({file:a,segments:[...t,l]})}}}await i(e,[]);let a=new Map;for(let e of n){let t=e.segments.join(` `),n=a.get(t);if(n)throw Error(`Duplicate filesystem command '${t}' from '${n}' and '${e.file}'.`);a.set(t,e.file)}return n}function xu(){return globalThis[Symbol.for(Eu)]?.shift()}async function Su(e){return Promise.all(e.map(async({load:e,...t})=>({...t,command:await e()})))}function Cu(e,t){if(!Tu.test(e))throw Error(`Invalid filesystem command segment '${e}' from '${t}'. Use lowercase kebab-case names.`)}var wu,Tu,Eu,Du=I((()=>{wu=[`.cts`,`.cjs`,`.mts`,`.mjs`,`.ts`,`.js`],Tu=/^[a-z0-9]+(?:-[a-z0-9]+)*$/,Eu=`incur.fs.manifests`}));function Ou(e){let t=f.toJSONSchema(e,{unrepresentable:`any`,override:e=>{let t=e.zodSchema._zod?.def?.type;(t===`bigint`||t===`date`)&&(e.jsonSchema.type=`string`)}});return delete t.$schema,t}var ku=I((()=>{}));function Au(e,t){let n=typeof e;if(n!==typeof t)return!1;if(Array.isArray(e)){if(!Array.isArray(t))return!1;let n=e.length;if(n!==t.length)return!1;for(let r=0;r<n;r++)if(!Au(e[r],t[r]))return!1;return!0}if(n===`object`){if(!e||!t)return e===t;let n=Object.keys(e),r=Object.keys(t);if(n.length!==r.length)return!1;for(let r of n)if(!Au(e[r],t[r]))return!1;return!0}return e===t}var ju=I((()=>{}));function Mu(e){return encodeURI(Nu(e))}function Nu(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}var Pu=I((()=>{}));function Fu(e,t=Object.create(null),n=zu,r=``){if(e&&typeof e==`object`&&!Array.isArray(e)){let i=e.$id||e.id;if(i){let a=new URL(i,n.href);a.hash.length>1?t[a.href]=e:(a.hash=``,r===``?n=a:Fu(e,t,n))}}else if(e!==!0&&e!==!1)return t;let i=n.href+(r?`#`+r:``);if(t[i]!==void 0)throw Error(`Duplicate schema URI "${i}".`);if(t[i]=e,e===!0||e===!1)return t;if(e.__absolute_uri__===void 0&&Object.defineProperty(e,"__absolute_uri__",{enumerable:!1,value:i}),e.$ref&&e.__absolute_ref__===void 0){let t=new URL(e.$ref,n.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_ref__",{enumerable:!1,value:t.href})}if(e.$recursiveRef&&e.__absolute_recursive_ref__===void 0){let t=new URL(e.$recursiveRef,n.href);t.hash=t.hash,Object.defineProperty(e,"__absolute_recursive_ref__",{enumerable:!1,value:t.href})}if(e.$anchor){let r=new URL(`#`+e.$anchor,n.href);t[r.href]=e}for(let i in e){if(Ru[i])continue;let a=`${r}/${Mu(i)}`,o=e[i];if(Array.isArray(o)){if(Iu[i]){let e=o.length;for(let r=0;r<e;r++)Fu(o[r],t,n,`${a}/${r}`)}}else if(Lu[i])for(let e in o)Fu(o[e],t,n,`${a}/${Mu(e)}`);else Fu(o,t,n,a)}return t}var Iu,Lu,Ru,zu,Bu=I((()=>{Pu(),Iu={prefixItems:!0,items:!0,allOf:!0,anyOf:!0,oneOf:!0},Lu={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependentSchemas:!0},Ru={id:!0,$id:!0,$ref:!0,$schema:!0,$anchor:!0,$vocabulary:!0,$comment:!0,default:!0,enum:!0,const:!0,required:!0,type:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0},zu=typeof self<`u`&&self.location&&self.location.origin!==`null`?new URL(self.location.origin+self.location.pathname+location.search):new URL(`https://github.com/cfworker`)}));function Vu(e){return e.test.bind(e)}function Hu(e){return e%4==0&&(e%100!=0||e%400==0)}function Uu(e){let t=e.match(Ju);if(!t)return!1;let n=+t[1],r=+t[2],i=+t[3];return r>=1&&r<=12&&i>=1&&i<=(r==2&&Hu(n)?29:Yu[r])}function Wu(e,t){let n=t.match(Xu);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=!!n[5];return(r<=23&&i<=59&&a<=59||r==23&&i==59&&a==60)&&(!e||o)}function Gu(e){let t=e.split(ud);return t.length==2&&Uu(t[0])&&Wu(!0,t[1])}function Ku(e){return dd.test(e)&&fd.test(e)}function qu(e){if(pd.test(e))return!1;try{return new RegExp(e,`u`),!0}catch{return!1}}var Ju,Yu,Xu,Zu,Qu,$u,ed,td,nd,rd,id,ad,od,sd,cd,ld,ud,dd,fd,pd,md=I((()=>{Ju=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Yu=[0,31,28,31,30,31,30,31,31,30,31,30,31],Xu=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,Zu=/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,Qu=/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,$u=/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,ed=/^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)(?:\.(?:[a-z\u{00a1}-\u{ffff}0-9]+-?)*[a-z\u{00a1}-\u{ffff}0-9]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,td=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,nd=/^(?:\/(?:[^~/]|~0|~1)*)*$/,rd=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,id=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,ad=e=>{if(e[0]===`"`)return!1;let[t,n,...r]=e.split(`@`);return!t||!n||r.length!==0||t.length>64||n.length>253||t[0]===`.`||t.endsWith(`.`)||t.includes(`..`)||!/^[a-z0-9.-]+$/i.test(n)||!/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+$/i.test(t)?!1:n.split(`.`).every(e=>/^[a-z0-9]([a-z0-9-]{0,61}[a-z0-9])?$/i.test(e))},od=/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,sd=/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,cd=e=>e.length>1&&e.length<80&&(/^P\d+([.,]\d+)?W$/.test(e)||/^P[\dYMDTHS]*(\d[.,]\d+)?[YMDHS]$/.test(e)&&/^P([.,\d]+Y)?([.,\d]+M)?([.,\d]+D)?(T([.,\d]+H)?([.,\d]+M)?([.,\d]+S)?)?$/.test(e)),ld={date:Uu,time:Wu.bind(void 0,!1),"date-time":Gu,duration:cd,uri:Ku,"uri-reference":Vu(Qu),"uri-template":Vu($u),url:Vu(ed),email:ad,hostname:Vu(Zu),ipv4:Vu(od),ipv6:Vu(sd),regex:qu,uuid:Vu(td),"json-pointer":Vu(nd),"json-pointer-uri-fragment":Vu(rd),"relative-json-pointer":Vu(id)},ud=/t|\s/i,dd=/\/|:/,fd=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,pd=/[^\\]\\Z/})),hd=I((()=>{}));function gd(e){let t=0,n=e.length,r=0,i;for(;r<n;)t++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<n&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return t}var _d=I((()=>{}));function vd(e,t,n=`2019-09`,r=Fu(t),i=!0,a=null,o=`#`,s=`#`,c=Object.create(null)){if(t===!0)return{valid:!0,errors:[]};if(t===!1)return{valid:!1,errors:[{instanceLocation:o,keyword:`false`,keywordLocation:o,error:`False boolean schema.`}]};let l=typeof e,u;switch(l){case`boolean`:case`number`:case`string`:u=l;break;case`object`:u=e===null?`null`:Array.isArray(e)?`array`:`object`;break;default:throw Error(`Instances of "${l}" type are not supported.`)}let{$ref:d,$recursiveRef:f,$recursiveAnchor:p,type:m,const:h,enum:g,required:_,not:v,anyOf:y,allOf:b,oneOf:x,if:S,then:C,else:w,format:T,properties:ee,patternProperties:E,additionalProperties:D,unevaluatedProperties:O,minProperties:k,maxProperties:A,propertyNames:te,dependentRequired:ne,dependentSchemas:j,dependencies:M,prefixItems:re,items:ie,additionalItems:ae,unevaluatedItems:oe,contains:se,minContains:N,maxContains:ce,minItems:le,maxItems:ue,uniqueItems:de,minimum:fe,maximum:pe,exclusiveMinimum:P,exclusiveMaximum:me,multipleOf:he,minLength:ge,maxLength:_e,pattern:ve,__absolute_ref__:ye,__absolute_recursive_ref__:be}=t,F=[];if(p===!0&&a===null&&(a=t),f===`#`){let l=a===null?r[be]:a,u=`${s}/$recursiveRef`,d=vd(e,a===null?t:a,n,r,i,l,o,u,c);d.valid||F.push({instanceLocation:o,keyword:`$recursiveRef`,keywordLocation:u,error:`A subschema had errors.`},...d.errors)}if(d!==void 0){let t=r[ye||d];if(t===void 0){let e=`Unresolved $ref "${d}".`;throw ye&&ye!==d&&(e+=` Absolute URI "${ye}".`),e+=`\nKnown schemas:\n- ${Object.keys(r).join(`
174
+ - `)}`,Error(e)}let l=`${s}/$ref`,u=vd(e,t,n,r,i,a,o,l,c);if(u.valid||F.push({instanceLocation:o,keyword:`$ref`,keywordLocation:l,error:`A subschema had errors.`},...u.errors),n===`4`||n===`7`)return{valid:F.length===0,errors:F}}if(Array.isArray(m)){let t=m.length,n=!1;for(let r=0;r<t;r++)if(u===m[r]||m[r]===`integer`&&u===`number`&&e%1==0&&e===e){n=!0;break}n||F.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m.join(`", "`)}".`})}else m===`integer`?(u!==`number`||e%1||e!==e)&&F.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`}):m!==void 0&&u!==m&&F.push({instanceLocation:o,keyword:`type`,keywordLocation:`${s}/type`,error:`Instance type "${u}" is invalid. Expected "${m}".`});if(h!==void 0&&(u===`object`||u===`array`?Au(e,h)||F.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`}):e!==h&&F.push({instanceLocation:o,keyword:`const`,keywordLocation:`${s}/const`,error:`Instance does not match ${JSON.stringify(h)}.`})),g!==void 0&&(u===`object`||u===`array`?g.some(t=>Au(e,t))||F.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`}):g.some(t=>e===t)||F.push({instanceLocation:o,keyword:`enum`,keywordLocation:`${s}/enum`,error:`Instance does not match any of ${JSON.stringify(g)}.`})),v!==void 0){let t=`${s}/not`;vd(e,v,n,r,i,a,o,t).valid&&F.push({instanceLocation:o,keyword:`not`,keywordLocation:t,error:`Instance matched "not" schema.`})}let xe=[];if(y!==void 0){let t=`${s}/anyOf`,l=F.length,u=!1;for(let s=0;s<y.length;s++){let l=y[s],d=Object.create(c),f=vd(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);F.push(...f.errors),u||=f.valid,f.valid&&xe.push(d)}u?F.length=l:F.splice(l,0,{instanceLocation:o,keyword:`anyOf`,keywordLocation:t,error:`Instance does not match any subschemas.`})}if(b!==void 0){let t=`${s}/allOf`,l=F.length,u=!0;for(let s=0;s<b.length;s++){let l=b[s],d=Object.create(c),f=vd(e,l,n,r,i,p===!0?a:null,o,`${t}/${s}`,d);F.push(...f.errors),u&&=f.valid,f.valid&&xe.push(d)}u?F.length=l:F.splice(l,0,{instanceLocation:o,keyword:`allOf`,keywordLocation:t,error:`Instance does not match every subschema.`})}if(x!==void 0){let t=`${s}/oneOf`,l=F.length,u=x.filter((s,l)=>{let u=Object.create(c),d=vd(e,s,n,r,i,p===!0?a:null,o,`${t}/${l}`,u);return F.push(...d.errors),d.valid&&xe.push(u),d.valid}).length;u===1?F.length=l:F.splice(l,0,{instanceLocation:o,keyword:`oneOf`,keywordLocation:t,error:`Instance does not match exactly one subschema (${u} matches).`})}if((u===`object`||u===`array`)&&Object.assign(c,...xe),S!==void 0){let t=`${s}/if`;if(vd(e,S,n,r,i,a,o,t,c).valid){if(C!==void 0){let l=vd(e,C,n,r,i,a,o,`${s}/then`,c);l.valid||F.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "then" schema.`},...l.errors)}}else if(w!==void 0){let l=vd(e,w,n,r,i,a,o,`${s}/else`,c);l.valid||F.push({instanceLocation:o,keyword:`if`,keywordLocation:t,error:`Instance does not match "else" schema.`},...l.errors)}}if(u===`object`){if(_!==void 0)for(let t of _)t in e||F.push({instanceLocation:o,keyword:`required`,keywordLocation:`${s}/required`,error:`Instance does not have required property "${t}".`});let t=Object.keys(e);if(k!==void 0&&t.length<k&&F.push({instanceLocation:o,keyword:`minProperties`,keywordLocation:`${s}/minProperties`,error:`Instance does not have at least ${k} properties.`}),A!==void 0&&t.length>A&&F.push({instanceLocation:o,keyword:`maxProperties`,keywordLocation:`${s}/maxProperties`,error:`Instance does not have at least ${A} properties.`}),te!==void 0){let t=`${s}/propertyNames`;for(let s in e){let e=`${o}/${Mu(s)}`,c=vd(s,te,n,r,i,a,e,t);c.valid||F.push({instanceLocation:o,keyword:`propertyNames`,keywordLocation:t,error:`Property name "${s}" does not match schema.`},...c.errors)}}if(ne!==void 0){let t=`${s}/dependantRequired`;for(let n in ne)if(n in e){let r=ne[n];for(let i of r)i in e||F.push({instanceLocation:o,keyword:`dependentRequired`,keywordLocation:t,error:`Instance has "${n}" but does not have "${i}".`})}}if(j!==void 0)for(let t in j){let l=`${s}/dependentSchemas`;if(t in e){let s=vd(e,j[t],n,r,i,a,o,`${l}/${Mu(t)}`,c);s.valid||F.push({instanceLocation:o,keyword:`dependentSchemas`,keywordLocation:l,error:`Instance has "${t}" but does not match dependant schema.`},...s.errors)}}if(M!==void 0){let t=`${s}/dependencies`;for(let s in M)if(s in e){let c=M[s];if(Array.isArray(c))for(let n of c)n in e||F.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not have "${n}".`});else{let l=vd(e,c,n,r,i,a,o,`${t}/${Mu(s)}`);l.valid||F.push({instanceLocation:o,keyword:`dependencies`,keywordLocation:t,error:`Instance has "${s}" but does not match dependant schema.`},...l.errors)}}}let l=Object.create(null),u=!1;if(ee!==void 0){let t=`${s}/properties`;for(let s in ee){if(!(s in e))continue;let d=`${o}/${Mu(s)}`,f=vd(e[s],ee[s],n,r,i,a,d,`${t}/${Mu(s)}`);if(f.valid)c[s]=l[s]=!0;else if(u=i,F.push({instanceLocation:o,keyword:`properties`,keywordLocation:t,error:`Property "${s}" does not match schema.`},...f.errors),u)break}}if(!u&&E!==void 0){let t=`${s}/patternProperties`;for(let s in E){let d=new RegExp(s,`u`),f=E[s];for(let p in e){if(!d.test(p))continue;let m=`${o}/${Mu(p)}`,h=vd(e[p],f,n,r,i,a,m,`${t}/${Mu(s)}`);h.valid?c[p]=l[p]=!0:(u=i,F.push({instanceLocation:o,keyword:`patternProperties`,keywordLocation:t,error:`Property "${p}" matches pattern "${s}" but does not match associated schema.`},...h.errors))}}}if(!u&&D!==void 0){let t=`${s}/additionalProperties`;for(let s in e){if(l[s])continue;let d=`${o}/${Mu(s)}`,f=vd(e[s],D,n,r,i,a,d,t);f.valid?c[s]=!0:(u=i,F.push({instanceLocation:o,keyword:`additionalProperties`,keywordLocation:t,error:`Property "${s}" does not match additional properties schema.`},...f.errors))}}else if(!u&&O!==void 0){let t=`${s}/unevaluatedProperties`;for(let s in e)if(!c[s]){let l=`${o}/${Mu(s)}`,u=vd(e[s],O,n,r,i,a,l,t);u.valid?c[s]=!0:F.push({instanceLocation:o,keyword:`unevaluatedProperties`,keywordLocation:t,error:`Property "${s}" does not match unevaluated properties schema.`},...u.errors)}}}else if(u===`array`){ue!==void 0&&e.length>ue&&F.push({instanceLocation:o,keyword:`maxItems`,keywordLocation:`${s}/maxItems`,error:`Array has too many items (${e.length} > ${ue}).`}),le!==void 0&&e.length<le&&F.push({instanceLocation:o,keyword:`minItems`,keywordLocation:`${s}/minItems`,error:`Array has too few items (${e.length} < ${le}).`});let t=e.length,l=0,u=!1;if(re!==void 0){let d=`${s}/prefixItems`,f=Math.min(re.length,t);for(;l<f;l++){let t=vd(e[l],re[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,F.push({instanceLocation:o,keyword:`prefixItems`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}if(ie!==void 0){let d=`${s}/items`;if(Array.isArray(ie)){let s=Math.min(ie.length,t);for(;l<s;l++){let t=vd(e[l],ie[l],n,r,i,a,`${o}/${l}`,`${d}/${l}`);if(c[l]=!0,!t.valid&&(u=i,F.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}}else for(;l<t;l++){let t=vd(e[l],ie,n,r,i,a,`${o}/${l}`,d);if(c[l]=!0,!t.valid&&(u=i,F.push({instanceLocation:o,keyword:`items`,keywordLocation:d,error:`Items did not match schema.`},...t.errors),u))break}if(!u&&ae!==void 0){let d=`${s}/additionalItems`;for(;l<t;l++){let t=vd(e[l],ae,n,r,i,a,`${o}/${l}`,d);c[l]=!0,t.valid||(u=i,F.push({instanceLocation:o,keyword:`additionalItems`,keywordLocation:d,error:`Items did not match additional items schema.`},...t.errors))}}}if(se!==void 0){if(t===0&&N===void 0)F.push({instanceLocation:o,keyword:`contains`,keywordLocation:`${s}/contains`,error:`Array is empty. It must contain at least one item matching the schema.`});else if(N!==void 0&&t<N)F.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array has less items (${t}) than minContains (${N}).`});else{let l=`${s}/contains`,u=F.length,d=0;for(let s=0;s<t;s++){let t=vd(e[s],se,n,r,i,a,`${o}/${s}`,l);t.valid?(c[s]=!0,d++):F.push(...t.errors)}d>=(N||0)&&(F.length=u),N===void 0&&ce===void 0&&d===0?F.splice(u,0,{instanceLocation:o,keyword:`contains`,keywordLocation:l,error:`Array does not contain item matching schema.`}):N!==void 0&&d<N?F.push({instanceLocation:o,keyword:`minContains`,keywordLocation:`${s}/minContains`,error:`Array must contain at least ${N} items matching schema. Only ${d} items were found.`}):ce!==void 0&&d>ce&&F.push({instanceLocation:o,keyword:`maxContains`,keywordLocation:`${s}/maxContains`,error:`Array may contain at most ${ce} items matching schema. ${d} items were found.`})}}if(!u&&oe!==void 0){let u=`${s}/unevaluatedItems`;for(;l<t;l++){if(c[l])continue;let t=vd(e[l],oe,n,r,i,a,`${o}/${l}`,u);c[l]=!0,t.valid||F.push({instanceLocation:o,keyword:`unevaluatedItems`,keywordLocation:u,error:`Items did not match unevaluated items schema.`},...t.errors)}}if(de)for(let n=0;n<t;n++){let r=e[n],i=typeof r==`object`&&!!r;for(let a=0;a<t;a++){if(n===a)continue;let t=e[a];(r===t||i&&typeof t==`object`&&t&&Au(r,t))&&(F.push({instanceLocation:o,keyword:`uniqueItems`,keywordLocation:`${s}/uniqueItems`,error:`Duplicate items at indexes ${n} and ${a}.`}),n=2**53-1,a=2**53-1)}}}else if(u===`number`){if(n===`4`?(fe!==void 0&&(P===!0&&e<=fe||e<fe)&&F.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${P?`or equal to `:``} ${fe}.`}),pe!==void 0&&(me===!0&&e>=pe||e>pe)&&F.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${me?`or equal to `:``} ${pe}.`})):(fe!==void 0&&e<fe&&F.push({instanceLocation:o,keyword:`minimum`,keywordLocation:`${s}/minimum`,error:`${e} is less than ${fe}.`}),pe!==void 0&&e>pe&&F.push({instanceLocation:o,keyword:`maximum`,keywordLocation:`${s}/maximum`,error:`${e} is greater than ${pe}.`}),P!==void 0&&e<=P&&F.push({instanceLocation:o,keyword:`exclusiveMinimum`,keywordLocation:`${s}/exclusiveMinimum`,error:`${e} is less than ${P}.`}),me!==void 0&&e>=me&&F.push({instanceLocation:o,keyword:`exclusiveMaximum`,keywordLocation:`${s}/exclusiveMaximum`,error:`${e} is greater than or equal to ${me}.`})),he!==void 0){let t=e%he;Math.abs(0-t)>=1.1920929e-7&&Math.abs(he-t)>=1.1920929e-7&&F.push({instanceLocation:o,keyword:`multipleOf`,keywordLocation:`${s}/multipleOf`,error:`${e} is not a multiple of ${he}.`})}}else if(u===`string`){let t=ge===void 0&&_e===void 0?0:gd(e);ge!==void 0&&t<ge&&F.push({instanceLocation:o,keyword:`minLength`,keywordLocation:`${s}/minLength`,error:`String is too short (${t} < ${ge}).`}),_e!==void 0&&t>_e&&F.push({instanceLocation:o,keyword:`maxLength`,keywordLocation:`${s}/maxLength`,error:`String is too long (${t} > ${_e}).`}),ve!==void 0&&!new RegExp(ve,`u`).test(e)&&F.push({instanceLocation:o,keyword:`pattern`,keywordLocation:`${s}/pattern`,error:`String does not match pattern.`}),T!==void 0&&ld[T]&&!ld[T](e)&&F.push({instanceLocation:o,keyword:`format`,keywordLocation:`${s}/format`,error:`String does not match format "${T}".`})}return{valid:F.length===0,errors:F}}var yd=I((()=>{ju(),Bu(),md(),Pu(),_d()})),bd,xd=I((()=>{Bu(),yd(),bd=class{schema;draft;shortCircuit;lookup;constructor(e,t=`2019-09`,n=!0){this.schema=e,this.draft=t,this.shortCircuit=n,this.lookup=Fu(e)}validate(e){return vd(e,this.schema,this.draft,this.lookup,this.shortCircuit)}addSchema(e,t){t&&(e={...e,$id:t}),Fu(e,this.lookup)}}})),Sd=I((()=>{ju(),Bu(),md(),Pu(),hd(),_d(),yd(),xd()}));function Cd(e){let t=typeof e==`string`?new URL(e):new URL(e.href);return t.hash=``,t}function wd({requestedResource:e,configuredResource:t}){let n=typeof e==`string`?new URL(e):new URL(e.href),r=typeof t==`string`?new URL(t):new URL(t.href);if(n.origin!==r.origin||n.pathname.length<r.pathname.length)return!1;let i=n.pathname.endsWith(`/`)?n.pathname:n.pathname+`/`,a=r.pathname.endsWith(`/`)?r.pathname:r.pathname+`/`;return i.startsWith(a)}function Td(e){return e.title!==void 0&&e.title!==``?e.title:`annotations`in e&&e.annotations?.title?e.annotations.title:e.name}function Ed(e){return _h[e]}function Dd(e){let t={};for(let n of e){let e=n.shape.method.value;t[e]=n}return t}function Od(e){return vh[e]}function kd(e){return yh[e]}function Ad(e){return Gf.parse(e)}function jd(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function Md(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}function Nd(e,t){return D.safeParse(e,t)}function Pd(e){return e===`completed`||e===`failed`||e===`cancelled`}function Fd(e){if(!e)return;let{taskStore:t,taskMessageQueue:n,defaultTaskPollInterval:r,maxTaskQueueSize:i}=e;return{taskStore:t,taskMessageQueue:n,defaultTaskPollInterval:r,maxTaskQueueSize:i}}function Id(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Ld(e,t){let n={...e};for(let e in t){let r=e,i=t[r];if(i===void 0)continue;let a=n[r];n[r]=Id(a)&&Id(i)?{...a,...i}:i}return n}async function Rd(e){let t=[];for await(let n of e)t.push(n);return t}async function zd(e){for await(let t of e)if(t.type===`result`)return t.result;else if(t.type===`error`)throw t.error;throw Error(`No result in stream.`)}function Bd(e){return Gf.parse(JSON.parse(e))}function Vd(e){return JSON.stringify(e)+`
175
+ `}function Hd(e){let t=[];if(e.length===0)return{isValid:!1,warnings:[`Tool name cannot be empty`]};if(e.length>128)return{isValid:!1,warnings:[`Tool name exceeds maximum length of 128 characters (current: ${e.length})`]};if(e.includes(` `)&&t.push(`Tool name contains spaces, which may cause parsing issues`),e.includes(`,`)&&t.push(`Tool name contains commas, which may cause parsing issues`),(e.startsWith(`-`)||e.endsWith(`-`))&&t.push(`Tool name starts or ends with a dash, which may cause parsing issues in some contexts`),(e.startsWith(`.`)||e.endsWith(`.`))&&t.push(`Tool name starts or ends with a dot, which may cause parsing issues in some contexts`),!Mh.test(e)){let n=[...e].filter(e=>!/[A-Za-z0-9._-]/.test(e)).filter((e,t,n)=>n.indexOf(e)===t);return t.push(`Tool name contains invalid characters: ${n.map(e=>`"${e}"`).join(`, `)}`,`Allowed characters are: A-Z, a-z, 0-9, underscore (_), dash (-), and dot (.)`),{isValid:!1,warnings:t}}return{isValid:!0,warnings:t}}function Ud(e,t){if(t.length>0){console.warn(`Tool name validation warning for "${e}":`);for(let e of t)console.warn(` - ${e}`);console.warn(`Tool registration will proceed, but this may cause compatibility issues.`),console.warn(`Consider updating the tool name to conform to the MCP tool naming standard.`),console.warn(`See SEP: Specify Format for Tool Names (https://github.com/modelcontextprotocol/modelcontextprotocol/issues/986) for more details.`)}}function Wd(e){let t=Hd(e);return Ud(e,t.warnings),t.isValid}function Gd(e){return e?e instanceof Headers?Object.fromEntries(e.entries()):Array.isArray(e)?Object.fromEntries(e):{...e}:{}}function Kd(e=fetch,t){return t?async(n,r)=>e(n,{...t,...r,headers:r?.headers?{...Gd(t.headers),...Gd(r.headers)}:t.headers}):e}function qd(e,t=`input`){let n=e[`~standard`].jsonSchema[t]({target:`draft-2020-12`});if(n.type!==void 0&&n.type!==`object`)throw Error(`MCP tool and prompt schemas must describe objects (got type: ${JSON.stringify(n.type)}). Wrap your schema in z.object({...}) or equivalent.`);return{type:`object`,...n}}function Jd(e){return e.path?.length?`${e.path.map(e=>String(typeof e==`object`?e.key:e)).join(`.`)}: ${e.message}`:e.message}async function Yd(e,t){let n=await e[`~standard`].validate(t);return n.issues&&n.issues.length>0?{success:!1,error:n.issues.map(e=>Jd(e)).join(`, `)}:{success:!0,data:n.value}}function Xd(e){let t=qd(e,`input`),n=t.properties||{},r=t.required||[];return Object.entries(n).map(([e,t])=>({name:e,description:t?.description,required:r.includes(e)}))}function Zd(){let e=new $g.Ajv({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,e_.default)(e),e}function Qd(e,t){let n=t.getValidator(e);return{"~standard":{version:1,vendor:`mcp`,jsonSchema:{input:()=>e,output:()=>e},validate:e=>{let t=n(e);return t.valid?{value:t.data}:{issues:[{message:t.errorMessage}]}}}}}var $d,ef,tf,nf,rf,af,B,of,sf,cf,lf,uf,V,df,ff,pf,mf,hf,gf,_f,vf,yf,bf,xf,Sf,Cf,wf,Tf,H,U,Ef,Df,Of,kf,Af,jf,Mf,Nf,Pf,Ff,If,Lf,Rf,zf,Bf,Vf,Hf,Uf,Wf,Gf,Kf,qf,Jf,Yf,Xf,Zf,Qf,$f,ep,tp,np,rp,ip,ap,op,sp,cp,lp,up,dp,fp,pp,mp,hp,gp,_p,vp,yp,bp,xp,Sp,Cp,wp,Tp,Ep,Dp,Op,kp,Ap,jp,Mp,Np,Pp,Fp,Ip,Lp,Rp,zp,Bp,Vp,Hp,Up,Wp,Gp,Kp,qp,Jp,Yp,Xp,Zp,Qp,$p,em,tm,nm,rm,im,am,om,sm,cm,lm,um,dm,fm,pm,mm,hm,gm,_m,vm,ym,bm,xm,Sm,Cm,wm,Tm,Em,Dm,Om,km,Am,jm,Mm,Nm,Pm,Fm,Im,Lm,Rm,zm,Bm,Vm,Hm,Um,Wm,Gm,Km,qm,Jm,Ym,Xm,Zm,Qm,$m,eh,th,nh,rh,ih,ah,oh,sh,ch,lh,uh,dh,fh,ph,mh,hh,gh,_h,vh,yh,bh,xh,Sh,Ch,wh,Th,Eh,Dh,Oh,kh,Ah,jh,Mh,Nh,Ph,Fh,Ih,Lh,Rh,zh,W,G,Bh,Vh,Hh,Uh,Wh,Gh,Kh,qh,Jh,Yh,Xh,Zh,Qh,$h,eg,tg,ng,rg,ig,ag,og,sg,cg,lg,ug,dg,fg,pg,mg,hg,gg,_g,vg,yg,bg,xg,Sg,Cg,wg,Tg,Eg,Dg,Og,kg,Ag,jg,Mg,Ng,Pg,Fg,Ig,Lg,Rg,zg,Bg,Vg,Hg,Ug,Wg,Gg,Kg,qg,Jg,Yg,Xg,Zg,Qg,$g,e_,t_,n_,r_=I((()=>{Sd(),$d=Object.create,ef=Object.defineProperty,tf=Object.getOwnPropertyDescriptor,nf=Object.getOwnPropertyNames,rf=Object.getPrototypeOf,af=Object.prototype.hasOwnProperty,B=(e,t)=>()=>(t||e((t={exports:{}}).exports,t),t.exports),of=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=nf(t),a=0,o=i.length,s;a<o;a++)s=i[a],!af.call(e,s)&&s!==n&&ef(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=tf(t,s))||r.enumerable});return e},sf=(e,t,n)=>(n=e==null?{}:$d(rf(e)),of(t||!e||!e.__esModule?ef(n,`default`,{value:e,enumerable:!0}):n,e)),cf=function(e){return e.InvalidRequest=`invalid_request`,e.InvalidClient=`invalid_client`,e.InvalidGrant=`invalid_grant`,e.UnauthorizedClient=`unauthorized_client`,e.UnsupportedGrantType=`unsupported_grant_type`,e.InvalidScope=`invalid_scope`,e.AccessDenied=`access_denied`,e.ServerError=`server_error`,e.TemporarilyUnavailable=`temporarily_unavailable`,e.UnsupportedResponseType=`unsupported_response_type`,e.UnsupportedTokenType=`unsupported_token_type`,e.InvalidToken=`invalid_token`,e.MethodNotAllowed=`method_not_allowed`,e.TooManyRequests=`too_many_requests`,e.InvalidClientMetadata=`invalid_client_metadata`,e.InsufficientScope=`insufficient_scope`,e.InvalidTarget=`invalid_target`,e}({}),lf=class e extends Error{constructor(e,t,n){super(t),this.code=e,this.errorUri=n,this.name=`OAuthError`}toResponseObject(){let e={error:this.code,error_description:this.message};return this.errorUri&&(e.error_uri=this.errorUri),e}static fromResponse(t){return new e(t.error,t.error_description??t.error,t.error_uri)}},uf=function(e){return e.NotConnected=`NOT_CONNECTED`,e.AlreadyConnected=`ALREADY_CONNECTED`,e.NotInitialized=`NOT_INITIALIZED`,e.CapabilityNotSupported=`CAPABILITY_NOT_SUPPORTED`,e.RequestTimeout=`REQUEST_TIMEOUT`,e.ConnectionClosed=`CONNECTION_CLOSED`,e.SendFailed=`SEND_FAILED`,e.ClientHttpNotImplemented=`CLIENT_HTTP_NOT_IMPLEMENTED`,e.ClientHttpAuthentication=`CLIENT_HTTP_AUTHENTICATION`,e.ClientHttpForbidden=`CLIENT_HTTP_FORBIDDEN`,e.ClientHttpUnexpectedContent=`CLIENT_HTTP_UNEXPECTED_CONTENT`,e.ClientHttpFailedToOpenStream=`CLIENT_HTTP_FAILED_TO_OPEN_STREAM`,e.ClientHttpFailedToTerminateSession=`CLIENT_HTTP_FAILED_TO_TERMINATE_SESSION`,e}({}),V=class extends Error{constructor(e,t,n){super(t),this.code=e,this.data=n,this.name=`SdkError`}},df=D.url().superRefine((e,t)=>{if(!URL.canParse(e))return t.addIssue({code:D.ZodIssueCode.custom,message:`URL must be parseable`,fatal:!0}),D.NEVER}).refine(e=>{let t=new URL(e);return t.protocol!==`javascript:`&&t.protocol!==`data:`&&t.protocol!==`vbscript:`},{message:`URL cannot use javascript:, data:, or vbscript: scheme`}),D.looseObject({resource:D.string().url(),authorization_servers:D.array(df).optional(),jwks_uri:D.string().url().optional(),scopes_supported:D.array(D.string()).optional(),bearer_methods_supported:D.array(D.string()).optional(),resource_signing_alg_values_supported:D.array(D.string()).optional(),resource_name:D.string().optional(),resource_documentation:D.string().optional(),resource_policy_uri:D.string().url().optional(),resource_tos_uri:D.string().url().optional(),tls_client_certificate_bound_access_tokens:D.boolean().optional(),authorization_details_types_supported:D.array(D.string()).optional(),dpop_signing_alg_values_supported:D.array(D.string()).optional(),dpop_bound_access_tokens_required:D.boolean().optional()}),ff=D.looseObject({issuer:D.string(),authorization_endpoint:df,token_endpoint:df,registration_endpoint:df.optional(),scopes_supported:D.array(D.string()).optional(),response_types_supported:D.array(D.string()),response_modes_supported:D.array(D.string()).optional(),grant_types_supported:D.array(D.string()).optional(),token_endpoint_auth_methods_supported:D.array(D.string()).optional(),token_endpoint_auth_signing_alg_values_supported:D.array(D.string()).optional(),service_documentation:df.optional(),revocation_endpoint:df.optional(),revocation_endpoint_auth_methods_supported:D.array(D.string()).optional(),revocation_endpoint_auth_signing_alg_values_supported:D.array(D.string()).optional(),introspection_endpoint:D.string().optional(),introspection_endpoint_auth_methods_supported:D.array(D.string()).optional(),introspection_endpoint_auth_signing_alg_values_supported:D.array(D.string()).optional(),code_challenge_methods_supported:D.array(D.string()).optional(),client_id_metadata_document_supported:D.boolean().optional()}),pf=D.looseObject({issuer:D.string(),authorization_endpoint:df,token_endpoint:df,userinfo_endpoint:df.optional(),jwks_uri:df,registration_endpoint:df.optional(),scopes_supported:D.array(D.string()).optional(),response_types_supported:D.array(D.string()),response_modes_supported:D.array(D.string()).optional(),grant_types_supported:D.array(D.string()).optional(),acr_values_supported:D.array(D.string()).optional(),subject_types_supported:D.array(D.string()),id_token_signing_alg_values_supported:D.array(D.string()),id_token_encryption_alg_values_supported:D.array(D.string()).optional(),id_token_encryption_enc_values_supported:D.array(D.string()).optional(),userinfo_signing_alg_values_supported:D.array(D.string()).optional(),userinfo_encryption_alg_values_supported:D.array(D.string()).optional(),userinfo_encryption_enc_values_supported:D.array(D.string()).optional(),request_object_signing_alg_values_supported:D.array(D.string()).optional(),request_object_encryption_alg_values_supported:D.array(D.string()).optional(),request_object_encryption_enc_values_supported:D.array(D.string()).optional(),token_endpoint_auth_methods_supported:D.array(D.string()).optional(),token_endpoint_auth_signing_alg_values_supported:D.array(D.string()).optional(),display_values_supported:D.array(D.string()).optional(),claim_types_supported:D.array(D.string()).optional(),claims_supported:D.array(D.string()).optional(),service_documentation:D.string().optional(),claims_locales_supported:D.array(D.string()).optional(),ui_locales_supported:D.array(D.string()).optional(),claims_parameter_supported:D.boolean().optional(),request_parameter_supported:D.boolean().optional(),request_uri_parameter_supported:D.boolean().optional(),require_request_uri_registration:D.boolean().optional(),op_policy_uri:df.optional(),op_tos_uri:df.optional(),client_id_metadata_document_supported:D.boolean().optional()}),D.object({...pf.shape,...ff.pick({code_challenge_methods_supported:!0}).shape}),D.object({access_token:D.string(),id_token:D.string().optional(),token_type:D.string(),expires_in:D.coerce.number().optional(),scope:D.string().optional(),refresh_token:D.string().optional()}).strip(),D.object({issued_token_type:D.literal(`urn:ietf:params:oauth:token-type:id-jag`),access_token:D.string(),token_type:D.string().optional(),expires_in:D.number().optional(),scope:D.string().optional()}).strip(),D.object({error:D.string(),error_description:D.string().optional(),error_uri:D.string().optional()}),mf=df.optional().or(D.literal(``).transform(()=>void 0)),hf=D.object({redirect_uris:D.array(df),token_endpoint_auth_method:D.string().optional(),grant_types:D.array(D.string()).optional(),response_types:D.array(D.string()).optional(),client_name:D.string().optional(),client_uri:df.optional(),logo_uri:mf,scope:D.string().optional(),contacts:D.array(D.string()).optional(),tos_uri:mf,policy_uri:D.string().optional(),jwks_uri:df.optional(),jwks:D.any().optional(),software_id:D.string().optional(),software_version:D.string().optional(),software_statement:D.string().optional()}).strip(),gf=D.object({client_id:D.string(),client_secret:D.string().optional(),client_id_issued_at:D.number().optional(),client_secret_expires_at:D.number().optional()}).strip(),hf.merge(gf),D.object({error:D.string(),error_description:D.string().optional()}).strip(),D.object({token:D.string(),token_type_hint:D.string().optional()}).strip(),_f=`2025-11-25`,vf=`2025-03-26`,yf=[_f,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],bf=`io.modelcontextprotocol/related-task`,xf=-32700,Sf=-32600,Cf=-32601,wf=-32602,Tf=-32603,H=function(e){return e[e.ParseError=-32700]=`ParseError`,e[e.InvalidRequest=-32600]=`InvalidRequest`,e[e.MethodNotFound=-32601]=`MethodNotFound`,e[e.InvalidParams=-32602]=`InvalidParams`,e[e.InternalError=-32603]=`InternalError`,e[e.ResourceNotFound=-32002]=`ResourceNotFound`,e[e.UrlElicitationRequired=-32042]=`UrlElicitationRequired`,e}({}),U=class e extends Error{constructor(e,t,n){super(t),this.code=e,this.data=n,this.name=`ProtocolError`}static fromError(t,n,r){if(t===H.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new Ef(e.elicitations,n)}return new e(t,n,r)}},Ef=class extends U{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(H.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}},Df=D.lazy(()=>D.union([D.string(),D.number(),D.boolean(),D.null(),D.record(D.string(),Df),D.array(Df)])),Of=D.record(D.string(),Df),D.array(Df),kf=D.union([D.string(),D.number().int()]),Af=D.string(),D.looseObject({ttl:D.number().optional(),pollInterval:D.number().optional()}),jf=D.object({ttl:D.number().optional()}),Mf=D.object({taskId:D.string()}),Nf=D.looseObject({progressToken:kf.optional(),[bf]:Mf.optional()}),Pf=D.object({_meta:Nf.optional()}),Ff=Pf.extend({task:jf.optional()}),If=D.object({method:D.string(),params:Pf.loose().optional()}),Lf=D.object({_meta:Nf.optional()}),Rf=D.object({method:D.string(),params:Lf.loose().optional()}),zf=D.looseObject({_meta:Nf.optional()}),Bf=D.union([D.string(),D.number().int()]),Vf=D.object({jsonrpc:D.literal(`2.0`),id:Bf,...If.shape}).strict(),Hf=D.object({jsonrpc:D.literal(`2.0`),...Rf.shape}).strict(),Uf=D.object({jsonrpc:D.literal(`2.0`),id:Bf,result:zf}).strict(),Wf=D.object({jsonrpc:D.literal(`2.0`),id:Bf.optional(),error:D.object({code:D.number().int(),message:D.string(),data:D.unknown().optional()})}).strict(),Gf=D.union([Vf,Hf,Uf,Wf]),D.union([Uf,Wf]),Kf=zf.strict(),qf=Lf.extend({requestId:Bf.optional(),reason:D.string().optional()}),Jf=Rf.extend({method:D.literal(`notifications/cancelled`),params:qf}),Yf=D.object({src:D.string(),mimeType:D.string().optional(),sizes:D.array(D.string()).optional(),theme:D.enum([`light`,`dark`]).optional()}),Xf=D.object({icons:D.array(Yf).optional()}),Zf=D.object({name:D.string(),title:D.string().optional()}),Qf=Zf.extend({...Zf.shape,...Xf.shape,version:D.string(),websiteUrl:D.string().optional(),description:D.string().optional()}),$f=D.intersection(D.object({applyDefaults:D.boolean().optional()}),Of),ep=D.preprocess(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,D.intersection(D.object({form:$f.optional(),url:Of.optional()}),Of.optional())),tp=D.looseObject({list:Of.optional(),cancel:Of.optional(),requests:D.looseObject({sampling:D.looseObject({createMessage:Of.optional()}).optional(),elicitation:D.looseObject({create:Of.optional()}).optional()}).optional()}),np=D.looseObject({list:Of.optional(),cancel:Of.optional(),requests:D.looseObject({tools:D.looseObject({call:Of.optional()}).optional()}).optional()}),rp=D.object({experimental:D.record(D.string(),Of).optional(),sampling:D.object({context:Of.optional(),tools:Of.optional()}).optional(),elicitation:ep.optional(),roots:D.object({listChanged:D.boolean().optional()}).optional(),tasks:tp.optional(),extensions:D.record(D.string(),Of).optional()}),ip=Pf.extend({protocolVersion:D.string(),capabilities:rp,clientInfo:Qf}),ap=If.extend({method:D.literal(`initialize`),params:ip}),op=D.object({experimental:D.record(D.string(),Of).optional(),logging:Of.optional(),completions:Of.optional(),prompts:D.object({listChanged:D.boolean().optional()}).optional(),resources:D.object({subscribe:D.boolean().optional(),listChanged:D.boolean().optional()}).optional(),tools:D.object({listChanged:D.boolean().optional()}).optional(),tasks:np.optional(),extensions:D.record(D.string(),Of).optional()}),sp=zf.extend({protocolVersion:D.string(),capabilities:op,serverInfo:Qf,instructions:D.string().optional()}),cp=Rf.extend({method:D.literal(`notifications/initialized`),params:Lf.optional()}),lp=If.extend({method:D.literal(`ping`),params:Pf.optional()}),up=D.object({progress:D.number(),total:D.optional(D.number()),message:D.optional(D.string())}),dp=D.object({...Lf.shape,...up.shape,progressToken:kf}),fp=Rf.extend({method:D.literal(`notifications/progress`),params:dp}),pp=Pf.extend({cursor:Af.optional()}),mp=If.extend({params:pp.optional()}),hp=zf.extend({nextCursor:Af.optional()}),gp=D.enum([`working`,`input_required`,`completed`,`failed`,`cancelled`]),_p=D.object({taskId:D.string(),status:gp,ttl:D.union([D.number(),D.null()]),createdAt:D.string(),lastUpdatedAt:D.string(),pollInterval:D.optional(D.number()),statusMessage:D.optional(D.string())}),vp=zf.extend({task:_p}),yp=Lf.merge(_p),bp=Rf.extend({method:D.literal(`notifications/tasks/status`),params:yp}),xp=If.extend({method:D.literal(`tasks/get`),params:Pf.extend({taskId:D.string()})}),Sp=zf.merge(_p),Cp=If.extend({method:D.literal(`tasks/result`),params:Pf.extend({taskId:D.string()})}),wp=zf.loose(),Tp=mp.extend({method:D.literal(`tasks/list`)}),Ep=hp.extend({tasks:D.array(_p)}),Dp=If.extend({method:D.literal(`tasks/cancel`),params:Pf.extend({taskId:D.string()})}),Op=zf.merge(_p),kp=D.object({uri:D.string(),mimeType:D.optional(D.string()),_meta:D.record(D.string(),D.unknown()).optional()}),Ap=kp.extend({text:D.string()}),jp=D.string().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),Mp=kp.extend({blob:jp}),Np=D.enum([`user`,`assistant`]),Pp=D.object({audience:D.array(Np).optional(),priority:D.number().min(0).max(1).optional(),lastModified:D.iso.datetime({offset:!0}).optional()}),Fp=D.object({...Zf.shape,...Xf.shape,uri:D.string(),description:D.optional(D.string()),mimeType:D.optional(D.string()),size:D.optional(D.number()),annotations:Pp.optional(),_meta:D.optional(D.looseObject({}))}),Ip=D.object({...Zf.shape,...Xf.shape,uriTemplate:D.string(),description:D.optional(D.string()),mimeType:D.optional(D.string()),annotations:Pp.optional(),_meta:D.optional(D.looseObject({}))}),Lp=mp.extend({method:D.literal(`resources/list`)}),Rp=hp.extend({resources:D.array(Fp)}),zp=mp.extend({method:D.literal(`resources/templates/list`)}),Bp=hp.extend({resourceTemplates:D.array(Ip)}),Vp=Pf.extend({uri:D.string()}),Hp=Vp,Up=If.extend({method:D.literal(`resources/read`),params:Hp}),Wp=zf.extend({contents:D.array(D.union([Ap,Mp]))}),Gp=Rf.extend({method:D.literal(`notifications/resources/list_changed`),params:Lf.optional()}),Kp=Vp,qp=If.extend({method:D.literal(`resources/subscribe`),params:Kp}),Jp=Vp,Yp=If.extend({method:D.literal(`resources/unsubscribe`),params:Jp}),Xp=Lf.extend({uri:D.string()}),Zp=Rf.extend({method:D.literal(`notifications/resources/updated`),params:Xp}),Qp=D.object({name:D.string(),description:D.optional(D.string()),required:D.optional(D.boolean())}),$p=D.object({...Zf.shape,...Xf.shape,description:D.optional(D.string()),arguments:D.optional(D.array(Qp)),_meta:D.optional(D.looseObject({}))}),em=mp.extend({method:D.literal(`prompts/list`)}),tm=hp.extend({prompts:D.array($p)}),nm=Pf.extend({name:D.string(),arguments:D.record(D.string(),D.string()).optional()}),rm=If.extend({method:D.literal(`prompts/get`),params:nm}),im=D.object({type:D.literal(`text`),text:D.string(),annotations:Pp.optional(),_meta:D.record(D.string(),D.unknown()).optional()}),am=D.object({type:D.literal(`image`),data:jp,mimeType:D.string(),annotations:Pp.optional(),_meta:D.record(D.string(),D.unknown()).optional()}),om=D.object({type:D.literal(`audio`),data:jp,mimeType:D.string(),annotations:Pp.optional(),_meta:D.record(D.string(),D.unknown()).optional()}),sm=D.object({type:D.literal(`tool_use`),name:D.string(),id:D.string(),input:D.record(D.string(),D.unknown()),_meta:D.record(D.string(),D.unknown()).optional()}),cm=D.object({type:D.literal(`resource`),resource:D.union([Ap,Mp]),annotations:Pp.optional(),_meta:D.record(D.string(),D.unknown()).optional()}),lm=Fp.extend({type:D.literal(`resource_link`)}),um=D.union([im,am,om,lm,cm]),dm=D.object({role:Np,content:um}),fm=zf.extend({description:D.string().optional(),messages:D.array(dm)}),pm=Rf.extend({method:D.literal(`notifications/prompts/list_changed`),params:Lf.optional()}),mm=D.object({title:D.string().optional(),readOnlyHint:D.boolean().optional(),destructiveHint:D.boolean().optional(),idempotentHint:D.boolean().optional(),openWorldHint:D.boolean().optional()}),hm=D.object({taskSupport:D.enum([`required`,`optional`,`forbidden`]).optional()}),gm=D.object({...Zf.shape,...Xf.shape,description:D.string().optional(),inputSchema:D.object({type:D.literal(`object`),properties:D.record(D.string(),Df).optional(),required:D.array(D.string()).optional()}).catchall(D.unknown()),outputSchema:D.object({type:D.literal(`object`),properties:D.record(D.string(),Df).optional(),required:D.array(D.string()).optional()}).catchall(D.unknown()).optional(),annotations:mm.optional(),execution:hm.optional(),_meta:D.record(D.string(),D.unknown()).optional()}),_m=mp.extend({method:D.literal(`tools/list`)}),vm=hp.extend({tools:D.array(gm)}),ym=zf.extend({content:D.array(um).default([]),structuredContent:D.record(D.string(),D.unknown()).optional(),isError:D.boolean().optional()}),ym.or(zf.extend({toolResult:D.unknown()})),bm=Ff.extend({name:D.string(),arguments:D.record(D.string(),D.unknown()).optional()}),xm=If.extend({method:D.literal(`tools/call`),params:bm}),Sm=Rf.extend({method:D.literal(`notifications/tools/list_changed`),params:Lf.optional()}),D.object({autoRefresh:D.boolean().default(!0),debounceMs:D.number().int().nonnegative().default(300)}),Cm=D.enum([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),wm=Pf.extend({level:Cm}),Tm=If.extend({method:D.literal(`logging/setLevel`),params:wm}),Em=Lf.extend({level:Cm,logger:D.string().optional(),data:D.unknown()}),Dm=Rf.extend({method:D.literal(`notifications/message`),params:Em}),Om=D.object({name:D.string().optional()}),km=D.object({hints:D.array(Om).optional(),costPriority:D.number().min(0).max(1).optional(),speedPriority:D.number().min(0).max(1).optional(),intelligencePriority:D.number().min(0).max(1).optional()}),Am=D.object({mode:D.enum([`auto`,`required`,`none`]).optional()}),jm=D.object({type:D.literal(`tool_result`),toolUseId:D.string().describe(`The unique identifier for the corresponding tool call.`),content:D.array(um).default([]),structuredContent:D.object({}).loose().optional(),isError:D.boolean().optional(),_meta:D.record(D.string(),D.unknown()).optional()}),Mm=D.discriminatedUnion(`type`,[im,am,om]),Nm=D.discriminatedUnion(`type`,[im,am,om,sm,jm]),Pm=D.object({role:Np,content:D.union([Nm,D.array(Nm)]),_meta:D.record(D.string(),D.unknown()).optional()}),Fm=Ff.extend({messages:D.array(Pm),modelPreferences:km.optional(),systemPrompt:D.string().optional(),includeContext:D.enum([`none`,`thisServer`,`allServers`]).optional(),temperature:D.number().optional(),maxTokens:D.number().int(),stopSequences:D.array(D.string()).optional(),metadata:Of.optional(),tools:D.array(gm).optional(),toolChoice:Am.optional()}),Im=If.extend({method:D.literal(`sampling/createMessage`),params:Fm}),Lm=zf.extend({model:D.string(),stopReason:D.optional(D.enum([`endTurn`,`stopSequence`,`maxTokens`]).or(D.string())),role:Np,content:Mm}),Rm=zf.extend({model:D.string(),stopReason:D.optional(D.enum([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(D.string())),role:Np,content:D.union([Nm,D.array(Nm)])}),zm=D.object({type:D.literal(`boolean`),title:D.string().optional(),description:D.string().optional(),default:D.boolean().optional()}),Bm=D.object({type:D.literal(`string`),title:D.string().optional(),description:D.string().optional(),minLength:D.number().optional(),maxLength:D.number().optional(),format:D.enum([`email`,`uri`,`date`,`date-time`]).optional(),default:D.string().optional()}),Vm=D.object({type:D.enum([`number`,`integer`]),title:D.string().optional(),description:D.string().optional(),minimum:D.number().optional(),maximum:D.number().optional(),default:D.number().optional()}),Hm=D.object({type:D.literal(`string`),title:D.string().optional(),description:D.string().optional(),enum:D.array(D.string()),default:D.string().optional()}),Um=D.object({type:D.literal(`string`),title:D.string().optional(),description:D.string().optional(),oneOf:D.array(D.object({const:D.string(),title:D.string()})),default:D.string().optional()}),Wm=D.object({type:D.literal(`string`),title:D.string().optional(),description:D.string().optional(),enum:D.array(D.string()),enumNames:D.array(D.string()).optional(),default:D.string().optional()}),Gm=D.union([Hm,Um]),Km=D.object({type:D.literal(`array`),title:D.string().optional(),description:D.string().optional(),minItems:D.number().optional(),maxItems:D.number().optional(),items:D.object({type:D.literal(`string`),enum:D.array(D.string())}),default:D.array(D.string()).optional()}),qm=D.object({type:D.literal(`array`),title:D.string().optional(),description:D.string().optional(),minItems:D.number().optional(),maxItems:D.number().optional(),items:D.object({anyOf:D.array(D.object({const:D.string(),title:D.string()}))}),default:D.array(D.string()).optional()}),Jm=D.union([Km,qm]),Ym=D.union([Wm,Gm,Jm]),Xm=D.union([Ym,zm,Bm,Vm]),Zm=Ff.extend({mode:D.literal(`form`).optional(),message:D.string(),requestedSchema:D.object({type:D.literal(`object`),properties:D.record(D.string(),Xm),required:D.array(D.string()).optional()})}),Qm=Ff.extend({mode:D.literal(`url`),message:D.string(),elicitationId:D.string(),url:D.string().url()}),$m=D.union([Zm,Qm]),eh=If.extend({method:D.literal(`elicitation/create`),params:$m}),th=Lf.extend({elicitationId:D.string()}),nh=Rf.extend({method:D.literal(`notifications/elicitation/complete`),params:th}),rh=zf.extend({action:D.enum([`accept`,`decline`,`cancel`]),content:D.preprocess(e=>e===null?void 0:e,D.record(D.string(),D.union([D.string(),D.number(),D.boolean(),D.array(D.string())])).optional())}),ih=D.object({type:D.literal(`ref/resource`),uri:D.string()}),ah=D.object({type:D.literal(`ref/prompt`),name:D.string()}),oh=Pf.extend({ref:D.union([ah,ih]),argument:D.object({name:D.string(),value:D.string()}),context:D.object({arguments:D.record(D.string(),D.string()).optional()}).optional()}),sh=If.extend({method:D.literal(`completion/complete`),params:oh}),ch=zf.extend({completion:D.looseObject({values:D.array(D.string()).max(100),total:D.optional(D.number().int()),hasMore:D.optional(D.boolean())})}),lh=D.object({uri:D.string().startsWith(`file://`),name:D.string().optional(),_meta:D.record(D.string(),D.unknown()).optional()}),uh=If.extend({method:D.literal(`roots/list`),params:Pf.optional()}),dh=zf.extend({roots:D.array(lh)}),fh=Rf.extend({method:D.literal(`notifications/roots/list_changed`),params:Lf.optional()}),ph=D.union([lp,ap,sh,Tm,rm,em,Lp,zp,Up,qp,Yp,xm,_m,xp,Cp,Tp,Dp]),mh=D.union([Jf,fp,cp,fh,bp]),D.union([Kf,Lm,Rm,rh,dh,Sp,Ep,vp]),hh=D.union([lp,Im,eh,uh,xp,Cp,Tp,Dp]),gh=D.union([Jf,fp,Dm,Zp,Gp,Sm,pm,bp,nh]),D.union([Kf,sp,ch,fm,tm,Rp,Bp,Wp,ym,vm,Sp,Ep,vp]),_h={ping:Kf,initialize:sp,"completion/complete":ch,"logging/setLevel":Kf,"prompts/get":fm,"prompts/list":tm,"resources/list":Rp,"resources/templates/list":Bp,"resources/read":Wp,"resources/subscribe":Kf,"resources/unsubscribe":Kf,"tools/call":D.union([ym,vp]),"tools/list":vm,"sampling/createMessage":D.union([Rm,vp]),"elicitation/create":D.union([rh,vp]),"roots/list":dh,"tasks/get":Sp,"tasks/result":zf,"tasks/list":Ep,"tasks/cancel":Op},vh=Dd([...ph.options,...hh.options]),yh=Dd([...mh.options,...gh.options]),bh=e=>Vf.safeParse(e).success,xh=e=>Hf.safeParse(e).success,Sh=e=>Uf.safeParse(e).success,Ch=e=>Wf.safeParse(e).success,wh=e=>Ff.safeParse(e).success,Th=e=>ap.safeParse(e).success,Eh=e=>cp.safeParse(e).success,Dh=class{_taskStore;_taskMessageQueue;_taskProgressTokens=new Map;_requestResolvers=new Map;_options;_host;constructor(e){this._options=e,this._taskStore=e.taskStore,this._taskMessageQueue=e.taskMessageQueue}bind(e){this._host=e,this._taskStore&&(e.registerHandler(`tasks/get`,async(e,t)=>{let n=e.params;return{...await this.handleGetTask(n.taskId,t.sessionId)}}),e.registerHandler(`tasks/result`,async(t,n)=>{let r=t.params;return await this.handleGetTaskPayload(r.taskId,n.sessionId,n.mcpReq.signal,async t=>{await e.sendOnResponseStream(t,n.mcpReq.id)})}),e.registerHandler(`tasks/list`,async(e,t)=>{let n=e.params;return await this.handleListTasks(n?.cursor,t.sessionId)}),e.registerHandler(`tasks/cancel`,async(e,t)=>{let n=e.params;return await this.handleCancelTask(n.taskId,t.sessionId)}))}get _requireHost(){if(!this._host)throw new U(H.InternalError,`TaskManager is not bound to a Protocol host — call bind() first`);return this._host}get taskStore(){return this._taskStore}get _requireTaskStore(){if(!this._taskStore)throw new U(H.InternalError,`TaskStore is not configured`);return this._taskStore}get taskMessageQueue(){return this._taskMessageQueue}async*requestStream(e,t,n){let r=this._requireHost,{task:i}=n??{};if(!i){try{yield{type:`result`,result:await r.request(e,t,n)}}catch(e){yield{type:`error`,error:e instanceof Error?e:Error(String(e))}}return}let a;try{let i=await r.request(e,vp,n);if(i.task)a=i.task.taskId,yield{type:`taskCreated`,task:i.task};else throw new U(H.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:a},n);if(yield{type:`taskStatus`,task:e},Pd(e.status)){switch(e.status){case`completed`:yield{type:`result`,result:await this.getTaskResult({taskId:a},t,n)};break;case`failed`:yield{type:`error`,error:new U(H.InternalError,`Task ${a} failed`)};break;case`cancelled`:yield{type:`error`,error:new U(H.InternalError,`Task ${a} was cancelled`)}}return}if(e.status===`input_required`){yield{type:`result`,result:await this.getTaskResult({taskId:a},t,n)};return}let r=e.pollInterval??this._options.defaultTaskPollInterval??1e3;await new Promise(e=>setTimeout(e,r)),n?.signal?.throwIfAborted()}}catch(e){yield{type:`error`,error:e instanceof Error?e:Error(String(e))}}}async getTask(e,t){return this._requireHost.request({method:`tasks/get`,params:e},Sp,t)}async getTaskResult(e,t,n){return this._requireHost.request({method:`tasks/result`,params:e},t,n)}async listTasks(e,t){return this._requireHost.request({method:`tasks/list`,params:e},Ep,t)}async cancelTask(e,t){return this._requireHost.request({method:`tasks/cancel`,params:e},Op,t)}async handleGetTask(e,t){let n=await this._requireTaskStore.getTask(e,t);if(!n)throw new U(H.InvalidParams,`Failed to retrieve task: Task not found`);return n}async handleGetTaskPayload(e,t,n,r){let i=async()=>{if(this._taskMessageQueue){let n;for(;n=await this._taskMessageQueue.dequeue(e,t);){if(n.type===`response`||n.type===`error`){let e=n.message,t=e.id,r=this._requestResolvers.get(t);if(r){if(this._requestResolvers.delete(t),n.type===`response`)r(e);else{let t=e;r(new U(t.error.code,t.error.message,t.error.data))}}else{let e=n.type===`response`?`Response`:`Error`;this._host?.reportError(Error(`${e} handler missing for request ${t}`))}continue}await r(n.message)}}let a=await this._requireTaskStore.getTask(e,t);if(!a)throw new U(H.InvalidParams,`Task not found: ${e}`);if(!Pd(a.status))return await this._waitForTaskUpdate(a.pollInterval,n),await i();let o=await this._requireTaskStore.getTaskResult(e,t);return await this._clearTaskQueue(e),{...o,_meta:{...o._meta,[bf]:{taskId:e}}}};return await i()}async handleListTasks(e,t){try{let{tasks:n,nextCursor:r}=await this._requireTaskStore.listTasks(e,t);return{tasks:n,nextCursor:r,_meta:{}}}catch(e){throw new U(H.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}async handleCancelTask(e,t){try{let n=await this._requireTaskStore.getTask(e,t);if(!n)throw new U(H.InvalidParams,`Task not found: ${e}`);if(Pd(n.status))throw new U(H.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._requireTaskStore.updateTaskStatus(e,`cancelled`,`Client cancelled task execution.`,t),await this._clearTaskQueue(e);let r=await this._requireTaskStore.getTask(e,t);if(!r)throw new U(H.InvalidParams,`Task not found after cancellation: ${e}`);return{_meta:{},...r}}catch(e){throw e instanceof U?e:new U(H.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}prepareOutboundRequest(e,t,n,r,i){let{task:a,relatedTask:o}=t??{};a&&(e.params={...e.params,task:a}),o&&(e.params={...e.params,_meta:{...e.params?._meta,[bf]:o}});let s=o?.taskId;return s?(this._requestResolvers.set(n,r),this._enqueueTaskMessage(s,{type:`request`,message:e,timestamp:Date.now()}).catch(e=>{i(e)}),!0):!1}extractInboundTaskContext(e,t){let n=(e.params?._meta)?.[bf]?.taskId,r=wh(e.params)?e.params.task:void 0,i;return this._taskStore&&(i={id:n,store:this.createRequestTaskStore(e,t),requestedTtl:r?.ttl}),!n&&!r&&!i?{}:{relatedTaskId:n,taskCreationParams:r,taskContext:i}}wrapSendNotification(e,t){return async n=>{await t(n,{relatedTask:{taskId:e}})}}wrapSendRequest(e,t,n){return async(r,i,a)=>{let o={...a};e&&!o.relatedTask&&(o.relatedTask={taskId:e});let s=o.relatedTask?.taskId??e;return s&&t&&await t.updateTaskStatus(s,`input_required`),await n(r,i,o)}}handleResponse(e){let t=Number(e.id),n=this._requestResolvers.get(t);return n?(this._requestResolvers.delete(t),Sh(e)?n(e):n(new U(e.error.code,e.error.message,e.error.data)),!0):!1}shouldPreserveProgressHandler(e,t){if(Sh(e)&&e.result&&typeof e.result==`object`){let n=e.result;if(n.task&&typeof n.task==`object`){let e=n.task;if(typeof e.taskId==`string`)return this._taskProgressTokens.set(e.taskId,t),!0}}return!1}async routeNotification(e,t){let n=t?.relatedTask?.taskId;if(!n)return!1;let r={...e,jsonrpc:`2.0`,params:{...e.params,_meta:{...e.params?._meta,[bf]:t.relatedTask}}};return await this._enqueueTaskMessage(n,{type:`notification`,message:r,timestamp:Date.now()}),!0}async routeResponse(e,t,n){return!e||!this._taskMessageQueue?!1:(await(Ch(t)?this._enqueueTaskMessage(e,{type:`error`,message:t,timestamp:Date.now()},n):this._enqueueTaskMessage(e,{type:`response`,message:t,timestamp:Date.now()},n)),!0)}createRequestTaskStore(e,t){let n=this._requireTaskStore,r=this._host;return{createTask:async r=>{if(!e)throw Error(`No request provided`);return await n.createTask(r,e.id,{method:e.method,params:e.params},t)},getTask:async e=>{let r=await n.getTask(e,t);if(!r)throw new U(H.InvalidParams,`Failed to retrieve task: Task not found`);return r},storeTaskResult:async(e,i,a)=>{await n.storeTaskResult(e,i,a,t);let o=await n.getTask(e,t);if(o){let t=bp.parse({method:`notifications/tasks/status`,params:o});await r?.notification(t),Pd(o.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>n.getTaskResult(e,t),updateTaskStatus:async(e,i,a)=>{let o=await n.getTask(e,t);if(!o)throw new U(H.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(Pd(o.status))throw new U(H.InvalidParams,`Cannot update task "${e}" from terminal status "${o.status}" to "${i}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(e,i,a,t);let s=await n.getTask(e,t);if(s){let t=bp.parse({method:`notifications/tasks/status`,params:s});await r?.notification(t),Pd(s.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}processInboundRequest(e,t){let n=this.extractInboundTaskContext(e,t.sessionId),r=n?.relatedTaskId,i=r?this.wrapSendNotification(r,t.sendNotification):e=>t.sendNotification(e),a=r?this.wrapSendRequest(r,n?.taskContext?.store,t.sendRequest):n?.taskContext?this.wrapSendRequest(``,n.taskContext.store,t.sendRequest):t.sendRequest,o=!!n?.taskCreationParams;return{taskContext:n?.taskContext,sendNotification:i,sendRequest:a,routeResponse:async e=>r?this.routeResponse(r,e,t.sessionId):!1,hasTaskCreationParams:o,validateInbound:o?()=>this._requireHost.assertTaskHandlerCapability(e.method):void 0}}processOutboundRequest(e,t,n,r,i){return this._requireHost.enforceStrictCapabilities&&t?.task&&this._requireHost.assertTaskCapability(e.method),{queued:this.prepareOutboundRequest(e,t,n,r,i)}}processInboundResponse(e,t){return this.handleResponse(e)?{consumed:!0,preserveProgress:!1}:{consumed:!1,preserveProgress:this.shouldPreserveProgressHandler(e,t)}}async processOutboundNotification(e,t){if(await this.routeNotification(e,t))return{queued:!0};let n={...e,jsonrpc:`2.0`};return t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta,[bf]:t.relatedTask}}}),{queued:!1,jsonrpcNotification:n}}onClose(){this._taskProgressTokens.clear(),this._requestResolvers.clear()}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw Error(`Cannot enqueue task message: taskStore and taskMessageQueue are not configured`);await this._taskMessageQueue.enqueue(e,t,n,this._options.maxTaskQueueSize)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,t);for(let t of n)if(t.type===`request`&&bh(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new U(H.InternalError,`Task cancelled or completed`)),this._requestResolvers.delete(n)):this._host?.reportError(Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t){let n=e??this._options.defaultTaskPollInterval??1e3;return new Promise((e,r)=>{if(t.aborted){r(new U(H.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,n);t.addEventListener(`abort`,()=>{clearTimeout(i),r(new U(H.InvalidRequest,`Request cancelled`))},{once:!0})})}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);t!==void 0&&(this._host?.removeProgressHandler(t),this._taskProgressTokens.delete(e))}},Oh=class extends Dh{constructor(){super({})}processInboundRequest(e,t){let n=wh(e.params)&&!!e.params.task;return{taskContext:void 0,sendNotification:e=>t.sendNotification(e),sendRequest:t.sendRequest,routeResponse:async()=>!1,hasTaskCreationParams:n,validateInbound:n?()=>this._requireHost.assertTaskHandlerCapability(e.method):void 0}}async processOutboundNotification(e,t){return{queued:!1,jsonrpcNotification:{...e,jsonrpc:`2.0`}}}},kh=6e4,Ah=class{_transport;_requestMessageId=0;_requestHandlers=new Map;_requestHandlerAbortControllers=new Map;_notificationHandlers=new Map;_responseHandlers=new Map;_progressHandlers=new Map;_timeoutInfo=new Map;_pendingDebouncedNotifications=new Set;_taskManager;_supportedProtocolVersions;onclose;onerror;fallbackRequestHandler;fallbackNotificationHandler;constructor(e){this._options=e,this._supportedProtocolVersions=e?.supportedProtocolVersions??yf,this._taskManager=e?.tasks?new Dh(e.tasks):new Oh,this._bindTaskManager(),this.setNotificationHandler(`notifications/cancelled`,e=>{this._oncancel(e)}),this.setNotificationHandler(`notifications/progress`,e=>{this._onprogress(e)}),this.setRequestHandler(`ping`,e=>({}))}get taskManager(){return this._taskManager}_bindTaskManager(){let e=this._taskManager,t={request:(e,t,n)=>this._requestWithSchema(e,t,n),notification:(e,t)=>this.notification(e,t),reportError:e=>this._onerror(e),removeProgressHandler:e=>this._progressHandlers.delete(e),registerHandler:(e,t)=>{let n=Od(e);this._requestHandlers.set(e,(e,r)=>(n.parse(e),t(e,r)))},sendOnResponseStream:async(e,t)=>{await this._transport?.send(e,{relatedRequestId:t})},enforceStrictCapabilities:this._options?.enforceStrictCapabilities===!0,assertTaskCapability:e=>this.assertTaskCapability(e),assertTaskHandlerCapability:e=>this.assertTaskHandlerCapability(e)};e.bind(t)}async _oncancel(e){e.params.requestId&&this._requestHandlerAbortControllers.get(e.params.requestId)?.abort(e.params.reason)}_setupTimeout(e,t,n,r,i=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(r,t),startTime:Date.now(),timeout:t,maxTotalTimeout:n,resetTimeoutOnProgress:i,onTimeout:r})}_resetTimeout(e){let t=this._timeoutInfo.get(e);if(!t)return!1;let n=Date.now()-t.startTime;if(t.maxTotalTimeout&&n>=t.maxTotalTimeout)throw this._timeoutInfo.delete(e),new V(uf.RequestTimeout,`Maximum total timeout exceeded`,{maxTotalTimeout:t.maxTotalTimeout,totalElapsed:n});return clearTimeout(t.timeoutId),t.timeoutId=setTimeout(t.onTimeout,t.timeout),!0}_cleanupTimeout(e){let t=this._timeoutInfo.get(e);t&&(clearTimeout(t.timeoutId),this._timeoutInfo.delete(e))}async connect(e){this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{try{t?.()}finally{this._onclose()}};let n=this.transport?.onerror;this._transport.onerror=e=>{n?.(e),this._onerror(e)};let r=this._transport?.onmessage;this._transport.onmessage=(e,t)=>{r?.(e,t),Sh(e)||Ch(e)?this._onresponse(e):bh(e)?this._onrequest(e,t):xh(e)?this._onnotification(e):this._onerror(Error(`Unknown message type: ${JSON.stringify(e)}`))},e.setSupportedProtocolVersions?.(this._supportedProtocolVersions),await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._taskManager.onClose(),this._pendingDebouncedNotifications.clear();for(let e of this._timeoutInfo.values())clearTimeout(e.timeoutId);this._timeoutInfo.clear();let t=this._requestHandlerAbortControllers;this._requestHandlerAbortControllers=new Map;let n=new V(uf.ConnectionClosed,`Connection closed`);this._transport=void 0;try{this.onclose?.()}finally{for(let t of e.values())t(n);for(let e of t.values())e.abort(n)}}_onerror(e){this.onerror?.(e)}_onnotification(e){let t=this._notificationHandlers.get(e.method)??this.fallbackNotificationHandler;t!==void 0&&Promise.resolve().then(()=>t(e)).catch(e=>this._onerror(Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,r=this._transport,i={sessionId:r?.sessionId,sendNotification:(t,n)=>this.notification(t,{...n,relatedRequestId:e.id}),sendRequest:(t,n,r)=>this._requestWithSchema(t,n,{...r,relatedRequestId:e.id})},a=this._taskManager.processInboundRequest(e,i),o=a.sendNotification,s=a.sendRequest,c=a.taskContext,l=a.routeResponse,u=[];if(a.validateInbound&&u.push(a.validateInbound),n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:H.MethodNotFound,message:`Method not found`}};l(t).then(e=>{e||r?.send(t).catch(e=>this._onerror(Error(`Failed to send an error response: ${e}`)))}).catch(e=>this._onerror(Error(`Failed to enqueue error response: ${e}`)));return}let d=new AbortController;this._requestHandlerAbortControllers.set(e.id,d);let f={sessionId:r?.sessionId,mcpReq:{id:e.id,method:e.method,_meta:e.params?._meta,signal:d.signal,send:(e,t)=>s(e,Ed(e.method),t),notify:o},http:t?.authInfo?{authInfo:t.authInfo}:void 0,task:c},p=this.buildContext(f,t);Promise.resolve().then(()=>{for(let e of u)e()}).then(()=>n(e,p)).then(async t=>{if(d.signal.aborted)return;let n={result:t,jsonrpc:`2.0`,id:e.id};await l(n)||await r?.send(n)},async t=>{if(d.signal.aborted)return;let n={jsonrpc:`2.0`,id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:H.InternalError,message:t.message??`Internal error`,...t.data!==void 0&&{data:t.data}}};await l(n)||await r?.send(n)}).catch(e=>this._onerror(Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===d&&this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:t,...n}=e.params,r=Number(t),i=this._progressHandlers.get(r);if(!i){this._onerror(Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let a=this._responseHandlers.get(r),o=this._timeoutInfo.get(r);if(o&&a&&o.resetTimeoutOnProgress)try{this._resetTimeout(r)}catch(e){this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),a(e);return}i(n)}_onresponse(e){let t=Number(e.id),n=this._taskManager.processInboundResponse(e,t);if(n.consumed)return;let r=n.preserveProgress,i=this._responseHandlers.get(t);if(i===void 0){this._onerror(Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t),r||this._progressHandlers.delete(t),Sh(e)?i(e):i(U.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}request(e,t){let n=Ed(e.method);return this._requestWithSchema(e,n,t)}_requestWithSchema(e,t,n){let{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}=n??{},o,s;return new Promise((c,l)=>{let u=e=>{l(e)};if(!this._transport){u(Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method)}catch(e){u(e);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++;s=d;let f={...e,jsonrpc:`2.0`,id:d};n?.onprogress&&(this._progressHandlers.set(d,n.onprogress),f.params={...e.params,_meta:{...e.params?._meta,progressToken:d}});let p=e=>{this._progressHandlers.delete(d),this._transport?.send({jsonrpc:`2.0`,method:`notifications/cancelled`,params:{requestId:d,reason:String(e)}},{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>this._onerror(Error(`Failed to send cancellation: ${e}`))),l(e instanceof V?e:new V(uf.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=Nd(t,e.result);n.success?c(n.data):l(n.error)}catch(e){l(e)}}}),o=()=>p(n?.signal?.reason),n?.signal?.addEventListener(`abort`,o,{once:!0});let m=n?.timeout??6e4;this._setupTimeout(d,m,n?.maxTotalTimeout,()=>p(new V(uf.RequestTimeout,`Request timed out`,{timeout:m})),n?.resetTimeoutOnProgress??!1);let h=e=>{let t=this._responseHandlers.get(d);t?t(e):this._onerror(Error(`Response handler missing for side-channeled request ${d}`))},g=!1;try{this._taskManager.processOutboundRequest(f,n,d,h,e=>{this._progressHandlers.delete(d),l(e)}).queued&&(g=!0)}catch(e){this._progressHandlers.delete(d),l(e);return}g||this._transport.send(f,{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>{this._progressHandlers.delete(d),l(e)})}).finally(()=>{o&&n?.signal?.removeEventListener(`abort`,o),s!==void 0&&(this._responseHandlers.delete(s),this._cleanupTimeout(s))})}async notification(e,t){if(!this._transport)throw new V(uf.NotConnected,`Not connected`);this.assertNotificationCapability(e.method);let n=await this._taskManager.processOutboundNotification(e,t),r=n.queued,i=n.queued?void 0:n.jsonrpcNotification;if(!r){if((this._options?.debouncedNotificationMethods??[]).includes(e.method)&&!e.params&&!t?.relatedRequestId&&!t?.relatedTask){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{this._pendingDebouncedNotifications.delete(e.method),this._transport&&this._transport?.send(i,t).catch(e=>this._onerror(e))});return}await this._transport.send(i,t)}}setRequestHandler(e,t){this.assertRequestHandlerCapability(e);let n=Od(e);this._requestHandlers.set(e,(e,r)=>{let i=n.parse(e);return Promise.resolve(t(i,r))})}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,t){let n=kd(e);this._notificationHandlers.set(e,e=>{let r=n.parse(e);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}},jh=class{_buffer;append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){for(;this._buffer;){let e=this._buffer.indexOf(`
176
+ `);if(e===-1)return null;let t=this._buffer.toString(`utf8`,0,e).replace(/\r$/,``);this._buffer=this._buffer.subarray(e+1);try{return Bd(t)}catch(e){if(e instanceof SyntaxError)continue;throw e}}return null}clear(){this._buffer=void 0}},Mh=/^[A-Za-z0-9._-]{1,128}$/,Nh=1e6,Ph=1e6,Fh=1e4,Ih=1e6,Lh=class e{static isTemplate(e){return/\{[^}\s]+\}/.test(e)}static validateLength(e,t,n){if(e.length>t)throw Error(`${n} exceeds maximum length of ${t} characters (got ${e.length})`)}template;parts;get variableNames(){return this.parts.flatMap(e=>typeof e==`string`?[]:e.names)}constructor(t){e.validateLength(t,Nh,`Template`),this.template=t,this.parts=this.parse(t)}toString(){return this.template}parse(t){let n=[],r=``,i=0,a=0;for(;i<t.length;)if(t[i]===`{`){r&&=(n.push(r),``);let o=t.indexOf(`}`,i);if(o===-1)throw Error(`Unclosed template expression`);if(a++,a>Fh)throw Error(`Template contains too many expressions (max ${Fh})`);let s=t.slice(i+1,o),c=this.getOperator(s),l=s.includes(`*`),u=this.getNames(s),d=u[0];for(let t of u)e.validateLength(t,Ph,`Variable name`);n.push({name:d,operator:c,names:u,exploded:l}),i=o+1}else r+=t[i],i++;return r&&n.push(r),n}getOperator(e){return[`+`,`#`,`.`,`/`,`?`,`&`].find(t=>e.startsWith(t))||``}getNames(e){let t=this.getOperator(e);return e.slice(t.length).split(`,`).map(e=>e.replace(`*`,``).trim()).filter(e=>e.length>0)}encodeValue(t,n){return e.validateLength(t,Ph,`Variable value`),n===`+`||n===`#`?encodeURI(t):encodeURIComponent(t)}expandPart(e,t){if(e.operator===`?`||e.operator===`&`){let n=e.names.map(n=>{let r=t[n];return r===void 0?``:`${n}=${Array.isArray(r)?r.map(t=>this.encodeValue(t,e.operator)).join(`,`):this.encodeValue(r.toString(),e.operator)}`}).filter(e=>e.length>0);return n.length===0?``:(e.operator===`?`?`?`:`&`)+n.join(`&`)}if(e.names.length>1){let n=e.names.map(e=>t[e]).filter(e=>e!==void 0);return n.length===0?``:n.map(e=>Array.isArray(e)?e[0]:e).join(`,`)}let n=t[e.name];if(n===void 0)return``;let r=(Array.isArray(n)?n:[n]).map(t=>this.encodeValue(t,e.operator));switch(e.operator){case``:return r.join(`,`);case`+`:return r.join(`,`);case`#`:return`#`+r.join(`,`);case`.`:return`.`+r.join(`.`);case`/`:return`/`+r.join(`/`);default:return r.join(`,`)}}expand(e){let t=``,n=!1;for(let r of this.parts){if(typeof r==`string`){t+=r;continue}let i=this.expandPart(r,e);i&&(t+=(r.operator===`?`||r.operator===`&`)&&n?i.replace(`?`,`&`):i,(r.operator===`?`||r.operator===`&`)&&(n=!0))}return t}escapeRegExp(e){return e.replaceAll(/[.*+?^${}()|[\]\\]/g,String.raw`\$&`)}partToRegExp(t){let n=[];for(let n of t.names)e.validateLength(n,Ph,`Variable name`);if(t.operator===`?`||t.operator===`&`){for(let e=0;e<t.names.length;e++){let r=t.names[e],i=e===0?`\\`+t.operator:`&`;n.push({pattern:i+this.escapeRegExp(r)+`=([^&]+)`,name:r})}return n}let r,i=t.name;switch(t.operator){case``:r=t.exploded?`([^/,]+(?:,[^/,]+)*)`:`([^/,]+)`;break;case`+`:case`#`:r=`(.+)`;break;case`.`:r=String.raw`\.([^/,]+)`;break;case`/`:r=`/`+(t.exploded?`([^/,]+(?:,[^/,]+)*)`:`([^/,]+)`);break;default:r=`([^/]+)`}return n.push({pattern:r,name:i}),n}match(t){e.validateLength(t,Nh,`URI`);let n=`^`,r=[];for(let e of this.parts)if(typeof e==`string`)n+=this.escapeRegExp(e);else{let t=this.partToRegExp(e);for(let{pattern:i,name:a}of t)n+=i,r.push({name:a,exploded:e.exploded})}n+=`$`,e.validateLength(n,Ih,`Generated regex pattern`);let i=new RegExp(n),a=t.match(i);if(!a)return null;let o={};for(let[e,t]of r.entries()){let{name:n,exploded:r}=t,i=a[e+1],s=n.replace(`*`,``);o[s]=r&&i.includes(`,`)?i.split(`,`):i}return o}},Rh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.regexpCode=e.getEsmExportName=e.getProperty=e.safeStringify=e.stringify=e.strConcat=e.addCodeArg=e.str=e._=e.nil=e._Code=e.Name=e.IDENTIFIER=e._CodeOrName=void 0;var t=class{};e._CodeOrName=t,e.IDENTIFIER=/^[a-z$_][a-z$_0-9]*$/i;var n=class extends t{constructor(t){if(super(),!e.IDENTIFIER.test(t))throw Error(`CodeGen: name must be a valid identifier`);this.str=t}toString(){return this.str}emptyStr(){return!1}get names(){return{[this.str]:1}}};e.Name=n;var r=class extends t{constructor(e){super(),this._items=typeof e==`string`?[e]:e}toString(){return this.str}emptyStr(){if(this._items.length>1)return!1;let e=this._items[0];return e===``||e===`""`}get str(){return this._str??=this._items.reduce((e,t)=>`${e}${t}`,``)}get names(){return this._names??=this._items.reduce((e,t)=>(t instanceof n&&(e[t.str]=(e[t.str]||0)+1),e),{})}};e._Code=r,e.nil=new r(``);function i(e,...t){let n=[e[0]],i=0;for(;i<t.length;)s(n,t[i]),n.push(e[++i]);return new r(n)}e._=i;let a=new r(`+`);function o(e,...t){let n=[p(e[0])],i=0;for(;i<t.length;)n.push(a),s(n,t[i]),n.push(a,p(e[++i]));return c(n),new r(n)}e.str=o;function s(e,t){t instanceof r?e.push(...t._items):t instanceof n?e.push(t):e.push(d(t))}e.addCodeArg=s;function c(e){let t=1;for(;t<e.length-1;){if(e[t]===a){let n=l(e[t-1],e[t+1]);if(n!==void 0){e.splice(t-1,3,n);continue}e[t++]=`+`}t++}}function l(e,t){if(t===`""`)return e;if(e===`""`)return t;if(typeof e==`string`)return t instanceof n||e[e.length-1]!==`"`?void 0:typeof t==`string`?t[0]===`"`?e.slice(0,-1)+t.slice(1):void 0:`${e.slice(0,-1)}${t}"`;if(typeof t==`string`&&t[0]===`"`&&!(e instanceof n))return`"${e}${t.slice(1)}`}function u(e,t){return t.emptyStr()?e:e.emptyStr()?t:o`${e}${t}`}e.strConcat=u;function d(e){return typeof e==`number`||typeof e==`boolean`||e===null?e:p(Array.isArray(e)?e.join(`,`):e)}function f(e){return new r(p(e))}e.stringify=f;function p(e){return JSON.stringify(e).replace(/\u2028/g,`\\u2028`).replace(/\u2029/g,`\\u2029`)}e.safeStringify=p;function m(t){return typeof t==`string`&&e.IDENTIFIER.test(t)?new r(`.${t}`):i`[${t}]`}e.getProperty=m;function h(t){if(typeof t==`string`&&e.IDENTIFIER.test(t))return new r(`${t}`);throw Error(`CodeGen: invalid export name: ${t}, use explicit $id name mapping`)}e.getEsmExportName=h;function g(e){return new r(e.toString())}e.regexpCode=g})),zh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=Rh();var n=class extends Error{constructor(e){super(`CodeGen: "code" for ${e} not defined`),this.value=e.value}},r;(function(e){e[e.Started=0]=`Started`,e[e.Completed=1]=`Completed`})(r||(e.UsedValueState=r={})),e.varKinds={const:new t.Name(`const`),let:new t.Name(`let`),var:new t.Name(`var`)};var i=class{constructor({prefixes:e,parent:t}={}){this._names={},this._prefixes=e,this._parent=t}toName(e){return e instanceof t.Name?e:this.name(e)}name(e){return new t.Name(this._newName(e))}_newName(e){let t=this._names[e]||this._nameGroup(e);return`${e}${t.index++}`}_nameGroup(e){if((this._parent?._prefixes)?.has(e)||this._prefixes&&!this._prefixes.has(e))throw Error(`CodeGen: prefix "${e}" is not allowed in this scope`);return this._names[e]={prefix:e,index:0}}};e.Scope=i;var a=class extends t.Name{constructor(e,t){super(t),this.prefix=e}setValue(e,{property:n,itemIndex:r}){this.value=e,this.scopePath=(0,t._)`.${new t.Name(n)}[${r}]`}};e.ValueScopeName=a;let o=(0,t._)`\n`;e.ValueScope=class extends i{constructor(e){super(e),this._values={},this._scope=e.scope,this.opts={...e,_n:e.lines?o:t.nil}}get(){return this._scope}name(e){return new a(e,this._newName(e))}value(e,t){if(t.ref===void 0)throw Error(`CodeGen: ref must be passed in value`);let n=this.toName(e),{prefix:r}=n,i=t.key??t.ref,a=this._values[r];if(a){let e=a.get(i);if(e)return e}else a=this._values[r]=new Map;a.set(i,n);let o=this._scope[r]||(this._scope[r]=[]),s=o.length;return o[s]=t.ref,n.setValue(t,{property:r,itemIndex:s}),n}getValue(e,t){let n=this._values[e];if(n)return n.get(t)}scopeRefs(e,n=this._values){return this._reduceValues(n,n=>{if(n.scopePath===void 0)throw Error(`CodeGen: name "${n}" has no value`);return(0,t._)`${e}${n.scopePath}`})}scopeCode(e=this._values,t,n){return this._reduceValues(e,e=>{if(e.value===void 0)throw Error(`CodeGen: name "${e}" has no value`);return e.value.code},t,n)}_reduceValues(i,a,o={},s){let c=t.nil;for(let l in i){let u=i[l];if(!u)continue;let d=o[l]=o[l]||new Map;u.forEach(i=>{if(d.has(i))return;d.set(i,r.Started);let o=a(i);if(o){let n=this.opts.es5?e.varKinds.var:e.varKinds.const;c=(0,t._)`${c}${n} ${i} = ${o};${this.opts._n}`}else if(o=s?.(i))c=(0,t._)`${c}${o}${this.opts._n}`;else throw new n(i);d.set(i,r.Completed)})}return c}}})),W=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.or=e.and=e.not=e.CodeGen=e.operators=e.varKinds=e.ValueScopeName=e.ValueScope=e.Scope=e.Name=e.regexpCode=e.stringify=e.getProperty=e.nil=e.strConcat=e.str=e._=void 0;let t=Rh(),n=zh();var r=Rh();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return r._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return r.str}}),Object.defineProperty(e,"strConcat",{enumerable:!0,get:function(){return r.strConcat}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return r.nil}}),Object.defineProperty(e,"getProperty",{enumerable:!0,get:function(){return r.getProperty}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return r.stringify}}),Object.defineProperty(e,"regexpCode",{enumerable:!0,get:function(){return r.regexpCode}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return r.Name}});var i=zh();Object.defineProperty(e,"Scope",{enumerable:!0,get:function(){return i.Scope}}),Object.defineProperty(e,"ValueScope",{enumerable:!0,get:function(){return i.ValueScope}}),Object.defineProperty(e,"ValueScopeName",{enumerable:!0,get:function(){return i.ValueScopeName}}),Object.defineProperty(e,"varKinds",{enumerable:!0,get:function(){return i.varKinds}}),e.operators={GT:new t._Code(`>`),GTE:new t._Code(`>=`),LT:new t._Code(`<`),LTE:new t._Code(`<=`),EQ:new t._Code(`===`),NEQ:new t._Code(`!==`),NOT:new t._Code(`!`),OR:new t._Code(`||`),AND:new t._Code(`&&`),ADD:new t._Code(`+`)};var a=class{optimizeNodes(){return this}optimizeNames(e,t){return this}},o=class extends a{constructor(e,t,n){super(),this.varKind=e,this.name=t,this.rhs=n}render({es5:e,_n:t}){let r=e?n.varKinds.var:this.varKind,i=this.rhs===void 0?``:` = ${this.rhs}`;return`${r} ${this.name}${i};`+t}optimizeNames(e,t){if(e[this.name.str])return this.rhs&&=O(this.rhs,e,t),this}get names(){return this.rhs instanceof t._CodeOrName?this.rhs.names:{}}},s=class extends a{constructor(e,t,n){super(),this.lhs=e,this.rhs=t,this.sideEffects=n}render({_n:e}){return`${this.lhs} = ${this.rhs};`+e}optimizeNames(e,n){if(!(this.lhs instanceof t.Name&&!e[this.lhs.str]&&!this.sideEffects))return this.rhs=O(this.rhs,e,n),this}get names(){return D(this.lhs instanceof t.Name?{}:{...this.lhs.names},this.rhs)}},c=class extends s{constructor(e,t,n,r){super(e,n,r),this.op=t}render({_n:e}){return`${this.lhs} ${this.op}= ${this.rhs};`+e}},l=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`${this.label}:`+e}},u=class extends a{constructor(e){super(),this.label=e,this.names={}}render({_n:e}){return`break${this.label?` ${this.label}`:``};`+e}},d=class extends a{constructor(e){super(),this.error=e}render({_n:e}){return`throw ${this.error};`+e}get names(){return this.error.names}},f=class extends a{constructor(e){super(),this.code=e}render({_n:e}){return`${this.code};`+e}optimizeNodes(){return`${this.code}`?this:void 0}optimizeNames(e,t){return this.code=O(this.code,e,t),this}get names(){return this.code instanceof t._CodeOrName?this.code.names:{}}},p=class extends a{constructor(e=[]){super(),this.nodes=e}render(e){return this.nodes.reduce((t,n)=>t+n.render(e),``)}optimizeNodes(){let{nodes:e}=this,t=e.length;for(;t--;){let n=e[t].optimizeNodes();Array.isArray(n)?e.splice(t,1,...n):n?e[t]=n:e.splice(t,1)}return e.length>0?this:void 0}optimizeNames(e,t){let{nodes:n}=this,r=n.length;for(;r--;){let i=n[r];i.optimizeNames(e,t)||(k(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>E(e,t.names),{})}},m=class extends p{render(e){return`{`+e._n+super.render(e)+`}`+e._n}},h=class extends p{},g=class extends m{};g.kind=`else`;var _=class e extends m{constructor(e,t){super(t),this.condition=e}render(e){let t=`if(${this.condition})`+super.render(e);return this.else&&(t+=`else `+this.else.render(e)),t}optimizeNodes(){super.optimizeNodes();let t=this.condition;if(t===!0)return this.nodes;let n=this.else;if(n){let e=n.optimizeNodes();n=this.else=Array.isArray(e)?new g(e):e}if(n)return t===!1?n instanceof e?n:n.nodes:this.nodes.length?this:new e(A(t),n instanceof e?[n]:n.nodes);if(!(t===!1||!this.nodes.length))return this}optimizeNames(e,t){if(this.else=this.else?.optimizeNames(e,t),super.optimizeNames(e,t)||this.else)return this.condition=O(this.condition,e,t),this}get names(){let e=super.names;return D(e,this.condition),this.else&&E(e,this.else.names),e}};_.kind=`if`;var v=class extends m{};v.kind=`for`;var y=class extends v{constructor(e){super(),this.iteration=e}render(e){return`for(${this.iteration})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iteration=O(this.iteration,e,t),this}get names(){return E(super.names,this.iteration.names)}},b=class extends v{constructor(e,t,n,r){super(),this.varKind=e,this.name=t,this.from=n,this.to=r}render(e){let t=e.es5?n.varKinds.var:this.varKind,{name:r,from:i,to:a}=this;return`for(${t} ${r}=${i}; ${r}<${a}; ${r}++)`+super.render(e)}get names(){return D(D(super.names,this.from),this.to)}},x=class extends v{constructor(e,t,n,r){super(),this.loop=e,this.varKind=t,this.name=n,this.iterable=r}render(e){return`for(${this.varKind} ${this.name} ${this.loop} ${this.iterable})`+super.render(e)}optimizeNames(e,t){if(super.optimizeNames(e,t))return this.iterable=O(this.iterable,e,t),this}get names(){return E(super.names,this.iterable.names)}},S=class extends m{constructor(e,t,n){super(),this.name=e,this.args=t,this.async=n}render(e){return`${this.async?`async `:``}function ${this.name}(${this.args})`+super.render(e)}};S.kind=`func`;var C=class extends p{render(e){return`return `+super.render(e)}};C.kind=`return`;var w=class extends m{render(e){let t=`try`+super.render(e);return this.catch&&(t+=this.catch.render(e)),this.finally&&(t+=this.finally.render(e)),t}optimizeNodes(){var e,t;return super.optimizeNodes(),(e=this.catch)==null||e.optimizeNodes(),(t=this.finally)==null||t.optimizeNodes(),this}optimizeNames(e,t){var n,r;return super.optimizeNames(e,t),(n=this.catch)==null||n.optimizeNames(e,t),(r=this.finally)==null||r.optimizeNames(e,t),this}get names(){let e=super.names;return this.catch&&E(e,this.catch.names),this.finally&&E(e,this.finally.names),e}},T=class extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};T.kind=`catch`;var ee=class extends m{render(e){return`finally`+super.render(e)}};ee.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
177
+ `:``},this._extScope=e,this._scope=new n.Scope({parent:e}),this._nodes=[new h]}toString(){return this._root.render(this.opts)}name(e){return this._scope.name(e)}scopeName(e){return this._extScope.name(e)}scopeValue(e,t){let n=this._extScope.value(e,t);return(this._values[n.prefix]||(this._values[n.prefix]=new Set)).add(n),n}getScopeValue(e,t){return this._extScope.getValue(e,t)}scopeRefs(e){return this._extScope.scopeRefs(e,this._values)}scopeCode(){return this._extScope.scopeCode(this._values)}_def(e,t,n,r){let i=this._scope.toName(t);return n!==void 0&&r&&(this._constants[i.str]=n),this._leafNode(new o(e,i,n)),i}const(e,t,r){return this._def(n.varKinds.const,e,t,r)}let(e,t,r){return this._def(n.varKinds.let,e,t,r)}var(e,t,r){return this._def(n.varKinds.var,e,t,r)}assign(e,t,n){return this._leafNode(new s(e,t,n))}add(t,n){return this._leafNode(new c(t,e.operators.ADD,n))}code(e){return typeof e==`function`?e():e!==t.nil&&this._leafNode(new f(e)),this}object(...e){let n=[`{`];for(let[r,i]of e)n.length>1&&n.push(`,`),n.push(r),(r!==i||this.opts.es5)&&(n.push(`:`),(0,t.addCodeArg)(n,i));return n.push(`}`),new t._Code(n)}if(e,t,n){if(this._blockNode(new _(e)),t&&n)this.code(t).else().code(n).endIf();else if(t)this.code(t).endIf();else if(n)throw Error(`CodeGen: "else" body without "then" body`);return this}elseIf(e){return this._elseNode(new _(e))}else(){return this._elseNode(new g)}endIf(){return this._endBlockNode(_,g)}_for(e,t){return this._blockNode(e),t&&this.code(t).endFor(),this}for(e,t){return this._for(new y(e),t)}forRange(e,t,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.let){let o=this._scope.toName(e);return this._for(new b(a,o,t,r),()=>i(o))}forOf(e,r,i,a=n.varKinds.const){let o=this._scope.toName(e);if(this.opts.es5){let e=r instanceof t.Name?r:this.var(`_arr`,r);return this.forRange(`_i`,0,(0,t._)`${e}.length`,n=>{this.var(o,(0,t._)`${e}[${n}]`),i(o)})}return this._for(new x(`of`,a,o,r),()=>i(o))}forIn(e,r,i,a=this.opts.es5?n.varKinds.var:n.varKinds.const){if(this.opts.ownProperties)return this.forOf(e,(0,t._)`Object.keys(${r})`,i);let o=this._scope.toName(e);return this._for(new x(`in`,a,o,r),()=>i(o))}endFor(){return this._endBlockNode(v)}label(e){return this._leafNode(new l(e))}break(e){return this._leafNode(new u(e))}return(e){let t=new C;if(this._blockNode(t),this.code(e),t.nodes.length!==1)throw Error(`CodeGen: "return" should have one node`);return this._endBlockNode(C)}try(e,t,n){if(!t&&!n)throw Error(`CodeGen: "try" without "catch" and "finally"`);let r=new w;if(this._blockNode(r),this.code(e),t){let e=this.name(`e`);this._currNode=r.catch=new T(e),t(e)}return n&&(this._currNode=r.finally=new ee,this.code(n)),this._endBlockNode(T,ee)}throw(e){return this._leafNode(new d(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error(`CodeGen: not in self-balancing block`);let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,n=t.nil,r,i){return this._blockNode(new S(e,n,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(S)}optimize(e=1){for(;e-->0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof _))throw Error(`CodeGen: "else" without "if"`);return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};function E(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function D(e,n){return n instanceof t._CodeOrName?E(e,n.names):e}function O(e,n,r){if(e instanceof t.Name)return i(e);if(!a(e))return e;return new t._Code(e._items.reduce((e,n)=>(n instanceof t.Name&&(n=i(n)),n instanceof t._Code?e.push(...n._items):e.push(n),e),[]));function i(e){let t=r[e.str];return t===void 0||n[e.str]!==1?e:(delete n[e.str],t)}function a(e){return e instanceof t._Code&&e._items.some(e=>e instanceof t.Name&&n[e.str]===1&&r[e.str]!==void 0)}}function k(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function A(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${ie(e)}`}e.not=A;let te=re(e.operators.AND);function ne(...e){return e.reduce(te)}e.and=ne;let j=re(e.operators.OR);function M(...e){return e.reduce(j)}e.or=M;function re(e){return(n,r)=>n===t.nil?r:r===t.nil?n:(0,t._)`${ie(n)} ${e} ${ie(r)}`}function ie(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),G=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.checkStrictMode=e.getErrorPath=e.Type=e.useFunc=e.setEvaluated=e.evaluatedPropsToName=e.mergeEvaluated=e.eachItem=e.unescapeJsonPointer=e.escapeJsonPointer=e.escapeFragment=e.unescapeFragment=e.schemaRefOrVal=e.schemaHasRulesButRef=e.schemaHasRules=e.checkUnknownRules=e.alwaysValidSchema=e.toHash=void 0;let t=W(),n=Rh();function r(e){let t={};for(let n of e)t[n]=!0;return t}e.toHash=r;function i(e,t){return typeof t==`boolean`?t:Object.keys(t).length===0||(a(e,t),!o(t,e.self.RULES.all))}e.alwaysValidSchema=i;function a(e,t=e.schema){let{opts:n,self:r}=e;if(!n.strictSchema||typeof t==`boolean`)return;let i=r.RULES.keywords;for(let n in t)i[n]||x(e,`unknown keyword: "${n}"`)}e.checkUnknownRules=a;function o(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(t[n])return!0;return!1}e.schemaHasRules=o;function s(e,t){if(typeof e==`boolean`)return!e;for(let n in e)if(n!==`$ref`&&t.all[n])return!0;return!1}e.schemaHasRulesButRef=s;function c({topSchemaRef:e,schemaPath:n},r,i,a){if(!a){if(typeof r==`number`||typeof r==`boolean`)return r;if(typeof r==`string`)return(0,t._)`${r}`}return(0,t._)`${e}${n}${(0,t.getProperty)(i)}`}e.schemaRefOrVal=c;function l(e){return f(decodeURIComponent(e))}e.unescapeFragment=l;function u(e){return encodeURIComponent(d(e))}e.escapeFragment=u;function d(e){return typeof e==`number`?`${e}`:e.replace(/~/g,`~0`).replace(/\//g,`~1`)}e.escapeJsonPointer=d;function f(e){return e.replace(/~1/g,`/`).replace(/~0/g,`~`)}e.unescapeJsonPointer=f;function p(e,t){if(Array.isArray(e))for(let n of e)t(n);else t(e)}e.eachItem=p;function m({mergeNames:e,mergeToName:n,mergeValues:r,resultToName:i}){return(a,o,s,c)=>{let l=s===void 0?o:s instanceof t.Name?(o instanceof t.Name?e(a,o,s):n(a,o,s),s):o instanceof t.Name?(n(a,s,o),o):r(o,s);return c===t.Name&&!(l instanceof t.Name)?i(a,l):l}}e.mergeEvaluated={props:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>{e.if((0,t._)`${n} === true`,()=>e.assign(r,!0),()=>e.assign(r,(0,t._)`${r} || {}`).code((0,t._)`Object.assign(${r}, ${n})`))}),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>{n===!0?e.assign(r,!0):(e.assign(r,(0,t._)`${r} || {}`),g(e,r,n))}),mergeValues:(e,t)=>e===!0||{...e,...t},resultToName:h}),items:m({mergeNames:(e,n,r)=>e.if((0,t._)`${r} !== true && ${n} !== undefined`,()=>e.assign(r,(0,t._)`${n} === true ? true : ${r} > ${n} ? ${r} : ${n}`)),mergeToName:(e,n,r)=>e.if((0,t._)`${r} !== true`,()=>e.assign(r,n===!0||(0,t._)`${r} > ${n} ? ${r} : ${n}`)),mergeValues:(e,t)=>e===!0||Math.max(e,t),resultToName:(e,t)=>e.var(`items`,t)})};function h(e,n){if(n===!0)return e.var(`props`,!0);let r=e.var(`props`,(0,t._)`{}`);return n!==void 0&&g(e,r,n),r}e.evaluatedPropsToName=h;function g(e,n,r){Object.keys(r).forEach(r=>e.assign((0,t._)`${n}${(0,t.getProperty)(r)}`,!0))}e.setEvaluated=g;let _={};function v(e,t){return e.scopeValue(`func`,{ref:t,code:_[t.code]||(_[t.code]=new n._Code(t.code))})}e.useFunc=v;var y;(function(e){e[e.Num=0]=`Num`,e[e.Str=1]=`Str`})(y||(e.Type=y={}));function b(e,n,r){if(e instanceof t.Name){let i=n===y.Num;return r?i?(0,t._)`"[" + ${e} + "]"`:(0,t._)`"['" + ${e} + "']"`:i?(0,t._)`"/" + ${e}`:(0,t._)`"/" + ${e}.replace(/~/g, "~0").replace(/\\//g, "~1")`}return r?(0,t.getProperty)(e).toString():`/`+d(e)}e.getErrorPath=b;function x(e,t,n=e.opts.strictSchema){if(n){if(t=`strict mode: ${t}`,n===!0)throw Error(t);e.self.logger.warn(t)}}e.checkStrictMode=x})),Bh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W();e.default={data:new t.Name(`data`),valCxt:new t.Name(`valCxt`),instancePath:new t.Name(`instancePath`),parentData:new t.Name(`parentData`),parentDataProperty:new t.Name(`parentDataProperty`),rootData:new t.Name(`rootData`),dynamicAnchors:new t.Name(`dynamicAnchors`),vErrors:new t.Name(`vErrors`),errors:new t.Name(`errors`),this:new t.Name(`this`),self:new t.Name(`self`),scope:new t.Name(`scope`),json:new t.Name(`json`),jsonPos:new t.Name(`jsonPos`),jsonLen:new t.Name(`jsonLen`),jsonPart:new t.Name(`jsonPart`)}})),Vh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;let t=W(),n=G(),r=Bh();e.keywordError={message:({keyword:e})=>(0,t.str)`must pass "${e}" keyword validation`},e.keyword$DataError={message:({keyword:e,schemaType:n})=>n?(0,t.str)`"${e}" keyword must be ${n} ($data)`:(0,t.str)`"${e}" keyword is invalid ($data)`};function i(n,r=e.keywordError,i,a){let{it:o}=n,{gen:s,compositeRule:u,allErrors:f}=o,p=d(n,r,i);a??(u||f)?c(s,p):l(o,(0,t._)`[${p}]`)}e.reportError=i;function a(t,n=e.keywordError,i){let{it:a}=t,{gen:o,compositeRule:s,allErrors:u}=a;c(o,d(t,n,i)),s||u||l(a,r.default.vErrors)}e.reportExtraError=a;function o(e,n){e.assign(r.default.errors,n),e.if((0,t._)`${r.default.vErrors} !== null`,()=>e.if(n,()=>e.assign((0,t._)`${r.default.vErrors}.length`,n),()=>e.assign(r.default.vErrors,null)))}e.resetErrorsCount=o;function s({gen:e,keyword:n,schemaValue:i,data:a,errsCount:o,it:s}){if(o===void 0)throw Error(`ajv implementation error`);let c=e.name(`err`);e.forRange(`i`,o,r.default.errors,o=>{e.const(c,(0,t._)`${r.default.vErrors}[${o}]`),e.if((0,t._)`${c}.instancePath === undefined`,()=>e.assign((0,t._)`${c}.instancePath`,(0,t.strConcat)(r.default.instancePath,s.errorPath))),e.assign((0,t._)`${c}.schemaPath`,(0,t.str)`${s.errSchemaPath}/${n}`),s.opts.verbose&&(e.assign((0,t._)`${c}.schema`,i),e.assign((0,t._)`${c}.data`,a))})}e.extendErrors=s;function c(e,n){let i=e.const(`err`,n);e.if((0,t._)`${r.default.vErrors} === null`,()=>e.assign(r.default.vErrors,(0,t._)`[${i}]`),(0,t._)`${r.default.vErrors}.push(${i})`),e.code((0,t._)`${r.default.errors}++`)}function l(e,n){let{gen:r,validateName:i,schemaEnv:a}=e;a.$async?r.throw((0,t._)`new ${e.ValidationError}(${n})`):(r.assign((0,t._)`${i}.errors`,n),r.return(!1))}let u={keyword:new t.Name(`keyword`),schemaPath:new t.Name(`schemaPath`),params:new t.Name(`params`),propertyName:new t.Name(`propertyName`),message:new t.Name(`message`),schema:new t.Name(`schema`),parentSchema:new t.Name(`parentSchema`)};function d(e,n,r){let{createErrors:i}=e.it;return i===!1?(0,t._)`{}`:f(e,n,r)}function f(e,t,n={}){let{gen:r,it:i}=e,a=[p(i,n),m(e,n)];return h(e,t,a),r.object(...a)}function p({errorPath:e},{instancePath:i}){let a=i?(0,t.str)`${e}${(0,n.getErrorPath)(i,n.Type.Str)}`:e;return[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,a)]}function m({keyword:e,it:{errSchemaPath:r}},{schemaPath:i,parentSchema:a}){let o=a?r:(0,t.str)`${r}/${e}`;return i&&(o=(0,t.str)`${o}${(0,n.getErrorPath)(i,n.Type.Str)}`),[u.schemaPath,o]}function h(e,{params:n,message:i},a){let{keyword:o,data:s,schemaValue:c,it:l}=e,{opts:d,propertyName:f,topSchemaRef:p,schemaPath:m}=l;a.push([u.keyword,o],[u.params,typeof n==`function`?n(e):n||(0,t._)`{}`]),d.messages&&a.push([u.message,typeof i==`function`?i(e):i]),d.verbose&&a.push([u.schema,c],[u.parentSchema,(0,t._)`${p}${m}`],[r.default.data,s]),f&&a.push([u.propertyName,f])}})),Hh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=Vh(),n=W(),r=Bh(),i={message:`boolean schema is false`};function a(e){let{gen:t,schema:i,validateName:a}=e;i===!1?s(e,!1):typeof i==`object`&&i.$async===!0?t.return(r.default.data):(t.assign((0,n._)`${a}.errors`,null),t.return(!0))}e.topBoolOrEmptySchema=a;function o(e,t){let{gen:n,schema:r}=e;r===!1?(n.var(t,!1),s(e)):n.var(t,!0)}e.boolOrEmptySchema=o;function s(e,n){let{gen:r,data:a}=e,o={gen:r,keyword:`false schema`,data:a,schema:!1,schemaCode:!1,schemaValue:!1,params:{},it:e};(0,t.reportError)(o,i,void 0,n)}})),Uh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getRules=e.isJSONType=void 0;let t=new Set([`string`,`number`,`integer`,`boolean`,`null`,`object`,`array`]);function n(e){return typeof e==`string`&&t.has(e)}e.isJSONType=n;function r(){let e={number:{type:`number`,rules:[]},string:{type:`string`,rules:[]},array:{type:`array`,rules:[]},object:{type:`object`,rules:[]}};return{types:{...e,integer:!0,boolean:!0,null:!0},rules:[{rules:[]},e.number,e.string,e.array,e.object],post:{rules:[]},all:{},keywords:{}}}e.getRules=r})),Wh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.shouldUseRule=e.shouldUseGroup=e.schemaHasRulesForType=void 0;function t({schema:e,self:t},r){let i=t.RULES.types[r];return i&&i!==!0&&n(e,i)}e.schemaHasRulesForType=t;function n(e,t){return t.rules.some(t=>r(e,t))}e.shouldUseGroup=n;function r(e,t){return e[t.keyword]!==void 0||t.definition.implements?.some(t=>e[t]!==void 0)}e.shouldUseRule=r})),Gh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.reportTypeError=e.checkDataTypes=e.checkDataType=e.coerceAndCheckDataType=e.getJSONTypes=e.getSchemaTypes=e.DataType=void 0;let t=Uh(),n=Wh(),r=Vh(),i=W(),a=G();var o;(function(e){e[e.Correct=0]=`Correct`,e[e.Wrong=1]=`Wrong`})(o||(e.DataType=o={}));function s(e){let t=c(e.type);if(t.includes(`null`)){if(e.nullable===!1)throw Error(`type: null contradicts nullable: false`)}else{if(!t.length&&e.nullable!==void 0)throw Error(`"nullable" cannot be used without "type"`);e.nullable===!0&&t.push(`null`)}return t}e.getSchemaTypes=s;function c(e){let n=Array.isArray(e)?e:e?[e]:[];if(n.every(t.isJSONType))return n;throw Error(`type must be JSONType or JSONType[]: `+n.join(`,`))}e.getJSONTypes=c;function l(e,t){let{gen:r,data:i,opts:a}=e,s=d(t,a.coerceTypes),c=t.length>0&&!(s.length===0&&t.length===1&&(0,n.schemaHasRulesForType)(e,t[0]));if(c){let n=h(t,i,a.strictNumbers,o.Wrong);r.if(n,()=>{s.length?f(e,t,s):_(e)})}return c}e.coerceAndCheckDataType=l;let u=new Set([`string`,`number`,`integer`,`boolean`,`null`]);function d(e,t){return t?e.filter(e=>u.has(e)||t===`array`&&e===`array`):[]}function f(e,t,n){let{gen:r,data:a,opts:o}=e,s=r.let(`dataType`,(0,i._)`typeof ${a}`),c=r.let(`coerced`,(0,i._)`undefined`);o.coerceTypes===`array`&&r.if((0,i._)`${s} == 'object' && Array.isArray(${a}) && ${a}.length == 1`,()=>r.assign(a,(0,i._)`${a}[0]`).assign(s,(0,i._)`typeof ${a}`).if(h(t,a,o.strictNumbers),()=>r.assign(c,a))),r.if((0,i._)`${c} !== undefined`);for(let e of n)(u.has(e)||e===`array`&&o.coerceTypes===`array`)&&l(e);r.else(),_(e),r.endIf(),r.if((0,i._)`${c} !== undefined`,()=>{r.assign(a,c),p(e,c)});function l(e){switch(e){case`string`:r.elseIf((0,i._)`${s} == "number" || ${s} == "boolean"`).assign(c,(0,i._)`"" + ${a}`).elseIf((0,i._)`${a} === null`).assign(c,(0,i._)`""`);return;case`number`:r.elseIf((0,i._)`${s} == "boolean" || ${a} === null
178
178
  || (${s} == "string" && ${a} && ${a} == +${a})`).assign(c,(0,i._)`+${a}`);return;case`integer`:r.elseIf((0,i._)`${s} === "boolean" || ${a} === null
179
179
  || (${s} === "string" && ${a} && ${a} == +${a} && !(${a} % 1))`).assign(c,(0,i._)`+${a}`);return;case`boolean`:r.elseIf((0,i._)`${a} === "false" || ${a} === 0 || ${a} === null`).assign(c,!1).elseIf((0,i._)`${a} === "true" || ${a} === 1`).assign(c,!0);return;case`null`:r.elseIf((0,i._)`${a} === "" || ${a} === 0 || ${a} === false`),r.assign(c,null);return;case`array`:r.elseIf((0,i._)`${s} === "string" || ${s} === "number"
180
- || ${s} === "boolean" || ${a} === null`).assign(c,(0,i._)`[${a}]`)}}}function p({gen:e,parentData:t,parentDataProperty:n},r){e.if((0,i._)`${t} !== undefined`,()=>e.assign((0,i._)`${t}[${n}]`,r))}function m(e,t,n,r=o.Correct){let a=r===o.Correct?i.operators.EQ:i.operators.NEQ,s;switch(e){case`null`:return(0,i._)`${t} ${a} null`;case`array`:s=(0,i._)`Array.isArray(${t})`;break;case`object`:s=(0,i._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case`integer`:s=c((0,i._)`!(${t} % 1) && !isNaN(${t})`);break;case`number`:s=c();break;default:return(0,i._)`typeof ${t} ${a} ${e}`}return r===o.Correct?s:(0,i.not)(s);function c(e=i.nil){return(0,i.and)((0,i._)`typeof ${t} == "number"`,e,n?(0,i._)`isFinite(${t})`:i.nil)}}e.checkDataType=m;function h(e,t,n,r){if(e.length===1)return m(e[0],t,n,r);let o,s=(0,a.toHash)(e);if(s.array&&s.object){let e=(0,i._)`typeof ${t} != "object"`;o=s.null?e:(0,i._)`!${t} || ${e}`,delete s.null,delete s.array,delete s.object}else o=i.nil;s.number&&delete s.integer;for(let e in s)o=(0,i.and)(o,m(e,t,n,r));return o}e.checkDataTypes=h;let g={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e==`string`?(0,i._)`{type: ${e}}`:(0,i._)`{type: ${t}}`};function _(e){let t=v(e);(0,r.reportError)(t,g)}e.reportTypeError=_;function v(e){let{gen:t,data:n,schema:r}=e,i=(0,a.schemaRefOrVal)(e,r,`type`);return{gen:t,keyword:`type`,data:n,schema:r.type,schemaCode:i,schemaValue:i,parentSchema:r,params:{},it:e}}})),Kh=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.assignDefaults=void 0;let t=W(),n=G();function r(e,t){let{properties:n,items:r}=e.schema;if(t===`object`&&n)for(let t in n)i(e,t,n[t].default);else t===`array`&&Array.isArray(r)&&r.forEach((t,n)=>i(e,n,t.default))}e.assignDefaults=r;function i(e,r,i){let{gen:a,compositeRule:o,data:s,opts:c}=e;if(i===void 0)return;let l=(0,t._)`${s}${(0,t.getProperty)(r)}`;if(o){(0,n.checkStrictMode)(e,`default is ignored for: ${l}`);return}let u=(0,t._)`${l} === undefined`;c.useDefaults===`empty`&&(u=(0,t._)`${u} || ${l} === null || ${l} === ""`),a.if(u,(0,t._)`${l} = ${(0,t.stringify)(i)}`)}})),qh=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateUnion=e.validateArray=e.usePattern=e.callValidateCode=e.schemaProperties=e.allSchemaProperties=e.noPropertyInData=e.propertyInData=e.isOwnProperty=e.hasPropFunc=e.reportMissingProp=e.checkMissingProp=e.checkReportMissingProp=void 0;let t=W(),n=G(),r=Bh(),i=G();function a(e,n){let{gen:r,data:i,it:a}=e;r.if(d(r,i,n,a.opts.ownProperties),()=>{e.setParams({missingProperty:(0,t._)`${n}`},!0),e.error()})}e.checkReportMissingProp=a;function o({gen:e,data:n,it:{opts:r}},i,a){return(0,t.or)(...i.map(i=>(0,t.and)(d(e,n,i,r.ownProperties),(0,t._)`${a} = ${i}`)))}e.checkMissingProp=o;function s(e,t){e.setParams({missingProperty:t},!0),e.error()}e.reportMissingProp=s;function c(e){return e.scopeValue(`func`,{ref:Object.prototype.hasOwnProperty,code:(0,t._)`Object.prototype.hasOwnProperty`})}e.hasPropFunc=c;function l(e,n,r){return(0,t._)`${c(e)}.call(${n}, ${r})`}e.isOwnProperty=l;function u(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} !== undefined`;return i?(0,t._)`${a} && ${l(e,n,r)}`:a}e.propertyInData=u;function d(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} === undefined`;return i?(0,t.or)(a,(0,t.not)(l(e,n,r))):a}e.noPropertyInData=d;function f(e){return e?Object.keys(e).filter(e=>e!==`__proto__`):[]}e.allSchemaProperties=f;function p(e,t){return f(t).filter(r=>!(0,n.alwaysValidSchema)(e,t[r]))}e.schemaProperties=p;function m({schemaCode:e,data:n,it:{gen:i,topSchemaRef:a,schemaPath:o,errorPath:s},it:c},l,u,d){let f=d?(0,t._)`${e}, ${n}, ${a}${o}`:n,p=[[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,s)],[r.default.parentData,c.parentData],[r.default.parentDataProperty,c.parentDataProperty],[r.default.rootData,r.default.rootData]];c.opts.dynamicRef&&p.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);let m=(0,t._)`${f}, ${i.object(...p)}`;return u===t.nil?(0,t._)`${l}(${m})`:(0,t._)`${l}.call(${u}, ${m})`}e.callValidateCode=m;let h=(0,t._)`new RegExp`;function g({gen:e,it:{opts:n}},r){let a=n.unicodeRegExp?`u`:``,{regExp:o}=n.code,s=o(r,a);return e.scopeValue(`pattern`,{key:s.toString(),ref:s,code:(0,t._)`${o.code===`new RegExp`?h:(0,i.useFunc)(e,o)}(${r}, ${a})`})}e.usePattern=g;function _(e){let{gen:r,data:i,keyword:a,it:o}=e,s=r.name(`valid`);if(o.allErrors){let e=r.let(`valid`,!0);return c(()=>r.assign(e,!1)),e}return r.var(s,!0),c(()=>r.break()),s;function c(o){let c=r.const(`len`,(0,t._)`${i}.length`);r.forRange(`i`,0,c,i=>{e.subschema({keyword:a,dataProp:i,dataPropType:n.Type.Num},s),r.if((0,t.not)(s),o)})}}e.validateArray=_;function v(e){let{gen:r,schema:i,keyword:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(i.some(e=>(0,n.alwaysValidSchema)(o,e))&&!o.opts.unevaluated)return;let s=r.let(`valid`,!1),c=r.name(`_valid`);r.block(()=>i.forEach((n,i)=>{let o=e.subschema({keyword:a,schemaProp:i,compositeRule:!0},c);r.assign(s,(0,t._)`${s} || ${c}`),e.mergeValidEvaluated(o,c)||r.if((0,t.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}e.validateUnion=v})),Jh=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;let t=W(),n=Bh(),r=qh(),i=Vh();function a(e,n){let{gen:r,keyword:i,schema:a,parentSchema:o,it:s}=e,c=n.macro.call(s.self,a,o,s),l=u(r,i,c);s.opts.validateSchema!==!1&&s.self.validateSchema(c,!0);let d=r.name(`valid`);e.subschema({schema:c,schemaPath:t.nil,errSchemaPath:`${s.errSchemaPath}/${i}`,topSchemaRef:l,compositeRule:!0},d),e.pass(d,()=>e.error(!0))}e.macroKeywordCode=a;function o(e,i){let{gen:a,keyword:o,schema:d,parentSchema:f,$data:p,it:m}=e;l(m,i);let h=u(a,o,!p&&i.compile?i.compile.call(m.self,d,f,m):i.validate),g=a.let(`valid`);e.block$data(g,_),e.ok(i.valid??g);function _(){if(i.errors===!1)b(),i.modifying&&s(e),x(()=>e.error());else{let t=i.async?v():y();i.modifying&&s(e),x(()=>c(e,t))}}function v(){let e=a.let(`ruleErrs`,null);return a.try(()=>b((0,t._)`await `),n=>a.assign(g,!1).if((0,t._)`${n} instanceof ${m.ValidationError}`,()=>a.assign(e,(0,t._)`${n}.errors`),()=>a.throw(n))),e}function y(){let e=(0,t._)`${h}.errors`;return a.assign(e,null),b(t.nil),e}function b(o=i.async?(0,t._)`await `:t.nil){let s=m.opts.passContext?n.default.this:n.default.self,c=!(`compile`in i&&!p||i.schema===!1);a.assign(g,(0,t._)`${o}${(0,r.callValidateCode)(e,h,s,c)}`,i.modifying)}function x(e){a.if((0,t.not)(i.valid??g),e)}}e.funcKeywordCode=o;function s(e){let{gen:n,data:r,it:i}=e;n.if(i.parentData,()=>n.assign(r,(0,t._)`${i.parentData}[${i.parentDataProperty}]`))}function c(e,r){let{gen:a}=e;a.if((0,t._)`Array.isArray(${r})`,()=>{a.assign(n.default.vErrors,(0,t._)`${n.default.vErrors} === null ? ${r} : ${n.default.vErrors}.concat(${r})`).assign(n.default.errors,(0,t._)`${n.default.vErrors}.length`),(0,i.extendErrors)(e)},()=>e.error())}function l({schemaEnv:e},t){if(t.async&&!e.$async)throw Error(`async keyword in sync schema`)}function u(e,n,r){if(r===void 0)throw Error(`keyword "${n}" failed to compile`);return e.scopeValue(`keyword`,typeof r==`function`?{ref:r}:{ref:r,code:(0,t.stringify)(r)})}function d(e,t,n=!1){return!t.length||t.some(t=>t===`array`?Array.isArray(e):t===`object`?e&&typeof e==`object`&&!Array.isArray(e):typeof e==t||n&&e===void 0)}e.validSchemaType=d;function f({schema:e,opts:t,self:n,errSchemaPath:r},i,a){if(Array.isArray(i.keyword)?!i.keyword.includes(a):i.keyword!==a)throw Error(`ajv implementation error`);let o=i.dependencies;if(o?.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw Error(`parent schema must have dependencies of ${a}: ${o.join(`,`)}`);if(i.validateSchema&&!i.validateSchema(e[a])){let e=`keyword "${a}" value is invalid at path "${r}": `+n.errorsText(i.validateSchema.errors);if(t.validateSchema===`log`)n.logger.error(e);else throw Error(e)}}e.validateKeywordUsage=f})),Yh=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;let t=W(),n=G();function r(e,{keyword:r,schemaProp:i,schema:a,schemaPath:o,errSchemaPath:s,topSchemaRef:c}){if(r!==void 0&&a!==void 0)throw Error(`both "keyword" and "schema" passed, only one allowed`);if(r!==void 0){let a=e.schema[r];return i===void 0?{schema:a,schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${r}`}:{schema:a[i],schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}${(0,t.getProperty)(i)}`,errSchemaPath:`${e.errSchemaPath}/${r}/${(0,n.escapeFragment)(i)}`}}if(a!==void 0){if(o===void 0||s===void 0||c===void 0)throw Error(`"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"`);return{schema:a,schemaPath:o,topSchemaRef:c,errSchemaPath:s}}throw Error(`either "keyword" or "schema" must be passed`)}e.getSubschema=r;function i(e,r,{dataProp:i,dataPropType:a,data:o,dataTypes:s,propertyName:c}){if(o!==void 0&&i!==void 0)throw Error(`both "data" and "dataProp" passed, only one allowed`);let{gen:l}=r;if(i!==void 0){let{errorPath:o,dataPathArr:s,opts:c}=r;u(l.let(`data`,(0,t._)`${r.data}${(0,t.getProperty)(i)}`,!0)),e.errorPath=(0,t.str)`${o}${(0,n.getErrorPath)(i,a,c.jsPropertySyntax)}`,e.parentDataProperty=(0,t._)`${i}`,e.dataPathArr=[...s,e.parentDataProperty]}o!==void 0&&(u(o instanceof t.Name?o:l.let(`data`,o,!0)),c!==void 0&&(e.propertyName=c)),s&&(e.dataTypes=s);function u(t){e.data=t,e.dataLevel=r.dataLevel+1,e.dataTypes=[],r.definedProperties=new Set,e.parentData=r.data,e.dataNames=[...r.dataNames,t]}}e.extendSubschemaData=i;function a(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:r,createErrors:i,allErrors:a}){r!==void 0&&(e.compositeRule=r),i!==void 0&&(e.createErrors=i),a!==void 0&&(e.allErrors=a),e.jtdDiscriminator=t,e.jtdMetadata=n}e.extendSubschemaMode=a})),Xh=z(((e,t)=>{t.exports=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t==`object`&&typeof n==`object`){if(t.constructor!==n.constructor)return!1;var r,i,a;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(i=r;i--!==0;)if(!e(t[i],n[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(a=Object.keys(t),r=a.length,r!==Object.keys(n).length)return!1;for(i=r;i--!==0;)if(!Object.prototype.hasOwnProperty.call(n,a[i]))return!1;for(i=r;i--!==0;){var o=a[i];if(!e(t[o],n[o]))return!1}return!0}return t!==t&&n!==n}})),Zh=z(((e,t)=>{var n=t.exports=function(e,t,n){typeof t==`function`&&(n=t,t={}),n=t.cb||n;var i=typeof n==`function`?n:n.pre||function(){},a=n.post||function(){};r(t,i,a,e,``,e)};n.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},n.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},n.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},n.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function r(e,t,a,o,s,c,l,u,d,f){if(o&&typeof o==`object`&&!Array.isArray(o)){for(var p in t(o,s,c,l,u,d,f),o){var m=o[p];if(Array.isArray(m)){if(p in n.arrayKeywords)for(var h=0;h<m.length;h++)r(e,t,a,m[h],s+`/`+p+`/`+h,c,s,p,o,h)}else if(p in n.propsKeywords){if(m&&typeof m==`object`)for(var g in m)r(e,t,a,m[g],s+`/`+p+`/`+i(g),c,s,p,o,g)}else(p in n.keywords||e.allKeys&&!(p in n.skipKeywords))&&r(e,t,a,m,s+`/`+p,c,s,p,o)}a(o,s,c,l,u,d,f)}}function i(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}})),Qh=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;let t=G(),n=Xh(),r=Zh(),i=new Set([`type`,`format`,`pattern`,`maxLength`,`minLength`,`maxProperties`,`minProperties`,`maxItems`,`minItems`,`maximum`,`minimum`,`uniqueItems`,`multipleOf`,`required`,`enum`,`const`]);function a(e,t=!0){return typeof e==`boolean`?!0:t===!0?!s(e):t?c(e)<=t:!1}e.inlineRef=a;let o=new Set([`$ref`,`$recursiveRef`,`$recursiveAnchor`,`$dynamicRef`,`$dynamicAnchor`]);function s(e){for(let t in e){if(o.has(t))return!0;let n=e[t];if(Array.isArray(n)&&n.some(s)||typeof n==`object`&&s(n))return!0}return!1}function c(e){let n=0;for(let r in e)if(r===`$ref`||(n++,!i.has(r)&&(typeof e[r]==`object`&&(0,t.eachItem)(e[r],e=>n+=c(e)),n===1/0)))return 1/0;return n}function l(e,t=``,n){return n!==!1&&(t=f(t)),u(e,e.parse(t))}e.getFullPath=l;function u(e,t){return e.serialize(t).split(`#`)[0]+`#`}e._getFullPath=u;let d=/#\/?$/;function f(e){return e?e.replace(d,``):``}e.normalizeId=f;function p(e,t,n){return n=f(n),e.resolve(t,n)}e.resolveUrl=p;let m=/^[a-z_][-a-z0-9._]*$/i;function h(e,t){if(typeof e==`boolean`)return{};let{schemaId:i,uriResolver:a}=this.opts,o=f(e[i]||t),s={"":o},c=l(a,o,!1),u={},d=new Set;return r(e,{allKeys:!0},(e,t,n,r)=>{if(r===void 0)return;let a=c+t,o=s[r];typeof e[i]==`string`&&(o=l.call(this,e[i])),g.call(this,e.$anchor),g.call(this,e.$dynamicAnchor),s[t]=o;function l(t){let n=this.opts.uriResolver.resolve;if(t=f(o?n(o,t):t),d.has(t))throw h(t);d.add(t);let r=this.refs[t];return typeof r==`string`&&(r=this.refs[r]),typeof r==`object`?p(e,r.schema,t):t!==f(a)&&(t[0]===`#`?(p(e,u[t],t),u[t]=e):this.refs[t]=a),t}function g(e){if(typeof e==`string`){if(!m.test(e))throw Error(`invalid anchor "${e}"`);l.call(this,`#${e}`)}}}),u;function p(e,t,r){if(t!==void 0&&!n(e,t))throw h(r)}function h(e){return Error(`reference "${e}" resolves to more than one schema`)}}e.getSchemaRefs=h})),$h=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=Hh(),n=Gh(),r=Wh(),i=Gh(),a=Kh(),o=Jh(),s=Yh(),c=W(),l=Bh(),u=Qh(),d=G(),f=Vh();function p(e){if(S(e)&&(w(e),x(e))){_(e);return}m(e,()=>(0,t.topBoolOrEmptySchema)(e))}e.validateFunctionCode=p;function m({gen:e,validateName:t,schema:n,schemaEnv:r,opts:i},a){i.code.es5?e.func(t,(0,c._)`${l.default.data}, ${l.default.valCxt}`,r.$async,()=>{e.code((0,c._)`"use strict"; ${y(n,i)}`),g(e,i),e.code(a)}):e.func(t,(0,c._)`${l.default.data}, ${h(i)}`,r.$async,()=>e.code(y(n,i)).code(a))}function h(e){return(0,c._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${e.dynamicRef?(0,c._)`, ${l.default.dynamicAnchors}={}`:c.nil}}={}`}function g(e,t){e.if(l.default.valCxt,()=>{e.var(l.default.instancePath,(0,c._)`${l.default.valCxt}.${l.default.instancePath}`),e.var(l.default.parentData,(0,c._)`${l.default.valCxt}.${l.default.parentData}`),e.var(l.default.parentDataProperty,(0,c._)`${l.default.valCxt}.${l.default.parentDataProperty}`),e.var(l.default.rootData,(0,c._)`${l.default.valCxt}.${l.default.rootData}`),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{e.var(l.default.instancePath,(0,c._)`""`),e.var(l.default.parentData,(0,c._)`undefined`),e.var(l.default.parentDataProperty,(0,c._)`undefined`),e.var(l.default.rootData,l.default.data),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`{}`)})}function _(e){let{schema:t,opts:n,gen:r}=e;m(e,()=>{n.$comment&&t.$comment&&k(e),E(e),r.let(l.default.vErrors,null),r.let(l.default.errors,0),n.unevaluated&&v(e),T(e),te(e)})}function v(e){let{gen:t,validateName:n}=e;e.evaluated=t.const(`evaluated`,(0,c._)`${n}.evaluated`),t.if((0,c._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,c._)`${e.evaluated}.props`,(0,c._)`undefined`)),t.if((0,c._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,c._)`${e.evaluated}.items`,(0,c._)`undefined`))}function y(e,t){let n=typeof e==`object`&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,c._)`/*# sourceURL=${n} */`:c.nil}function b(e,n){if(S(e)&&(w(e),x(e))){C(e,n);return}(0,t.boolOrEmptySchema)(e,n)}function x({schema:e,self:t}){if(typeof e==`boolean`)return!e;for(let n in e)if(t.RULES.all[n])return!0;return!1}function S(e){return typeof e.schema!=`boolean`}function C(e,t){let{schema:n,gen:r,opts:i}=e;i.$comment&&n.$comment&&k(e),D(e),O(e);let a=r.const(`_errs`,l.default.errors);T(e,a),r.var(t,(0,c._)`${a} === ${l.default.errors}`)}function w(e){(0,d.checkUnknownRules)(e),ee(e)}function T(e,t){if(e.opts.jtd)return re(e,[],!1,t);let r=(0,n.getSchemaTypes)(e.schema);re(e,r,!(0,n.coerceAndCheckDataType)(e,r),t)}function ee(e){let{schema:t,errSchemaPath:n,opts:r,self:i}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function E(e){let{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,d.checkStrictMode)(e,`default is ignored in the schema root`)}function D(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function O(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error(`async schema in sync schema`)}function k({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:i}){let a=n.$comment;if(i.$comment===!0)e.code((0,c._)`${l.default.self}.logger.log(${a})`);else if(typeof i.$comment==`function`){let n=(0,c.str)`${r}/$comment`,i=e.scopeValue(`root`,{ref:t.root});e.code((0,c._)`${l.default.self}.opts.$comment(${a}, ${n}, ${i}.schema)`)}}function te(e){let{gen:t,schemaEnv:n,validateName:r,ValidationError:i,opts:a}=e;n.$async?t.if((0,c._)`${l.default.errors} === 0`,()=>t.return(l.default.data),()=>t.throw((0,c._)`new ${i}(${l.default.vErrors})`)):(t.assign((0,c._)`${r}.errors`,l.default.vErrors),a.unevaluated&&ne(e),t.return((0,c._)`${l.default.errors} === 0`))}function ne({gen:e,evaluated:t,props:n,items:r}){n instanceof c.Name&&e.assign((0,c._)`${t}.props`,n),r instanceof c.Name&&e.assign((0,c._)`${t}.items`,r)}function re(e,t,n,a){let{gen:o,schema:s,data:u,allErrors:f,opts:p,self:m}=e,{RULES:h}=m;if(s.$ref&&(p.ignoreKeywordsWithRef||!(0,d.schemaHasRulesButRef)(s,h))){o.block(()=>de(e,`$ref`,h.all.$ref.definition));return}p.jtd||j(e,t),o.block(()=>{for(let e of h.rules)g(e);g(h.post)});function g(d){(0,r.shouldUseGroup)(s,d)&&(d.type?(o.if((0,i.checkDataType)(d.type,u,p.strictNumbers)),A(e,d),t.length===1&&t[0]===d.type&&n&&(o.else(),(0,i.reportTypeError)(e)),o.endIf()):A(e,d),f||o.if((0,c._)`${l.default.errors} === ${a||0}`))}}function A(e,t){let{gen:n,schema:i,opts:{useDefaults:o}}=e;o&&(0,a.assignDefaults)(e,t.type),n.block(()=>{for(let n of t.rules)(0,r.shouldUseRule)(i,n)&&de(e,n.keyword,n.definition,t.type)})}function j(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(ie(e,t),e.opts.allowUnionTypes||ae(e,t),oe(e,e.dataTypes))}function ie(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(t=>{ce(e.dataTypes,t)||le(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),M(e,t)}}function ae(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&le(e,`use allowUnionTypes to allow union type keyword`)}function oe(e,t){let n=e.self.RULES.all;for(let i in n){let a=n[i];if(typeof a==`object`&&(0,r.shouldUseRule)(e.schema,a)){let{type:n}=a.definition;n.length&&!n.some(e=>se(t,e))&&le(e,`missing type "${n.join(`,`)}" for keyword "${i}"`)}}}function se(e,t){return e.includes(t)||t===`number`&&e.includes(`integer`)}function ce(e,t){return e.includes(t)||t===`integer`&&e.includes(`number`)}function M(e,t){let n=[];for(let r of e.dataTypes)ce(t,r)?n.push(r):t.includes(`integer`)&&r===`number`&&n.push(`integer`);e.dataTypes=n}function le(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}var ue=class{constructor(e,t,n){if((0,o.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const(`vSchema`,me(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);(`code`in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const(`_errs`,l.default.errors))}result(e,t,n){this.failResult((0,c.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,c.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,c._)`${t} !== undefined && (${(0,c.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t){this.setParams(t),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,t){(e?f.reportExtraError:f.reportError)(this,this.def.error,t)}$dataError(){(0,f.reportError)(this,this.def.$dataError||f.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error(`add "trackErrors" to keyword definition`);(0,f.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=c.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=c.nil,t=c.nil){if(!this.$data)return;let{gen:n,schemaCode:r,schemaType:i,def:a}=this;n.if((0,c.or)((0,c._)`${r} === undefined`,t)),e!==c.nil&&n.assign(e,!0),(i.length||a.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==c.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:r,it:a}=this;return(0,c.or)(o(),s());function o(){if(n.length){if(!(t instanceof c.Name))throw Error(`ajv implementation error`);let e=Array.isArray(n)?n:[n];return(0,c._)`${(0,i.checkDataTypes)(e,t,a.opts.strictNumbers,i.DataType.Wrong)}`}return c.nil}function s(){if(r.validateSchema){let n=e.scopeValue(`validate$data`,{ref:r.validateSchema});return(0,c._)`!${n}(${t})`}return c.nil}}subschema(e,t){let n=(0,s.getSubschema)(this.it,e);(0,s.extendSubschemaData)(n,this.it,e),(0,s.extendSubschemaMode)(n,e);let r={...this.it,...n,items:void 0,props:void 0};return b(r,t),r}mergeEvaluated(e,t){let{it:n,gen:r}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=d.mergeEvaluated.props(r,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=d.mergeEvaluated.items(r,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:r}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return r.if(t,()=>this.mergeEvaluated(e,c.Name)),!0}};e.KeywordCxt=ue;function de(e,t,n,r){let i=new ue(e,n,t);`code`in n?n.code(i,r):i.$data&&n.validate?(0,o.funcKeywordCode)(i,n):`macro`in n?(0,o.macroKeywordCode)(i,n):(n.compile||n.validate)&&(0,o.funcKeywordCode)(i,n)}let fe=/^\/(?:[^~]|~0|~1)*$/,pe=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function me(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let i,a;if(e===``)return l.default.rootData;if(e[0]===`/`){if(!fe.test(e))throw Error(`Invalid JSON-pointer: ${e}`);i=e,a=l.default.rootData}else{let o=pe.exec(e);if(!o)throw Error(`Invalid JSON-pointer: ${e}`);let s=+o[1];if(i=o[2],i===`#`){if(s>=t)throw Error(u(`property/index`,s));return r[t-s]}if(s>t)throw Error(u(`data`,s));if(a=n[t-s],!i)return a}let o=a,s=i.split(`/`);for(let e of s)e&&(a=(0,c._)`${a}${(0,c.getProperty)((0,d.unescapeJsonPointer)(e))}`,o=(0,c._)`${o} && ${a}`);return o;function u(e,n){return`Cannot access ${e} ${n} levels up, current level is ${t}`}}e.getData=me})),eg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=class extends Error{constructor(e){super(`validation failed`),this.errors=e,this.ajv=this.validation=!0}}})),tg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Qh();e.default=class extends Error{constructor(e,n,r,i){super(i||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,t.resolveUrl)(e,n,r),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(e,this.missingRef))}}})),ng=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=W(),n=eg(),r=Bh(),i=Qh(),a=G(),o=$h();var s=class{constructor(e){this.refs={},this.dynamicAnchors={};let t;typeof e.schema==`object`&&(t=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=e.baseId??(0,i.normalizeId)(t?.[e.schemaId||`$id`]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=t?.$async,this.refs={}}};e.SchemaEnv=s;function c(e){let a=d.call(this,e);if(a)return a;let s=(0,i.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:c,lines:l}=this.opts.code,{ownProperties:u}=this.opts,f=new t.CodeGen(this.scope,{es5:c,lines:l,ownProperties:u}),p;e.$async&&(p=f.scopeValue(`Error`,{ref:n.default,code:(0,t._)`require("ajv/dist/runtime/validation_error").default`}));let m=f.scopeName(`validate`);e.validateName=m;let h={gen:f,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:f.scopeValue(`schema`,this.opts.code.source===!0?{ref:e.schema,code:(0,t.stringify)(e.schema)}:{ref:e.schema}),validateName:m,ValidationError:p,schema:e.schema,schemaEnv:e,rootId:s,baseId:e.baseId||s,schemaPath:t.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?``:`#`),errorPath:(0,t._)`""`,opts:this.opts,self:this},g;try{this._compilations.add(e),(0,o.validateFunctionCode)(h),f.optimize(this.opts.code.optimize);let n=f.toString();g=`${f.scopeRefs(r.default.scope)}return ${n}`,this.opts.code.process&&(g=this.opts.code.process(g,e));let i=Function(`${r.default.self}`,`${r.default.scope}`,g)(this,this.scope.get());if(this.scope.value(m,{ref:i}),i.errors=null,i.schema=e.schema,i.schemaEnv=e,e.$async&&(i.$async=!0),this.opts.code.source===!0&&(i.source={validateName:m,validateCode:n,scopeValues:f._values}),this.opts.unevaluated){let{props:e,items:n}=h;i.evaluated={props:e instanceof t.Name?void 0:e,items:n instanceof t.Name?void 0:n,dynamicProps:e instanceof t.Name,dynamicItems:n instanceof t.Name},i.source&&(i.source.evaluated=(0,t.stringify)(i.evaluated))}return e.validate=i,e}catch(t){throw delete e.validate,delete e.validateName,g&&this.logger.error(`Error compiling schema, function code:`,g),t}finally{this._compilations.delete(e)}}e.compileSchema=c;function l(e,t,n){n=(0,i.resolveUrl)(this.opts.uriResolver,t,n);let r=e.refs[n];if(r)return r;let a=p.call(this,e,n);if(a===void 0){let r=e.localRefs?.[n],{schemaId:i}=this.opts;r&&(a=new s({schema:r,schemaId:i,root:e,baseId:t}))}if(a!==void 0)return e.refs[n]=u.call(this,a)}e.resolveRef=l;function u(e){return(0,i.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:c.call(this,e)}function d(e){for(let t of this._compilations)if(f(t,e))return t}e.getCompilingSchema=d;function f(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function p(e,t){let n;for(;typeof(n=this.refs[t])==`string`;)t=n;return n||this.schemas[t]||m.call(this,e,t)}function m(e,t){let n=this.opts.uriResolver.parse(t),r=(0,i._getFullPath)(this.opts.uriResolver,n),a=(0,i.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===a)return g.call(this,n,e);let o=(0,i.normalizeId)(r),l=this.refs[o]||this.schemas[o];if(typeof l==`string`){let t=m.call(this,e,l);return typeof t?.schema==`object`?g.call(this,n,t):void 0}if(typeof l?.schema==`object`){if(l.validate||c.call(this,l),o===(0,i.normalizeId)(t)){let{schema:t}=l,{schemaId:n}=this.opts,r=t[n];return r&&(a=(0,i.resolveUrl)(this.opts.uriResolver,a,r)),new s({schema:t,schemaId:n,root:e,baseId:a})}return g.call(this,n,l)}}e.resolveSchema=m;let h=new Set([`properties`,`patternProperties`,`enum`,`dependencies`,`definitions`]);function g(e,{baseId:t,schema:n,root:r}){if(e.fragment?.[0]!==`/`)return;for(let r of e.fragment.slice(1).split(`/`)){if(typeof n==`boolean`)return;let e=n[(0,a.unescapeFragment)(r)];if(e===void 0)return;n=e;let o=typeof n==`object`&&n[this.opts.schemaId];!h.has(r)&&o&&(t=(0,i.resolveUrl)(this.opts.uriResolver,t,o))}let o;if(typeof n!=`boolean`&&n.$ref&&!(0,a.schemaHasRulesButRef)(n,this.RULES)){let e=(0,i.resolveUrl)(this.opts.uriResolver,t,n.$ref);o=m.call(this,r,e)}let{schemaId:c}=this.opts;if(o||=new s({schema:n,schemaId:c,root:r,baseId:t}),o.schema!==o.root.schema)return o}})),rg=z(((e,t)=>{t.exports={$id:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`,description:`Meta-schema for $data reference (JSON AnySchema extension proposal)`,type:`object`,required:[`$data`],properties:{$data:{type:`string`,anyOf:[{format:`relative-json-pointer`},{format:`json-pointer`}]}},additionalProperties:!1}})),ig=z(((e,t)=>{let n=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),r=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function i(e){let t=``,n=0,r=0;for(r=0;r<e.length;r++)if(n=e[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r];break}for(r+=1;r<e.length;r++){if(n=e[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r]}return t}let a=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function o(e){return e.length=0,!0}function s(e,t,n){if(e.length){let r=i(e);if(r!==``)t.push(r);else return n.error=!0,!1;e.length=0}return!0}function c(e){let t=0,n={error:!1,address:``,zone:``},r=[],a=[],c=!1,l=!1,u=s;for(let i=0;i<e.length;i++){let s=e[i];if(s!==`[`&&s!==`]`){if(s===`:`){if(c===!0&&(l=!0),!u(a,r,n))break;if(++t>7){n.error=!0;break}i>0&&e[i-1]===`:`&&(c=!0),r.push(`:`);continue}if(s===`%`){if(!u(a,r,n))break;u=o}else{a.push(s);continue}}}return a.length&&(u===o?n.zone=a.join(``):l?r.push(a.join(``)):r.push(i(a))),n.address=r.join(``),n}function l(e){if(u(e,`:`)<2)return{host:e,isIPV6:!1};let t=c(e);if(t.error)return{host:e,isIPV6:!1};{let e=t.address,n=t.address;return t.zone&&(e+=`%`+t.zone,n+=`%25`+t.zone),{host:e,isIPV6:!0,escapedHost:n}}}function u(e,t){let n=0;for(let r=0;r<e.length;r++)e[r]===t&&n++;return n}function d(e){let t=e,n=[],r=-1,i=0;for(;i=t.length;){if(i===1){if(t===`.`)break;if(t===`/`){n.push(`/`);break}n.push(t);break}if(i===2){if(t[0]===`.`){if(t[1]===`.`)break;if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&(t[1]===`.`||t[1]===`/`)){n.push(`/`);break}}else if(i===3&&t===`/..`){n.length!==0&&n.pop(),n.push(`/`);break}if(t[0]===`.`){if(t[1]===`.`){if(t[2]===`/`){t=t.slice(3);continue}}else if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&t[1]===`.`){if(t[2]===`/`){t=t.slice(2);continue}if(t[2]===`.`&&t[3]===`/`){t=t.slice(3),n.length!==0&&n.pop();continue}}if((r=t.indexOf(`/`,1))===-1){n.push(t);break}n.push(t.slice(0,r)),t=t.slice(r)}return n.join(``)}function f(e,t){let n=t===!0?unescape:escape;return e.scheme!==void 0&&(e.scheme=n(e.scheme)),e.userinfo!==void 0&&(e.userinfo=n(e.userinfo)),e.host!==void 0&&(e.host=n(e.host)),e.path!==void 0&&(e.path=n(e.path)),e.query!==void 0&&(e.query=n(e.query)),e.fragment!==void 0&&(e.fragment=n(e.fragment)),e}function p(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push(`@`)),e.host!==void 0){let n=unescape(e.host);if(!r(n)){let t=l(n);n=t.isIPV6===!0?`[${t.escapedHost}]`:e.host}t.push(n)}return(typeof e.port==`number`||typeof e.port==`string`)&&(t.push(`:`),t.push(String(e.port))),t.length?t.join(``):void 0}t.exports={nonSimpleDomain:a,recomposeAuthority:p,normalizeComponentEncoding:f,removeDotSegments:d,isIPv4:r,isUUID:n,normalizeIPv6:l,stringArrayToHexStripped:i}})),ag=z(((e,t)=>{let{isUUID:n}=ig(),r=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,i=[`http`,`https`,`ws`,`wss`,`urn`,`urn:uuid`];function a(e){return i.indexOf(e)!==-1}function o(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]===`w`||e.scheme[0]===`W`)&&(e.scheme[1]===`s`||e.scheme[1]===`S`)&&(e.scheme[2]===`s`||e.scheme[2]===`S`):!1}function s(e){return e.host||(e.error=e.error||`HTTP URIs must have a host.`),e}function c(e){let t=String(e.scheme).toLowerCase()===`https`;return(e.port===(t?443:80)||e.port===``)&&(e.port=void 0),e.path||=`/`,e}function l(e){return e.secure=o(e),e.resourceName=(e.path||`/`)+(e.query?`?`+e.query:``),e.path=void 0,e.query=void 0,e}function u(e){if((e.port===(o(e)?443:80)||e.port===``)&&(e.port=void 0),typeof e.secure==`boolean`&&(e.scheme=e.secure?`wss`:`ws`,e.secure=void 0),e.resourceName){let[t,n]=e.resourceName.split(`?`);e.path=t&&t!==`/`?t:void 0,e.query=n,e.resourceName=void 0}return e.fragment=void 0,e}function d(e,t){if(!e.path)return e.error=`URN can not be parsed`,e;let n=e.path.match(r);if(n){let r=t.scheme||e.scheme||`urn`;e.nid=n[1].toLowerCase(),e.nss=n[2];let i=y(`${r}:${t.nid||e.nid}`);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||`URN can not be parsed.`;return e}function f(e,t){if(e.nid===void 0)throw Error(`URN without nid cannot be serialized`);let n=t.scheme||e.scheme||`urn`,r=e.nid.toLowerCase(),i=y(`${n}:${t.nid||r}`);i&&(e=i.serialize(e,t));let a=e,o=e.nss;return a.path=`${r||t.nid}:${o}`,t.skipEscape=!0,a}function p(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!n(r.uuid))&&(r.error=r.error||`UUID is not valid.`),r}function m(e){let t=e;return t.nss=(e.uuid||``).toLowerCase(),t}let h={scheme:`http`,domainHost:!0,parse:s,serialize:c},g={scheme:`https`,domainHost:h.domainHost,parse:s,serialize:c},_={scheme:`ws`,domainHost:!0,parse:l,serialize:u},v={http:h,https:g,ws:_,wss:{scheme:`wss`,domainHost:_.domainHost,parse:_.parse,serialize:_.serialize},urn:{scheme:`urn`,parse:d,serialize:f,skipNormalize:!0},"urn:uuid":{scheme:`urn:uuid`,parse:p,serialize:m,skipNormalize:!0}};Object.setPrototypeOf(v,null);function y(e){return e&&(v[e]||v[e.toLowerCase()])||void 0}t.exports={wsIsSecure:o,SCHEMES:v,isValidSchemeName:a,getSchemeHandler:y}})),og=z(((e,t)=>{let{normalizeIPv6:n,removeDotSegments:r,recomposeAuthority:i,normalizeComponentEncoding:a,isIPv4:o,nonSimpleDomain:s}=ig(),{SCHEMES:c,getSchemeHandler:l}=ag();function u(e,t){return typeof e==`string`?e=m(g(e,t),t):typeof e==`object`&&(e=g(m(e,t),t)),e}function d(e,t,n){let r=n?Object.assign({scheme:`null`},n):{scheme:`null`},i=f(g(e,r),g(t,r),r,!0);return r.skipEscape=!0,m(i,r)}function f(e,t,n,i){let a={};return i||(e=g(m(e,n),n),t=g(m(t,n),n)),n||={},!n.tolerant&&t.scheme?(a.scheme=t.scheme,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.path?(t.path[0]===`/`?a.path=r(t.path):(a.path=(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?`/`+t.path:e.path?e.path.slice(0,e.path.lastIndexOf(`/`)+1)+t.path:t.path,a.path=r(a.path)),a.query=t.query):(a.path=e.path,a.query=t.query===void 0?e.query:t.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=t.fragment,a}function p(e,t,n){return typeof e==`string`?(e=unescape(e),e=m(a(g(e,n),!0),{...n,skipEscape:!0})):typeof e==`object`&&(e=m(a(e,!0),{...n,skipEscape:!0})),typeof t==`string`?(t=unescape(t),t=m(a(g(t,n),!0),{...n,skipEscape:!0})):typeof t==`object`&&(t=m(a(t,!0),{...n,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()}function m(e,t){let n={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:``},a=Object.assign({},t),o=[],s=l(a.scheme||n.scheme);s&&s.serialize&&s.serialize(n,a),n.path!==void 0&&(a.skipEscape?n.path=unescape(n.path):(n.path=escape(n.path),n.scheme!==void 0&&(n.path=n.path.split(`%3A`).join(`:`)))),a.reference!==`suffix`&&n.scheme&&o.push(n.scheme,`:`);let c=i(n);if(c!==void 0&&(a.reference!==`suffix`&&o.push(`//`),o.push(c),n.path&&n.path[0]!==`/`&&o.push(`/`)),n.path!==void 0){let e=n.path;!a.absolutePath&&(!s||!s.absolutePath)&&(e=r(e)),c===void 0&&e[0]===`/`&&e[1]===`/`&&(e=`/%2F`+e.slice(2)),o.push(e)}return n.query!==void 0&&o.push(`?`,n.query),n.fragment!==void 0&&o.push(`#`,n.fragment),o.join(``)}let h=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function g(e,t){let r=Object.assign({},t),i={scheme:void 0,userinfo:void 0,host:``,port:void 0,path:``,query:void 0,fragment:void 0},a=!1;r.reference===`suffix`&&(e=r.scheme?r.scheme+`:`+e:`//`+e);let c=e.match(h);if(c){if(i.scheme=c[1],i.userinfo=c[3],i.host=c[4],i.port=parseInt(c[5],10),i.path=c[6]||``,i.query=c[7],i.fragment=c[8],isNaN(i.port)&&(i.port=c[5]),i.host){if(o(i.host)===!1){let e=n(i.host);i.host=e.host.toLowerCase(),a=e.isIPV6}else a=!0}i.reference=i.scheme===void 0&&i.userinfo===void 0&&i.host===void 0&&i.port===void 0&&i.query===void 0&&!i.path?`same-document`:i.scheme===void 0?`relative`:i.fragment===void 0?`absolute`:`uri`,r.reference&&r.reference!==`suffix`&&r.reference!==i.reference&&(i.error=i.error||`URI is not a `+r.reference+` reference.`);let t=l(r.scheme||i.scheme);if(!r.unicodeSupport&&(!t||!t.unicodeSupport)&&i.host&&(r.domainHost||t&&t.domainHost)&&a===!1&&s(i.host))try{i.host=URL.domainToASCII(i.host.toLowerCase())}catch(e){i.error=i.error||`Host's domain name can not be converted to ASCII: `+e}(!t||t&&!t.skipNormalize)&&(e.indexOf(`%`)!==-1&&(i.scheme!==void 0&&(i.scheme=unescape(i.scheme)),i.host!==void 0&&(i.host=unescape(i.host))),i.path&&=escape(unescape(i.path)),i.fragment&&=encodeURI(decodeURIComponent(i.fragment))),t&&t.parse&&t.parse(i,r)}else i.error=i.error||`URI can not be parsed.`;return i}let _={SCHEMES:c,normalize:u,resolve:d,resolveComponent:f,equal:p,serialize:m,parse:g};t.exports=_,t.exports.default=_,t.exports.fastUri=_})),sg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=og();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),cg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=$h();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var n=W();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return n.CodeGen}});let r=eg(),i=tg(),a=Uh(),o=ng(),s=W(),c=Qh(),l=Gh(),u=G(),d=rg(),f=sg(),p=(e,t)=>new RegExp(e,t);p.code=`new RegExp`;let m=[`removeAdditional`,`useDefaults`,`coerceTypes`],h=new Set([`validate`,`serialize`,`parse`,`wrapper`,`root`,`schema`,`keyword`,`pattern`,`formats`,`validate$data`,`func`,`obj`,`Error`]),g={errorDataPath:``,format:"`validateFormats: false` can be used instead.",nullable:`"nullable" keyword is supported by default.`,jsonPointers:`Deprecated jsPropertySyntax can be used instead.`,extendRefs:`Deprecated ignoreKeywordsWithRef can be used instead.`,missingRefs:`Pass empty schema with $id that should be ignored to ajv.addSchema.`,processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:`"uniqueItems" keyword is always validated.`,unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:`Map is used as cache, schema object as key.`,serialize:`Map is used as cache, schema object as key.`,ajvErrors:`It is default now.`},_={ignoreKeywordsWithRef:``,jsPropertySyntax:``,unicode:`"minLength"/"maxLength" account for unicode characters by default.`};function v(e){let t=e.strict,n=e.code?.optimize,r=n===!0||n===void 0?1:n||0,i=e.code?.regExp??p,a=e.uriResolver??f.default;return{strictSchema:e.strictSchema??t??!0,strictNumbers:e.strictNumbers??t??!0,strictTypes:e.strictTypes??t??`log`,strictTuples:e.strictTuples??t??`log`,strictRequired:e.strictRequired??t??!1,code:e.code?{...e.code,optimize:r,regExp:i}:{optimize:r,regExp:i},loopRequired:e.loopRequired??200,loopEnum:e.loopEnum??200,meta:e.meta??!0,messages:e.messages??!0,inlineRefs:e.inlineRefs??!0,schemaId:e.schemaId??`$id`,addUsedSchema:e.addUsedSchema??!0,validateSchema:e.validateSchema??!0,validateFormats:e.validateFormats??!0,unicodeRegExp:e.unicodeRegExp??!0,int32range:e.int32range??!0,uriResolver:a}}var y=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...v(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new s.ValueScope({scope:{},prefixes:h,es5:t,lines:n}),this.logger=E(e.logger);let r=e.validateFormats;e.validateFormats=!1,this.RULES=(0,a.getRules)(),b.call(this,g,e,`NOT SUPPORTED`),b.call(this,_,e,`DEPRECATED`,`warn`),this._metaOpts=T.call(this),e.formats&&C.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&w.call(this,e.keywords),typeof e.meta==`object`&&this.addMetaSchema(e.meta),S.call(this),e.validateFormats=r}_addVocabularies(){this.addKeyword(`$async`)}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,r=d;n===`id`&&(r={...d},r.id=r.$id,delete r.$id),t&&e&&this.addMetaSchema(r,r[n],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e==`object`?e[t]||e:void 0}validate(e,t){let n;if(typeof e==`string`){if(n=this.getSchema(e),!n)throw Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let r=n(t);return`$async`in n||(this.errors=n.errors),r}compile(e,t){let n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if(typeof this.opts.loadSchema!=`function`)throw Error(`options.loadSchema should be a function`);let{loadSchema:n}=this.opts;return r.call(this,e,t);async function r(e,t){await a.call(this,e.$schema);let n=this._addSchema(e,t);return n.validate||o.call(this,n)}async function a(e){e&&!this.getSchema(e)&&await r.call(this,{$ref:e},!0)}async function o(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof i.default))throw t;return s.call(this,t),await c.call(this,t.missingSchema),o.call(this,e)}}function s({missingSchema:e,missingRef:t}){if(this.refs[e])throw Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){let n=await l.call(this,e);this.refs[e]||await a.call(this,n.$schema),this.refs[e]||this.addSchema(n,e,t)}async function l(e){let t=this._loading[e];if(t)return t;try{return await(this._loading[e]=n(e))}finally{delete this._loading[e]}}}addSchema(e,t,n,r=this.opts.validateSchema){if(Array.isArray(e)){for(let t of e)this.addSchema(t,void 0,n,r);return this}let i;if(typeof e==`object`){let{schemaId:t}=this.opts;if(i=e[t],i!==void 0&&typeof i!=`string`)throw Error(`schema ${t} must be string`)}return t=(0,c.normalizeId)(t||i),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,r,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if(typeof e==`boolean`)return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!=`string`)throw Error(`$schema must be a string`);if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn(`meta-schema not available`),this.errors=null,!0;let r=this.validate(n,e);if(!r&&t){let e=`schema is invalid: `+this.errorsText();if(this.opts.validateSchema===`log`)this.logger.error(e);else throw Error(e)}return r}getSchema(e){let t;for(;typeof(t=x.call(this,e))==`string`;)e=t;if(t===void 0){let{schemaId:n}=this.opts,r=new o.SchemaEnv({schema:{},schemaId:n});if(t=o.resolveSchema.call(this,r,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case`undefined`:return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case`string`:{let t=x.call(this,e);return typeof t==`object`&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case`object`:{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,c.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw Error(`ajv.removeSchema: invalid parameter`)}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e==`string`)n=e,typeof t==`object`&&(this.logger.warn(`these parameters are deprecated, see docs for addKeyword`),t.keyword=n);else if(typeof e==`object`&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw Error(`addKeywords: keyword must be string or non-empty array`)}else throw Error(`invalid addKeywords parameters`);if(O.call(this,n,t),!t)return(0,u.eachItem)(n,e=>k.call(this,e)),this;ne.call(this,t);let r={...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)};return(0,u.eachItem)(n,r.type.length===0?e=>k.call(this,e,r):e=>r.type.forEach(t=>k.call(this,e,r,t))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t==`object`?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let n of t.rules){let t=n.rules.findIndex(t=>t.keyword===e);t>=0&&n.rules.splice(t,1)}return this}addFormat(e,t){return typeof t==`string`&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=`, `,dataVar:n=`data`}={}){return!e||e.length===0?`No errors`:e.map(e=>`${n}${e.instancePath} ${e.message}`).reduce((e,n)=>e+t+n)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let r of t){let t=r.split(`/`).slice(1),i=e;for(let e of t)i=i[e];for(let e in n){let t=n[e];if(typeof t!=`object`)continue;let{$data:r}=t.definition,a=i[e];r&&a&&(i[e]=A(a))}}return e}_removeAllSchemas(e,t){for(let n in e){let r=e[n];(!t||t.test(n))&&(typeof r==`string`?delete e[n]:r&&!r.meta&&(this._cache.delete(r.schema),delete e[n]))}}_addSchema(e,t,n,r=this.opts.validateSchema,i=this.opts.addUsedSchema){let a,{schemaId:s}=this.opts;if(typeof e==`object`)a=e[s];else if(this.opts.jtd)throw Error(`schema must be object`);else if(typeof e!=`boolean`)throw Error(`schema must be object or boolean`);let l=this._cache.get(e);if(l!==void 0)return l;n=(0,c.normalizeId)(a||n);let u=c.getSchemaRefs.call(this,e,n);return l=new o.SchemaEnv({schema:e,schemaId:s,meta:t,baseId:n,localRefs:u}),this._cache.set(l.schema,l),i&&!n.startsWith(`#`)&&(n&&this._checkUnique(n),this.refs[n]=l),r&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):o.compileSchema.call(this,e),!e.validate)throw Error(`ajv implementation error`);return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,e)}finally{this.opts=t}}};y.ValidationError=r.default,y.MissingRefError=i.default,e.default=y;function b(e,t,n,r=`error`){for(let i in e){let a=i;a in t&&this.logger[r](`${n}: option ${i}. ${e[a]}`)}}function x(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function S(){let e=this.opts.schemas;if(e){if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}}function C(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function w(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn(`keywords option as map is deprecated, pass array`);for(let t in e){let n=e[t];n.keyword||=t,this.addKeyword(n)}}function T(){let e={...this.opts};for(let t of m)delete e[t];return e}let ee={log(){},warn(){},error(){}};function E(e){if(e===!1)return ee;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error(`logger must implement log, warn and error methods`)}let D=/^[a-z_$][a-z0-9_$:-]*$/i;function O(e,t){let{RULES:n}=this;if((0,u.eachItem)(e,e=>{if(n.keywords[e])throw Error(`Keyword ${e} is already defined`);if(!D.test(e))throw Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!(`code`in t||`validate`in t))throw Error(`$data keyword must have "code" or "validate" function`)}function k(e,t,n){var r;let i=t?.post;if(n&&i)throw Error(`keyword with "post" flag cannot have "type"`);let{RULES:a}=this,o=i?a.post:a.rules.find(({type:e})=>e===n);if(o||(o={type:n,rules:[]},a.rules.push(o)),a.keywords[e]=!0,!t)return;let s={keyword:e,definition:{...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)}};t.before?te.call(this,o,s,t.before):o.rules.push(s),a.all[e]=s,(r=t.implements)==null||r.forEach(e=>this.addKeyword(e))}function te(e,t,n){let r=e.rules.findIndex(e=>e.keyword===n);r>=0?e.rules.splice(r,0,t):(e.rules.push(t),this.logger.warn(`rule ${n} is not defined`))}function ne(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=A(t)),e.validateSchema=this.compile(t,!0))}let re={$ref:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`};function A(e){return{anyOf:[e,re]}}})),lg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),ug=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.callRef=e.getValidate=void 0;let t=tg(),n=qh(),r=W(),i=Bh(),a=ng(),o=G(),s={keyword:`$ref`,schemaType:`string`,code(e){let{gen:n,schema:i,it:o}=e,{baseId:s,schemaEnv:u,validateName:d,opts:f,self:p}=o,{root:m}=u;if((i===`#`||i===`#/`)&&s===m.baseId)return g();let h=a.resolveRef.call(p,m,s,i);if(h===void 0)throw new t.default(o.opts.uriResolver,s,i);if(h instanceof a.SchemaEnv)return _(h);return v(h);function g(){if(u===m)return l(e,d,u,u.$async);let t=n.scopeValue(`root`,{ref:m});return l(e,(0,r._)`${t}.validate`,m,m.$async)}function _(t){l(e,c(e,t),t,t.$async)}function v(t){let a=n.scopeValue(`schema`,f.code.source===!0?{ref:t,code:(0,r.stringify)(t)}:{ref:t}),o=n.name(`valid`),s=e.subschema({schema:t,dataTypes:[],schemaPath:r.nil,topSchemaRef:a,errSchemaPath:i},o);e.mergeEvaluated(s),e.ok(o)}}};function c(e,t){let{gen:n}=e;return t.validate?n.scopeValue(`validate`,{ref:t.validate}):(0,r._)`${n.scopeValue(`wrapper`,{ref:t})}.validate`}e.getValidate=c;function l(e,t,a,s){let{gen:c,it:l}=e,{allErrors:u,schemaEnv:d,opts:f}=l,p=f.passContext?i.default.this:r.nil;s?m():h();function m(){if(!d.$async)throw Error(`async schema referenced by sync schema`);let i=c.let(`valid`);c.try(()=>{c.code((0,r._)`await ${(0,n.callValidateCode)(e,t,p)}`),_(t),u||c.assign(i,!0)},e=>{c.if((0,r._)`!(${e} instanceof ${l.ValidationError})`,()=>c.throw(e)),g(e),u||c.assign(i,!1)}),e.ok(i)}function h(){e.result((0,n.callValidateCode)(e,t,p),()=>_(t),()=>g(t))}function g(e){let t=(0,r._)`${e}.errors`;c.assign(i.default.vErrors,(0,r._)`${i.default.vErrors} === null ? ${t} : ${i.default.vErrors}.concat(${t})`),c.assign(i.default.errors,(0,r._)`${i.default.vErrors}.length`)}function _(e){if(!l.opts.unevaluated)return;let t=a?.validate?.evaluated;if(l.props!==!0){if(t&&!t.dynamicProps)t.props!==void 0&&(l.props=o.mergeEvaluated.props(c,t.props,l.props));else{let t=c.var(`props`,(0,r._)`${e}.evaluated.props`);l.props=o.mergeEvaluated.props(c,t,l.props,r.Name)}}if(l.items!==!0){if(t&&!t.dynamicItems)t.items!==void 0&&(l.items=o.mergeEvaluated.items(c,t.items,l.items));else{let t=c.var(`items`,(0,r._)`${e}.evaluated.items`);l.items=o.mergeEvaluated.items(c,t,l.items,r.Name)}}}}e.callRef=l,e.default=s})),dg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=lg(),n=ug();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),fg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=t.operators,r={maximum:{okStr:`<=`,ok:n.LTE,fail:n.GT},minimum:{okStr:`>=`,ok:n.GTE,fail:n.LT},exclusiveMaximum:{okStr:`<`,ok:n.LT,fail:n.GTE},exclusiveMinimum:{okStr:`>`,ok:n.GT,fail:n.LTE}};e.default={keyword:Object.keys(r),type:`number`,schemaType:`number`,$data:!0,error:{message:({keyword:e,schemaCode:n})=>(0,t.str)`must be ${r[e].okStr} ${n}`,params:({keyword:e,schemaCode:n})=>(0,t._)`{comparison: ${r[e].okStr}, limit: ${n}}`},code(e){let{keyword:n,data:i,schemaCode:a}=e;e.fail$data((0,t._)`${i} ${r[n].fail} ${a} || isNaN(${i})`)}}})),pg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W();e.default={keyword:`multipleOf`,type:`number`,schemaType:`number`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,t._)`{multipleOf: ${e}}`},code(e){let{gen:n,data:r,schemaCode:i,it:a}=e,o=a.opts.multipleOfPrecision,s=n.let(`res`),c=o?(0,t._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${o}`:(0,t._)`${s} !== parseInt(${s})`;e.fail$data((0,t._)`(${i} === 0 || (${s} = ${r}/${i}, ${c}))`)}}})),mg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){let t=e.length,n=0,r=0,i;for(;r<t;)n++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<t&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return n}e.default=t,t.code=`require("ajv/dist/runtime/ucs2length").default`})),hg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G(),r=mg();e.default={keyword:[`maxLength`,`minLength`],type:`string`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxLength`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} characters`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:i,data:a,schemaCode:o,it:s}=e,c=i===`maxLength`?t.operators.GT:t.operators.LT,l=s.opts.unicode===!1?(0,t._)`${a}.length`:(0,t._)`${(0,n.useFunc)(e.gen,r.default)}(${a})`;e.fail$data((0,t._)`${l} ${c} ${o}`)}}})),gg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=qh(),n=G(),r=W();e.default={keyword:`pattern`,type:`string`,schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,r.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,r._)`{pattern: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e,u=l.opts.unicodeRegExp?`u`:``;if(o){let{regExp:t}=l.opts.code,o=t.code===`new RegExp`?(0,r._)`new RegExp`:(0,n.useFunc)(i,t),s=i.let(`valid`);i.try(()=>i.assign(s,(0,r._)`${o}(${c}, ${u}).test(${a})`),()=>i.assign(s,!1)),e.fail$data((0,r._)`!${s}`)}else{let n=(0,t.usePattern)(e,s);e.fail$data((0,r._)`!${n}.test(${a})`)}}}})),_g=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W();e.default={keyword:[`maxProperties`,`minProperties`],type:`object`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxProperties`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} properties`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxProperties`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`Object.keys(${r}).length ${a} ${i}`)}}})),vg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=qh(),n=W(),r=G();e.default={keyword:`required`,type:`object`,schemaType:`array`,$data:!0,error:{message:({params:{missingProperty:e}})=>(0,n.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,n._)`{missingProperty: ${e}}`},code(e){let{gen:i,schema:a,schemaCode:o,data:s,$data:c,it:l}=e,{opts:u}=l;if(!c&&a.length===0)return;let d=a.length>=u.loopRequired;if(l.allErrors?f():p(),u.strictRequired){let t=e.parentSchema.properties,{definedProperties:n}=e.it;for(let e of a)if(t?.[e]===void 0&&!n.has(e)){let t=`required property "${e}" is not defined at "${l.schemaEnv.baseId+l.errSchemaPath}" (strictRequired)`;(0,r.checkStrictMode)(l,t,l.opts.strictRequired)}}function f(){if(d||c)e.block$data(n.nil,m);else for(let n of a)(0,t.checkReportMissingProp)(e,n)}function p(){let n=i.let(`missing`);if(d||c){let t=i.let(`valid`,!0);e.block$data(t,()=>h(n,t)),e.ok(t)}else i.if((0,t.checkMissingProp)(e,a,n)),(0,t.reportMissingProp)(e,n),i.else()}function m(){i.forOf(`prop`,o,n=>{e.setParams({missingProperty:n}),i.if((0,t.noPropertyInData)(i,s,n,u.ownProperties),()=>e.error())})}function h(r,a){e.setParams({missingProperty:r}),i.forOf(r,o,()=>{i.assign(a,(0,t.propertyInData)(i,s,r,u.ownProperties)),i.if((0,n.not)(a),()=>{e.error(),i.break()})},n.nil)}}}})),yg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W();e.default={keyword:[`maxItems`,`minItems`],type:`array`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxItems`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} items`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxItems`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`${r}.length ${a} ${i}`)}}})),bg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Xh();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),xg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Gh(),n=W(),r=G(),i=bg();e.default={keyword:`uniqueItems`,type:`array`,schemaType:`boolean`,$data:!0,error:{message:({params:{i:e,j:t}})=>(0,n.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,n._)`{i: ${e}, j: ${t}}`},code(e){let{gen:a,data:o,$data:s,schema:c,parentSchema:l,schemaCode:u,it:d}=e;if(!s&&!c)return;let f=a.let(`valid`),p=l.items?(0,t.getSchemaTypes)(l.items):[];e.block$data(f,m,(0,n._)`${u} === false`),e.ok(f);function m(){let t=a.let(`i`,(0,n._)`${o}.length`),r=a.let(`j`);e.setParams({i:t,j:r}),a.assign(f,!0),a.if((0,n._)`${t} > 1`,()=>(h()?g:_)(t,r))}function h(){return p.length>0&&!p.some(e=>e===`object`||e===`array`)}function g(r,i){let s=a.name(`item`),c=(0,t.checkDataTypes)(p,s,d.opts.strictNumbers,t.DataType.Wrong),l=a.const(`indices`,(0,n._)`{}`);a.for((0,n._)`;${r}--;`,()=>{a.let(s,(0,n._)`${o}[${r}]`),a.if(c,(0,n._)`continue`),p.length>1&&a.if((0,n._)`typeof ${s} == "string"`,(0,n._)`${s} += "_"`),a.if((0,n._)`typeof ${l}[${s}] == "number"`,()=>{a.assign(i,(0,n._)`${l}[${s}]`),e.error(),a.assign(f,!1).break()}).code((0,n._)`${l}[${s}] = ${r}`)})}function _(t,s){let c=(0,r.useFunc)(a,i.default),l=a.name(`outer`);a.label(l).for((0,n._)`;${t}--;`,()=>a.for((0,n._)`${s} = ${t}; ${s}--;`,()=>a.if((0,n._)`${c}(${o}[${t}], ${o}[${s}])`,()=>{e.error(),a.assign(f,!1).break(l)})))}}}})),Sg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G(),r=bg();e.default={keyword:`const`,$data:!0,error:{message:`must be equal to constant`,params:({schemaCode:e})=>(0,t._)`{allowedValue: ${e}}`},code(e){let{gen:i,data:a,$data:o,schemaCode:s,schema:c}=e;o||c&&typeof c==`object`?e.fail$data((0,t._)`!${(0,n.useFunc)(i,r.default)}(${a}, ${s})`):e.fail((0,t._)`${c} !== ${a}`)}}})),Cg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G(),r=bg();e.default={keyword:`enum`,schemaType:`array`,$data:!0,error:{message:`must be equal to one of the allowed values`,params:({schemaCode:e})=>(0,t._)`{allowedValues: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e;if(!o&&s.length===0)throw Error(`enum must have non-empty array`);let u=s.length>=l.opts.loopEnum,d,f=()=>d??=(0,n.useFunc)(i,r.default),p;if(u||o)p=i.let(`valid`),e.block$data(p,m);else{if(!Array.isArray(s))throw Error(`ajv implementation error`);let e=i.const(`vSchema`,c);p=(0,t.or)(...s.map((t,n)=>h(e,n)))}e.pass(p);function m(){i.assign(p,!1),i.forOf(`v`,c,e=>i.if((0,t._)`${f()}(${a}, ${e})`,()=>i.assign(p,!0).break()))}function h(e,n){let r=s[n];return typeof r==`object`&&r?(0,t._)`${f()}(${a}, ${e}[${n}])`:(0,t._)`${a} === ${r}`}}}})),wg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=fg(),n=pg(),r=hg(),i=gg(),a=_g(),o=vg(),s=yg(),c=xg(),l=Sg(),u=Cg();e.default=[t.default,n.default,r.default,i.default,a.default,o.default,s.default,c.default,{keyword:`type`,schemaType:[`string`,`array`]},{keyword:`nullable`,schemaType:`boolean`},l.default,u.default]})),Tg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateAdditionalItems=void 0;let t=W(),n=G(),r={keyword:`additionalItems`,type:`array`,schemaType:[`boolean`,`object`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{parentSchema:t,it:r}=e,{items:a}=t;if(!Array.isArray(a)){(0,n.checkStrictMode)(r,`"additionalItems" is ignored when "items" is not an array of schemas`);return}i(e,a)}};function i(e,r){let{gen:i,schema:a,data:o,keyword:s,it:c}=e;c.items=!0;let l=i.const(`len`,(0,t._)`${o}.length`);if(a===!1)e.setParams({len:r.length}),e.pass((0,t._)`${l} <= ${r.length}`);else if(typeof a==`object`&&!(0,n.alwaysValidSchema)(c,a)){let n=i.var(`valid`,(0,t._)`${l} <= ${r.length}`);i.if((0,t.not)(n),()=>u(n)),e.ok(n)}function u(a){i.forRange(`i`,r.length,l,r=>{e.subschema({keyword:s,dataProp:r,dataPropType:n.Type.Num},a),c.allErrors||i.if((0,t.not)(a),()=>i.break())})}}e.validateAdditionalItems=i,e.default=r})),Eg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateTuple=void 0;let t=W(),n=G(),r=qh(),i={keyword:`items`,type:`array`,schemaType:[`object`,`array`,`boolean`],before:`uniqueItems`,code(e){let{schema:t,it:i}=e;if(Array.isArray(t))return a(e,`additionalItems`,t);i.items=!0,!(0,n.alwaysValidSchema)(i,t)&&e.ok((0,r.validateArray)(e))}};function a(e,r,i=e.schema){let{gen:a,parentSchema:o,data:s,keyword:c,it:l}=e;f(o),l.opts.unevaluated&&i.length&&l.items!==!0&&(l.items=n.mergeEvaluated.items(a,i.length,l.items));let u=a.name(`valid`),d=a.const(`len`,(0,t._)`${s}.length`);i.forEach((r,i)=>{(0,n.alwaysValidSchema)(l,r)||(a.if((0,t._)`${d} > ${i}`,()=>e.subschema({keyword:c,schemaProp:i,dataProp:i},u)),e.ok(u))});function f(e){let{opts:t,errSchemaPath:a}=l,o=i.length,s=o===e.minItems&&(o===e.maxItems||e[r]===!1);if(t.strictTuples&&!s){let e=`"${c}" is ${o}-tuple, but minItems or maxItems/${r} are not specified or different at path "${a}"`;(0,n.checkStrictMode)(l,e,t.strictTuples)}}}e.validateTuple=a,e.default=i})),Dg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Eg();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),Og=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G(),r=qh(),i=Tg();e.default={keyword:`items`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{schema:t,parentSchema:a,it:o}=e,{prefixItems:s}=a;o.items=!0,!(0,n.alwaysValidSchema)(o,t)&&(s?(0,i.validateAdditionalItems)(e,s):e.ok((0,r.validateArray)(e)))}}})),kg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G();e.default={keyword:`contains`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,trackErrors:!0,error:{message:({params:{min:e,max:n}})=>n===void 0?(0,t.str)`must contain at least ${e} valid item(s)`:(0,t.str)`must contain at least ${e} and no more than ${n} valid item(s)`,params:({params:{min:e,max:n}})=>n===void 0?(0,t._)`{minContains: ${e}}`:(0,t._)`{minContains: ${e}, maxContains: ${n}}`},code(e){let{gen:r,schema:i,parentSchema:a,data:o,it:s}=e,c,l,{minContains:u,maxContains:d}=a;s.opts.next?(c=u===void 0?1:u,l=d):c=1;let f=r.const(`len`,(0,t._)`${o}.length`);if(e.setParams({min:c,max:l}),l===void 0&&c===0){(0,n.checkStrictMode)(s,`"minContains" == 0 without "maxContains": "contains" keyword ignored`);return}if(l!==void 0&&c>l){(0,n.checkStrictMode)(s,`"minContains" > "maxContains" is always invalid`),e.fail();return}if((0,n.alwaysValidSchema)(s,i)){let n=(0,t._)`${f} >= ${c}`;l!==void 0&&(n=(0,t._)`${n} && ${f} <= ${l}`),e.pass(n);return}s.items=!0;let p=r.name(`valid`);l===void 0&&c===1?h(p,()=>r.if(p,()=>r.break())):c===0?(r.let(p,!0),l!==void 0&&r.if((0,t._)`${o}.length > 0`,m)):(r.let(p,!1),m()),e.result(p,()=>e.reset());function m(){let e=r.name(`_valid`),t=r.let(`count`,0);h(e,()=>r.if(e,()=>g(t)))}function h(t,i){r.forRange(`i`,0,f,r=>{e.subschema({keyword:`contains`,dataProp:r,dataPropType:n.Type.Num,compositeRule:!0},t),i()})}function g(e){r.code((0,t._)`${e}++`),l===void 0?r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0).break()):(r.if((0,t._)`${e} > ${l}`,()=>r.assign(p,!1).break()),c===1?r.assign(p,!0):r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0)))}}}})),Ag=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;let t=W(),n=G(),r=qh();e.error={message:({params:{property:e,depsCount:n,deps:r}})=>{let i=n===1?`property`:`properties`;return(0,t.str)`must have ${i} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:n,deps:r,missingProperty:i}})=>(0,t._)`{property: ${e},
180
+ || ${s} === "boolean" || ${a} === null`).assign(c,(0,i._)`[${a}]`)}}}function p({gen:e,parentData:t,parentDataProperty:n},r){e.if((0,i._)`${t} !== undefined`,()=>e.assign((0,i._)`${t}[${n}]`,r))}function m(e,t,n,r=o.Correct){let a=r===o.Correct?i.operators.EQ:i.operators.NEQ,s;switch(e){case`null`:return(0,i._)`${t} ${a} null`;case`array`:s=(0,i._)`Array.isArray(${t})`;break;case`object`:s=(0,i._)`${t} && typeof ${t} == "object" && !Array.isArray(${t})`;break;case`integer`:s=c((0,i._)`!(${t} % 1) && !isNaN(${t})`);break;case`number`:s=c();break;default:return(0,i._)`typeof ${t} ${a} ${e}`}return r===o.Correct?s:(0,i.not)(s);function c(e=i.nil){return(0,i.and)((0,i._)`typeof ${t} == "number"`,e,n?(0,i._)`isFinite(${t})`:i.nil)}}e.checkDataType=m;function h(e,t,n,r){if(e.length===1)return m(e[0],t,n,r);let o,s=(0,a.toHash)(e);if(s.array&&s.object){let e=(0,i._)`typeof ${t} != "object"`;o=s.null?e:(0,i._)`!${t} || ${e}`,delete s.null,delete s.array,delete s.object}else o=i.nil;s.number&&delete s.integer;for(let e in s)o=(0,i.and)(o,m(e,t,n,r));return o}e.checkDataTypes=h;let g={message:({schema:e})=>`must be ${e}`,params:({schema:e,schemaValue:t})=>typeof e==`string`?(0,i._)`{type: ${e}}`:(0,i._)`{type: ${t}}`};function _(e){let t=v(e);(0,r.reportError)(t,g)}e.reportTypeError=_;function v(e){let{gen:t,data:n,schema:r}=e,i=(0,a.schemaRefOrVal)(e,r,`type`);return{gen:t,keyword:`type`,data:n,schema:r.type,schemaCode:i,schemaValue:i,parentSchema:r,params:{},it:e}}})),Kh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.assignDefaults=void 0;let t=W(),n=G();function r(e,t){let{properties:n,items:r}=e.schema;if(t===`object`&&n)for(let t in n)i(e,t,n[t].default);else t===`array`&&Array.isArray(r)&&r.forEach((t,n)=>i(e,n,t.default))}e.assignDefaults=r;function i(e,r,i){let{gen:a,compositeRule:o,data:s,opts:c}=e;if(i===void 0)return;let l=(0,t._)`${s}${(0,t.getProperty)(r)}`;if(o){(0,n.checkStrictMode)(e,`default is ignored for: ${l}`);return}let u=(0,t._)`${l} === undefined`;c.useDefaults===`empty`&&(u=(0,t._)`${u} || ${l} === null || ${l} === ""`),a.if(u,(0,t._)`${l} = ${(0,t.stringify)(i)}`)}})),qh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateUnion=e.validateArray=e.usePattern=e.callValidateCode=e.schemaProperties=e.allSchemaProperties=e.noPropertyInData=e.propertyInData=e.isOwnProperty=e.hasPropFunc=e.reportMissingProp=e.checkMissingProp=e.checkReportMissingProp=void 0;let t=W(),n=G(),r=Bh(),i=G();function a(e,n){let{gen:r,data:i,it:a}=e;r.if(d(r,i,n,a.opts.ownProperties),()=>{e.setParams({missingProperty:(0,t._)`${n}`},!0),e.error()})}e.checkReportMissingProp=a;function o({gen:e,data:n,it:{opts:r}},i,a){return(0,t.or)(...i.map(i=>(0,t.and)(d(e,n,i,r.ownProperties),(0,t._)`${a} = ${i}`)))}e.checkMissingProp=o;function s(e,t){e.setParams({missingProperty:t},!0),e.error()}e.reportMissingProp=s;function c(e){return e.scopeValue(`func`,{ref:Object.prototype.hasOwnProperty,code:(0,t._)`Object.prototype.hasOwnProperty`})}e.hasPropFunc=c;function l(e,n,r){return(0,t._)`${c(e)}.call(${n}, ${r})`}e.isOwnProperty=l;function u(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} !== undefined`;return i?(0,t._)`${a} && ${l(e,n,r)}`:a}e.propertyInData=u;function d(e,n,r,i){let a=(0,t._)`${n}${(0,t.getProperty)(r)} === undefined`;return i?(0,t.or)(a,(0,t.not)(l(e,n,r))):a}e.noPropertyInData=d;function f(e){return e?Object.keys(e).filter(e=>e!==`__proto__`):[]}e.allSchemaProperties=f;function p(e,t){return f(t).filter(r=>!(0,n.alwaysValidSchema)(e,t[r]))}e.schemaProperties=p;function m({schemaCode:e,data:n,it:{gen:i,topSchemaRef:a,schemaPath:o,errorPath:s},it:c},l,u,d){let f=d?(0,t._)`${e}, ${n}, ${a}${o}`:n,p=[[r.default.instancePath,(0,t.strConcat)(r.default.instancePath,s)],[r.default.parentData,c.parentData],[r.default.parentDataProperty,c.parentDataProperty],[r.default.rootData,r.default.rootData]];c.opts.dynamicRef&&p.push([r.default.dynamicAnchors,r.default.dynamicAnchors]);let m=(0,t._)`${f}, ${i.object(...p)}`;return u===t.nil?(0,t._)`${l}(${m})`:(0,t._)`${l}.call(${u}, ${m})`}e.callValidateCode=m;let h=(0,t._)`new RegExp`;function g({gen:e,it:{opts:n}},r){let a=n.unicodeRegExp?`u`:``,{regExp:o}=n.code,s=o(r,a);return e.scopeValue(`pattern`,{key:s.toString(),ref:s,code:(0,t._)`${o.code===`new RegExp`?h:(0,i.useFunc)(e,o)}(${r}, ${a})`})}e.usePattern=g;function _(e){let{gen:r,data:i,keyword:a,it:o}=e,s=r.name(`valid`);if(o.allErrors){let e=r.let(`valid`,!0);return c(()=>r.assign(e,!1)),e}return r.var(s,!0),c(()=>r.break()),s;function c(o){let c=r.const(`len`,(0,t._)`${i}.length`);r.forRange(`i`,0,c,i=>{e.subschema({keyword:a,dataProp:i,dataPropType:n.Type.Num},s),r.if((0,t.not)(s),o)})}}e.validateArray=_;function v(e){let{gen:r,schema:i,keyword:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(i.some(e=>(0,n.alwaysValidSchema)(o,e))&&!o.opts.unevaluated)return;let s=r.let(`valid`,!1),c=r.name(`_valid`);r.block(()=>i.forEach((n,i)=>{let o=e.subschema({keyword:a,schemaProp:i,compositeRule:!0},c);r.assign(s,(0,t._)`${s} || ${c}`),e.mergeValidEvaluated(o,c)||r.if((0,t.not)(s))})),e.result(s,()=>e.reset(),()=>e.error(!0))}e.validateUnion=v})),Jh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;let t=W(),n=Bh(),r=qh(),i=Vh();function a(e,n){let{gen:r,keyword:i,schema:a,parentSchema:o,it:s}=e,c=n.macro.call(s.self,a,o,s),l=u(r,i,c);s.opts.validateSchema!==!1&&s.self.validateSchema(c,!0);let d=r.name(`valid`);e.subschema({schema:c,schemaPath:t.nil,errSchemaPath:`${s.errSchemaPath}/${i}`,topSchemaRef:l,compositeRule:!0},d),e.pass(d,()=>e.error(!0))}e.macroKeywordCode=a;function o(e,i){let{gen:a,keyword:o,schema:d,parentSchema:f,$data:p,it:m}=e;l(m,i);let h=u(a,o,!p&&i.compile?i.compile.call(m.self,d,f,m):i.validate),g=a.let(`valid`);e.block$data(g,_),e.ok(i.valid??g);function _(){if(i.errors===!1)b(),i.modifying&&s(e),x(()=>e.error());else{let t=i.async?v():y();i.modifying&&s(e),x(()=>c(e,t))}}function v(){let e=a.let(`ruleErrs`,null);return a.try(()=>b((0,t._)`await `),n=>a.assign(g,!1).if((0,t._)`${n} instanceof ${m.ValidationError}`,()=>a.assign(e,(0,t._)`${n}.errors`),()=>a.throw(n))),e}function y(){let e=(0,t._)`${h}.errors`;return a.assign(e,null),b(t.nil),e}function b(o=i.async?(0,t._)`await `:t.nil){let s=m.opts.passContext?n.default.this:n.default.self,c=!(`compile`in i&&!p||i.schema===!1);a.assign(g,(0,t._)`${o}${(0,r.callValidateCode)(e,h,s,c)}`,i.modifying)}function x(e){a.if((0,t.not)(i.valid??g),e)}}e.funcKeywordCode=o;function s(e){let{gen:n,data:r,it:i}=e;n.if(i.parentData,()=>n.assign(r,(0,t._)`${i.parentData}[${i.parentDataProperty}]`))}function c(e,r){let{gen:a}=e;a.if((0,t._)`Array.isArray(${r})`,()=>{a.assign(n.default.vErrors,(0,t._)`${n.default.vErrors} === null ? ${r} : ${n.default.vErrors}.concat(${r})`).assign(n.default.errors,(0,t._)`${n.default.vErrors}.length`),(0,i.extendErrors)(e)},()=>e.error())}function l({schemaEnv:e},t){if(t.async&&!e.$async)throw Error(`async keyword in sync schema`)}function u(e,n,r){if(r===void 0)throw Error(`keyword "${n}" failed to compile`);return e.scopeValue(`keyword`,typeof r==`function`?{ref:r}:{ref:r,code:(0,t.stringify)(r)})}function d(e,t,n=!1){return!t.length||t.some(t=>t===`array`?Array.isArray(e):t===`object`?e&&typeof e==`object`&&!Array.isArray(e):typeof e==t||n&&e===void 0)}e.validSchemaType=d;function f({schema:e,opts:t,self:n,errSchemaPath:r},i,a){if(Array.isArray(i.keyword)?!i.keyword.includes(a):i.keyword!==a)throw Error(`ajv implementation error`);let o=i.dependencies;if(o?.some(t=>!Object.prototype.hasOwnProperty.call(e,t)))throw Error(`parent schema must have dependencies of ${a}: ${o.join(`,`)}`);if(i.validateSchema&&!i.validateSchema(e[a])){let e=`keyword "${a}" value is invalid at path "${r}": `+n.errorsText(i.validateSchema.errors);if(t.validateSchema===`log`)n.logger.error(e);else throw Error(e)}}e.validateKeywordUsage=f})),Yh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;let t=W(),n=G();function r(e,{keyword:r,schemaProp:i,schema:a,schemaPath:o,errSchemaPath:s,topSchemaRef:c}){if(r!==void 0&&a!==void 0)throw Error(`both "keyword" and "schema" passed, only one allowed`);if(r!==void 0){let a=e.schema[r];return i===void 0?{schema:a,schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}`,errSchemaPath:`${e.errSchemaPath}/${r}`}:{schema:a[i],schemaPath:(0,t._)`${e.schemaPath}${(0,t.getProperty)(r)}${(0,t.getProperty)(i)}`,errSchemaPath:`${e.errSchemaPath}/${r}/${(0,n.escapeFragment)(i)}`}}if(a!==void 0){if(o===void 0||s===void 0||c===void 0)throw Error(`"schemaPath", "errSchemaPath" and "topSchemaRef" are required with "schema"`);return{schema:a,schemaPath:o,topSchemaRef:c,errSchemaPath:s}}throw Error(`either "keyword" or "schema" must be passed`)}e.getSubschema=r;function i(e,r,{dataProp:i,dataPropType:a,data:o,dataTypes:s,propertyName:c}){if(o!==void 0&&i!==void 0)throw Error(`both "data" and "dataProp" passed, only one allowed`);let{gen:l}=r;if(i!==void 0){let{errorPath:o,dataPathArr:s,opts:c}=r;u(l.let(`data`,(0,t._)`${r.data}${(0,t.getProperty)(i)}`,!0)),e.errorPath=(0,t.str)`${o}${(0,n.getErrorPath)(i,a,c.jsPropertySyntax)}`,e.parentDataProperty=(0,t._)`${i}`,e.dataPathArr=[...s,e.parentDataProperty]}o!==void 0&&(u(o instanceof t.Name?o:l.let(`data`,o,!0)),c!==void 0&&(e.propertyName=c)),s&&(e.dataTypes=s);function u(t){e.data=t,e.dataLevel=r.dataLevel+1,e.dataTypes=[],r.definedProperties=new Set,e.parentData=r.data,e.dataNames=[...r.dataNames,t]}}e.extendSubschemaData=i;function a(e,{jtdDiscriminator:t,jtdMetadata:n,compositeRule:r,createErrors:i,allErrors:a}){r!==void 0&&(e.compositeRule=r),i!==void 0&&(e.createErrors=i),a!==void 0&&(e.allErrors=a),e.jtdDiscriminator=t,e.jtdMetadata=n}e.extendSubschemaMode=a})),Xh=B(((e,t)=>{t.exports=function e(t,n){if(t===n)return!0;if(t&&n&&typeof t==`object`&&typeof n==`object`){if(t.constructor!==n.constructor)return!1;var r,i,a;if(Array.isArray(t)){if(r=t.length,r!=n.length)return!1;for(i=r;i--!==0;)if(!e(t[i],n[i]))return!1;return!0}if(t.constructor===RegExp)return t.source===n.source&&t.flags===n.flags;if(t.valueOf!==Object.prototype.valueOf)return t.valueOf()===n.valueOf();if(t.toString!==Object.prototype.toString)return t.toString()===n.toString();if(a=Object.keys(t),r=a.length,r!==Object.keys(n).length)return!1;for(i=r;i--!==0;)if(!Object.prototype.hasOwnProperty.call(n,a[i]))return!1;for(i=r;i--!==0;){var o=a[i];if(!e(t[o],n[o]))return!1}return!0}return t!==t&&n!==n}})),Zh=B(((e,t)=>{var n=t.exports=function(e,t,n){typeof t==`function`&&(n=t,t={}),n=t.cb||n;var i=typeof n==`function`?n:n.pre||function(){},a=n.post||function(){};r(t,i,a,e,``,e)};n.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0,if:!0,then:!0,else:!0},n.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0},n.propsKeywords={$defs:!0,definitions:!0,properties:!0,patternProperties:!0,dependencies:!0},n.skipKeywords={default:!0,enum:!0,const:!0,required:!0,maximum:!0,minimum:!0,exclusiveMaximum:!0,exclusiveMinimum:!0,multipleOf:!0,maxLength:!0,minLength:!0,pattern:!0,format:!0,maxItems:!0,minItems:!0,uniqueItems:!0,maxProperties:!0,minProperties:!0};function r(e,t,a,o,s,c,l,u,d,f){if(o&&typeof o==`object`&&!Array.isArray(o)){for(var p in t(o,s,c,l,u,d,f),o){var m=o[p];if(Array.isArray(m)){if(p in n.arrayKeywords)for(var h=0;h<m.length;h++)r(e,t,a,m[h],s+`/`+p+`/`+h,c,s,p,o,h)}else if(p in n.propsKeywords){if(m&&typeof m==`object`)for(var g in m)r(e,t,a,m[g],s+`/`+p+`/`+i(g),c,s,p,o,g)}else(p in n.keywords||e.allKeys&&!(p in n.skipKeywords))&&r(e,t,a,m,s+`/`+p,c,s,p,o)}a(o,s,c,l,u,d,f)}}function i(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}})),Qh=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;let t=G(),n=Xh(),r=Zh(),i=new Set([`type`,`format`,`pattern`,`maxLength`,`minLength`,`maxProperties`,`minProperties`,`maxItems`,`minItems`,`maximum`,`minimum`,`uniqueItems`,`multipleOf`,`required`,`enum`,`const`]);function a(e,t=!0){return typeof e==`boolean`?!0:t===!0?!s(e):t?c(e)<=t:!1}e.inlineRef=a;let o=new Set([`$ref`,`$recursiveRef`,`$recursiveAnchor`,`$dynamicRef`,`$dynamicAnchor`]);function s(e){for(let t in e){if(o.has(t))return!0;let n=e[t];if(Array.isArray(n)&&n.some(s)||typeof n==`object`&&s(n))return!0}return!1}function c(e){let n=0;for(let r in e)if(r===`$ref`||(n++,!i.has(r)&&(typeof e[r]==`object`&&(0,t.eachItem)(e[r],e=>n+=c(e)),n===1/0)))return 1/0;return n}function l(e,t=``,n){return n!==!1&&(t=f(t)),u(e,e.parse(t))}e.getFullPath=l;function u(e,t){return e.serialize(t).split(`#`)[0]+`#`}e._getFullPath=u;let d=/#\/?$/;function f(e){return e?e.replace(d,``):``}e.normalizeId=f;function p(e,t,n){return n=f(n),e.resolve(t,n)}e.resolveUrl=p;let m=/^[a-z_][-a-z0-9._]*$/i;function h(e,t){if(typeof e==`boolean`)return{};let{schemaId:i,uriResolver:a}=this.opts,o=f(e[i]||t),s={"":o},c=l(a,o,!1),u={},d=new Set;return r(e,{allKeys:!0},(e,t,n,r)=>{if(r===void 0)return;let a=c+t,o=s[r];typeof e[i]==`string`&&(o=l.call(this,e[i])),g.call(this,e.$anchor),g.call(this,e.$dynamicAnchor),s[t]=o;function l(t){let n=this.opts.uriResolver.resolve;if(t=f(o?n(o,t):t),d.has(t))throw h(t);d.add(t);let r=this.refs[t];return typeof r==`string`&&(r=this.refs[r]),typeof r==`object`?p(e,r.schema,t):t!==f(a)&&(t[0]===`#`?(p(e,u[t],t),u[t]=e):this.refs[t]=a),t}function g(e){if(typeof e==`string`){if(!m.test(e))throw Error(`invalid anchor "${e}"`);l.call(this,`#${e}`)}}}),u;function p(e,t,r){if(t!==void 0&&!n(e,t))throw h(r)}function h(e){return Error(`reference "${e}" resolves to more than one schema`)}}e.getSchemaRefs=h})),$h=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=Hh(),n=Gh(),r=Wh(),i=Gh(),a=Kh(),o=Jh(),s=Yh(),c=W(),l=Bh(),u=Qh(),d=G(),f=Vh();function p(e){if(S(e)&&(w(e),x(e))){_(e);return}m(e,()=>(0,t.topBoolOrEmptySchema)(e))}e.validateFunctionCode=p;function m({gen:e,validateName:t,schema:n,schemaEnv:r,opts:i},a){i.code.es5?e.func(t,(0,c._)`${l.default.data}, ${l.default.valCxt}`,r.$async,()=>{e.code((0,c._)`"use strict"; ${y(n,i)}`),g(e,i),e.code(a)}):e.func(t,(0,c._)`${l.default.data}, ${h(i)}`,r.$async,()=>e.code(y(n,i)).code(a))}function h(e){return(0,c._)`{${l.default.instancePath}="", ${l.default.parentData}, ${l.default.parentDataProperty}, ${l.default.rootData}=${l.default.data}${e.dynamicRef?(0,c._)`, ${l.default.dynamicAnchors}={}`:c.nil}}={}`}function g(e,t){e.if(l.default.valCxt,()=>{e.var(l.default.instancePath,(0,c._)`${l.default.valCxt}.${l.default.instancePath}`),e.var(l.default.parentData,(0,c._)`${l.default.valCxt}.${l.default.parentData}`),e.var(l.default.parentDataProperty,(0,c._)`${l.default.valCxt}.${l.default.parentDataProperty}`),e.var(l.default.rootData,(0,c._)`${l.default.valCxt}.${l.default.rootData}`),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`${l.default.valCxt}.${l.default.dynamicAnchors}`)},()=>{e.var(l.default.instancePath,(0,c._)`""`),e.var(l.default.parentData,(0,c._)`undefined`),e.var(l.default.parentDataProperty,(0,c._)`undefined`),e.var(l.default.rootData,l.default.data),t.dynamicRef&&e.var(l.default.dynamicAnchors,(0,c._)`{}`)})}function _(e){let{schema:t,opts:n,gen:r}=e;m(e,()=>{n.$comment&&t.$comment&&k(e),E(e),r.let(l.default.vErrors,null),r.let(l.default.errors,0),n.unevaluated&&v(e),T(e),A(e)})}function v(e){let{gen:t,validateName:n}=e;e.evaluated=t.const(`evaluated`,(0,c._)`${n}.evaluated`),t.if((0,c._)`${e.evaluated}.dynamicProps`,()=>t.assign((0,c._)`${e.evaluated}.props`,(0,c._)`undefined`)),t.if((0,c._)`${e.evaluated}.dynamicItems`,()=>t.assign((0,c._)`${e.evaluated}.items`,(0,c._)`undefined`))}function y(e,t){let n=typeof e==`object`&&e[t.schemaId];return n&&(t.code.source||t.code.process)?(0,c._)`/*# sourceURL=${n} */`:c.nil}function b(e,n){if(S(e)&&(w(e),x(e))){C(e,n);return}(0,t.boolOrEmptySchema)(e,n)}function x({schema:e,self:t}){if(typeof e==`boolean`)return!e;for(let n in e)if(t.RULES.all[n])return!0;return!1}function S(e){return typeof e.schema!=`boolean`}function C(e,t){let{schema:n,gen:r,opts:i}=e;i.$comment&&n.$comment&&k(e),D(e),O(e);let a=r.const(`_errs`,l.default.errors);T(e,a),r.var(t,(0,c._)`${a} === ${l.default.errors}`)}function w(e){(0,d.checkUnknownRules)(e),ee(e)}function T(e,t){if(e.opts.jtd)return ne(e,[],!1,t);let r=(0,n.getSchemaTypes)(e.schema);ne(e,r,!(0,n.coerceAndCheckDataType)(e,r),t)}function ee(e){let{schema:t,errSchemaPath:n,opts:r,self:i}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function E(e){let{schema:t,opts:n}=e;t.default!==void 0&&n.useDefaults&&n.strictSchema&&(0,d.checkStrictMode)(e,`default is ignored in the schema root`)}function D(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function O(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error(`async schema in sync schema`)}function k({gen:e,schemaEnv:t,schema:n,errSchemaPath:r,opts:i}){let a=n.$comment;if(i.$comment===!0)e.code((0,c._)`${l.default.self}.logger.log(${a})`);else if(typeof i.$comment==`function`){let n=(0,c.str)`${r}/$comment`,i=e.scopeValue(`root`,{ref:t.root});e.code((0,c._)`${l.default.self}.opts.$comment(${a}, ${n}, ${i}.schema)`)}}function A(e){let{gen:t,schemaEnv:n,validateName:r,ValidationError:i,opts:a}=e;n.$async?t.if((0,c._)`${l.default.errors} === 0`,()=>t.return(l.default.data),()=>t.throw((0,c._)`new ${i}(${l.default.vErrors})`)):(t.assign((0,c._)`${r}.errors`,l.default.vErrors),a.unevaluated&&te(e),t.return((0,c._)`${l.default.errors} === 0`))}function te({gen:e,evaluated:t,props:n,items:r}){n instanceof c.Name&&e.assign((0,c._)`${t}.props`,n),r instanceof c.Name&&e.assign((0,c._)`${t}.items`,r)}function ne(e,t,n,a){let{gen:o,schema:s,data:u,allErrors:f,opts:p,self:m}=e,{RULES:h}=m;if(s.$ref&&(p.ignoreKeywordsWithRef||!(0,d.schemaHasRulesButRef)(s,h))){o.block(()=>ue(e,`$ref`,h.all.$ref.definition));return}p.jtd||M(e,t),o.block(()=>{for(let e of h.rules)g(e);g(h.post)});function g(d){(0,r.shouldUseGroup)(s,d)&&(d.type?(o.if((0,i.checkDataType)(d.type,u,p.strictNumbers)),j(e,d),t.length===1&&t[0]===d.type&&n&&(o.else(),(0,i.reportTypeError)(e)),o.endIf()):j(e,d),f||o.if((0,c._)`${l.default.errors} === ${a||0}`))}}function j(e,t){let{gen:n,schema:i,opts:{useDefaults:o}}=e;o&&(0,a.assignDefaults)(e,t.type),n.block(()=>{for(let n of t.rules)(0,r.shouldUseRule)(i,n)&&ue(e,n.keyword,n.definition,t.type)})}function M(e,t){e.schemaEnv.meta||!e.opts.strictTypes||(re(e,t),e.opts.allowUnionTypes||ie(e,t),ae(e,e.dataTypes))}function re(e,t){if(t.length){if(!e.dataTypes.length){e.dataTypes=t;return}t.forEach(t=>{se(e.dataTypes,t)||ce(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),N(e,t)}}function ie(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&ce(e,`use allowUnionTypes to allow union type keyword`)}function ae(e,t){let n=e.self.RULES.all;for(let i in n){let a=n[i];if(typeof a==`object`&&(0,r.shouldUseRule)(e.schema,a)){let{type:n}=a.definition;n.length&&!n.some(e=>oe(t,e))&&ce(e,`missing type "${n.join(`,`)}" for keyword "${i}"`)}}}function oe(e,t){return e.includes(t)||t===`number`&&e.includes(`integer`)}function se(e,t){return e.includes(t)||t===`integer`&&e.includes(`number`)}function N(e,t){let n=[];for(let r of e.dataTypes)se(t,r)?n.push(r):t.includes(`integer`)&&r===`number`&&n.push(`integer`);e.dataTypes=n}function ce(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}var le=class{constructor(e,t,n){if((0,o.validateKeywordUsage)(e,t,n),this.gen=e.gen,this.allErrors=e.allErrors,this.keyword=n,this.data=e.data,this.schema=e.schema[n],this.$data=t.$data&&e.opts.$data&&this.schema&&this.schema.$data,this.schemaValue=(0,d.schemaRefOrVal)(e,this.schema,n,this.$data),this.schemaType=t.schemaType,this.parentSchema=e.schema,this.params={},this.it=e,this.def=t,this.$data)this.schemaCode=e.gen.const(`vSchema`,pe(this.$data,e));else if(this.schemaCode=this.schemaValue,!(0,o.validSchemaType)(this.schema,t.schemaType,t.allowUndefined))throw Error(`${n} value must be ${JSON.stringify(t.schemaType)}`);(`code`in t?t.trackErrors:t.errors!==!1)&&(this.errsCount=e.gen.const(`_errs`,l.default.errors))}result(e,t,n){this.failResult((0,c.not)(e),t,n)}failResult(e,t,n){this.gen.if(e),n?n():this.error(),t?(this.gen.else(),t(),this.allErrors&&this.gen.endIf()):this.allErrors?this.gen.endIf():this.gen.else()}pass(e,t){this.failResult((0,c.not)(e),void 0,t)}fail(e){if(e===void 0){this.error(),this.allErrors||this.gen.if(!1);return}this.gen.if(e),this.error(),this.allErrors?this.gen.endIf():this.gen.else()}fail$data(e){if(!this.$data)return this.fail(e);let{schemaCode:t}=this;this.fail((0,c._)`${t} !== undefined && (${(0,c.or)(this.invalid$data(),e)})`)}error(e,t,n){if(t){this.setParams(t),this._error(e,n),this.setParams({});return}this._error(e,n)}_error(e,t){(e?f.reportExtraError:f.reportError)(this,this.def.error,t)}$dataError(){(0,f.reportError)(this,this.def.$dataError||f.keyword$DataError)}reset(){if(this.errsCount===void 0)throw Error(`add "trackErrors" to keyword definition`);(0,f.resetErrorsCount)(this.gen,this.errsCount)}ok(e){this.allErrors||this.gen.if(e)}setParams(e,t){t?Object.assign(this.params,e):this.params=e}block$data(e,t,n=c.nil){this.gen.block(()=>{this.check$data(e,n),t()})}check$data(e=c.nil,t=c.nil){if(!this.$data)return;let{gen:n,schemaCode:r,schemaType:i,def:a}=this;n.if((0,c.or)((0,c._)`${r} === undefined`,t)),e!==c.nil&&n.assign(e,!0),(i.length||a.validateSchema)&&(n.elseIf(this.invalid$data()),this.$dataError(),e!==c.nil&&n.assign(e,!1)),n.else()}invalid$data(){let{gen:e,schemaCode:t,schemaType:n,def:r,it:a}=this;return(0,c.or)(o(),s());function o(){if(n.length){if(!(t instanceof c.Name))throw Error(`ajv implementation error`);let e=Array.isArray(n)?n:[n];return(0,c._)`${(0,i.checkDataTypes)(e,t,a.opts.strictNumbers,i.DataType.Wrong)}`}return c.nil}function s(){if(r.validateSchema){let n=e.scopeValue(`validate$data`,{ref:r.validateSchema});return(0,c._)`!${n}(${t})`}return c.nil}}subschema(e,t){let n=(0,s.getSubschema)(this.it,e);(0,s.extendSubschemaData)(n,this.it,e),(0,s.extendSubschemaMode)(n,e);let r={...this.it,...n,items:void 0,props:void 0};return b(r,t),r}mergeEvaluated(e,t){let{it:n,gen:r}=this;n.opts.unevaluated&&(n.props!==!0&&e.props!==void 0&&(n.props=d.mergeEvaluated.props(r,e.props,n.props,t)),n.items!==!0&&e.items!==void 0&&(n.items=d.mergeEvaluated.items(r,e.items,n.items,t)))}mergeValidEvaluated(e,t){let{it:n,gen:r}=this;if(n.opts.unevaluated&&(n.props!==!0||n.items!==!0))return r.if(t,()=>this.mergeEvaluated(e,c.Name)),!0}};e.KeywordCxt=le;function ue(e,t,n,r){let i=new le(e,n,t);`code`in n?n.code(i,r):i.$data&&n.validate?(0,o.funcKeywordCode)(i,n):`macro`in n?(0,o.macroKeywordCode)(i,n):(n.compile||n.validate)&&(0,o.funcKeywordCode)(i,n)}let de=/^\/(?:[^~]|~0|~1)*$/,fe=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function pe(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let i,a;if(e===``)return l.default.rootData;if(e[0]===`/`){if(!de.test(e))throw Error(`Invalid JSON-pointer: ${e}`);i=e,a=l.default.rootData}else{let o=fe.exec(e);if(!o)throw Error(`Invalid JSON-pointer: ${e}`);let s=+o[1];if(i=o[2],i===`#`){if(s>=t)throw Error(u(`property/index`,s));return r[t-s]}if(s>t)throw Error(u(`data`,s));if(a=n[t-s],!i)return a}let o=a,s=i.split(`/`);for(let e of s)e&&(a=(0,c._)`${a}${(0,c.getProperty)((0,d.unescapeJsonPointer)(e))}`,o=(0,c._)`${o} && ${a}`);return o;function u(e,n){return`Cannot access ${e} ${n} levels up, current level is ${t}`}}e.getData=pe})),eg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=class extends Error{constructor(e){super(`validation failed`),this.errors=e,this.ajv=this.validation=!0}}})),tg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Qh();e.default=class extends Error{constructor(e,n,r,i){super(i||`can't resolve reference ${r} from id ${n}`),this.missingRef=(0,t.resolveUrl)(e,n,r),this.missingSchema=(0,t.normalizeId)((0,t.getFullPath)(e,this.missingRef))}}})),ng=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=W(),n=eg(),r=Bh(),i=Qh(),a=G(),o=$h();var s=class{constructor(e){this.refs={},this.dynamicAnchors={};let t;typeof e.schema==`object`&&(t=e.schema),this.schema=e.schema,this.schemaId=e.schemaId,this.root=e.root||this,this.baseId=e.baseId??(0,i.normalizeId)(t?.[e.schemaId||`$id`]),this.schemaPath=e.schemaPath,this.localRefs=e.localRefs,this.meta=e.meta,this.$async=t?.$async,this.refs={}}};e.SchemaEnv=s;function c(e){let a=d.call(this,e);if(a)return a;let s=(0,i.getFullPath)(this.opts.uriResolver,e.root.baseId),{es5:c,lines:l}=this.opts.code,{ownProperties:u}=this.opts,f=new t.CodeGen(this.scope,{es5:c,lines:l,ownProperties:u}),p;e.$async&&(p=f.scopeValue(`Error`,{ref:n.default,code:(0,t._)`require("ajv/dist/runtime/validation_error").default`}));let m=f.scopeName(`validate`);e.validateName=m;let h={gen:f,allErrors:this.opts.allErrors,data:r.default.data,parentData:r.default.parentData,parentDataProperty:r.default.parentDataProperty,dataNames:[r.default.data],dataPathArr:[t.nil],dataLevel:0,dataTypes:[],definedProperties:new Set,topSchemaRef:f.scopeValue(`schema`,this.opts.code.source===!0?{ref:e.schema,code:(0,t.stringify)(e.schema)}:{ref:e.schema}),validateName:m,ValidationError:p,schema:e.schema,schemaEnv:e,rootId:s,baseId:e.baseId||s,schemaPath:t.nil,errSchemaPath:e.schemaPath||(this.opts.jtd?``:`#`),errorPath:(0,t._)`""`,opts:this.opts,self:this},g;try{this._compilations.add(e),(0,o.validateFunctionCode)(h),f.optimize(this.opts.code.optimize);let n=f.toString();g=`${f.scopeRefs(r.default.scope)}return ${n}`,this.opts.code.process&&(g=this.opts.code.process(g,e));let i=Function(`${r.default.self}`,`${r.default.scope}`,g)(this,this.scope.get());if(this.scope.value(m,{ref:i}),i.errors=null,i.schema=e.schema,i.schemaEnv=e,e.$async&&(i.$async=!0),this.opts.code.source===!0&&(i.source={validateName:m,validateCode:n,scopeValues:f._values}),this.opts.unevaluated){let{props:e,items:n}=h;i.evaluated={props:e instanceof t.Name?void 0:e,items:n instanceof t.Name?void 0:n,dynamicProps:e instanceof t.Name,dynamicItems:n instanceof t.Name},i.source&&(i.source.evaluated=(0,t.stringify)(i.evaluated))}return e.validate=i,e}catch(t){throw delete e.validate,delete e.validateName,g&&this.logger.error(`Error compiling schema, function code:`,g),t}finally{this._compilations.delete(e)}}e.compileSchema=c;function l(e,t,n){n=(0,i.resolveUrl)(this.opts.uriResolver,t,n);let r=e.refs[n];if(r)return r;let a=p.call(this,e,n);if(a===void 0){let r=e.localRefs?.[n],{schemaId:i}=this.opts;r&&(a=new s({schema:r,schemaId:i,root:e,baseId:t}))}if(a!==void 0)return e.refs[n]=u.call(this,a)}e.resolveRef=l;function u(e){return(0,i.inlineRef)(e.schema,this.opts.inlineRefs)?e.schema:e.validate?e:c.call(this,e)}function d(e){for(let t of this._compilations)if(f(t,e))return t}e.getCompilingSchema=d;function f(e,t){return e.schema===t.schema&&e.root===t.root&&e.baseId===t.baseId}function p(e,t){let n;for(;typeof(n=this.refs[t])==`string`;)t=n;return n||this.schemas[t]||m.call(this,e,t)}function m(e,t){let n=this.opts.uriResolver.parse(t),r=(0,i._getFullPath)(this.opts.uriResolver,n),a=(0,i.getFullPath)(this.opts.uriResolver,e.baseId,void 0);if(Object.keys(e.schema).length>0&&r===a)return g.call(this,n,e);let o=(0,i.normalizeId)(r),l=this.refs[o]||this.schemas[o];if(typeof l==`string`){let t=m.call(this,e,l);return typeof t?.schema==`object`?g.call(this,n,t):void 0}if(typeof l?.schema==`object`){if(l.validate||c.call(this,l),o===(0,i.normalizeId)(t)){let{schema:t}=l,{schemaId:n}=this.opts,r=t[n];return r&&(a=(0,i.resolveUrl)(this.opts.uriResolver,a,r)),new s({schema:t,schemaId:n,root:e,baseId:a})}return g.call(this,n,l)}}e.resolveSchema=m;let h=new Set([`properties`,`patternProperties`,`enum`,`dependencies`,`definitions`]);function g(e,{baseId:t,schema:n,root:r}){if(e.fragment?.[0]!==`/`)return;for(let r of e.fragment.slice(1).split(`/`)){if(typeof n==`boolean`)return;let e=n[(0,a.unescapeFragment)(r)];if(e===void 0)return;n=e;let o=typeof n==`object`&&n[this.opts.schemaId];!h.has(r)&&o&&(t=(0,i.resolveUrl)(this.opts.uriResolver,t,o))}let o;if(typeof n!=`boolean`&&n.$ref&&!(0,a.schemaHasRulesButRef)(n,this.RULES)){let e=(0,i.resolveUrl)(this.opts.uriResolver,t,n.$ref);o=m.call(this,r,e)}let{schemaId:c}=this.opts;if(o||=new s({schema:n,schemaId:c,root:r,baseId:t}),o.schema!==o.root.schema)return o}})),rg=B(((e,t)=>{t.exports={$id:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`,description:`Meta-schema for $data reference (JSON AnySchema extension proposal)`,type:`object`,required:[`$data`],properties:{$data:{type:`string`,anyOf:[{format:`relative-json-pointer`},{format:`json-pointer`}]}},additionalProperties:!1}})),ig=B(((e,t)=>{let n=RegExp.prototype.test.bind(/^[\da-f]{8}-[\da-f]{4}-[\da-f]{4}-[\da-f]{4}-[\da-f]{12}$/iu),r=RegExp.prototype.test.bind(/^(?:(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d{2}|[1-9]\d|\d)$/u);function i(e){let t=``,n=0,r=0;for(r=0;r<e.length;r++)if(n=e[r].charCodeAt(0),n!==48){if(!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r];break}for(r+=1;r<e.length;r++){if(n=e[r].charCodeAt(0),!(n>=48&&n<=57||n>=65&&n<=70||n>=97&&n<=102))return``;t+=e[r]}return t}let a=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function o(e){return e.length=0,!0}function s(e,t,n){if(e.length){let r=i(e);if(r!==``)t.push(r);else return n.error=!0,!1;e.length=0}return!0}function c(e){let t=0,n={error:!1,address:``,zone:``},r=[],a=[],c=!1,l=!1,u=s;for(let i=0;i<e.length;i++){let s=e[i];if(s!==`[`&&s!==`]`){if(s===`:`){if(c===!0&&(l=!0),!u(a,r,n))break;if(++t>7){n.error=!0;break}i>0&&e[i-1]===`:`&&(c=!0),r.push(`:`);continue}if(s===`%`){if(!u(a,r,n))break;u=o}else{a.push(s);continue}}}return a.length&&(u===o?n.zone=a.join(``):l?r.push(a.join(``)):r.push(i(a))),n.address=r.join(``),n}function l(e){if(u(e,`:`)<2)return{host:e,isIPV6:!1};let t=c(e);if(t.error)return{host:e,isIPV6:!1};{let e=t.address,n=t.address;return t.zone&&(e+=`%`+t.zone,n+=`%25`+t.zone),{host:e,isIPV6:!0,escapedHost:n}}}function u(e,t){let n=0;for(let r=0;r<e.length;r++)e[r]===t&&n++;return n}function d(e){let t=e,n=[],r=-1,i=0;for(;i=t.length;){if(i===1){if(t===`.`)break;if(t===`/`){n.push(`/`);break}n.push(t);break}if(i===2){if(t[0]===`.`){if(t[1]===`.`)break;if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&(t[1]===`.`||t[1]===`/`)){n.push(`/`);break}}else if(i===3&&t===`/..`){n.length!==0&&n.pop(),n.push(`/`);break}if(t[0]===`.`){if(t[1]===`.`){if(t[2]===`/`){t=t.slice(3);continue}}else if(t[1]===`/`){t=t.slice(2);continue}}else if(t[0]===`/`&&t[1]===`.`){if(t[2]===`/`){t=t.slice(2);continue}if(t[2]===`.`&&t[3]===`/`){t=t.slice(3),n.length!==0&&n.pop();continue}}if((r=t.indexOf(`/`,1))===-1){n.push(t);break}n.push(t.slice(0,r)),t=t.slice(r)}return n.join(``)}function f(e,t){let n=t===!0?unescape:escape;return e.scheme!==void 0&&(e.scheme=n(e.scheme)),e.userinfo!==void 0&&(e.userinfo=n(e.userinfo)),e.host!==void 0&&(e.host=n(e.host)),e.path!==void 0&&(e.path=n(e.path)),e.query!==void 0&&(e.query=n(e.query)),e.fragment!==void 0&&(e.fragment=n(e.fragment)),e}function p(e){let t=[];if(e.userinfo!==void 0&&(t.push(e.userinfo),t.push(`@`)),e.host!==void 0){let n=unescape(e.host);if(!r(n)){let t=l(n);n=t.isIPV6===!0?`[${t.escapedHost}]`:e.host}t.push(n)}return(typeof e.port==`number`||typeof e.port==`string`)&&(t.push(`:`),t.push(String(e.port))),t.length?t.join(``):void 0}t.exports={nonSimpleDomain:a,recomposeAuthority:p,normalizeComponentEncoding:f,removeDotSegments:d,isIPv4:r,isUUID:n,normalizeIPv6:l,stringArrayToHexStripped:i}})),ag=B(((e,t)=>{let{isUUID:n}=ig(),r=/([\da-z][\d\-a-z]{0,31}):((?:[\w!$'()*+,\-.:;=@]|%[\da-f]{2})+)/iu,i=[`http`,`https`,`ws`,`wss`,`urn`,`urn:uuid`];function a(e){return i.indexOf(e)!==-1}function o(e){return e.secure===!0?!0:e.secure===!1?!1:e.scheme?e.scheme.length===3&&(e.scheme[0]===`w`||e.scheme[0]===`W`)&&(e.scheme[1]===`s`||e.scheme[1]===`S`)&&(e.scheme[2]===`s`||e.scheme[2]===`S`):!1}function s(e){return e.host||(e.error=e.error||`HTTP URIs must have a host.`),e}function c(e){let t=String(e.scheme).toLowerCase()===`https`;return(e.port===(t?443:80)||e.port===``)&&(e.port=void 0),e.path||=`/`,e}function l(e){return e.secure=o(e),e.resourceName=(e.path||`/`)+(e.query?`?`+e.query:``),e.path=void 0,e.query=void 0,e}function u(e){if((e.port===(o(e)?443:80)||e.port===``)&&(e.port=void 0),typeof e.secure==`boolean`&&(e.scheme=e.secure?`wss`:`ws`,e.secure=void 0),e.resourceName){let[t,n]=e.resourceName.split(`?`);e.path=t&&t!==`/`?t:void 0,e.query=n,e.resourceName=void 0}return e.fragment=void 0,e}function d(e,t){if(!e.path)return e.error=`URN can not be parsed`,e;let n=e.path.match(r);if(n){let r=t.scheme||e.scheme||`urn`;e.nid=n[1].toLowerCase(),e.nss=n[2];let i=y(`${r}:${t.nid||e.nid}`);e.path=void 0,i&&(e=i.parse(e,t))}else e.error=e.error||`URN can not be parsed.`;return e}function f(e,t){if(e.nid===void 0)throw Error(`URN without nid cannot be serialized`);let n=t.scheme||e.scheme||`urn`,r=e.nid.toLowerCase(),i=y(`${n}:${t.nid||r}`);i&&(e=i.serialize(e,t));let a=e,o=e.nss;return a.path=`${r||t.nid}:${o}`,t.skipEscape=!0,a}function p(e,t){let r=e;return r.uuid=r.nss,r.nss=void 0,!t.tolerant&&(!r.uuid||!n(r.uuid))&&(r.error=r.error||`UUID is not valid.`),r}function m(e){let t=e;return t.nss=(e.uuid||``).toLowerCase(),t}let h={scheme:`http`,domainHost:!0,parse:s,serialize:c},g={scheme:`https`,domainHost:h.domainHost,parse:s,serialize:c},_={scheme:`ws`,domainHost:!0,parse:l,serialize:u},v={http:h,https:g,ws:_,wss:{scheme:`wss`,domainHost:_.domainHost,parse:_.parse,serialize:_.serialize},urn:{scheme:`urn`,parse:d,serialize:f,skipNormalize:!0},"urn:uuid":{scheme:`urn:uuid`,parse:p,serialize:m,skipNormalize:!0}};Object.setPrototypeOf(v,null);function y(e){return e&&(v[e]||v[e.toLowerCase()])||void 0}t.exports={wsIsSecure:o,SCHEMES:v,isValidSchemeName:a,getSchemeHandler:y}})),og=B(((e,t)=>{let{normalizeIPv6:n,removeDotSegments:r,recomposeAuthority:i,normalizeComponentEncoding:a,isIPv4:o,nonSimpleDomain:s}=ig(),{SCHEMES:c,getSchemeHandler:l}=ag();function u(e,t){return typeof e==`string`?e=m(g(e,t),t):typeof e==`object`&&(e=g(m(e,t),t)),e}function d(e,t,n){let r=n?Object.assign({scheme:`null`},n):{scheme:`null`},i=f(g(e,r),g(t,r),r,!0);return r.skipEscape=!0,m(i,r)}function f(e,t,n,i){let a={};return i||(e=g(m(e,n),n),t=g(m(t,n),n)),n||={},!n.tolerant&&t.scheme?(a.scheme=t.scheme,a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0?(a.userinfo=t.userinfo,a.host=t.host,a.port=t.port,a.path=r(t.path||``),a.query=t.query):(t.path?(t.path[0]===`/`?a.path=r(t.path):(a.path=(e.userinfo!==void 0||e.host!==void 0||e.port!==void 0)&&!e.path?`/`+t.path:e.path?e.path.slice(0,e.path.lastIndexOf(`/`)+1)+t.path:t.path,a.path=r(a.path)),a.query=t.query):(a.path=e.path,a.query=t.query===void 0?e.query:t.query),a.userinfo=e.userinfo,a.host=e.host,a.port=e.port),a.scheme=e.scheme),a.fragment=t.fragment,a}function p(e,t,n){return typeof e==`string`?(e=unescape(e),e=m(a(g(e,n),!0),{...n,skipEscape:!0})):typeof e==`object`&&(e=m(a(e,!0),{...n,skipEscape:!0})),typeof t==`string`?(t=unescape(t),t=m(a(g(t,n),!0),{...n,skipEscape:!0})):typeof t==`object`&&(t=m(a(t,!0),{...n,skipEscape:!0})),e.toLowerCase()===t.toLowerCase()}function m(e,t){let n={host:e.host,scheme:e.scheme,userinfo:e.userinfo,port:e.port,path:e.path,query:e.query,nid:e.nid,nss:e.nss,uuid:e.uuid,fragment:e.fragment,reference:e.reference,resourceName:e.resourceName,secure:e.secure,error:``},a=Object.assign({},t),o=[],s=l(a.scheme||n.scheme);s&&s.serialize&&s.serialize(n,a),n.path!==void 0&&(a.skipEscape?n.path=unescape(n.path):(n.path=escape(n.path),n.scheme!==void 0&&(n.path=n.path.split(`%3A`).join(`:`)))),a.reference!==`suffix`&&n.scheme&&o.push(n.scheme,`:`);let c=i(n);if(c!==void 0&&(a.reference!==`suffix`&&o.push(`//`),o.push(c),n.path&&n.path[0]!==`/`&&o.push(`/`)),n.path!==void 0){let e=n.path;!a.absolutePath&&(!s||!s.absolutePath)&&(e=r(e)),c===void 0&&e[0]===`/`&&e[1]===`/`&&(e=`/%2F`+e.slice(2)),o.push(e)}return n.query!==void 0&&o.push(`?`,n.query),n.fragment!==void 0&&o.push(`#`,n.fragment),o.join(``)}let h=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u;function g(e,t){let r=Object.assign({},t),i={scheme:void 0,userinfo:void 0,host:``,port:void 0,path:``,query:void 0,fragment:void 0},a=!1;r.reference===`suffix`&&(e=r.scheme?r.scheme+`:`+e:`//`+e);let c=e.match(h);if(c){if(i.scheme=c[1],i.userinfo=c[3],i.host=c[4],i.port=parseInt(c[5],10),i.path=c[6]||``,i.query=c[7],i.fragment=c[8],isNaN(i.port)&&(i.port=c[5]),i.host){if(o(i.host)===!1){let e=n(i.host);i.host=e.host.toLowerCase(),a=e.isIPV6}else a=!0}i.reference=i.scheme===void 0&&i.userinfo===void 0&&i.host===void 0&&i.port===void 0&&i.query===void 0&&!i.path?`same-document`:i.scheme===void 0?`relative`:i.fragment===void 0?`absolute`:`uri`,r.reference&&r.reference!==`suffix`&&r.reference!==i.reference&&(i.error=i.error||`URI is not a `+r.reference+` reference.`);let t=l(r.scheme||i.scheme);if(!r.unicodeSupport&&(!t||!t.unicodeSupport)&&i.host&&(r.domainHost||t&&t.domainHost)&&a===!1&&s(i.host))try{i.host=URL.domainToASCII(i.host.toLowerCase())}catch(e){i.error=i.error||`Host's domain name can not be converted to ASCII: `+e}(!t||t&&!t.skipNormalize)&&(e.indexOf(`%`)!==-1&&(i.scheme!==void 0&&(i.scheme=unescape(i.scheme)),i.host!==void 0&&(i.host=unescape(i.host))),i.path&&=escape(unescape(i.path)),i.fragment&&=encodeURI(decodeURIComponent(i.fragment))),t&&t.parse&&t.parse(i,r)}else i.error=i.error||`URI can not be parsed.`;return i}let _={SCHEMES:c,normalize:u,resolve:d,resolveComponent:f,equal:p,serialize:m,parse:g};t.exports=_,t.exports.default=_,t.exports.fastUri=_})),sg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=og();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),cg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=$h();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var n=W();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return n._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return n.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return n.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return n.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return n.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return n.CodeGen}});let r=eg(),i=tg(),a=Uh(),o=ng(),s=W(),c=Qh(),l=Gh(),u=G(),d=rg(),f=sg(),p=(e,t)=>new RegExp(e,t);p.code=`new RegExp`;let m=[`removeAdditional`,`useDefaults`,`coerceTypes`],h=new Set([`validate`,`serialize`,`parse`,`wrapper`,`root`,`schema`,`keyword`,`pattern`,`formats`,`validate$data`,`func`,`obj`,`Error`]),g={errorDataPath:``,format:"`validateFormats: false` can be used instead.",nullable:`"nullable" keyword is supported by default.`,jsonPointers:`Deprecated jsPropertySyntax can be used instead.`,extendRefs:`Deprecated ignoreKeywordsWithRef can be used instead.`,missingRefs:`Pass empty schema with $id that should be ignored to ajv.addSchema.`,processCode:"Use option `code: {process: (code, schemaEnv: object) => string}`",sourceCode:"Use option `code: {source: true}`",strictDefaults:"It is default now, see option `strict`.",strictKeywords:"It is default now, see option `strict`.",uniqueItems:`"uniqueItems" keyword is always validated.`,unknownFormats:"Disable strict mode or pass `true` to `ajv.addFormat` (or `formats` option).",cache:`Map is used as cache, schema object as key.`,serialize:`Map is used as cache, schema object as key.`,ajvErrors:`It is default now.`},_={ignoreKeywordsWithRef:``,jsPropertySyntax:``,unicode:`"minLength"/"maxLength" account for unicode characters by default.`};function v(e){let t=e.strict,n=e.code?.optimize,r=n===!0||n===void 0?1:n||0,i=e.code?.regExp??p,a=e.uriResolver??f.default;return{strictSchema:e.strictSchema??t??!0,strictNumbers:e.strictNumbers??t??!0,strictTypes:e.strictTypes??t??`log`,strictTuples:e.strictTuples??t??`log`,strictRequired:e.strictRequired??t??!1,code:e.code?{...e.code,optimize:r,regExp:i}:{optimize:r,regExp:i},loopRequired:e.loopRequired??200,loopEnum:e.loopEnum??200,meta:e.meta??!0,messages:e.messages??!0,inlineRefs:e.inlineRefs??!0,schemaId:e.schemaId??`$id`,addUsedSchema:e.addUsedSchema??!0,validateSchema:e.validateSchema??!0,validateFormats:e.validateFormats??!0,unicodeRegExp:e.unicodeRegExp??!0,int32range:e.int32range??!0,uriResolver:a}}var y=class{constructor(e={}){this.schemas={},this.refs={},this.formats={},this._compilations=new Set,this._loading={},this._cache=new Map,e=this.opts={...e,...v(e)};let{es5:t,lines:n}=this.opts.code;this.scope=new s.ValueScope({scope:{},prefixes:h,es5:t,lines:n}),this.logger=E(e.logger);let r=e.validateFormats;e.validateFormats=!1,this.RULES=(0,a.getRules)(),b.call(this,g,e,`NOT SUPPORTED`),b.call(this,_,e,`DEPRECATED`,`warn`),this._metaOpts=T.call(this),e.formats&&C.call(this),this._addVocabularies(),this._addDefaultMetaSchema(),e.keywords&&w.call(this,e.keywords),typeof e.meta==`object`&&this.addMetaSchema(e.meta),S.call(this),e.validateFormats=r}_addVocabularies(){this.addKeyword(`$async`)}_addDefaultMetaSchema(){let{$data:e,meta:t,schemaId:n}=this.opts,r=d;n===`id`&&(r={...d},r.id=r.$id,delete r.$id),t&&e&&this.addMetaSchema(r,r[n],!1)}defaultMeta(){let{meta:e,schemaId:t}=this.opts;return this.opts.defaultMeta=typeof e==`object`?e[t]||e:void 0}validate(e,t){let n;if(typeof e==`string`){if(n=this.getSchema(e),!n)throw Error(`no schema with key or ref "${e}"`)}else n=this.compile(e);let r=n(t);return`$async`in n||(this.errors=n.errors),r}compile(e,t){let n=this._addSchema(e,t);return n.validate||this._compileSchemaEnv(n)}compileAsync(e,t){if(typeof this.opts.loadSchema!=`function`)throw Error(`options.loadSchema should be a function`);let{loadSchema:n}=this.opts;return r.call(this,e,t);async function r(e,t){await a.call(this,e.$schema);let n=this._addSchema(e,t);return n.validate||o.call(this,n)}async function a(e){e&&!this.getSchema(e)&&await r.call(this,{$ref:e},!0)}async function o(e){try{return this._compileSchemaEnv(e)}catch(t){if(!(t instanceof i.default))throw t;return s.call(this,t),await c.call(this,t.missingSchema),o.call(this,e)}}function s({missingSchema:e,missingRef:t}){if(this.refs[e])throw Error(`AnySchema ${e} is loaded but ${t} cannot be resolved`)}async function c(e){let n=await l.call(this,e);this.refs[e]||await a.call(this,n.$schema),this.refs[e]||this.addSchema(n,e,t)}async function l(e){let t=this._loading[e];if(t)return t;try{return await(this._loading[e]=n(e))}finally{delete this._loading[e]}}}addSchema(e,t,n,r=this.opts.validateSchema){if(Array.isArray(e)){for(let t of e)this.addSchema(t,void 0,n,r);return this}let i;if(typeof e==`object`){let{schemaId:t}=this.opts;if(i=e[t],i!==void 0&&typeof i!=`string`)throw Error(`schema ${t} must be string`)}return t=(0,c.normalizeId)(t||i),this._checkUnique(t),this.schemas[t]=this._addSchema(e,n,t,r,!0),this}addMetaSchema(e,t,n=this.opts.validateSchema){return this.addSchema(e,t,!0,n),this}validateSchema(e,t){if(typeof e==`boolean`)return!0;let n;if(n=e.$schema,n!==void 0&&typeof n!=`string`)throw Error(`$schema must be a string`);if(n=n||this.opts.defaultMeta||this.defaultMeta(),!n)return this.logger.warn(`meta-schema not available`),this.errors=null,!0;let r=this.validate(n,e);if(!r&&t){let e=`schema is invalid: `+this.errorsText();if(this.opts.validateSchema===`log`)this.logger.error(e);else throw Error(e)}return r}getSchema(e){let t;for(;typeof(t=x.call(this,e))==`string`;)e=t;if(t===void 0){let{schemaId:n}=this.opts,r=new o.SchemaEnv({schema:{},schemaId:n});if(t=o.resolveSchema.call(this,r,e),!t)return;this.refs[e]=t}return t.validate||this._compileSchemaEnv(t)}removeSchema(e){if(e instanceof RegExp)return this._removeAllSchemas(this.schemas,e),this._removeAllSchemas(this.refs,e),this;switch(typeof e){case`undefined`:return this._removeAllSchemas(this.schemas),this._removeAllSchemas(this.refs),this._cache.clear(),this;case`string`:{let t=x.call(this,e);return typeof t==`object`&&this._cache.delete(t.schema),delete this.schemas[e],delete this.refs[e],this}case`object`:{let t=e;this._cache.delete(t);let n=e[this.opts.schemaId];return n&&(n=(0,c.normalizeId)(n),delete this.schemas[n],delete this.refs[n]),this}default:throw Error(`ajv.removeSchema: invalid parameter`)}}addVocabulary(e){for(let t of e)this.addKeyword(t);return this}addKeyword(e,t){let n;if(typeof e==`string`)n=e,typeof t==`object`&&(this.logger.warn(`these parameters are deprecated, see docs for addKeyword`),t.keyword=n);else if(typeof e==`object`&&t===void 0){if(t=e,n=t.keyword,Array.isArray(n)&&!n.length)throw Error(`addKeywords: keyword must be string or non-empty array`)}else throw Error(`invalid addKeywords parameters`);if(O.call(this,n,t),!t)return(0,u.eachItem)(n,e=>k.call(this,e)),this;te.call(this,t);let r={...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)};return(0,u.eachItem)(n,r.type.length===0?e=>k.call(this,e,r):e=>r.type.forEach(t=>k.call(this,e,r,t))),this}getKeyword(e){let t=this.RULES.all[e];return typeof t==`object`?t.definition:!!t}removeKeyword(e){let{RULES:t}=this;delete t.keywords[e],delete t.all[e];for(let n of t.rules){let t=n.rules.findIndex(t=>t.keyword===e);t>=0&&n.rules.splice(t,1)}return this}addFormat(e,t){return typeof t==`string`&&(t=new RegExp(t)),this.formats[e]=t,this}errorsText(e=this.errors,{separator:t=`, `,dataVar:n=`data`}={}){return!e||e.length===0?`No errors`:e.map(e=>`${n}${e.instancePath} ${e.message}`).reduce((e,n)=>e+t+n)}$dataMetaSchema(e,t){let n=this.RULES.all;e=JSON.parse(JSON.stringify(e));for(let r of t){let t=r.split(`/`).slice(1),i=e;for(let e of t)i=i[e];for(let e in n){let t=n[e];if(typeof t!=`object`)continue;let{$data:r}=t.definition,a=i[e];r&&a&&(i[e]=j(a))}}return e}_removeAllSchemas(e,t){for(let n in e){let r=e[n];(!t||t.test(n))&&(typeof r==`string`?delete e[n]:r&&!r.meta&&(this._cache.delete(r.schema),delete e[n]))}}_addSchema(e,t,n,r=this.opts.validateSchema,i=this.opts.addUsedSchema){let a,{schemaId:s}=this.opts;if(typeof e==`object`)a=e[s];else if(this.opts.jtd)throw Error(`schema must be object`);else if(typeof e!=`boolean`)throw Error(`schema must be object or boolean`);let l=this._cache.get(e);if(l!==void 0)return l;n=(0,c.normalizeId)(a||n);let u=c.getSchemaRefs.call(this,e,n);return l=new o.SchemaEnv({schema:e,schemaId:s,meta:t,baseId:n,localRefs:u}),this._cache.set(l.schema,l),i&&!n.startsWith(`#`)&&(n&&this._checkUnique(n),this.refs[n]=l),r&&this.validateSchema(e,!0),l}_checkUnique(e){if(this.schemas[e]||this.refs[e])throw Error(`schema with key or id "${e}" already exists`)}_compileSchemaEnv(e){if(e.meta?this._compileMetaSchema(e):o.compileSchema.call(this,e),!e.validate)throw Error(`ajv implementation error`);return e.validate}_compileMetaSchema(e){let t=this.opts;this.opts=this._metaOpts;try{o.compileSchema.call(this,e)}finally{this.opts=t}}};y.ValidationError=r.default,y.MissingRefError=i.default,e.default=y;function b(e,t,n,r=`error`){for(let i in e){let a=i;a in t&&this.logger[r](`${n}: option ${i}. ${e[a]}`)}}function x(e){return e=(0,c.normalizeId)(e),this.schemas[e]||this.refs[e]}function S(){let e=this.opts.schemas;if(e){if(Array.isArray(e))this.addSchema(e);else for(let t in e)this.addSchema(e[t],t)}}function C(){for(let e in this.opts.formats){let t=this.opts.formats[e];t&&this.addFormat(e,t)}}function w(e){if(Array.isArray(e)){this.addVocabulary(e);return}this.logger.warn(`keywords option as map is deprecated, pass array`);for(let t in e){let n=e[t];n.keyword||=t,this.addKeyword(n)}}function T(){let e={...this.opts};for(let t of m)delete e[t];return e}let ee={log(){},warn(){},error(){}};function E(e){if(e===!1)return ee;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error(`logger must implement log, warn and error methods`)}let D=/^[a-z_$][a-z0-9_$:-]*$/i;function O(e,t){let{RULES:n}=this;if((0,u.eachItem)(e,e=>{if(n.keywords[e])throw Error(`Keyword ${e} is already defined`);if(!D.test(e))throw Error(`Keyword ${e} has invalid name`)}),t&&t.$data&&!(`code`in t||`validate`in t))throw Error(`$data keyword must have "code" or "validate" function`)}function k(e,t,n){var r;let i=t?.post;if(n&&i)throw Error(`keyword with "post" flag cannot have "type"`);let{RULES:a}=this,o=i?a.post:a.rules.find(({type:e})=>e===n);if(o||(o={type:n,rules:[]},a.rules.push(o)),a.keywords[e]=!0,!t)return;let s={keyword:e,definition:{...t,type:(0,l.getJSONTypes)(t.type),schemaType:(0,l.getJSONTypes)(t.schemaType)}};t.before?A.call(this,o,s,t.before):o.rules.push(s),a.all[e]=s,(r=t.implements)==null||r.forEach(e=>this.addKeyword(e))}function A(e,t,n){let r=e.rules.findIndex(e=>e.keyword===n);r>=0?e.rules.splice(r,0,t):(e.rules.push(t),this.logger.warn(`rule ${n} is not defined`))}function te(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=j(t)),e.validateSchema=this.compile(t,!0))}let ne={$ref:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`};function j(e){return{anyOf:[e,ne]}}})),lg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),ug=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.callRef=e.getValidate=void 0;let t=tg(),n=qh(),r=W(),i=Bh(),a=ng(),o=G(),s={keyword:`$ref`,schemaType:`string`,code(e){let{gen:n,schema:i,it:o}=e,{baseId:s,schemaEnv:u,validateName:d,opts:f,self:p}=o,{root:m}=u;if((i===`#`||i===`#/`)&&s===m.baseId)return g();let h=a.resolveRef.call(p,m,s,i);if(h===void 0)throw new t.default(o.opts.uriResolver,s,i);if(h instanceof a.SchemaEnv)return _(h);return v(h);function g(){if(u===m)return l(e,d,u,u.$async);let t=n.scopeValue(`root`,{ref:m});return l(e,(0,r._)`${t}.validate`,m,m.$async)}function _(t){l(e,c(e,t),t,t.$async)}function v(t){let a=n.scopeValue(`schema`,f.code.source===!0?{ref:t,code:(0,r.stringify)(t)}:{ref:t}),o=n.name(`valid`),s=e.subschema({schema:t,dataTypes:[],schemaPath:r.nil,topSchemaRef:a,errSchemaPath:i},o);e.mergeEvaluated(s),e.ok(o)}}};function c(e,t){let{gen:n}=e;return t.validate?n.scopeValue(`validate`,{ref:t.validate}):(0,r._)`${n.scopeValue(`wrapper`,{ref:t})}.validate`}e.getValidate=c;function l(e,t,a,s){let{gen:c,it:l}=e,{allErrors:u,schemaEnv:d,opts:f}=l,p=f.passContext?i.default.this:r.nil;s?m():h();function m(){if(!d.$async)throw Error(`async schema referenced by sync schema`);let i=c.let(`valid`);c.try(()=>{c.code((0,r._)`await ${(0,n.callValidateCode)(e,t,p)}`),_(t),u||c.assign(i,!0)},e=>{c.if((0,r._)`!(${e} instanceof ${l.ValidationError})`,()=>c.throw(e)),g(e),u||c.assign(i,!1)}),e.ok(i)}function h(){e.result((0,n.callValidateCode)(e,t,p),()=>_(t),()=>g(t))}function g(e){let t=(0,r._)`${e}.errors`;c.assign(i.default.vErrors,(0,r._)`${i.default.vErrors} === null ? ${t} : ${i.default.vErrors}.concat(${t})`),c.assign(i.default.errors,(0,r._)`${i.default.vErrors}.length`)}function _(e){if(!l.opts.unevaluated)return;let t=a?.validate?.evaluated;if(l.props!==!0){if(t&&!t.dynamicProps)t.props!==void 0&&(l.props=o.mergeEvaluated.props(c,t.props,l.props));else{let t=c.var(`props`,(0,r._)`${e}.evaluated.props`);l.props=o.mergeEvaluated.props(c,t,l.props,r.Name)}}if(l.items!==!0){if(t&&!t.dynamicItems)t.items!==void 0&&(l.items=o.mergeEvaluated.items(c,t.items,l.items));else{let t=c.var(`items`,(0,r._)`${e}.evaluated.items`);l.items=o.mergeEvaluated.items(c,t,l.items,r.Name)}}}}e.callRef=l,e.default=s})),dg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=lg(),n=ug();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),fg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=t.operators,r={maximum:{okStr:`<=`,ok:n.LTE,fail:n.GT},minimum:{okStr:`>=`,ok:n.GTE,fail:n.LT},exclusiveMaximum:{okStr:`<`,ok:n.LT,fail:n.GTE},exclusiveMinimum:{okStr:`>`,ok:n.GT,fail:n.LTE}};e.default={keyword:Object.keys(r),type:`number`,schemaType:`number`,$data:!0,error:{message:({keyword:e,schemaCode:n})=>(0,t.str)`must be ${r[e].okStr} ${n}`,params:({keyword:e,schemaCode:n})=>(0,t._)`{comparison: ${r[e].okStr}, limit: ${n}}`},code(e){let{keyword:n,data:i,schemaCode:a}=e;e.fail$data((0,t._)`${i} ${r[n].fail} ${a} || isNaN(${i})`)}}})),pg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W();e.default={keyword:`multipleOf`,type:`number`,schemaType:`number`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must be multiple of ${e}`,params:({schemaCode:e})=>(0,t._)`{multipleOf: ${e}}`},code(e){let{gen:n,data:r,schemaCode:i,it:a}=e,o=a.opts.multipleOfPrecision,s=n.let(`res`),c=o?(0,t._)`Math.abs(Math.round(${s}) - ${s}) > 1e-${o}`:(0,t._)`${s} !== parseInt(${s})`;e.fail$data((0,t._)`(${i} === 0 || (${s} = ${r}/${i}, ${c}))`)}}})),mg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});function t(e){let t=e.length,n=0,r=0,i;for(;r<t;)n++,i=e.charCodeAt(r++),i>=55296&&i<=56319&&r<t&&(i=e.charCodeAt(r),(i&64512)==56320&&r++);return n}e.default=t,t.code=`require("ajv/dist/runtime/ucs2length").default`})),hg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G(),r=mg();e.default={keyword:[`maxLength`,`minLength`],type:`string`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxLength`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} characters`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:i,data:a,schemaCode:o,it:s}=e,c=i===`maxLength`?t.operators.GT:t.operators.LT,l=s.opts.unicode===!1?(0,t._)`${a}.length`:(0,t._)`${(0,n.useFunc)(e.gen,r.default)}(${a})`;e.fail$data((0,t._)`${l} ${c} ${o}`)}}})),gg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=qh(),n=G(),r=W();e.default={keyword:`pattern`,type:`string`,schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,r.str)`must match pattern "${e}"`,params:({schemaCode:e})=>(0,r._)`{pattern: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e,u=l.opts.unicodeRegExp?`u`:``;if(o){let{regExp:t}=l.opts.code,o=t.code===`new RegExp`?(0,r._)`new RegExp`:(0,n.useFunc)(i,t),s=i.let(`valid`);i.try(()=>i.assign(s,(0,r._)`${o}(${c}, ${u}).test(${a})`),()=>i.assign(s,!1)),e.fail$data((0,r._)`!${s}`)}else{let n=(0,t.usePattern)(e,s);e.fail$data((0,r._)`!${n}.test(${a})`)}}}})),_g=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W();e.default={keyword:[`maxProperties`,`minProperties`],type:`object`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxProperties`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} properties`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxProperties`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`Object.keys(${r}).length ${a} ${i}`)}}})),vg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=qh(),n=W(),r=G();e.default={keyword:`required`,type:`object`,schemaType:`array`,$data:!0,error:{message:({params:{missingProperty:e}})=>(0,n.str)`must have required property '${e}'`,params:({params:{missingProperty:e}})=>(0,n._)`{missingProperty: ${e}}`},code(e){let{gen:i,schema:a,schemaCode:o,data:s,$data:c,it:l}=e,{opts:u}=l;if(!c&&a.length===0)return;let d=a.length>=u.loopRequired;if(l.allErrors?f():p(),u.strictRequired){let t=e.parentSchema.properties,{definedProperties:n}=e.it;for(let e of a)if(t?.[e]===void 0&&!n.has(e)){let t=`required property "${e}" is not defined at "${l.schemaEnv.baseId+l.errSchemaPath}" (strictRequired)`;(0,r.checkStrictMode)(l,t,l.opts.strictRequired)}}function f(){if(d||c)e.block$data(n.nil,m);else for(let n of a)(0,t.checkReportMissingProp)(e,n)}function p(){let n=i.let(`missing`);if(d||c){let t=i.let(`valid`,!0);e.block$data(t,()=>h(n,t)),e.ok(t)}else i.if((0,t.checkMissingProp)(e,a,n)),(0,t.reportMissingProp)(e,n),i.else()}function m(){i.forOf(`prop`,o,n=>{e.setParams({missingProperty:n}),i.if((0,t.noPropertyInData)(i,s,n,u.ownProperties),()=>e.error())})}function h(r,a){e.setParams({missingProperty:r}),i.forOf(r,o,()=>{i.assign(a,(0,t.propertyInData)(i,s,r,u.ownProperties)),i.if((0,n.not)(a),()=>{e.error(),i.break()})},n.nil)}}}})),yg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W();e.default={keyword:[`maxItems`,`minItems`],type:`array`,schemaType:`number`,$data:!0,error:{message({keyword:e,schemaCode:n}){let r=e===`maxItems`?`more`:`fewer`;return(0,t.str)`must NOT have ${r} than ${n} items`},params:({schemaCode:e})=>(0,t._)`{limit: ${e}}`},code(e){let{keyword:n,data:r,schemaCode:i}=e,a=n===`maxItems`?t.operators.GT:t.operators.LT;e.fail$data((0,t._)`${r}.length ${a} ${i}`)}}})),bg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Xh();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),xg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Gh(),n=W(),r=G(),i=bg();e.default={keyword:`uniqueItems`,type:`array`,schemaType:`boolean`,$data:!0,error:{message:({params:{i:e,j:t}})=>(0,n.str)`must NOT have duplicate items (items ## ${t} and ${e} are identical)`,params:({params:{i:e,j:t}})=>(0,n._)`{i: ${e}, j: ${t}}`},code(e){let{gen:a,data:o,$data:s,schema:c,parentSchema:l,schemaCode:u,it:d}=e;if(!s&&!c)return;let f=a.let(`valid`),p=l.items?(0,t.getSchemaTypes)(l.items):[];e.block$data(f,m,(0,n._)`${u} === false`),e.ok(f);function m(){let t=a.let(`i`,(0,n._)`${o}.length`),r=a.let(`j`);e.setParams({i:t,j:r}),a.assign(f,!0),a.if((0,n._)`${t} > 1`,()=>(h()?g:_)(t,r))}function h(){return p.length>0&&!p.some(e=>e===`object`||e===`array`)}function g(r,i){let s=a.name(`item`),c=(0,t.checkDataTypes)(p,s,d.opts.strictNumbers,t.DataType.Wrong),l=a.const(`indices`,(0,n._)`{}`);a.for((0,n._)`;${r}--;`,()=>{a.let(s,(0,n._)`${o}[${r}]`),a.if(c,(0,n._)`continue`),p.length>1&&a.if((0,n._)`typeof ${s} == "string"`,(0,n._)`${s} += "_"`),a.if((0,n._)`typeof ${l}[${s}] == "number"`,()=>{a.assign(i,(0,n._)`${l}[${s}]`),e.error(),a.assign(f,!1).break()}).code((0,n._)`${l}[${s}] = ${r}`)})}function _(t,s){let c=(0,r.useFunc)(a,i.default),l=a.name(`outer`);a.label(l).for((0,n._)`;${t}--;`,()=>a.for((0,n._)`${s} = ${t}; ${s}--;`,()=>a.if((0,n._)`${c}(${o}[${t}], ${o}[${s}])`,()=>{e.error(),a.assign(f,!1).break(l)})))}}}})),Sg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G(),r=bg();e.default={keyword:`const`,$data:!0,error:{message:`must be equal to constant`,params:({schemaCode:e})=>(0,t._)`{allowedValue: ${e}}`},code(e){let{gen:i,data:a,$data:o,schemaCode:s,schema:c}=e;o||c&&typeof c==`object`?e.fail$data((0,t._)`!${(0,n.useFunc)(i,r.default)}(${a}, ${s})`):e.fail((0,t._)`${c} !== ${a}`)}}})),Cg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G(),r=bg();e.default={keyword:`enum`,schemaType:`array`,$data:!0,error:{message:`must be equal to one of the allowed values`,params:({schemaCode:e})=>(0,t._)`{allowedValues: ${e}}`},code(e){let{gen:i,data:a,$data:o,schema:s,schemaCode:c,it:l}=e;if(!o&&s.length===0)throw Error(`enum must have non-empty array`);let u=s.length>=l.opts.loopEnum,d,f=()=>d??=(0,n.useFunc)(i,r.default),p;if(u||o)p=i.let(`valid`),e.block$data(p,m);else{if(!Array.isArray(s))throw Error(`ajv implementation error`);let e=i.const(`vSchema`,c);p=(0,t.or)(...s.map((t,n)=>h(e,n)))}e.pass(p);function m(){i.assign(p,!1),i.forOf(`v`,c,e=>i.if((0,t._)`${f()}(${a}, ${e})`,()=>i.assign(p,!0).break()))}function h(e,n){let r=s[n];return typeof r==`object`&&r?(0,t._)`${f()}(${a}, ${e}[${n}])`:(0,t._)`${a} === ${r}`}}}})),wg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=fg(),n=pg(),r=hg(),i=gg(),a=_g(),o=vg(),s=yg(),c=xg(),l=Sg(),u=Cg();e.default=[t.default,n.default,r.default,i.default,a.default,o.default,s.default,c.default,{keyword:`type`,schemaType:[`string`,`array`]},{keyword:`nullable`,schemaType:`boolean`},l.default,u.default]})),Tg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateAdditionalItems=void 0;let t=W(),n=G(),r={keyword:`additionalItems`,type:`array`,schemaType:[`boolean`,`object`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{parentSchema:t,it:r}=e,{items:a}=t;if(!Array.isArray(a)){(0,n.checkStrictMode)(r,`"additionalItems" is ignored when "items" is not an array of schemas`);return}i(e,a)}};function i(e,r){let{gen:i,schema:a,data:o,keyword:s,it:c}=e;c.items=!0;let l=i.const(`len`,(0,t._)`${o}.length`);if(a===!1)e.setParams({len:r.length}),e.pass((0,t._)`${l} <= ${r.length}`);else if(typeof a==`object`&&!(0,n.alwaysValidSchema)(c,a)){let n=i.var(`valid`,(0,t._)`${l} <= ${r.length}`);i.if((0,t.not)(n),()=>u(n)),e.ok(n)}function u(a){i.forRange(`i`,r.length,l,r=>{e.subschema({keyword:s,dataProp:r,dataPropType:n.Type.Num},a),c.allErrors||i.if((0,t.not)(a),()=>i.break())})}}e.validateAdditionalItems=i,e.default=r})),Eg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateTuple=void 0;let t=W(),n=G(),r=qh(),i={keyword:`items`,type:`array`,schemaType:[`object`,`array`,`boolean`],before:`uniqueItems`,code(e){let{schema:t,it:i}=e;if(Array.isArray(t))return a(e,`additionalItems`,t);i.items=!0,!(0,n.alwaysValidSchema)(i,t)&&e.ok((0,r.validateArray)(e))}};function a(e,r,i=e.schema){let{gen:a,parentSchema:o,data:s,keyword:c,it:l}=e;f(o),l.opts.unevaluated&&i.length&&l.items!==!0&&(l.items=n.mergeEvaluated.items(a,i.length,l.items));let u=a.name(`valid`),d=a.const(`len`,(0,t._)`${s}.length`);i.forEach((r,i)=>{(0,n.alwaysValidSchema)(l,r)||(a.if((0,t._)`${d} > ${i}`,()=>e.subschema({keyword:c,schemaProp:i,dataProp:i},u)),e.ok(u))});function f(e){let{opts:t,errSchemaPath:a}=l,o=i.length,s=o===e.minItems&&(o===e.maxItems||e[r]===!1);if(t.strictTuples&&!s){let e=`"${c}" is ${o}-tuple, but minItems or maxItems/${r} are not specified or different at path "${a}"`;(0,n.checkStrictMode)(l,e,t.strictTuples)}}}e.validateTuple=a,e.default=i})),Dg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Eg();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),Og=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G(),r=qh(),i=Tg();e.default={keyword:`items`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,error:{message:({params:{len:e}})=>(0,t.str)`must NOT have more than ${e} items`,params:({params:{len:e}})=>(0,t._)`{limit: ${e}}`},code(e){let{schema:t,parentSchema:a,it:o}=e,{prefixItems:s}=a;o.items=!0,!(0,n.alwaysValidSchema)(o,t)&&(s?(0,i.validateAdditionalItems)(e,s):e.ok((0,r.validateArray)(e)))}}})),kg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G();e.default={keyword:`contains`,type:`array`,schemaType:[`object`,`boolean`],before:`uniqueItems`,trackErrors:!0,error:{message:({params:{min:e,max:n}})=>n===void 0?(0,t.str)`must contain at least ${e} valid item(s)`:(0,t.str)`must contain at least ${e} and no more than ${n} valid item(s)`,params:({params:{min:e,max:n}})=>n===void 0?(0,t._)`{minContains: ${e}}`:(0,t._)`{minContains: ${e}, maxContains: ${n}}`},code(e){let{gen:r,schema:i,parentSchema:a,data:o,it:s}=e,c,l,{minContains:u,maxContains:d}=a;s.opts.next?(c=u===void 0?1:u,l=d):c=1;let f=r.const(`len`,(0,t._)`${o}.length`);if(e.setParams({min:c,max:l}),l===void 0&&c===0){(0,n.checkStrictMode)(s,`"minContains" == 0 without "maxContains": "contains" keyword ignored`);return}if(l!==void 0&&c>l){(0,n.checkStrictMode)(s,`"minContains" > "maxContains" is always invalid`),e.fail();return}if((0,n.alwaysValidSchema)(s,i)){let n=(0,t._)`${f} >= ${c}`;l!==void 0&&(n=(0,t._)`${n} && ${f} <= ${l}`),e.pass(n);return}s.items=!0;let p=r.name(`valid`);l===void 0&&c===1?h(p,()=>r.if(p,()=>r.break())):c===0?(r.let(p,!0),l!==void 0&&r.if((0,t._)`${o}.length > 0`,m)):(r.let(p,!1),m()),e.result(p,()=>e.reset());function m(){let e=r.name(`_valid`),t=r.let(`count`,0);h(e,()=>r.if(e,()=>g(t)))}function h(t,i){r.forRange(`i`,0,f,r=>{e.subschema({keyword:`contains`,dataProp:r,dataPropType:n.Type.Num,compositeRule:!0},t),i()})}function g(e){r.code((0,t._)`${e}++`),l===void 0?r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0).break()):(r.if((0,t._)`${e} > ${l}`,()=>r.assign(p,!1).break()),c===1?r.assign(p,!0):r.if((0,t._)`${e} >= ${c}`,()=>r.assign(p,!0)))}}}})),Ag=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;let t=W(),n=G(),r=qh();e.error={message:({params:{property:e,depsCount:n,deps:r}})=>{let i=n===1?`property`:`properties`;return(0,t.str)`must have ${i} ${r} when property ${e} is present`},params:({params:{property:e,depsCount:n,deps:r,missingProperty:i}})=>(0,t._)`{property: ${e},
181
181
  missingProperty: ${i},
182
182
  depsCount: ${n},
183
- deps: ${r}}`};let i={keyword:`dependencies`,type:`object`,schemaType:`object`,error:e.error,code(e){let[t,n]=a(e);o(e,t),s(e,n)}};function a({schema:e}){let t={},n={};for(let r in e){if(r===`__proto__`)continue;let i=Array.isArray(e[r])?t:n;i[r]=e[r]}return[t,n]}function o(e,n=e.schema){let{gen:i,data:a,it:o}=e;if(Object.keys(n).length===0)return;let s=i.let(`missing`);for(let c in n){let l=n[c];if(l.length===0)continue;let u=(0,r.propertyInData)(i,a,c,o.opts.ownProperties);e.setParams({property:c,depsCount:l.length,deps:l.join(`, `)}),o.allErrors?i.if(u,()=>{for(let t of l)(0,r.checkReportMissingProp)(e,t)}):(i.if((0,t._)`${u} && (${(0,r.checkMissingProp)(e,l,s)})`),(0,r.reportMissingProp)(e,s),i.else())}}e.validatePropertyDeps=o;function s(e,t=e.schema){let{gen:i,data:a,keyword:o,it:s}=e,c=i.name(`valid`);for(let l in t)(0,n.alwaysValidSchema)(s,t[l])||(i.if((0,r.propertyInData)(i,a,l,s.opts.ownProperties),()=>{let t=e.subschema({keyword:o,schemaProp:l},c);e.mergeValidEvaluated(t,c)},()=>i.var(c,!0)),e.ok(c))}e.validateSchemaDeps=s,e.default=i})),jg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G();e.default={keyword:`propertyNames`,type:`object`,schemaType:[`object`,`boolean`],error:{message:`property name must be valid`,params:({params:e})=>(0,t._)`{propertyName: ${e.propertyName}}`},code(e){let{gen:r,schema:i,data:a,it:o}=e;if((0,n.alwaysValidSchema)(o,i))return;let s=r.name(`valid`);r.forIn(`key`,a,n=>{e.setParams({propertyName:n}),e.subschema({keyword:`propertyNames`,data:n,dataTypes:[`string`],propertyName:n,compositeRule:!0},s),r.if((0,t.not)(s),()=>{e.error(!0),o.allErrors||r.break()})}),e.ok(s)}}})),Mg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=qh(),n=W(),r=Bh(),i=G();e.default={keyword:`additionalProperties`,type:[`object`],schemaType:[`boolean`,`object`],allowUndefined:!0,trackErrors:!0,error:{message:`must NOT have additional properties`,params:({params:e})=>(0,n._)`{additionalProperty: ${e.additionalProperty}}`},code(e){let{gen:a,schema:o,parentSchema:s,data:c,errsCount:l,it:u}=e;if(!l)throw Error(`ajv implementation error`);let{allErrors:d,opts:f}=u;if(u.props=!0,f.removeAdditional!==`all`&&(0,i.alwaysValidSchema)(u,o))return;let p=(0,t.allSchemaProperties)(s.properties),m=(0,t.allSchemaProperties)(s.patternProperties);h(),e.ok((0,n._)`${l} === ${r.default.errors}`);function h(){a.forIn(`key`,c,e=>{!p.length&&!m.length?v(e):a.if(g(e),()=>v(e))})}function g(r){let o;if(p.length>8){let e=(0,i.schemaRefOrVal)(u,s.properties,`properties`);o=(0,t.isOwnProperty)(a,e,r)}else o=p.length?(0,n.or)(...p.map(e=>(0,n._)`${r} === ${e}`)):n.nil;return m.length&&(o=(0,n.or)(o,...m.map(i=>(0,n._)`${(0,t.usePattern)(e,i)}.test(${r})`))),(0,n.not)(o)}function _(e){a.code((0,n._)`delete ${c}[${e}]`)}function v(t){if(f.removeAdditional===`all`||f.removeAdditional&&o===!1){_(t);return}if(o===!1){e.setParams({additionalProperty:t}),e.error(),d||a.break();return}if(typeof o==`object`&&!(0,i.alwaysValidSchema)(u,o)){let r=a.name(`valid`);f.removeAdditional===`failing`?(y(t,r,!1),a.if((0,n.not)(r),()=>{e.reset(),_(t)})):(y(t,r),d||a.if((0,n.not)(r),()=>a.break()))}}function y(t,n,r){let a={keyword:`additionalProperties`,dataProp:t,dataPropType:i.Type.Str};r===!1&&Object.assign(a,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(a,n)}}}})),Ng=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=$h(),n=qh(),r=G(),i=Mg();e.default={keyword:`properties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,parentSchema:s,data:c,it:l}=e;l.opts.removeAdditional===`all`&&s.additionalProperties===void 0&&i.default.code(new t.KeywordCxt(l,i.default,`additionalProperties`));let u=(0,n.allSchemaProperties)(o);for(let e of u)l.definedProperties.add(e);l.opts.unevaluated&&u.length&&l.props!==!0&&(l.props=r.mergeEvaluated.props(a,(0,r.toHash)(u),l.props));let d=u.filter(e=>!(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0)return;let f=a.name(`valid`);for(let t of d)p(t)?m(t):(a.if((0,n.propertyInData)(a,c,t,l.opts.ownProperties)),m(t),l.allErrors||a.else().var(f,!0),a.endIf()),e.it.definedProperties.add(t),e.ok(f);function p(e){return l.opts.useDefaults&&!l.compositeRule&&o[e].default!==void 0}function m(t){e.subschema({keyword:`properties`,schemaProp:t,dataProp:t},f)}}}})),Pg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=qh(),n=W(),r=G(),i=G();e.default={keyword:`patternProperties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,data:s,parentSchema:c,it:l}=e,{opts:u}=l,d=(0,t.allSchemaProperties)(o),f=d.filter(e=>(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0||f.length===d.length&&(!l.opts.unevaluated||l.props===!0))return;let p=u.strictSchema&&!u.allowMatchingProperties&&c.properties,m=a.name(`valid`);l.props!==!0&&!(l.props instanceof n.Name)&&(l.props=(0,i.evaluatedPropsToName)(a,l.props));let{props:h}=l;g();function g(){for(let e of d)p&&_(e),l.allErrors?v(e):(a.var(m,!0),v(e),a.if(m))}function _(e){for(let t in p)new RegExp(e).test(t)&&(0,r.checkStrictMode)(l,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function v(r){a.forIn(`key`,s,o=>{a.if((0,n._)`${(0,t.usePattern)(e,r)}.test(${o})`,()=>{let t=f.includes(r);t||e.subschema({keyword:`patternProperties`,schemaProp:r,dataProp:o,dataPropType:i.Type.Str},m),l.opts.unevaluated&&h!==!0?a.assign((0,n._)`${h}[${o}]`,!0):!t&&!l.allErrors&&a.if((0,n.not)(m),()=>a.break())})})}}}})),Fg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G();e.default={keyword:`not`,schemaType:[`object`,`boolean`],trackErrors:!0,code(e){let{gen:n,schema:r,it:i}=e;if((0,t.alwaysValidSchema)(i,r)){e.fail();return}let a=n.name(`valid`);e.subschema({keyword:`not`,compositeRule:!0,createErrors:!1,allErrors:!1},a),e.failResult(a,()=>e.reset(),()=>e.error())},error:{message:`must NOT be valid`}}})),Ig=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:qh().validateUnion,error:{message:`must match a schema in anyOf`}}})),Lg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G();e.default={keyword:`oneOf`,schemaType:`array`,trackErrors:!0,error:{message:`must match exactly one schema in oneOf`,params:({params:e})=>(0,t._)`{passingSchemas: ${e.passing}}`},code(e){let{gen:r,schema:i,parentSchema:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(o.opts.discriminator&&a.discriminator)return;let s=i,c=r.let(`valid`,!1),l=r.let(`passing`,null),u=r.name(`_valid`);e.setParams({passing:l}),r.block(d),e.result(c,()=>e.reset(),()=>e.error(!0));function d(){s.forEach((i,a)=>{let s;(0,n.alwaysValidSchema)(o,i)?r.var(u,!0):s=e.subschema({keyword:`oneOf`,schemaProp:a,compositeRule:!0},u),a>0&&r.if((0,t._)`${u} && ${c}`).assign(c,!1).assign(l,(0,t._)`[${l}, ${a}]`).else(),r.if(u,()=>{r.assign(c,!0),r.assign(l,a),s&&e.mergeEvaluated(s,t.Name)})})}}}})),Rg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G();e.default={keyword:`allOf`,schemaType:`array`,code(e){let{gen:n,schema:r,it:i}=e;if(!Array.isArray(r))throw Error(`ajv implementation error`);let a=n.name(`valid`);r.forEach((n,r)=>{if((0,t.alwaysValidSchema)(i,n))return;let o=e.subschema({keyword:`allOf`,schemaProp:r},a);e.ok(a),e.mergeEvaluated(o)})}}})),zg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G(),r={keyword:`if`,schemaType:[`object`,`boolean`],trackErrors:!0,error:{message:({params:e})=>(0,t.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,t._)`{failingKeyword: ${e.ifClause}}`},code(e){let{gen:r,parentSchema:a,it:o}=e;a.then===void 0&&a.else===void 0&&(0,n.checkStrictMode)(o,`"if" without "then" and "else" is ignored`);let s=i(o,`then`),c=i(o,`else`);if(!s&&!c)return;let l=r.let(`valid`,!0),u=r.name(`_valid`);if(d(),e.reset(),s&&c){let t=r.let(`ifClause`);e.setParams({ifClause:t}),r.if(u,f(`then`,t),f(`else`,t))}else s?r.if(u,f(`then`)):r.if((0,t.not)(u),f(`else`));e.pass(l,()=>e.error(!0));function d(){let t=e.subschema({keyword:`if`,compositeRule:!0,createErrors:!1,allErrors:!1},u);e.mergeEvaluated(t)}function f(n,i){return()=>{let a=e.subschema({keyword:n},u);r.assign(l,u),e.mergeValidEvaluated(a,l),i?r.assign(i,(0,t._)`${n}`):e.setParams({ifClause:n})}}}};function i(e,t){let r=e.schema[t];return r!==void 0&&!(0,n.alwaysValidSchema)(e,r)}e.default=r})),Bg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G();e.default={keyword:[`then`,`else`],schemaType:[`object`,`boolean`],code({keyword:e,parentSchema:n,it:r}){n.if===void 0&&(0,t.checkStrictMode)(r,`"${e}" without "if" is ignored`)}}})),Vg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Tg(),n=Dg(),r=Eg(),i=Og(),a=kg(),o=Ag(),s=jg(),c=Mg(),l=Ng(),u=Pg(),d=Fg(),f=Ig(),p=Lg(),m=Rg(),h=zg(),g=Bg();function _(e=!1){let _=[d.default,f.default,p.default,m.default,h.default,g.default,s.default,c.default,o.default,l.default,u.default];return e?_.push(n.default,i.default):_.push(t.default,r.default),_.push(a.default),_}e.default=_})),Hg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W();e.default={keyword:`format`,type:[`number`,`string`],schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,t._)`{format: ${e}}`},code(e,n){let{gen:r,data:i,$data:a,schema:o,schemaCode:s,it:c}=e,{opts:l,errSchemaPath:u,schemaEnv:d,self:f}=c;if(!l.validateFormats)return;a?p():m();function p(){let a=r.scopeValue(`formats`,{ref:f.formats,code:l.code.formats}),o=r.const(`fDef`,(0,t._)`${a}[${s}]`),c=r.let(`fType`),u=r.let(`format`);r.if((0,t._)`typeof ${o} == "object" && !(${o} instanceof RegExp)`,()=>r.assign(c,(0,t._)`${o}.type || "string"`).assign(u,(0,t._)`${o}.validate`),()=>r.assign(c,(0,t._)`"string"`).assign(u,o)),e.fail$data((0,t.or)(p(),m()));function p(){return l.strictSchema===!1?t.nil:(0,t._)`${s} && !${u}`}function m(){let e=d.$async?(0,t._)`(${o}.async ? await ${u}(${i}) : ${u}(${i}))`:(0,t._)`${u}(${i})`,r=(0,t._)`(typeof ${u} == "function" ? ${e} : ${u}.test(${i}))`;return(0,t._)`${u} && ${u} !== true && ${c} === ${n} && !${r}`}}function m(){let a=f.formats[o];if(!a){m();return}if(a===!0)return;let[s,c,p]=h(a);s===n&&e.pass(g());function m(){if(l.strictSchema===!1){f.logger.warn(e());return}throw Error(e());function e(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function h(e){let n=e instanceof RegExp?(0,t.regexpCode)(e):l.code.formats?(0,t._)`${l.code.formats}${(0,t.getProperty)(o)}`:void 0,i=r.scopeValue(`formats`,{key:o,ref:e,code:n});return typeof e==`object`&&!(e instanceof RegExp)?[e.type||`string`,e.validate,(0,t._)`${i}.validate`]:[`string`,e,i]}function g(){if(typeof a==`object`&&!(a instanceof RegExp)&&a.async){if(!d.$async)throw Error(`async format in sync schema`);return(0,t._)`await ${p}(${i})`}return typeof c==`function`?(0,t._)`${p}(${i})`:(0,t._)`${p}.test(${i})`}}}}})),Ug=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=[Hg().default]})),Wg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.contentVocabulary=e.metadataVocabulary=void 0,e.metadataVocabulary=[`title`,`description`,`default`,`deprecated`,`readOnly`,`writeOnly`,`examples`],e.contentVocabulary=[`contentMediaType`,`contentEncoding`,`contentSchema`]})),Gg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=dg(),n=wg(),r=Vg(),i=Ug(),a=Wg();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),Kg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DiscrError=void 0;var t;(function(e){e.Tag=`tag`,e.Mapping=`mapping`})(t||(e.DiscrError=t={}))})),qg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=Kg(),r=ng(),i=tg(),a=G();e.default={keyword:`discriminator`,type:`object`,schemaType:`object`,error:{message:({params:{discrError:e,tagName:t}})=>e===n.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:n,tagName:r}})=>(0,t._)`{error: ${e}, tag: ${r}, tagValue: ${n}}`},code(e){let{gen:o,data:s,schema:c,parentSchema:l,it:u}=e,{oneOf:d}=l;if(!u.opts.discriminator)throw Error(`discriminator: requires discriminator option`);let f=c.propertyName;if(typeof f!=`string`)throw Error(`discriminator: requires propertyName`);if(c.mapping)throw Error(`discriminator: mapping is not supported`);if(!d)throw Error(`discriminator: requires oneOf keyword`);let p=o.let(`valid`,!1),m=o.const(`tag`,(0,t._)`${s}${(0,t.getProperty)(f)}`);o.if((0,t._)`typeof ${m} == "string"`,()=>h(),()=>e.error(!1,{discrError:n.DiscrError.Tag,tag:m,tagName:f})),e.ok(p);function h(){let r=_();o.if(!1);for(let e in r)o.elseIf((0,t._)`${m} === ${e}`),o.assign(p,g(r[e]));o.else(),e.error(!1,{discrError:n.DiscrError.Mapping,tag:m,tagName:f}),o.endIf()}function g(n){let r=o.name(`valid`),i=e.subschema({keyword:`oneOf`,schemaProp:n},r);return e.mergeEvaluated(i,t.Name),r}function _(){let e={},t=o(l),n=!0;for(let e=0;e<d.length;e++){let c=d[e];if(c?.$ref&&!(0,a.schemaHasRulesButRef)(c,u.self.RULES)){let e=c.$ref;if(c=r.resolveRef.call(u.self,u.schemaEnv.root,u.baseId,e),c instanceof r.SchemaEnv&&(c=c.schema),c===void 0)throw new i.default(u.opts.uriResolver,u.baseId,e)}let l=c?.properties?.[f];if(typeof l!=`object`)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${f}"`);n&&=t||o(c),s(l,e)}if(!n)throw Error(`discriminator: "${f}" must be required`);return e;function o({required:e}){return Array.isArray(e)&&e.includes(f)}function s(e,t){if(e.const)c(e.const,t);else if(e.enum)for(let n of e.enum)c(n,t);else throw Error(`discriminator: "properties/${f}" must have "const" or "enum"`)}function c(t,n){if(typeof t!=`string`||t in e)throw Error(`discriminator: "${f}" values must be unique strings`);e[t]=n}}}}})),Jg=z(((e,t)=>{t.exports={$schema:`http://json-schema.org/draft-07/schema#`,$id:`http://json-schema.org/draft-07/schema#`,title:`Core schema meta-schema`,definitions:{schemaArray:{type:`array`,minItems:1,items:{$ref:`#`}},nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:`#/definitions/nonNegativeInteger`},{default:0}]},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}},type:[`object`,`boolean`],properties:{$id:{type:`string`,format:`uri-reference`},$schema:{type:`string`,format:`uri`},$ref:{type:`string`,format:`uri-reference`},$comment:{type:`string`},title:{type:`string`},description:{type:`string`},default:!0,readOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/definitions/nonNegativeInteger`},minLength:{$ref:`#/definitions/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},additionalItems:{$ref:`#`},items:{anyOf:[{$ref:`#`},{$ref:`#/definitions/schemaArray`}],default:!0},maxItems:{$ref:`#/definitions/nonNegativeInteger`},minItems:{$ref:`#/definitions/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},contains:{$ref:`#`},maxProperties:{$ref:`#/definitions/nonNegativeInteger`},minProperties:{$ref:`#/definitions/nonNegativeIntegerDefault0`},required:{$ref:`#/definitions/stringArray`},additionalProperties:{$ref:`#`},definitions:{type:`object`,additionalProperties:{$ref:`#`},default:{}},properties:{type:`object`,additionalProperties:{$ref:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$ref:`#`},propertyNames:{format:`regex`},default:{}},dependencies:{type:`object`,additionalProperties:{anyOf:[{$ref:`#`},{$ref:`#/definitions/stringArray`}]}},propertyNames:{$ref:`#`},const:!0,enum:{type:`array`,items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:`#/definitions/simpleTypes`},{type:`array`,items:{$ref:`#/definitions/simpleTypes`},minItems:1,uniqueItems:!0}]},format:{type:`string`},contentMediaType:{type:`string`},contentEncoding:{type:`string`},if:{$ref:`#`},then:{$ref:`#`},else:{$ref:`#`},allOf:{$ref:`#/definitions/schemaArray`},anyOf:{$ref:`#/definitions/schemaArray`},oneOf:{$ref:`#/definitions/schemaArray`},not:{$ref:`#`}},default:!0}})),Yg=z(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;let n=cg(),r=Gg(),i=qg(),a=Jg(),o=[`/properties`],s=`http://json-schema.org/draft-07/schema`;var c=class extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(a,o):a;this.addMetaSchema(e,s,!1),this.refs[`http://json-schema.org/schema`]=s}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}};e.Ajv=c,t.exports=e=c,t.exports.Ajv=c,Object.defineProperty(e,"__esModule",{value:!0}),e.default=c;var l=$h();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return l.KeywordCxt}});var u=W();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var d=eg();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return d.default}});var f=tg();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return f.default}})})),Xg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(e,t){return{validate:e,compare:t}}e.fullFormats={date:t(a,o),time:t(c(!0),l),"date-time":t(f(!0),p),"iso-time":t(c(),u),"iso-date-time":t(f(),m),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:_,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:ee,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:y,int32:{type:`number`,validate:S},int64:{type:`number`,validate:C},float:{type:`number`,validate:w},double:{type:`number`,validate:w},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,o),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,l),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,p),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,m),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function n(e){return e%4==0&&(e%100!=0||e%400==0)}let r=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31];function a(e){let t=r.exec(e);if(!t)return!1;let a=+t[1],o=+t[2],s=+t[3];return o>=1&&o<=12&&s>=1&&s<=(o===2&&n(a)?29:i[o])}function o(e,t){if(e&&t)return e>t?1:e<t?-1:0}let s=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(e){return function(t){let n=s.exec(t);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=n[4],c=n[5]===`-`?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||e&&!o)return!1;if(r<=23&&i<=59&&a<60)return!0;let d=i-u*c,f=r-l*c-+(d<0);return(f===23||f===-1)&&(d===59||d===-1)&&a<61}}function l(e,t){if(!(e&&t))return;let n=new Date(`2020-01-01T`+e).valueOf(),r=new Date(`2020-01-01T`+t).valueOf();if(n&&r)return n-r}function u(e,t){if(!(e&&t))return;let n=s.exec(e),r=s.exec(t);if(n&&r)return e=n[1]+n[2]+n[3],t=r[1]+r[2]+r[3],e>t?1:e<t?-1:0}let d=/t|\s/i;function f(e){let t=c(e);return function(e){let n=e.split(d);return n.length===2&&a(n[0])&&t(n[1])}}function p(e,t){if(!(e&&t))return;let n=new Date(e).valueOf(),r=new Date(t).valueOf();if(n&&r)return n-r}function m(e,t){if(!(e&&t))return;let[n,r]=e.split(d),[i,a]=t.split(d),s=o(n,i);if(s!==void 0)return s||l(r,a)}let h=/\/|:/,g=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function _(e){return h.test(e)&&g.test(e)}let v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function y(e){return v.lastIndex=0,v.test(e)}let b=-(2**31),x=2**31-1;function S(e){return Number.isInteger(e)&&e<=x&&e>=b}function C(e){return Number.isInteger(e)}function w(){return!0}let T=/[^\\]\\Z/;function ee(e){if(T.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),Zg=z((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;let t=Yg(),n=W(),r=n.operators,i={formatMaximum:{okStr:`<=`,ok:r.LTE,fail:r.GT},formatMinimum:{okStr:`>=`,ok:r.GTE,fail:r.LT},formatExclusiveMaximum:{okStr:`<`,ok:r.LT,fail:r.GTE},formatExclusiveMinimum:{okStr:`>`,ok:r.GT,fail:r.LTE}};e.formatLimitDefinition={keyword:Object.keys(i),type:`string`,schemaType:`string`,$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,n.str)`should be ${i[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,n._)`{comparison: ${i[e].okStr}, limit: ${t}}`},code(e){let{gen:r,data:a,schemaCode:o,keyword:s,it:c}=e,{opts:l,self:u}=c;if(!l.validateFormats)return;let d=new t.KeywordCxt(c,u.RULES.all.format.definition,`format`);d.$data?f():p();function f(){let t=r.scopeValue(`formats`,{ref:u.formats,code:l.code.formats}),i=r.const(`fmt`,(0,n._)`${t}[${d.schemaCode}]`);e.fail$data((0,n.or)((0,n._)`typeof ${i} != "object"`,(0,n._)`${i} instanceof RegExp`,(0,n._)`typeof ${i}.compare != "function"`,m(i)))}function p(){let t=d.schema,i=u.formats[t];if(!i||i===!0)return;if(typeof i!=`object`||i instanceof RegExp||typeof i.compare!=`function`)throw Error(`"${s}": format "${t}" does not define "compare" function`);let a=r.scopeValue(`formats`,{key:t,ref:i,code:l.code.formats?(0,n._)`${l.code.formats}${(0,n.getProperty)(t)}`:void 0});e.fail$data(m(a))}function m(e){return(0,n._)`${e}.compare(${a}, ${o}) ${i[s].fail} 0`}},dependencies:[`format`]},e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)})),Qg=z(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});let n=Xg(),r=Zg(),i=W(),a=new i.Name(`fullFormats`),o=new i.Name(`fastFormats`),s=(e,t={keywords:!0})=>{if(Array.isArray(t))return c(e,t,n.fullFormats,a),e;let[i,s]=t.mode===`fast`?[n.fastFormats,o]:[n.fullFormats,a];return c(e,t.formats||n.formatNames,i,s),t.keywords&&(0,r.default)(e),e};s.get=(e,t=`full`)=>{let r=(t===`fast`?n.fastFormats:n.fullFormats)[e];if(!r)throw Error(`Unknown format "${e}"`);return r};function c(e,t,n,r){var a;(a=e.opts.code).formats??(a.formats=(0,i._)`require("ajv-formats/dist/formats").${r}`);for(let r of t)e.addFormat(r,n[r])}t.exports=e=s,Object.defineProperty(e,"__esModule",{value:!0}),e.default=s})),$g=Yg(),e_=cf(Qg(),1),t_=class{_ajv;constructor(e){this._ajv=e??Qd()}getValidator(e){let t=`$id`in e&&typeof e.$id==`string`?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}},n_=class{shortcircuit;draft;constructor(e){this.shortcircuit=e?.shortcircuit??!0,this.draft=e?.draft??`2020-12`}getValidator(e){let t=new xd(e,this.draft,this.shortcircuit);return e=>{let n=t.validate(e);return n.valid?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:n.errors.map(e=>`${e.instanceLocation}: ${e.error}`).join(`; `)}}}}}));function i_(){throw Error(`StdioServerTransport is not supported in this environment. Use StreamableHTTPServerTransport instead.`)}var a_,o_=F((()=>{r_(),a_={get stdin(){return i_()},get stdout(){return i_()}}})),s_=Qe({AjvJsonSchemaValidator:()=>t_,CfWorkerJsonSchemaValidator:()=>n_,DEFAULT_NEGOTIATED_PROTOCOL_VERSION:()=>vf,DEFAULT_REQUEST_TIMEOUT_MSEC:()=>kh,ExperimentalMcpServerTasks:()=>E_,ExperimentalServerTasks:()=>D_,INTERNAL_ERROR:()=>Tf,INVALID_PARAMS:()=>wf,INVALID_REQUEST:()=>Sf,InMemoryTaskMessageQueue:()=>T_,InMemoryTaskStore:()=>w_,JSONRPC_VERSION:()=>`2.0`,LATEST_PROTOCOL_VERSION:()=>_f,METHOD_NOT_FOUND:()=>Cf,McpServer:()=>k_,OAuthError:()=>uf,OAuthErrorCode:()=>lf,PARSE_ERROR:()=>xf,ProtocolError:()=>U,ProtocolErrorCode:()=>H,RELATED_TASK_META_KEY:()=>bf,ReadBuffer:()=>jh,ResourceTemplate:()=>A_,SUPPORTED_PROTOCOL_VERSIONS:()=>yf,SdkError:()=>V,SdkErrorCode:()=>B,Server:()=>O_,StdioServerTransport:()=>N_,UriTemplate:()=>Lh,UrlElicitationRequiredError:()=>Ef,WebStandardStreamableHTTPServerTransport:()=>P_,assertClientRequestTaskCapability:()=>f_,assertCompleteRequestPrompt:()=>Md,assertCompleteRequestResourceTemplate:()=>Nd,assertToolsCallTaskCapability:()=>d_,checkResourceAllowed:()=>Td,completable:()=>c_,createFetchWithInit:()=>qd,deserializeMessage:()=>Vd,fromJsonSchema:()=>S_,getDisplayName:()=>Ed,hostHeaderValidationResponse:()=>x_,isCompletable:()=>l_,isInitializeRequest:()=>Th,isInitializedNotification:()=>Eh,isJSONRPCErrorResponse:()=>Ch,isJSONRPCNotification:()=>xh,isJSONRPCRequest:()=>bh,isJSONRPCResultResponse:()=>Sh,isTaskAugmentedRequestParams:()=>wh,isTerminal:()=>Fd,localhostAllowedHostnames:()=>b_,parseJSONRPCMessage:()=>jd,resourceUrlFromServerUrl:()=>wd,serializeMessage:()=>Hd,takeResult:()=>Bd,toArrayAsync:()=>zd,validateHostHeader:()=>y_});function c_(e,t){return Object.defineProperty(e,C_,{value:{complete:t},enumerable:!1,writable:!1,configurable:!1}),e}function l_(e){return!!e&&typeof e==`object`&&C_ in e}function u_(e){return e[C_]?.complete}function d_(e,t,n){if(!e)throw new V(B.CapabilityNotSupported,`${n} does not support task creation (required for ${t})`);if(t===`tools/call`&&!e.tools?.call)throw new V(B.CapabilityNotSupported,`${n} does not support task creation for tools/call (required for ${t})`)}function f_(e,t,n){if(!e)throw new V(B.CapabilityNotSupported,`${n} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw new V(B.CapabilityNotSupported,`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw new V(B.CapabilityNotSupported,`${n} does not support task creation for elicitation/create (required for ${t})`)}}function p_(e,t){if(`createTask`in t){let n=t;return async(t,r)=>{if(!r.task?.store)throw Error(`No task store provided.`);let i={...r,task:{store:r.task.store,requestedTtl:r.task?.requestedTtl}};return e?n.createTask(t,i):n.createTask(i)}}if(e){let e=t;return async(t,n)=>e(t,n)}let n=t;return async(e,t)=>n(t)}function m_(e,t,n){if(t){let r=n;return async(n,i)=>{let a=await Xd(t,n);if(!a.success)throw new U(H.InvalidParams,`Invalid arguments for prompt ${e}: ${a.error}`);return r(a.data,i)}}{let e=n;return async(t,n)=>e(n)}}function h_(e){return{completion:{values:e.map(String).slice(0,100),total:e.length,hasMore:e.length>100}}}function g_(e){let t=e;if(t.shape&&typeof t.shape==`object`)return t.shape}function __(e){return e?.type===`optional`}function v_(e){return __(e)?e.def?.innerType??e:e}function y_(e,t){if(!e)return{ok:!1,errorCode:`missing_host`,message:`Missing Host header`};let n;try{n=new URL(`http://${e}`).hostname}catch{return{ok:!1,errorCode:`invalid_host_header`,message:`Invalid Host header: ${e}`,hostHeader:e}}return t.includes(n)?{ok:!0,hostname:n}:{ok:!1,errorCode:`invalid_host`,message:`Invalid Host: ${n}`,hostHeader:e,hostname:n}}function b_(){return[`localhost`,`127.0.0.1`,`[::1]`]}function x_(e,t){let n=y_(e.headers.get(`host`),t);if(!n.ok)return Response.json({jsonrpc:`2.0`,error:{code:-32e3,message:n.message},id:null},{status:403,headers:{"Content-Type":`application/json`}})}function S_(e,t){return $d(e,t??(F_??=new n_))}var C_,w_,T_,E_,D_,O_,k_,A_,j_,M_,N_,P_,F_,I_=F((()=>{r_(),o_(),C_=Symbol.for(`mcp.completable`),w_=class{tasks=new Map;cleanupTimers=new Map;generateTaskId(){return crypto.randomUUID().replaceAll(`-`,``)}async createTask(e,t,n,r){let i=this.generateTaskId();if(this.tasks.has(i))throw Error(`Task with ID ${i} already exists`);let a=e.ttl??null,o=new Date().toISOString(),s={taskId:i,status:`working`,ttl:a,createdAt:o,lastUpdatedAt:o,pollInterval:e.pollInterval??1e3};if(this.tasks.set(i,{task:s,request:n,requestId:t,sessionId:r}),a){let e=setTimeout(()=>{this.tasks.delete(i),this.cleanupTimers.delete(i)},a);this.cleanupTimers.set(i,e)}return s}getStoredTask(e,t){let n=this.tasks.get(e);if(n&&(t===void 0||n.sessionId===void 0||n.sessionId===t))return n}async getTask(e,t){let n=this.getStoredTask(e,t);return n?{...n.task}:null}async storeTaskResult(e,t,n,r){let i=this.getStoredTask(e,r);if(!i)throw Error(`Task with ID ${e} not found`);if(Fd(i.task.status))throw Error(`Cannot store result for task ${e} in terminal status '${i.task.status}'. Task results can only be stored once.`);if(i.result=n,i.task.status=t,i.task.lastUpdatedAt=new Date().toISOString(),i.task.ttl){let t=this.cleanupTimers.get(e);t&&clearTimeout(t);let n=setTimeout(()=>{this.tasks.delete(e),this.cleanupTimers.delete(e)},i.task.ttl);this.cleanupTimers.set(e,n)}}async getTaskResult(e,t){let n=this.getStoredTask(e,t);if(!n)throw Error(`Task with ID ${e} not found`);if(!n.result)throw Error(`Task ${e} has no result stored`);return n.result}async updateTaskStatus(e,t,n,r){let i=this.getStoredTask(e,r);if(!i)throw Error(`Task with ID ${e} not found`);if(Fd(i.task.status))throw Error(`Cannot update task ${e} from terminal status '${i.task.status}' to '${t}'. Terminal states (completed, failed, cancelled) cannot transition to other states.`);if(i.task.status=t,n&&(i.task.statusMessage=n),i.task.lastUpdatedAt=new Date().toISOString(),Fd(t)&&i.task.ttl){let t=this.cleanupTimers.get(e);t&&clearTimeout(t);let n=setTimeout(()=>{this.tasks.delete(e),this.cleanupTimers.delete(e)},i.task.ttl);this.cleanupTimers.set(e,n)}}async listTasks(e,t){let n=[...this.tasks.entries()].filter(([,e])=>t===void 0||e.sessionId===void 0||e.sessionId===t).map(([e])=>e),r=0;if(e){let t=n.indexOf(e);if(t===-1)throw Error(`Invalid cursor: ${e}`);r=t+1}let i=n.slice(r,r+10);return{tasks:i.map(e=>({...this.tasks.get(e).task})),nextCursor:r+10<n.length?i.at(-1):void 0}}cleanup(){for(let e of this.cleanupTimers.values())clearTimeout(e);this.cleanupTimers.clear(),this.tasks.clear()}getAllTasks(){return[...this.tasks.values()].map(e=>({...e.task}))}},T_=class{queues=new Map;getQueueKey(e,t){return e}getQueue(e,t){let n=this.getQueueKey(e,t),r=this.queues.get(n);return r||(r=[],this.queues.set(n,r)),r}async enqueue(e,t,n,r){let i=this.getQueue(e,n);if(r!==void 0&&i.length>=r)throw Error(`Task message queue overflow: queue size (${i.length}) exceeds maximum (${r})`);i.push(t)}async dequeue(e,t){return this.getQueue(e,t).shift()}async dequeueAll(e,t){let n=this.getQueueKey(e,t),r=this.queues.get(n)??[];return this.queues.delete(n),r}},E_=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,n){let r={taskSupport:`required`,...t.execution};if(r.taskSupport===`forbidden`)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,r,t._meta,n)}},D_=class{constructor(e){this._server=e}get _module(){return this._server.taskManager}requestStream(e,t){let n=Dd(e.method);return this._module.requestStream(e,n,t)}createMessageStream(e,t){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new V(B.CapabilityNotSupported,`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages.at(-1),n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages.at(-2):void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return this.requestStream({method:`sampling/createMessage`,params:e},t)}elicitInputStream(e,t){let n=this._server.getClientCapabilities(),r=e.mode??`form`;switch(r){case`url`:if(!n?.elicitation?.url)throw new V(B.CapabilityNotSupported,`Client does not support url elicitation.`);break;case`form`:if(!n?.elicitation?.form)throw new V(B.CapabilityNotSupported,`Client does not support form elicitation.`)}let i=r===`form`&&e.mode!==`form`?{...e,mode:`form`}:e;return this.requestStream({method:`elicitation/create`,params:i},t)}async getTask(e,t){return this._module.getTask({taskId:e},t)}async getTaskResult(e,t){return this._module.getTaskResult({taskId:e},wp,t)}async listTasks(e,t){return this._module.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._module.cancelTask({taskId:e},t)}},O_=class extends Ah{_clientCapabilities;_clientVersion;_capabilities;_instructions;_jsonSchemaValidator;_experimental;oninitialized;constructor(e,t){if(super({...t,tasks:Id(t?.capabilities?.tasks)}),this._serverInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new n_,t?.capabilities?.tasks){let{taskStore:e,taskMessageQueue:n,defaultTaskPollInterval:r,maxTaskQueueSize:i,...a}=t.capabilities.tasks;this._capabilities.tasks=a}this.setRequestHandler(`initialize`,e=>this._oninitialize(e)),this.setNotificationHandler(`notifications/initialized`,()=>this.oninitialized?.()),this._capabilities.logging&&this._registerLoggingHandler()}_registerLoggingHandler(){this.setRequestHandler(`logging/setLevel`,async(e,t)=>{let n=t.sessionId||t.http?.req?.headers.get(`mcp-session-id`)||void 0,{level:r}=e.params,i=Pd(Cm,r);return i.success&&this._loggingLevels.set(n,i.data),{}})}buildContext(e,t){let n=e.http||t?.request||t?.closeSSEStream||t?.closeStandaloneSSEStream;return{...e,mcpReq:{...e.mcpReq,log:(e,t,n)=>this.sendLoggingMessage({level:e,data:t,logger:n}),elicitInput:(e,t)=>this.elicitInput(e,t),requestSampling:(e,t)=>this.createMessage(e,t)},http:n?{...e.http,req:t?.request,closeSSE:t?.closeSSEStream,closeStandaloneSSE:t?.closeStandaloneSSEStream}:void 0}}get experimental(){return this._experimental||={tasks:new D_(this)},this._experimental}_loggingLevels=new Map;LOG_LEVEL_SEVERITY=new Map(Cm.options.map((e,t)=>[e,t]));isMessageIgnored=(e,t)=>{let n=this._loggingLevels.get(t);return n?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n):!1};registerCapabilities(e){if(this.transport)throw new V(B.AlreadyConnected,`Cannot register capabilities after connecting to transport`);let t=!!this._capabilities.logging;this._capabilities=Rd(this._capabilities,e),!t&&this._capabilities.logging&&this._registerLoggingHandler()}setRequestHandler(e,t){return e===`tools/call`?super.setRequestHandler(e,async(e,n)=>{let r=Pd(xm,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new U(H.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=Pd(vp,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new U(H.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=Pd(ym,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new U(H.InvalidParams,`Invalid tools/call result: ${e}`)}return o.data}):super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw new V(B.CapabilityNotSupported,`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw new V(B.CapabilityNotSupported,`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw new V(B.CapabilityNotSupported,`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw new V(B.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw new V(B.CapabilityNotSupported,`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw new V(B.CapabilityNotSupported,`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw new V(B.CapabilityNotSupported,`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw new V(B.CapabilityNotSupported,`Client does not support URL elicitation (required for ${e})`)}}assertRequestHandlerCapability(e){switch(e){case`completion/complete`:if(!this._capabilities.completions)throw new V(B.CapabilityNotSupported,`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw new V(B.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw new V(B.CapabilityNotSupported,`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw new V(B.CapabilityNotSupported,`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw new V(B.CapabilityNotSupported,`Server does not support tools (required for ${e})`)}}assertTaskCapability(e){f_(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){d_(this._capabilities?.tasks?.requests,e,`Server`)}async _oninitialize(e){let t=e.params.protocolVersion;this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo;let n=this._supportedProtocolVersions.includes(t)?t:this._supportedProtocolVersions[0]??`2025-11-25`;return this.transport?.setProtocolVersion?.(n),{protocolVersion:n,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this._requestWithSchema({method:`ping`},Kf)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new V(B.CapabilityNotSupported,`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages.at(-1),n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages.at(-2):void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw new U(H.InvalidParams,`The last message must contain only tool_result content if any is present`);if(!o)throw new U(H.InvalidParams,`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw new U(H.InvalidParams,`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return e.tools?this._requestWithSchema({method:`sampling/createMessage`,params:e},Rm,t):this._requestWithSchema({method:`sampling/createMessage`,params:e},Lm,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw new V(B.CapabilityNotSupported,`Client does not support url elicitation.`);let n=e;return this._requestWithSchema({method:`elicitation/create`,params:n},rh,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw new V(B.CapabilityNotSupported,`Client does not support form elicitation.`);let n=e.mode===`form`?e:{...e,mode:`form`},r=await this._requestWithSchema({method:`elicitation/create`,params:n},rh,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new U(H.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof U?e:new U(H.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw new V(B.CapabilityNotSupported,`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this._requestWithSchema({method:`roots/list`,params:e},dh,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}},k_=class{server;_registeredResources={};_registeredResourceTemplates={};_registeredTools={};_registeredPrompts={};_experimental;constructor(e,t){this.server=new O_(e,t)}get experimental(){return this._experimental||={tasks:new E_(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}_toolHandlersInitialized=!1;setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(`tools/list`),this.server.assertCanSetRequestHandler(`tools/call`),this.server.registerCapabilities({tools:{listChanged:this.server.getCapabilities().tools?.listChanged??!0}}),this.server.setRequestHandler(`tools/list`,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:t.inputSchema?Jd(t.inputSchema,`input`):j_,annotations:t.annotations,execution:t.execution,_meta:t._meta};return t.outputSchema&&(n.outputSchema=Jd(t.outputSchema,`output`)),n})})),this.server.setRequestHandler(`tools/call`,async(e,t)=>{let n=this._registeredTools[e.params.name];if(!n)throw new U(H.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new U(H.InvalidParams,`Tool ${e.params.name} disabled`);try{let r=!!e.params.task,i=n.execution?.taskSupport,a=`createTask`in n.handler;if((i===`required`||i===`optional`)&&!a)throw new U(H.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new U(H.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i===`optional`&&!r&&a)return await this.handleAutomaticTaskPolling(n,e,t);let o=await this.validateToolInput(n,e.params.arguments,e.params.name),s=await this.executeToolHandler(n,o,t);return r||await this.validateToolOutput(n,s,e.params.name),s}catch(e){if(e instanceof U&&e.code===H.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,n){if(!e.inputSchema)return;let r=await Xd(e.inputSchema,t??{});if(!r.success)throw new U(H.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${r.error}`);return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema||!(`content`in t)||t.isError)return;if(!t.structuredContent)throw new U(H.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await Xd(e.outputSchema,t.structuredContent);if(!r.success)throw new U(H.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${r.error}`)}async executeToolHandler(e,t,n){return e.executor(t,n)}async handleAutomaticTaskPolling(e,t,n){if(!n.task?.store)throw Error(`No task store provided for task-capable tool.`);let r=await this.validateToolInput(e,t.params.arguments,t.params.name),i=await e.executor(r,n),a=i.task.taskId,o=i.task,s=o.pollInterval??5e3;for(;o.status!==`completed`&&o.status!==`failed`&&o.status!==`cancelled`;){await new Promise(e=>setTimeout(e,s));let e=await n.task.store.getTask(a);if(!e)throw new U(H.InternalError,`Task ${a} not found during polling`);o=e}return await n.task.store.getTaskResult(a)}_completionHandlerInitialized=!1;setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(`completion/complete`),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(`completion/complete`,async e=>{switch(e.params.ref.type){case`ref/prompt`:return Md(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return Nd(e),this.handleResourceCompletion(e,e.params.ref);default:throw new U(H.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new U(H.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new U(H.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return M_;let r=v_(g_(n.argsSchema)?.[e.params.argument.name]);if(!l_(r))return M_;let i=u_(r);return i?h_(await i(e.params.argument.value,e.params.context)):M_}async handleResourceCompletion(e,t){let n=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return M_;throw new U(H.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?h_(await r(e.params.argument.value,e.params.context)):M_}_resourceHandlersInitialized=!1;setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(`resources/list`),this.server.assertCanSetRequestHandler(`resources/templates/list`),this.server.assertCanSetRequestHandler(`resources/read`),this.server.registerCapabilities({resources:{listChanged:this.server.getCapabilities().resources?.listChanged??!0}}),this.server.setRequestHandler(`resources/list`,async(e,t)=>{let n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let n=await e.resourceTemplate.listCallback(t);for(let t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}}),this.server.setRequestHandler(`resources/templates/list`,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(`resources/read`,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new U(H.InvalidParams,`Resource ${n} disabled`);return r.readCallback(n,t)}for(let e of Object.values(this._registeredResourceTemplates)){let r=e.resourceTemplate.uriTemplate.match(n.toString());if(r)return e.readCallback(n,r,t)}throw new U(H.ResourceNotFound,`Resource ${n} not found`)}),!0)}_promptHandlersInitialized=!1;setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(`prompts/list`),this.server.assertCanSetRequestHandler(`prompts/get`),this.server.registerCapabilities({prompts:{listChanged:this.server.getCapabilities().prompts?.listChanged??!0}}),this.server.setRequestHandler(`prompts/list`,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?Zd(t.argsSchema):void 0,_meta:t._meta}))})),this.server.setRequestHandler(`prompts/get`,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new U(H.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new U(H.InvalidParams,`Prompt ${e.params.name} disabled`);return n.handler(e.params.arguments,t)}),!0)}registerResource(e,t,n,r){if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,t,n,r,i){let a={name:e,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=a)),e.name!==void 0&&(a.name=e.name),e.title!==void 0&&(a.title=e.title),e.metadata!==void 0&&(a.metadata=e.metadata),e.callback!==void 0&&(a.readCallback=e.callback),e.enabled!==void 0&&(a.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,t,n,r,i){let a={resourceTemplate:n,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.template!==void 0&&(a.resourceTemplate=t.template),t.metadata!==void 0&&(a.metadata=t.metadata),t.callback!==void 0&&(a.readCallback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let o=n.uriTemplate.variableNames;return Array.isArray(o)&&o.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,t,n,r,i,a){let o=r,s=i,c={title:t,description:n,argsSchema:r,_meta:a,handler:m_(e,r,i),enabled:!0,disable:()=>c.update({enabled:!1}),enable:()=>c.update({enabled:!0}),remove:()=>c.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=c)),t.title!==void 0&&(c.title=t.title),t.description!==void 0&&(c.description=t.description),t._meta!==void 0&&(c._meta=t._meta);let n=!1;t.argsSchema!==void 0&&(c.argsSchema=t.argsSchema,o=t.argsSchema,n=!0),t.callback!==void 0&&(s=t.callback,n=!0),n&&(c.handler=m_(e,o,s)),t.enabled!==void 0&&(c.enabled=t.enabled),this.sendPromptListChanged()}};if(this._registeredPrompts[e]=c,r){let e=g_(r);e&&Object.values(e).some(e=>l_(v_(e)))&&this.setCompletionRequestHandler()}return c}_createRegisteredTool(e,t,n,r,i,a,o,s,c){Gd(e);let l=c,u={title:t,description:n,inputSchema:r,outputSchema:i,annotations:a,execution:o,_meta:s,handler:c,executor:p_(r,c),enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&Gd(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=u)),t.title!==void 0&&(u.title=t.title),t.description!==void 0&&(u.description=t.description);let n=!1;t.paramsSchema!==void 0&&(u.inputSchema=t.paramsSchema,n=!0),t.callback!==void 0&&(u.handler=t.callback,l=t.callback,n=!0),n&&(u.executor=p_(u.inputSchema,l)),t.outputSchema!==void 0&&(u.outputSchema=t.outputSchema),t.annotations!==void 0&&(u.annotations=t.annotations),t._meta!==void 0&&(u._meta=t._meta),t.enabled!==void 0&&(u.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:r,description:i,inputSchema:a,outputSchema:o,annotations:s,_meta:c}=t;return this._createRegisteredTool(e,r,i,a,o,s,{taskSupport:`forbidden`},c,n)}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:r,description:i,argsSchema:a,_meta:o}=t,s=this._createRegisteredPrompt(e,r,i,a,n,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},A_=class{_uriTemplate;constructor(e,t){this._callbacks=t,this._uriTemplate=typeof e==`string`?new Lh(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}},j_={type:`object`,properties:{}},M_={completion:{values:[],hasMore:!1}},N_=class{_readBuffer=new jh;_started=!1;_closed=!1;constructor(e=a_.stdin,t=a_.stdout){this._stdin=e,this._stdout=t}onclose;onerror;onmessage;_ondata=e=>{this._readBuffer.append(e),this.processReadBuffer()};_onerror=e=>{this.onerror?.(e)};_onstdouterror=e=>{this.onerror?.(e),this.close().catch(()=>{})};async start(){if(this._started)throw Error(`StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.`);this._started=!0,this._stdin.on(`data`,this._ondata),this._stdin.on(`error`,this._onerror),this._stdout.on(`error`,this._onstdouterror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._closed||(this._closed=!0,this._stdin.off(`data`,this._ondata),this._stdin.off(`error`,this._onerror),this._stdout.off(`error`,this._onstdouterror),this._stdin.listenerCount(`data`)===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.())}send(e){return this._closed?Promise.reject(Error(`StdioServerTransport is closed`)):new Promise((t,n)=>{let r=Hd(e),i=!1,a=e=>{i||(i=!0,this._stdout.off(`error`,a),this._stdout.off(`drain`,o),n(e))},o=()=>{i||(i=!0,this._stdout.off(`error`,a),this._stdout.off(`drain`,o),t())};if(this._stdout.once(`error`,a),this._stdout.write(r)){if(i)return;i=!0,this._stdout.off(`error`,a),t()}else i||this._stdout.once(`drain`,o)})}},P_=class{sessionIdGenerator;_started=!1;_streamMapping=new Map;_requestToStreamMapping=new Map;_requestResponseMap=new Map;_initialized=!1;_enableJsonResponse=!1;_standaloneSseStreamId=`_GET_stream`;_eventStore;_onsessioninitialized;_onsessionclosed;_allowedHosts;_allowedOrigins;_enableDnsRebindingProtection;_retryInterval;_supportedProtocolVersions;sessionId;onclose;onerror;onmessage;constructor(e={}){this.sessionIdGenerator=e.sessionIdGenerator,this._enableJsonResponse=e.enableJsonResponse??!1,this._eventStore=e.eventStore,this._onsessioninitialized=e.onsessioninitialized,this._onsessionclosed=e.onsessionclosed,this._allowedHosts=e.allowedHosts,this._allowedOrigins=e.allowedOrigins,this._enableDnsRebindingProtection=e.enableDnsRebindingProtection??!1,this._retryInterval=e.retryInterval,this._supportedProtocolVersions=e.supportedProtocolVersions??yf}async start(){if(this._started)throw Error(`Transport already started`);this._started=!0}setSupportedProtocolVersions(e){this._supportedProtocolVersions=e}createJsonErrorResponse(e,t,n,r){let i={code:t,message:n};return r?.data!==void 0&&(i.data=r.data),Response.json({jsonrpc:`2.0`,error:i,id:null},{status:e,headers:{"Content-Type":`application/json`,...r?.headers}})}validateRequestHeaders(e){if(this._enableDnsRebindingProtection){if(this._allowedHosts&&this._allowedHosts.length>0){let t=e.headers.get(`host`);if(!t||!this._allowedHosts.includes(t)){let e=`Invalid Host header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let t=e.headers.get(`origin`);if(t&&!this._allowedOrigins.includes(t)){let e=`Invalid Origin header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}}}async handleRequest(e,t){let n=this.validateRequestHeaders(e);if(n)return n;switch(e.method){case`POST`:return this.handlePostRequest(e,t);case`GET`:return this.handleGetRequest(e);case`DELETE`:return this.handleDeleteRequest(e);default:return this.handleUnsupportedRequest()}}async writePrimingEvent(e,t,n,r){if(!this._eventStore||r<`2025-11-25`)return;let i=await this._eventStore.storeEvent(n,{}),a=`id: ${i}\ndata: \n\n`;this._retryInterval!==void 0&&(a=`id: ${i}\nretry: ${this._retryInterval}\ndata: \n\n`),e.enqueue(t.encode(a))}async handleGetRequest(e){if(!e.headers.get(`accept`)?.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept text/event-stream`);let t=this.validateSession(e);if(t)return t;let n=this.validateProtocolVersion(e);if(n)return n;if(this._eventStore){let t=e.headers.get(`last-event-id`);if(t)return this.replayEvents(t)}if(this._streamMapping.get(this._standaloneSseStreamId)!==void 0)return this.onerror?.(Error(`Conflict: Only one SSE stream is allowed per session`)),this.createJsonErrorResponse(409,-32e3,`Conflict: Only one SSE stream is allowed per session`);let r=new TextEncoder,i,a=new ReadableStream({start:e=>{i=e},cancel:()=>{this._streamMapping.delete(this._standaloneSseStreamId)}}),o={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`};return this.sessionId!==void 0&&(o[`mcp-session-id`]=this.sessionId),this._streamMapping.set(this._standaloneSseStreamId,{controller:i,encoder:r,cleanup:()=>{this._streamMapping.delete(this._standaloneSseStreamId);try{i.close()}catch{}}}),new Response(a,{headers:o})}async replayEvents(e){if(!this._eventStore)return this.onerror?.(Error(`Event store not configured`)),this.createJsonErrorResponse(400,-32e3,`Event store not configured`);try{let t;if(this._eventStore.getStreamIdForEventId){if(t=await this._eventStore.getStreamIdForEventId(e),!t)return this.onerror?.(Error(`Invalid event ID format`)),this.createJsonErrorResponse(400,-32e3,`Invalid event ID format`);if(this._streamMapping.get(t)!==void 0)return this.onerror?.(Error(`Conflict: Stream already has an active connection`)),this.createJsonErrorResponse(409,-32e3,`Conflict: Stream already has an active connection`)}let n={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`};this.sessionId!==void 0&&(n[`mcp-session-id`]=this.sessionId);let r=new TextEncoder,i,a=new ReadableStream({start:e=>{i=e},cancel:()=>{}}),o=await this._eventStore.replayEventsAfter(e,{send:async(e,t)=>{if(!this.writeSSEEvent(i,r,t,e))try{i.close()}catch{}}});return this._streamMapping.set(o,{controller:i,encoder:r,cleanup:()=>{this._streamMapping.delete(o);try{i.close()}catch{}}}),new Response(a,{headers:n})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(500,-32e3,`Error replaying events`)}}writeSSEEvent(e,t,n,r){try{let i=`event: message
184
- `;return r&&(i+=`id: ${r}\n`),i+=`data: ${JSON.stringify(n)}\n\n`,e.enqueue(t.encode(i)),!0}catch(e){return this.onerror?.(e),!1}}handleUnsupportedRequest(){return this.onerror?.(Error(`Method not allowed.`)),Response.json({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null},{status:405,headers:{Allow:`GET, POST, DELETE`,"Content-Type":`application/json`}})}async handlePostRequest(e,t){try{let n=e.headers.get(`accept`);if(!n?.includes(`application/json`)||!n.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept both application/json and text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept both application/json and text/event-stream`);let r=e.headers.get(`content-type`);if(!r||!r.includes(`application/json`))return this.onerror?.(Error(`Unsupported Media Type: Content-Type must be application/json`)),this.createJsonErrorResponse(415,-32e3,`Unsupported Media Type: Content-Type must be application/json`);let i=e,a;if(t?.parsedBody===void 0)try{a=await e.json()}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON`)}else a=t.parsedBody;let o;try{o=Array.isArray(a)?a.map(e=>Gf.parse(e)):[Gf.parse(a)]}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON-RPC message`)}let s=o.some(e=>Th(e));if(s){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(Error(`Invalid Request: Server already initialized`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Server already initialized`);if(o.length>1)return this.onerror?.(Error(`Invalid Request: Only one initialization request is allowed`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Only one initialization request is allowed`);this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!s){let t=this.validateSession(e);if(t)return t;let n=this.validateProtocolVersion(e);if(n)return n}if(!o.some(e=>bh(e))){for(let e of o)this.onmessage?.(e,{authInfo:t?.authInfo,request:i});return new Response(null,{status:202})}let c=crypto.randomUUID(),l=o.find(e=>Th(e)),u=l?l.params.protocolVersion:e.headers.get(`mcp-protocol-version`)??`2025-03-26`;if(this._enableJsonResponse)return new Promise(e=>{this._streamMapping.set(c,{resolveJson:e,cleanup:()=>{this._streamMapping.delete(c)}});for(let e of o)bh(e)&&this._requestToStreamMapping.set(e.id,c);for(let e of o)this.onmessage?.(e,{authInfo:t?.authInfo,request:i})});let d=new TextEncoder,f,p=new ReadableStream({start:e=>{f=e},cancel:()=>{this._streamMapping.delete(c)}}),m={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`};this.sessionId!==void 0&&(m[`mcp-session-id`]=this.sessionId);for(let e of o)bh(e)&&(this._streamMapping.set(c,{controller:f,encoder:d,cleanup:()=>{this._streamMapping.delete(c);try{f.close()}catch{}}}),this._requestToStreamMapping.set(e.id,c));await this.writePrimingEvent(f,d,c,u);for(let e of o){let n,r;bh(e)&&this._eventStore&&u>=`2025-11-25`&&(n=()=>{this.closeSSEStream(e.id)},r=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(e,{authInfo:t?.authInfo,request:i,closeSSEStream:n,closeStandaloneSSEStream:r})}return new Response(p,{status:200,headers:m})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error`,{data:String(e)})}}async handleDeleteRequest(e){return this.validateSession(e)||this.validateProtocolVersion(e)||(await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200}))}validateSession(e){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(Error(`Bad Request: Server not initialized`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Server not initialized`);let t=e.headers.get(`mcp-session-id`);if(!t)return this.onerror?.(Error(`Bad Request: Mcp-Session-Id header is required`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Mcp-Session-Id header is required`);if(t!==this.sessionId)return this.onerror?.(Error(`Session not found`)),this.createJsonErrorResponse(404,-32001,`Session not found`)}validateProtocolVersion(e){let t=e.headers.get(`mcp-protocol-version`);if(t!==null&&!this._supportedProtocolVersions.includes(t)){let e=`Bad Request: Unsupported protocol version: ${t} (supported versions: ${this._supportedProtocolVersions.join(`, `)})`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(400,-32e3,e)}}async close(){for(let{cleanup:e}of this._streamMapping.values())e();this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(e){let t=this._requestToStreamMapping.get(e);if(!t)return;let n=this._streamMapping.get(t);n&&n.cleanup()}closeStandaloneSSEStream(){let e=this._streamMapping.get(this._standaloneSseStreamId);e&&e.cleanup()}async send(e,t){let n=t?.relatedRequestId;if((Sh(e)||Ch(e))&&(n=e.id),n===void 0){if(Sh(e)||Ch(e))throw Error(`Cannot send a response on a standalone SSE stream unless resuming a previous client request`);let t;this._eventStore&&(t=await this._eventStore.storeEvent(this._standaloneSseStreamId,e));let n=this._streamMapping.get(this._standaloneSseStreamId);if(n===void 0)return;n.controller&&n.encoder&&this.writeSSEEvent(n.controller,n.encoder,e,t);return}let r=this._requestToStreamMapping.get(n);if(!r)throw Error(`No connection established for request ID: ${String(n)}`);let i=this._streamMapping.get(r);if(!this._enableJsonResponse&&i?.controller&&i?.encoder){let t;this._eventStore&&(t=await this._eventStore.storeEvent(r,e)),this.writeSSEEvent(i.controller,i.encoder,e,t)}if(Sh(e)||Ch(e)){this._requestResponseMap.set(n,e);let t=[...this._requestToStreamMapping.entries()].filter(([e,t])=>t===r).map(([e])=>e);if(t.every(e=>this._requestResponseMap.has(e))){if(!i)throw Error(`No connection established for request ID: ${String(n)}`);if(this._enableJsonResponse&&i.resolveJson){let e={"Content-Type":`application/json`};this.sessionId!==void 0&&(e[`mcp-session-id`]=this.sessionId);let n=t.map(e=>this._requestResponseMap.get(e));n.length===1?i.resolveJson(Response.json(n[0],{status:200,headers:e})):i.resolveJson(Response.json(n,{status:200,headers:e}))}else i.cleanup();for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e)}}}}}));async function L_(e,t,n,r={}){let i=z_(),a=await Promise.resolve().then(()=>(I_(),s_)),{fromJsonSchema:o,McpServer:s}=a,c=await R_(a,i),l=new s({name:e,...r.title?{title:r.title}:void 0,version:t},r.instructions?{instructions:r.instructions}:void 0);V_(l,n,{env:r.env,fromJsonSchema:o,middlewares:r.middlewares,name:e,sendNotification:e=>l.server.notification(e),tools:r.tools,vars:r.vars,version:t});let u=new c(r.input??process.stdin,r.output??process.stdout);await l.connect(u)}async function R_(e,t){let n=e.StdioServerTransport;if(n)return n;let r=await t;if(r.error)throw r.error;return r.module.StdioServerTransport}function z_(){return Promise.resolve().then(()=>(I_(),s_)).then(e=>({module:e})).catch(e=>({error:e}))}async function B_(e,t,n={}){let r=[...n.middlewares??[],...e.middlewares??[],...e.command.middleware??[]],i=await Kl(e.command,{agent:!0,argv:[],env:n.env,format:`json`,formatExplicit:!0,inputOptions:t,middlewares:r,name:n.name??e.name,parseMode:`flat`,path:e.name,request:n.request,vars:n.vars,version:n.version});if(`stream`in i){let e=[],t=n.extra?.mcpReq?._meta?.progressToken,r=0;try{for await(let a of i.stream)e.push(a),t!==void 0&&n.sendNotification&&await n.sendNotification({method:`notifications/progress`,params:{progressToken:t,progress:++r,message:Rr(a)}})}catch(e){return{content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],isError:!0}}return{content:[{type:`text`,text:Rr(e)}]}}if(!i.ok){let t=_u(n.name??e.name,i.cta),r=i.error.fieldErrors?JSON.stringify(i.error):i.error.message??`Command failed`;return{content:[{type:`text`,text:t?`${r}\n\n${vu(t)}`:r}],...t?{_meta:{cta:t}}:void 0,isError:!0}}let a=i.data??null,o=zr(a),s=_u(n.name??e.name,i.cta),c=Rr(o);return{content:[{type:`text`,text:s?`${c}\n\n${vu(s)}`:c}],...a!==null&&e.outputSchema?{structuredContent:o}:void 0,...s?{_meta:{cta:s}}:void 0}}function V_(e,t,n){let r=X_(t,[],[],n.tools);if(r.length!==0){if((n.tools?.discovery??`progressive`)===`direct`){for(let t of r)H_(e,t,n);return}U_(e,r,n)}}function H_(e,t,n){let r={...t.command.args?.shape,...t.command.options?.shape},i=Object.keys(r).length>0;e.registerTool(t.name,{...t.description?{description:t.description}:void 0,...i?{inputSchema:f.object(r)}:void 0,...t.outputSchema?{outputSchema:n.fromJsonSchema(t.outputSchema)}:void 0,...t.annotations?{annotations:t.annotations}:void 0,...t.instructions?{_meta:{instructions:t.instructions}}:void 0},async(...e)=>B_(t,i?e[0]:{},W_(n,i?e[1]:e[0])))}function U_(e,t,n){let r=new Map(t.map(e=>[e.name,e]));e.registerTool(`search_tools`,{description:`Search or page through available tools by capability. Returns names and descriptions without loading their schemas. Inspect a result before calling it.`,inputSchema:f.object({limit:f.number().int().min(1).max(20).default(5).describe(`Maximum matches.`),offset:f.number().int().min(0).default(0).describe(`Matches to skip.`),query:f.string().default(``).describe(`Capability to find. Empty lists all tools.`)}),annotations:av},async e=>{let n=G_(t,e.query),r=n.slice(e.offset,e.offset+e.limit);return J_({tools:r.map(e=>({name:e.name,...e.description?{description:e.description}:void 0,...e.annotations?{annotations:e.annotations}:void 0})),...e.offset+r.length<n.length?{nextOffset:e.offset+r.length}:void 0})}),e.registerTool(`get_tool_details`,{description:`Inspect one tool returned by search_tools. Returns its complete input schema and metadata.`,inputSchema:f.object({name:f.string().min(1).describe(`Exact tool name.`)}),annotations:av},async e=>{let t=r.get(e.name);return t?J_({name:t.name,...t.description?{description:t.description}:void 0,inputSchema:t.inputSchema,...t.outputSchema?{outputSchema:t.outputSchema}:void 0,...t.annotations?{annotations:t.annotations}:void 0,...t.instructions?{instructions:t.instructions}:void 0}):Y_(`Unknown tool: ${e.name}`)}),e.registerTool(`call_read_tool`,{description:`Execute a tool marked read-only after inspecting its schema with get_tool_details.`,inputSchema:iv,annotations:ov},async(e,t)=>{let i=r.get(e.name);return i?i.annotations?.readOnlyHint===!0?B_(i,e.arguments,W_(n,t)):Y_(`Tool is not read-only: ${e.name}`):Y_(`Unknown tool: ${e.name}`)}),e.registerTool(`call_write_tool`,{description:`Execute a writable or unclassified tool after inspecting its schema with get_tool_details.`,inputSchema:iv,annotations:sv},async(e,t)=>{let i=r.get(e.name);return i?i.annotations?.readOnlyHint===!0?Y_(`Tool is read-only: ${e.name}`):B_(i,e.arguments,W_(n,t)):Y_(`Unknown tool: ${e.name}`)})}function W_(e,t){return{env:e.env,extra:t,middlewares:e.middlewares,name:e.name,request:e.request?.(t),...e.sendNotification?{sendNotification:e.sendNotification}:void 0,vars:e.vars,version:e.version}}function G_(e,t){let n=q_(t),r=n.split(` `).filter(Boolean);return e.map(e=>({tool:e,score:K_(e,n,r)})).filter(({score:e})=>e>0).sort((e,t)=>t.score-e.score||e.tool.name.localeCompare(t.tool.name)).map(({tool:e})=>e)}function K_(e,t,n){let r=q_(e.name),i=q_(e.description??``);if(r===t)return 1e3;let a=r.startsWith(t)?100:r.includes(t)?50:0;for(let e of n)r.split(` `).includes(e)?a+=20:r.includes(e)&&(a+=10),i.includes(e)&&(a+=2);return a}function q_(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,` `).trim()}function J_(e){return{content:[{type:`text`,text:Rr(e)}]}}function Y_(e){return{...J_({error:e}),isError:!0}}function X_(e,t,n=[],r){let i=$_(Z_(e,t,n),r);return tv(i),i.sort((e,t)=>e.name.localeCompare(t.name))}function Z_(e,t,n=[]){let r=[];for(let[i,a]of e){if(`_alias`in a||a.mcp===!1)continue;let e=[...t,i];if(`_group`in a&&a._group){let t=[...n,...a.middlewares??[]];a.root&&a.root.mcp!==!1&&r.push(Q_(a.root,e,t)),r.push(...Z_(a.commands,e,t))}else r.push(Q_(a,e,n))}return r}function Q_(e,t,n){let r=e.mcp===!1?void 0:e.mcp,i=e.output?nv(e.output):void 0;return{name:r?.name??t.join(`_`),description:r?.description??e.description,inputSchema:rv(e.args,e.options),...i?{outputSchema:i}:void 0,...r?.annotations?{annotations:r.annotations}:void 0,...r?.instructions?{instructions:r.instructions}:void 0,command:e,...n.length>0?{middlewares:n}:void 0}}function $_(e,t){if(!t)return e;let n=t.include?.map(ev),r=t.exclude?.map(ev)??[];return e.filter(e=>r.some(t=>t.test(e.name))?!1:!n||n.length===0||n.some(t=>t.test(e.name)))}function ev(e){let t=e.replace(/[|\\{}()[\]^$+?.]/g,`\\$&`).replace(/\*/g,`.*`);return RegExp(`^${t}$`)}function tv(e){let t=new Set;for(let n of e){if(t.has(n.name))throw Error(`Duplicate MCP tool name: ${n.name}`);t.add(n.name)}}function nv(e){let t=ku(e);if(t.type===`object`)return t}function rv(e,t){let n={},r=[];for(let i of[e,t]){if(!i)continue;let e=ku(i);Object.assign(n,e.properties??{}),r.push(...e.required??[])}return r.length>0?{type:`object`,properties:n,required:r}:{type:`object`,properties:n}}var iv,av,ov,sv,cv=F((()=>{nu(),bu(),Br(),Au(),iv=f.object({name:f.string().min(1).describe(`Exact tool name.`),arguments:f.record(f.string(),f.unknown()).default({}).describe(`Arguments from its schema.`)}),av={destructiveHint:!1,idempotentHint:!0,openWorldHint:!1,readOnlyHint:!0},ov={destructiveHint:!1,idempotentHint:!0,openWorldHint:!0,readOnlyHint:!0},sv={destructiveHint:!0,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1}}));function lv(e){return uv(e,e,new Map)}function uv(e,t,n){if(Array.isArray(e))return e.map(e=>uv(e,t,n));if(typeof e!=`object`||!e)return e;let r=e;if(typeof r.$ref==`string`&&r.$ref.startsWith(`#`)){let e=r.$ref;if(n.has(e))return n.get(e);let i=dv(t,e);if(typeof i!=`object`||!i||Array.isArray(i)){let r=uv(i,t,n);return n.set(e,r),r}let a={};n.set(e,a);let o=uv(i,t,n);return typeof o!=`object`||!o||Array.isArray(o)?(n.set(e,o),o):(Object.assign(a,o),a)}let i={};for(let e of Object.keys(r))i[e]=uv(r[e],t,n);return i}function dv(e,t){let n=t.slice(1);if(n===``||n===`/`)return e;let r=n.slice(1).split(`/`).map(e=>e.replace(/~1/g,`/`).replace(/~0/g,`~`)),i=e;for(let e of r){if(typeof i!=`object`||!i)throw Error(`Cannot resolve $ref "${t}": path segment "${e}" not found`);if(i=i[e],i===void 0)throw Error(`Cannot resolve $ref "${t}": "${e}" not found`)}return i}var fv=F((()=>{}));function pv(e,t={}){let n=_x.get(e);if(!n)throw Error(`No commands registered on this CLI instance`);let r={},i=bx.get(e);i&&gv(r,[],i);for(let[e,t]of n)mv(r,hv(e),t);return{openapi:`3.2.0`,info:{title:t.title??e.name,version:t.version??`0.0.0`,...t.description??e.description?{description:t.description??e.description}:void 0},...t.servers?{servers:t.servers}:void 0,paths:r}}function mv(e,t,n){if(!(`_alias`in n)&&!(`_fetch`in n)){if(`_group`in n){n.root&&gv(e,t,n.root);for(let[r,i]of n.commands)mv(e,[...t,...hv(r)],i);return}gv(e,t,n)}}function hv(e){return e.split(/\s+/).filter(Boolean)}function gv(e,t,n){let r=n.args?ku(n.args):void 0,i=n.options?ku(n.options):void 0,a=n.output?ku(n.output):void 0,o=wv(r),s=new Set(Tv(r)),c=vv(t),l=_v(t,o,s);for(let r of l){let s=[];for(let e of r.args){let t=o[e]??{type:`string`};s.push({name:e,in:`path`,required:!0,schema:t})}if(c===`get`||c===`delete`)for(let[e,t]of Object.entries(wv(i)))s.push({name:e,in:`query`,...Tv(i).includes(e)?{required:!0}:void 0,schema:t});let l={operationId:Ev(t,c,r.args),...n.description?{summary:n.description}:void 0,...s.length?{parameters:s}:void 0,...bv(c,i),responses:xv(a)},u=e[r.path]??{};u[c]=l,e[r.path]=u}}function _v(e,t,n){let r=Object.keys(t),i=r.findIndex(e=>!n.has(e)),a=i===-1?r.length:i,o=[];for(let t=a;t<=r.length;t++){let n=r.slice(0,t),i=n.map(e=>`{${e}}`);o.push({args:n,path:`/${[...e,...i].map(Dv).join(`/`)}`})}return o.length===0&&o.push({args:[],path:`/${e.map(Dv).join(`/`)}`}),o}function vv(e){let t=e.map(yv).join(` `).toLowerCase();return/\b(delete|remove|rm|destroy|clear)\b/.test(t)?`delete`:/\b(update|edit|modify|set|enable|disable|rename|patch)\b/.test(t)?`patch`:/\b(get|list|show|read|search|find|status|describe|info|health|check)\b/.test(t)?`get`:`post`}function yv(e){return e.replace(/([a-z0-9])([A-Z])/g,`$1 $2`)}function bv(e,t){return!t||e===`get`||e===`delete`?{}:{requestBody:{required:Tv(t).length>0,content:{"application/json":{schema:t}}}}}function xv(e){return{200:{description:`Command completed successfully.`,content:{"application/json":{schema:{type:`object`,required:[`ok`,`data`,`meta`],properties:{ok:{const:!0},data:e??{},meta:Cv()}}}}},400:Sv(`Validation error.`),500:Sv(`Command failed.`)}}function Sv(e){return{description:e,content:{"application/json":{schema:{type:`object`,required:[`ok`,`error`,`meta`],properties:{ok:{const:!1},error:{type:`object`,required:[`code`,`message`],properties:{code:{type:`string`},message:{type:`string`},retryable:{type:`boolean`}}},meta:Cv()}}}}}}function Cv(){return{type:`object`,required:[`command`,`duration`],properties:{command:{type:`string`},duration:{type:`string`}}}}function wv(e){return e?.properties??{}}function Tv(e){return e?.required??[]}function Ev(e,t,n){return`${t}${[...e,...n.length?[n.join(` `)]:[]].join(` `).replace(/(?:^|[\s_-]+)(\w)/g,(e,t)=>t.toUpperCase())}`}function Dv(e){return e.startsWith(`{`)&&e.endsWith(`}`)?e:encodeURIComponent(e)}async function Ov(e,t={}){if(typeof e!=`string`&&!(e instanceof URL))return e;let n=await fetch(kv(e,t.baseUrl));if(!n.ok)throw Error(`Failed to fetch OpenAPI spec from ${e}: ${n.status}`);return await n.json()}function kv(e,t){if(e instanceof URL)return e;try{return new URL(e)}catch{if(t===void 0)throw Error(`Relative OpenAPI spec URL requires a fetch URL base: ${e}`);let n=new URL(t);return n.pathname.endsWith(`/`)||(n.pathname=`${n.pathname}/`),new URL(e,n)}}async function Av(e,t,n={}){let r=lv(structuredClone(e)),i=new Map,a=Mv(r.paths??{}),o=Bv(a),{config:s}=n;s?.compact&&Fv(a);for(let{method:e,operation:c,path:l}of a){let a=Vv({method:e,mode:s?.mode??`operation`,namespaceInfo:o,operation:c,path:l}),u=e.toUpperCase(),d=(c.parameters??[]).filter(e=>e.in===`path`),p=(c.parameters??[]).filter(e=>e.in===`query`),m=Rv([...(c.parameters??[]).filter(e=>e.in===`header`),...s?.security===!1?[]:Nv(r,c)]),h=c.requestBody?.content?.[`application/json`]?.schema,g=h?.properties??{},_=new Set(h?.required??[]),v;if(d.length>0){let e={};for(let t of d){let n=t.schema?Zv(t.schema):f.string();t.description&&(n=n.describe(t.description)),e[t.name]=Qv(n)}v=f.object(e)}let y={},b=new Set;for(let e of p){let t=e.schema?Zv(e.schema):f.string();e.required||(t=t.optional()),e.description&&(t=t.describe(e.description)),y[e.name]=Qv(t),b.add(e.name)}for(let[e,t]of Object.entries(g)){let n=Zv(t);_.has(e)||(n=n.optional()),y[e]=n,b.add(e)}for(let e of m){let t=zv(e.optionName,b);e.optionName=t;let n=e.schema?Zv(e.schema):f.string();e.required||(n=n.optional()),n=n.describe(e.description??`${e.name} header`),y[t]=Qv(n),b.add(t)}let x=Object.keys(y).length>0?f.object(y):void 0;Jv(i,a,{description:c.summary??c.description,mcp:{annotations:jv(e),...c.summary&&c.description&&c.summary!==c.description?{description:`${c.summary}\n\n${c.description}`}:void 0},args:v,options:x,run:Xv({basePath:n.basePath,fetch:t,forwardHeaders:s?.forwardHeaders,httpMethod:u,path:l,headerParams:m,pathParams:d,queryParams:p,bodyProps:g})})}return i}function jv(e){let t=[`get`,`head`,`options`,`trace`].includes(e);return{destructiveHint:!t,idempotentHint:t||e===`delete`||e===`put`,openWorldHint:!0,readOnlyHint:t}}function Mv(e){let t=[];for(let[n,r]of Object.entries(e))for(let[e,i]of Object.entries(r))$v.has(e)&&t.push({method:e,operation:i,path:n});return t}function Nv(e,t){let n=e.components?.securitySchemes??{},r=t.security??e.security??[],i=[];for(let e of r)for(let t of Object.keys(e)){let e=n[t],r=Pv(t,e);r&&i.push(r)}return i}function Pv(e,t){if(t){if(t.type===`apiKey`&&t.in===`header`&&t.name)return{description:t.description??`${t.name} header`,in:`header`,name:t.name,required:!1,schema:{type:`string`}};if(t.type===`http`&&ey.has(t.scheme?.toLowerCase()??``))return{description:t.description??`${e} authorization header`,in:`header`,name:`authorization`,required:!1,schema:{type:`string`}}}}function Fv(e){for(let{operation:t}of e){for(let e of t.parameters??[])e.schema&&=Iv(e.schema);let e=t.requestBody?.content?.[`application/json`];e?.schema&&(e.schema=Iv(e.schema))}}function Iv(e,t=new Map){let n=t.get(e);if(n)return n;let r={...e};t.set(e,r),delete r.example,delete r.examples,typeof r.pattern==`string`&&r.pattern.length>ty&&delete r.pattern,typeof r.format==`string`&&ny.has(r.format)&&delete r.format;for(let e of[`allOf`,`anyOf`,`oneOf`,`prefixItems`]){if(!Array.isArray(r[e]))continue;let n=r[e].map(e=>Iv(e,t)).filter(e=>Object.keys(e).length>0);n.length>0?r[e]=n:delete r[e]}for(let e of[`additionalProperties`,`contains`,`items`,`not`,`propertyNames`]){let n=r[e];Lv(n)&&(r[e]=Iv(n,t))}for(let e of[`$defs`,`patternProperties`,`properties`]){let n=r[e];if(!Lv(n))continue;let i={};for(let[e,r]of Object.entries(n))i[e]=Lv(r)?Iv(r,t):r;r[e]=i}return r}function Lv(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Rv(e){let t=new Set,n=[];for(let r of e){let e=r.name.toLowerCase();t.has(e)||(t.add(e),n.push({...r,optionName:e}))}return n}function zv(e,t){if(!t.has(e))return e;let n=`header-${e}`;if(!t.has(n))return n;for(let e=2;;e++){let r=`${n}-${e}`;if(!t.has(r))return r}}function Bv(e){let t=new Map,n=new Set;for(let{path:r}of e){t.set(r,(t.get(r)??0)+1);let e=Uv(r);for(let t=1;t<e.length;t++)n.add(`/${e.slice(0,t).join(`/`)}`)}return{parentPaths:n,pathOperations:t}}function Vv(e){let{method:t,mode:n,namespaceInfo:r,operation:i,path:a}=e;if(n===`operation`)return[{name:i.operationId??`${t}_${a.replace(/[/{}]/g,`_`)}`}];let o=Hv(a,i),s=o.length===0||r.parentPaths.has(Wv(a))||(r.pathOperations.get(a)??0)>1,c=qv(o,i.summary??i.description);return[...c.length>0?c:[{name:`root`}],...s?[{name:t}]:[]]}function Hv(e,t){return e.split(`/`).map(e=>Gv(e,t)).filter(Kv)}function Uv(e){return Hv(e).map(e=>e.name)}function Wv(e){return`/${Uv(e).join(`/`)}`}function Gv(e,t){if(!e)return;let n=e.startsWith(`{`)&&e.endsWith(`}`)?e.slice(1,-1):e,r=t?.parameters?.find(e=>e.in===`path`&&e.name===n)?.description;return{...r?{description:r}:void 0,name:n.replace(/[^\w.-]+/g,`-`)}}function Kv(e){return e!==void 0}function qv(e,t){return!t||e.length===0?e:e.map((n,r)=>r===e.length-1&&!n.description?{...n,description:t}:n)}function Jv(e,t,n){let[r,...i]=t;if(r){if(i.length===0){e.set(r.name,n);return}Jv(Yv(e,r).commands,i,n)}}function Yv(e,t){let n=e.get(t.name);if(n&&`_group`in n)return!n.description&&t.description&&(n.description=t.description),n;let r={_group:!0,commands:new Map,...t.description?{description:t.description}:void 0};return e.set(t.name,r),r}function Xv(e){return async t=>{let{args:n={},options:r={}}=t,i=(e.basePath??``)+e.path;for(let t of e.pathParams){let e=n[t.name];e!==void 0&&(i=i.replace(`{${t.name}}`,String(e)))}let a=new URLSearchParams;for(let t of e.queryParams){let e=r[t.name];e!==void 0&&a.set(t.name,String(e))}let o,s=Object.keys(e.bodyProps);if(s.length>0){let e={};for(let t of s)r[t]!==void 0&&(e[t]=r[t]);Object.keys(e).length>0&&(o=JSON.stringify(e))}let c={path:i,method:e.httpMethod,headers:new Headers,body:o,query:a};for(let t of e.headerParams){let e=r[t.optionName];e!==void 0&&c.headers.set(t.name,String(e))}for(let n of e.forwardHeaders??[]){let e=t.request?.headers.get(n);!c.headers.has(n)&&e!=null&&c.headers.set(n,e)}o&&!c.headers.has(`content-type`)&&c.headers.set(`content-type`,`application/json`);let l=kn(c),u=await Mn(await e.fetch(l));return u.ok?u.data:t.error({code:`HTTP_${u.status}`,message:typeof u.data==`object`&&u.data!==null&&`message`in u.data?String(u.data.message):typeof u.data==`string`?u.data:`HTTP ${u.status}`})}}function Zv(e){return f.fromJSONSchema(e)}function Qv(e){let t=e instanceof f.ZodOptional,n=t?e.unwrap():e,r=(()=>{if(n instanceof f.ZodNumber)return t?f.coerce.number().optional():f.coerce.number();if(n instanceof f.ZodBoolean)return t?f.coerce.boolean().optional():f.coerce.boolean();if(n instanceof f.ZodUnion){let e=n._zod?.def?.options;if(e?.some(e=>e instanceof f.ZodNumber))return t?f.coerce.number().optional():f.coerce.number();if(e?.some(e=>e instanceof f.ZodBoolean))return t?f.coerce.boolean().optional():f.coerce.boolean()}})();if(!r)return e;let i=e.description??n.description;return i?r.describe(i):r}var $v,ey,ty,ny,ry=F((()=>{Dx(),Fn(),fv(),Au(),$v=new Set([`delete`,`get`,`head`,`options`,`patch`,`post`,`put`,`trace`]),ey=new Set([`basic`,`bearer`]),ty=100,ny=new Set([`date`,`date-time`,`duration`,`time`])}));async function iy(e,t={}){let n=ly(e);await uy(n,`initialize`,{protocolVersion:gy,capabilities:{},clientInfo:{name:`incur`,version:t.version??`1.0.0`}}),n.initialized=!0,await uy(n,`notifications/initialized`);let r=(await uy(n,`tools/list`)).tools??[];return oy(r)?{discovery:`progressive`,tools:await sy(n),session:n}:{tools:r,session:n}}function ay(e){let t=new Map;for(let n of e.tools){let r=n.inputSchema?fy(n.inputSchema):void 0,i=py(n.outputSchema);t.set(n.name,{description:n.description,...n.annotations?{mcp:{annotations:n.annotations}}:void 0,...r?{options:r}:void 0,...i?{output:i}:void 0,async run(t){let r={name:n.name,arguments:{...t.args,...t.options}},i=await uy(e.session,`tools/call`,e.discovery===`progressive`?{name:n.annotations?.readOnlyHint===!0?`call_read_tool`:`call_write_tool`,arguments:r}:r);return i.isError?t.error({code:`MCP_TOOL_ERROR`,message:my(i)}):hy(i)}})}return t}function oy(e){if(e.length!==4)return!1;let t=new Set(e.map(e=>e.name));return t.has(`search_tools`)&&t.has(`get_tool_details`)&&t.has(`call_read_tool`)&&t.has(`call_write_tool`)}async function sy(e){let t=[],n=0;for(;n!==void 0;){let r=await cy(e,`search_tools`,{query:``,limit:20,offset:n});for(let n of r.tools??[]){if(!n.name)continue;let r=await cy(e,`get_tool_details`,{name:n.name});r.name&&t.push(r)}if(r.nextOffset!==void 0&&r.nextOffset<=n)throw Error(`MCP tool catalog returned a non-advancing offset`);n=r.nextOffset}return t}async function cy(e,t,n){let r=await uy(e,`tools/call`,{name:t,arguments:n});if(r.isError)throw Error(my(r)||`MCP tool failed: ${t}`);return hy(r)}function ly(e){return typeof e==`string`||e instanceof URL?{url:new URL(e),fetch:globalThis.fetch.bind(globalThis)}:{url:new URL(e.url),fetch:e.fetch??globalThis.fetch.bind(globalThis),...e.headers?{headers:e.headers}:void 0}}async function uy(e,t,n){let r=t.startsWith(`notifications/`),i=r?void 0:crypto.randomUUID(),a=new Headers(e.headers);a.set(`content-type`,`application/json`),a.set(`accept`,`application/json, text/event-stream`),e.id&&a.set(`mcp-session-id`,e.id),e.initialized&&a.set(`MCP-Protocol-Version`,gy);let o=JSON.stringify({jsonrpc:`2.0`,...i?{id:i}:void 0,method:t,params:n}),s=await e.fetch(new Request(e.url,{method:`POST`,headers:a,body:o})),c=s.headers.get(`mcp-session-id`);if(c&&(e.id=c),!s.ok)throw Error(`MCP HTTP ${s.status}`);if(r&&s.status===202)return{};let l=await s.text();if(!l)return{};let u=(s.headers.get(`content-type`)??``).includes(`text/event-stream`)?dy(l,i):JSON.parse(l);if(u.error)throw Error(u.error.message??`MCP request failed`);return u.result??{}}function dy(e,t){for(let n of e.split(/\r?\n\r?\n/)){let e=n.split(/\r?\n/).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trimStart()).join(`
183
+ deps: ${r}}`};let i={keyword:`dependencies`,type:`object`,schemaType:`object`,error:e.error,code(e){let[t,n]=a(e);o(e,t),s(e,n)}};function a({schema:e}){let t={},n={};for(let r in e){if(r===`__proto__`)continue;let i=Array.isArray(e[r])?t:n;i[r]=e[r]}return[t,n]}function o(e,n=e.schema){let{gen:i,data:a,it:o}=e;if(Object.keys(n).length===0)return;let s=i.let(`missing`);for(let c in n){let l=n[c];if(l.length===0)continue;let u=(0,r.propertyInData)(i,a,c,o.opts.ownProperties);e.setParams({property:c,depsCount:l.length,deps:l.join(`, `)}),o.allErrors?i.if(u,()=>{for(let t of l)(0,r.checkReportMissingProp)(e,t)}):(i.if((0,t._)`${u} && (${(0,r.checkMissingProp)(e,l,s)})`),(0,r.reportMissingProp)(e,s),i.else())}}e.validatePropertyDeps=o;function s(e,t=e.schema){let{gen:i,data:a,keyword:o,it:s}=e,c=i.name(`valid`);for(let l in t)(0,n.alwaysValidSchema)(s,t[l])||(i.if((0,r.propertyInData)(i,a,l,s.opts.ownProperties),()=>{let t=e.subschema({keyword:o,schemaProp:l},c);e.mergeValidEvaluated(t,c)},()=>i.var(c,!0)),e.ok(c))}e.validateSchemaDeps=s,e.default=i})),jg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G();e.default={keyword:`propertyNames`,type:`object`,schemaType:[`object`,`boolean`],error:{message:`property name must be valid`,params:({params:e})=>(0,t._)`{propertyName: ${e.propertyName}}`},code(e){let{gen:r,schema:i,data:a,it:o}=e;if((0,n.alwaysValidSchema)(o,i))return;let s=r.name(`valid`);r.forIn(`key`,a,n=>{e.setParams({propertyName:n}),e.subschema({keyword:`propertyNames`,data:n,dataTypes:[`string`],propertyName:n,compositeRule:!0},s),r.if((0,t.not)(s),()=>{e.error(!0),o.allErrors||r.break()})}),e.ok(s)}}})),Mg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=qh(),n=W(),r=Bh(),i=G();e.default={keyword:`additionalProperties`,type:[`object`],schemaType:[`boolean`,`object`],allowUndefined:!0,trackErrors:!0,error:{message:`must NOT have additional properties`,params:({params:e})=>(0,n._)`{additionalProperty: ${e.additionalProperty}}`},code(e){let{gen:a,schema:o,parentSchema:s,data:c,errsCount:l,it:u}=e;if(!l)throw Error(`ajv implementation error`);let{allErrors:d,opts:f}=u;if(u.props=!0,f.removeAdditional!==`all`&&(0,i.alwaysValidSchema)(u,o))return;let p=(0,t.allSchemaProperties)(s.properties),m=(0,t.allSchemaProperties)(s.patternProperties);h(),e.ok((0,n._)`${l} === ${r.default.errors}`);function h(){a.forIn(`key`,c,e=>{!p.length&&!m.length?v(e):a.if(g(e),()=>v(e))})}function g(r){let o;if(p.length>8){let e=(0,i.schemaRefOrVal)(u,s.properties,`properties`);o=(0,t.isOwnProperty)(a,e,r)}else o=p.length?(0,n.or)(...p.map(e=>(0,n._)`${r} === ${e}`)):n.nil;return m.length&&(o=(0,n.or)(o,...m.map(i=>(0,n._)`${(0,t.usePattern)(e,i)}.test(${r})`))),(0,n.not)(o)}function _(e){a.code((0,n._)`delete ${c}[${e}]`)}function v(t){if(f.removeAdditional===`all`||f.removeAdditional&&o===!1){_(t);return}if(o===!1){e.setParams({additionalProperty:t}),e.error(),d||a.break();return}if(typeof o==`object`&&!(0,i.alwaysValidSchema)(u,o)){let r=a.name(`valid`);f.removeAdditional===`failing`?(y(t,r,!1),a.if((0,n.not)(r),()=>{e.reset(),_(t)})):(y(t,r),d||a.if((0,n.not)(r),()=>a.break()))}}function y(t,n,r){let a={keyword:`additionalProperties`,dataProp:t,dataPropType:i.Type.Str};r===!1&&Object.assign(a,{compositeRule:!0,createErrors:!1,allErrors:!1}),e.subschema(a,n)}}}})),Ng=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=$h(),n=qh(),r=G(),i=Mg();e.default={keyword:`properties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,parentSchema:s,data:c,it:l}=e;l.opts.removeAdditional===`all`&&s.additionalProperties===void 0&&i.default.code(new t.KeywordCxt(l,i.default,`additionalProperties`));let u=(0,n.allSchemaProperties)(o);for(let e of u)l.definedProperties.add(e);l.opts.unevaluated&&u.length&&l.props!==!0&&(l.props=r.mergeEvaluated.props(a,(0,r.toHash)(u),l.props));let d=u.filter(e=>!(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0)return;let f=a.name(`valid`);for(let t of d)p(t)?m(t):(a.if((0,n.propertyInData)(a,c,t,l.opts.ownProperties)),m(t),l.allErrors||a.else().var(f,!0),a.endIf()),e.it.definedProperties.add(t),e.ok(f);function p(e){return l.opts.useDefaults&&!l.compositeRule&&o[e].default!==void 0}function m(t){e.subschema({keyword:`properties`,schemaProp:t,dataProp:t},f)}}}})),Pg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=qh(),n=W(),r=G(),i=G();e.default={keyword:`patternProperties`,type:`object`,schemaType:`object`,code(e){let{gen:a,schema:o,data:s,parentSchema:c,it:l}=e,{opts:u}=l,d=(0,t.allSchemaProperties)(o),f=d.filter(e=>(0,r.alwaysValidSchema)(l,o[e]));if(d.length===0||f.length===d.length&&(!l.opts.unevaluated||l.props===!0))return;let p=u.strictSchema&&!u.allowMatchingProperties&&c.properties,m=a.name(`valid`);l.props!==!0&&!(l.props instanceof n.Name)&&(l.props=(0,i.evaluatedPropsToName)(a,l.props));let{props:h}=l;g();function g(){for(let e of d)p&&_(e),l.allErrors?v(e):(a.var(m,!0),v(e),a.if(m))}function _(e){for(let t in p)new RegExp(e).test(t)&&(0,r.checkStrictMode)(l,`property ${t} matches pattern ${e} (use allowMatchingProperties)`)}function v(r){a.forIn(`key`,s,o=>{a.if((0,n._)`${(0,t.usePattern)(e,r)}.test(${o})`,()=>{let t=f.includes(r);t||e.subschema({keyword:`patternProperties`,schemaProp:r,dataProp:o,dataPropType:i.Type.Str},m),l.opts.unevaluated&&h!==!0?a.assign((0,n._)`${h}[${o}]`,!0):!t&&!l.allErrors&&a.if((0,n.not)(m),()=>a.break())})})}}}})),Fg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G();e.default={keyword:`not`,schemaType:[`object`,`boolean`],trackErrors:!0,code(e){let{gen:n,schema:r,it:i}=e;if((0,t.alwaysValidSchema)(i,r)){e.fail();return}let a=n.name(`valid`);e.subschema({keyword:`not`,compositeRule:!0,createErrors:!1,allErrors:!1},a),e.failResult(a,()=>e.reset(),()=>e.error())},error:{message:`must NOT be valid`}}})),Ig=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:qh().validateUnion,error:{message:`must match a schema in anyOf`}}})),Lg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G();e.default={keyword:`oneOf`,schemaType:`array`,trackErrors:!0,error:{message:`must match exactly one schema in oneOf`,params:({params:e})=>(0,t._)`{passingSchemas: ${e.passing}}`},code(e){let{gen:r,schema:i,parentSchema:a,it:o}=e;if(!Array.isArray(i))throw Error(`ajv implementation error`);if(o.opts.discriminator&&a.discriminator)return;let s=i,c=r.let(`valid`,!1),l=r.let(`passing`,null),u=r.name(`_valid`);e.setParams({passing:l}),r.block(d),e.result(c,()=>e.reset(),()=>e.error(!0));function d(){s.forEach((i,a)=>{let s;(0,n.alwaysValidSchema)(o,i)?r.var(u,!0):s=e.subschema({keyword:`oneOf`,schemaProp:a,compositeRule:!0},u),a>0&&r.if((0,t._)`${u} && ${c}`).assign(c,!1).assign(l,(0,t._)`[${l}, ${a}]`).else(),r.if(u,()=>{r.assign(c,!0),r.assign(l,a),s&&e.mergeEvaluated(s,t.Name)})})}}}})),Rg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G();e.default={keyword:`allOf`,schemaType:`array`,code(e){let{gen:n,schema:r,it:i}=e;if(!Array.isArray(r))throw Error(`ajv implementation error`);let a=n.name(`valid`);r.forEach((n,r)=>{if((0,t.alwaysValidSchema)(i,n))return;let o=e.subschema({keyword:`allOf`,schemaProp:r},a);e.ok(a),e.mergeEvaluated(o)})}}})),zg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=G(),r={keyword:`if`,schemaType:[`object`,`boolean`],trackErrors:!0,error:{message:({params:e})=>(0,t.str)`must match "${e.ifClause}" schema`,params:({params:e})=>(0,t._)`{failingKeyword: ${e.ifClause}}`},code(e){let{gen:r,parentSchema:a,it:o}=e;a.then===void 0&&a.else===void 0&&(0,n.checkStrictMode)(o,`"if" without "then" and "else" is ignored`);let s=i(o,`then`),c=i(o,`else`);if(!s&&!c)return;let l=r.let(`valid`,!0),u=r.name(`_valid`);if(d(),e.reset(),s&&c){let t=r.let(`ifClause`);e.setParams({ifClause:t}),r.if(u,f(`then`,t),f(`else`,t))}else s?r.if(u,f(`then`)):r.if((0,t.not)(u),f(`else`));e.pass(l,()=>e.error(!0));function d(){let t=e.subschema({keyword:`if`,compositeRule:!0,createErrors:!1,allErrors:!1},u);e.mergeEvaluated(t)}function f(n,i){return()=>{let a=e.subschema({keyword:n},u);r.assign(l,u),e.mergeValidEvaluated(a,l),i?r.assign(i,(0,t._)`${n}`):e.setParams({ifClause:n})}}}};function i(e,t){let r=e.schema[t];return r!==void 0&&!(0,n.alwaysValidSchema)(e,r)}e.default=r})),Bg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=G();e.default={keyword:[`then`,`else`],schemaType:[`object`,`boolean`],code({keyword:e,parentSchema:n,it:r}){n.if===void 0&&(0,t.checkStrictMode)(r,`"${e}" without "if" is ignored`)}}})),Vg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Tg(),n=Dg(),r=Eg(),i=Og(),a=kg(),o=Ag(),s=jg(),c=Mg(),l=Ng(),u=Pg(),d=Fg(),f=Ig(),p=Lg(),m=Rg(),h=zg(),g=Bg();function _(e=!1){let _=[d.default,f.default,p.default,m.default,h.default,g.default,s.default,c.default,o.default,l.default,u.default];return e?_.push(n.default,i.default):_.push(t.default,r.default),_.push(a.default),_}e.default=_})),Hg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W();e.default={keyword:`format`,type:[`number`,`string`],schemaType:`string`,$data:!0,error:{message:({schemaCode:e})=>(0,t.str)`must match format "${e}"`,params:({schemaCode:e})=>(0,t._)`{format: ${e}}`},code(e,n){let{gen:r,data:i,$data:a,schema:o,schemaCode:s,it:c}=e,{opts:l,errSchemaPath:u,schemaEnv:d,self:f}=c;if(!l.validateFormats)return;a?p():m();function p(){let a=r.scopeValue(`formats`,{ref:f.formats,code:l.code.formats}),o=r.const(`fDef`,(0,t._)`${a}[${s}]`),c=r.let(`fType`),u=r.let(`format`);r.if((0,t._)`typeof ${o} == "object" && !(${o} instanceof RegExp)`,()=>r.assign(c,(0,t._)`${o}.type || "string"`).assign(u,(0,t._)`${o}.validate`),()=>r.assign(c,(0,t._)`"string"`).assign(u,o)),e.fail$data((0,t.or)(p(),m()));function p(){return l.strictSchema===!1?t.nil:(0,t._)`${s} && !${u}`}function m(){let e=d.$async?(0,t._)`(${o}.async ? await ${u}(${i}) : ${u}(${i}))`:(0,t._)`${u}(${i})`,r=(0,t._)`(typeof ${u} == "function" ? ${e} : ${u}.test(${i}))`;return(0,t._)`${u} && ${u} !== true && ${c} === ${n} && !${r}`}}function m(){let a=f.formats[o];if(!a){m();return}if(a===!0)return;let[s,c,p]=h(a);s===n&&e.pass(g());function m(){if(l.strictSchema===!1){f.logger.warn(e());return}throw Error(e());function e(){return`unknown format "${o}" ignored in schema at path "${u}"`}}function h(e){let n=e instanceof RegExp?(0,t.regexpCode)(e):l.code.formats?(0,t._)`${l.code.formats}${(0,t.getProperty)(o)}`:void 0,i=r.scopeValue(`formats`,{key:o,ref:e,code:n});return typeof e==`object`&&!(e instanceof RegExp)?[e.type||`string`,e.validate,(0,t._)`${i}.validate`]:[`string`,e,i]}function g(){if(typeof a==`object`&&!(a instanceof RegExp)&&a.async){if(!d.$async)throw Error(`async format in sync schema`);return(0,t._)`await ${p}(${i})`}return typeof c==`function`?(0,t._)`${p}(${i})`:(0,t._)`${p}.test(${i})`}}}}})),Ug=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=[Hg().default]})),Wg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.contentVocabulary=e.metadataVocabulary=void 0,e.metadataVocabulary=[`title`,`description`,`default`,`deprecated`,`readOnly`,`writeOnly`,`examples`],e.contentVocabulary=[`contentMediaType`,`contentEncoding`,`contentSchema`]})),Gg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=dg(),n=wg(),r=Vg(),i=Ug(),a=Wg();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),Kg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.DiscrError=void 0;var t;(function(e){e.Tag=`tag`,e.Mapping=`mapping`})(t||(e.DiscrError=t={}))})),qg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=W(),n=Kg(),r=ng(),i=tg(),a=G();e.default={keyword:`discriminator`,type:`object`,schemaType:`object`,error:{message:({params:{discrError:e,tagName:t}})=>e===n.DiscrError.Tag?`tag "${t}" must be string`:`value of tag "${t}" must be in oneOf`,params:({params:{discrError:e,tag:n,tagName:r}})=>(0,t._)`{error: ${e}, tag: ${r}, tagValue: ${n}}`},code(e){let{gen:o,data:s,schema:c,parentSchema:l,it:u}=e,{oneOf:d}=l;if(!u.opts.discriminator)throw Error(`discriminator: requires discriminator option`);let f=c.propertyName;if(typeof f!=`string`)throw Error(`discriminator: requires propertyName`);if(c.mapping)throw Error(`discriminator: mapping is not supported`);if(!d)throw Error(`discriminator: requires oneOf keyword`);let p=o.let(`valid`,!1),m=o.const(`tag`,(0,t._)`${s}${(0,t.getProperty)(f)}`);o.if((0,t._)`typeof ${m} == "string"`,()=>h(),()=>e.error(!1,{discrError:n.DiscrError.Tag,tag:m,tagName:f})),e.ok(p);function h(){let r=_();o.if(!1);for(let e in r)o.elseIf((0,t._)`${m} === ${e}`),o.assign(p,g(r[e]));o.else(),e.error(!1,{discrError:n.DiscrError.Mapping,tag:m,tagName:f}),o.endIf()}function g(n){let r=o.name(`valid`),i=e.subschema({keyword:`oneOf`,schemaProp:n},r);return e.mergeEvaluated(i,t.Name),r}function _(){let e={},t=o(l),n=!0;for(let e=0;e<d.length;e++){let c=d[e];if(c?.$ref&&!(0,a.schemaHasRulesButRef)(c,u.self.RULES)){let e=c.$ref;if(c=r.resolveRef.call(u.self,u.schemaEnv.root,u.baseId,e),c instanceof r.SchemaEnv&&(c=c.schema),c===void 0)throw new i.default(u.opts.uriResolver,u.baseId,e)}let l=c?.properties?.[f];if(typeof l!=`object`)throw Error(`discriminator: oneOf subschemas (or referenced schemas) must have "properties/${f}"`);n&&=t||o(c),s(l,e)}if(!n)throw Error(`discriminator: "${f}" must be required`);return e;function o({required:e}){return Array.isArray(e)&&e.includes(f)}function s(e,t){if(e.const)c(e.const,t);else if(e.enum)for(let n of e.enum)c(n,t);else throw Error(`discriminator: "properties/${f}" must have "const" or "enum"`)}function c(t,n){if(typeof t!=`string`||t in e)throw Error(`discriminator: "${f}" values must be unique strings`);e[t]=n}}}}})),Jg=B(((e,t)=>{t.exports={$schema:`http://json-schema.org/draft-07/schema#`,$id:`http://json-schema.org/draft-07/schema#`,title:`Core schema meta-schema`,definitions:{schemaArray:{type:`array`,minItems:1,items:{$ref:`#`}},nonNegativeInteger:{type:`integer`,minimum:0},nonNegativeIntegerDefault0:{allOf:[{$ref:`#/definitions/nonNegativeInteger`},{default:0}]},simpleTypes:{enum:[`array`,`boolean`,`integer`,`null`,`number`,`object`,`string`]},stringArray:{type:`array`,items:{type:`string`},uniqueItems:!0,default:[]}},type:[`object`,`boolean`],properties:{$id:{type:`string`,format:`uri-reference`},$schema:{type:`string`,format:`uri`},$ref:{type:`string`,format:`uri-reference`},$comment:{type:`string`},title:{type:`string`},description:{type:`string`},default:!0,readOnly:{type:`boolean`,default:!1},examples:{type:`array`,items:!0},multipleOf:{type:`number`,exclusiveMinimum:0},maximum:{type:`number`},exclusiveMaximum:{type:`number`},minimum:{type:`number`},exclusiveMinimum:{type:`number`},maxLength:{$ref:`#/definitions/nonNegativeInteger`},minLength:{$ref:`#/definitions/nonNegativeIntegerDefault0`},pattern:{type:`string`,format:`regex`},additionalItems:{$ref:`#`},items:{anyOf:[{$ref:`#`},{$ref:`#/definitions/schemaArray`}],default:!0},maxItems:{$ref:`#/definitions/nonNegativeInteger`},minItems:{$ref:`#/definitions/nonNegativeIntegerDefault0`},uniqueItems:{type:`boolean`,default:!1},contains:{$ref:`#`},maxProperties:{$ref:`#/definitions/nonNegativeInteger`},minProperties:{$ref:`#/definitions/nonNegativeIntegerDefault0`},required:{$ref:`#/definitions/stringArray`},additionalProperties:{$ref:`#`},definitions:{type:`object`,additionalProperties:{$ref:`#`},default:{}},properties:{type:`object`,additionalProperties:{$ref:`#`},default:{}},patternProperties:{type:`object`,additionalProperties:{$ref:`#`},propertyNames:{format:`regex`},default:{}},dependencies:{type:`object`,additionalProperties:{anyOf:[{$ref:`#`},{$ref:`#/definitions/stringArray`}]}},propertyNames:{$ref:`#`},const:!0,enum:{type:`array`,items:!0,minItems:1,uniqueItems:!0},type:{anyOf:[{$ref:`#/definitions/simpleTypes`},{type:`array`,items:{$ref:`#/definitions/simpleTypes`},minItems:1,uniqueItems:!0}]},format:{type:`string`},contentMediaType:{type:`string`},contentEncoding:{type:`string`},if:{$ref:`#`},then:{$ref:`#`},else:{$ref:`#`},allOf:{$ref:`#/definitions/schemaArray`},anyOf:{$ref:`#/definitions/schemaArray`},oneOf:{$ref:`#/definitions/schemaArray`},not:{$ref:`#`}},default:!0}})),Yg=B(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0}),e.MissingRefError=e.ValidationError=e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=e.Ajv=void 0;let n=cg(),r=Gg(),i=qg(),a=Jg(),o=[`/properties`],s=`http://json-schema.org/draft-07/schema`;var c=class extends n.default{_addVocabularies(){super._addVocabularies(),r.default.forEach(e=>this.addVocabulary(e)),this.opts.discriminator&&this.addKeyword(i.default)}_addDefaultMetaSchema(){if(super._addDefaultMetaSchema(),!this.opts.meta)return;let e=this.opts.$data?this.$dataMetaSchema(a,o):a;this.addMetaSchema(e,s,!1),this.refs[`http://json-schema.org/schema`]=s}defaultMeta(){return this.opts.defaultMeta=super.defaultMeta()||(this.getSchema(s)?s:void 0)}};e.Ajv=c,t.exports=e=c,t.exports.Ajv=c,Object.defineProperty(e,"__esModule",{value:!0}),e.default=c;var l=$h();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return l.KeywordCxt}});var u=W();Object.defineProperty(e,"_",{enumerable:!0,get:function(){return u._}}),Object.defineProperty(e,"str",{enumerable:!0,get:function(){return u.str}}),Object.defineProperty(e,"stringify",{enumerable:!0,get:function(){return u.stringify}}),Object.defineProperty(e,"nil",{enumerable:!0,get:function(){return u.nil}}),Object.defineProperty(e,"Name",{enumerable:!0,get:function(){return u.Name}}),Object.defineProperty(e,"CodeGen",{enumerable:!0,get:function(){return u.CodeGen}});var d=eg();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return d.default}});var f=tg();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return f.default}})})),Xg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(e,t){return{validate:e,compare:t}}e.fullFormats={date:t(a,o),time:t(c(!0),l),"date-time":t(f(!0),p),"iso-time":t(c(),u),"iso-date-time":t(f(),m),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:_,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:ee,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:y,int32:{type:`number`,validate:S},int64:{type:`number`,validate:C},float:{type:`number`,validate:w},double:{type:`number`,validate:w},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,o),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,l),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,p),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,m),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function n(e){return e%4==0&&(e%100!=0||e%400==0)}let r=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31];function a(e){let t=r.exec(e);if(!t)return!1;let a=+t[1],o=+t[2],s=+t[3];return o>=1&&o<=12&&s>=1&&s<=(o===2&&n(a)?29:i[o])}function o(e,t){if(e&&t)return e>t?1:e<t?-1:0}let s=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(e){return function(t){let n=s.exec(t);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=n[4],c=n[5]===`-`?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||e&&!o)return!1;if(r<=23&&i<=59&&a<60)return!0;let d=i-u*c,f=r-l*c-+(d<0);return(f===23||f===-1)&&(d===59||d===-1)&&a<61}}function l(e,t){if(!(e&&t))return;let n=new Date(`2020-01-01T`+e).valueOf(),r=new Date(`2020-01-01T`+t).valueOf();if(n&&r)return n-r}function u(e,t){if(!(e&&t))return;let n=s.exec(e),r=s.exec(t);if(n&&r)return e=n[1]+n[2]+n[3],t=r[1]+r[2]+r[3],e>t?1:e<t?-1:0}let d=/t|\s/i;function f(e){let t=c(e);return function(e){let n=e.split(d);return n.length===2&&a(n[0])&&t(n[1])}}function p(e,t){if(!(e&&t))return;let n=new Date(e).valueOf(),r=new Date(t).valueOf();if(n&&r)return n-r}function m(e,t){if(!(e&&t))return;let[n,r]=e.split(d),[i,a]=t.split(d),s=o(n,i);if(s!==void 0)return s||l(r,a)}let h=/\/|:/,g=/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'()*+,;=:@]|%[0-9a-f]{2})*)*)(?:\?(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i;function _(e){return h.test(e)&&g.test(e)}let v=/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/gm;function y(e){return v.lastIndex=0,v.test(e)}let b=-(2**31),x=2**31-1;function S(e){return Number.isInteger(e)&&e<=x&&e>=b}function C(e){return Number.isInteger(e)}function w(){return!0}let T=/[^\\]\\Z/;function ee(e){if(T.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),Zg=B((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;let t=Yg(),n=W(),r=n.operators,i={formatMaximum:{okStr:`<=`,ok:r.LTE,fail:r.GT},formatMinimum:{okStr:`>=`,ok:r.GTE,fail:r.LT},formatExclusiveMaximum:{okStr:`<`,ok:r.LT,fail:r.GTE},formatExclusiveMinimum:{okStr:`>`,ok:r.GT,fail:r.LTE}};e.formatLimitDefinition={keyword:Object.keys(i),type:`string`,schemaType:`string`,$data:!0,error:{message:({keyword:e,schemaCode:t})=>(0,n.str)`should be ${i[e].okStr} ${t}`,params:({keyword:e,schemaCode:t})=>(0,n._)`{comparison: ${i[e].okStr}, limit: ${t}}`},code(e){let{gen:r,data:a,schemaCode:o,keyword:s,it:c}=e,{opts:l,self:u}=c;if(!l.validateFormats)return;let d=new t.KeywordCxt(c,u.RULES.all.format.definition,`format`);d.$data?f():p();function f(){let t=r.scopeValue(`formats`,{ref:u.formats,code:l.code.formats}),i=r.const(`fmt`,(0,n._)`${t}[${d.schemaCode}]`);e.fail$data((0,n.or)((0,n._)`typeof ${i} != "object"`,(0,n._)`${i} instanceof RegExp`,(0,n._)`typeof ${i}.compare != "function"`,m(i)))}function p(){let t=d.schema,i=u.formats[t];if(!i||i===!0)return;if(typeof i!=`object`||i instanceof RegExp||typeof i.compare!=`function`)throw Error(`"${s}": format "${t}" does not define "compare" function`);let a=r.scopeValue(`formats`,{key:t,ref:i,code:l.code.formats?(0,n._)`${l.code.formats}${(0,n.getProperty)(t)}`:void 0});e.fail$data(m(a))}function m(e){return(0,n._)`${e}.compare(${a}, ${o}) ${i[s].fail} 0`}},dependencies:[`format`]},e.default=t=>(t.addKeyword(e.formatLimitDefinition),t)})),Qg=B(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});let n=Xg(),r=Zg(),i=W(),a=new i.Name(`fullFormats`),o=new i.Name(`fastFormats`),s=(e,t={keywords:!0})=>{if(Array.isArray(t))return c(e,t,n.fullFormats,a),e;let[i,s]=t.mode===`fast`?[n.fastFormats,o]:[n.fullFormats,a];return c(e,t.formats||n.formatNames,i,s),t.keywords&&(0,r.default)(e),e};s.get=(e,t=`full`)=>{let r=(t===`fast`?n.fastFormats:n.fullFormats)[e];if(!r)throw Error(`Unknown format "${e}"`);return r};function c(e,t,n,r){var a;(a=e.opts.code).formats??(a.formats=(0,i._)`require("ajv-formats/dist/formats").${r}`);for(let r of t)e.addFormat(r,n[r])}t.exports=e=s,Object.defineProperty(e,"__esModule",{value:!0}),e.default=s})),$g=Yg(),e_=sf(Qg(),1),t_=class{_ajv;constructor(e){this._ajv=e??Zd()}getValidator(e){let t=`$id`in e&&typeof e.$id==`string`?this._ajv.getSchema(e.$id)??this._ajv.compile(e):this._ajv.compile(e);return e=>t(e)?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:this._ajv.errorsText(t.errors)}}},n_=class{shortcircuit;draft;constructor(e){this.shortcircuit=e?.shortcircuit??!0,this.draft=e?.draft??`2020-12`}getValidator(e){let t=new bd(e,this.draft,this.shortcircuit);return e=>{let n=t.validate(e);return n.valid?{valid:!0,data:e,errorMessage:void 0}:{valid:!1,data:void 0,errorMessage:n.errors.map(e=>`${e.instanceLocation}: ${e.error}`).join(`; `)}}}}}));function i_(){throw Error(`StdioServerTransport is not supported in this environment. Use StreamableHTTPServerTransport instead.`)}var a_,o_=I((()=>{r_(),a_={get stdin(){return i_()},get stdout(){return i_()}}})),s_=Ze({AjvJsonSchemaValidator:()=>t_,CfWorkerJsonSchemaValidator:()=>n_,DEFAULT_NEGOTIATED_PROTOCOL_VERSION:()=>vf,DEFAULT_REQUEST_TIMEOUT_MSEC:()=>kh,ExperimentalMcpServerTasks:()=>E_,ExperimentalServerTasks:()=>D_,INTERNAL_ERROR:()=>Tf,INVALID_PARAMS:()=>wf,INVALID_REQUEST:()=>Sf,InMemoryTaskMessageQueue:()=>T_,InMemoryTaskStore:()=>w_,JSONRPC_VERSION:()=>`2.0`,LATEST_PROTOCOL_VERSION:()=>_f,METHOD_NOT_FOUND:()=>Cf,McpServer:()=>k_,OAuthError:()=>lf,OAuthErrorCode:()=>cf,PARSE_ERROR:()=>xf,ProtocolError:()=>U,ProtocolErrorCode:()=>H,RELATED_TASK_META_KEY:()=>bf,ReadBuffer:()=>jh,ResourceTemplate:()=>A_,SUPPORTED_PROTOCOL_VERSIONS:()=>yf,SdkError:()=>V,SdkErrorCode:()=>uf,Server:()=>O_,StdioServerTransport:()=>N_,UriTemplate:()=>Lh,UrlElicitationRequiredError:()=>Ef,WebStandardStreamableHTTPServerTransport:()=>P_,assertClientRequestTaskCapability:()=>f_,assertCompleteRequestPrompt:()=>jd,assertCompleteRequestResourceTemplate:()=>Md,assertToolsCallTaskCapability:()=>d_,checkResourceAllowed:()=>wd,completable:()=>c_,createFetchWithInit:()=>Kd,deserializeMessage:()=>Bd,fromJsonSchema:()=>S_,getDisplayName:()=>Td,hostHeaderValidationResponse:()=>x_,isCompletable:()=>l_,isInitializeRequest:()=>Th,isInitializedNotification:()=>Eh,isJSONRPCErrorResponse:()=>Ch,isJSONRPCNotification:()=>xh,isJSONRPCRequest:()=>bh,isJSONRPCResultResponse:()=>Sh,isTaskAugmentedRequestParams:()=>wh,isTerminal:()=>Pd,localhostAllowedHostnames:()=>b_,parseJSONRPCMessage:()=>Ad,resourceUrlFromServerUrl:()=>Cd,serializeMessage:()=>Vd,takeResult:()=>zd,toArrayAsync:()=>Rd,validateHostHeader:()=>y_});function c_(e,t){return Object.defineProperty(e,C_,{value:{complete:t},enumerable:!1,writable:!1,configurable:!1}),e}function l_(e){return!!e&&typeof e==`object`&&C_ in e}function u_(e){return e[C_]?.complete}function d_(e,t,n){if(!e)throw new V(uf.CapabilityNotSupported,`${n} does not support task creation (required for ${t})`);if(t===`tools/call`&&!e.tools?.call)throw new V(uf.CapabilityNotSupported,`${n} does not support task creation for tools/call (required for ${t})`)}function f_(e,t,n){if(!e)throw new V(uf.CapabilityNotSupported,`${n} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw new V(uf.CapabilityNotSupported,`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw new V(uf.CapabilityNotSupported,`${n} does not support task creation for elicitation/create (required for ${t})`)}}function p_(e,t){if(`createTask`in t){let n=t;return async(t,r)=>{if(!r.task?.store)throw Error(`No task store provided.`);let i={...r,task:{store:r.task.store,requestedTtl:r.task?.requestedTtl}};return e?n.createTask(t,i):n.createTask(i)}}if(e){let e=t;return async(t,n)=>e(t,n)}let n=t;return async(e,t)=>n(t)}function m_(e,t,n){if(t){let r=n;return async(n,i)=>{let a=await Yd(t,n);if(!a.success)throw new U(H.InvalidParams,`Invalid arguments for prompt ${e}: ${a.error}`);return r(a.data,i)}}{let e=n;return async(t,n)=>e(n)}}function h_(e){return{completion:{values:e.map(String).slice(0,100),total:e.length,hasMore:e.length>100}}}function g_(e){let t=e;if(t.shape&&typeof t.shape==`object`)return t.shape}function __(e){return e?.type===`optional`}function v_(e){return __(e)?e.def?.innerType??e:e}function y_(e,t){if(!e)return{ok:!1,errorCode:`missing_host`,message:`Missing Host header`};let n;try{n=new URL(`http://${e}`).hostname}catch{return{ok:!1,errorCode:`invalid_host_header`,message:`Invalid Host header: ${e}`,hostHeader:e}}return t.includes(n)?{ok:!0,hostname:n}:{ok:!1,errorCode:`invalid_host`,message:`Invalid Host: ${n}`,hostHeader:e,hostname:n}}function b_(){return[`localhost`,`127.0.0.1`,`[::1]`]}function x_(e,t){let n=y_(e.headers.get(`host`),t);if(!n.ok)return Response.json({jsonrpc:`2.0`,error:{code:-32e3,message:n.message},id:null},{status:403,headers:{"Content-Type":`application/json`}})}function S_(e,t){return Qd(e,t??(F_??=new n_))}var C_,w_,T_,E_,D_,O_,k_,A_,j_,M_,N_,P_,F_,I_=I((()=>{r_(),o_(),C_=Symbol.for(`mcp.completable`),w_=class{tasks=new Map;cleanupTimers=new Map;generateTaskId(){return crypto.randomUUID().replaceAll(`-`,``)}async createTask(e,t,n,r){let i=this.generateTaskId();if(this.tasks.has(i))throw Error(`Task with ID ${i} already exists`);let a=e.ttl??null,o=new Date().toISOString(),s={taskId:i,status:`working`,ttl:a,createdAt:o,lastUpdatedAt:o,pollInterval:e.pollInterval??1e3};if(this.tasks.set(i,{task:s,request:n,requestId:t,sessionId:r}),a){let e=setTimeout(()=>{this.tasks.delete(i),this.cleanupTimers.delete(i)},a);this.cleanupTimers.set(i,e)}return s}getStoredTask(e,t){let n=this.tasks.get(e);if(n&&(t===void 0||n.sessionId===void 0||n.sessionId===t))return n}async getTask(e,t){let n=this.getStoredTask(e,t);return n?{...n.task}:null}async storeTaskResult(e,t,n,r){let i=this.getStoredTask(e,r);if(!i)throw Error(`Task with ID ${e} not found`);if(Pd(i.task.status))throw Error(`Cannot store result for task ${e} in terminal status '${i.task.status}'. Task results can only be stored once.`);if(i.result=n,i.task.status=t,i.task.lastUpdatedAt=new Date().toISOString(),i.task.ttl){let t=this.cleanupTimers.get(e);t&&clearTimeout(t);let n=setTimeout(()=>{this.tasks.delete(e),this.cleanupTimers.delete(e)},i.task.ttl);this.cleanupTimers.set(e,n)}}async getTaskResult(e,t){let n=this.getStoredTask(e,t);if(!n)throw Error(`Task with ID ${e} not found`);if(!n.result)throw Error(`Task ${e} has no result stored`);return n.result}async updateTaskStatus(e,t,n,r){let i=this.getStoredTask(e,r);if(!i)throw Error(`Task with ID ${e} not found`);if(Pd(i.task.status))throw Error(`Cannot update task ${e} from terminal status '${i.task.status}' to '${t}'. Terminal states (completed, failed, cancelled) cannot transition to other states.`);if(i.task.status=t,n&&(i.task.statusMessage=n),i.task.lastUpdatedAt=new Date().toISOString(),Pd(t)&&i.task.ttl){let t=this.cleanupTimers.get(e);t&&clearTimeout(t);let n=setTimeout(()=>{this.tasks.delete(e),this.cleanupTimers.delete(e)},i.task.ttl);this.cleanupTimers.set(e,n)}}async listTasks(e,t){let n=[...this.tasks.entries()].filter(([,e])=>t===void 0||e.sessionId===void 0||e.sessionId===t).map(([e])=>e),r=0;if(e){let t=n.indexOf(e);if(t===-1)throw Error(`Invalid cursor: ${e}`);r=t+1}let i=n.slice(r,r+10);return{tasks:i.map(e=>({...this.tasks.get(e).task})),nextCursor:r+10<n.length?i.at(-1):void 0}}cleanup(){for(let e of this.cleanupTimers.values())clearTimeout(e);this.cleanupTimers.clear(),this.tasks.clear()}getAllTasks(){return[...this.tasks.values()].map(e=>({...e.task}))}},T_=class{queues=new Map;getQueueKey(e,t){return e}getQueue(e,t){let n=this.getQueueKey(e,t),r=this.queues.get(n);return r||(r=[],this.queues.set(n,r)),r}async enqueue(e,t,n,r){let i=this.getQueue(e,n);if(r!==void 0&&i.length>=r)throw Error(`Task message queue overflow: queue size (${i.length}) exceeds maximum (${r})`);i.push(t)}async dequeue(e,t){return this.getQueue(e,t).shift()}async dequeueAll(e,t){let n=this.getQueueKey(e,t),r=this.queues.get(n)??[];return this.queues.delete(n),r}},E_=class{constructor(e){this._mcpServer=e}registerToolTask(e,t,n){let r={taskSupport:`required`,...t.execution};if(r.taskSupport===`forbidden`)throw Error(`Cannot register task-based tool '${e}' with taskSupport 'forbidden'. Use registerTool() instead.`);return this._mcpServer._createRegisteredTool(e,t.title,t.description,t.inputSchema,t.outputSchema,t.annotations,r,t._meta,n)}},D_=class{constructor(e){this._server=e}get _module(){return this._server.taskManager}requestStream(e,t){let n=Ed(e.method);return this._module.requestStream(e,n,t)}createMessageStream(e,t){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw new V(uf.CapabilityNotSupported,`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages.at(-1),n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages.at(-2):void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw Error(`The last message must contain only tool_result content if any is present`);if(!o)throw Error(`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw Error(`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return this.requestStream({method:`sampling/createMessage`,params:e},t)}elicitInputStream(e,t){let n=this._server.getClientCapabilities(),r=e.mode??`form`;switch(r){case`url`:if(!n?.elicitation?.url)throw new V(uf.CapabilityNotSupported,`Client does not support url elicitation.`);break;case`form`:if(!n?.elicitation?.form)throw new V(uf.CapabilityNotSupported,`Client does not support form elicitation.`)}let i=r===`form`&&e.mode!==`form`?{...e,mode:`form`}:e;return this.requestStream({method:`elicitation/create`,params:i},t)}async getTask(e,t){return this._module.getTask({taskId:e},t)}async getTaskResult(e,t){return this._module.getTaskResult({taskId:e},wp,t)}async listTasks(e,t){return this._module.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._module.cancelTask({taskId:e},t)}},O_=class extends Ah{_clientCapabilities;_clientVersion;_capabilities;_instructions;_jsonSchemaValidator;_experimental;oninitialized;constructor(e,t){if(super({...t,tasks:Fd(t?.capabilities?.tasks)}),this._serverInfo=e,this._capabilities=t?.capabilities?{...t.capabilities}:{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new n_,t?.capabilities?.tasks){let{taskStore:e,taskMessageQueue:n,defaultTaskPollInterval:r,maxTaskQueueSize:i,...a}=t.capabilities.tasks;this._capabilities.tasks=a}this.setRequestHandler(`initialize`,e=>this._oninitialize(e)),this.setNotificationHandler(`notifications/initialized`,()=>this.oninitialized?.()),this._capabilities.logging&&this._registerLoggingHandler()}_registerLoggingHandler(){this.setRequestHandler(`logging/setLevel`,async(e,t)=>{let n=t.sessionId||t.http?.req?.headers.get(`mcp-session-id`)||void 0,{level:r}=e.params,i=Nd(Cm,r);return i.success&&this._loggingLevels.set(n,i.data),{}})}buildContext(e,t){let n=e.http||t?.request||t?.closeSSEStream||t?.closeStandaloneSSEStream;return{...e,mcpReq:{...e.mcpReq,log:(e,t,n)=>this.sendLoggingMessage({level:e,data:t,logger:n}),elicitInput:(e,t)=>this.elicitInput(e,t),requestSampling:(e,t)=>this.createMessage(e,t)},http:n?{...e.http,req:t?.request,closeSSE:t?.closeSSEStream,closeStandaloneSSE:t?.closeStandaloneSSEStream}:void 0}}get experimental(){return this._experimental||={tasks:new D_(this)},this._experimental}_loggingLevels=new Map;LOG_LEVEL_SEVERITY=new Map(Cm.options.map((e,t)=>[e,t]));isMessageIgnored=(e,t)=>{let n=this._loggingLevels.get(t);return n?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n):!1};registerCapabilities(e){if(this.transport)throw new V(uf.AlreadyConnected,`Cannot register capabilities after connecting to transport`);let t=!!this._capabilities.logging;this._capabilities=Ld(this._capabilities,e),!t&&this._capabilities.logging&&this._registerLoggingHandler()}setRequestHandler(e,t){return e===`tools/call`?super.setRequestHandler(e,async(e,n)=>{let r=Nd(xm,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new U(H.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=Nd(vp,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new U(H.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=Nd(ym,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new U(H.InvalidParams,`Invalid tools/call result: ${e}`)}return o.data}):super.setRequestHandler(e,t)}assertCapabilityForMethod(e){switch(e){case`sampling/createMessage`:if(!this._clientCapabilities?.sampling)throw new V(uf.CapabilityNotSupported,`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw new V(uf.CapabilityNotSupported,`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw new V(uf.CapabilityNotSupported,`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw new V(uf.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw new V(uf.CapabilityNotSupported,`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw new V(uf.CapabilityNotSupported,`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw new V(uf.CapabilityNotSupported,`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw new V(uf.CapabilityNotSupported,`Client does not support URL elicitation (required for ${e})`)}}assertRequestHandlerCapability(e){switch(e){case`completion/complete`:if(!this._capabilities.completions)throw new V(uf.CapabilityNotSupported,`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw new V(uf.CapabilityNotSupported,`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw new V(uf.CapabilityNotSupported,`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw new V(uf.CapabilityNotSupported,`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw new V(uf.CapabilityNotSupported,`Server does not support tools (required for ${e})`)}}assertTaskCapability(e){f_(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){d_(this._capabilities?.tasks?.requests,e,`Server`)}async _oninitialize(e){let t=e.params.protocolVersion;this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo;let n=this._supportedProtocolVersions.includes(t)?t:this._supportedProtocolVersions[0]??`2025-11-25`;return this.transport?.setProtocolVersion?.(n),{protocolVersion:n,capabilities:this.getCapabilities(),serverInfo:this._serverInfo,...this._instructions&&{instructions:this._instructions}}}getClientCapabilities(){return this._clientCapabilities}getClientVersion(){return this._clientVersion}getCapabilities(){return this._capabilities}async ping(){return this._requestWithSchema({method:`ping`},Kf)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw new V(uf.CapabilityNotSupported,`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages.at(-1),n=Array.isArray(t.content)?t.content:[t.content],r=n.some(e=>e.type===`tool_result`),i=e.messages.length>1?e.messages.at(-2):void 0,a=i?Array.isArray(i.content)?i.content:[i.content]:[],o=a.some(e=>e.type===`tool_use`);if(r){if(n.some(e=>e.type!==`tool_result`))throw new U(H.InvalidParams,`The last message must contain only tool_result content if any is present`);if(!o)throw new U(H.InvalidParams,`tool_result blocks are not matching any tool_use from the previous message`)}if(o){let e=new Set(a.filter(e=>e.type===`tool_use`).map(e=>e.id)),t=new Set(n.filter(e=>e.type===`tool_result`).map(e=>e.toolUseId));if(e.size!==t.size||![...e].every(e=>t.has(e)))throw new U(H.InvalidParams,`ids of tool_result blocks and tool_use blocks from previous message do not match`)}}return e.tools?this._requestWithSchema({method:`sampling/createMessage`,params:e},Rm,t):this._requestWithSchema({method:`sampling/createMessage`,params:e},Lm,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw new V(uf.CapabilityNotSupported,`Client does not support url elicitation.`);let n=e;return this._requestWithSchema({method:`elicitation/create`,params:n},rh,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw new V(uf.CapabilityNotSupported,`Client does not support form elicitation.`);let n=e.mode===`form`?e:{...e,mode:`form`},r=await this._requestWithSchema({method:`elicitation/create`,params:n},rh,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new U(H.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof U?e:new U(H.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw new V(uf.CapabilityNotSupported,`Client does not support URL elicitation (required for notifications/elicitation/complete)`);return()=>this.notification({method:`notifications/elicitation/complete`,params:{elicitationId:e}},t)}async listRoots(e,t){return this._requestWithSchema({method:`roots/list`,params:e},dh,t)}async sendLoggingMessage(e,t){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,t))return this.notification({method:`notifications/message`,params:e})}async sendResourceUpdated(e){return this.notification({method:`notifications/resources/updated`,params:e})}async sendResourceListChanged(){return this.notification({method:`notifications/resources/list_changed`})}async sendToolListChanged(){return this.notification({method:`notifications/tools/list_changed`})}async sendPromptListChanged(){return this.notification({method:`notifications/prompts/list_changed`})}},k_=class{server;_registeredResources={};_registeredResourceTemplates={};_registeredTools={};_registeredPrompts={};_experimental;constructor(e,t){this.server=new O_(e,t)}get experimental(){return this._experimental||={tasks:new E_(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}_toolHandlersInitialized=!1;setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(`tools/list`),this.server.assertCanSetRequestHandler(`tools/call`),this.server.registerCapabilities({tools:{listChanged:this.server.getCapabilities().tools?.listChanged??!0}}),this.server.setRequestHandler(`tools/list`,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:t.inputSchema?qd(t.inputSchema,`input`):j_,annotations:t.annotations,execution:t.execution,_meta:t._meta};return t.outputSchema&&(n.outputSchema=qd(t.outputSchema,`output`)),n})})),this.server.setRequestHandler(`tools/call`,async(e,t)=>{let n=this._registeredTools[e.params.name];if(!n)throw new U(H.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new U(H.InvalidParams,`Tool ${e.params.name} disabled`);try{let r=!!e.params.task,i=n.execution?.taskSupport,a=`createTask`in n.handler;if((i===`required`||i===`optional`)&&!a)throw new U(H.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new U(H.MethodNotFound,`Tool ${e.params.name} requires task augmentation (taskSupport: 'required')`);if(i===`optional`&&!r&&a)return await this.handleAutomaticTaskPolling(n,e,t);let o=await this.validateToolInput(n,e.params.arguments,e.params.name),s=await this.executeToolHandler(n,o,t);return r||await this.validateToolOutput(n,s,e.params.name),s}catch(e){if(e instanceof U&&e.code===H.UrlElicitationRequired)throw e;return this.createToolError(e instanceof Error?e.message:String(e))}}),!0)}createToolError(e){return{content:[{type:`text`,text:e}],isError:!0}}async validateToolInput(e,t,n){if(!e.inputSchema)return;let r=await Yd(e.inputSchema,t??{});if(!r.success)throw new U(H.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${r.error}`);return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema||!(`content`in t)||t.isError)return;if(!t.structuredContent)throw new U(H.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await Yd(e.outputSchema,t.structuredContent);if(!r.success)throw new U(H.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${r.error}`)}async executeToolHandler(e,t,n){return e.executor(t,n)}async handleAutomaticTaskPolling(e,t,n){if(!n.task?.store)throw Error(`No task store provided for task-capable tool.`);let r=await this.validateToolInput(e,t.params.arguments,t.params.name),i=await e.executor(r,n),a=i.task.taskId,o=i.task,s=o.pollInterval??5e3;for(;o.status!==`completed`&&o.status!==`failed`&&o.status!==`cancelled`;){await new Promise(e=>setTimeout(e,s));let e=await n.task.store.getTask(a);if(!e)throw new U(H.InternalError,`Task ${a} not found during polling`);o=e}return await n.task.store.getTaskResult(a)}_completionHandlerInitialized=!1;setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(`completion/complete`),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(`completion/complete`,async e=>{switch(e.params.ref.type){case`ref/prompt`:return jd(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return Md(e),this.handleResourceCompletion(e,e.params.ref);default:throw new U(H.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new U(H.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new U(H.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return M_;let r=v_(g_(n.argsSchema)?.[e.params.argument.name]);if(!l_(r))return M_;let i=u_(r);return i?h_(await i(e.params.argument.value,e.params.context)):M_}async handleResourceCompletion(e,t){let n=Object.values(this._registeredResourceTemplates).find(e=>e.resourceTemplate.uriTemplate.toString()===t.uri);if(!n){if(this._registeredResources[t.uri])return M_;throw new U(H.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?h_(await r(e.params.argument.value,e.params.context)):M_}_resourceHandlersInitialized=!1;setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(`resources/list`),this.server.assertCanSetRequestHandler(`resources/templates/list`),this.server.assertCanSetRequestHandler(`resources/read`),this.server.registerCapabilities({resources:{listChanged:this.server.getCapabilities().resources?.listChanged??!0}}),this.server.setRequestHandler(`resources/list`,async(e,t)=>{let n=Object.entries(this._registeredResources).filter(([e,t])=>t.enabled).map(([e,t])=>({uri:e,name:t.name,...t.metadata})),r=[];for(let e of Object.values(this._registeredResourceTemplates)){if(!e.resourceTemplate.listCallback)continue;let n=await e.resourceTemplate.listCallback(t);for(let t of n.resources)r.push({...e.metadata,...t})}return{resources:[...n,...r]}}),this.server.setRequestHandler(`resources/templates/list`,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(`resources/read`,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new U(H.InvalidParams,`Resource ${n} disabled`);return r.readCallback(n,t)}for(let e of Object.values(this._registeredResourceTemplates)){let r=e.resourceTemplate.uriTemplate.match(n.toString());if(r)return e.readCallback(n,r,t)}throw new U(H.ResourceNotFound,`Resource ${n} not found`)}),!0)}_promptHandlersInitialized=!1;setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(`prompts/list`),this.server.assertCanSetRequestHandler(`prompts/get`),this.server.registerCapabilities({prompts:{listChanged:this.server.getCapabilities().prompts?.listChanged??!0}}),this.server.setRequestHandler(`prompts/list`,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?Xd(t.argsSchema):void 0,_meta:t._meta}))})),this.server.setRequestHandler(`prompts/get`,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new U(H.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new U(H.InvalidParams,`Prompt ${e.params.name} disabled`);return n.handler(e.params.arguments,t)}),!0)}registerResource(e,t,n,r){if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let i=this._createRegisteredResource(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let i=this._createRegisteredResourceTemplate(e,n.title,t,n,r);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),i}}_createRegisteredResource(e,t,n,r,i){let a={name:e,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({uri:null}),update:e=>{e.uri!==void 0&&e.uri!==n&&(delete this._registeredResources[n],e.uri&&(this._registeredResources[e.uri]=a)),e.name!==void 0&&(a.name=e.name),e.title!==void 0&&(a.title=e.title),e.metadata!==void 0&&(a.metadata=e.metadata),e.callback!==void 0&&(a.readCallback=e.callback),e.enabled!==void 0&&(a.enabled=e.enabled),this.sendResourceListChanged()}};return this._registeredResources[n]=a,a}_createRegisteredResourceTemplate(e,t,n,r,i){let a={resourceTemplate:n,title:t,metadata:r,readCallback:i,enabled:!0,disable:()=>a.update({enabled:!1}),enable:()=>a.update({enabled:!0}),remove:()=>a.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredResourceTemplates[e],t.name&&(this._registeredResourceTemplates[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.template!==void 0&&(a.resourceTemplate=t.template),t.metadata!==void 0&&(a.metadata=t.metadata),t.callback!==void 0&&(a.readCallback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendResourceListChanged()}};this._registeredResourceTemplates[e]=a;let o=n.uriTemplate.variableNames;return Array.isArray(o)&&o.some(e=>!!n.completeCallback(e))&&this.setCompletionRequestHandler(),a}_createRegisteredPrompt(e,t,n,r,i,a){let o=r,s=i,c={title:t,description:n,argsSchema:r,_meta:a,handler:m_(e,r,i),enabled:!0,disable:()=>c.update({enabled:!1}),enable:()=>c.update({enabled:!0}),remove:()=>c.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(delete this._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=c)),t.title!==void 0&&(c.title=t.title),t.description!==void 0&&(c.description=t.description),t._meta!==void 0&&(c._meta=t._meta);let n=!1;t.argsSchema!==void 0&&(c.argsSchema=t.argsSchema,o=t.argsSchema,n=!0),t.callback!==void 0&&(s=t.callback,n=!0),n&&(c.handler=m_(e,o,s)),t.enabled!==void 0&&(c.enabled=t.enabled),this.sendPromptListChanged()}};if(this._registeredPrompts[e]=c,r){let e=g_(r);e&&Object.values(e).some(e=>l_(v_(e)))&&this.setCompletionRequestHandler()}return c}_createRegisteredTool(e,t,n,r,i,a,o,s,c){Wd(e);let l=c,u={title:t,description:n,inputSchema:r,outputSchema:i,annotations:a,execution:o,_meta:s,handler:c,executor:p_(r,c),enabled:!0,disable:()=>u.update({enabled:!1}),enable:()=>u.update({enabled:!0}),remove:()=>u.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&Wd(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=u)),t.title!==void 0&&(u.title=t.title),t.description!==void 0&&(u.description=t.description);let n=!1;t.paramsSchema!==void 0&&(u.inputSchema=t.paramsSchema,n=!0),t.callback!==void 0&&(u.handler=t.callback,l=t.callback,n=!0),n&&(u.executor=p_(u.inputSchema,l)),t.outputSchema!==void 0&&(u.outputSchema=t.outputSchema),t.annotations!==void 0&&(u.annotations=t.annotations),t._meta!==void 0&&(u._meta=t._meta),t.enabled!==void 0&&(u.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=u,this.setToolRequestHandlers(),this.sendToolListChanged(),u}registerTool(e,t,n){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let{title:r,description:i,inputSchema:a,outputSchema:o,annotations:s,_meta:c}=t;return this._createRegisteredTool(e,r,i,a,o,s,{taskSupport:`forbidden`},c,n)}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:r,description:i,argsSchema:a,_meta:o}=t,s=this._createRegisteredPrompt(e,r,i,a,n,o);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),s}isConnected(){return this.server.transport!==void 0}async sendLoggingMessage(e,t){return this.server.sendLoggingMessage(e,t)}sendResourceListChanged(){this.isConnected()&&this.server.sendResourceListChanged()}sendToolListChanged(){this.isConnected()&&this.server.sendToolListChanged()}sendPromptListChanged(){this.isConnected()&&this.server.sendPromptListChanged()}},A_=class{_uriTemplate;constructor(e,t){this._callbacks=t,this._uriTemplate=typeof e==`string`?new Lh(e):e}get uriTemplate(){return this._uriTemplate}get listCallback(){return this._callbacks.list}completeCallback(e){return this._callbacks.complete?.[e]}},j_={type:`object`,properties:{}},M_={completion:{values:[],hasMore:!1}},N_=class{_readBuffer=new jh;_started=!1;_closed=!1;constructor(e=a_.stdin,t=a_.stdout){this._stdin=e,this._stdout=t}onclose;onerror;onmessage;_ondata=e=>{this._readBuffer.append(e),this.processReadBuffer()};_onerror=e=>{this.onerror?.(e)};_onstdouterror=e=>{this.onerror?.(e),this.close().catch(()=>{})};async start(){if(this._started)throw Error(`StdioServerTransport already started! If using Server class, note that connect() calls start() automatically.`);this._started=!0,this._stdin.on(`data`,this._ondata),this._stdin.on(`error`,this._onerror),this._stdout.on(`error`,this._onstdouterror)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._closed||(this._closed=!0,this._stdin.off(`data`,this._ondata),this._stdin.off(`error`,this._onerror),this._stdout.off(`error`,this._onstdouterror),this._stdin.listenerCount(`data`)===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.())}send(e){return this._closed?Promise.reject(Error(`StdioServerTransport is closed`)):new Promise((t,n)=>{let r=Vd(e),i=!1,a=e=>{i||(i=!0,this._stdout.off(`error`,a),this._stdout.off(`drain`,o),n(e))},o=()=>{i||(i=!0,this._stdout.off(`error`,a),this._stdout.off(`drain`,o),t())};if(this._stdout.once(`error`,a),this._stdout.write(r)){if(i)return;i=!0,this._stdout.off(`error`,a),t()}else i||this._stdout.once(`drain`,o)})}},P_=class{sessionIdGenerator;_started=!1;_streamMapping=new Map;_requestToStreamMapping=new Map;_requestResponseMap=new Map;_initialized=!1;_enableJsonResponse=!1;_standaloneSseStreamId=`_GET_stream`;_eventStore;_onsessioninitialized;_onsessionclosed;_allowedHosts;_allowedOrigins;_enableDnsRebindingProtection;_retryInterval;_supportedProtocolVersions;sessionId;onclose;onerror;onmessage;constructor(e={}){this.sessionIdGenerator=e.sessionIdGenerator,this._enableJsonResponse=e.enableJsonResponse??!1,this._eventStore=e.eventStore,this._onsessioninitialized=e.onsessioninitialized,this._onsessionclosed=e.onsessionclosed,this._allowedHosts=e.allowedHosts,this._allowedOrigins=e.allowedOrigins,this._enableDnsRebindingProtection=e.enableDnsRebindingProtection??!1,this._retryInterval=e.retryInterval,this._supportedProtocolVersions=e.supportedProtocolVersions??yf}async start(){if(this._started)throw Error(`Transport already started`);this._started=!0}setSupportedProtocolVersions(e){this._supportedProtocolVersions=e}createJsonErrorResponse(e,t,n,r){let i={code:t,message:n};return r?.data!==void 0&&(i.data=r.data),Response.json({jsonrpc:`2.0`,error:i,id:null},{status:e,headers:{"Content-Type":`application/json`,...r?.headers}})}validateRequestHeaders(e){if(this._enableDnsRebindingProtection){if(this._allowedHosts&&this._allowedHosts.length>0){let t=e.headers.get(`host`);if(!t||!this._allowedHosts.includes(t)){let e=`Invalid Host header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}if(this._allowedOrigins&&this._allowedOrigins.length>0){let t=e.headers.get(`origin`);if(t&&!this._allowedOrigins.includes(t)){let e=`Invalid Origin header: ${t}`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(403,-32e3,e)}}}}async handleRequest(e,t){let n=this.validateRequestHeaders(e);if(n)return n;switch(e.method){case`POST`:return this.handlePostRequest(e,t);case`GET`:return this.handleGetRequest(e);case`DELETE`:return this.handleDeleteRequest(e);default:return this.handleUnsupportedRequest()}}async writePrimingEvent(e,t,n,r){if(!this._eventStore||r<`2025-11-25`)return;let i=await this._eventStore.storeEvent(n,{}),a=`id: ${i}\ndata: \n\n`;this._retryInterval!==void 0&&(a=`id: ${i}\nretry: ${this._retryInterval}\ndata: \n\n`),e.enqueue(t.encode(a))}async handleGetRequest(e){if(!e.headers.get(`accept`)?.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept text/event-stream`);let t=this.validateSession(e);if(t)return t;let n=this.validateProtocolVersion(e);if(n)return n;if(this._eventStore){let t=e.headers.get(`last-event-id`);if(t)return this.replayEvents(t)}if(this._streamMapping.get(this._standaloneSseStreamId)!==void 0)return this.onerror?.(Error(`Conflict: Only one SSE stream is allowed per session`)),this.createJsonErrorResponse(409,-32e3,`Conflict: Only one SSE stream is allowed per session`);let r=new TextEncoder,i,a=new ReadableStream({start:e=>{i=e},cancel:()=>{this._streamMapping.delete(this._standaloneSseStreamId)}}),o={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`};return this.sessionId!==void 0&&(o[`mcp-session-id`]=this.sessionId),this._streamMapping.set(this._standaloneSseStreamId,{controller:i,encoder:r,cleanup:()=>{this._streamMapping.delete(this._standaloneSseStreamId);try{i.close()}catch{}}}),new Response(a,{headers:o})}async replayEvents(e){if(!this._eventStore)return this.onerror?.(Error(`Event store not configured`)),this.createJsonErrorResponse(400,-32e3,`Event store not configured`);try{let t;if(this._eventStore.getStreamIdForEventId){if(t=await this._eventStore.getStreamIdForEventId(e),!t)return this.onerror?.(Error(`Invalid event ID format`)),this.createJsonErrorResponse(400,-32e3,`Invalid event ID format`);if(this._streamMapping.get(t)!==void 0)return this.onerror?.(Error(`Conflict: Stream already has an active connection`)),this.createJsonErrorResponse(409,-32e3,`Conflict: Stream already has an active connection`)}let n={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache, no-transform`,Connection:`keep-alive`};this.sessionId!==void 0&&(n[`mcp-session-id`]=this.sessionId);let r=new TextEncoder,i,a=new ReadableStream({start:e=>{i=e},cancel:()=>{}}),o=await this._eventStore.replayEventsAfter(e,{send:async(e,t)=>{if(!this.writeSSEEvent(i,r,t,e))try{i.close()}catch{}}});return this._streamMapping.set(o,{controller:i,encoder:r,cleanup:()=>{this._streamMapping.delete(o);try{i.close()}catch{}}}),new Response(a,{headers:n})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(500,-32e3,`Error replaying events`)}}writeSSEEvent(e,t,n,r){try{let i=`event: message
184
+ `;return r&&(i+=`id: ${r}\n`),i+=`data: ${JSON.stringify(n)}\n\n`,e.enqueue(t.encode(i)),!0}catch(e){return this.onerror?.(e),!1}}handleUnsupportedRequest(){return this.onerror?.(Error(`Method not allowed.`)),Response.json({jsonrpc:`2.0`,error:{code:-32e3,message:`Method not allowed.`},id:null},{status:405,headers:{Allow:`GET, POST, DELETE`,"Content-Type":`application/json`}})}async handlePostRequest(e,t){try{let n=e.headers.get(`accept`);if(!n?.includes(`application/json`)||!n.includes(`text/event-stream`))return this.onerror?.(Error(`Not Acceptable: Client must accept both application/json and text/event-stream`)),this.createJsonErrorResponse(406,-32e3,`Not Acceptable: Client must accept both application/json and text/event-stream`);let r=e.headers.get(`content-type`);if(!r||!r.includes(`application/json`))return this.onerror?.(Error(`Unsupported Media Type: Content-Type must be application/json`)),this.createJsonErrorResponse(415,-32e3,`Unsupported Media Type: Content-Type must be application/json`);let i=e,a;if(t?.parsedBody===void 0)try{a=await e.json()}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON`)}else a=t.parsedBody;let o;try{o=Array.isArray(a)?a.map(e=>Gf.parse(e)):[Gf.parse(a)]}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error: Invalid JSON-RPC message`)}let s=o.some(e=>Th(e));if(s){if(this._initialized&&this.sessionId!==void 0)return this.onerror?.(Error(`Invalid Request: Server already initialized`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Server already initialized`);if(o.length>1)return this.onerror?.(Error(`Invalid Request: Only one initialization request is allowed`)),this.createJsonErrorResponse(400,-32600,`Invalid Request: Only one initialization request is allowed`);this.sessionId=this.sessionIdGenerator?.(),this._initialized=!0,this.sessionId&&this._onsessioninitialized&&await Promise.resolve(this._onsessioninitialized(this.sessionId))}if(!s){let t=this.validateSession(e);if(t)return t;let n=this.validateProtocolVersion(e);if(n)return n}if(!o.some(e=>bh(e))){for(let e of o)this.onmessage?.(e,{authInfo:t?.authInfo,request:i});return new Response(null,{status:202})}let c=crypto.randomUUID(),l=o.find(e=>Th(e)),u=l?l.params.protocolVersion:e.headers.get(`mcp-protocol-version`)??`2025-03-26`;if(this._enableJsonResponse)return new Promise(e=>{this._streamMapping.set(c,{resolveJson:e,cleanup:()=>{this._streamMapping.delete(c)}});for(let e of o)bh(e)&&this._requestToStreamMapping.set(e.id,c);for(let e of o)this.onmessage?.(e,{authInfo:t?.authInfo,request:i})});let d=new TextEncoder,f,p=new ReadableStream({start:e=>{f=e},cancel:()=>{this._streamMapping.delete(c)}}),m={"Content-Type":`text/event-stream`,"Cache-Control":`no-cache`,Connection:`keep-alive`};this.sessionId!==void 0&&(m[`mcp-session-id`]=this.sessionId);for(let e of o)bh(e)&&(this._streamMapping.set(c,{controller:f,encoder:d,cleanup:()=>{this._streamMapping.delete(c);try{f.close()}catch{}}}),this._requestToStreamMapping.set(e.id,c));await this.writePrimingEvent(f,d,c,u);for(let e of o){let n,r;bh(e)&&this._eventStore&&u>=`2025-11-25`&&(n=()=>{this.closeSSEStream(e.id)},r=()=>{this.closeStandaloneSSEStream()}),this.onmessage?.(e,{authInfo:t?.authInfo,request:i,closeSSEStream:n,closeStandaloneSSEStream:r})}return new Response(p,{status:200,headers:m})}catch(e){return this.onerror?.(e),this.createJsonErrorResponse(400,-32700,`Parse error`,{data:String(e)})}}async handleDeleteRequest(e){return this.validateSession(e)||this.validateProtocolVersion(e)||(await Promise.resolve(this._onsessionclosed?.(this.sessionId)),await this.close(),new Response(null,{status:200}))}validateSession(e){if(this.sessionIdGenerator===void 0)return;if(!this._initialized)return this.onerror?.(Error(`Bad Request: Server not initialized`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Server not initialized`);let t=e.headers.get(`mcp-session-id`);if(!t)return this.onerror?.(Error(`Bad Request: Mcp-Session-Id header is required`)),this.createJsonErrorResponse(400,-32e3,`Bad Request: Mcp-Session-Id header is required`);if(t!==this.sessionId)return this.onerror?.(Error(`Session not found`)),this.createJsonErrorResponse(404,-32001,`Session not found`)}validateProtocolVersion(e){let t=e.headers.get(`mcp-protocol-version`);if(t!==null&&!this._supportedProtocolVersions.includes(t)){let e=`Bad Request: Unsupported protocol version: ${t} (supported versions: ${this._supportedProtocolVersions.join(`, `)})`;return this.onerror?.(Error(e)),this.createJsonErrorResponse(400,-32e3,e)}}async close(){for(let{cleanup:e}of this._streamMapping.values())e();this._streamMapping.clear(),this._requestResponseMap.clear(),this.onclose?.()}closeSSEStream(e){let t=this._requestToStreamMapping.get(e);if(!t)return;let n=this._streamMapping.get(t);n&&n.cleanup()}closeStandaloneSSEStream(){let e=this._streamMapping.get(this._standaloneSseStreamId);e&&e.cleanup()}async send(e,t){let n=t?.relatedRequestId;if((Sh(e)||Ch(e))&&(n=e.id),n===void 0){if(Sh(e)||Ch(e))throw Error(`Cannot send a response on a standalone SSE stream unless resuming a previous client request`);let t;this._eventStore&&(t=await this._eventStore.storeEvent(this._standaloneSseStreamId,e));let n=this._streamMapping.get(this._standaloneSseStreamId);if(n===void 0)return;n.controller&&n.encoder&&this.writeSSEEvent(n.controller,n.encoder,e,t);return}let r=this._requestToStreamMapping.get(n);if(!r)throw Error(`No connection established for request ID: ${String(n)}`);let i=this._streamMapping.get(r);if(!this._enableJsonResponse&&i?.controller&&i?.encoder){let t;this._eventStore&&(t=await this._eventStore.storeEvent(r,e)),this.writeSSEEvent(i.controller,i.encoder,e,t)}if(Sh(e)||Ch(e)){this._requestResponseMap.set(n,e);let t=[...this._requestToStreamMapping.entries()].filter(([e,t])=>t===r).map(([e])=>e);if(t.every(e=>this._requestResponseMap.has(e))){if(!i)throw Error(`No connection established for request ID: ${String(n)}`);if(this._enableJsonResponse&&i.resolveJson){let e={"Content-Type":`application/json`};this.sessionId!==void 0&&(e[`mcp-session-id`]=this.sessionId);let n=t.map(e=>this._requestResponseMap.get(e));n.length===1?i.resolveJson(Response.json(n[0],{status:200,headers:e})):i.resolveJson(Response.json(n,{status:200,headers:e}))}else i.cleanup();for(let e of t)this._requestResponseMap.delete(e),this._requestToStreamMapping.delete(e)}}}}}));async function L_(e,t,n,r={}){let i=z_(),a=await Promise.resolve().then(()=>(I_(),s_)),{fromJsonSchema:o,McpServer:s}=a,c=await R_(a,i),l=new s({name:e,...r.title?{title:r.title}:void 0,version:t},r.instructions?{instructions:r.instructions}:void 0);V_(l,n,{env:r.env,fromJsonSchema:o,middlewares:r.middlewares,name:e,sendNotification:e=>l.server.notification(e),tools:r.tools,vars:r.vars,version:t});let u=new c(r.input??process.stdin,r.output??process.stdout);await l.connect(u)}async function R_(e,t){let n=e.StdioServerTransport;if(n)return n;let r=await t;if(r.error)throw r.error;return r.module.StdioServerTransport}function z_(){return Promise.resolve().then(()=>(I_(),s_)).then(e=>({module:e})).catch(e=>({error:e}))}async function B_(e,t,n={}){let r=[...n.middlewares??[],...e.middlewares??[],...e.command.middleware??[]],i=await Gl(e.command,{agent:!0,argv:[],env:n.env,format:`json`,formatExplicit:!0,inputOptions:t,middlewares:r,name:n.name??e.name,parseMode:`flat`,path:e.name,request:n.request,vars:n.vars,version:n.version});if(`stream`in i){let e=[],t=n.extra?.mcpReq?._meta?.progressToken,r=0;try{for await(let a of i.stream)e.push(a),t!==void 0&&n.sendNotification&&await n.sendNotification({method:`notifications/progress`,params:{progressToken:t,progress:++r,message:Lr(a)}})}catch(e){return{content:[{type:`text`,text:e instanceof Error?e.message:String(e)}],isError:!0}}return{content:[{type:`text`,text:Lr(e)}]}}if(!i.ok){let t=gu(n.name??e.name,i.cta),r=i.error.fieldErrors?JSON.stringify(i.error):i.error.message??`Command failed`;return{content:[{type:`text`,text:t?`${r}\n\n${_u(t)}`:r}],...t?{_meta:{cta:t}}:void 0,isError:!0}}let a=i.data??null,o=Rr(a),s=gu(n.name??e.name,i.cta),c=Lr(o);return{content:[{type:`text`,text:s?`${c}\n\n${_u(s)}`:c}],...a!==null&&e.outputSchema?{structuredContent:o}:void 0,...s?{_meta:{cta:s}}:void 0}}function V_(e,t,n){let r=X_(t,[],[],n.tools);if(r.length!==0){if((n.tools?.discovery??`progressive`)===`direct`){for(let t of r)H_(e,t,n);return}U_(e,r,n)}}function H_(e,t,n){let r={...t.command.args?.shape,...t.command.options?.shape},i=Object.keys(r).length>0;e.registerTool(t.name,{...t.description?{description:t.description}:void 0,...i?{inputSchema:f.object(r)}:void 0,...t.outputSchema?{outputSchema:n.fromJsonSchema(t.outputSchema)}:void 0,...t.annotations?{annotations:t.annotations}:void 0,...t.instructions?{_meta:{instructions:t.instructions}}:void 0},async(...e)=>B_(t,i?e[0]:{},W_(n,i?e[1]:e[0])))}function U_(e,t,n){let r=new Map(t.map(e=>[e.name,e]));e.registerTool(`search_tools`,{description:`Search or page through available tools by capability. Returns names and descriptions without loading their schemas. Inspect a result before calling it.`,inputSchema:f.object({limit:f.number().int().min(1).max(20).default(5).describe(`Maximum matches.`),offset:f.number().int().min(0).default(0).describe(`Matches to skip.`),query:f.string().default(``).describe(`Capability to find. Empty lists all tools.`)}),annotations:av},async e=>{let n=G_(t,e.query),r=n.slice(e.offset,e.offset+e.limit);return J_({tools:r.map(e=>({name:e.name,...e.description?{description:e.description}:void 0,...e.annotations?{annotations:e.annotations}:void 0})),...e.offset+r.length<n.length?{nextOffset:e.offset+r.length}:void 0})}),e.registerTool(`get_tool_details`,{description:`Inspect one tool returned by search_tools. Returns its complete input schema and metadata.`,inputSchema:f.object({name:f.string().min(1).describe(`Exact tool name.`)}),annotations:av},async e=>{let t=r.get(e.name);return t?J_({name:t.name,...t.description?{description:t.description}:void 0,inputSchema:t.inputSchema,...t.outputSchema?{outputSchema:t.outputSchema}:void 0,...t.annotations?{annotations:t.annotations}:void 0,...t.instructions?{instructions:t.instructions}:void 0}):Y_(`Unknown tool: ${e.name}`)}),e.registerTool(`call_read_tool`,{description:`Execute a tool marked read-only after inspecting its schema with get_tool_details.`,inputSchema:iv,annotations:ov},async(e,t)=>{let i=r.get(e.name);return i?i.annotations?.readOnlyHint===!0?B_(i,e.arguments,W_(n,t)):Y_(`Tool is not read-only: ${e.name}`):Y_(`Unknown tool: ${e.name}`)}),e.registerTool(`call_write_tool`,{description:`Execute a writable or unclassified tool after inspecting its schema with get_tool_details.`,inputSchema:iv,annotations:sv},async(e,t)=>{let i=r.get(e.name);return i?i.annotations?.readOnlyHint===!0?Y_(`Tool is read-only: ${e.name}`):B_(i,e.arguments,W_(n,t)):Y_(`Unknown tool: ${e.name}`)})}function W_(e,t){return{env:e.env,extra:t,middlewares:e.middlewares,name:e.name,request:e.request?.(t),...e.sendNotification?{sendNotification:e.sendNotification}:void 0,vars:e.vars,version:e.version}}function G_(e,t){let n=q_(t),r=n.split(` `).filter(Boolean);return e.map(e=>({tool:e,score:K_(e,n,r)})).filter(({score:e})=>e>0).sort((e,t)=>t.score-e.score||e.tool.name.localeCompare(t.tool.name)).map(({tool:e})=>e)}function K_(e,t,n){let r=q_(e.name),i=q_(e.description??``);if(r===t)return 1e3;let a=r.startsWith(t)?100:r.includes(t)?50:0;for(let e of n)r.split(` `).includes(e)?a+=20:r.includes(e)&&(a+=10),i.includes(e)&&(a+=2);return a}function q_(e){return e.toLowerCase().replace(/[^a-z0-9]+/g,` `).trim()}function J_(e){return{content:[{type:`text`,text:Lr(e)}]}}function Y_(e){return{...J_({error:e}),isError:!0}}function X_(e,t,n=[],r){let i=$_(Z_(e,t,n),r);return tv(i),i.sort((e,t)=>e.name.localeCompare(t.name))}function Z_(e,t,n=[]){let r=[];for(let[i,a]of e){if(`_alias`in a||a.mcp===!1)continue;let e=[...t,i];if(`_group`in a&&a._group){let t=[...n,...a.middlewares??[]];a.root&&a.root.mcp!==!1&&r.push(Q_(a.root,e,t)),r.push(...Z_(a.commands,e,t))}else r.push(Q_(a,e,n))}return r}function Q_(e,t,n){let r=e.mcp===!1?void 0:e.mcp,i=e.output?nv(e.output):void 0;return{name:r?.name??t.join(`_`),description:r?.description??e.description,inputSchema:rv(e.args,e.options),...i?{outputSchema:i}:void 0,...r?.annotations?{annotations:r.annotations}:void 0,...r?.instructions?{instructions:r.instructions}:void 0,command:e,...n.length>0?{middlewares:n}:void 0}}function $_(e,t){if(!t)return e;let n=t.include?.map(ev),r=t.exclude?.map(ev)??[];return e.filter(e=>r.some(t=>t.test(e.name))?!1:!n||n.length===0||n.some(t=>t.test(e.name)))}function ev(e){let t=e.replace(/[|\\{}()[\]^$+?.]/g,`\\$&`).replace(/\*/g,`.*`);return RegExp(`^${t}$`)}function tv(e){let t=new Set;for(let n of e){if(t.has(n.name))throw Error(`Duplicate MCP tool name: ${n.name}`);t.add(n.name)}}function nv(e){let t=Ou(e);if(t.type===`object`)return t}function rv(e,t){let n={},r=[];for(let i of[e,t]){if(!i)continue;let e=Ou(i);Object.assign(n,e.properties??{}),r.push(...e.required??[])}return r.length>0?{type:`object`,properties:n,required:r}:{type:`object`,properties:n}}var iv,av,ov,sv,cv=I((()=>{tu(),yu(),zr(),ku(),iv=f.object({name:f.string().min(1).describe(`Exact tool name.`),arguments:f.record(f.string(),f.unknown()).default({}).describe(`Arguments from its schema.`)}),av={destructiveHint:!1,idempotentHint:!0,openWorldHint:!1,readOnlyHint:!0},ov={destructiveHint:!1,idempotentHint:!0,openWorldHint:!0,readOnlyHint:!0},sv={destructiveHint:!0,idempotentHint:!1,openWorldHint:!0,readOnlyHint:!1}}));function lv(e){return uv(e,e,new Map)}function uv(e,t,n){if(Array.isArray(e))return e.map(e=>uv(e,t,n));if(typeof e!=`object`||!e)return e;let r=e;if(typeof r.$ref==`string`&&r.$ref.startsWith(`#`)){let e=r.$ref;if(n.has(e))return n.get(e);let i=dv(t,e);if(typeof i!=`object`||!i||Array.isArray(i)){let r=uv(i,t,n);return n.set(e,r),r}let a={};n.set(e,a);let o=uv(i,t,n);return typeof o!=`object`||!o||Array.isArray(o)?(n.set(e,o),o):(Object.assign(a,o),a)}let i={};for(let e of Object.keys(r))i[e]=uv(r[e],t,n);return i}function dv(e,t){let n=t.slice(1);if(n===``||n===`/`)return e;let r=n.slice(1).split(`/`).map(e=>e.replace(/~1/g,`/`).replace(/~0/g,`~`)),i=e;for(let e of r){if(typeof i!=`object`||!i)throw Error(`Cannot resolve $ref "${t}": path segment "${e}" not found`);if(i=i[e],i===void 0)throw Error(`Cannot resolve $ref "${t}": "${e}" not found`)}return i}var fv=I((()=>{}));function pv(e,t={}){let n=_x.get(e);if(!n)throw Error(`No commands registered on this CLI instance`);let r={},i=bx.get(e);i&&gv(r,[],i);for(let[e,t]of n)mv(r,hv(e),t);return{openapi:`3.2.0`,info:{title:t.title??e.name,version:t.version??`0.0.0`,...t.description??e.description?{description:t.description??e.description}:void 0},...t.servers?{servers:t.servers}:void 0,paths:r}}function mv(e,t,n){if(!(`_alias`in n)&&!(`_fetch`in n)){if(`_group`in n){n.root&&gv(e,t,n.root);for(let[r,i]of n.commands)mv(e,[...t,...hv(r)],i);return}gv(e,t,n)}}function hv(e){return e.split(/\s+/).filter(Boolean)}function gv(e,t,n){let r=n.args?Ou(n.args):void 0,i=n.options?Ou(n.options):void 0,a=n.output?Ou(n.output):void 0,o=wv(r),s=new Set(Tv(r)),c=vv(t),l=_v(t,o,s);for(let r of l){let s=[];for(let e of r.args){let t=o[e]??{type:`string`};s.push({name:e,in:`path`,required:!0,schema:t})}if(c===`get`||c===`delete`)for(let[e,t]of Object.entries(wv(i)))s.push({name:e,in:`query`,...Tv(i).includes(e)?{required:!0}:void 0,schema:t});let l={operationId:Ev(t,c,r.args),...n.description?{summary:n.description}:void 0,...s.length?{parameters:s}:void 0,...bv(c,i),responses:xv(a)},u=e[r.path]??{};u[c]=l,e[r.path]=u}}function _v(e,t,n){let r=Object.keys(t),i=r.findIndex(e=>!n.has(e)),a=i===-1?r.length:i,o=[];for(let t=a;t<=r.length;t++){let n=r.slice(0,t),i=n.map(e=>`{${e}}`);o.push({args:n,path:`/${[...e,...i].map(Dv).join(`/`)}`})}return o.length===0&&o.push({args:[],path:`/${e.map(Dv).join(`/`)}`}),o}function vv(e){let t=e.map(yv).join(` `).toLowerCase();return/\b(delete|remove|rm|destroy|clear)\b/.test(t)?`delete`:/\b(update|edit|modify|set|enable|disable|rename|patch)\b/.test(t)?`patch`:/\b(get|list|show|read|search|find|status|describe|info|health|check)\b/.test(t)?`get`:`post`}function yv(e){return e.replace(/([a-z0-9])([A-Z])/g,`$1 $2`)}function bv(e,t){return!t||e===`get`||e===`delete`?{}:{requestBody:{required:Tv(t).length>0,content:{"application/json":{schema:t}}}}}function xv(e){return{200:{description:`Command completed successfully.`,content:{"application/json":{schema:{type:`object`,required:[`ok`,`data`,`meta`],properties:{ok:{const:!0},data:e??{},meta:Cv()}}}}},400:Sv(`Validation error.`),500:Sv(`Command failed.`)}}function Sv(e){return{description:e,content:{"application/json":{schema:{type:`object`,required:[`ok`,`error`,`meta`],properties:{ok:{const:!1},error:{type:`object`,required:[`code`,`message`],properties:{code:{type:`string`},message:{type:`string`},retryable:{type:`boolean`}}},meta:Cv()}}}}}}function Cv(){return{type:`object`,required:[`command`,`duration`],properties:{command:{type:`string`},duration:{type:`string`}}}}function wv(e){return e?.properties??{}}function Tv(e){return e?.required??[]}function Ev(e,t,n){return`${t}${[...e,...n.length?[n.join(` `)]:[]].join(` `).replace(/(?:^|[\s_-]+)(\w)/g,(e,t)=>t.toUpperCase())}`}function Dv(e){return e.startsWith(`{`)&&e.endsWith(`}`)?e:encodeURIComponent(e)}async function Ov(e,t={}){if(typeof e!=`string`&&!(e instanceof URL))return e;let n=await fetch(kv(e,t.baseUrl));if(!n.ok)throw Error(`Failed to fetch OpenAPI spec from ${e}: ${n.status}`);return await n.json()}function kv(e,t){if(e instanceof URL)return e;try{return new URL(e)}catch{if(t===void 0)throw Error(`Relative OpenAPI spec URL requires a fetch URL base: ${e}`);let n=new URL(t);return n.pathname.endsWith(`/`)||(n.pathname=`${n.pathname}/`),new URL(e,n)}}async function Av(e,t,n={}){let r=lv(structuredClone(e)),i=new Map,a=Mv(r.paths??{}),o=Bv(a),{config:s}=n;s?.compact&&Fv(a);for(let{method:e,operation:c,path:l}of a){let a=Vv({method:e,mode:s?.mode??`operation`,namespaceInfo:o,operation:c,path:l}),u=e.toUpperCase(),d=(c.parameters??[]).filter(e=>e.in===`path`),p=(c.parameters??[]).filter(e=>e.in===`query`),m=Rv([...(c.parameters??[]).filter(e=>e.in===`header`),...s?.security===!1?[]:Nv(r,c)]),h=c.requestBody?.content?.[`application/json`]?.schema,g=h?.properties??{},_=new Set(h?.required??[]),v;if(d.length>0){let e={};for(let t of d){let n=t.schema?Zv(t.schema):f.string();t.description&&(n=n.describe(t.description)),e[t.name]=Qv(n)}v=f.object(e)}let y={},b=new Set;for(let e of p){let t=e.schema?Zv(e.schema):f.string();e.required||(t=t.optional()),e.description&&(t=t.describe(e.description)),y[e.name]=Qv(t),b.add(e.name)}for(let[e,t]of Object.entries(g)){let n=Zv(t);_.has(e)||(n=n.optional()),y[e]=n,b.add(e)}for(let e of m){let t=zv(e.optionName,b);e.optionName=t;let n=e.schema?Zv(e.schema):f.string();e.required||(n=n.optional()),n=n.describe(e.description??`${e.name} header`),y[t]=Qv(n),b.add(t)}let x=Object.keys(y).length>0?f.object(y):void 0;Jv(i,a,{description:c.summary??c.description,mcp:{annotations:jv(e),...c.summary&&c.description&&c.summary!==c.description?{description:`${c.summary}\n\n${c.description}`}:void 0},args:v,options:x,run:Xv({basePath:n.basePath,fetch:t,forwardHeaders:s?.forwardHeaders,httpMethod:u,path:l,headerParams:m,pathParams:d,queryParams:p,bodyProps:g})})}return i}function jv(e){let t=[`get`,`head`,`options`,`trace`].includes(e);return{destructiveHint:!t,idempotentHint:t||e===`delete`||e===`put`,openWorldHint:!0,readOnlyHint:t}}function Mv(e){let t=[];for(let[n,r]of Object.entries(e))for(let[e,i]of Object.entries(r))$v.has(e)&&t.push({method:e,operation:i,path:n});return t}function Nv(e,t){let n=e.components?.securitySchemes??{},r=t.security??e.security??[],i=[];for(let e of r)for(let t of Object.keys(e)){let e=n[t],r=Pv(t,e);r&&i.push(r)}return i}function Pv(e,t){if(t){if(t.type===`apiKey`&&t.in===`header`&&t.name)return{description:t.description??`${t.name} header`,in:`header`,name:t.name,required:!1,schema:{type:`string`}};if(t.type===`http`&&ey.has(t.scheme?.toLowerCase()??``))return{description:t.description??`${e} authorization header`,in:`header`,name:`authorization`,required:!1,schema:{type:`string`}}}}function Fv(e){for(let{operation:t}of e){for(let e of t.parameters??[])e.schema&&=Iv(e.schema);let e=t.requestBody?.content?.[`application/json`];e?.schema&&(e.schema=Iv(e.schema))}}function Iv(e,t=new Map){let n=t.get(e);if(n)return n;let r={...e};t.set(e,r),delete r.example,delete r.examples,typeof r.pattern==`string`&&r.pattern.length>ty&&delete r.pattern,typeof r.format==`string`&&ny.has(r.format)&&delete r.format;for(let e of[`allOf`,`anyOf`,`oneOf`,`prefixItems`]){if(!Array.isArray(r[e]))continue;let n=r[e].map(e=>Iv(e,t)).filter(e=>Object.keys(e).length>0);n.length>0?r[e]=n:delete r[e]}for(let e of[`additionalProperties`,`contains`,`items`,`not`,`propertyNames`]){let n=r[e];Lv(n)&&(r[e]=Iv(n,t))}for(let e of[`$defs`,`patternProperties`,`properties`]){let n=r[e];if(!Lv(n))continue;let i={};for(let[e,r]of Object.entries(n))i[e]=Lv(r)?Iv(r,t):r;r[e]=i}return r}function Lv(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Rv(e){let t=new Set,n=[];for(let r of e){let e=r.name.toLowerCase();t.has(e)||(t.add(e),n.push({...r,optionName:e}))}return n}function zv(e,t){if(!t.has(e))return e;let n=`header-${e}`;if(!t.has(n))return n;for(let e=2;;e++){let r=`${n}-${e}`;if(!t.has(r))return r}}function Bv(e){let t=new Map,n=new Set;for(let{path:r}of e){t.set(r,(t.get(r)??0)+1);let e=Uv(r);for(let t=1;t<e.length;t++)n.add(`/${e.slice(0,t).join(`/`)}`)}return{parentPaths:n,pathOperations:t}}function Vv(e){let{method:t,mode:n,namespaceInfo:r,operation:i,path:a}=e;if(n===`operation`)return[{name:i.operationId??`${t}_${a.replace(/[/{}]/g,`_`)}`}];let o=Hv(a,i),s=o.length===0||r.parentPaths.has(Wv(a))||(r.pathOperations.get(a)??0)>1,c=qv(o,i.summary??i.description);return[...c.length>0?c:[{name:`root`}],...s?[{name:t}]:[]]}function Hv(e,t){return e.split(`/`).map(e=>Gv(e,t)).filter(Kv)}function Uv(e){return Hv(e).map(e=>e.name)}function Wv(e){return`/${Uv(e).join(`/`)}`}function Gv(e,t){if(!e)return;let n=e.startsWith(`{`)&&e.endsWith(`}`)?e.slice(1,-1):e,r=t?.parameters?.find(e=>e.in===`path`&&e.name===n)?.description;return{...r?{description:r}:void 0,name:n.replace(/[^\w.-]+/g,`-`)}}function Kv(e){return e!==void 0}function qv(e,t){return!t||e.length===0?e:e.map((n,r)=>r===e.length-1&&!n.description?{...n,description:t}:n)}function Jv(e,t,n){let[r,...i]=t;if(r){if(i.length===0){e.set(r.name,n);return}Jv(Yv(e,r).commands,i,n)}}function Yv(e,t){let n=e.get(t.name);if(n&&`_group`in n)return!n.description&&t.description&&(n.description=t.description),n;let r={_group:!0,commands:new Map,...t.description?{description:t.description}:void 0};return e.set(t.name,r),r}function Xv(e){return async t=>{let{args:n={},options:r={}}=t,i=(e.basePath??``)+e.path;for(let t of e.pathParams){let e=n[t.name];e!==void 0&&(i=i.replace(`{${t.name}}`,String(e)))}let a=new URLSearchParams;for(let t of e.queryParams){let e=r[t.name];e!==void 0&&a.set(t.name,String(e))}let o,s=Object.keys(e.bodyProps);if(s.length>0){let e={};for(let t of s)r[t]!==void 0&&(e[t]=r[t]);Object.keys(e).length>0&&(o=JSON.stringify(e))}let c={path:i,method:e.httpMethod,headers:new Headers,body:o,query:a};for(let t of e.headerParams){let e=r[t.optionName];e!==void 0&&c.headers.set(t.name,String(e))}for(let n of e.forwardHeaders??[]){let e=t.request?.headers.get(n);!c.headers.has(n)&&e!=null&&c.headers.set(n,e)}o&&!c.headers.has(`content-type`)&&c.headers.set(`content-type`,`application/json`);let l=On(c),u=await jn(await e.fetch(l));return u.ok?u.data:t.error({code:`HTTP_${u.status}`,message:typeof u.data==`object`&&u.data!==null&&`message`in u.data?String(u.data.message):typeof u.data==`string`?u.data:`HTTP ${u.status}`})}}function Zv(e){return f.fromJSONSchema(e)}function Qv(e){let t=e instanceof f.ZodOptional,n=t?e.unwrap():e,r=(()=>{if(n instanceof f.ZodNumber)return t?f.coerce.number().optional():f.coerce.number();if(n instanceof f.ZodBoolean)return t?f.coerce.boolean().optional():f.coerce.boolean();if(n instanceof f.ZodUnion){let e=n._zod?.def?.options;if(e?.some(e=>e instanceof f.ZodNumber))return t?f.coerce.number().optional():f.coerce.number();if(e?.some(e=>e instanceof f.ZodBoolean))return t?f.coerce.boolean().optional():f.coerce.boolean()}})();if(!r)return e;let i=e.description??n.description;return i?r.describe(i):r}var $v,ey,ty,ny,ry=I((()=>{Dx(),Pn(),fv(),ku(),$v=new Set([`delete`,`get`,`head`,`options`,`patch`,`post`,`put`,`trace`]),ey=new Set([`basic`,`bearer`]),ty=100,ny=new Set([`date`,`date-time`,`duration`,`time`])}));async function iy(e,t={}){let n=ly(e);await uy(n,`initialize`,{protocolVersion:gy,capabilities:{},clientInfo:{name:`incur`,version:t.version??`1.0.0`}}),n.initialized=!0,await uy(n,`notifications/initialized`);let r=(await uy(n,`tools/list`)).tools??[];return oy(r)?{discovery:`progressive`,tools:await sy(n),session:n}:{tools:r,session:n}}function ay(e){let t=new Map;for(let n of e.tools){let r=n.inputSchema?fy(n.inputSchema):void 0,i=py(n.outputSchema);t.set(n.name,{description:n.description,...n.annotations?{mcp:{annotations:n.annotations}}:void 0,...r?{options:r}:void 0,...i?{output:i}:void 0,async run(t){let r={name:n.name,arguments:{...t.args,...t.options}},i=await uy(e.session,`tools/call`,e.discovery===`progressive`?{name:n.annotations?.readOnlyHint===!0?`call_read_tool`:`call_write_tool`,arguments:r}:r);return i.isError?t.error({code:`MCP_TOOL_ERROR`,message:my(i)}):hy(i)}})}return t}function oy(e){if(e.length!==4)return!1;let t=new Set(e.map(e=>e.name));return t.has(`search_tools`)&&t.has(`get_tool_details`)&&t.has(`call_read_tool`)&&t.has(`call_write_tool`)}async function sy(e){let t=[],n=0;for(;n!==void 0;){let r=await cy(e,`search_tools`,{query:``,limit:20,offset:n});for(let n of r.tools??[]){if(!n.name)continue;let r=await cy(e,`get_tool_details`,{name:n.name});r.name&&t.push(r)}if(r.nextOffset!==void 0&&r.nextOffset<=n)throw Error(`MCP tool catalog returned a non-advancing offset`);n=r.nextOffset}return t}async function cy(e,t,n){let r=await uy(e,`tools/call`,{name:t,arguments:n});if(r.isError)throw Error(my(r)||`MCP tool failed: ${t}`);return hy(r)}function ly(e){return typeof e==`string`||e instanceof URL?{url:new URL(e),fetch:globalThis.fetch.bind(globalThis)}:{url:new URL(e.url),fetch:e.fetch??globalThis.fetch.bind(globalThis),...e.headers?{headers:e.headers}:void 0}}async function uy(e,t,n){let r=t.startsWith(`notifications/`),i=r?void 0:crypto.randomUUID(),a=new Headers(e.headers);a.set(`content-type`,`application/json`),a.set(`accept`,`application/json, text/event-stream`),e.id&&a.set(`mcp-session-id`,e.id),e.initialized&&a.set(`MCP-Protocol-Version`,gy);let o=JSON.stringify({jsonrpc:`2.0`,...i?{id:i}:void 0,method:t,params:n}),s=await e.fetch(new Request(e.url,{method:`POST`,headers:a,body:o})),c=s.headers.get(`mcp-session-id`);if(c&&(e.id=c),!s.ok)throw Error(`MCP HTTP ${s.status}`);if(r&&s.status===202)return{};let l=await s.text();if(!l)return{};let u=(s.headers.get(`content-type`)??``).includes(`text/event-stream`)?dy(l,i):JSON.parse(l);if(u.error)throw Error(u.error.message??`MCP request failed`);return u.result??{}}function dy(e,t){for(let n of e.split(/\r?\n\r?\n/)){let e=n.split(/\r?\n/).filter(e=>e.startsWith(`data:`)).map(e=>e.slice(5).trimStart()).join(`
185
185
  `);if(!e)continue;let r=JSON.parse(e);if(t===void 0||r.id===t)return r}throw Error(`MCP SSE response did not include the matching JSON-RPC message`)}function fy(e){let t=e.properties??{},n=new Set(e.required??[]),r={};for(let[e,i]of Object.entries(t)){let t=Zv(i);n.has(e)||(t=t.optional()),typeof i.description==`string`&&(t=t.describe(i.description)),r[e]=Qv(t)}return Object.keys(r).length>0?f.object(r):void 0}function py(e){if(!(!e||e.type!==`object`))try{return f.fromJSONSchema(e)}catch{return}}function my(e){return(Array.isArray(e.content)?e.content:[]).map(e=>e.type===`text`?e.text:``).filter(Boolean).join(`
186
- `)}function hy(e){if(e.structuredContent!==void 0)return e.structuredContent;let t=(Array.isArray(e.content)?e.content:[]).filter(e=>e.type===`text`).map(e=>e.text);if(t.length===1)try{return JSON.parse(t[0])}catch{return t[0]}return t}var gy,_y=F((()=>{ry(),gy=`2025-06-18`}));function vy(e,t,n){let r=[`# ${e}`];n&&r.push(``,n),r.push(``),r.push(`| Command | Description |`),r.push(`|---------|-------------|`);for(let n of t){let t=yy(e,n),i=n.description??``;r.push(`| \`${t}\` | ${i} |`)}return r.push(``,`Run \`${e} --llms-full\` for full manifest. Run \`${e} <command> --schema\` for argument details.`),r.join(`
187
- `)}function yy(e,t){let n=t.name?`${e} ${t.name}`:e;if(!t.args)return n;let r=t.args.shape,i=ku(t.args),a=new Set(i.required??[]),o=i.properties;return`${n} ${Object.keys(r).map(e=>{let t=o?.[e]?.type===`array`?`${e}...`:e;return a.has(e)?`<${t}>`:`[${t}]`}).join(` `)}`}function by(e,t,n=new Map){if(!(n.size>0))return t.map(t=>Cy(e,t)).join(`
186
+ `)}function hy(e){if(e.structuredContent!==void 0)return e.structuredContent;let t=(Array.isArray(e.content)?e.content:[]).filter(e=>e.type===`text`).map(e=>e.text);if(t.length===1)try{return JSON.parse(t[0])}catch{return t[0]}return t}var gy,_y=I((()=>{ry(),gy=`2025-06-18`}));function vy(e,t,n){let r=[`# ${e}`];n&&r.push(``,n),r.push(``),r.push(`| Command | Description |`),r.push(`|---------|-------------|`);for(let n of t){let t=yy(e,n),i=n.description??``;r.push(`| \`${t}\` | ${i} |`)}return r.push(``,`Run \`${e} --llms-full\` for full manifest. Run \`${e} <command> --schema\` for argument details.`),r.join(`
187
+ `)}function yy(e,t){let n=t.name?`${e} ${t.name}`:e;if(!t.args)return n;let r=t.args.shape,i=Ou(t.args),a=new Set(i.required??[]),o=i.properties;return`${n} ${Object.keys(r).map(e=>{let t=o?.[e]?.type===`array`?`${e}...`:e;return a.has(e)?`<${t}>`:`[${t}]`}).join(` `)}`}function by(e,t,n=new Map){if(!(n.size>0))return t.map(t=>Cy(e,t)).join(`
188
188
 
189
189
  `);let r=[`# ${e}`],i;for(let a of t){let t=a.name?a.name.split(` `)[0]:``;if(t!==i&&(i=t,t)){let i=n.get(t),a=i?`## ${e} ${t}\n\n${i}`:`## ${e} ${t}`;r.push(a)}r.push(Cy(e,a,t?3:2))}return r.join(`
190
190
 
191
- `)}function xy(e,t,n,r=new Map){if(n===0)return[{dir:``,content:Sy(e,e,t,r,e)}];let i=new Map;for(let r of t){if(!r.name){let t=Ey(e),n=i.get(t)??[];n.push(r),i.set(t,n);continue}let t=r.name.split(` `).slice(0,n).join(`-`),a=i.get(t)??[];a.push(r),i.set(t,a)}return[...i.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([t,i])=>{let a=i[0],o=a.name?a.name.split(` `).slice(0,n).join(` `):``;return{dir:t,content:Sy(e,o?`${e} ${o}`:e,i,r,o||void 0)}})}function Sy(e,t,n,r,i){let a=i?r.get(i):void 0,o=n.length===1&&n[0].description?n[0].description:void 0,s=a??o,c=s?`${s.replace(/\.$/,``)}. Run \`${t} --help\` for usage details.`:`Run \`${t} --help\` for usage details.`;return`${`---\n${_l().stringify({name:Ey(t),description:c,requires_bin:e,command:t},{lineWidth:0}).trimEnd()}\n---`}\n\n${n.map(t=>Cy(e,t)).join(`
191
+ `)}function xy(e,t,n,r=new Map){if(n===0)return[{dir:``,content:Sy(e,e,t,r,e)}];let i=new Map;for(let r of t){if(!r.name){let t=Ey(e),n=i.get(t)??[];n.push(r),i.set(t,n);continue}let t=r.name.split(` `).slice(0,n).join(`-`),a=i.get(t)??[];a.push(r),i.set(t,a)}return[...i.entries()].sort(([e],[t])=>e.localeCompare(t)).map(([t,i])=>{let a=i[0],o=a.name?a.name.split(` `).slice(0,n).join(` `):``;return{dir:t,content:Sy(e,o?`${e} ${o}`:e,i,r,o||void 0)}})}function Sy(e,t,n,r,i){let a=i?r.get(i):void 0,o=n.length===1&&n[0].description?n[0].description:void 0,s=a??o,c=s?`${s.replace(/\.$/,``)}. Run \`${t} --help\` for usage details.`:`Run \`${t} --help\` for usage details.`;return`${`---\n${gl().stringify({name:Ey(t),description:c,requires_bin:e,command:t},{lineWidth:0}).trimEnd()}\n---`}\n\n${n.map(t=>Cy(e,t)).join(`
192
192
 
193
193
  ---
194
194
 
195
- `)}`}function Cy(e,t,n=1){let r=t.name?`${e} ${t.name}`:e,i=[],a=e=>`#`.repeat(e),o=`${a(n)} ${r}`;t.description&&(o+=`\n\n${t.description}`),i.push(o);let s=a(n+1);if(t.args){let e=t.args.shape,n=ku(t.args),r=new Set(n.required??[]),a=n.properties,o=Object.entries(e).map(([e,t])=>{let n=a?.[e];return`| \`${e}\` | \`${Dy(n)}\` | ${r.has(e)?`yes`:`no`} | ${t.description??``} |`});i.push(`${s} Arguments\n\n| Name | Type | Required | Description |\n|------|------|----------|-------------|\n${o.join(`
196
- `)}`)}if(t.env){let e=t.env.shape,n=ku(t.env),r=new Set(n.required??[]),a=n.properties,o=Object.entries(e).map(([e,t])=>{let n=a?.[e],i=Dy(n),o=n?.default===void 0?``:String(n.default),s=r.has(e)?`yes`:`no`,c=t.description??``;return`| \`${e}\` | \`${i}\` | ${s} | ${o?`\`${o}\``:``} | ${c} |`});i.push(`${s} Environment Variables\n\n| Name | Type | Required | Default | Description |\n|------|------|----------|---------|-------------|\n${o.join(`
197
- `)}`)}if(t.options){let e=t.options.shape,n=ku(t.options).properties,r=Object.entries(e).map(([e,t])=>{let r=n?.[e],i=Dy(r),a=r?.default===void 0?``:String(r.default),o=t.description??``,s=r?.deprecated?`**Deprecated.** ${o}`:o;return`| \`--${e}\` | \`${i}\` | ${a?`\`${a}\``:``} | ${s} |`});i.push(`${s} Options\n\n| Flag | Type | Default | Description |\n|------|------|---------|-------------|\n${r.join(`
198
- `)}`)}if(t.output){let e=ku(t.output),n=Ty(e);if(n)i.push(`${s} Output\n\n${n}`);else{let t=Dy(e);i.push(`${s} Output\n\nType: \`${t}\``)}}if(t.examples&&t.examples.length>0){let n=t.examples.map(t=>`${t.description?`# ${t.description}\n`:``}${e} ${t.command}`);i.push(`${s} Examples\n\n\`\`\`sh\n${n.join(`
195
+ `)}`}function Cy(e,t,n=1){let r=t.name?`${e} ${t.name}`:e,i=[],a=e=>`#`.repeat(e),o=`${a(n)} ${r}`;t.description&&(o+=`\n\n${t.description}`),i.push(o);let s=a(n+1);if(t.args){let e=t.args.shape,n=Ou(t.args),r=new Set(n.required??[]),a=n.properties,o=Object.entries(e).map(([e,t])=>{let n=a?.[e];return`| \`${e}\` | \`${Dy(n)}\` | ${r.has(e)?`yes`:`no`} | ${t.description??``} |`});i.push(`${s} Arguments\n\n| Name | Type | Required | Description |\n|------|------|----------|-------------|\n${o.join(`
196
+ `)}`)}if(t.env){let e=t.env.shape,n=Ou(t.env),r=new Set(n.required??[]),a=n.properties,o=Object.entries(e).map(([e,t])=>{let n=a?.[e],i=Dy(n),o=n?.default===void 0?``:String(n.default),s=r.has(e)?`yes`:`no`,c=t.description??``;return`| \`${e}\` | \`${i}\` | ${s} | ${o?`\`${o}\``:``} | ${c} |`});i.push(`${s} Environment Variables\n\n| Name | Type | Required | Default | Description |\n|------|------|----------|---------|-------------|\n${o.join(`
197
+ `)}`)}if(t.options){let e=t.options.shape,n=Ou(t.options).properties,r=Object.entries(e).map(([e,t])=>{let r=n?.[e],i=Dy(r),a=r?.default===void 0?``:String(r.default),o=t.description??``,s=r?.deprecated?`**Deprecated.** ${o}`:o;return`| \`--${e}\` | \`${i}\` | ${a?`\`${a}\``:``} | ${s} |`});i.push(`${s} Options\n\n| Flag | Type | Default | Description |\n|------|------|---------|-------------|\n${r.join(`
198
+ `)}`)}if(t.output){let e=Ou(t.output),n=Ty(e);if(n)i.push(`${s} Output\n\n${n}`);else{let t=Dy(e);i.push(`${s} Output\n\nType: \`${t}\``)}}if(t.examples&&t.examples.length>0){let n=t.examples.map(t=>`${t.description?`# ${t.description}\n`:``}${e} ${t.command}`);i.push(`${s} Examples\n\n\`\`\`sh\n${n.join(`
199
199
 
200
200
  `)}\n\`\`\``)}return t.hint&&i.push(`> ${t.hint}`),i.join(`
201
201
 
202
- `)}function wy(e){let t=e.map(e=>({name:e.name,description:e.description,hint:e.hint,args:e.args?ku(e.args):void 0,env:e.env?ku(e.env):void 0,options:e.options?ku(e.options):void 0,output:e.output?ku(e.output):void 0}));return g(`sha256`).update(JSON.stringify(t)).digest(`hex`).slice(0,16)}function Ty(e,t=``){if(e.type!==`object`)return;let n=e.properties;if(!n||Object.keys(n).length===0)return;let r=new Set(e.required??[]),i=[];for(let[e,a]of Object.entries(n)){let n=t?`${t}.${e}`:e,o=Dy(a),s=r.has(e)?`yes`:`no`,c=a.description??``;if(i.push(`| \`${n}\` | \`${o}\` | ${s} | ${c} |`),a.type===`object`&&a.properties){let e=Ty(a,n);if(e){let t=e.split(`
202
+ `)}function wy(e){let t=e.map(e=>({name:e.name,description:e.description,hint:e.hint,args:e.args?Ou(e.args):void 0,env:e.env?Ou(e.env):void 0,options:e.options?Ou(e.options):void 0,output:e.output?Ou(e.output):void 0}));return g(`sha256`).update(JSON.stringify(t)).digest(`hex`).slice(0,16)}function Ty(e,t=``){if(e.type!==`object`)return;let n=e.properties;if(!n||Object.keys(n).length===0)return;let r=new Set(e.required??[]),i=[];for(let[e,a]of Object.entries(n)){let n=t?`${t}.${e}`:e,o=Dy(a),s=r.has(e)?`yes`:`no`,c=a.description??``;if(i.push(`| \`${n}\` | \`${o}\` | ${s} | ${c} |`),a.type===`object`&&a.properties){let e=Ty(a,n);if(e){let t=e.split(`
203
203
  `);i.push(...t.slice(2))}}if(a.type===`array`&&a.items){let e=a.items;if(e.type===`object`&&e.properties){let t=Ty(e,`${n}[]`);if(t){let e=t.split(`
204
204
  `);i.push(...e.slice(2))}}}}return`| Field | Type | Required | Description |\n|-------|------|----------|-------------|\n${i.join(`
205
- `)}`}function Ey(e){return e.toLowerCase().replace(/[^a-z0-9-]+/g,`-`).replace(/-{2,}/g,`-`).replace(/^-|-$/g,``)}function Dy(e){if(!e)return`unknown`;let t=e.type;return t?t===`integer`?`number`:t:`unknown`}var Oy=F((()=>{yl(),Au()}));async function ky(e,t={}){let n=nt(),r=t.command??jy(t.cli??e,n),i=t.agents??[],a=i.length===1&&i[0]===`amp`,o=[];if(!a){let a=[r,`--name`,e,`-y`];t.global!==!1&&a.push(`-g`);for(let e of i.filter(e=>e!==`amp`))a.push(`-a`,e);let[s,...c]=n.split(` `),{stdout:l}=await Ly(s,[...c,`add-mcp`,...a]);o.push(...l.split(`
205
+ `)}`}function Ey(e){return e.toLowerCase().replace(/[^a-z0-9-]+/g,`-`).replace(/-{2,}/g,`-`).replace(/^-|-$/g,``)}function Dy(e){if(!e)return`unknown`;let t=e.type;return t?t===`integer`?`number`:t:`unknown`}var Oy=I((()=>{vl(),ku()}));async function ky(e,t={}){let n=tt(),r=t.command??jy(t.cli??e,n),i=t.agents??[],a=i.length===1&&i[0]===`amp`,o=[];if(!a){let a=[r,`--name`,e,`-y`];t.global!==!1&&a.push(`-g`);for(let e of i.filter(e=>e!==`amp`))a.push(`-a`,e);let[s,...c]=n.split(` `),{stdout:l}=await Ly(s,[...c,`add-mcp`,...a]);o.push(...l.split(`
206
206
  `).filter(e=>e.includes(`✓`)||e.includes(`✔`)).map(e=>e.replace(/[│┃|]/g,``).replace(/.*[✓✔]\s*/,``).replace(/:.*/,``).trim()).filter(Boolean))}return(i.length===0||i.includes(`amp`))&&Ay(e,r)&&o.push(`Amp`),{command:r,agents:o}}function Ay(e,t){let n=d(S(),`.config`,`amp`,`settings.json`),s={};if(r(n))try{s=JSON.parse(a(n,`utf-8`))}catch{return!1}let[c,...l]=Iy(t);if(!c)return!1;let f=s[`amp.mcpServers`]??{};f[e]={command:c,args:l},s[`amp.mcpServers`]=f;let p=u(n);return r(p)||i(p,{recursive:!0}),o(n,JSON.stringify(s,null,2)+`
207
- `),!0}function jy(e,t){return Ny(e)?`${e} --mcp`:`${t} ${Fy(e)} --mcp`}function My(){let e=(process.argv[1]?.replace(/\\/g,`/`))?.match(/^(.+)\/node_modules\/(.+)$/);return e?{root:e[1],entry:e[2]}:null}function Ny(e){let t=process.argv[1];if(!t)return!1;let n=My();if(n)return!n.entry.startsWith(`.bin/`)&&!Py(n.root,e);let r=t.replace(/\\/g,`/`).split(`/`).pop();return r===e||r===`${e}.cmd`||r===`${e}.ps1`}function Py(e,t){try{let n=JSON.parse(a(d(e,`package.json`),`utf-8`));return[n.dependencies,n.devDependencies,n.optionalDependencies,n.peerDependencies].some(e=>t in(e??{}))}catch{return!1}}function Fy(e){let t=My();if(!t)return e;try{let n=JSON.parse(a(d(t.root,`package.json`),`utf-8`)).dependencies??{},r=n[e];if(!r||Object.keys(n).length!==1)return e;if(/^https?:\/\//.test(r)||r.startsWith(`file:`))return r;if(/^\d/.test(r))return`${e}@${r}`}catch{}return e}function Iy(e){let t=[],n=``,r=null;for(let i=0;i<e.length;i++){let a=e[i];r?a===r?r=null:n+=a:a===`"`||a===`'`?r=a:a===` `?(n&&t.push(n),n=``):n+=a}return n&&t.push(n),t}function Ly(e,t){return new Promise((n,r)=>{h(e,t,(e,t,i)=>{if(e){let n=i?.trim()||t?.trim()||e.message;r(Error(n))}else n({stdout:t,stderr:i})})})}var Ry=F((()=>{it()}));function zy(){return Yy.filter(e=>e.detect())}function By(e,n={}){let r=n.global!==!1,i=n.cwd||process.cwd(),a=r?K:i,o=c.join(a,`.agents`,`skills`),s=n.agents??zy(),l=[],u=[];for(let n of Hy(e)){let e=c.join(o,n.name);Wy(e),t.mkdirSync(e,{recursive:!0}),n.root?t.copyFileSync(c.join(n.dir,`SKILL.md`),c.join(e,`SKILL.md`)):t.cpSync(n.dir,e,{recursive:!0}),l.push(e);for(let a of s){if(a.universal)continue;let o=r?a.globalSkillsDir:c.join(i,a.projectSkillsDir),s=c.join(o,n.name);if(Gy(s)!==Gy(e))try{Wy(s),t.mkdirSync(c.dirname(s),{recursive:!0});let n=Gy(c.dirname(s)),r=Gy(e),i=c.relative(n,r);t.symlinkSync(i,s),u.push({agent:a.name,path:s,mode:`symlink`})}catch{try{t.cpSync(e,s,{recursive:!0}),u.push({agent:a.name,path:s,mode:`copy`})}catch{}}}}return{paths:l,agents:u}}function Vy(e,t={}){let n=t.global!==!1,r=t.cwd||process.cwd(),i=n?K:r;Wy(c.join(i,`.agents`,`skills`,e));for(let t of zy()){if(t.universal)continue;let i=n?t.globalSkillsDir:c.join(r,t.projectSkillsDir);Wy(c.join(i,e))}}function Hy(e){let n=[];function r(e){let i;try{i=t.readdirSync(e,{withFileTypes:!0})}catch{return}for(let a of i){if(!a.isDirectory())continue;let i=c.join(e,a.name),o=c.join(i,`SKILL.md`);if(t.existsSync(o)){let e=t.readFileSync(o,`utf8`).match(/^name:\s*(.+)$/m);n.push({name:Uy(e?.[1]??a.name),dir:i})}r(i)}}r(e);let i=c.join(e,`SKILL.md`);if(t.existsSync(i)){let r=Uy(t.readFileSync(i,`utf8`).match(/^name:\s*(.+)$/m)?.[1]??`skill`);n.some(e=>e.name===r)||n.push({name:r,dir:e,root:!0})}return n}function Uy(e){return e.trim().replace(/[/\\]/g,`-`).replace(/\.\./g,``).slice(0,255)}function Wy(e){try{t.lstatSync(e).isSymbolicLink()?t.unlinkSync(e):t.rmSync(e,{recursive:!0,force:!0})}catch{}}function Gy(e){try{return t.realpathSync(e)}catch{let n=c.dirname(e);if(n===e)return e;try{return c.join(t.realpathSync(n),c.relative(n,e))}catch{return e}}}var K,Ky,qy,Jy,Yy,Xy=F((()=>{K=b.homedir(),Ky=process.env.XDG_CONFIG_HOME||c.join(K,`.config`),qy=process.env.CLAUDE_CONFIG_DIR?.trim()||c.join(K,`.claude`),Jy=process.env.CODEX_HOME?.trim()||c.join(K,`.codex`),Yy=[{name:`Amp`,globalSkillsDir:c.join(Ky,`agents`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(c.join(Ky,`amp`))},{name:`Cline`,globalSkillsDir:c.join(K,`.agents`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(c.join(K,`.cline`))},{name:`Codex`,globalSkillsDir:c.join(Jy,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(Jy)},{name:`Cursor`,globalSkillsDir:c.join(K,`.cursor`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(c.join(K,`.cursor`))},{name:`Gemini CLI`,globalSkillsDir:c.join(K,`.gemini`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(c.join(K,`.gemini`))},{name:`GitHub Copilot`,globalSkillsDir:c.join(K,`.copilot`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(c.join(K,`.copilot`))},{name:`Kimi CLI`,globalSkillsDir:c.join(Ky,`agents`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(c.join(K,`.kimi`))},{name:`OpenCode`,globalSkillsDir:c.join(Ky,`opencode`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(c.join(Ky,`opencode`))},{name:`Claude Code`,globalSkillsDir:c.join(qy,`skills`),projectSkillsDir:`.claude/skills`,universal:!1,detect:()=>t.existsSync(qy)},{name:`Windsurf`,globalSkillsDir:c.join(K,`.codeium`,`windsurf`,`skills`),projectSkillsDir:`.windsurf/skills`,universal:!1,detect:()=>t.existsSync(c.join(K,`.codeium`,`windsurf`))},{name:`Continue`,globalSkillsDir:c.join(K,`.continue`,`skills`),projectSkillsDir:`.continue/skills`,universal:!1,detect:()=>t.existsSync(c.join(K,`.continue`))},{name:`Roo`,globalSkillsDir:c.join(K,`.roo`,`skills`),projectSkillsDir:`.roo/skills`,universal:!1,detect:()=>t.existsSync(c.join(K,`.roo`))},{name:`Kilo`,globalSkillsDir:c.join(K,`.kilocode`,`skills`),projectSkillsDir:`.kilocode/skills`,universal:!1,detect:()=>t.existsSync(c.join(K,`.kilocode`))},{name:`Goose`,globalSkillsDir:c.join(Ky,`goose`,`skills`),projectSkillsDir:`.goose/skills`,universal:!1,detect:()=>t.existsSync(c.join(Ky,`goose`))},{name:`Augment`,globalSkillsDir:c.join(K,`.augment`,`skills`),projectSkillsDir:`.augment/skills`,universal:!1,detect:()=>t.existsSync(c.join(K,`.augment`))},{name:`Trae`,globalSkillsDir:c.join(K,`.trae`,`skills`),projectSkillsDir:`.trae/skills`,universal:!1,detect:()=>t.existsSync(c.join(K,`.trae`))},{name:`Junie`,globalSkillsDir:c.join(K,`.junie`,`skills`),projectSkillsDir:`.junie/skills`,universal:!1,detect:()=>t.existsSync(c.join(K,`.junie`))},{name:`Crush`,globalSkillsDir:c.join(Ky,`crush`,`skills`),projectSkillsDir:`.crush/skills`,universal:!1,detect:()=>t.existsSync(c.join(Ky,`crush`))},{name:`Kiro CLI`,globalSkillsDir:c.join(K,`.kiro`,`skills`),projectSkillsDir:`.kiro/skills`,universal:!1,detect:()=>t.existsSync(c.join(K,`.kiro`))},{name:`Qwen Code`,globalSkillsDir:c.join(K,`.qwen`,`skills`),projectSkillsDir:`.qwen/skills`,universal:!1,detect:()=>t.existsSync(c.join(K,`.qwen`))},{name:`OpenHands`,globalSkillsDir:c.join(K,`.openhands`,`skills`),projectSkillsDir:`.openhands/skills`,universal:!1,detect:()=>t.existsSync(c.join(K,`.openhands`))}]}));async function Zy(e,t,n={}){let{depth:r=1,description:i,global:a=!0}=n,o=n.cwd??(a?eb():process.cwd());await gl();let s=new Map;i&&s.set(e,i);let c=xy(e,ax(t,[],s,n.rootCommand),r,s),u=await w.mkdtemp(l.join(x.tmpdir(),`incur-skills-${e}-`));try{let r=[];for(let t of c){let n=t.dir?l.join(u,t.dir,`SKILL.md`):l.join(u,`SKILL.md`);await w.mkdir(l.dirname(n),{recursive:!0}),await w.writeFile(n,`${t.content}\n`);let i=ux(t.content);r.push({name:i.name??(t.dir||e),description:i.description})}if(n.include)for(let t of n.include){let n=t===`_root`?`SKILL.md`:l.join(t,`SKILL.md`);for await(let i of w.glob(n,{cwd:o}))try{let n=await w.readFile(l.resolve(o,i),`utf8`),a=ux(n),s=t===`_root`?a.name??e:l.basename(l.dirname(i)),c=l.join(u,s,`SKILL.md`);await w.mkdir(l.dirname(c),{recursive:!0}),await w.writeFile(c,n),r.some(e=>e.name===s)||r.push({name:s,description:a.description,external:!0})}catch{}}let{paths:i,agents:s}=By(u,{global:a,cwd:o}),d=new Set(i.map(e=>l.basename(e))),f=rb(e);if(f?.skills)for(let e of f.skills)d.has(e)||Vy(e,{global:a,cwd:o});return nb(e,wy(ax(t,[],new Map,n.rootCommand)),[...d],[...i,...s.map(e=>e.path)]),{skills:r.sort((e,t)=>e.name.localeCompare(t.name)),paths:i,agents:s}}finally{await w.rm(u,{recursive:!0,force:!0})}}async function Qy(e,t,n={}){let{depth:r=1,description:i}=n,a=n.cwd??process.cwd();await gl();let o=new Map;i&&o.set(e,i);let s=xy(e,ax(t,[],o,n.rootCommand),r,o),c=[],u=ib(e,{cwd:a});for(let t of s){let n=ux(t.content),r=n.name??(t.dir||e);c.push({name:r,description:n.description,installed:u.has(r)})}if(n.include)for(let t of n.include){let n=t===`_root`?`SKILL.md`:l.join(t,`SKILL.md`);for await(let r of w.glob(n,{cwd:a}))try{let n=ux(await w.readFile(l.resolve(a,r),`utf8`)),i=t===`_root`?n.name??e:l.basename(l.dirname(r));c.some(e=>e.name===i)||c.push({name:i,description:n.description,installed:u.has(i)})}catch{}}return c.sort((e,t)=>e.name.localeCompare(t.name))}function $y(e,t={}){return ib(e,t).size>0}function eb(){let e=process.argv[1];if(!e)return process.cwd();let t=l.dirname((()=>{try{return n.realpathSync(e)}catch{return process.execPath}})()),r=l.parse(t).root;for(;t!==r;){try{return n.accessSync(l.join(t,`package.json`)),t}catch{}t=l.dirname(t)}return process.cwd()}function tb(e){let t=process.env.XDG_DATA_HOME||l.join(x.homedir(),`.local`,`share`);return l.join(t,`incur`,`${e}.json`)}function nb(e,t,r,i){let a=tb(e),o=l.dirname(a);n.existsSync(o)||n.mkdirSync(o,{recursive:!0}),n.writeFileSync(a,JSON.stringify({hash:t,skills:r,paths:i,at:new Date().toISOString()})+`
208
- `)}function rb(e){try{return JSON.parse(n.readFileSync(tb(e),`utf-8`))}catch{return}}function ib(e,t={}){let n=rb(e);if(!n?.skills?.length)return new Set;if(n.paths?.length){let e=n.paths.filter(e=>ab(e)).map(e=>l.basename(e));return new Set(e)}let r=t.cwd??process.cwd(),i=[l.join(x.homedir(),`.agents`,`skills`),l.join(r,`.agents`,`skills`)],a=n.skills.filter(e=>i.some(t=>ab(l.join(t,e))));return new Set(a)}function ab(e){return n.existsSync(l.join(e,`SKILL.md`))}function ob(e){return rb(e)?.hash}var sb=F((()=>{Dx(),Xy(),yl(),Oy()}));function cb(e,t){let n=typeof e==`string`?e:e.name,r=typeof e==`string`?t??{}:e,i=r.version??zt,a=`run`in r?r:void 0,o=`fetch`in r&&r.fetch!==void 0?r.fetch:void 0,s=o===void 0?void 0:Vb(o),c=o===void 0?void 0:Hb(o),l=new Map,u=[],d=[],f=ub(r.mcp?.name??n,i??`0.0.0`,{instructions:r.mcp?.instructions,stateless:r.mcp?.stateless,title:r.mcp?.title,tools:r.mcp?.tools});r.openapi&&s&&d.push((async()=>{let e=await Av(await Ov(r.openapi,{baseUrl:c}),s,{config:r.openapiConfig});for(let[t,n]of e)l.set(t,n)})());let p={name:n,description:r.description,env:r.env,vars:r.vars,command(e,t){if(typeof e==`string`){if(Bb(t))return d.push((async()=>{let n=ay(await iy(t.mcp)),r={_group:!0,description:t.description,commands:n,...t.outputPolicy?{outputPolicy:t.outputPolicy}:void 0};qb(e,r,wx.get(p)),l.set(e,r)})()),p;if(t&&`fetch`in t&&zb(t.fetch)){let n=Vb(t.fetch);return t.openapi?(d.push((async()=>{let r=await Av(await Ov(t.openapi,{baseUrl:Hb(t.fetch)}),n,{basePath:t.basePath,config:t.openapiConfig}),i={_group:!0,description:t.description,commands:r,...t.outputPolicy?{outputPolicy:t.outputPolicy}:void 0,...t.mcp===!1?{mcp:!1}:void 0};qb(e,i,wx.get(p)),l.set(e,i)})()),p):(l.set(e,{_fetch:!0,basePath:t.basePath,description:t.description,fetch:n,...t.outputPolicy?{outputPolicy:t.outputPolicy}:void 0}),p)}if(qb(e,t,wx.get(p)),l.set(e,t),t.aliases)for(let n of t.aliases)l.set(n,{_alias:!0,target:e});return p}let n=bx.get(e),r=e,i=_x.get(r),a=Cx.get(r),o=yx.get(r),s=vx.get(r),c=n&&i.size===0?n:{_group:!0,description:r.description,commands:i,...n?{root:n}:void 0,...a?{outputPolicy:a}:void 0,...o?.length?{middlewares:o}:void 0};if(s?.length?d.push(Promise.all(s).then(()=>{qb(r.name,c,wx.get(p))})):qb(r.name,c,wx.get(p)),l.set(r.name,c),n){let t=Tx.get(e);if(t)for(let n of t)l.set(n,{_alias:!0,target:e.name})}return p},async fetch(e){d.length>0&&await Promise.all(d);let t=wx.get(p);return pb(n,l,e,{description:r.description,envSchema:r.env,globals:t,mcpHandler:f,middlewares:u,name:n,rootCommand:a,vars:r.vars,version:i})},fs(e){let t=Su();return d.push((async()=>{let n=t?await Cu(t):await Fb(await Pb(e));for(let e of n){if(!Ib(e.command))throw Error(`Expected the default export from '${e.file}' to be created with \`Cli.command()\`.`);Lb(l,e.segments,e.command,e.file,wx.get(p))}})()),p},async serve(e=process.argv.slice(2),t={}){if(await Tt(e))return;d.length>0&&await Promise.all(d);let o=wx.get(p);return lb(n,l,e,{...t,aliases:r.aliases,banner:r.banner,config:r.config,description:r.description,envSchema:r.env,format:r.format,globals:o,mcp:r.mcp,middlewares:u,outputPolicy:r.outputPolicy,rootCommand:a,rootFetch:s,sync:r.sync,update:r.update,vars:r.vars,version:i})},use(e){return u.push(e),p}};if(a&&bx.set(p,a),a&&r.aliases&&Tx.set(p,r.aliases),r.options&&xx.set(p,r.options),r.config!==void 0&&Sx.set(p,!0),r.outputPolicy&&Cx.set(p,r.outputPolicy),r.globals){wx.set(p,{schema:r.globals,alias:r.globalAlias});let e=[`verbose`,`format`,`json`,`llms`,`llmsFull`,`mcp`,`help`,`incurBinaryApply`,`incurUpdateCheck`,`update`,`version`,`schema`,`filterOutput`,`tokenLimit`,`tokenOffset`,`tokenCount`,...r.config?.flag?[r.config.flag,`no${r.config.flag[0].toUpperCase()}${r.config.flag.slice(1)}`]:[]],t=Object.keys(r.globals.shape);for(let n of t)if(e.includes(n))throw Error(`Global option '${n}' conflicts with a built-in flag. Choose a different name.`);let n=new Set([`h`]);if(r.globalAlias){for(let[e,t]of Object.entries(r.globalAlias))if(n.has(t))throw Error(`Global alias '-${t}' for '${e}' conflicts with a built-in short flag. Choose a different alias.`)}}return yx.set(p,u),_x.set(p,l),vx.set(p,d),p}async function lb(e,t,n,r={}){let i=r.stdout??(e=>process.stdout.write(e)),a=r.exit??(e=>process.exit(e)),o=process.stdout.isTTY===!0,s=o,c=r.config!==void 0,l=r.config?.flag,u=px(e,r.aliases);function d(e){i(e.endsWith(`
209
- `)?e:`${e}\n`)}async function f(){if(!r.banner||w)return;let e=typeof r.banner==`function`?{render:r.banner,mode:`all`}:r.banner,t=e.mode??`all`;if(t===`all`||t===(s?`human`:`agent`))try{let t=await e.render();t&&d(t)}catch{}}let p;try{p=vb(n,{configFlag:l})}catch(e){let t=e instanceof Error?e.message:String(e);d(s?Jb({code:`UNKNOWN`,message:t}):bl({code:`UNKNOWN`,message:t},`toon`)),a(1);return}let{fullOutput:m,format:h,formatExplicit:g,filterOutput:_,tokenLimit:v,tokenOffset:y,tokenCount:b,llms:x,llmsFull:S,mcp:C,help:w,update:T,updateCheck:ee,version:E,schema:D,configPath:O,configDisabled:k,rest:te}=p;s=o&&!g;let ne={...typeof r.update==`object`?r.update:void 0,binary:Rt!==void 0,version:r.version},re={},A=te;function j(e){if(!r.globals)return!0;try{let t=Ul(te,r.globals.schema,r.globals.alias,{validate:e});return e&&(re=t.parsed),A=t.rest,!0}catch(e){let t=e instanceof Error?e.message:String(e);return d(s?Jb({code:`UNKNOWN`,message:t}):bl({code:`UNKNOWN`,message:t},`toon`)),a(1),!1}}if(!j(!1))return;if(h===`yaml`&&await gl(),ee){if(r.update!==!1)try{await ot(e,ne)}catch{}return}if(T&&!w){try{let t=await st(e,ne);if(s){let e=[t.deferred?`✓ Update staged for ${t.name}`:`✓ Updated ${t.name}`];t.command&&e.push(` ${t.command}`),t.deferred&&e.push(` Installation will finish after this process exits.`),d(e.join(`
210
- `))}else d(bl(t,h))}catch(e){let t={code:`UPDATE_FAILED`,message:e instanceof Error?e.message:String(e)};d(s?Jb(t):bl(t,h)),a(1)}return}if(C){await L_(r.mcp?.name??e,r.version??`0.0.0`,t,{middlewares:r.middlewares,env:r.envSchema,vars:r.vars,version:r.version,...r.mcp?.instructions?{instructions:r.mcp.instructions}:void 0,...r.mcp?.title?{title:r.mcp.title}:void 0,...r.mcp?.tools?{tools:r.mcp.tools}:void 0});return}let ie=process.env.COMPLETE;if(ie){let a=n.indexOf(`--`),o=a===-1?n:n.slice(a+1);if(o.length===0)i([e,...r.aliases??[]].map(e=>ln(ie,e)).join(`
211
- `));else{let e=Number(process.env._COMPLETE_INDEX??o.length-1),n=un(t,r.rootCommand,o,e,r.globals?{schema:r.globals.schema,alias:r.globals.alias}:void 0),a=o[e]??``,s=o.slice(0,e).filter(e=>!e.startsWith(`-`));if(s.length<=1)for(let e of tu)e.name.startsWith(a)&&!n.some(t=>t.value===e.name)&&n.push({value:e.name,description:e.description,...e.subcommands?{noSpace:!0}:void 0});else if(s.length===2){let e=s[s.length-1],t=Zl(e);if(t?.subcommands)for(let e of t.subcommands)for(let t of[e.name,...e.aliases??[]])t.startsWith(a)&&!n.some(e=>e.value===t)&&n.push({value:t,description:e.description})}let c=dn(ie,n);c&&i(c)}return}let ae;if(!x&&!S&&!D&&!w&&!T&&!ee&&!E){let n=Tb(A,e,`skills`)!==-1,i=Tb(A,e,`mcp`)!==-1;if(!n&&!i){let n=ob(e);n&&$y(e,{cwd:r.sync?.cwd})&&wy(ax(t,[],new Map,r.rootCommand))!==n&&(ae={description:`Skills are out of date:`,commands:[{command:process.env.npm_config_user_agent||process.env.npm_execpath?`${nt()} ${Fy(e)} skills add`:`${u} skills add`,description:`sync outdated skills`}]})}}if(x||S){let n=t,i=[],a=r.description,o=r.rootCommand;for(let e of A){let t=n.get(e);if(!t)break;let r=Kb(n,t);if(Ub(r))n=r.commands,a=r.description,o=r.root,i.push(e);else{n=new Map([[e,r]]),o=void 0;break}}i.length===0&&(o=r.rootCommand);let s=i.length>0?[]:i;if(S){if(!g||h===`md`){let t=new Map,r=ax(n,s,t,o);d(by(i.length>0?`${e} ${i.join(` `)}`:e,r,t));return}d(bl(nx(n,i,r.globals?.schema,o),h));return}if(!g||h===`md`){let t=ax(n,s,new Map,o);d(vy(i.length>0?`${e} ${i.join(` `)}`:e,t,a));return}d(bl(ex(n,i,r.globals?.schema,o),h));return}let oe=Tb(A,e,`completions`);if(oe!==-1){let t=A[oe+1];if(w||!t){let t=Zl(`completions`);d(iu(`${e} completions`,{args:t.args,description:t.description,hideGlobalOptions:!0,hint:t.hint?.(e)}));return}if(!eu.includes(t)){d(Jb({code:`INVALID_SHELL`,message:`Unknown shell '${t}'. Supported: ${eu.join(`, `)}`})),a(1);return}d([e,...r.aliases??[]].map(e=>ln(t,e)).join(`
212
- `));return}let se=Tb(A,e,`skills`);if(se!==-1){let o=Zl(`skills`),c=A[se+1],l=c?Ql(o,c):void 0;if(c&&!l){let t=sn(c,o.subcommands?.flatMap(e=>[e.name,...e.aliases??[]])??[]),r=`'${c}' is not a command for '${e} skills'.${t?` Did you mean '${t}'?`:``}`,i=[];if(t){let r=n.map(e=>e===c?t:e);i.push({command:`${e} ${r.join(` `)}`})}i.push({command:`${e} skills --help`,description:`see all available commands`});let l={description:i.length===1?`Suggested command:`:`Suggested commands:`,commands:i};s?(d(Jb({code:`COMMAND_NOT_FOUND`,message:r})),d(Yb(l))):d(bl({code:`COMMAND_NOT_FOUND`,message:r,cta:l},`toon`)),a(1);return}if(!c){d(Eb(e,o));return}if(l?.name===`list`){if(w){d(Db(e,o,`list`));return}try{let n=await Qy(e,t,{cwd:r.sync?.cwd,depth:r.sync?.depth??1,description:r.description,include:r.sync?.include,rootCommand:r.rootCommand});if(n.length===0){d(`No skills found.`);return}let i=[],a=Math.max(...n.map(e=>e.name.length));for(let e of n){let t=e.installed?`✓`:`✗`,n=e.description?`${` `.repeat(a-e.name.length)} ${e.description}`:``;i.push(` ${t} ${e.name}${n}`)}let o=n.filter(e=>e.installed).length;i.push(``),i.push(`${n.length} skill${n.length===1?``:`s`} (${o} installed)`),d(i.join(`
213
- `))}catch(e){d(bl({code:`LIST_SKILLS_FAILED`,message:e instanceof Error?e.message:String(e)},g?h:`toon`)),a(1)}return}if(w){d(Db(e,o,`add`));return}let u=A.slice(se+2),f=u.indexOf(`--depth`),p=u.find(e=>e.startsWith(`--depth=`)),_=f===-1?p?Number(p.split(`=`)[1]):r.sync?.depth??1:Number(u[f+1]),v=!u.includes(`--no-global`)&&void 0;try{i(`Syncing...`);let n=await Zy(e,t,{cwd:r.sync?.cwd,depth:_,description:r.description,global:v,include:r.sync?.include,rootCommand:r.rootCommand});i(`\r\x1B[K`);let a=[],o=e=>e.name,s=Math.max(...n.skills.map(e=>o(e).length));for(let e of n.skills){let t=o(e),n=e.description?`${` `.repeat(s-t.length)} ${e.description}`:``;a.push(` ✓ ${t}${n}`)}a.push(``),a.push(`${n.skills.length} skill${n.skills.length===1?``:`s`} synced`);let c=r.sync?.body;c&&(a.push(``),a.push(c));let l=r.sync?.suggestions;if(l&&l.length>0){a.push(``),a.push(`Your agent can now use ${e}. Try asking:`);for(let e of l)a.push(` "${e}"`)}if(a.push(``),a.push(`Run \`${e} --help\` to see the full command reference.`),d(a.join(`
214
- `)),m||g){let e={skills:n.paths};c&&(e.body=c),m&&n.agents.length>0&&(e.agents=n.agents),d(bl(e,g?h:`toon`))}}catch(e){d(bl({code:`SYNC_SKILLS_FAILED`,message:e instanceof Error?e.message:String(e)},g?h:`toon`)),a(1)}return}let ce=Tb(A,e,`mcp`);if(ce!==-1){let o=Zl(`mcp`),c=A[ce+1],l=c?Ql(o,c):void 0;if(c&&!l){let t=sn(c,o.subcommands?.flatMap(e=>[e.name,...e.aliases??[]])??[]),r=`'${c}' is not a command for '${e} mcp'.${t?` Did you mean '${t}'?`:``}`,i=[];if(t){let r=n.map(e=>e===c?t:e);i.push({command:`${e} ${r.join(` `)}`})}i.push({command:`${e} mcp --help`,description:`see all available commands`});let l={description:i.length===1?`Suggested command:`:`Suggested commands:`,commands:i};s?(d(Jb({code:`COMMAND_NOT_FOUND`,message:r})),d(Yb(l))):d(bl({code:`COMMAND_NOT_FOUND`,message:r,cta:l},`toon`)),a(1);return}if(!c){d(Eb(e,o));return}if(w){d(Db(e,o,l.name));return}if(l.name===`doctor`){let n=await Ob(e,t,r);d(bl(n,g?h:`toon`)),n.ok||a(1);return}let u=A.slice(ce+2),f=!u.includes(`--no-global`),p=r.mcp?.command,_=[...r.mcp?.agents??[]];for(let e=0;e<u.length;e++)(u[e]===`--command`||u[e]===`-c`)&&u[e+1]?p=u[++e]:u[e]===`--agent`&&u[e+1]&&_.push(u[++e]);try{let t=r.mcp?.name??e;i(`Registering MCP server...`);let n=await ky(t,{...t===e?void 0:{cli:e},command:p,global:f,agents:_});i(`\r\x1B[K`);let a=[];a.push(`✓ Registered ${t} as MCP server`),n.agents.length>0&&a.push(` Agents: ${n.agents.join(`, `)}`),a.push(``),a.push(`Agents can now use ${t} tools.`);let o=r.sync?.suggestions;if(o&&o.length>0){a.push(``),a.push(`Try asking:`);for(let e of o)a.push(` "${e}"`)}d(a.join(`
215
- `)),(m||g)&&d(bl({name:t,command:n.command,agents:n.agents},g?h:`toon`))}catch(e){d(bl({code:`MCP_ADD_FAILED`,message:e instanceof Error?e.message:String(e)},g?h:`toon`)),a(1)}return}if(E&&!w&&r.version){d(r.version);return}if(A.length===0){if(r.rootCommand&&s&&r.rootCommand.args&&Zb(r.rootCommand.args)){let n=r.rootCommand;await f(),d(iu(e,{alias:n.alias,aliases:r.aliases,configFlag:l,description:n.description??r.description,globals:r.globals,version:r.version,args:n.args,env:n.env,envSource:r.env,hint:n.hint,options:n.options,examples:lx(n.examples),usage:n.usage,commands:t.size>0?wb(t):void 0,root:!0}));return}if(!(r.rootCommand||r.rootFetch)){await f(),d(ru(e,{aliases:r.aliases,configFlag:l,description:r.description,globals:r.globals,version:r.version,commands:wb(t),root:!0}));return}}let M=A.length===0&&r.rootCommand?{command:r.rootCommand,path:e,rest:[]}:A.length===0&&r.rootFetch?{fetchGateway:{_fetch:!0,fetch:r.rootFetch,description:r.description},middlewares:[],path:e,rest:[]}:_b(t,A);if(w&&`fetchGateway`in M){let n=M.path===e?e:`${e} ${M.path}`;M.path===e&&t.size>0?d(ru(e,{aliases:r.aliases,configFlag:l,description:r.description,version:r.version,commands:wb(t),root:!0})):d(Nb(n,M.fetchGateway.description));return}if(w){if(`help`in M||`error`in M){let n=`help`in M?`${e} ${M.path}`:e,i=`help`in M?M.description:r.description,a=`help`in M?M.commands:t,o=n===e;if(o&&r.rootCommand&&a.size>0){let t=r.rootCommand;d(iu(e,{alias:t.alias,aliases:r.aliases,configFlag:l,description:t.description??r.description,globals:r.globals,version:r.version,args:t.args,env:t.env,envSource:r.env,hint:t.hint,options:t.options,examples:lx(t.examples),usage:t.usage,commands:wb(a),root:!0}))}else d(ru(n,{aliases:o?r.aliases:void 0,configFlag:l,description:i,globals:r.globals,version:o?r.version:void 0,commands:wb(a),root:o}))}else if(`command`in M){let n=M.command,i=M.path===e,a=i?e:`${e} ${M.path}`,o=`commands`in M&&M.commands&&M.commands.size>0?wb(M.commands):i&&r.rootCommand&&t.size>0?wb(t):void 0;d(iu(a,{alias:n.alias,aliases:i?r.aliases:n.aliases,configFlag:l,description:n.description,globals:r.globals,version:i?r.version:void 0,args:n.args,env:n.env,envSource:r.env,hint:n.hint,options:n.options,examples:lx(n.examples),usage:n.usage,commands:o,root:i}))}return}if(D){if(`help`in M){d(ru(`${e} ${M.path}`,{configFlag:l,description:M.description,globals:r.globals,commands:wb(M.commands)}));return}if(`error`in M){let t=M.path?`${e} ${M.path}`:e,n=sn(M.error,M.commands.keys()),r=n?` Did you mean '${n}'?`:``;d(`Error: '${M.error}' is not a command for '${t}'.${r}`),a(1);return}if(`fetchGateway`in M){d(`--schema is not supported for fetch commands.`),a(1);return}let t=M.command,n=g?h:`toon`,i={};t.args&&(i.args=ku(t.args)),t.env&&(i.env=ku(t.env)),t.options&&(i.options=ku(t.options)),t.output&&(i.output=ku(t.output)),r.globals?.schema&&(i.globals=ku(r.globals.schema)),d(bl(i,n));return}if(`help`in M){d(ru(`${e} ${M.path}`,{configFlag:l,description:M.description,globals:r.globals,commands:wb(M.commands)}));return}let le;if(s&&r.update!==!1){let t=at(e,ne);t&&(le={description:`Update available for ${t.name}:`,commands:[{command:`${u} --update`,description:`upgrade from ${t.current} to ${t.latest}`}]})}let ue=Xb(ae,le),de=performance.now(),fe=`command`in M&&M.command.format,pe=g?h:fe||r.format||`toon`;pe===`yaml`&&await gl();let me=`error`in M&&!M.path&&(()=>{let e=[...M.commands.keys()];for(let t of tu)e.push(t.name);return sn(M.error,e)!==void 0})(),N=`error`in M&&r.rootFetch&&!M.path&&!me?{fetchGateway:{_fetch:!0,fetch:r.rootFetch,description:r.description},middlewares:[],path:e,rest:A}:`error`in M&&r.rootCommand&&!M.path&&!me?{command:r.rootCommand,path:e,rest:A}:M,he=`outputPolicy`in M&&M.outputPolicy||r.outputPolicy,ge=!(s&&!g&&he===`agent-only`),_e=_?In(_):void 0;function ve(e){if(v==null&&y==null)return{text:e,truncated:!1};let t=qt(e),n=y??0,r=v==null?t:n+v;if(n===0&&r>=t)return{text:e,truncated:!1};let i=Jt(e,n,r),a=Math.min(r,t),o=a<t?a:void 0;return{text:`${i}\n[truncated: showing tokens ${n}–${a} of ${t}]`,truncated:!0,nextOffset:o}}function ye(e){if(_e&&e.ok&&e.data!=null&&(e={...e,data:Ln(e.data,_e)}),ue){let t=e.meta.cta;e={...e,meta:{...e.meta,cta:t?{description:t.description,commands:[...t.commands,...ue.commands]}:ue}}}if(b){let t=e.ok?e.data:e.error,n=t==null?``:bl(t,pe);return d(String(qt(n)))}let t=e.meta.cta;if(s&&!m){e.ok&&e.data!=null&&ge?d(ve(bl(e.data,pe)).text):e.ok||d(Jb(e.error)),t&&d(Yb(t));return}if(m){if(v!=null||y!=null){let t=ve(e.ok&&e.data!=null?bl(e.data,pe):e.ok?``:bl(e.error,pe));if(t.truncated){let n=e.ok?{ok:!0,data:t.text}:{ok:!1,error:t.text},r={...e.meta};return t.nextOffset!=null&&(r.nextOffset=t.nextOffset),n.meta=r,d(bl(n,pe))}}return d(bl(e,pe))}let n=e.ok?e.data:e.error,r=bl(n,pe);if(!t){r&&d(ve(r).text);return}d(ve(bl(typeof n==`object`&&n?{...n,cta:t}:{data:n,cta:t},pe)).text)}if(`error`in N){let t=N.path?`${e} ${N.path} --help`:`${e} --help`,r=N.path?`${e} ${N.path}`:e,i=`commands`in N?[...N.commands.keys()]:[];if(!N.path)for(let e of tu)i.push(e.name);let o=sn(N.error,i),c=o?` Did you mean '${o}'?`:``,l=`'${N.error}' is not a command for '${r}'.${c}`,u=[];if(o){let t=n.map(e=>e===N.error?o:e);u.push({command:`${e} ${t.join(` `)}`})}u.push({command:t,description:`see all available commands`});let f={description:u.length===1?`Suggested command:`:`Suggested commands:`,commands:u};if(s&&!m){d(Jb({code:`COMMAND_NOT_FOUND`,message:l})),d(Yb(ue?{...f,commands:[...f.commands,...ue.commands]}:f)),a(1);return}ye({ok:!1,error:{code:`COMMAND_NOT_FOUND`,message:l},meta:{command:N.error,cta:f,duration:`${Math.round(performance.now()-de)}ms`}}),a(1);return}if(`fetchGateway`in N){if(!j(!0))return;let{fetchGateway:t,path:n,rest:i}=N,o=[...r.middlewares??[],...N.middlewares??[]],c=async()=>{let r=On(i);t.basePath&&(r.path=t.basePath+r.path);let o=kn(r),c=await t.fetch(o);if(An(c)){await $b(jn(c),{name:e,path:n,start:de,format:pe,formatExplicit:g,human:s,renderOutput:ge,fullOutput:m,truncate:ve,write:ye,writeln:d,exit:a});return}let l=await Mn(c);l.ok?ye({ok:!0,data:l.data,meta:{command:n,duration:`${Math.round(performance.now()-de)}ms`}}):(ye({ok:!1,error:{code:`HTTP_${l.status}`,message:typeof l.data==`object`&&l.data!==null&&`message`in l.data?String(l.data.message):typeof l.data==`string`?l.data:`HTTP ${l.status}`},meta:{command:n,duration:`${Math.round(performance.now()-de)}ms`}}),a(1))};try{let t=r.envSchema?Bl(r.envSchema,r.env??process.env):{};if(o.length>0){let i=r.vars?r.vars.parse({}):{},l={agent:!s,command:n,displayName:u,env:t,error:e=>({[Ex]:`error`,...e}),format:pe,formatExplicit:g,globals:re,name:e,set(e,t){i[e]=t},var:i,version:r.version},d=e=>{if(!Qb(e)||e[Ex]!==`error`)return;let t=e,r=_u(u,t.cta);ye({ok:!1,error:{code:t.code,message:t.message,...t.retryable===void 0?void 0:{retryable:t.retryable}},meta:{command:n,duration:`${Math.round(performance.now()-de)}ms`,...r?{cta:r}:void 0}}),a(t.exitCode??1)};await o.reduceRight((e,t)=>async()=>{d(await t(l,e))},c)()}else await c()}catch(e){ye({ok:!1,error:{code:e instanceof I?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e)},meta:{command:n,duration:`${Math.round(performance.now()-de)}ms`}}),a(e instanceof I?e.exitCode??1:1)}return}let{command:be,path:xe,rest:P}=N;if(!j(!0))return;let Se=[...r.middlewares??[],...`middlewares`in M?M.middlewares??[]:[],...be.middleware??[]];s&&fx(P,be.options,be.alias);let Ce;if(c)try{Ce=await yb(e,xe,{configDisabled:k,configPath:O,files:r.config?.files,loader:r.config?.loader})}catch(e){ye({ok:!1,error:{code:e instanceof I?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e)},meta:{command:xe,duration:`${Math.round(performance.now()-de)}ms`}}),a(e instanceof I?e.exitCode??1:1);return}let we=await Kl(be,{agent:!s,argv:P,defaults:Ce,displayName:u,env:r.envSchema,envSource:r.env,format:pe,formatExplicit:g,globals:re,inputOptions:{},middlewares:Se,name:e,path:xe,vars:r.vars,version:r.version}),Te=`${Math.round(performance.now()-de)}ms`;if(`stream`in we){await $b(we.stream,{name:u,path:xe,start:de,format:pe,formatExplicit:g,human:s,renderOutput:ge,fullOutput:m,truncate:ve,write:ye,writeln:d,exit:a});return}if(we.ok){let e=_u(u,we.cta);ye({ok:!0,data:we.data,meta:{command:xe,duration:Te,...e?{cta:e}:void 0}})}else{let e=_u(u,we.cta);if(s&&!g&&we.error.fieldErrors){d(hb(u,xe,be,new Tn({message:we.error.message,fieldErrors:we.error.fieldErrors}),r.env,l)),a(1);return}ye({ok:!1,error:{code:we.error.code,message:we.error.message,...we.error.retryable===void 0?void 0:{retryable:we.error.retryable},...we.error.fieldErrors?{fieldErrors:we.error.fieldErrors}:void 0},meta:{command:xe,duration:Te,...e?{cta:e}:void 0}}),a(we.exitCode??1)}}function ub(e,t,n={}){let r;async function i(r,i,a){let{fromJsonSchema:o,McpServer:s,WebStandardStreamableHTTPServerTransport:c}=await Promise.resolve().then(()=>(I_(),s_)),l=new s({name:e,...n.title?{title:n.title}:void 0,version:t},n.instructions?{instructions:n.instructions}:void 0);V_(l,r,{env:i?.env,fromJsonSchema:o,middlewares:i?.middlewares,name:e,request:e=>e?.http?.req,sendNotification:e=>l.server.notification(e),tools:n.tools,vars:i?.vars,version:t});let u=new c(a?{enableJsonResponse:!0}:{sessionIdGenerator:()=>crypto.randomUUID(),enableJsonResponse:!0});return await l.connect(u),{server:l,transport:u}}return async(e,t,a)=>{let o=n.stateless??!0;if(o&&e.method!==`POST`)return new Response(null,{status:405,headers:{Allow:`POST`}});if(!o)return r??=i(t,a,!1).catch(e=>{throw r=void 0,e}),(await r).transport.handleRequest(e);let s=()=>e.signal.reason??new DOMException(`This operation was aborted`,`AbortError`);if(e.signal.aborted)throw s();let{server:c,transport:l}=await i(t,a,!0),u,d=()=>u??=c.close(),f,p=new Promise((e,t)=>{f=t}),m=!1,h=()=>{m||(m=!0,f(s()),d())};e.signal.addEventListener(`abort`,h,{once:!0}),e.signal.aborted&&h();try{return e.signal.aborted?await p:await Promise.race([l.handleRequest(e),p])}finally{e.signal.removeEventListener(`abort`,h),await d()}}}function db(e){return e.length===1?e[0]===`openapi.json`||e[0]===`openapi.yml`||e[0]===`openapi.yaml`:e[0]===`.well-known`&&e[1]===`openapi.json`&&e.length===2}function fb(e,t,n){let r={name:e,description:n.description};return _x.set(r,t),n.rootCommand&&bx.set(r,n.rootCommand),pv(r,{title:e,...n.version?{version:n.version}:void 0,...n.description?{description:n.description}:void 0})}async function pb(e,t,n,r={}){let i=performance.now(),a=new URL(n.url),o=a.pathname.split(`/`).filter(Boolean);if(n.method===`GET`&&db(o)){let n=fb(e,t,r),i=o[0]===`openapi.yml`||o[0]===`openapi.yaml`;return new Response(i?(await gl()).stringify(n):JSON.stringify(n),{status:200,headers:{"content-type":i?`application/yaml`:`application/json`,"cache-control":`public, max-age=300`}})}if(o[0]===`mcp`&&o.length===1&&r.mcpHandler)return r.mcpHandler(n,t,{middlewares:r.middlewares,env:r.envSchema,vars:r.vars});if(o[0]===`.well-known`&&o[1]===`skills`&&o.length>=3&&n.method===`GET`){await gl();let n=new Map,i=ax(t,[],n,r.rootCommand);if(o[2]===`index.json`&&o.length===3){let t=xy(e,i,1,n).map(t=>{let n=t.content.match(/^---\n([\s\S]*?)\n---/),r=n?_l().parse(n[1]):{};return{name:t.dir||e,description:r.description??``,files:[`SKILL.md`]}});return new Response(JSON.stringify({skills:t}),{status:200,headers:{"content-type":`application/json`,"cache-control":`public, max-age=300`}})}if(o.length===4&&o[3]===`SKILL.md`){let t=o[2],r=xy(e,i,1,n).find(n=>(n.dir||e)===t);return r?new Response(r.content,{status:200,headers:{"content-type":`text/markdown`,"cache-control":`public, max-age=300`}}):new Response(`Not Found`,{status:404})}return new Response(`Not Found`,{status:404})}let s={};if(n.method===`GET`)for(let[e,t]of a.searchParams)s[e]=t;else try{(n.headers.get(`content-type`)??``).includes(`application/json`)&&(s=await n.json())}catch{}function c(e,t){return new Response(Rr(e),{status:t,headers:{"content-type":`application/json`}})}if(o.length===0)return r.rootCommand?mb(e,r.rootCommand,[],s,n,i,r):c({ok:!1,error:{code:`COMMAND_NOT_FOUND`,message:`No root command defined.`},meta:{command:`/`,duration:`${Math.round(performance.now()-i)}ms`}},404);let l=_b(t,o);if(`error`in l){let t=l.path?`${e} ${l.path}`:e,n=sn(l.error,l.commands.keys()),r=n?` Did you mean '${n}'?`:``;return c({ok:!1,error:{code:`COMMAND_NOT_FOUND`,message:`'${l.error}' is not a command for '${t}'.${r}`},meta:{command:l.error,duration:`${Math.round(performance.now()-i)}ms`}},404)}if(`help`in l)return c({ok:!1,error:{code:`COMMAND_NOT_FOUND`,message:`'${l.path}' is a command group. Specify a subcommand.`},meta:{command:l.path,duration:`${Math.round(performance.now()-i)}ms`}},404);if(`fetchGateway`in l)return l.fetchGateway.fetch(n);let{command:u,path:d,rest:f}=l,p=`middlewares`in l?l.middlewares:[];return mb(d,u,f,s,n,i,{...r,groupMiddlewares:p})}async function mb(e,t,n,r,i,a,o){function s(e,t){return new Response(Rr(e),{status:t,headers:{"content-type":`application/json`}})}let c=[...o.middlewares??[],...o.groupMiddlewares??[],...t.middleware??[]],l={},u=r;if(o.globals){let t=new Set(Object.keys(o.globals.schema.shape)),n={};u={};for(let[e,i]of Object.entries(r))t.has(e)?n[e]=i:u[e]=i;try{l=o.globals.schema.parse(n)}catch(t){return s({ok:!1,error:{code:`VALIDATION_ERROR`,message:(t?.issues??t?.error?.issues??[]).map(e=>e.message).join(`; `)||`Validation failed`},meta:{command:e,duration:`${Math.round(performance.now()-a)}ms`}},400)}}let d=await Kl(t,{agent:!0,argv:n,env:o.envSchema,format:`json`,formatExplicit:!0,globals:l,inputOptions:u,middlewares:c,name:o.name??e,parseMode:`split`,path:e,request:i,vars:o.vars,version:o.version}),f=`${Math.round(performance.now()-a)}ms`;if(`stream`in d){let t=d.stream,n=new TextEncoder,r=t=>({command:e,duration:`${Math.round(performance.now()-a)}ms`,...t?{cta:t}:void 0}),i=t=>({type:`error`,ok:!1,error:{code:t.code,message:t.message,...t.retryable===void 0?void 0:{retryable:t.retryable}},meta:r(_u(o.name??e,t.cta))}),s=new ReadableStream({async cancel(){await t.return(void 0)},async pull(a){try{let{value:s,done:c}=await t.next();if(c){if(Qb(s)&&s[Ex]===`error`){a.enqueue(n.encode(Rr(i(s))+`
216
- `)),a.close();return}let t=Qb(s)&&s[Ex]===`ok`?_u(o.name??e,s.cta):void 0;a.enqueue(n.encode(Rr({type:`done`,ok:!0,meta:r(t)})+`
217
- `)),a.close();return}if(Qb(s)&&s[Ex]===`error`){a.enqueue(n.encode(Rr(i(s))+`
218
- `)),await t.return(void 0),a.close();return}a.enqueue(n.encode(Rr({type:`chunk`,data:s})+`
219
- `))}catch(e){a.enqueue(n.encode(Rr({type:`error`,ok:!1,error:{code:e instanceof I?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e),...e instanceof I?{retryable:e.retryable}:void 0},meta:r()})+`
220
- `)),a.close()}}});return new Response(s,{status:200,headers:{"content-type":`application/x-ndjson`}})}if(!d.ok){let t=_u(o.name??e,d.cta);return s({ok:!1,error:{code:d.error.code,message:d.error.message,...d.error.retryable===void 0?void 0:{retryable:d.error.retryable},...d.error.fieldErrors?{fieldErrors:d.error.fieldErrors}:void 0},meta:{command:e,duration:f,...t?{cta:t}:void 0}},d.error.code===`VALIDATION_ERROR`?400:500)}let p=_u(o.name??e,d.cta);return s({ok:!0,data:d.data,meta:{command:e,duration:f,...p?{cta:p}:void 0}},200)}function hb(e,t,n,r,i,a){let o=[];for(let e of r.fieldErrors){let t=(()=>{let t=gb(n,e.path);return e.missing?`Error: missing required ${t.kind} ${t.label}`:t.kind===`environment variable`?`Error: invalid value for environment variable ${t.label}: ${e.message}`:`Error: invalid value for ${t.label}: ${e.message}`})();o.push(t)}return o.push(`See below for usage.`),o.push(``),o.push(iu(t===e?e:`${e} ${t}`,{alias:n.alias,configFlag:a,description:n.description,args:n.args,env:n.env,envSource:i,hint:n.hint,options:n.options,examples:lx(n.examples),usage:n.usage})),o.join(`
221
- `)}function gb(e,t){let[n,...r]=t.split(`.`);if(!n)return{kind:`argument`,label:`input`};if(e.options?.shape[n]){let e=r.length>0?`.${r.join(`.`)}`:``;return{kind:`option`,label:`--${an(n)}${e}`}}return e.env?.shape[n]?{kind:`environment variable`,label:`${n}${r.length>0?`.${r.join(`.`)}`:``}`}:{kind:`argument`,label:`<${t}>`}}function _b(e,t){let[n,...r]=t;if(!n||!e.has(n))return{error:n??`(none)`,path:``,commands:e,rest:r};let i=Kb(e,e.get(n)),a=[n],o=r,s,c=[];if(Wb(i)){let e=i.outputPolicy??s;return{fetchGateway:i,middlewares:c,path:a.join(` `),rest:o,...e?{outputPolicy:e}:void 0}}for(;Ub(i);){i.outputPolicy&&(s=i.outputPolicy),i.middlewares&&c.push(...i.middlewares);let e=o[0];if(!e&&i.root){let e=i.root.outputPolicy??s;return{command:i.root,commands:i.commands,middlewares:c,path:a.join(` `),rest:o,...e?{outputPolicy:e}:void 0}}if(!e)return{help:!0,path:a.join(` `),description:i.description,commands:i.commands};let t=i.commands.get(e);if(!t){if(i.root&&!sn(e,i.commands.keys())){let e=i.root.outputPolicy??s;return{command:i.root,commands:i.commands,middlewares:c,path:a.join(` `),rest:o,...e?{outputPolicy:e}:void 0}}return{error:e,path:a.join(` `),commands:i.commands,rest:o.slice(1)}}let n=Kb(i.commands,t);if(a.push(e),o=o.slice(1),i=n,Wb(i)){let e=i.outputPolicy??s;return{fetchGateway:i,middlewares:c,path:a.join(` `),rest:o,...e?{outputPolicy:e}:void 0}}}let l=i.outputPolicy??s;return{command:i,middlewares:c,path:a.join(` `),rest:o,...l?{outputPolicy:l}:void 0}}function vb(e,t={}){let n=!1,r=!1,i=!1,a=!1,o=!1,s=!1,c=!1,l=!1,u=!1,d=`toon`,f=!1,p,m=!1,h,g,_,v=!1,y=[],b=t.configFlag?`--${t.configFlag}`:void 0,x=t.configFlag?`--${t.configFlag}=`:void 0,S=t.configFlag?`--no-${t.configFlag}`:void 0;for(let t=0;t<e.length;t++){let C=e[t];if(C===`--full-output`)n=!0;else if(C===`--llms`)r=!0;else if(C===`--llms-full`)i=!0;else if(C===`--mcp`)a=!0;else if(C===`--help`||C===`-h`)o=!0;else if(C===`--update`)s=!0;else if(C===`--incur-update-check`)c=!0;else if(C===`--version`&&(e[t+1]===void 0||e[t+1].startsWith(`-`)))l=!0;else if(C===`--schema`)u=!0;else if(C===`--json`)d=`json`,f=!0;else if(C===`--format`&&e[t+1]){if(!gx.has(e[t+1]))throw new En({message:`Invalid format: "${e[t+1]}". Expected one of: ${[...gx].join(`, `)}`});d=e[t+1],f=!0,t++}else if(b&&C===b){let n=e[t+1];if(n===void 0)throw new En({message:`Missing value for flag: ${b}`});p=n,m=!1,t++}else if(x&&C.startsWith(x)){let e=C.slice(x.length);if(e.length===0)throw new En({message:`Missing value for flag: ${b}`});p=e,m=!1}else if(S&&C===S)p=void 0,m=!0;else if(C===`--filter-output`&&e[t+1])h=e[t+1],t++;else if(C===`--token-limit`&&e[t+1]){let n=Number(e[t+1]);if(!Number.isFinite(n)||e[t+1].trim()===``)throw new En({message:`Invalid value for --token-limit: "${e[t+1]}"`});g=n,t++}else if(C===`--token-offset`&&e[t+1]){let n=Number(e[t+1]);if(!Number.isFinite(n)||e[t+1].trim()===``)throw new En({message:`Invalid value for --token-offset: "${e[t+1]}"`});_=n,t++}else C===`--token-count`?v=!0:y.push(C)}return{fullOutput:n,format:d,formatExplicit:f,configPath:p,configDisabled:m,filterOutput:h,tokenLimit:g,tokenOffset:_,tokenCount:v,llms:r,llmsFull:i,mcp:a,help:o,update:s,updateCheck:c,version:l,schema:u,rest:y}}async function yb(e,t,n={}){if(n.configDisabled)return;let{loader:r}=n,i;i=n.configPath?bb(n.configPath):await xb(n.files??[`${e}.json`]);let a;if(r){let e=await r(i);if(e===void 0)return;if(!rn(e))throw new En({message:`Config loader must return a plain object or undefined`});a=e}else{if(!i)return;let e=await Sb(i,!!n.configPath);if(!e)return;a=e}return Cb(a,e,t)}function bb(e){return e.startsWith(`~/`)||e===`~`?c.join(b.homedir(),e.slice(1)):c.resolve(process.cwd(),e)}async function xb(e){for(let t of e){let e=bb(t);try{return await C.access(e,C.constants.R_OK),e}catch{}}}async function Sb(e,t){let n;try{n=await C.readFile(e,`utf8`)}catch(n){if(n.code===`ENOENT`){if(t)throw new En({message:`Config file not found: ${e}`});return}throw n}let r;try{r=JSON.parse(n)}catch(t){throw new En({message:`Invalid JSON config file: ${e}`,cause:t instanceof Error?t:void 0})}if(!rn(r))throw new En({message:`Invalid config file: expected a top-level object in ${e}`});return r}function Cb(e,t,n){let r=n===t?[]:n.split(` `),i=e;for(let e of r){if(!rn(i))return;let t=i.commands;if(!rn(t)||(i=t[e],i===void 0))return}if(!rn(i))throw new En({message:`Invalid config section for '${n}': expected an object`});let a=i.options;if(a!==void 0){if(!rn(a))throw new En({message:`Invalid config 'options' for '${n}': expected an object`});return Object.keys(a).length>0?a:void 0}}function wb(e){let t=[];for(let[n,r]of e)Gb(r)||t.push({name:n,description:r.description});return t.sort((e,t)=>e.name.localeCompare(t.name))}function Tb(e,t,n){return Zl(e[0])?.name===n?0:e[0]===t&&Zl(e[1])?.name===n?1:-1}function Eb(e,t){return ru(`${e} ${t.name}`,{aliases:t.aliases,description:t.description,commands:t.subcommands?.map(e=>({name:e.name,description:e.description}))})}function Db(e,t,n){let r=Ql(t,n);return iu(`${e} ${t.name} ${n}`,{alias:r?.alias,aliases:r?.aliases,description:r?.description,hideGlobalOptions:!0,options:r?.options})}async function Ob(e,t,n){let r=[],i=[],a=new T,o=new T,s=[];o.on(`data`,e=>s.push(e.toString()));let c,l=L_(n.mcp?.name??e,n.version??`0.0.0`,t,{input:a,output:o,middlewares:n.middlewares,env:n.envSchema,vars:n.vars,version:n.version,...n.mcp?.instructions?{instructions:n.mcp.instructions}:void 0,...n.mcp?.title?{title:n.mcp.title}:void 0,tools:{...n.mcp?.tools,discovery:`direct`}}).catch(e=>{c=e}),u=!1;if(l.finally(()=>{u=!0}),a.write(`${Rr({jsonrpc:`2.0`,id:1,method:`initialize`,params:{protocolVersion:`2024-11-05`,capabilities:{},clientInfo:{name:`incur-doctor`,version:`1.0.0`}}})}\n`),a.write(`${Rr({jsonrpc:`2.0`,id:2,method:`tools/list`,params:{}})}\n`),await kb(s,()=>u),a.end(),await l,c)return{ok:!1,toolCount:0,tools:[],warnings:r,errors:[{code:`MCP_SERVER_FAILED`,message:jb(c)}]};let d;try{d=Ab(s)}catch(e){return{ok:!1,toolCount:0,tools:[],warnings:r,errors:[{code:`MCP_RESPONSE_PARSE_FAILED`,message:jb(e)}]}}let f=d.find(e=>e.id===1);f?f.error&&i.push({code:`MCP_INITIALIZE_FAILED`,message:Mb(f.error)}):i.push({code:`MCP_INITIALIZE_MISSING`,message:`Missing initialize response.`});let p=d.find(e=>e.id===2),m=[];return p?p.error?i.push({code:`MCP_TOOLS_LIST_FAILED`,message:Mb(p.error)}):!rn(p.result)||!Array.isArray(p.result.tools)?i.push({code:`MCP_TOOLS_LIST_INVALID`,message:`tools/list did not return a tools array.`}):m=p.result.tools.filter(rn).map(e=>({name:typeof e.name==`string`?e.name:``,...typeof e.description==`string`?{description:e.description}:void 0})).filter(e=>e.name):i.push({code:`MCP_TOOLS_LIST_MISSING`,message:`Missing tools/list response.`}),i.length===0&&m.length===0&&r.push(`No MCP tools exposed.`),{ok:i.length===0,toolCount:m.length,tools:m,warnings:r,errors:i}}async function kb(e,t){let n=Date.now();for(;!t()&&(e.join(``).match(/\n/g)?.length??0)<2;){if(Date.now()-n>=1e3)return;await new Promise(e=>setTimeout(e,5))}}function Ab(e){let t=[];for(let n of e.join(``).split(/\r?\n/)){let e=n.trim();if(!e)continue;let r=JSON.parse(e);if(!rn(r))throw Error(`Expected JSON-RPC response object.`);t.push(r)}return t}function jb(e){return e instanceof Error?e.message:String(e)}function Mb(e){return rn(e)&&typeof e.message==`string`?e.message:Rr(e)}function Nb(e,t){let n=[];return t?n.push(`${e} — ${t}`):n.push(e),n.push(``),n.push(`Usage: ${e} <path> [options]`),n.push(``),n.push(`Path segments are joined into the request URL path.`),n.push(``),n.push(`Options:`),n.push(` -X, --method <METHOD> HTTP method (default: GET, POST if body present)`),n.push(` -H, --header "Key: Val" Set a request header (repeatable)`),n.push(` -d, --data <json> Request body (implies POST)`),n.push(` --body <json> Request body (implies POST)`),n.push(` --<key> <value> Query string parameter`),n.join(`
222
- `)}async function Pb(e){if(e)return{directory:ee(e)};let t=process.argv[1];if(!t)throw Error("Could not infer the filesystem command directory without an executed entrypoint. Pass a directory URL to `fs()`.");let n=c.resolve(t);try{let e=await C.realpath(n);return{directory:c.dirname(e),exclude:e}}catch(e){if(e.code!==`ENOENT`)throw e;return{directory:c.dirname(n),exclude:n}}}async function Fb(e){let t=await xu(e.directory,{exclude:e.exclude});return Promise.all(t.map(async e=>({...e,command:(await import(E(e.file).href)).default})))}function Ib(e){return typeof e==`object`&&!!e&&e[hx]===!0}function Lb(e,t,n,r,i){let a=e;for(let[e,o]of t.entries()){let s=e===t.length-1,c=a.get(o);if(s){if(!c)a.set(o,n);else if(Ub(c)&&!c.root)c.root=n,c.description??=n.description;else throw Rb(t,r);qb(t.join(` `),n,i);for(let e of n.aliases??[]){if(a.has(e))throw Rb([...t.slice(0,-1),e],r);a.set(e,{_alias:!0,target:o})}return}if(!c){let e={_group:!0,commands:new Map};a.set(o,e),a=e.commands;continue}if(Gb(c)||Wb(c))throw Rb(t,r);if(Ub(c)){a=c.commands;continue}let l={_group:!0,commands:new Map,description:c.description,root:c};a.set(o,l),a=l.commands}}function Rb(e,t){return Error(`Filesystem command '${e.join(` `)}' from '${t}' conflicts with an existing command or alias.`)}function zb(e){if(typeof e==`function`)return!0;if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.fetch==`function`&&t.url instanceof URL}function Bb(e){if(typeof e!=`object`||!e||!(`mcp`in e))return!1;let t=e.mcp;return typeof t==`string`||t instanceof URL||typeof t==`object`&&!!t&&`url`in t}function Vb(e){return typeof e==`function`?e:e.fetch}function Hb(e){return typeof e==`function`?void 0:e.url}function Ub(e){return`_group`in e}function Wb(e){return`_fetch`in e}function Gb(e){return`_alias`in e}function Kb(e,t){return Gb(t)?e.get(t.target):t}function qb(e,t,n){if(!(!n||Wb(t)||Gb(t))){if(Ub(t)){t.root&&qb(e,t.root,n);for(let[r,i]of t.commands)qb(`${e} ${r}`,i,n);return}if(t.options){let r=Object.keys(n.schema.shape),i=Object.keys(t.options.shape);for(let t of i)if(r.includes(t))throw Error(`Command '${e}' option '${t}' conflicts with a global option. Choose a different name.`)}if(n.alias&&t.alias){let r=new Set(Object.values(n.alias));for(let[n,i]of Object.entries(t.alias))if(i&&r.has(i))throw Error(`Command '${e}' alias '-${i}' for '${n}' conflicts with a global alias. Choose a different alias.`)}}}function Jb(e){let t=`${e.code===`UNKNOWN`||e.code===`COMMAND_NOT_FOUND`?`Error`:`Error (${e.code})`}: ${e.message}`;if(e.fieldErrors)for(let n of e.fieldErrors)t+=`\n ${n.path}: ${n.message}`;return t}function Yb(e){let t=[``,e.description],n=Math.max(...e.commands.map(e=>e.command.length));for(let r of e.commands){let e=r.description?` ${``.padEnd(n-r.command.length)}# ${r.description}`:``;t.push(` ${r.command}${e}`)}return t.join(`
223
- `)}function Xb(...e){let t=e.filter(e=>e!==void 0);if(t.length!==0)return{description:t[0].description,commands:t.flatMap(e=>e.commands)}}function Zb(e){return Object.values(e.shape).some(e=>e._zod.optout!==`optional`)}function Qb(e){return typeof e==`object`&&!!e&&Ex in e}async function $b(e,t){let n=t.format===`jsonl`;if(n||!t.formatExplicit&&t.format===`toon`)try{let r;for(;;){let{value:i,done:a}=await e.next();if(a){r=i;break}if(Qb(i)){let e=i;if(e[Ex]===`error`){n?t.writeln(JSON.stringify({type:`error`,ok:!1,error:{code:e.code,message:e.message,...e.retryable===void 0?void 0:{retryable:e.retryable}}})):t.writeln(Jb({code:e.code,message:e.message})),t.exit(e.exitCode??1);return}}n?t.writeln(Rr({type:`chunk`,data:i})):t.renderOutput&&t.writeln(t.truncate(bl(i,t.format)).text)}if(Qb(r)&&r[Ex]===`error`){let e=r;n?t.writeln(JSON.stringify({type:`error`,ok:!1,error:{code:e.code,message:e.message,...e.retryable===void 0?void 0:{retryable:e.retryable}}})):t.writeln(Jb({code:e.code,message:e.message})),t.exit(e.exitCode??1);return}let i=Qb(r)&&r[Ex]===`ok`?_u(t.name,r.cta):void 0;n?t.writeln(JSON.stringify({type:`done`,ok:!0,meta:{command:t.path,duration:`${Math.round(performance.now()-t.start)}ms`,...i?{cta:i}:void 0}})):i&&t.writeln(Yb(i))}catch(e){n?t.writeln(JSON.stringify({type:`error`,ok:!1,error:{code:e instanceof I?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e),...e instanceof I?{retryable:e.retryable}:void 0}})):t.writeln(Jb({code:`UNKNOWN`,message:e instanceof Error?e.message:String(e)})),t.exit(e instanceof I?e.exitCode??1:1)}else{let n=[];try{let r;for(;;){let{value:i,done:a}=await e.next();if(a){r=i;break}if(Qb(i)){let e=i;if(e[Ex]===`error`){t.write({ok:!1,error:{code:e.code,message:e.message,...e.retryable===void 0?void 0:{retryable:e.retryable}},meta:{command:t.path,duration:`${Math.round(performance.now()-t.start)}ms`}}),t.exit(e.exitCode??1);return}}n.push(i)}if(Qb(r)&&r[Ex]===`error`){let e=r;t.write({ok:!1,error:{code:e.code,message:e.message,...e.retryable===void 0?void 0:{retryable:e.retryable}},meta:{command:t.path,duration:`${Math.round(performance.now()-t.start)}ms`}}),t.exit(e.exitCode??1);return}let i=Qb(r)&&r[Ex]===`ok`?_u(t.name,r.cta):void 0;t.write({ok:!0,data:n,meta:{command:t.path,duration:`${Math.round(performance.now()-t.start)}ms`,...i?{cta:i}:void 0}})}catch(e){t.write({ok:!1,error:{code:e instanceof I?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e),...e instanceof I?{retryable:e.retryable}:void 0},meta:{command:t.path,duration:`${Math.round(performance.now()-t.start)}ms`}}),t.exit(e instanceof I?e.exitCode??1:1)}}}function ex(e,t=[],n,r){let i=tx(e,t);return r&&t.length>0&&i.push({name:t.join(` `),...r.description?{description:r.description}:void 0}),{version:`incur.v1`,commands:i.sort((e,t)=>e.name.localeCompare(t.name)),...n?{globals:ku(n)}:void 0}}function tx(e,t){let n=[];for(let[r,i]of e){if(Gb(i))continue;let e=[...t,r];if(Ub(i)){if(i.root){let t={name:e.join(` `)};i.root.description&&(t.description=i.root.description),n.push(t)}n.push(...tx(i.commands,e))}else{let t={name:e.join(` `)};Wb(i),i.description&&(t.description=i.description),n.push(t)}}return n}function nx(e,t=[],n,r){let i=rx(e,t);return r&&t.length>0&&i.push(ix(t,r)),{version:`incur.v1`,commands:i.sort((e,t)=>e.name.localeCompare(t.name)),...n?{globals:ku(n)}:void 0}}function rx(e,t){let n=[];for(let[r,i]of e){if(Gb(i))continue;let e=[...t,r];if(Wb(i)){let t={name:e.join(` `)};i.description&&(t.description=i.description),n.push(t)}else Ub(i)?(i.root&&n.push(ix(e,i.root)),n.push(...rx(i.commands,e))):n.push(ix(e,i))}return n}function ix(e,t){let n={name:e.join(` `)};t.description&&(n.description=t.description);let r=dx(t.args,t.env,t.options),i=t.output?ku(t.output):void 0;(r||i)&&(n.schema={},r?.args&&(n.schema.args=r.args),r?.env&&(n.schema.env=r.env),r?.options&&(n.schema.options=r.options),i&&(n.schema.output=i));let a=lx(t.examples);if(a){let t=e.join(` `);n.examples=a.map(e=>({...e,command:e.command?`${t} ${e.command}`:t}))}return n}function ax(e,t,n,r){let i=[];if(r){let e={};r.description&&(e.description=r.description),r.args&&(e.args=r.args),r.env&&(e.env=r.env),r.hint&&(e.hint=r.hint),sx(r)&&(e.hint=cx(e.hint)),r.options&&(e.options=r.options),r.output&&(e.output=r.output);let t=lx(r.examples);t&&(e.examples=t),i.push(e)}for(let[r,a]of e){if(Gb(a))continue;let e=[...t,r];if(Wb(a)){let t={name:e.join(` `)};a.description&&(t.description=a.description),t.hint=`Fetch gateway. Pass path segments and curl-style flags (-X, -H, -d, --key value).`,i.push(t)}else Ub(a)?(a.description&&n.set(e.join(` `),a.description),a.root&&i.push(ox(e,a.root)),i.push(...ax(a.commands,e,n))):i.push(ox(e,a))}return i.sort((e,t)=>(e.name??``).localeCompare(t.name??``))}function ox(e,t){let n={name:e.join(` `)};t.description&&(n.description=t.description),t.args&&(n.args=t.args),t.env&&(n.env=t.env),t.hint&&(n.hint=t.hint),sx(t)&&(n.hint=cx(n.hint)),t.options&&(n.options=t.options),t.output&&(n.output=t.output);let r=lx(t.examples);if(r){let t=e.join(` `);n.examples=r.map(e=>({...e,command:e.command?`${t} ${e.command}`:t}))}return n}function sx(e){return e.destructive===!0||e.mcp!==!1&&e.mcp?.annotations?.destructiveHint===!0}function cx(e){return e?e.includes(mx)?e:`${e} ${mx}`:mx}function lx(e){if(!(!e||e.length===0))return e.map(e=>{let t=[];if(e.args)for(let n of Object.values(e.args))t.push(String(n));if(e.options)for(let[n,r]of Object.entries(e.options))t.push(`--${n} ${r}`);let n={command:t.join(` `)};return e.description&&(n.description=e.description),n})}function ux(e){let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!t)return{};let n=_l().parse(t[1]);return!n||typeof n!=`object`?{}:n}function dx(e,t,n){if(!e&&!t&&!n)return;let r={};return e&&(r.args=ku(e)),t&&(r.env=ku(t)),n&&(r.options=ku(n)),r}function fx(e,t,n){if(!t)return;let r=t.shape,i=new Set,a=new Map;for(let e of Object.keys(r))if(r[e]?.meta?.()?.deprecated){let t=e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`);i.add(t),n?.[e]&&a.set(n[e],t)}if(i.size!==0){for(let t of e)if(t.startsWith(`--`)){let e=t.split(`=`)[0].slice(2),n=!i.has(e)&&e.startsWith(`no-`)?e.slice(3):e;i.has(n)&&process.stderr.write(`Warning: --${n} is deprecated\n`)}else if(t.startsWith(`-`)&&t.length>=2)for(let e of t.slice(1))a.has(e)&&process.stderr.write(`Warning: --${a.get(e)} is deprecated\n`)}}function px(e,t){let n=process.argv[1];if(!n)return e;let r=c.basename(n);return r===e?e:t?.includes(r)?r:e}var mx,hx,gx,_x,vx,yx,bx,xx,Sx,Cx,wx,Tx,Ex,Dx=F((()=>{nn(),Bt(),Sn(),Dn(),Fn(),zn(),Ol(),gu(),nu(),bu(),Ou(),cn(),Br(),it(),wt(),yl(),cv(),_y(),ry(),Gl(),Au(),Oy(),Ry(),sb(),mx=`Confirm with the user before executing this destructive command.`,hx=Symbol.for(`incur.fileCommand`),gx=new Set([`toon`,`json`,`yaml`,`md`,`jsonl`]),_x=new WeakMap,vx=new WeakMap,yx=new WeakMap,bx=new WeakMap,xx=new WeakMap,Sx=new WeakMap,Cx=new WeakMap,wx=new WeakMap,Tx=new WeakMap,Ex=Symbol.for(`incur.sentinel`)})),Ox=F((()=>{Bt(),Dx(),Sn(),Dn(),Ol(),gu(),cv(),Fn(),ry(),Gl(),Au(),Oy(),yl(),Ry(),sb()}));function kx(e,t){if(!(!e||typeof e!=`object`))return e[t]}var q,Ax,jx,Mx,Nx,Px,Fx=F((()=>{q={acceptPayment:`Accept-Payment`,authorization:`Authorization`,paymentAuthorization:`Payment-Authorization`,paymentReceipt:`Payment-Receipt`,paymentSession:`Payment-Session`,paymentSessionSnapshot:`Payment-Session-Snapshot`,wwwAuthenticate:`WWW-Authenticate`},Ax={payment:`Payment`},jx={evm:`evm`,stripe:`stripe`,tempo:`tempo`},Mx={charge:`charge`,session:`session`,subscription:`subscription`},Nx={sessionProtocol:`sessionProtocol`,sessionSnapshot:`sessionSnapshot`},Px={v1:`v1`,v2:`v2`}}));function Ix(e){let t=k.toString(e);return JSON.parse(t)}function Lx(e,t){return e.schema.request.parse(t)}function Rx(e){let t=A.canonicalize(e);return k.fromString(t,{pad:!1,url:!0})}var zx=F((()=>{})),J=Qe({address:()=>Kx,amount:()=>Vx,datetime:()=>Hx,datetimeInput:()=>Ux,hash:()=>qx,period:()=>Jx,signature:()=>Yx,toDate:()=>Wx,toDatetimeString:()=>Gx,unwrapOptional:()=>Xx});import*as Bx from"zod/mini";et(J,Bx);function Vx(){return xe.string().check(xe.regex(/^\d+(\.\d+)?$/,`Invalid amount`))}function Hx(){return xe.string().check(xe.regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/,`Invalid ISO 8601 datetime`))}function Ux(e=`Invalid ISO 8601 datetime`){return xe.pipe(xe.union([Hx(),xe.custom(e=>e instanceof Date)]),xe.transform(Wx)).check(xe.refine(e=>Number.isFinite(e.getTime()),e))}function Wx(e){return e instanceof Date?e:new Date(e)}function Gx(e){return e instanceof Date?Number.isFinite(e.getTime())?e.toISOString():`Invalid Date`:e}function Kx(){return xe.string().check(xe.regex(/^0x[0-9a-fA-F]{40}$/,`Invalid address`))}function qx(){return xe.string().check(xe.regex(/^0x[0-9a-fA-F]{64}$/,`Invalid hash`))}function Jx(){return xe.string().check(xe.regex(/^(day|week|month|year|\d+)$/,`Invalid period`))}function Yx(){return xe.string().check(xe.regex(/^0x[0-9a-fA-F]+$/,`Invalid signature`))}function Xx(e){return e._zod.def.type===`optional`?e._zod.def.innerType:e}var Zx=F((()=>{}));function Qx(e,t){let{description:n,digest:r,meta:i,method:a,header:o,intent:s,realm:c,request:l,secretKey:u}=e,d=pS(o)?void 0:o,f=e.expires?Gx(e.expires):void 0,p=e.opaque??(i===void 0?void 0:Rx(i)),m=u?mS({...e,expires:f,...i!==void 0&&{meta:i},opaque:p},{secretKey:u}):e.id;return gS.parse({id:m,realm:c,method:a,intent:s,request:l,...n&&{description:n},...r&&{digest:r},...f&&{expires:f},...d!==void 0&&{header:d},...i!==void 0&&{meta:i},...p!==void 0&&{opaque:p}})}function $x(e){let t=[eS(`id`,e.id),eS(`realm`,e.realm),eS(`method`,e.method),eS(`intent`,e.intent),eS(`request`,Rx(e.request))];e.description!==void 0&&t.push(eS(`description`,e.description)),e.digest!==void 0&&t.push(eS(`digest`,e.digest)),e.expires!==void 0&&t.push(eS(`expires`,e.expires));let n=e.header;return n!==void 0&&!pS(n)&&t.push(eS(`header`,n)),e.opaque===void 0?e.meta!==void 0&&t.push(eS(`opaque`,Rx(e.meta))):t.push(eS(`opaque`,e.opaque)),`${Ax.payment} ${t.join(`, `)}`}function eS(e,t){if(/[\r\n]/.test(t))throw Error(`Invalid quoted-string value.`);return`${e}="${t.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/[\u0100-\uffff]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}"`}function tS(e,t){let n=nS(e);if(!n)throw Error(`Missing Payment scheme.`);let{request:r,opaque:i,...a}=rS(n);if(!r)throw Error(`Missing request parameter.`);if(r.length>hS)throw Error(`Request parameter too large.`);if(a.method&&!/^[a-z][a-z0-9:_-]*$/.test(a.method))throw Error(`Invalid method: "${a.method}". Must be lowercase per spec.`);return Qx({...a,request:Ix(r),...i&&{opaque:i}},t)}function nS(e){let t=Ax.payment,[n]=sS(e,t);if(n===void 0)return null;let r=n+t.length;for(;r<e.length&&/\s/.test(e[r]??``);)r++;return e.slice(r)}function rS(e){let t=Object.create(null),n=0;for(;n<e.length;){for(;n<e.length&&/[\s,]/.test(e[n]??``);)n++;if(n>=e.length)break;let r=n;for(;n<e.length&&/[A-Za-z0-9_-]/.test(e[n]??``);)n++;let i=e.slice(r,n).toLowerCase();if(!i)throw Error(`Malformed auth-param.`);for(;n<e.length&&/\s/.test(e[n]??``);)n++;if(e[n]!==`=`)break;for(n++;n<e.length&&/\s/.test(e[n]??``);)n++;let[a,o]=iS(e,n);if(n=o,i in t)throw Error(`Duplicate parameter: ${i}`);t[i]=a}return t}function iS(e,t){if(e[t]===`"`)return aS(e,t+1);let n=t;for(;n<e.length&&e[n]!==`,`;)n++;return[e.slice(t,n).trim(),n]}function aS(e,t){let n=t,r=!1,i=t,a;for(;n<e.length;){let o=e[n];if(n++,r){a??=[];let t=o===`u`?e.slice(n,n+4):void 0;t&&/^[0-9A-Fa-f]{4}$/.test(t)?(a.push(String.fromCharCode(Number.parseInt(t,16))),n+=4):a.push(o),i=n,r=!1;continue}if(o===`\\`){a??=[],a.push(e.slice(i,n-1)),i=n,r=!0;continue}if(o===`"`)return[a?[...a,e.slice(i,n-1)].join(``):e.slice(t,n-1),n]}throw Error(`Unterminated quoted-string.`)}function oS(e,t,n){if(e.slice(t,t+n.length).toLowerCase()!==n.toLowerCase())return!1;let r=e[t+n.length];return!!(r&&/\s/.test(r))}function sS(e,t){let n=[],r=!1,i=!1;for(let a=0;a<e.length;a++){let o=e[a];if(r){i?i=!1:o===`\\`?i=!0:o===`"`&&(r=!1);continue}if(o===`"`){r=!0;continue}if(!oS(e,a,t))continue;let s=a-1;for(;s>=0&&/\s/.test(e[s]??``);)s--;s>=0&&e[s]!==`,`||n.push(a)}return n}function cS(e,t){if(e.status!==402)throw Error(`Response status is not 402.`);return lS(e.headers,t)}function lS(e,t){let n=e.get(q.wwwAuthenticate);if(!n)throw Error(`Missing ${q.wwwAuthenticate} header.`);return uS(n,t)}function uS(e,t){let n=sS(e,Ax.payment);if(n.length===0)throw Error(`No Payment schemes found.`);return n.map((r,i)=>{let a=i+1<n.length?n[i+1]:e.length;return tS(e.slice(r,a).replace(/,\s*$/,``),t)})}function dS(e){let t=[e.realm,e.method,e.intent,Rx(e.request),e.expires??``,e.digest??``],n=e.header;return n!==void 0&&!pS(n)&&t.push(n),t.push(e.opaque??(e.meta?Rx(e.meta):``)),t.join(`|`)}function fS(e){return e.header??q.authorization}function pS(e){return e?.toLowerCase()===q.authorization.toLowerCase()}function mS(e,t){let n=dS(e),r=te.fromString(t.secretKey),i=te.fromString(n),a=ne.hmac256(r,i,{as:`Bytes`});return k.fromBytes(a,{url:!0,pad:!1})}var hS,gS,_S=F((()=>{Fx(),zx(),Zx(),hS=16384,gS=J.object({description:J.optional(J.string()),digest:J.optional(J.string().check(J.regex(/^sha-256=/,`Invalid digest format`))),expires:J.optional(Hx()),header:J.optional(J.string().check(J.regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,`Invalid HTTP header name`))),id:J.string().check(J.minLength(1)),intent:J.string(),method:J.string(),meta:J.optional(J.record(J.string(),J.string())),opaque:J.optional(J.string()),realm:J.string(),request:J.record(J.string(),J.unknown())})})),vS,yS,Y,bS,xS,SS=F((()=>{vS=class extends Error{details;status=402;hint;constructor(e,t={}){super(e),this.details=t.details,t.cause!==void 0&&Object.defineProperty(this,"cause",{configurable:!0,value:t.cause,writable:!0})}toProblemDetails(e){return{type:this.type,title:this.title,status:this.status,detail:this.message,...this.details&&Object.keys(this.details).length>0&&{details:this.details},...this.hint&&{hint:this.hint},...e&&{challengeId:e}}}},yS=class extends vS{name=`InvalidChallengeError`;title=`Invalid Challenge`;status=402;type=`https://paymentauth.org/problems/invalid-challenge`;constructor(e={}){let{id:t,reason:n}=e,r=t?` "${t}"`:``,i=n?`: ${n}`:``;super(`Challenge${r} is invalid${i}.`)}},Y=class extends vS{name=`VerificationFailedError`;title=`Verification Failed`;type=`https://paymentauth.org/problems/verification-failed`;constructor(e={}){let{details:t,reason:n}=e;super(n?`Payment verification failed: ${n}.`:`Payment verification failed.`,{details:t})}},bS=class extends vS{name=`PaymentExpiredError`;title=`Payment Expired`;type=`https://paymentauth.org/problems/payment-expired`;constructor(e={}){let{expires:t}=e;super(t?`Payment expired at ${t}.`:`Payment has expired.`)}},xS=class extends vS{name=`PaymentOutcomeUnknownError`;title=`Payment Outcome Unknown`;type=`https://paymentauth.org/problems/payment-outcome-unknown`;challenge;credential;transactionHash;constructor(e){let{cause:t,challenge:n,credential:r,transactionHash:i}=e;super(`Payment outcome is unknown after sending a credential for challenge "${n.id}". Do not blindly retry.`,{cause:t}),this.challenge=n,this.credential=r,this.transactionHash=i}}}));function CS(e,t){if(!e)throw new yS({...t&&{id:t},reason:`missing required expires field`});if(Number.isNaN(new Date(e).getTime()))throw new yS({...t&&{id:t},reason:`malformed expires timestamp`});if(new Date(e)<new Date)throw new bS({expires:e})}var wS=F((()=>{SS()}));function TS(e){return Object.defineProperty(e,DS,{value:!0}),e}function ES(e){return!!e?.[DS]}var DS,OS=F((()=>{DS=Symbol.for(`mppx.x402.challenge`)}));function kS(e){let t={};for(let n of e){let e=t[n.name]??={};e[n.intent]=FS(n)}return t}function AS(e,t){let n=kS(e),r=HS(e,n,t),i=e.map((e,t)=>({intent:e.intent,method:e.name,q:r[FS(e)]??1,index:t}));return{definition:r,entries:i,header:MS(i),keys:n}}function jS(e){let t=e.split(/\s*,\s*/).map(e=>e.trim()).filter(Boolean);if(t.length===0)throw Error(`Accept-Payment header is empty.`);return t.map((e,t)=>BS(e,t))}function MS(e){return e.map(({method:e,intent:t,q:n})=>{let r=`${e}/${t}`;return n===1?r:`${r};q=${KS(n)}`}).join(`, `)}function NS(e,t,n){let r=PS(e,t,n)[0];if(r)return{challenge:r.challenge,method:r.method}}function PS(e,t,n){let r=new Map;for(let e of t){let t=FS(e),n=r.get(t);n?n.push(e):r.set(t,[e])}return e.flatMap((e,t)=>{let i=r.get(FS(e));if(!i)return[];let a=IS(e,n);return!a||a.q<=0?[]:i.filter(t=>t.canHandleChallenge?.({challenge:e})??!0).map(n=>({challenge:e,index:t,match:a,method:n}))}).sort((e,t)=>zS(e.challenge)-zS(t.challenge)||t.match.q-e.match.q||e.index-t.index).map(e=>{let{match:t,...n}=e;return n})}function FS(e){let t=e.method??e.name;if(!t)throw Error(`Missing payment method name.`);return`${t}/${e.intent}`}function IS(e,t){let n;for(let r of t){if(!LS(e,r))continue;let t={...r,specificity:RS(r)};(!n||t.specificity>n.specificity||t.specificity===n.specificity&&t.q>n.q||t.specificity===n.specificity&&t.q===n.q&&t.index<n.index)&&(n=t)}return n}function LS(e,t){return(t.method===`*`||t.method===e.method)&&(t.intent===`*`||t.intent===e.intent)}function RS(e){return Number(e.method!==`*`)+Number(e.intent!==`*`)}function zS(e){return+!!ES(e)}function BS(e,t){let n=/^(?<method>[^/;\s]+|\*)\s*\/\s*(?<intent>[^/;\s]+|\*)(?<params>(?:\s*;\s*.+)?)$/u.exec(e),r=n?.groups?.method,i=n?.groups?.intent;if(!r||!i)throw Error(`Invalid Accept-Payment entry: ${e}`);qS(r,`method`),qS(i,`intent`);let a=1;for(let t of VS(n.groups?.params)){if(!t)continue;let n=/^(?<name>[A-Za-z0-9_-]+)\s*=\s*(?<value>\S+)$/u.exec(t),r=n?.groups?.name,i=n?.groups?.value;if(!r||!i)throw Error(`Invalid Accept-Payment parameter: ${t}`);r===`q`&&(a=WS(i,`Accept-Payment entry "${e}"`))}return{intent:i,method:r,q:a,index:t}}function VS(e){return e?e.split(/\s*;\s*/).filter(Boolean):[]}function HS(e,t,n){if(!n)return{};let r=typeof n==`function`?n(t):n,i=new Set(e.map(e=>FS(e))),a={};for(let[e,t]of Object.entries(r??{})){if(!i.has(e))throw Error(`Unknown payment preference "${e}". Available: ${[...i].join(`, `)}`);a[e]=US(t,`payment preference "${e}"`)}return a}function US(e,t){if(typeof e!=`number`||Number.isNaN(e)||!Number.isFinite(e))throw Error(`Invalid q-value for ${t}. Expected a finite number.`);return GS(e,t)}function WS(e,t){if(!/^0(?:\.\d{0,3})?$|^1(?:\.0{0,3})?$/.test(e))throw Error(`Invalid q-value for ${t}. Expected an HTTP qvalue.`);return GS(Number(e),t)}function GS(e,t){if(e<0||e>1)throw Error(`Invalid q-value for ${t}. Expected a value between 0 and 1.`);let n=Math.round(e*1e3);if(Math.abs(e*1e3-n)>1e-9)throw Error(`Invalid q-value for ${t}. Expected at most 3 decimal places.`);return n/1e3}function KS(e){return e.toFixed(3).replace(/\.0+$/,``).replace(/(\.\d*?)0+$/,`$1`)}function qS(e,t){if(e!==`*`&&!/^[a-z0-9-]+$/.test(e))throw Error(`Invalid Accept-Payment ${t}: ${e}`)}var JS=F((()=>{OS()}));function YS(e){let t=e.match(RegExp(`^${Ax.payment}\\s+(.+)$`,`i`));if(!t?.[1])throw new eC;try{let e=k.toString(t[1]),n=JSON.parse(e),{opaque:r,request:i,meta:a,...o}=n.challenge,{meta:s,opaque:c}=XS(r);return{challenge:gS.parse({...o,...s!==void 0&&{meta:s},...c!==void 0&&{opaque:c},request:Ix(i)}),payload:n.payload,...n.source&&{source:n.source}}}catch{throw new tC}}function XS(e){if(e===void 0)return{};if(typeof e==`string`)return{opaque:e};if(!ZS(e))throw Error(`Invalid opaque.`);return{meta:e,opaque:Rx(e)}}function ZS(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:Object.values(e).every(e=>typeof e==`string`)}function QS(e){let{challenge:t,payload:n,source:r}=e;return{challenge:t,payload:n,...r&&{source:r}}}function $S(e){let{meta:t,opaque:n,request:r,...i}=e.challenge,a=n??(t===void 0?void 0:Rx(t)),o={challenge:{...i,...a!==void 0&&{opaque:a},request:Rx(r)},payload:e.payload,...e.source&&{source:e.source}},s=JSON.stringify(o),c=k.fromString(s,{pad:!1,url:!0});return`${Ax.payment} ${c}`}var eC,tC,nC=F((()=>{_S(),Fx(),zx(),eC=class extends Error{name=`MissingPaymentSchemeError`;constructor(){super(`Missing Payment scheme.`)}},tC=class extends Error{name=`InvalidCredentialEncodingError`;constructor(){super(`Invalid base64url or JSON.`)}}})),rC,iC,aC=F((()=>{rC=`org.paymentauth/credential`,iC=`org.paymentauth/payment-required`}));function oC(e){let{extensions:t,resource:n,...r}=e;return bC.parse(r)}var sC,cC,lC,uC,dC,fC,pC,mC,hC,gC,_C,vC,yC,bC,xC,SC,CC,wC,TC,EC,DC,OC,kC=F((()=>{Zx(),sC=`charge`,cC=[`exact`],lC=`eip155:`,uC=`x402:`,dC=`PAYMENT-REQUIRED`,fC=`PAYMENT-SIGNATURE`,pC=`PAYMENT-RESPONSE`,mC=J.string().check(J.minLength(1)),hC=J.number().check(J.refine(e=>e>0,`Must be positive`)),gC=J.string().check(J.regex(/^\d+$/,`Invalid atomic amount`)),_C=Kx(),vC=J.string().check(J.regex(RegExp(`^${lC}\\d+$`),`Invalid EVM CAIP-2 network`)),yC=J.object({description:J.optional(J.string()),iconUrl:J.optional(J.string()),mimeType:J.optional(J.string()),serviceName:J.optional(J.string()),tags:J.optional(J.array(J.string())),url:mC}),J.discriminatedUnion(`type`,[J.object({name:mC,type:J.literal(`eip3009`),version:mC}),J.object({name:J.optional(J.string()),type:J.literal(`permit2`),version:J.optional(J.string())})]),bC=J.object({amount:gC,asset:mC,extra:J.optional(J.record(J.string(),J.unknown())),maxTimeoutSeconds:hC,network:vC,payTo:mC,scheme:J.enum(cC)}),xC=J.object({info:J.record(J.string(),J.unknown()),schema:J.record(J.string(),J.unknown())}),SC=J.record(J.string(),xC),CC=J.object({accepts:J.array(bC).check(J.minLength(1)),error:J.optional(J.string()),extensions:J.optional(SC),resource:yC,x402Version:J.literal(2)}),wC=J.object({authorization:J.object({from:_C,nonce:qx(),to:_C,validAfter:gC,validBefore:gC,value:gC}),signature:Yx()}),TC=J.object({permit2Authorization:J.object({deadline:gC,from:_C,nonce:gC,permitted:J.object({amount:gC,token:_C}),spender:_C,witness:J.object({to:_C,validAfter:gC})}),signature:Yx()}),EC=J.union([wC,TC]),DC=J.object({accepted:bC,extensions:J.optional(SC),payload:EC,resource:J.optional(yC),x402Version:J.literal(2)}),J.object({extensions:J.optional(SC),extra:J.optional(J.record(J.string(),J.unknown())),invalidMessage:J.optional(J.string()),invalidReason:J.optional(J.string()),isValid:J.boolean(),payer:J.optional(J.string())}),OC=J.object({amount:J.optional(gC),errorMessage:J.optional(J.string()),errorReason:J.optional(J.string()),extensions:J.optional(SC),extra:J.optional(J.record(J.string(),J.unknown())),network:mC,payer:J.optional(J.string()),success:J.boolean(),transaction:J.string()})}));function AC(e,t,n){let r=new Headers(e.headers);for(let e of jC)e===q.authorization&&!r.get(e)?.startsWith(`Payment `)||r.delete(e);return r.set(t,n),{...e,headers:r}}var jC,MC=F((()=>{Fx(),kC(),jC=[q.authorization,dC,pC,fC]}));function NC(e){if(typeof e==`string`)try{let t=JSON.parse(e),n=t?.id;return t?.jsonrpc!==`2.0`||typeof t?.method!=`string`?void 0:typeof n==`string`||typeof n==`number`?n:void 0}catch{return}}function PC(e){let t=NC(e?.body);if(t===void 0)return;let n=new Headers(e?.headers);if(n.has(`mcp-method`))return t;let r=n.get(`accept`)?.toLowerCase()??``;return r.includes(`application/json`)&&r.includes(`text/event-stream`)?t:void 0}function FC(e){if(!e||typeof e!=`object`)return;let t=e,n=t.id;if(t.jsonrpc!==`2.0`||n!==void 0&&typeof n!=`string`&&typeof n!=`number`)return;let r=`error`in t;if(r!==`result`in t)return r?Number.isInteger(t.error?.code)&&typeof t.error?.message==`string`?e:void 0:n!==void 0&&typeof t.result==`object`?e:void 0}function IC(e){if(!e||typeof e!=`object`)return;let t=e?.challenges;if(!Array.isArray(t)||t.length===0)return;let n=[];for(let e of t){let t=gS.safeParse(e);if(!t.success)return;n.push(t.data)}let{httpStatus:r,problem:i}=e;return{challenges:n,...typeof r==`number`?{httpStatus:r}:{},...i===void 0?{}:{problem:i}}}function LC(e){if(e)return`error`in e?e.error?.code!==-32042&&e.error?.code!==-32043?void 0:IC(e.error.data):IC(e.result?._meta?.[iC])}function RC(e,t){return!e||e.id!==t?[]:LC(e)?.challenges??[]}async function zC(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=0,i=!1,a,o=P({onEvent(e){if(!(i||!e.data)&&(i=!0,!(e.event&&e.event!==`message`)))try{a=FC(JSON.parse(e.data))}catch{}}});try{for(;;){if(i)return a;let{done:e,value:s}=await t.read();if(e)return o.feed(n.decode()),o.reset({consume:!0}),a;if(r+=s.byteLength,r>UC)return;o.feed(n.decode(s,{stream:!0}))}}finally{t.cancel().catch(()=>{})}}async function BC(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=0,i=``;try{for(;;){let{done:e,value:a}=await t.read();if(e)return FC(JSON.parse(i+n.decode()));if(r+=a.byteLength,r>UC)return;i+=n.decode(a,{stream:!0})}}catch{return}finally{t.cancel().catch(()=>{})}}function VC(e){let t=WC.get(e);if(t)return t;let n=(async()=>{let t=e.headers.get(`content-type`)?.toLowerCase()??``;if(!(Number(e.headers.get(`content-length`))>UC)){if(t.includes(`application/json`))return BC(e);if(t.includes(`text/event-stream`))return zC(e)}})();return WC.set(e,n),n}function HC(){return{getChallenges(e,t){let n=PC(t);return e.status===402||n===void 0?[]:VC(e).then(e=>RC(e,n))},setCredential(e,t){let n=JSON.parse(e.body),r=YS(t);return{...e,body:JSON.stringify({...n,params:{...n.params,_meta:{...n.params?._meta,[rC]:r}}})}}}}var UC,WC,GC=F((()=>{_S(),nC(),aC(),MC(),UC=1048576,WC=new WeakMap}));function KC(){return{getChallenges(e){return e.status!==402||!e.headers.has(q.wwwAuthenticate)?[]:cS(e)},setCredential(e,t,n){return AC(e,n?.challenge?fS(n.challenge):q.authorization,t)}}}var qC=F((()=>{_S(),Fx(),MC()}));function JC(e){return{encode(t){return k.fromString(JSON.stringify(e.parse(t)))},decode(t){try{return e.parse(JSON.parse(k.toString(t)))}catch{throw new YC}}}}var YC,XC=F((()=>{YC=class extends Error{name=`InvalidJsonHeaderError`;constructor(){super(`Invalid base64 JSON header.`)}}}));function ZC(e){try{let t=JSON.parse(k.toString(e));return rw(t)}catch{throw new YC}}var QC,$C,ew,tw,nw,rw,iw=F((()=>{XC(),kC(),QC=JC(CC),$C=JC(DC),ew=JC(OC),tw=QC.encode,QC.decode,nw=$C.encode,$C.decode,ew.encode,ew.decode,rw=e=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new YC;let t=e;if(t.x402Version!==2||!Array.isArray(t.accepts))throw new YC;let n=yC.parse(t.resource),r=t.extensions===void 0?void 0:SC.safeParse(t.extensions).data;return{accepts:t.accepts,...r?{extensions:r}:{},resource:n,x402Version:2}}}));function aw(){return{getChallenges(e){if(e.status!==402)return[];let t=e.headers.get(dC);if(!t)return[];let n=ZC(t);return n.accepts.flatMap((e,t)=>{let r=bC.safeParse(e);if(!r.success)return[];let i=r.data;return TS(Qx({id:`${uC}${t}`,intent:sC,method:`evm`,realm:new URL(n.resource.url).host,request:{...i,...n.extensions?{extensions:n.extensions}:{},resource:n.resource}}))})},setCredential(e,t){return AC(e,fC,t)}}}var ow=F((()=>{_S(),iw(),OS(),kC(),MC()}));function sw(e){return e}function cw(){let e=[KC(),aw(),HC()],t=new WeakMap,n=(e,n)=>{for(let r of n)t.set(r,e);return n},r=(t,r)=>{let i=(a,o)=>{for(let s=a;s<e.length;s++){let a=e[s],c=a.getChallenges(t,r);if(c instanceof Promise)return c.then(e=>i(s+1,[...o,...n(a,e)]));o.push(...n(a,c))}return o};return i(0,[])};return sw({name:`http`,isPaymentRequired(e,t){if(e.status===402)return!0;let n=r(e,t);return n instanceof Promise?n.then(e=>e.length>0):n.length>0},getChallenges(e,t){return r(e,t)},setCredential(n,r,i){let a=i?.challenge?t.get(i.challenge):void 0,o=e[0];if(!a&&!o)throw Error(`No protocol to attach the credential.`);return(a??o).setCredential(n,r,i)}})}var lw=F((()=>{GC(),qC(),MC(),ow()}));function uw(e,t){return pw.set(e,t),e}function dw(e){return pw.has(e)}function fw(e,t){return Promise.resolve(pw.get(e)?.(t))}var pw,mw=F((()=>{pw=new WeakMap}));function hw(e,t){return Sw.set(e,t),e}function gw(e){Sw.delete(e)}function _w(e,t,n){Sw.has(e)&&Cw.set(t,n)}function vw(e){return Cw.get(e)}function yw(e,t){return Promise.resolve(Sw.get(e)?.(t)??t.response)}function bw(e,t){return ww.set(e,t),e}function xw(e,t){try{return ww.get(e)?.(t)}catch{return}}var Sw,Cw,ww,Tw=F((()=>{Sw=new WeakMap,Cw=new WeakMap,ww=new WeakMap}));async function Ew(e){if(!e.body)return e;let t=e.clone().body.getReader(),n=[],r=0,i=!1,a=setTimeout(()=>{i=!0,t.cancel().catch(()=>{})},pT);try{for(;;){let{done:e,value:a}=await t.read();if(e)break;if(n.push(a),r+=a.byteLength,r>fT){i=!0;break}}}finally{clearTimeout(a),t.cancel().catch(()=>{})}if(!i)return e;e.body.cancel().catch(()=>{});let o=new Headers(e.headers);o.delete(`content-length`),o.set(mT,`true`);let s=new Response(new Blob(n).slice(0,fT),{headers:o,status:e.status,statusText:e.statusText});for(let t of[`redirected`,`type`,`url`])Object.defineProperty(s,t,{value:e[t]});return s}async function Dw(e,t){let n=e?.attempt.settle;if(!n)return t.status!==`pending`;e.attempt.settle=void 0;let r=await n(t);return r||(e.attempt.settle=n),r}function Ow(e){let{acceptPayment:t,acceptPaymentPolicy:n=`always`,fetch:r=globalThis.fetch,maxPaymentRetries:i=dT,methods:a,onChallenge:o,orderChallenges:s,transport:c=cw()}=e,l=e.eventDispatcher??jw(),u=t??AS(a),d=Qw(r),f=async(e,t,r)=>{let p=Zw(e,t?.headers),m=p.has(q.acceptPayment),h=rT(p,u),g=Yw(e,t,p),_=Jw(e,t,p,h.header,m,n),v=await d($w(_.input),_.init),y=Xw(_.init,await g);if(!await c.isPaymentRequired(v,y))return v;let b=t?.context,{context:x,orderChallenges:S,...C}=y??{},w,T,ee,E,D;try{for(let n=0;n<i;n++){T=await c.getChallenges(v,y);let i=(await iT(PS(T,a,h.entries),S??s))[0];if(!i){if(await Dw(E,{challenges:T,response:v,status:`rejected`}),n>0)return v;throw Error(`No method found for challenges: ${T.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${a.map(e=>`${e.name}.${e.intent}`).join(`, `)}`)}let u=i.challenge;w=u,ee=i.method,w.expires&&CS(w.expires,w.id);let p=lT(v,_.input,_.input),m=E,g=$x(u),x=m?.method===i.method&&m?.key===g,O=!1;if(m){let e=await Dw(m,{challenges:T,response:v,status:x?`pending`:`rejected`});O=x&&!e}E=O?m:void 0;let k=Iw(async n=>{if(n===void 0&&O&&m)return m.promise;O&&m&&(await Dw(m,{status:`rejected`}),E=void 0);let r=n??b;if(!dw(i.method))return nT(u,i.method,r);let a={prepare:()=>fw(i.method,{challenge:u,context:r,fetch:d,input:p,signal:eT(e,t)})},o=a.prepare().then(()=>nT(u,i.method,r,a));return E={attempt:a,key:n===void 0?g:void 0,method:i.method,promise:o},o}),te=await l.emit(`challenge.received`,Lw({challenge:u,challenges:T,createCredential:k,init:t,input:e,method:i.method,response:v}))??(o?await o(w,{createCredential:k}):void 0)??await k(),ne=E;ne&&await ne.promise.catch(()=>void 0)!==te&&(await Dw(ne,{status:`rejected`}),E=void 0),tT(te),await l.emit(`credential.created`,Rw({challenge:u,credential:te,init:t,input:e,method:i.method,response:v}));let re=e=>new xS({cause:e,challenge:u,credential:te,transactionHash:xw(i.method,te)});try{v=await d(p,{...c.setCredential({...C,headers:_.headers},te,{challenge:u}),redirect:`manual`})}catch(e){throw D=re(e),e}let A=await c.isPaymentRequired(v,y);if(A||(await Dw(ne,{response:v,status:v.status>=300&&v.status<400?`pending`:v.ok?`accepted`:`rejected`}),E=void 0),v.ok&&Mw(l,`payment.response`)&&await l.emit(`payment.response`,zw({challenge:u,credential:te,init:t,input:e,method:i.method,response:v})),!A){if(v.status>=500&&Mw(l,`payment.failed`)){try{v=await Ew(v)}catch(e){throw D=re(e),v=new Response(null,{headers:v.headers,status:v.status,statusText:v.statusText}),e}await l.emit(`payment.failed`,Bw({challenge:u,challenges:T,error:re(),init:t,input:e,method:i.method,response:v}))}return v.ok?yw(i.method,{challenge:u,credential:te,fetch:d,headers:_.headers,input:p,...r?{refetch:()=>f($w(_.input),t,!1)}:{},response:v,signal:eT(e,t)}):v}}T=void 0;try{T=await c.getChallenges(v,y)}catch{}return await Dw(E,{challenges:T,response:v,status:`rejected`}),v}catch(n){throw await Dw(E,{challenges:T,response:v,status:`rejected`}),await l.emit(`payment.failed`,Bw({challenge:w,challenges:T,error:D??n,init:t,input:e,method:ee,response:v})),n}},p=(e,t)=>f(e,t,!0);return p[uT]=d,p}function kw(e){let t=Object.getOwnPropertyDescriptor(globalThis,`fetch`);if(!t||!t.writable&&!t.set)throw Error(`globalThis.fetch is not writable`);hT||=globalThis.fetch,globalThis.fetch=Ow({...e,acceptPaymentPolicy:e.acceptPaymentPolicy??(sT()?`same-origin`:`always`),fetch:globalThis.fetch})}function Aw(e){if(!e)return{};if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}return Array.isArray(e)?Object.fromEntries(e):e}function jw(){let e={"*":new Set,"challenge.received":new Set,"credential.created":new Set,"payment.failed":new Set,"payment.response":new Set},t={async emit(t,n){switch(t){case`challenge.received`:{let r;for(let t of e[`challenge.received`]){let e=await Nw(t,n);if(typeof e==`string`&&e.length>0){r=e;break}}return await Fw(e[`*`],t,n),r}case`credential.created`:await Pw(e[`credential.created`],n),await Fw(e[`*`],t,n);return;case`payment.failed`:await Pw(e[`payment.failed`],n),await Fw(e[`*`],t,n);return;case`payment.response`:await Pw(e[`payment.response`],n),await Fw(e[`*`],t,n);return}},on:(t,n)=>{switch(t){case`*`:case`challenge.received`:case`credential.created`:case`payment.failed`:case`payment.response`:return e[t].add(n),()=>e[t].delete(n);default:throw Error(`Unknown client event "${String(t)}".`)}}};return gT.set(t,t=>e[t].size>0||e[`*`].size>0),t}function Mw(e,t){return gT.get(e)?.(t)??!0}async function Nw(e,t){try{return await e(t)}catch{return}}async function Pw(e,t){for(let n of e)try{await n(t)}catch{}}async function Fw(e,t,n){await Pw(e,Object.freeze({name:t,payload:n}))}function Iw(e){let t;return n=>(t??=e(n),t)}function Lw(e){return Object.freeze({challenge:Gw(e.challenge),challenges:e.challenges.map(e=>Gw(e)),createCredential:e.createCredential,init:Vw(e.init),input:Hw(e.input),method:Uw(e.method),response:Ww(e.response)})}function Rw(e){return Object.freeze({challenge:Gw(e.challenge),credential:e.credential,init:Vw(e.init),input:Hw(e.input),method:Uw(e.method),...e.response===void 0?{}:{response:Ww(e.response)}})}function zw(e){return Object.freeze({challenge:Gw(e.challenge),credential:e.credential,init:Vw(e.init),input:Hw(e.input),method:Uw(e.method),response:Ww(e.response)})}function Bw(e){return Object.freeze({...e.challenge?{challenge:Gw(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>Gw(e))}:{},error:e.error,init:Vw(e.init),input:Hw(e.input),...e.method?{method:Uw(e.method)}:{},...e.response===void 0?{}:{response:Ww(e.response)}})}function Vw(e){if(e)return qw({...e,...e.headers?{headers:new Headers(e.headers)}:{}})}function Hw(e){if(e instanceof Request)try{return e.clone()}catch{return e}return e instanceof URL?new URL(e):e}function Uw(e){return qw(Object.assign({},e))}function Ww(e){return e instanceof Response?e.clone():Gw(e)}function Gw(e){try{return Kw(structuredClone(e))}catch{return qw(e)}}function Kw(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))Kw(t);return e}function qw(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function Jw(e,t,n,r,i,a){let o=!!r&&!i&&aT(e,a);if(!o)return{headers:n,init:t,input:e};let s=new Headers(e instanceof Request?e.headers:void 0);return n.forEach((e,t)=>{s.set(t,e)}),s.set(q.acceptPayment,r),t?(t.headers=s,{headers:s,init:t,input:e}):{headers:s,init:o?{headers:s}:void 0,input:e}}function Yw(e,t,n){if(!(!(e instanceof Request)||t?.body!==void 0||!e.body||e.bodyUsed)){if(!n.has(`mcp-method`)){let e=n.get(`accept`)?.toLowerCase()??``;if(!e.includes(`application/json`)||!e.includes(`text/event-stream`))return}try{return e.clone().text().catch(()=>void 0)}catch{return}}}function Xw(e,t){return t===void 0?e:{...e,body:t}}function Zw(e,t){return t?new Headers(t):new Headers(e instanceof Request?e.headers:void 0)}function Qw(e){let t=e;for(;t[uT];)t=t[uT];return t}function $w(e){if(!(e instanceof Request)||!e.body||e.bodyUsed)return e;try{return e.clone()}catch{return e}}function eT(e,t){if(t?.signal!==null)return t?.signal===void 0?e instanceof Request?e.signal:void 0:t.signal}function tT(e){if(!e.trim())throw Error(`Credential header value must be non-empty`);if(e.includes(`\r`)||e.includes(`
224
- `))throw Error(`Credential header value contains illegal newline characters`)}async function nT(e,t,n,r){let i=t.context&&n!==void 0?t.context.parse(n):void 0,a=i===void 0?{challenge:e}:{challenge:e,context:i};return r&&_w(t,a,r),t.createCredential(a)}function rT(e,t){let n=e.get(q.acceptPayment);if(!n)return t;try{return{...t,entries:jS(n),header:n}}catch{return t}}async function iT(e,t){return t?t(e):e}function aT(e,t){if(t===`always`)return!0;if(t===`never`)return!1;let n=cT(e);return t===`same-origin`?!sT()||n.origin===globalThis.location.origin:t.origins.some(e=>oT(n,e))}function oT(e,t){if(t.startsWith(`*.`)){let n=t.slice(1);return e.hostname.endsWith(n)||e.hostname===t.slice(2)}return e.origin===new URL(t).origin}function sT(){return globalThis.location!==void 0}function cT(e){return e instanceof URL?e:e instanceof Request?new URL(e.url):new URL(e,sT()?globalThis.location.href:void 0)}function lT(e,t,n){if(!e.url)return t;let r=new URL(e.url),i=cT(n);if(r.origin!==i.origin)throw Error(`Refusing to send payment credential across redirect from ${i.origin} to ${r.origin}`);return e.url}var uT,dT,fT,pT,mT,hT,gT,_T=F((()=>{_S(),Fx(),SS(),wS(),JS(),lw(),mw(),Tw(),uT=Symbol.for(`mppx.fetch.wrapper`),dT=3,fT=65536,pT=2e3,mT=`Mppx-Body-Truncated`,gT=new WeakMap}));Ox(),_T();function vT(){let e=new Uint8Array(64);return crypto.getRandomValues(e),Object.freeze({created:Math.floor(Date.now()/1e3),nonce:k.fromBytes(e,{pad:!1,url:!0})})}function yT(...e){return{protocol:`composed`,async sign(t,n=vT()){for(let r of e)t=await r.sign(t,n);return t}}}function bT(e,t){return async(n,r)=>e(await t.sign(new Request(n,r)))}Fx(),wS(),JS(),mw(),lw();const xT=new WeakMap;function ST(e){let{attestation:t,maxPaymentRetries:n,onChallenge:r,orderChallenges:i,polyfill:a=!0,acceptPaymentPolicy:o=a&&globalThis.location!==void 0?`same-origin`:`always`,transport:s=cw()}=e,c=Qw(e.fetch??globalThis.fetch),l=t?CT(t):void 0,u=l?bT(c,l):c,d=e.methods.flat(),f=AS(d,e.paymentPreferences),p=jw(),m=r,h={acceptPayment:f,acceptPaymentPolicy:o,...(e.fetch||t)&&{fetch:u},eventDispatcher:p,...n!==void 0&&{maxPaymentRetries:n},...m&&{onChallenge:m},...i&&{orderChallenges:i},methods:d,transport:s},g=Ow(h);a&&kw(h);function _(e){return p.on(`challenge.received`,e)}function v(e){return p.on(`credential.created`,e)}function y(e){return p.on(`payment.failed`,e)}function b(e){return p.on(`payment.response`,e)}async function x(e,t){let n=LT(e),r=await s.getChallenges(e,t?.request),a=Object.freeze(r.map(e=>RT(e))),o=VT(f.entries,t?.acceptPayment),c,l;try{let e=(await HT(PS(r,d,o),t?.orderChallenges??i))[0];if(!e)throw Error(`No method found for challenges: ${r.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${d.map(e=>`${e.name}.${e.intent}`).join(`, `)}`);let u=e.challenge;c=a[e.index],l=e.method,c.expires&&CS(c.expires,c.id);let f=c,m=l,h=MT(async e=>{try{f.expires&&CS(f.expires,f.id);let t=MT(t=>UT(f,m,t??e)),i=await p.emit(`challenge.received`,NT({challenge:f,challenges:r,createCredential:t,method:m,response:n}))??await t();return tT(i),await p.emit(`credential.created`,PT({challenge:f,credential:i,method:m,response:n})),i}catch(e){throw await p.emit(`payment.failed`,FT({challenge:f,challenges:r,error:e,method:m,response:n})),e}}),g=Object.freeze({challenge:f,challenges:a,createCredential:h,method:IT(m),setCredential(e,t){return tT(t),s.setCredential(e,t,{challenge:u})}});return xT.set(g,m),g}catch(e){throw await p.emit(`payment.failed`,FT({challenge:c,challenges:r,error:e,method:l,response:n})),e}}async function S(e,t,n){let{maxRedirects:r=20,requirePayment:i=!1,...a}=n??{},d=await DT({acceptPayment:f.header,acceptPaymentPolicy:o,fetch:c,init:t,input:e,maxRedirects:r,signer:l}),p=OT(d.replayRequest,d.body);if(!await s.isPaymentRequired(d.response,p)){if(i)throw Error(`Response does not require payment.`);return Object.freeze({payment:void 0,request:d.request,response:d.response,redirects:d.redirects})}let m=await x(d.response,{...a,request:p}),h=xT.get(m)??m.method,g=MT(async e=>(dw(h)&&await fw(h,{challenge:m.challenge,context:e,fetch:u,input:d.replayRequest,signal:d.replayRequest.signal}),m.createCredential(e))),_=Object.freeze({...m,createCredential:g,async pay(e){let t=await g(e),n=m.setCredential(OT(d.replayRequest,d.body),t);return u(d.replayRequest.url,{...n,redirect:`manual`})}});return Object.freeze({payment:_,request:d.request,response:d.response,redirects:d.redirects})}return{fetch:g,rawFetch:c,methods:d,transport:s,on:p.on,onChallengeReceived:_,onCredentialCreated:v,onPaymentFailed:y,onPaymentResponse:b,preparePayment:x,prepareRequest:S,async createCredential(e,t,n){return(await x(e,n)).createCredential(t)}}}function CT(e){let t=Object.values(e);if(t.length===0)throw TypeError(`Mppx client attestation must configure at least one signer.`);return yT(...t)}const wT=new Set([301,302,303,307,308]),TT=[`content-encoding`,`content-language`,`content-length`,`content-location`,`content-type`,`transfer-encoding`],ET=[`authorization`,`cookie`,`cookie2`,`host`,`payment-authorization`,`payment-signature`,`proxy-authorization`,`x-payment`];async function DT(e){let{acceptPayment:t,acceptPaymentPolicy:n,fetch:r,init:i,input:a,maxRedirects:o,signer:s}=e;if(!Number.isInteger(o)||o<0)throw TypeError(`maxRedirects must be a non-negative integer.`);let c=new Request(a,{...i,redirect:`manual`}),l=c.headers.has(q.acceptPayment),u=await kT(c,i?.body),d=[];for(;;){c=AT(c,t,l,n);let e=s?await s.sign(c.clone()):c.clone(),i=await r(e);if(i.type===`opaqueredirect`||i.status===0)throw Error(`prepareRequest requires a runtime that exposes manual redirect responses.`);if(!wT.has(i.status))return{body:u,replayRequest:c,request:e,response:i,redirects:Object.freeze(d)};let a=i.headers.get(`location`);if(!a)return{body:u,replayRequest:c,request:e,response:i,redirects:Object.freeze(d)};if(d.length>=o)throw await i.body?.cancel(),Error(`Payment request exceeded ${o} redirects.`);let f=new URL(c.url),p=new URL(a,f);if(f.protocol===`https:`&&p.protocol!==`https:`)throw await i.body?.cancel(),Error(`Payment request refused HTTPS downgrade redirect to ${p.href}`);let m=new Headers(c.headers),h=c.method;if((i.status===301||i.status===302)&&h===`POST`||i.status===303&&h!==`GET`&&h!==`HEAD`){h=`GET`,u=void 0;for(let e of TT)m.delete(e)}if(f.origin!==p.origin)for(let e of[...m.keys()]){let t=m.get(e)??``;(ET.includes(e)||t.startsWith(`Payment `))&&m.delete(e)}d.push(Object.freeze({from:f.href,status:i.status,to:p.href})),await i.body?.cancel(),c=new Request(p,jT(c,m,h,u))}}function OT(e,t){return jT(e,new Headers(e.headers),e.method,t)}async function kT(e,t){if(typeof t==`string`)return t;if(!e.body)return;let n=e.headers.get(`accept`)?.toLowerCase()??``;return e.headers.has(`mcp-method`)||n.includes(`application/json`)&&n.includes(`text/event-stream`)?e.clone().text():e.clone().arrayBuffer()}function AT(e,t,n,r){if(n)return e;let i=new Headers(e.headers);return i.delete(q.acceptPayment),t&&aT(e,r)&&i.set(q.acceptPayment,t),new Request(e,{headers:i})}function jT(e,t,n,r){return{...r?{body:r}:{},cache:e.cache,credentials:e.credentials,headers:t,integrity:e.integrity,keepalive:e.keepalive,method:n,mode:e.mode,redirect:`manual`,referrer:e.referrer,referrerPolicy:e.referrerPolicy,signal:e.signal}}function MT(e){let t;return n=>(t??=e(n),t)}function NT(e){return Object.freeze({challenge:RT(e.challenge),challenges:e.challenges.map(e=>RT(e)),createCredential:e.createCredential,method:IT(e.method),response:LT(e.response)})}function PT(e){return Object.freeze({challenge:RT(e.challenge),credential:e.credential,method:IT(e.method),response:LT(e.response)})}function FT(e){return Object.freeze({...e.challenge?{challenge:RT(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>RT(e))}:{},error:e.error,...e.method?{method:IT(e.method)}:{},response:LT(e.response)})}function IT(e){return BT(Object.assign({},e))}function LT(e){return e instanceof Response?e.body===null?e.clone():new Response(null,{headers:e.headers,status:e.status,statusText:e.statusText}):RT(e)}function RT(e){try{let t=structuredClone(e);if(e&&t&&typeof e==`object`&&typeof t==`object`)for(let n of Object.getOwnPropertySymbols(e)){let r=Object.getOwnPropertyDescriptor(e,n);r&&Object.defineProperty(t,n,r)}return zT(t)}catch{return BT(e)}}function zT(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))zT(t);return e}function BT(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function VT(e,t){return t?typeof t==`string`?jS(t):t:e}async function HT(e,t){return t?t(e):e}async function UT(e,t,n){let r=t.context&&n!==void 0?t.context.parse(n):void 0;return t.createCredential(r===void 0?{challenge:e}:{challenge:e,context:r})}function WT(){return J.string().check(J.regex(GT,`Invalid URI or path`))}var GT,KT,qT,JT,YT,XT,ZT,QT,$T,eE=F((()=>{Zx(),GT=/^([a-zA-Z][a-zA-Z\d+.-]*:\/\/\S+|\/\S*)$/,KT=new Set([`amount`,`currency`,`description`,`intent`,`method`]),qT=J.looseObject({amount:J.optional(J.union([J.null(),J.string().check(J.regex(/^(0|[1-9][0-9]*)$/,`Invalid amount`))])),currency:J.optional(J.string()),description:J.optional(J.string()),intent:J.optional(J.string()),method:J.optional(J.string())}),JT=J.pipe(J.looseObject({amount:J.optional(J.union([J.null(),J.string().check(J.regex(/^(0|[1-9][0-9]*)$/,`Invalid amount`))])),currency:J.optional(J.string()),description:J.optional(J.string()),intent:J.optional(J.string()),method:J.optional(J.string()),offers:J.optional(J.array(qT).check(J.minLength(1)))}).check(J.refine(e=>e.offers===void 0||Object.keys(e).every(e=>e===`offers`||!KT.has(e)),`Cannot mix offers with flat payment info fields`)),J.transform(e=>{if(e.offers)return{offers:e.offers};let t={};for(let[n,r]of Object.entries(e))n!==`offers`&&(KT.has(n)||r!==void 0)&&(t[n]=r);return{offers:[t]}})),YT=J.looseObject({apiReference:J.optional(WT()),homepage:J.optional(WT()),llms:J.optional(WT())}),XT=J.looseObject({categories:J.optional(J.array(J.string())),docs:J.optional(YT)}),ZT=J.looseObject({"x-payment-info":J.optional(JT),requestBody:J.optional(J.unknown()),responses:J.optional(J.record(J.string(),J.unknown())),summary:J.optional(J.string())}),QT=J.looseObject({delete:J.optional(ZT),get:J.optional(ZT),head:J.optional(ZT),options:J.optional(ZT),patch:J.optional(ZT),post:J.optional(ZT),put:J.optional(ZT),trace:J.optional(ZT)}),$T=J.looseObject({openapi:J.string(),info:J.looseObject({title:J.string(),version:J.string()}),"x-service-info":J.optional(XT),paths:J.optional(J.record(J.string(),QT))})}));eE();function tE(e){let t=[],n=$T.safeParse(e);if(!n.success){for(let e of n.error.issues)t.push({message:e.message,path:e.path.map(String).join(`.`)||`(root)`,severity:`error`});return t}let r=n.data.paths;if(!r)return t;for(let[e,n]of Object.entries(r))for(let[r,i]of Object.entries(n)){if(!i||typeof i!=`object`||Array.isArray(i))continue;let n=i,a=`paths.${e}.${r}`,o=n[`x-payment-info`];if(!o)continue;let s=JT.safeParse(o);if(!s.success){for(let e of s.error.issues){let n=e.path.length>0?`.${e.path.map(String).join(`.`)}`:``;t.push({message:e.message,path:`${a}.x-payment-info${n}`,severity:`error`})}continue}let c=n.responses;(!c||!(`402`in c))&&t.push({message:`Operation with x-payment-info MUST have a 402 response`,path:`${a}.responses`,severity:`error`});let l=r.toUpperCase();!n.requestBody&&(l===`POST`||l===`PUT`||l===`PATCH`)&&t.push({message:`Operation with x-payment-info has no requestBody`,path:a,severity:`warning`})}return t}function nE(e){return e}function rE(e,t){let{canHandleChallenge:n,context:r,createCredential:i}=t;return{...e,canHandleChallenge:n,context:r,createCredential:i}}var iE=F((()=>{}));function aE(e){return J.refine(e=>{let{amount:t,decimals:n}=e;return N(t,n)>0n},e)}function oE(e){let{periodCount:t,periodUnit:n}=e;try{let e=uE[n];return e!==void 0&&BigInt(t)*e<=lE}catch{return!1}}var sE,cE,lE,uE,dE,fE,pE,mE,hE,gE,_E,vE,yE,bE=F((()=>{Fx(),iE(),Zx(),sE=[`push`,`pull`],cE=J.object({amount:Vx(),memo:J.optional(qx()),recipient:J.pipe(J.string(),J.transform(e=>e))}),lE=(1n<<64n)-1n,uE={dev_second:1n,day:86400n,week:604800n},dE=J.pipe(Kx(),J.transform(e=>e.toLowerCase())),fE=J.object({accessKeyAddress:dE,keyType:J.enum([`p256`,`secp256k1`,`webAuthn`])}),pE=J.object({accessKey:J.optional(fE),chainId:J.optional(J.number())}),mE=Ux(`subscriptionExpires must be a valid date`).check(J.refine(e=>e.getTime()%1e3==0,`subscriptionExpires must be representable as whole seconds`)),hE=J.enum([`dev_second`,`day`,`week`]),gE=J.pipe(J.union([J.string(),J.bigint(),J.custom(e=>typeof e==`number`&&Number.isSafeInteger(e))]),J.transform(e=>e.toString())).check(J.regex(/^[1-9]\d*$/,`Invalid periodCount`),J.refine(e=>{try{return BigInt(e)<=lE}catch{return!1}},`periodCount exceeds uint64`)),_E=nE({name:`tempo`,intent:`charge`,schema:{credential:{payload:J.discriminatedUnion(`type`,[J.object({hash:qx(),type:J.literal(`hash`)}),J.object({signature:Yx(),type:J.literal(`transaction`)}),J.object({signature:Yx(),type:J.literal(`proof`)})])},request:J.pipe(J.object({machineTokenEnabled:J.optional(J.boolean()),amount:Vx(),chainId:J.optional(J.number()),currency:J.string(),decimals:J.number(),description:J.optional(J.string()),externalId:J.optional(J.string()),feePayer:J.optional(J.pipe(J.union([J.boolean(),J.custom()]),J.transform(e=>typeof e==`object`||e))),memo:J.optional(J.never()),recipient:J.optional(J.string()),splits:J.optional(J.array(cE).check(J.minLength(1),J.maxLength(10))),supportedModes:J.optional(J.array(J.enum(sE)).check(J.minLength(1)))}).check(J.refine(({amount:e,decimals:t,splits:n})=>{if(!n)return!0;let r=N(e,t),i=n.reduce((e,n)=>e+N(n.amount,t),0n);return n.every(e=>N(e.amount,t)>0n)&&i<r},`Invalid splits`)),J.transform(({machineTokenEnabled:e,amount:t,chainId:n,decimals:r,feePayer:i,memo:a,splits:o,supportedModes:s,...c})=>({...c,amount:N(t,r).toString(),...e!==void 0||n!==void 0||i!==void 0||o!==void 0||s!==void 0?{methodDetails:{...e!==void 0&&{machineTokenEnabled:e},...n!==void 0&&{chainId:n},...i!==void 0&&{feePayer:i},...o!==void 0&&{splits:o.map(e=>({...e,amount:N(e.amount,r).toString()}))},...s!==void 0&&{supportedModes:s}}}:{}})))}}),vE=nE({name:`tempo`,intent:`session`,schema:{credential:{payload:J.discriminatedUnion(`action`,[J.object({action:J.literal(`open`),authorizedSigner:J.optional(J.string()),channelId:qx(),cumulativeAmount:Vx(),descriptor:J.optional(J.custom()),signature:Yx(),transaction:Yx(),type:J.literal(`transaction`)}),J.object({action:J.literal(`topUp`),additionalDeposit:Vx(),channelId:qx(),descriptor:J.optional(J.custom()),transaction:Yx(),type:J.literal(`transaction`)}),J.object({action:J.literal(`voucher`),channelId:qx(),cumulativeAmount:Vx(),descriptor:J.optional(J.custom()),signature:Yx()}),J.object({action:J.literal(`close`),channelId:qx(),closeSignature:Yx(),cumulativeAmount:Vx(),descriptor:J.optional(J.custom()),signature:Yx()})])},request:J.pipe(J.object({amount:Vx(),chainId:J.optional(J.number()),channelId:J.optional(qx()),currency:J.string(),decimals:J.number(),escrowContract:J.optional(J.string()),feePayer:J.optional(J.pipe(J.union([J.boolean(),J.custom()]),J.transform(e=>typeof e==`object`||e))),feeToken:J.optional(Kx()),minVoucherDelta:J.optional(Vx()),operator:J.optional(Kx()),recipient:J.optional(J.string()),sessionProtocol:J.optional(J.enum([Px.v2,Px.v1])),sessionSnapshot:J.optional(J.custom()),suggestedDeposit:J.optional(Vx()),unitType:J.string()}).check(J.refine(({amount:e,decimals:t})=>N(e,t)>0n,`Session amount must be greater than 0`)),J.transform(({amount:e,chainId:t,channelId:n,decimals:r,escrowContract:i,feePayer:a,feeToken:o,minVoucherDelta:s,operator:c,sessionProtocol:l,sessionSnapshot:u,suggestedDeposit:d,...f})=>({...f,amount:N(e,r).toString(),...d?{suggestedDeposit:N(d,r).toString()}:{},methodDetails:{escrowContract:i,...n!==void 0&&{channelId:n},...s!==void 0&&{minVoucherDelta:N(s,r).toString()},...t!==void 0&&{chainId:t},...a!==void 0&&{feePayer:a},...o!==void 0&&{feeToken:o},...c!==void 0&&{operator:c},...l!==void 0&&{[Nx.sessionProtocol]:l},...u!==void 0&&{[Nx.sessionSnapshot]:u}}})))}}),yE=nE({name:`tempo`,intent:`subscription`,schema:{credential:{payload:J.object({signature:Yx(),type:J.literal(`keyAuthorization`)})},request:J.pipe(J.object({amount:Vx(),accessKey:J.optional(fE),chainId:J.optional(J.number()),currency:dE,decimals:J.number(),description:J.optional(J.string()),externalId:J.optional(J.string()),methodDetails:J.optional(pE),periodCount:gE,periodUnit:hE,recipient:dE,subscriptionExpires:mE}).check(aE(`Subscription amount must be greater than 0`),J.refine(oE,`Subscription period exceeds uint64`)),J.transform(({accessKey:e,amount:t,chainId:n,decimals:r,methodDetails:i,subscriptionExpires:a,...o})=>{let s={...i,...e!==void 0&&{accessKey:e},...n!==void 0&&{chainId:n}};return{...o,amount:N(t,r).toString(),subscriptionExpires:a.toISOString(),...Object.keys(s).length>0?{methodDetails:s}:{}}}))}})}));function xE(e){return e>=0n&&e<=BE}function SE(e){if(!/^\d{1,29}$/.test(e))return;let t=BigInt(e);return xE(t)?t:void 0}function CE(e){return wE(e),e}function wE(e){if(!xE(e))throw Error(`Value ${e} is outside uint96 bounds.`)}function TE(e){return typeof e==`object`&&!!e}function EE(e){return typeof e==`string`&&VE.has(e)}function DE(e){if(typeof e!=`object`||!e)return!1;let t=e;return!(typeof t.channelId!=`string`||t.action!==void 0&&!EE(t.action))}function OE(e,t=`No session credential context available.`){if(!DE(e))throw Error(t);return e}function kE(e){let t=e.request.amount;if(typeof t!=`string`)throw Error(`Session challenge is missing amount.`);return BigInt(t)}function AE(e){return TE(e)?typeof e.channelId==`string`&&typeof e.requiredCumulative==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.deposit==`string`:!1}function jE(e){return TE(e)?e.method===`tempo`&&e.intent===`session`&&e.status===`success`&&typeof e.timestamp==`string`&&typeof e.reference==`string`&&typeof e.challengeId==`string`&&typeof e.channelId==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.spent==`string`&&(e.units===void 0||typeof e.units==`number`)&&(e.txHash===void 0||typeof e.txHash==`string`):!1}function ME(e){let t=k.toString(e),n=JSON.parse(t);if(!jE(n))throw Error(`Invalid session receipt.`);return n}function NE(e){return e.headers.get(`content-type`)?.toLowerCase().startsWith(`text/event-stream`)??!1}function PE(e){let t=`message`,n=[];for(let r of e.split(`
207
+ `),!0}function jy(e,t){return Ny(e)?`${e} --mcp`:`${t} ${Fy(e)} --mcp`}function My(){let e=(process.argv[1]?.replace(/\\/g,`/`))?.match(/^(.+)\/node_modules\/(.+)$/);return e?{root:e[1],entry:e[2]}:null}function Ny(e){let t=process.argv[1];if(!t)return!1;let n=My();if(n)return!n.entry.startsWith(`.bin/`)&&!Py(n.root,e);let r=t.replace(/\\/g,`/`).split(`/`).pop();return r===e||r===`${e}.cmd`||r===`${e}.ps1`}function Py(e,t){try{let n=JSON.parse(a(d(e,`package.json`),`utf-8`));return[n.dependencies,n.devDependencies,n.optionalDependencies,n.peerDependencies].some(e=>t in(e??{}))}catch{return!1}}function Fy(e){let t=My();if(!t)return e;try{let n=JSON.parse(a(d(t.root,`package.json`),`utf-8`)).dependencies??{},r=n[e];if(!r||Object.keys(n).length!==1)return e;if(/^https?:\/\//.test(r)||r.startsWith(`file:`))return r;if(/^\d/.test(r))return`${e}@${r}`}catch{}return e}function Iy(e){let t=[],n=``,r=null;for(let i=0;i<e.length;i++){let a=e[i];r?a===r?r=null:n+=a:a===`"`||a===`'`?r=a:a===` `?(n&&t.push(n),n=``):n+=a}return n&&t.push(n),t}function Ly(e,t){return new Promise((n,r)=>{h(e,t,(e,t,i)=>{if(e){let n=i?.trim()||t?.trim()||e.message;r(Error(n))}else n({stdout:t,stderr:i})})})}var Ry=I((()=>{rt()}));function zy(){return Yy.filter(e=>e.detect())}function By(e,n={}){let r=n.global!==!1,i=n.cwd||process.cwd(),a=r?K:i,o=c.join(a,`.agents`,`skills`),s=n.agents??zy(),l=[],u=[];for(let n of Hy(e)){let e=c.join(o,n.name);Wy(e),t.mkdirSync(e,{recursive:!0}),n.root?t.copyFileSync(c.join(n.dir,`SKILL.md`),c.join(e,`SKILL.md`)):t.cpSync(n.dir,e,{recursive:!0}),l.push(e);for(let a of s){if(a.universal)continue;let o=r?a.globalSkillsDir:c.join(i,a.projectSkillsDir),s=c.join(o,n.name);if(Gy(s)!==Gy(e))try{Wy(s),t.mkdirSync(c.dirname(s),{recursive:!0});let n=Gy(c.dirname(s)),r=Gy(e),i=c.relative(n,r);t.symlinkSync(i,s),u.push({agent:a.name,path:s,mode:`symlink`})}catch{try{t.cpSync(e,s,{recursive:!0}),u.push({agent:a.name,path:s,mode:`copy`})}catch{}}}}return{paths:l,agents:u}}function Vy(e,t={}){let n=t.global!==!1,r=t.cwd||process.cwd(),i=n?K:r;Wy(c.join(i,`.agents`,`skills`,e));for(let t of zy()){if(t.universal)continue;let i=n?t.globalSkillsDir:c.join(r,t.projectSkillsDir);Wy(c.join(i,e))}}function Hy(e){let n=[];function r(e){let i;try{i=t.readdirSync(e,{withFileTypes:!0})}catch{return}for(let a of i){if(!a.isDirectory())continue;let i=c.join(e,a.name),o=c.join(i,`SKILL.md`);if(t.existsSync(o)){let e=t.readFileSync(o,`utf8`).match(/^name:\s*(.+)$/m);n.push({name:Uy(e?.[1]??a.name),dir:i})}r(i)}}r(e);let i=c.join(e,`SKILL.md`);if(t.existsSync(i)){let r=Uy(t.readFileSync(i,`utf8`).match(/^name:\s*(.+)$/m)?.[1]??`skill`);n.some(e=>e.name===r)||n.push({name:r,dir:e,root:!0})}return n}function Uy(e){return e.trim().replace(/[/\\]/g,`-`).replace(/\.\./g,``).slice(0,255)}function Wy(e){try{t.lstatSync(e).isSymbolicLink()?t.unlinkSync(e):t.rmSync(e,{recursive:!0,force:!0})}catch{}}function Gy(e){try{return t.realpathSync(e)}catch{let n=c.dirname(e);if(n===e)return e;try{return c.join(t.realpathSync(n),c.relative(n,e))}catch{return e}}}var K,Ky,qy,Jy,Yy,Xy=I((()=>{K=b.homedir(),Ky=process.env.XDG_CONFIG_HOME||c.join(K,`.config`),qy=process.env.CLAUDE_CONFIG_DIR?.trim()||c.join(K,`.claude`),Jy=process.env.CODEX_HOME?.trim()||c.join(K,`.codex`),Yy=[{name:`Amp`,globalSkillsDir:c.join(Ky,`agents`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(c.join(Ky,`amp`))},{name:`Cline`,globalSkillsDir:c.join(K,`.agents`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(c.join(K,`.cline`))},{name:`Codex`,globalSkillsDir:c.join(Jy,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(Jy)},{name:`Cursor`,globalSkillsDir:c.join(K,`.cursor`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(c.join(K,`.cursor`))},{name:`Gemini CLI`,globalSkillsDir:c.join(K,`.gemini`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(c.join(K,`.gemini`))},{name:`GitHub Copilot`,globalSkillsDir:c.join(K,`.copilot`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(c.join(K,`.copilot`))},{name:`Kimi CLI`,globalSkillsDir:c.join(Ky,`agents`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(c.join(K,`.kimi`))},{name:`OpenCode`,globalSkillsDir:c.join(Ky,`opencode`,`skills`),projectSkillsDir:`.agents/skills`,universal:!0,detect:()=>t.existsSync(c.join(Ky,`opencode`))},{name:`Claude Code`,globalSkillsDir:c.join(qy,`skills`),projectSkillsDir:`.claude/skills`,universal:!1,detect:()=>t.existsSync(qy)},{name:`Windsurf`,globalSkillsDir:c.join(K,`.codeium`,`windsurf`,`skills`),projectSkillsDir:`.windsurf/skills`,universal:!1,detect:()=>t.existsSync(c.join(K,`.codeium`,`windsurf`))},{name:`Continue`,globalSkillsDir:c.join(K,`.continue`,`skills`),projectSkillsDir:`.continue/skills`,universal:!1,detect:()=>t.existsSync(c.join(K,`.continue`))},{name:`Roo`,globalSkillsDir:c.join(K,`.roo`,`skills`),projectSkillsDir:`.roo/skills`,universal:!1,detect:()=>t.existsSync(c.join(K,`.roo`))},{name:`Kilo`,globalSkillsDir:c.join(K,`.kilocode`,`skills`),projectSkillsDir:`.kilocode/skills`,universal:!1,detect:()=>t.existsSync(c.join(K,`.kilocode`))},{name:`Goose`,globalSkillsDir:c.join(Ky,`goose`,`skills`),projectSkillsDir:`.goose/skills`,universal:!1,detect:()=>t.existsSync(c.join(Ky,`goose`))},{name:`Augment`,globalSkillsDir:c.join(K,`.augment`,`skills`),projectSkillsDir:`.augment/skills`,universal:!1,detect:()=>t.existsSync(c.join(K,`.augment`))},{name:`Trae`,globalSkillsDir:c.join(K,`.trae`,`skills`),projectSkillsDir:`.trae/skills`,universal:!1,detect:()=>t.existsSync(c.join(K,`.trae`))},{name:`Junie`,globalSkillsDir:c.join(K,`.junie`,`skills`),projectSkillsDir:`.junie/skills`,universal:!1,detect:()=>t.existsSync(c.join(K,`.junie`))},{name:`Crush`,globalSkillsDir:c.join(Ky,`crush`,`skills`),projectSkillsDir:`.crush/skills`,universal:!1,detect:()=>t.existsSync(c.join(Ky,`crush`))},{name:`Kiro CLI`,globalSkillsDir:c.join(K,`.kiro`,`skills`),projectSkillsDir:`.kiro/skills`,universal:!1,detect:()=>t.existsSync(c.join(K,`.kiro`))},{name:`Qwen Code`,globalSkillsDir:c.join(K,`.qwen`,`skills`),projectSkillsDir:`.qwen/skills`,universal:!1,detect:()=>t.existsSync(c.join(K,`.qwen`))},{name:`OpenHands`,globalSkillsDir:c.join(K,`.openhands`,`skills`),projectSkillsDir:`.openhands/skills`,universal:!1,detect:()=>t.existsSync(c.join(K,`.openhands`))}]}));async function Zy(e,t,n={}){let{depth:r=1,description:i,global:a=!0}=n,o=n.cwd??(a?eb():process.cwd());await hl();let s=new Map;i&&s.set(e,i);let c=xy(e,ax(t,[],s,n.rootCommand),r,s),u=await w.mkdtemp(l.join(x.tmpdir(),`incur-skills-${e}-`));try{let r=[];for(let t of c){let n=t.dir?l.join(u,t.dir,`SKILL.md`):l.join(u,`SKILL.md`);await w.mkdir(l.dirname(n),{recursive:!0}),await w.writeFile(n,`${t.content}\n`);let i=ux(t.content);r.push({name:i.name??(t.dir||e),description:i.description})}if(n.include)for(let t of n.include){let n=t===`_root`?`SKILL.md`:l.join(t,`SKILL.md`);for await(let i of w.glob(n,{cwd:o}))try{let n=await w.readFile(l.resolve(o,i),`utf8`),a=ux(n),s=t===`_root`?a.name??e:l.basename(l.dirname(i)),c=l.join(u,s,`SKILL.md`);await w.mkdir(l.dirname(c),{recursive:!0}),await w.writeFile(c,n),r.some(e=>e.name===s)||r.push({name:s,description:a.description,external:!0})}catch{}}let{paths:i,agents:s}=By(u,{global:a,cwd:o}),d=new Set(i.map(e=>l.basename(e))),f=rb(e);if(f?.skills)for(let e of f.skills)d.has(e)||Vy(e,{global:a,cwd:o});return nb(e,wy(ax(t,[],new Map,n.rootCommand)),[...d],[...i,...s.map(e=>e.path)]),{skills:r.sort((e,t)=>e.name.localeCompare(t.name)),paths:i,agents:s}}finally{await w.rm(u,{recursive:!0,force:!0})}}async function Qy(e,t,n={}){let{depth:r=1,description:i}=n,a=n.cwd??process.cwd();await hl();let o=new Map;i&&o.set(e,i);let s=xy(e,ax(t,[],o,n.rootCommand),r,o),c=[],u=ib(e,{cwd:a});for(let t of s){let n=ux(t.content),r=n.name??(t.dir||e);c.push({name:r,description:n.description,installed:u.has(r)})}if(n.include)for(let t of n.include){let n=t===`_root`?`SKILL.md`:l.join(t,`SKILL.md`);for await(let r of w.glob(n,{cwd:a}))try{let n=ux(await w.readFile(l.resolve(a,r),`utf8`)),i=t===`_root`?n.name??e:l.basename(l.dirname(r));c.some(e=>e.name===i)||c.push({name:i,description:n.description,installed:u.has(i)})}catch{}}return c.sort((e,t)=>e.name.localeCompare(t.name))}function $y(e,t={}){return ib(e,t).size>0}function eb(){let e=process.argv[1];if(!e)return process.cwd();let t=l.dirname((()=>{try{return n.realpathSync(e)}catch{return process.execPath}})()),r=l.parse(t).root;for(;t!==r;){try{return n.accessSync(l.join(t,`package.json`)),t}catch{}t=l.dirname(t)}return process.cwd()}function tb(e){let t=process.env.XDG_DATA_HOME||l.join(x.homedir(),`.local`,`share`);return l.join(t,`incur`,`${e}.json`)}function nb(e,t,r,i){let a=tb(e),o=l.dirname(a);n.existsSync(o)||n.mkdirSync(o,{recursive:!0}),n.writeFileSync(a,JSON.stringify({hash:t,skills:r,paths:i,at:new Date().toISOString()})+`
208
+ `)}function rb(e){try{return JSON.parse(n.readFileSync(tb(e),`utf-8`))}catch{return}}function ib(e,t={}){let n=rb(e);if(!n?.skills?.length)return new Set;if(n.paths?.length){let e=n.paths.filter(e=>ab(e)).map(e=>l.basename(e));return new Set(e)}let r=t.cwd??process.cwd(),i=[l.join(x.homedir(),`.agents`,`skills`),l.join(r,`.agents`,`skills`)],a=n.skills.filter(e=>i.some(t=>ab(l.join(t,e))));return new Set(a)}function ab(e){return n.existsSync(l.join(e,`SKILL.md`))}function ob(e){return rb(e)?.hash}var sb=I((()=>{Dx(),Xy(),vl(),Oy()}));function cb(e,t){let n=typeof e==`string`?e:e.name,r=typeof e==`string`?t??{}:e,i=r.version??Rt,a=`run`in r?r:void 0,o=`fetch`in r&&r.fetch!==void 0?r.fetch:void 0,s=o===void 0?void 0:Vb(o),c=o===void 0?void 0:Hb(o),l=new Map,u=[],d=[],f=ub(r.mcp?.name??n,i??`0.0.0`,{instructions:r.mcp?.instructions,stateless:r.mcp?.stateless,title:r.mcp?.title,tools:r.mcp?.tools});r.openapi&&s&&d.push((async()=>{let e=await Av(await Ov(r.openapi,{baseUrl:c}),s,{config:r.openapiConfig});for(let[t,n]of e)l.set(t,n)})());let p={name:n,description:r.description,env:r.env,vars:r.vars,command(e,t){if(typeof e==`string`){if(Bb(t))return d.push((async()=>{let n=ay(await iy(t.mcp)),r={_group:!0,description:t.description,commands:n,...t.outputPolicy?{outputPolicy:t.outputPolicy}:void 0};qb(e,r,wx.get(p)),l.set(e,r)})()),p;if(t&&`fetch`in t&&zb(t.fetch)){let n=Vb(t.fetch);return t.openapi?(d.push((async()=>{let r=await Av(await Ov(t.openapi,{baseUrl:Hb(t.fetch)}),n,{basePath:t.basePath,config:t.openapiConfig}),i={_group:!0,description:t.description,commands:r,...t.outputPolicy?{outputPolicy:t.outputPolicy}:void 0,...t.mcp===!1?{mcp:!1}:void 0};qb(e,i,wx.get(p)),l.set(e,i)})()),p):(l.set(e,{_fetch:!0,basePath:t.basePath,description:t.description,fetch:n,...t.outputPolicy?{outputPolicy:t.outputPolicy}:void 0}),p)}if(qb(e,t,wx.get(p)),l.set(e,t),t.aliases)for(let n of t.aliases)l.set(n,{_alias:!0,target:e});return p}let n=bx.get(e),r=e,i=_x.get(r),a=Cx.get(r),o=yx.get(r),s=vx.get(r),c=n&&i.size===0?n:{_group:!0,description:r.description,commands:i,...n?{root:n}:void 0,...a?{outputPolicy:a}:void 0,...o?.length?{middlewares:o}:void 0};if(s?.length?d.push(Promise.all(s).then(()=>{qb(r.name,c,wx.get(p))})):qb(r.name,c,wx.get(p)),l.set(r.name,c),n){let t=Tx.get(e);if(t)for(let n of t)l.set(n,{_alias:!0,target:e.name})}return p},async fetch(e){d.length>0&&await Promise.all(d);let t=wx.get(p);return pb(n,l,e,{description:r.description,envSchema:r.env,globals:t,mcpHandler:f,middlewares:u,name:n,rootCommand:a,vars:r.vars,version:i})},fs(e){let t=xu();return d.push((async()=>{let n=t?await Su(t):await Fb(await Pb(e));for(let e of n){if(!Ib(e.command))throw Error(`Expected the default export from '${e.file}' to be created with \`Cli.command()\`.`);Lb(l,e.segments,e.command,e.file,wx.get(p))}})()),p},async serve(e=process.argv.slice(2),t={}){if(await wt(e))return;d.length>0&&await Promise.all(d);let o=wx.get(p);return lb(n,l,e,{...t,aliases:r.aliases,banner:r.banner,config:r.config,description:r.description,envSchema:r.env,format:r.format,globals:o,mcp:r.mcp,middlewares:u,outputPolicy:r.outputPolicy,rootCommand:a,rootFetch:s,sync:r.sync,update:r.update,vars:r.vars,version:i})},use(e){return u.push(e),p}};if(a&&bx.set(p,a),a&&r.aliases&&Tx.set(p,r.aliases),r.options&&xx.set(p,r.options),r.config!==void 0&&Sx.set(p,!0),r.outputPolicy&&Cx.set(p,r.outputPolicy),r.globals){wx.set(p,{schema:r.globals,alias:r.globalAlias});let e=[`verbose`,`format`,`json`,`llms`,`llmsFull`,`mcp`,`help`,`incurBinaryApply`,`incurUpdateCheck`,`update`,`version`,`schema`,`filterOutput`,`tokenLimit`,`tokenOffset`,`tokenCount`,...r.config?.flag?[r.config.flag,`no${r.config.flag[0].toUpperCase()}${r.config.flag.slice(1)}`]:[]],t=Object.keys(r.globals.shape);for(let n of t)if(e.includes(n))throw Error(`Global option '${n}' conflicts with a built-in flag. Choose a different name.`);let n=new Set([`h`]);if(r.globalAlias){for(let[e,t]of Object.entries(r.globalAlias))if(n.has(t))throw Error(`Global alias '-${t}' for '${e}' conflicts with a built-in short flag. Choose a different alias.`)}}return yx.set(p,u),_x.set(p,l),vx.set(p,d),p}async function lb(e,t,n,r={}){let i=r.stdout??(e=>process.stdout.write(e)),a=r.exit??(e=>process.exit(e)),o=process.stdout.isTTY===!0,s=o,c=r.config!==void 0,l=r.config?.flag,u=px(e,r.aliases);function d(e){i(e.endsWith(`
209
+ `)?e:`${e}\n`)}async function f(){if(!r.banner||w)return;let e=typeof r.banner==`function`?{render:r.banner,mode:`all`}:r.banner,t=e.mode??`all`;if(t===`all`||t===(s?`human`:`agent`))try{let t=await e.render();t&&d(t)}catch{}}let p;try{p=vb(n,{configFlag:l})}catch(e){let t=e instanceof Error?e.message:String(e);d(s?Jb({code:`UNKNOWN`,message:t}):yl({code:`UNKNOWN`,message:t},`toon`)),a(1);return}let{fullOutput:m,format:h,formatExplicit:g,filterOutput:_,tokenLimit:v,tokenOffset:y,tokenCount:b,llms:x,llmsFull:S,mcp:C,help:w,update:T,updateCheck:ee,version:E,schema:D,configPath:O,configDisabled:k,rest:A}=p;s=o&&!g;let te={...typeof r.update==`object`?r.update:void 0,binary:Lt!==void 0,version:r.version},ne={},j=A;function M(e){if(!r.globals)return!0;try{let t=Hl(A,r.globals.schema,r.globals.alias,{validate:e});return e&&(ne=t.parsed),j=t.rest,!0}catch(e){let t=e instanceof Error?e.message:String(e);return d(s?Jb({code:`UNKNOWN`,message:t}):yl({code:`UNKNOWN`,message:t},`toon`)),a(1),!1}}if(!M(!1))return;if(h===`yaml`&&await hl(),ee){if(r.update!==!1)try{await at(e,te)}catch{}return}if(T&&!w){try{let t=await ot(e,te);if(s){let e=[t.deferred?`✓ Update staged for ${t.name}`:`✓ Updated ${t.name}`];t.command&&e.push(` ${t.command}`),t.deferred&&e.push(` Installation will finish after this process exits.`),d(e.join(`
210
+ `))}else d(yl(t,h))}catch(e){let t={code:`UPDATE_FAILED`,message:e instanceof Error?e.message:String(e)};d(s?Jb(t):yl(t,h)),a(1)}return}if(C){await L_(r.mcp?.name??e,r.version??`0.0.0`,t,{middlewares:r.middlewares,env:r.envSchema,vars:r.vars,version:r.version,...r.mcp?.instructions?{instructions:r.mcp.instructions}:void 0,...r.mcp?.title?{title:r.mcp.title}:void 0,...r.mcp?.tools?{tools:r.mcp.tools}:void 0});return}let re=process.env.COMPLETE;if(re){let a=n.indexOf(`--`),o=a===-1?n:n.slice(a+1);if(o.length===0)i([e,...r.aliases??[]].map(e=>cn(re,e)).join(`
211
+ `));else{let e=Number(process.env._COMPLETE_INDEX??o.length-1),n=ln(t,r.rootCommand,o,e,r.globals?{schema:r.globals.schema,alias:r.globals.alias}:void 0),a=o[e]??``,s=o.slice(0,e).filter(e=>!e.startsWith(`-`));if(s.length<=1)for(let e of eu)e.name.startsWith(a)&&!n.some(t=>t.value===e.name)&&n.push({value:e.name,description:e.description,...e.subcommands?{noSpace:!0}:void 0});else if(s.length===2){let e=s[s.length-1],t=Xl(e);if(t?.subcommands)for(let e of t.subcommands)for(let t of[e.name,...e.aliases??[]])t.startsWith(a)&&!n.some(e=>e.value===t)&&n.push({value:t,description:e.description})}let c=un(re,n);c&&i(c)}return}let ie;if(!x&&!S&&!D&&!w&&!T&&!ee&&!E){let n=Tb(j,e,`skills`)!==-1,i=Tb(j,e,`mcp`)!==-1;if(!n&&!i){let n=ob(e);n&&$y(e,{cwd:r.sync?.cwd})&&wy(ax(t,[],new Map,r.rootCommand))!==n&&(ie={description:`Skills are out of date:`,commands:[{command:process.env.npm_config_user_agent||process.env.npm_execpath?`${tt()} ${Fy(e)} skills add`:`${u} skills add`,description:`sync outdated skills`}]})}}if(x||S){let n=t,i=[],a=r.description,o=r.rootCommand;for(let e of j){let t=n.get(e);if(!t)break;let r=Kb(n,t);if(Ub(r))n=r.commands,a=r.description,o=r.root,i.push(e);else{n=new Map([[e,r]]),o=void 0;break}}i.length===0&&(o=r.rootCommand);let s=i.length>0?[]:i;if(S){if(!g||h===`md`){let t=new Map,r=ax(n,s,t,o);d(by(i.length>0?`${e} ${i.join(` `)}`:e,r,t));return}d(yl(nx(n,i,r.globals?.schema,o),h));return}if(!g||h===`md`){let t=ax(n,s,new Map,o);d(vy(i.length>0?`${e} ${i.join(` `)}`:e,t,a));return}d(yl(ex(n,i,r.globals?.schema,o),h));return}let ae=Tb(j,e,`completions`);if(ae!==-1){let t=j[ae+1];if(w||!t){let t=Xl(`completions`);d(ru(`${e} completions`,{args:t.args,description:t.description,hideGlobalOptions:!0,hint:t.hint?.(e)}));return}if(!$l.includes(t)){d(Jb({code:`INVALID_SHELL`,message:`Unknown shell '${t}'. Supported: ${$l.join(`, `)}`})),a(1);return}d([e,...r.aliases??[]].map(e=>cn(t,e)).join(`
212
+ `));return}let oe=Tb(j,e,`skills`);if(oe!==-1){let o=Xl(`skills`),c=j[oe+1],l=c?Zl(o,c):void 0;if(c&&!l){let t=on(c,o.subcommands?.flatMap(e=>[e.name,...e.aliases??[]])??[]),r=`'${c}' is not a command for '${e} skills'.${t?` Did you mean '${t}'?`:``}`,i=[];if(t){let r=n.map(e=>e===c?t:e);i.push({command:`${e} ${r.join(` `)}`})}i.push({command:`${e} skills --help`,description:`see all available commands`});let l={description:i.length===1?`Suggested command:`:`Suggested commands:`,commands:i};s?(d(Jb({code:`COMMAND_NOT_FOUND`,message:r})),d(Yb(l))):d(yl({code:`COMMAND_NOT_FOUND`,message:r,cta:l},`toon`)),a(1);return}if(!c){d(Eb(e,o));return}if(l?.name===`list`){if(w){d(Db(e,o,`list`));return}try{let n=await Qy(e,t,{cwd:r.sync?.cwd,depth:r.sync?.depth??1,description:r.description,include:r.sync?.include,rootCommand:r.rootCommand});if(n.length===0){d(`No skills found.`);return}let i=[],a=Math.max(...n.map(e=>e.name.length));for(let e of n){let t=e.installed?`✓`:`✗`,n=e.description?`${` `.repeat(a-e.name.length)} ${e.description}`:``;i.push(` ${t} ${e.name}${n}`)}let o=n.filter(e=>e.installed).length;i.push(``),i.push(`${n.length} skill${n.length===1?``:`s`} (${o} installed)`),d(i.join(`
213
+ `))}catch(e){d(yl({code:`LIST_SKILLS_FAILED`,message:e instanceof Error?e.message:String(e)},g?h:`toon`)),a(1)}return}if(w){d(Db(e,o,`add`));return}let u=j.slice(oe+2),f=u.indexOf(`--depth`),p=u.find(e=>e.startsWith(`--depth=`)),_=f===-1?p?Number(p.split(`=`)[1]):r.sync?.depth??1:Number(u[f+1]),v=!u.includes(`--no-global`)&&void 0;try{i(`Syncing...`);let n=await Zy(e,t,{cwd:r.sync?.cwd,depth:_,description:r.description,global:v,include:r.sync?.include,rootCommand:r.rootCommand});i(`\r\x1B[K`);let a=[],o=e=>e.name,s=Math.max(...n.skills.map(e=>o(e).length));for(let e of n.skills){let t=o(e),n=e.description?`${` `.repeat(s-t.length)} ${e.description}`:``;a.push(` ✓ ${t}${n}`)}a.push(``),a.push(`${n.skills.length} skill${n.skills.length===1?``:`s`} synced`);let c=r.sync?.body;c&&(a.push(``),a.push(c));let l=r.sync?.suggestions;if(l&&l.length>0){a.push(``),a.push(`Your agent can now use ${e}. Try asking:`);for(let e of l)a.push(` "${e}"`)}if(a.push(``),a.push(`Run \`${e} --help\` to see the full command reference.`),d(a.join(`
214
+ `)),m||g){let e={skills:n.paths};c&&(e.body=c),m&&n.agents.length>0&&(e.agents=n.agents),d(yl(e,g?h:`toon`))}}catch(e){d(yl({code:`SYNC_SKILLS_FAILED`,message:e instanceof Error?e.message:String(e)},g?h:`toon`)),a(1)}return}let se=Tb(j,e,`mcp`);if(se!==-1){let o=Xl(`mcp`),c=j[se+1],l=c?Zl(o,c):void 0;if(c&&!l){let t=on(c,o.subcommands?.flatMap(e=>[e.name,...e.aliases??[]])??[]),r=`'${c}' is not a command for '${e} mcp'.${t?` Did you mean '${t}'?`:``}`,i=[];if(t){let r=n.map(e=>e===c?t:e);i.push({command:`${e} ${r.join(` `)}`})}i.push({command:`${e} mcp --help`,description:`see all available commands`});let l={description:i.length===1?`Suggested command:`:`Suggested commands:`,commands:i};s?(d(Jb({code:`COMMAND_NOT_FOUND`,message:r})),d(Yb(l))):d(yl({code:`COMMAND_NOT_FOUND`,message:r,cta:l},`toon`)),a(1);return}if(!c){d(Eb(e,o));return}if(w){d(Db(e,o,l.name));return}if(l.name===`doctor`){let n=await Ob(e,t,r);d(yl(n,g?h:`toon`)),n.ok||a(1);return}let u=j.slice(se+2),f=!u.includes(`--no-global`),p=r.mcp?.command,_=[...r.mcp?.agents??[]];for(let e=0;e<u.length;e++)(u[e]===`--command`||u[e]===`-c`)&&u[e+1]?p=u[++e]:u[e]===`--agent`&&u[e+1]&&_.push(u[++e]);try{let t=r.mcp?.name??e;i(`Registering MCP server...`);let n=await ky(t,{...t===e?void 0:{cli:e},command:p,global:f,agents:_});i(`\r\x1B[K`);let a=[];a.push(`✓ Registered ${t} as MCP server`),n.agents.length>0&&a.push(` Agents: ${n.agents.join(`, `)}`),a.push(``),a.push(`Agents can now use ${t} tools.`);let o=r.sync?.suggestions;if(o&&o.length>0){a.push(``),a.push(`Try asking:`);for(let e of o)a.push(` "${e}"`)}d(a.join(`
215
+ `)),(m||g)&&d(yl({name:t,command:n.command,agents:n.agents},g?h:`toon`))}catch(e){d(yl({code:`MCP_ADD_FAILED`,message:e instanceof Error?e.message:String(e)},g?h:`toon`)),a(1)}return}if(E&&!w&&r.version){d(r.version);return}if(j.length===0){if(r.rootCommand&&s&&r.rootCommand.args&&Zb(r.rootCommand.args)){let n=r.rootCommand;await f(),d(ru(e,{alias:n.alias,aliases:r.aliases,configFlag:l,description:n.description??r.description,globals:r.globals,version:r.version,args:n.args,env:n.env,envSource:r.env,hint:n.hint,options:n.options,examples:lx(n.examples),usage:n.usage,commands:t.size>0?wb(t):void 0,root:!0}));return}if(!(r.rootCommand||r.rootFetch)){await f(),d(nu(e,{aliases:r.aliases,configFlag:l,description:r.description,globals:r.globals,version:r.version,commands:wb(t),root:!0}));return}}let N=j.length===0&&r.rootCommand?{command:r.rootCommand,path:e,rest:[]}:j.length===0&&r.rootFetch?{fetchGateway:{_fetch:!0,fetch:r.rootFetch,description:r.description},middlewares:[],path:e,rest:[]}:_b(t,j);if(w&&`fetchGateway`in N){let n=N.path===e?e:`${e} ${N.path}`;N.path===e&&t.size>0?d(nu(e,{aliases:r.aliases,configFlag:l,description:r.description,version:r.version,commands:wb(t),root:!0})):d(Nb(n,N.fetchGateway.description));return}if(w){if(`help`in N||`error`in N){let n=`help`in N?`${e} ${N.path}`:e,i=`help`in N?N.description:r.description,a=`help`in N?N.commands:t,o=n===e;if(o&&r.rootCommand&&a.size>0){let t=r.rootCommand;d(ru(e,{alias:t.alias,aliases:r.aliases,configFlag:l,description:t.description??r.description,globals:r.globals,version:r.version,args:t.args,env:t.env,envSource:r.env,hint:t.hint,options:t.options,examples:lx(t.examples),usage:t.usage,commands:wb(a),root:!0}))}else d(nu(n,{aliases:o?r.aliases:void 0,configFlag:l,description:i,globals:r.globals,version:o?r.version:void 0,commands:wb(a),root:o}))}else if(`command`in N){let n=N.command,i=N.path===e,a=i?e:`${e} ${N.path}`,o=`commands`in N&&N.commands&&N.commands.size>0?wb(N.commands):i&&r.rootCommand&&t.size>0?wb(t):void 0;d(ru(a,{alias:n.alias,aliases:i?r.aliases:n.aliases,configFlag:l,description:n.description,globals:r.globals,version:i?r.version:void 0,args:n.args,env:n.env,envSource:r.env,hint:n.hint,options:n.options,examples:lx(n.examples),usage:n.usage,commands:o,root:i}))}return}if(D){if(`help`in N){d(nu(`${e} ${N.path}`,{configFlag:l,description:N.description,globals:r.globals,commands:wb(N.commands)}));return}if(`error`in N){let t=N.path?`${e} ${N.path}`:e,n=on(N.error,N.commands.keys()),r=n?` Did you mean '${n}'?`:``;d(`Error: '${N.error}' is not a command for '${t}'.${r}`),a(1);return}if(`fetchGateway`in N){d(`--schema is not supported for fetch commands.`),a(1);return}let t=N.command,n=g?h:`toon`,i={};t.args&&(i.args=Ou(t.args)),t.env&&(i.env=Ou(t.env)),t.options&&(i.options=Ou(t.options)),t.output&&(i.output=Ou(t.output)),r.globals?.schema&&(i.globals=Ou(r.globals.schema)),d(yl(i,n));return}if(`help`in N){d(nu(`${e} ${N.path}`,{configFlag:l,description:N.description,globals:r.globals,commands:wb(N.commands)}));return}let ce;if(s&&r.update!==!1){let t=it(e,te);t&&(ce={description:`Update available for ${t.name}:`,commands:[{command:`${u} --update`,description:`upgrade from ${t.current} to ${t.latest}`}]})}let le=Xb(ie,ce),ue=performance.now(),de=`command`in N&&N.command.format,fe=g?h:de||r.format||`toon`;fe===`yaml`&&await hl();let pe=`error`in N&&!N.path&&(()=>{let e=[...N.commands.keys()];for(let t of eu)e.push(t.name);return on(N.error,e)!==void 0})(),P=`error`in N&&r.rootFetch&&!N.path&&!pe?{fetchGateway:{_fetch:!0,fetch:r.rootFetch,description:r.description},middlewares:[],path:e,rest:j}:`error`in N&&r.rootCommand&&!N.path&&!pe?{command:r.rootCommand,path:e,rest:j}:N,me=`outputPolicy`in N&&N.outputPolicy||r.outputPolicy,he=!(s&&!g&&me===`agent-only`),ge=_?Fn(_):void 0;function _e(e){if(v==null&&y==null)return{text:e,truncated:!1};let t=Kt(e),n=y??0,r=v==null?t:n+v;if(n===0&&r>=t)return{text:e,truncated:!1};let i=qt(e,n,r),a=Math.min(r,t),o=a<t?a:void 0;return{text:`${i}\n[truncated: showing tokens ${n}–${a} of ${t}]`,truncated:!0,nextOffset:o}}function ve(e){if(ge&&e.ok&&e.data!=null&&(e={...e,data:In(e.data,ge)}),le){let t=e.meta.cta;e={...e,meta:{...e.meta,cta:t?{description:t.description,commands:[...t.commands,...le.commands]}:le}}}if(b){let t=e.ok?e.data:e.error,n=t==null?``:yl(t,fe);return d(String(Kt(n)))}let t=e.meta.cta;if(s&&!m){e.ok&&e.data!=null&&he?d(_e(yl(e.data,fe)).text):e.ok||d(Jb(e.error)),t&&d(Yb(t));return}if(m){if(v!=null||y!=null){let t=_e(e.ok&&e.data!=null?yl(e.data,fe):e.ok?``:yl(e.error,fe));if(t.truncated){let n=e.ok?{ok:!0,data:t.text}:{ok:!1,error:t.text},r={...e.meta};return t.nextOffset!=null&&(r.nextOffset=t.nextOffset),n.meta=r,d(yl(n,fe))}}return d(yl(e,fe))}let n=e.ok?e.data:e.error,r=yl(n,fe);if(!t){r&&d(_e(r).text);return}d(_e(yl(typeof n==`object`&&n?{...n,cta:t}:{data:n,cta:t},fe)).text)}if(`error`in P){let t=P.path?`${e} ${P.path} --help`:`${e} --help`,r=P.path?`${e} ${P.path}`:e,i=`commands`in P?[...P.commands.keys()]:[];if(!P.path)for(let e of eu)i.push(e.name);let o=on(P.error,i),c=o?` Did you mean '${o}'?`:``,l=`'${P.error}' is not a command for '${r}'.${c}`,u=[];if(o){let t=n.map(e=>e===P.error?o:e);u.push({command:`${e} ${t.join(` `)}`})}u.push({command:t,description:`see all available commands`});let f={description:u.length===1?`Suggested command:`:`Suggested commands:`,commands:u};if(s&&!m){d(Jb({code:`COMMAND_NOT_FOUND`,message:l})),d(Yb(le?{...f,commands:[...f.commands,...le.commands]}:f)),a(1);return}ve({ok:!1,error:{code:`COMMAND_NOT_FOUND`,message:l},meta:{command:P.error,cta:f,duration:`${Math.round(performance.now()-ue)}ms`}}),a(1);return}if(`fetchGateway`in P){if(!M(!0))return;let{fetchGateway:t,path:n,rest:i}=P,o=[...r.middlewares??[],...P.middlewares??[]],c=async()=>{let r=Dn(i);t.basePath&&(r.path=t.basePath+r.path);let o=On(r),c=await t.fetch(o);if(kn(c)){await $b(An(c),{name:e,path:n,start:ue,format:fe,formatExplicit:g,human:s,renderOutput:he,fullOutput:m,truncate:_e,write:ve,writeln:d,exit:a});return}let l=await jn(c);l.ok?ve({ok:!0,data:l.data,meta:{command:n,duration:`${Math.round(performance.now()-ue)}ms`}}):(ve({ok:!1,error:{code:`HTTP_${l.status}`,message:typeof l.data==`object`&&l.data!==null&&`message`in l.data?String(l.data.message):typeof l.data==`string`?l.data:`HTTP ${l.status}`},meta:{command:n,duration:`${Math.round(performance.now()-ue)}ms`}}),a(1))};try{let t=r.envSchema?zl(r.envSchema,r.env??process.env):{};if(o.length>0){let i=r.vars?r.vars.parse({}):{},l={agent:!s,command:n,displayName:u,env:t,error:e=>({[Ex]:`error`,...e}),format:fe,formatExplicit:g,globals:ne,name:e,set(e,t){i[e]=t},var:i,version:r.version},d=e=>{if(!Qb(e)||e[Ex]!==`error`)return;let t=e,r=gu(u,t.cta);ve({ok:!1,error:{code:t.code,message:t.message,...t.retryable===void 0?void 0:{retryable:t.retryable}},meta:{command:n,duration:`${Math.round(performance.now()-ue)}ms`,...r?{cta:r}:void 0}}),a(t.exitCode??1)};await o.reduceRight((e,t)=>async()=>{d(await t(l,e))},c)()}else await c()}catch(e){ve({ok:!1,error:{code:e instanceof L?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e)},meta:{command:n,duration:`${Math.round(performance.now()-ue)}ms`}}),a(e instanceof L?e.exitCode??1:1)}return}let{command:ye,path:be,rest:F}=P;if(!M(!0))return;let xe=[...r.middlewares??[],...`middlewares`in N?N.middlewares??[]:[],...ye.middleware??[]];s&&fx(F,ye.options,ye.alias);let Se;if(c)try{Se=await yb(e,be,{configDisabled:k,configPath:O,files:r.config?.files,loader:r.config?.loader})}catch(e){ve({ok:!1,error:{code:e instanceof L?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e)},meta:{command:be,duration:`${Math.round(performance.now()-ue)}ms`}}),a(e instanceof L?e.exitCode??1:1);return}let Ce=await Gl(ye,{agent:!s,argv:F,defaults:Se,displayName:u,env:r.envSchema,envSource:r.env,format:fe,formatExplicit:g,globals:ne,inputOptions:{},middlewares:xe,name:e,path:be,vars:r.vars,version:r.version}),we=`${Math.round(performance.now()-ue)}ms`;if(`stream`in Ce){await $b(Ce.stream,{name:u,path:be,start:ue,format:fe,formatExplicit:g,human:s,renderOutput:he,fullOutput:m,truncate:_e,write:ve,writeln:d,exit:a});return}if(Ce.ok){let e=gu(u,Ce.cta);ve({ok:!0,data:Ce.data,meta:{command:be,duration:we,...e?{cta:e}:void 0}})}else{let e=gu(u,Ce.cta);if(s&&!g&&Ce.error.fieldErrors){d(hb(u,be,ye,new wn({message:Ce.error.message,fieldErrors:Ce.error.fieldErrors}),r.env,l)),a(1);return}ve({ok:!1,error:{code:Ce.error.code,message:Ce.error.message,...Ce.error.retryable===void 0?void 0:{retryable:Ce.error.retryable},...Ce.error.fieldErrors?{fieldErrors:Ce.error.fieldErrors}:void 0},meta:{command:be,duration:we,...e?{cta:e}:void 0}}),a(Ce.exitCode??1)}}function ub(e,t,n={}){let r;async function i(r,i,a){let{fromJsonSchema:o,McpServer:s,WebStandardStreamableHTTPServerTransport:c}=await Promise.resolve().then(()=>(I_(),s_)),l=new s({name:e,...n.title?{title:n.title}:void 0,version:t},n.instructions?{instructions:n.instructions}:void 0);V_(l,r,{env:i?.env,fromJsonSchema:o,middlewares:i?.middlewares,name:e,request:e=>e?.http?.req,sendNotification:e=>l.server.notification(e),tools:n.tools,vars:i?.vars,version:t});let u=new c(a?{enableJsonResponse:!0}:{sessionIdGenerator:()=>crypto.randomUUID(),enableJsonResponse:!0});return await l.connect(u),{server:l,transport:u}}return async(e,t,a)=>{let o=n.stateless??!0;if(o&&e.method!==`POST`)return new Response(null,{status:405,headers:{Allow:`POST`}});if(!o)return r??=i(t,a,!1).catch(e=>{throw r=void 0,e}),(await r).transport.handleRequest(e);let s=()=>e.signal.reason??new DOMException(`This operation was aborted`,`AbortError`);if(e.signal.aborted)throw s();let{server:c,transport:l}=await i(t,a,!0),u,d=()=>u??=c.close(),f,p=new Promise((e,t)=>{f=t}),m=!1,h=()=>{m||(m=!0,f(s()),d())};e.signal.addEventListener(`abort`,h,{once:!0}),e.signal.aborted&&h();try{return e.signal.aborted?await p:await Promise.race([l.handleRequest(e),p])}finally{e.signal.removeEventListener(`abort`,h),await d()}}}function db(e){return e.length===1?e[0]===`openapi.json`||e[0]===`openapi.yml`||e[0]===`openapi.yaml`:e[0]===`.well-known`&&e[1]===`openapi.json`&&e.length===2}function fb(e,t,n){let r={name:e,description:n.description};return _x.set(r,t),n.rootCommand&&bx.set(r,n.rootCommand),pv(r,{title:e,...n.version?{version:n.version}:void 0,...n.description?{description:n.description}:void 0})}async function pb(e,t,n,r={}){let i=performance.now(),a=new URL(n.url),o=a.pathname.split(`/`).filter(Boolean);if(n.method===`GET`&&db(o)){let n=fb(e,t,r),i=o[0]===`openapi.yml`||o[0]===`openapi.yaml`;return new Response(i?(await hl()).stringify(n):JSON.stringify(n),{status:200,headers:{"content-type":i?`application/yaml`:`application/json`,"cache-control":`public, max-age=300`}})}if(o[0]===`mcp`&&o.length===1&&r.mcpHandler)return r.mcpHandler(n,t,{middlewares:r.middlewares,env:r.envSchema,vars:r.vars});if(o[0]===`.well-known`&&o[1]===`skills`&&o.length>=3&&n.method===`GET`){await hl();let n=new Map,i=ax(t,[],n,r.rootCommand);if(o[2]===`index.json`&&o.length===3){let t=xy(e,i,1,n).map(t=>{let n=t.content.match(/^---\n([\s\S]*?)\n---/),r=n?gl().parse(n[1]):{};return{name:t.dir||e,description:r.description??``,files:[`SKILL.md`]}});return new Response(JSON.stringify({skills:t}),{status:200,headers:{"content-type":`application/json`,"cache-control":`public, max-age=300`}})}if(o.length===4&&o[3]===`SKILL.md`){let t=o[2],r=xy(e,i,1,n).find(n=>(n.dir||e)===t);return r?new Response(r.content,{status:200,headers:{"content-type":`text/markdown`,"cache-control":`public, max-age=300`}}):new Response(`Not Found`,{status:404})}return new Response(`Not Found`,{status:404})}let s={};if(n.method===`GET`)for(let[e,t]of a.searchParams)s[e]=t;else try{(n.headers.get(`content-type`)??``).includes(`application/json`)&&(s=await n.json())}catch{}function c(e,t){return new Response(Lr(e),{status:t,headers:{"content-type":`application/json`}})}if(o.length===0)return r.rootCommand?mb(e,r.rootCommand,[],s,n,i,r):c({ok:!1,error:{code:`COMMAND_NOT_FOUND`,message:`No root command defined.`},meta:{command:`/`,duration:`${Math.round(performance.now()-i)}ms`}},404);let l=_b(t,o);if(`error`in l){let t=l.path?`${e} ${l.path}`:e,n=on(l.error,l.commands.keys()),r=n?` Did you mean '${n}'?`:``;return c({ok:!1,error:{code:`COMMAND_NOT_FOUND`,message:`'${l.error}' is not a command for '${t}'.${r}`},meta:{command:l.error,duration:`${Math.round(performance.now()-i)}ms`}},404)}if(`help`in l)return c({ok:!1,error:{code:`COMMAND_NOT_FOUND`,message:`'${l.path}' is a command group. Specify a subcommand.`},meta:{command:l.path,duration:`${Math.round(performance.now()-i)}ms`}},404);if(`fetchGateway`in l)return l.fetchGateway.fetch(n);let{command:u,path:d,rest:f}=l,p=`middlewares`in l?l.middlewares:[];return mb(d,u,f,s,n,i,{...r,groupMiddlewares:p})}async function mb(e,t,n,r,i,a,o){function s(e,t){return new Response(Lr(e),{status:t,headers:{"content-type":`application/json`}})}let c=[...o.middlewares??[],...o.groupMiddlewares??[],...t.middleware??[]],l={},u=r;if(o.globals){let t=new Set(Object.keys(o.globals.schema.shape)),n={};u={};for(let[e,i]of Object.entries(r))t.has(e)?n[e]=i:u[e]=i;try{l=o.globals.schema.parse(n)}catch(t){return s({ok:!1,error:{code:`VALIDATION_ERROR`,message:(t?.issues??t?.error?.issues??[]).map(e=>e.message).join(`; `)||`Validation failed`},meta:{command:e,duration:`${Math.round(performance.now()-a)}ms`}},400)}}let d=await Gl(t,{agent:!0,argv:n,env:o.envSchema,format:`json`,formatExplicit:!0,globals:l,inputOptions:u,middlewares:c,name:o.name??e,parseMode:`split`,path:e,request:i,vars:o.vars,version:o.version}),f=`${Math.round(performance.now()-a)}ms`;if(`stream`in d){let t=d.stream,n=new TextEncoder,r=t=>({command:e,duration:`${Math.round(performance.now()-a)}ms`,...t?{cta:t}:void 0}),i=t=>({type:`error`,ok:!1,error:{code:t.code,message:t.message,...t.retryable===void 0?void 0:{retryable:t.retryable}},meta:r(gu(o.name??e,t.cta))}),s=new ReadableStream({async cancel(){await t.return(void 0)},async pull(a){try{let{value:s,done:c}=await t.next();if(c){if(Qb(s)&&s[Ex]===`error`){a.enqueue(n.encode(Lr(i(s))+`
216
+ `)),a.close();return}let t=Qb(s)&&s[Ex]===`ok`?gu(o.name??e,s.cta):void 0;a.enqueue(n.encode(Lr({type:`done`,ok:!0,meta:r(t)})+`
217
+ `)),a.close();return}if(Qb(s)&&s[Ex]===`error`){a.enqueue(n.encode(Lr(i(s))+`
218
+ `)),await t.return(void 0),a.close();return}a.enqueue(n.encode(Lr({type:`chunk`,data:s})+`
219
+ `))}catch(e){a.enqueue(n.encode(Lr({type:`error`,ok:!1,error:{code:e instanceof L?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e),...e instanceof L?{retryable:e.retryable}:void 0},meta:r()})+`
220
+ `)),a.close()}}});return new Response(s,{status:200,headers:{"content-type":`application/x-ndjson`}})}if(!d.ok){let t=gu(o.name??e,d.cta);return s({ok:!1,error:{code:d.error.code,message:d.error.message,...d.error.retryable===void 0?void 0:{retryable:d.error.retryable},...d.error.fieldErrors?{fieldErrors:d.error.fieldErrors}:void 0},meta:{command:e,duration:f,...t?{cta:t}:void 0}},d.error.code===`VALIDATION_ERROR`?400:500)}let p=gu(o.name??e,d.cta);return s({ok:!0,data:d.data,meta:{command:e,duration:f,...p?{cta:p}:void 0}},200)}function hb(e,t,n,r,i,a){let o=[];for(let e of r.fieldErrors){let t=(()=>{let t=gb(n,e.path);return e.missing?`Error: missing required ${t.kind} ${t.label}`:t.kind===`environment variable`?`Error: invalid value for environment variable ${t.label}: ${e.message}`:`Error: invalid value for ${t.label}: ${e.message}`})();o.push(t)}return o.push(`See below for usage.`),o.push(``),o.push(ru(t===e?e:`${e} ${t}`,{alias:n.alias,configFlag:a,description:n.description,args:n.args,env:n.env,envSource:i,hint:n.hint,options:n.options,examples:lx(n.examples),usage:n.usage})),o.join(`
221
+ `)}function gb(e,t){let[n,...r]=t.split(`.`);if(!n)return{kind:`argument`,label:`input`};if(e.options?.shape[n]){let e=r.length>0?`.${r.join(`.`)}`:``;return{kind:`option`,label:`--${rn(n)}${e}`}}return e.env?.shape[n]?{kind:`environment variable`,label:`${n}${r.length>0?`.${r.join(`.`)}`:``}`}:{kind:`argument`,label:`<${t}>`}}function _b(e,t){let[n,...r]=t;if(!n||!e.has(n))return{error:n??`(none)`,path:``,commands:e,rest:r};let i=Kb(e,e.get(n)),a=[n],o=r,s,c=[];if(Wb(i)){let e=i.outputPolicy??s;return{fetchGateway:i,middlewares:c,path:a.join(` `),rest:o,...e?{outputPolicy:e}:void 0}}for(;Ub(i);){i.outputPolicy&&(s=i.outputPolicy),i.middlewares&&c.push(...i.middlewares);let e=o[0];if(!e&&i.root){let e=i.root.outputPolicy??s;return{command:i.root,commands:i.commands,middlewares:c,path:a.join(` `),rest:o,...e?{outputPolicy:e}:void 0}}if(!e)return{help:!0,path:a.join(` `),description:i.description,commands:i.commands};let t=i.commands.get(e);if(!t){if(i.root&&!on(e,i.commands.keys())){let e=i.root.outputPolicy??s;return{command:i.root,commands:i.commands,middlewares:c,path:a.join(` `),rest:o,...e?{outputPolicy:e}:void 0}}return{error:e,path:a.join(` `),commands:i.commands,rest:o.slice(1)}}let n=Kb(i.commands,t);if(a.push(e),o=o.slice(1),i=n,Wb(i)){let e=i.outputPolicy??s;return{fetchGateway:i,middlewares:c,path:a.join(` `),rest:o,...e?{outputPolicy:e}:void 0}}}let l=i.outputPolicy??s;return{command:i,middlewares:c,path:a.join(` `),rest:o,...l?{outputPolicy:l}:void 0}}function vb(e,t={}){let n=!1,r=!1,i=!1,a=!1,o=!1,s=!1,c=!1,l=!1,u=!1,d=`toon`,f=!1,p,m=!1,h,g,_,v=!1,y=[],b=t.configFlag?`--${t.configFlag}`:void 0,x=t.configFlag?`--${t.configFlag}=`:void 0,S=t.configFlag?`--no-${t.configFlag}`:void 0;for(let t=0;t<e.length;t++){let C=e[t];if(C===`--full-output`)n=!0;else if(C===`--llms`)r=!0;else if(C===`--llms-full`)i=!0;else if(C===`--mcp`)a=!0;else if(C===`--help`||C===`-h`)o=!0;else if(C===`--update`)s=!0;else if(C===`--incur-update-check`)c=!0;else if(C===`--version`&&(e[t+1]===void 0||e[t+1].startsWith(`-`)))l=!0;else if(C===`--schema`)u=!0;else if(C===`--json`)d=`json`,f=!0;else if(C===`--format`&&e[t+1]){if(!gx.has(e[t+1]))throw new Tn({message:`Invalid format: "${e[t+1]}". Expected one of: ${[...gx].join(`, `)}`});d=e[t+1],f=!0,t++}else if(b&&C===b){let n=e[t+1];if(n===void 0)throw new Tn({message:`Missing value for flag: ${b}`});p=n,m=!1,t++}else if(x&&C.startsWith(x)){let e=C.slice(x.length);if(e.length===0)throw new Tn({message:`Missing value for flag: ${b}`});p=e,m=!1}else if(S&&C===S)p=void 0,m=!0;else if(C===`--filter-output`&&e[t+1])h=e[t+1],t++;else if(C===`--token-limit`&&e[t+1]){let n=Number(e[t+1]);if(!Number.isFinite(n)||e[t+1].trim()===``)throw new Tn({message:`Invalid value for --token-limit: "${e[t+1]}"`});g=n,t++}else if(C===`--token-offset`&&e[t+1]){let n=Number(e[t+1]);if(!Number.isFinite(n)||e[t+1].trim()===``)throw new Tn({message:`Invalid value for --token-offset: "${e[t+1]}"`});_=n,t++}else C===`--token-count`?v=!0:y.push(C)}return{fullOutput:n,format:d,formatExplicit:f,configPath:p,configDisabled:m,filterOutput:h,tokenLimit:g,tokenOffset:_,tokenCount:v,llms:r,llmsFull:i,mcp:a,help:o,update:s,updateCheck:c,version:l,schema:u,rest:y}}async function yb(e,t,n={}){if(n.configDisabled)return;let{loader:r}=n,i;i=n.configPath?bb(n.configPath):await xb(n.files??[`${e}.json`]);let a;if(r){let e=await r(i);if(e===void 0)return;if(!nn(e))throw new Tn({message:`Config loader must return a plain object or undefined`});a=e}else{if(!i)return;let e=await Sb(i,!!n.configPath);if(!e)return;a=e}return Cb(a,e,t)}function bb(e){return e.startsWith(`~/`)||e===`~`?c.join(b.homedir(),e.slice(1)):c.resolve(process.cwd(),e)}async function xb(e){for(let t of e){let e=bb(t);try{return await C.access(e,C.constants.R_OK),e}catch{}}}async function Sb(e,t){let n;try{n=await C.readFile(e,`utf8`)}catch(n){if(n.code===`ENOENT`){if(t)throw new Tn({message:`Config file not found: ${e}`});return}throw n}let r;try{r=JSON.parse(n)}catch(t){throw new Tn({message:`Invalid JSON config file: ${e}`,cause:t instanceof Error?t:void 0})}if(!nn(r))throw new Tn({message:`Invalid config file: expected a top-level object in ${e}`});return r}function Cb(e,t,n){let r=n===t?[]:n.split(` `),i=e;for(let e of r){if(!nn(i))return;let t=i.commands;if(!nn(t)||(i=t[e],i===void 0))return}if(!nn(i))throw new Tn({message:`Invalid config section for '${n}': expected an object`});let a=i.options;if(a!==void 0){if(!nn(a))throw new Tn({message:`Invalid config 'options' for '${n}': expected an object`});return Object.keys(a).length>0?a:void 0}}function wb(e){let t=[];for(let[n,r]of e)Gb(r)||t.push({name:n,description:r.description});return t.sort((e,t)=>e.name.localeCompare(t.name))}function Tb(e,t,n){return Xl(e[0])?.name===n?0:e[0]===t&&Xl(e[1])?.name===n?1:-1}function Eb(e,t){return nu(`${e} ${t.name}`,{aliases:t.aliases,description:t.description,commands:t.subcommands?.map(e=>({name:e.name,description:e.description}))})}function Db(e,t,n){let r=Zl(t,n);return ru(`${e} ${t.name} ${n}`,{alias:r?.alias,aliases:r?.aliases,description:r?.description,hideGlobalOptions:!0,options:r?.options})}async function Ob(e,t,n){let r=[],i=[],a=new T,o=new T,s=[];o.on(`data`,e=>s.push(e.toString()));let c,l=L_(n.mcp?.name??e,n.version??`0.0.0`,t,{input:a,output:o,middlewares:n.middlewares,env:n.envSchema,vars:n.vars,version:n.version,...n.mcp?.instructions?{instructions:n.mcp.instructions}:void 0,...n.mcp?.title?{title:n.mcp.title}:void 0,tools:{...n.mcp?.tools,discovery:`direct`}}).catch(e=>{c=e}),u=!1;if(l.finally(()=>{u=!0}),a.write(`${Lr({jsonrpc:`2.0`,id:1,method:`initialize`,params:{protocolVersion:`2024-11-05`,capabilities:{},clientInfo:{name:`incur-doctor`,version:`1.0.0`}}})}\n`),a.write(`${Lr({jsonrpc:`2.0`,id:2,method:`tools/list`,params:{}})}\n`),await kb(s,()=>u),a.end(),await l,c)return{ok:!1,toolCount:0,tools:[],warnings:r,errors:[{code:`MCP_SERVER_FAILED`,message:jb(c)}]};let d;try{d=Ab(s)}catch(e){return{ok:!1,toolCount:0,tools:[],warnings:r,errors:[{code:`MCP_RESPONSE_PARSE_FAILED`,message:jb(e)}]}}let f=d.find(e=>e.id===1);f?f.error&&i.push({code:`MCP_INITIALIZE_FAILED`,message:Mb(f.error)}):i.push({code:`MCP_INITIALIZE_MISSING`,message:`Missing initialize response.`});let p=d.find(e=>e.id===2),m=[];return p?p.error?i.push({code:`MCP_TOOLS_LIST_FAILED`,message:Mb(p.error)}):!nn(p.result)||!Array.isArray(p.result.tools)?i.push({code:`MCP_TOOLS_LIST_INVALID`,message:`tools/list did not return a tools array.`}):m=p.result.tools.filter(nn).map(e=>({name:typeof e.name==`string`?e.name:``,...typeof e.description==`string`?{description:e.description}:void 0})).filter(e=>e.name):i.push({code:`MCP_TOOLS_LIST_MISSING`,message:`Missing tools/list response.`}),i.length===0&&m.length===0&&r.push(`No MCP tools exposed.`),{ok:i.length===0,toolCount:m.length,tools:m,warnings:r,errors:i}}async function kb(e,t){let n=Date.now();for(;!t()&&(e.join(``).match(/\n/g)?.length??0)<2;){if(Date.now()-n>=1e3)return;await new Promise(e=>setTimeout(e,5))}}function Ab(e){let t=[];for(let n of e.join(``).split(/\r?\n/)){let e=n.trim();if(!e)continue;let r=JSON.parse(e);if(!nn(r))throw Error(`Expected JSON-RPC response object.`);t.push(r)}return t}function jb(e){return e instanceof Error?e.message:String(e)}function Mb(e){return nn(e)&&typeof e.message==`string`?e.message:Lr(e)}function Nb(e,t){let n=[];return t?n.push(`${e} — ${t}`):n.push(e),n.push(``),n.push(`Usage: ${e} <path> [options]`),n.push(``),n.push(`Path segments are joined into the request URL path.`),n.push(``),n.push(`Options:`),n.push(` -X, --method <METHOD> HTTP method (default: GET, POST if body present)`),n.push(` -H, --header "Key: Val" Set a request header (repeatable)`),n.push(` -d, --data <json> Request body (implies POST)`),n.push(` --body <json> Request body (implies POST)`),n.push(` --<key> <value> Query string parameter`),n.join(`
222
+ `)}async function Pb(e){if(e)return{directory:ee(e)};let t=process.argv[1];if(!t)throw Error("Could not infer the filesystem command directory without an executed entrypoint. Pass a directory URL to `fs()`.");let n=c.resolve(t);try{let e=await C.realpath(n);return{directory:c.dirname(e),exclude:e}}catch(e){if(e.code!==`ENOENT`)throw e;return{directory:c.dirname(n),exclude:n}}}async function Fb(e){let t=await bu(e.directory,{exclude:e.exclude});return Promise.all(t.map(async e=>({...e,command:(await import(E(e.file).href)).default})))}function Ib(e){return typeof e==`object`&&!!e&&e[hx]===!0}function Lb(e,t,n,r,i){let a=e;for(let[e,o]of t.entries()){let s=e===t.length-1,c=a.get(o);if(s){if(!c)a.set(o,n);else if(Ub(c)&&!c.root)c.root=n,c.description??=n.description;else throw Rb(t,r);qb(t.join(` `),n,i);for(let e of n.aliases??[]){if(a.has(e))throw Rb([...t.slice(0,-1),e],r);a.set(e,{_alias:!0,target:o})}return}if(!c){let e={_group:!0,commands:new Map};a.set(o,e),a=e.commands;continue}if(Gb(c)||Wb(c))throw Rb(t,r);if(Ub(c)){a=c.commands;continue}let l={_group:!0,commands:new Map,description:c.description,root:c};a.set(o,l),a=l.commands}}function Rb(e,t){return Error(`Filesystem command '${e.join(` `)}' from '${t}' conflicts with an existing command or alias.`)}function zb(e){if(typeof e==`function`)return!0;if(typeof e!=`object`||!e)return!1;let t=e;return typeof t.fetch==`function`&&t.url instanceof URL}function Bb(e){if(typeof e!=`object`||!e||!(`mcp`in e))return!1;let t=e.mcp;return typeof t==`string`||t instanceof URL||typeof t==`object`&&!!t&&`url`in t}function Vb(e){return typeof e==`function`?e:e.fetch}function Hb(e){return typeof e==`function`?void 0:e.url}function Ub(e){return`_group`in e}function Wb(e){return`_fetch`in e}function Gb(e){return`_alias`in e}function Kb(e,t){return Gb(t)?e.get(t.target):t}function qb(e,t,n){if(!(!n||Wb(t)||Gb(t))){if(Ub(t)){t.root&&qb(e,t.root,n);for(let[r,i]of t.commands)qb(`${e} ${r}`,i,n);return}if(t.options){let r=Object.keys(n.schema.shape),i=Object.keys(t.options.shape);for(let t of i)if(r.includes(t))throw Error(`Command '${e}' option '${t}' conflicts with a global option. Choose a different name.`)}if(n.alias&&t.alias){let r=new Set(Object.values(n.alias));for(let[n,i]of Object.entries(t.alias))if(i&&r.has(i))throw Error(`Command '${e}' alias '-${i}' for '${n}' conflicts with a global alias. Choose a different alias.`)}}}function Jb(e){let t=`${e.code===`UNKNOWN`||e.code===`COMMAND_NOT_FOUND`?`Error`:`Error (${e.code})`}: ${e.message}`;if(e.fieldErrors)for(let n of e.fieldErrors)t+=`\n ${n.path}: ${n.message}`;return t}function Yb(e){let t=[``,e.description],n=Math.max(...e.commands.map(e=>e.command.length));for(let r of e.commands){let e=r.description?` ${``.padEnd(n-r.command.length)}# ${r.description}`:``;t.push(` ${r.command}${e}`)}return t.join(`
223
+ `)}function Xb(...e){let t=e.filter(e=>e!==void 0);if(t.length!==0)return{description:t[0].description,commands:t.flatMap(e=>e.commands)}}function Zb(e){return Object.values(e.shape).some(e=>e._zod.optout!==`optional`)}function Qb(e){return typeof e==`object`&&!!e&&Ex in e}async function $b(e,t){let n=t.format===`jsonl`;if(n||!t.formatExplicit&&t.format===`toon`)try{let r;for(;;){let{value:i,done:a}=await e.next();if(a){r=i;break}if(Qb(i)){let e=i;if(e[Ex]===`error`){n?t.writeln(JSON.stringify({type:`error`,ok:!1,error:{code:e.code,message:e.message,...e.retryable===void 0?void 0:{retryable:e.retryable}}})):t.writeln(Jb({code:e.code,message:e.message})),t.exit(e.exitCode??1);return}}n?t.writeln(Lr({type:`chunk`,data:i})):t.renderOutput&&t.writeln(t.truncate(yl(i,t.format)).text)}if(Qb(r)&&r[Ex]===`error`){let e=r;n?t.writeln(JSON.stringify({type:`error`,ok:!1,error:{code:e.code,message:e.message,...e.retryable===void 0?void 0:{retryable:e.retryable}}})):t.writeln(Jb({code:e.code,message:e.message})),t.exit(e.exitCode??1);return}let i=Qb(r)&&r[Ex]===`ok`?gu(t.name,r.cta):void 0;n?t.writeln(JSON.stringify({type:`done`,ok:!0,meta:{command:t.path,duration:`${Math.round(performance.now()-t.start)}ms`,...i?{cta:i}:void 0}})):i&&t.writeln(Yb(i))}catch(e){n?t.writeln(JSON.stringify({type:`error`,ok:!1,error:{code:e instanceof L?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e),...e instanceof L?{retryable:e.retryable}:void 0}})):t.writeln(Jb({code:`UNKNOWN`,message:e instanceof Error?e.message:String(e)})),t.exit(e instanceof L?e.exitCode??1:1)}else{let n=[];try{let r;for(;;){let{value:i,done:a}=await e.next();if(a){r=i;break}if(Qb(i)){let e=i;if(e[Ex]===`error`){t.write({ok:!1,error:{code:e.code,message:e.message,...e.retryable===void 0?void 0:{retryable:e.retryable}},meta:{command:t.path,duration:`${Math.round(performance.now()-t.start)}ms`}}),t.exit(e.exitCode??1);return}}n.push(i)}if(Qb(r)&&r[Ex]===`error`){let e=r;t.write({ok:!1,error:{code:e.code,message:e.message,...e.retryable===void 0?void 0:{retryable:e.retryable}},meta:{command:t.path,duration:`${Math.round(performance.now()-t.start)}ms`}}),t.exit(e.exitCode??1);return}let i=Qb(r)&&r[Ex]===`ok`?gu(t.name,r.cta):void 0;t.write({ok:!0,data:n,meta:{command:t.path,duration:`${Math.round(performance.now()-t.start)}ms`,...i?{cta:i}:void 0}})}catch(e){t.write({ok:!1,error:{code:e instanceof L?e.code:`UNKNOWN`,message:e instanceof Error?e.message:String(e),...e instanceof L?{retryable:e.retryable}:void 0},meta:{command:t.path,duration:`${Math.round(performance.now()-t.start)}ms`}}),t.exit(e instanceof L?e.exitCode??1:1)}}}function ex(e,t=[],n,r){let i=tx(e,t);return r&&t.length>0&&i.push({name:t.join(` `),...r.description?{description:r.description}:void 0}),{version:`incur.v1`,commands:i.sort((e,t)=>e.name.localeCompare(t.name)),...n?{globals:Ou(n)}:void 0}}function tx(e,t){let n=[];for(let[r,i]of e){if(Gb(i))continue;let e=[...t,r];if(Ub(i)){if(i.root){let t={name:e.join(` `)};i.root.description&&(t.description=i.root.description),n.push(t)}n.push(...tx(i.commands,e))}else{let t={name:e.join(` `)};Wb(i),i.description&&(t.description=i.description),n.push(t)}}return n}function nx(e,t=[],n,r){let i=rx(e,t);return r&&t.length>0&&i.push(ix(t,r)),{version:`incur.v1`,commands:i.sort((e,t)=>e.name.localeCompare(t.name)),...n?{globals:Ou(n)}:void 0}}function rx(e,t){let n=[];for(let[r,i]of e){if(Gb(i))continue;let e=[...t,r];if(Wb(i)){let t={name:e.join(` `)};i.description&&(t.description=i.description),n.push(t)}else Ub(i)?(i.root&&n.push(ix(e,i.root)),n.push(...rx(i.commands,e))):n.push(ix(e,i))}return n}function ix(e,t){let n={name:e.join(` `)};t.description&&(n.description=t.description);let r=dx(t.args,t.env,t.options),i=t.output?Ou(t.output):void 0;(r||i)&&(n.schema={},r?.args&&(n.schema.args=r.args),r?.env&&(n.schema.env=r.env),r?.options&&(n.schema.options=r.options),i&&(n.schema.output=i));let a=lx(t.examples);if(a){let t=e.join(` `);n.examples=a.map(e=>({...e,command:e.command?`${t} ${e.command}`:t}))}return n}function ax(e,t,n,r){let i=[];if(r){let e={};r.description&&(e.description=r.description),r.args&&(e.args=r.args),r.env&&(e.env=r.env),r.hint&&(e.hint=r.hint),sx(r)&&(e.hint=cx(e.hint)),r.options&&(e.options=r.options),r.output&&(e.output=r.output);let t=lx(r.examples);t&&(e.examples=t),i.push(e)}for(let[r,a]of e){if(Gb(a))continue;let e=[...t,r];if(Wb(a)){let t={name:e.join(` `)};a.description&&(t.description=a.description),t.hint=`Fetch gateway. Pass path segments and curl-style flags (-X, -H, -d, --key value).`,i.push(t)}else Ub(a)?(a.description&&n.set(e.join(` `),a.description),a.root&&i.push(ox(e,a.root)),i.push(...ax(a.commands,e,n))):i.push(ox(e,a))}return i.sort((e,t)=>(e.name??``).localeCompare(t.name??``))}function ox(e,t){let n={name:e.join(` `)};t.description&&(n.description=t.description),t.args&&(n.args=t.args),t.env&&(n.env=t.env),t.hint&&(n.hint=t.hint),sx(t)&&(n.hint=cx(n.hint)),t.options&&(n.options=t.options),t.output&&(n.output=t.output);let r=lx(t.examples);if(r){let t=e.join(` `);n.examples=r.map(e=>({...e,command:e.command?`${t} ${e.command}`:t}))}return n}function sx(e){return e.destructive===!0||e.mcp!==!1&&e.mcp?.annotations?.destructiveHint===!0}function cx(e){return e?e.includes(mx)?e:`${e} ${mx}`:mx}function lx(e){if(!(!e||e.length===0))return e.map(e=>{let t=[];if(e.args)for(let n of Object.values(e.args))t.push(String(n));if(e.options)for(let[n,r]of Object.entries(e.options))t.push(`--${n} ${r}`);let n={command:t.join(` `)};return e.description&&(n.description=e.description),n})}function ux(e){let t=e.match(/^---\r?\n([\s\S]*?)\r?\n---/);if(!t)return{};let n=gl().parse(t[1]);return!n||typeof n!=`object`?{}:n}function dx(e,t,n){if(!e&&!t&&!n)return;let r={};return e&&(r.args=Ou(e)),t&&(r.env=Ou(t)),n&&(r.options=Ou(n)),r}function fx(e,t,n){if(!t)return;let r=t.shape,i=new Set,a=new Map;for(let e of Object.keys(r))if(r[e]?.meta?.()?.deprecated){let t=e.replace(/[A-Z]/g,e=>`-${e.toLowerCase()}`);i.add(t),n?.[e]&&a.set(n[e],t)}if(i.size!==0){for(let t of e)if(t.startsWith(`--`)){let e=t.split(`=`)[0].slice(2),n=!i.has(e)&&e.startsWith(`no-`)?e.slice(3):e;i.has(n)&&process.stderr.write(`Warning: --${n} is deprecated\n`)}else if(t.startsWith(`-`)&&t.length>=2)for(let e of t.slice(1))a.has(e)&&process.stderr.write(`Warning: --${a.get(e)} is deprecated\n`)}}function px(e,t){let n=process.argv[1];if(!n)return e;let r=c.basename(n);return r===e?e:t?.includes(r)?r:e}var mx,hx,gx,_x,vx,yx,bx,xx,Sx,Cx,wx,Tx,Ex,Dx=I((()=>{tn(),zt(),xn(),En(),Pn(),Rn(),Dl(),hu(),tu(),yu(),Du(),sn(),zr(),rt(),Ct(),vl(),cv(),_y(),ry(),Wl(),ku(),Oy(),Ry(),sb(),mx=`Confirm with the user before executing this destructive command.`,hx=Symbol.for(`incur.fileCommand`),gx=new Set([`toon`,`json`,`yaml`,`md`,`jsonl`]),_x=new WeakMap,vx=new WeakMap,yx=new WeakMap,bx=new WeakMap,xx=new WeakMap,Sx=new WeakMap,Cx=new WeakMap,wx=new WeakMap,Tx=new WeakMap,Ex=Symbol.for(`incur.sentinel`)})),Ox=I((()=>{zt(),Dx(),xn(),En(),Dl(),hu(),cv(),Pn(),ry(),Wl(),ku(),Oy(),vl(),Ry(),sb()}));function kx(e,t){if(!(!e||typeof e!=`object`))return e[t]}var q,Ax,jx,Mx,Nx,Px,Fx=I((()=>{q={acceptPayment:`Accept-Payment`,authorization:`Authorization`,paymentAuthorization:`Payment-Authorization`,paymentReceipt:`Payment-Receipt`,paymentSession:`Payment-Session`,paymentSessionSnapshot:`Payment-Session-Snapshot`,wwwAuthenticate:`WWW-Authenticate`},Ax={payment:`Payment`},jx={evm:`evm`,stripe:`stripe`,tempo:`tempo`},Mx={charge:`charge`,session:`session`,subscription:`subscription`},Nx={sessionProtocol:`sessionProtocol`,sessionSnapshot:`sessionSnapshot`},Px={v1:`v1`,v2:`v2`}}));function Ix(e){let t=k.toString(e);return JSON.parse(t)}function Lx(e,t){return e.schema.request.parse(t)}function Rx(e){let t=j.canonicalize(e);return k.fromString(t,{pad:!1,url:!0})}var zx=I((()=>{})),J=Ze({address:()=>Kx,amount:()=>Vx,datetime:()=>Hx,datetimeInput:()=>Ux,hash:()=>qx,period:()=>Jx,signature:()=>Yx,toDate:()=>Wx,toDatetimeString:()=>Gx,unwrapOptional:()=>Xx});import*as Bx from"zod/mini";$e(J,Bx);function Vx(){return be.string().check(be.regex(/^\d+(\.\d+)?$/,`Invalid amount`))}function Hx(){return be.string().check(be.regex(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:\d{2})$/,`Invalid ISO 8601 datetime`))}function Ux(e=`Invalid ISO 8601 datetime`){return be.pipe(be.union([Hx(),be.custom(e=>e instanceof Date)]),be.transform(Wx)).check(be.refine(e=>Number.isFinite(e.getTime()),e))}function Wx(e){return e instanceof Date?e:new Date(e)}function Gx(e){return e instanceof Date?Number.isFinite(e.getTime())?e.toISOString():`Invalid Date`:e}function Kx(){return be.string().check(be.regex(/^0x[0-9a-fA-F]{40}$/,`Invalid address`))}function qx(){return be.string().check(be.regex(/^0x[0-9a-fA-F]{64}$/,`Invalid hash`))}function Jx(){return be.string().check(be.regex(/^(day|week|month|year|\d+)$/,`Invalid period`))}function Yx(){return be.string().check(be.regex(/^0x[0-9a-fA-F]+$/,`Invalid signature`))}function Xx(e){return e._zod.def.type===`optional`?e._zod.def.innerType:e}var Zx=I((()=>{}));function Qx(e,t){let{description:n,digest:r,meta:i,method:a,header:o,intent:s,realm:c,request:l,secretKey:u}=e,d=pS(o)?void 0:o,f=e.expires?Gx(e.expires):void 0,p=e.opaque??(i===void 0?void 0:Rx(i)),m=u?mS({...e,expires:f,...i!==void 0&&{meta:i},opaque:p},{secretKey:u}):e.id;return gS.parse({id:m,realm:c,method:a,intent:s,request:l,...n&&{description:n},...r&&{digest:r},...f&&{expires:f},...d!==void 0&&{header:d},...i!==void 0&&{meta:i},...p!==void 0&&{opaque:p}})}function $x(e){let t=[eS(`id`,e.id),eS(`realm`,e.realm),eS(`method`,e.method),eS(`intent`,e.intent),eS(`request`,Rx(e.request))];e.description!==void 0&&t.push(eS(`description`,e.description)),e.digest!==void 0&&t.push(eS(`digest`,e.digest)),e.expires!==void 0&&t.push(eS(`expires`,e.expires));let n=e.header;return n!==void 0&&!pS(n)&&t.push(eS(`header`,n)),e.opaque===void 0?e.meta!==void 0&&t.push(eS(`opaque`,Rx(e.meta))):t.push(eS(`opaque`,e.opaque)),`${Ax.payment} ${t.join(`, `)}`}function eS(e,t){if(/[\r\n]/.test(t))throw Error(`Invalid quoted-string value.`);return`${e}="${t.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`).replace(/[\u0100-\uffff]/g,e=>`\\u${e.charCodeAt(0).toString(16).padStart(4,`0`)}`)}"`}function tS(e,t){let n=nS(e);if(!n)throw Error(`Missing Payment scheme.`);let{request:r,opaque:i,...a}=rS(n);if(!r)throw Error(`Missing request parameter.`);if(r.length>hS)throw Error(`Request parameter too large.`);if(a.method&&!/^[a-z][a-z0-9:_-]*$/.test(a.method))throw Error(`Invalid method: "${a.method}". Must be lowercase per spec.`);return Qx({...a,request:Ix(r),...i&&{opaque:i}},t)}function nS(e){let t=Ax.payment,[n]=sS(e,t);if(n===void 0)return null;let r=n+t.length;for(;r<e.length&&/\s/.test(e[r]??``);)r++;return e.slice(r)}function rS(e){let t=Object.create(null),n=0;for(;n<e.length;){for(;n<e.length&&/[\s,]/.test(e[n]??``);)n++;if(n>=e.length)break;let r=n;for(;n<e.length&&/[A-Za-z0-9_-]/.test(e[n]??``);)n++;let i=e.slice(r,n).toLowerCase();if(!i)throw Error(`Malformed auth-param.`);for(;n<e.length&&/\s/.test(e[n]??``);)n++;if(e[n]!==`=`)break;for(n++;n<e.length&&/\s/.test(e[n]??``);)n++;let[a,o]=iS(e,n);if(n=o,i in t)throw Error(`Duplicate parameter: ${i}`);t[i]=a}return t}function iS(e,t){if(e[t]===`"`)return aS(e,t+1);let n=t;for(;n<e.length&&e[n]!==`,`;)n++;return[e.slice(t,n).trim(),n]}function aS(e,t){let n=t,r=!1,i=t,a;for(;n<e.length;){let o=e[n];if(n++,r){a??=[];let t=o===`u`?e.slice(n,n+4):void 0;t&&/^[0-9A-Fa-f]{4}$/.test(t)?(a.push(String.fromCharCode(Number.parseInt(t,16))),n+=4):a.push(o),i=n,r=!1;continue}if(o===`\\`){a??=[],a.push(e.slice(i,n-1)),i=n,r=!0;continue}if(o===`"`)return[a?[...a,e.slice(i,n-1)].join(``):e.slice(t,n-1),n]}throw Error(`Unterminated quoted-string.`)}function oS(e,t,n){if(e.slice(t,t+n.length).toLowerCase()!==n.toLowerCase())return!1;let r=e[t+n.length];return!!(r&&/\s/.test(r))}function sS(e,t){let n=[],r=!1,i=!1;for(let a=0;a<e.length;a++){let o=e[a];if(r){i?i=!1:o===`\\`?i=!0:o===`"`&&(r=!1);continue}if(o===`"`){r=!0;continue}if(!oS(e,a,t))continue;let s=a-1;for(;s>=0&&/\s/.test(e[s]??``);)s--;s>=0&&e[s]!==`,`||n.push(a)}return n}function cS(e,t){if(e.status!==402)throw Error(`Response status is not 402.`);return lS(e.headers,t)}function lS(e,t){let n=e.get(q.wwwAuthenticate);if(!n)throw Error(`Missing ${q.wwwAuthenticate} header.`);return uS(n,t)}function uS(e,t){let n=sS(e,Ax.payment);if(n.length===0)throw Error(`No Payment schemes found.`);return n.map((r,i)=>{let a=i+1<n.length?n[i+1]:e.length;return tS(e.slice(r,a).replace(/,\s*$/,``),t)})}function dS(e){let t=[e.realm,e.method,e.intent,Rx(e.request),e.expires??``,e.digest??``],n=e.header;return n!==void 0&&!pS(n)&&t.push(n),t.push(e.opaque??(e.meta?Rx(e.meta):``)),t.join(`|`)}function fS(e){return e.header??q.authorization}function pS(e){return e?.toLowerCase()===q.authorization.toLowerCase()}function mS(e,t){let n=dS(e),r=A.fromString(t.secretKey),i=A.fromString(n),a=te.hmac256(r,i,{as:`Bytes`});return k.fromBytes(a,{url:!0,pad:!1})}var hS,gS,_S=I((()=>{Fx(),zx(),Zx(),hS=16384,gS=J.object({description:J.optional(J.string()),digest:J.optional(J.string().check(J.regex(/^sha-256=/,`Invalid digest format`))),expires:J.optional(Hx()),header:J.optional(J.string().check(J.regex(/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,`Invalid HTTP header name`))),id:J.string().check(J.minLength(1)),intent:J.string(),method:J.string(),meta:J.optional(J.record(J.string(),J.string())),opaque:J.optional(J.string()),realm:J.string(),request:J.record(J.string(),J.unknown())})})),vS,yS,Y,bS,xS,SS=I((()=>{vS=class extends Error{details;status=402;hint;constructor(e,t={}){super(e),this.details=t.details,t.cause!==void 0&&Object.defineProperty(this,"cause",{configurable:!0,value:t.cause,writable:!0})}toProblemDetails(e){return{type:this.type,title:this.title,status:this.status,detail:this.message,...this.details&&Object.keys(this.details).length>0&&{details:this.details},...this.hint&&{hint:this.hint},...e&&{challengeId:e}}}},yS=class extends vS{name=`InvalidChallengeError`;title=`Invalid Challenge`;status=402;type=`https://paymentauth.org/problems/invalid-challenge`;constructor(e={}){let{id:t,reason:n}=e,r=t?` "${t}"`:``,i=n?`: ${n}`:``;super(`Challenge${r} is invalid${i}.`)}},Y=class extends vS{name=`VerificationFailedError`;title=`Verification Failed`;type=`https://paymentauth.org/problems/verification-failed`;constructor(e={}){let{details:t,reason:n}=e;super(n?`Payment verification failed: ${n}.`:`Payment verification failed.`,{details:t})}},bS=class extends vS{name=`PaymentExpiredError`;title=`Payment Expired`;type=`https://paymentauth.org/problems/payment-expired`;constructor(e={}){let{expires:t}=e;super(t?`Payment expired at ${t}.`:`Payment has expired.`)}},xS=class extends vS{name=`PaymentOutcomeUnknownError`;title=`Payment Outcome Unknown`;type=`https://paymentauth.org/problems/payment-outcome-unknown`;challenge;credential;transactionHash;constructor(e){let{cause:t,challenge:n,credential:r,transactionHash:i}=e;super(`Payment outcome is unknown after sending a credential for challenge "${n.id}". Do not blindly retry.`,{cause:t}),this.challenge=n,this.credential=r,this.transactionHash=i}}}));function CS(e,t){if(!e)throw new yS({...t&&{id:t},reason:`missing required expires field`});if(Number.isNaN(new Date(e).getTime()))throw new yS({...t&&{id:t},reason:`malformed expires timestamp`});if(new Date(e)<new Date)throw new bS({expires:e})}var wS=I((()=>{SS()}));function TS(e){return Object.defineProperty(e,DS,{value:!0}),e}function ES(e){return!!e?.[DS]}var DS,OS=I((()=>{DS=Symbol.for(`mppx.x402.challenge`)}));function kS(e){let t={};for(let n of e){let e=t[n.name]??={};e[n.intent]=FS(n)}return t}function AS(e,t){let n=kS(e),r=HS(e,n,t),i=e.map((e,t)=>({intent:e.intent,method:e.name,q:r[FS(e)]??1,index:t}));return{definition:r,entries:i,header:MS(i),keys:n}}function jS(e){let t=e.split(/\s*,\s*/).map(e=>e.trim()).filter(Boolean);if(t.length===0)throw Error(`Accept-Payment header is empty.`);return t.map((e,t)=>BS(e,t))}function MS(e){return e.map(({method:e,intent:t,q:n})=>{let r=`${e}/${t}`;return n===1?r:`${r};q=${KS(n)}`}).join(`, `)}function NS(e,t,n){let r=PS(e,t,n)[0];if(r)return{challenge:r.challenge,method:r.method}}function PS(e,t,n){let r=new Map;for(let e of t){let t=FS(e),n=r.get(t);n?n.push(e):r.set(t,[e])}return e.flatMap((e,t)=>{let i=r.get(FS(e));if(!i)return[];let a=IS(e,n);return!a||a.q<=0?[]:i.filter(t=>t.canHandleChallenge?.({challenge:e})??!0).map(n=>({challenge:e,index:t,match:a,method:n}))}).sort((e,t)=>zS(e.challenge)-zS(t.challenge)||t.match.q-e.match.q||e.index-t.index).map(e=>{let{match:t,...n}=e;return n})}function FS(e){let t=e.method??e.name;if(!t)throw Error(`Missing payment method name.`);return`${t}/${e.intent}`}function IS(e,t){let n;for(let r of t){if(!LS(e,r))continue;let t={...r,specificity:RS(r)};(!n||t.specificity>n.specificity||t.specificity===n.specificity&&t.q>n.q||t.specificity===n.specificity&&t.q===n.q&&t.index<n.index)&&(n=t)}return n}function LS(e,t){return(t.method===`*`||t.method===e.method)&&(t.intent===`*`||t.intent===e.intent)}function RS(e){return Number(e.method!==`*`)+Number(e.intent!==`*`)}function zS(e){return+!!ES(e)}function BS(e,t){let n=/^(?<method>[^/;\s]+|\*)\s*\/\s*(?<intent>[^/;\s]+|\*)(?<params>(?:\s*;\s*.+)?)$/u.exec(e),r=n?.groups?.method,i=n?.groups?.intent;if(!r||!i)throw Error(`Invalid Accept-Payment entry: ${e}`);qS(r,`method`),qS(i,`intent`);let a=1;for(let t of VS(n.groups?.params)){if(!t)continue;let n=/^(?<name>[A-Za-z0-9_-]+)\s*=\s*(?<value>\S+)$/u.exec(t),r=n?.groups?.name,i=n?.groups?.value;if(!r||!i)throw Error(`Invalid Accept-Payment parameter: ${t}`);r===`q`&&(a=WS(i,`Accept-Payment entry "${e}"`))}return{intent:i,method:r,q:a,index:t}}function VS(e){return e?e.split(/\s*;\s*/).filter(Boolean):[]}function HS(e,t,n){if(!n)return{};let r=typeof n==`function`?n(t):n,i=new Set(e.map(e=>FS(e))),a={};for(let[e,t]of Object.entries(r??{})){if(!i.has(e))throw Error(`Unknown payment preference "${e}". Available: ${[...i].join(`, `)}`);a[e]=US(t,`payment preference "${e}"`)}return a}function US(e,t){if(typeof e!=`number`||Number.isNaN(e)||!Number.isFinite(e))throw Error(`Invalid q-value for ${t}. Expected a finite number.`);return GS(e,t)}function WS(e,t){if(!/^0(?:\.\d{0,3})?$|^1(?:\.0{0,3})?$/.test(e))throw Error(`Invalid q-value for ${t}. Expected an HTTP qvalue.`);return GS(Number(e),t)}function GS(e,t){if(e<0||e>1)throw Error(`Invalid q-value for ${t}. Expected a value between 0 and 1.`);let n=Math.round(e*1e3);if(Math.abs(e*1e3-n)>1e-9)throw Error(`Invalid q-value for ${t}. Expected at most 3 decimal places.`);return n/1e3}function KS(e){return e.toFixed(3).replace(/\.0+$/,``).replace(/(\.\d*?)0+$/,`$1`)}function qS(e,t){if(e!==`*`&&!/^[a-z0-9-]+$/.test(e))throw Error(`Invalid Accept-Payment ${t}: ${e}`)}var JS=I((()=>{OS()}));function YS(e){if(e.length>eC)throw new nC;let t=e.match(RegExp(`^${Ax.payment}\\s+(.+)$`,`i`));if(!t?.[1])throw new tC;try{let e=k.toString(t[1]),n=JSON.parse(e),{opaque:r,request:i,meta:a,...o}=n.challenge,{meta:s,opaque:c}=XS(r);return{challenge:gS.parse({...o,...s!==void 0&&{meta:s},...c!==void 0&&{opaque:c},request:Ix(i)}),payload:n.payload,...n.source&&{source:n.source}}}catch{throw new nC}}function XS(e){if(e===void 0)return{};if(typeof e==`string`)return{opaque:e};if(!ZS(e))throw Error(`Invalid opaque.`);return{meta:e,opaque:Rx(e)}}function ZS(e){return typeof e!=`object`||!e||Array.isArray(e)?!1:Object.values(e).every(e=>typeof e==`string`)}function QS(e){let{challenge:t,payload:n,source:r}=e;return{challenge:t,payload:n,...r&&{source:r}}}function $S(e){let{meta:t,opaque:n,request:r,...i}=e.challenge,a=n??(t===void 0?void 0:Rx(t)),o={challenge:{...i,...a!==void 0&&{opaque:a},request:Rx(r)},payload:e.payload,...e.source&&{source:e.source}},s=JSON.stringify(o),c=k.fromString(s,{pad:!1,url:!0});return`${Ax.payment} ${c}`}var eC,tC,nC,rC=I((()=>{_S(),Fx(),zx(),eC=65536,tC=class extends Error{name=`MissingPaymentSchemeError`;constructor(){super(`Missing Payment scheme.`)}},nC=class extends Error{name=`InvalidCredentialEncodingError`;constructor(){super(`Invalid base64url or JSON.`)}}})),iC,aC,oC=I((()=>{iC=`org.paymentauth/credential`,aC=`org.paymentauth/payment-required`}));function sC(e){let{extensions:t,resource:n,...r}=e;return xC.parse(r)}var cC,lC,uC,dC,fC,pC,mC,hC,gC,_C,vC,yC,bC,xC,SC,CC,wC,TC,EC,DC,OC,kC,AC=I((()=>{Zx(),cC=`charge`,lC=[`exact`],uC=`eip155:`,dC=`x402:`,fC=`PAYMENT-REQUIRED`,pC=`PAYMENT-SIGNATURE`,mC=`PAYMENT-RESPONSE`,hC=J.string().check(J.minLength(1)),gC=J.number().check(J.refine(e=>e>0,`Must be positive`)),_C=J.string().check(J.regex(/^\d+$/,`Invalid atomic amount`)),vC=Kx(),yC=J.string().check(J.regex(RegExp(`^${uC}\\d+$`),`Invalid EVM CAIP-2 network`)),bC=J.object({description:J.optional(J.string()),iconUrl:J.optional(J.string()),mimeType:J.optional(J.string()),serviceName:J.optional(J.string()),tags:J.optional(J.array(J.string())),url:hC}),J.discriminatedUnion(`type`,[J.object({name:hC,type:J.literal(`eip3009`),version:hC}),J.object({name:J.optional(J.string()),type:J.literal(`permit2`),version:J.optional(J.string())})]),xC=J.object({amount:_C,asset:hC,extra:J.optional(J.record(J.string(),J.unknown())),maxTimeoutSeconds:gC,network:yC,payTo:hC,scheme:J.enum(lC)}),SC=J.object({info:J.record(J.string(),J.unknown()),schema:J.record(J.string(),J.unknown())}),CC=J.record(J.string(),SC),wC=J.object({accepts:J.array(xC).check(J.minLength(1)),error:J.optional(J.string()),extensions:J.optional(CC),resource:bC,x402Version:J.literal(2)}),TC=J.object({authorization:J.object({from:vC,nonce:qx(),to:vC,validAfter:_C,validBefore:_C,value:_C}),signature:Yx()}),EC=J.object({permit2Authorization:J.object({deadline:_C,from:vC,nonce:_C,permitted:J.object({amount:_C,token:vC}),spender:vC,witness:J.object({to:vC,validAfter:_C})}),signature:Yx()}),DC=J.union([TC,EC]),OC=J.object({accepted:xC,extensions:J.optional(CC),payload:DC,resource:J.optional(bC),x402Version:J.literal(2)}),J.object({extensions:J.optional(CC),extra:J.optional(J.record(J.string(),J.unknown())),invalidMessage:J.optional(J.string()),invalidReason:J.optional(J.string()),isValid:J.boolean(),payer:J.optional(J.string())}),kC=J.object({amount:J.optional(_C),errorMessage:J.optional(J.string()),errorReason:J.optional(J.string()),extensions:J.optional(CC),extra:J.optional(J.record(J.string(),J.unknown())),network:hC,payer:J.optional(J.string()),success:J.boolean(),transaction:J.string()})}));function jC(e,t,n){let r=new Headers(e.headers);for(let e of MC)e===q.authorization&&!r.get(e)?.startsWith(`Payment `)||r.delete(e);return r.set(t,n),{...e,headers:r}}var MC,NC=I((()=>{Fx(),AC(),MC=[q.authorization,fC,mC,pC]}));function PC(e){if(typeof e==`string`)try{let t=JSON.parse(e),n=t?.id;return t?.jsonrpc!==`2.0`||typeof t?.method!=`string`?void 0:typeof n==`string`||typeof n==`number`?n:void 0}catch{return}}function FC(e){let t=PC(e?.body);if(t===void 0)return;let n=new Headers(e?.headers);if(n.has(`mcp-method`))return t;let r=n.get(`accept`)?.toLowerCase()??``;return r.includes(`application/json`)&&r.includes(`text/event-stream`)?t:void 0}function IC(e){if(!e||typeof e!=`object`)return;let t=e,n=t.id;if(t.jsonrpc!==`2.0`||n!==void 0&&typeof n!=`string`&&typeof n!=`number`)return;let r=`error`in t;if(r!==`result`in t)return r?Number.isInteger(t.error?.code)&&typeof t.error?.message==`string`?e:void 0:n!==void 0&&typeof t.result==`object`?e:void 0}function LC(e){if(!e||typeof e!=`object`)return;let t=e?.challenges;if(!Array.isArray(t)||t.length===0)return;let n=[];for(let e of t){let t=gS.safeParse(e);if(!t.success)return;n.push(t.data)}let{httpStatus:r,problem:i}=e;return{challenges:n,...typeof r==`number`?{httpStatus:r}:{},...i===void 0?{}:{problem:i}}}function RC(e){if(e)return`error`in e?e.error?.code!==-32042&&e.error?.code!==-32043?void 0:LC(e.error.data):LC(e.result?._meta?.[aC])}function zC(e,t){return!e||e.id!==t?[]:RC(e)?.challenges??[]}async function BC(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=0,i=!1,a,o=F({onEvent(e){if(!(i||!e.data)&&(i=!0,!(e.event&&e.event!==`message`)))try{a=IC(JSON.parse(e.data))}catch{}}});try{for(;;){if(i)return a;let{done:e,value:s}=await t.read();if(e)return o.feed(n.decode()),o.reset({consume:!0}),a;if(r+=s.byteLength,r>WC)return;o.feed(n.decode(s,{stream:!0}))}}finally{t.cancel().catch(()=>{})}}async function VC(e){let t=e.clone().body?.getReader();if(!t)return;let n=new TextDecoder,r=0,i=``;try{for(;;){let{done:e,value:a}=await t.read();if(e)return IC(JSON.parse(i+n.decode()));if(r+=a.byteLength,r>WC)return;i+=n.decode(a,{stream:!0})}}catch{return}finally{t.cancel().catch(()=>{})}}function HC(e){let t=GC.get(e);if(t)return t;let n=(async()=>{let t=e.headers.get(`content-type`)?.toLowerCase()??``;if(!(Number(e.headers.get(`content-length`))>WC)){if(t.includes(`application/json`))return VC(e);if(t.includes(`text/event-stream`))return BC(e)}})();return GC.set(e,n),n}function UC(){return{getChallenges(e,t){let n=FC(t);return e.status===402||n===void 0?[]:HC(e).then(e=>zC(e,n))},setCredential(e,t){let n=JSON.parse(e.body),r=YS(t);return{...e,body:JSON.stringify({...n,params:{...n.params,_meta:{...n.params?._meta,[iC]:r}}})}}}}var WC,GC,KC=I((()=>{_S(),rC(),oC(),NC(),WC=1048576,GC=new WeakMap}));function qC(){return{getChallenges(e){return e.status!==402||!e.headers.has(q.wwwAuthenticate)?[]:cS(e)},setCredential(e,t,n){return jC(e,n?.challenge?fS(n.challenge):q.authorization,t)}}}var JC=I((()=>{_S(),Fx(),NC()}));function YC(e){return{encode(t){return k.fromString(JSON.stringify(e.parse(t)))},decode(t){try{return e.parse(JSON.parse(k.toString(t)))}catch{throw new XC}}}}var XC,ZC=I((()=>{XC=class extends Error{name=`InvalidJsonHeaderError`;constructor(){super(`Invalid base64 JSON header.`)}}}));function QC(e){try{let t=JSON.parse(k.toString(e));return iw(t)}catch{throw new XC}}var $C,ew,tw,nw,rw,iw,aw=I((()=>{ZC(),AC(),$C=YC(wC),ew=YC(OC),tw=YC(kC),nw=$C.encode,$C.decode,rw=ew.encode,ew.decode,tw.encode,tw.decode,iw=e=>{if(!e||typeof e!=`object`||Array.isArray(e))throw new XC;let t=e;if(t.x402Version!==2||!Array.isArray(t.accepts))throw new XC;let n=bC.parse(t.resource),r=t.extensions===void 0?void 0:CC.safeParse(t.extensions).data;return{accepts:t.accepts,...r?{extensions:r}:{},resource:n,x402Version:2}}}));function ow(){return{getChallenges(e){if(e.status!==402)return[];let t=e.headers.get(fC);if(!t)return[];let n=QC(t);return n.accepts.flatMap((e,t)=>{let r=xC.safeParse(e);if(!r.success)return[];let i=r.data;return TS(Qx({id:`${dC}${t}`,intent:cC,method:`evm`,realm:new URL(n.resource.url).host,request:{...i,...n.extensions?{extensions:n.extensions}:{},resource:n.resource}}))})},setCredential(e,t){return jC(e,pC,t)}}}var sw=I((()=>{_S(),aw(),OS(),AC(),NC()}));function cw(e){return e}function lw(){let e=[qC(),ow(),UC()],t=new WeakMap,n=(e,n)=>{for(let r of n)t.set(r,e);return n},r=(t,r)=>{let i=(a,o)=>{for(let s=a;s<e.length;s++){let a=e[s],c=a.getChallenges(t,r);if(c instanceof Promise)return c.then(e=>i(s+1,[...o,...n(a,e)]));o.push(...n(a,c))}return o};return i(0,[])};return cw({name:`http`,isPaymentRequired(e,t){if(e.status===402)return!0;let n=r(e,t);return n instanceof Promise?n.then(e=>e.length>0):n.length>0},getChallenges(e,t){return r(e,t)},setCredential(n,r,i){let a=i?.challenge?t.get(i.challenge):void 0,o=e[0];if(!a&&!o)throw Error(`No protocol to attach the credential.`);return(a??o).setCredential(n,r,i)}})}var uw=I((()=>{KC(),JC(),NC(),sw()}));function dw(e,t){return hw.set(e,t),e}function fw(e){return hw.has(e)}function pw(e,t){return Promise.resolve(hw.get(e)?.(t))}function mw(e){return hw.get(e)}var hw,gw=I((()=>{hw=new WeakMap}));function _w(e,t){return ww.set(e,t),e}function vw(e){ww.delete(e)}function yw(e,t,n){ww.has(e)&&Tw.set(t,n)}function bw(e){return Tw.get(e)}function xw(e,t){return Promise.resolve(ww.get(e)?.(t)??t.response)}function Sw(e,t){return Ew.set(e,t),e}function Cw(e,t){try{return Ew.get(e)?.(t)}catch{return}}var ww,Tw,Ew,Dw=I((()=>{ww=new WeakMap,Tw=new WeakMap,Ew=new WeakMap}));async function Ow(e){if(!e.body)return e;let t=e.clone().body.getReader(),n=[],r=0,i=!1,a=setTimeout(()=>{i=!0,t.cancel().catch(()=>{})},hT);try{for(;;){let{done:e,value:a}=await t.read();if(e)break;if(n.push(a),r+=a.byteLength,r>mT){i=!0;break}}}finally{clearTimeout(a),t.cancel().catch(()=>{})}if(!i)return e;e.body.cancel().catch(()=>{});let o=new Headers(e.headers);o.delete(`content-length`),o.set(gT,`true`);let s=new Response(new Blob(n).slice(0,mT),{headers:o,status:e.status,statusText:e.statusText});for(let t of[`redirected`,`type`,`url`])Object.defineProperty(s,t,{value:e[t]});return s}async function kw(e,t){let n=e?.attempt.settle;if(!n)return t.status!==`pending`;e.attempt.settle=void 0;let r=await n(t);return r||(e.attempt.settle=n),r}function Aw(e){let{acceptPayment:t,acceptPaymentPolicy:n=`always`,fetch:r=globalThis.fetch,maxPaymentRetries:i=pT,methods:a,onChallenge:o,orderChallenges:s,transport:c=lw()}=e,l=e.eventDispatcher??Nw(),u=t??AS(a),d=eT(r),f=async(e,t,r)=>{let p=$w(e,t?.headers),m=p.has(q.acceptPayment),h=aT(p,u),g=Zw(e,t,p),_=Xw(e,t,p,h.header,m,n),v=await d(tT(_.input),_.init),y=Qw(_.init,await g);if(!await c.isPaymentRequired(v,y))return v;let b=t?.context,{context:x,orderChallenges:S,...C}=y??{},w,T,ee,E,D;try{for(let n=0;n<i;n++){T=await c.getChallenges(v,y);let i=(await oT(PS(T,a,h.entries),S??s))[0];if(!i){if(await kw(E,{challenges:T,response:v,status:`rejected`}),n>0)return v;throw Error(`No method found for challenges: ${T.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${a.map(e=>`${e.name}.${e.intent}`).join(`, `)}`)}let u=i.challenge;w=u,ee=i.method,w.expires&&CS(w.expires,w.id);let p=dT(v,_.input,_.input),m=E,g=$x(u),x=m?.method===i.method&&m?.key===g,O=!1;if(m){let e=await kw(m,{challenges:T,response:v,status:x?`pending`:`rejected`});O=x&&!e}E=O?m:void 0;let k=Rw(async n=>{if(n===void 0&&O&&m)return m.promise;O&&m&&(await kw(m,{status:`rejected`}),E=void 0);let r=n??b;if(!fw(i.method))return iT(u,i.method,r);let a={prepare:()=>pw(i.method,{challenge:u,context:r,fetch:d,input:p,signal:nT(e,t)})},o=a.prepare().then(()=>iT(u,i.method,r,a));return E={attempt:a,key:n===void 0?g:void 0,method:i.method,promise:o},o}),A=await l.emit(`challenge.received`,zw({challenge:u,challenges:T,createCredential:k,init:t,input:e,method:i.method,response:v}))??(o?await o(w,{createCredential:k}):void 0)??await k(),te=E;te&&await te.promise.catch(()=>void 0)!==A&&(await kw(te,{status:`rejected`}),E=void 0),rT(A),await l.emit(`credential.created`,Bw({challenge:u,credential:A,init:t,input:e,method:i.method,response:v}));let ne=e=>new xS({cause:e,challenge:u,credential:A,transactionHash:Cw(i.method,A)});try{v=await d(p,{...c.setCredential({...C,headers:_.headers},A,{challenge:u}),redirect:`manual`})}catch(e){throw D=ne(e),e}let j=await c.isPaymentRequired(v,y);if(j||(await kw(te,{response:v,status:v.status>=300&&v.status<400?`pending`:v.ok?`accepted`:`rejected`}),E=void 0),v.ok&&Pw(l,`payment.response`)&&await l.emit(`payment.response`,Vw({challenge:u,credential:A,init:t,input:e,method:i.method,response:v})),!j){if(v.status>=500&&Pw(l,`payment.failed`)){try{v=await Ow(v)}catch(e){throw D=ne(e),v=new Response(null,{headers:v.headers,status:v.status,statusText:v.statusText}),e}await l.emit(`payment.failed`,Hw({challenge:u,challenges:T,error:ne(),init:t,input:e,method:i.method,response:v}))}return v.ok?xw(i.method,{challenge:u,credential:A,fetch:d,headers:_.headers,input:p,...r?{refetch:()=>f(tT(_.input),t,!1)}:{},response:v,signal:nT(e,t)}):v}}T=void 0;try{T=await c.getChallenges(v,y)}catch{}return await kw(E,{challenges:T,response:v,status:`rejected`}),v}catch(n){throw await kw(E,{challenges:T,response:v,status:`rejected`}),await l.emit(`payment.failed`,Hw({challenge:w,challenges:T,error:D??n,init:t,input:e,method:ee,response:v})),n}},p=(e,t)=>f(e,t,!0);return p[fT]=d,p}function jw(e){let t=Object.getOwnPropertyDescriptor(globalThis,`fetch`);if(!t||!t.writable&&!t.set)throw Error(`globalThis.fetch is not writable`);_T||=globalThis.fetch,globalThis.fetch=Aw({...e,acceptPaymentPolicy:e.acceptPaymentPolicy??(lT()?`same-origin`:`always`),fetch:globalThis.fetch})}function Mw(e){if(!e)return{};if(e instanceof Headers){let t={};return e.forEach((e,n)=>{t[n]=e}),t}return Array.isArray(e)?Object.fromEntries(e):e}function Nw(){let e={"*":new Set,"challenge.received":new Set,"credential.created":new Set,"payment.failed":new Set,"payment.response":new Set},t={async emit(t,n){switch(t){case`challenge.received`:{let r;for(let t of e[`challenge.received`]){let e=await Fw(t,n);if(typeof e==`string`&&e.length>0){r=e;break}}return await Lw(e[`*`],t,n),r}case`credential.created`:await Iw(e[`credential.created`],n),await Lw(e[`*`],t,n);return;case`payment.failed`:await Iw(e[`payment.failed`],n),await Lw(e[`*`],t,n);return;case`payment.response`:await Iw(e[`payment.response`],n),await Lw(e[`*`],t,n);return}},on:(t,n)=>{switch(t){case`*`:case`challenge.received`:case`credential.created`:case`payment.failed`:case`payment.response`:return e[t].add(n),()=>e[t].delete(n);default:throw Error(`Unknown client event "${String(t)}".`)}}};return vT.set(t,t=>e[t].size>0||e[`*`].size>0),t}function Pw(e,t){return vT.get(e)?.(t)??!0}async function Fw(e,t){try{return await e(t)}catch{return}}async function Iw(e,t){for(let n of e)try{await n(t)}catch{}}async function Lw(e,t,n){await Iw(e,Object.freeze({name:t,payload:n}))}function Rw(e){let t;return n=>(t??=e(n),t)}function zw(e){return Object.freeze({challenge:qw(e.challenge),challenges:e.challenges.map(e=>qw(e)),createCredential:e.createCredential,init:Uw(e.init),input:Ww(e.input),method:Gw(e.method),response:Kw(e.response)})}function Bw(e){return Object.freeze({challenge:qw(e.challenge),credential:e.credential,init:Uw(e.init),input:Ww(e.input),method:Gw(e.method),...e.response===void 0?{}:{response:Kw(e.response)}})}function Vw(e){return Object.freeze({challenge:qw(e.challenge),credential:e.credential,init:Uw(e.init),input:Ww(e.input),method:Gw(e.method),response:Kw(e.response)})}function Hw(e){return Object.freeze({...e.challenge?{challenge:qw(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>qw(e))}:{},error:e.error,init:Uw(e.init),input:Ww(e.input),...e.method?{method:Gw(e.method)}:{},...e.response===void 0?{}:{response:Kw(e.response)}})}function Uw(e){if(e)return Yw({...e,...e.headers?{headers:new Headers(e.headers)}:{}})}function Ww(e){if(e instanceof Request)try{return e.clone()}catch{return e}return e instanceof URL?new URL(e):e}function Gw(e){return Yw(Object.assign({},e))}function Kw(e){return e instanceof Response?e.clone():qw(e)}function qw(e){try{return Jw(structuredClone(e))}catch{return Yw(e)}}function Jw(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))Jw(t);return e}function Yw(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function Xw(e,t,n,r,i,a){let o=!!r&&!i&&sT(e,a);if(!o)return{headers:n,init:t,input:e};let s=new Headers(e instanceof Request?e.headers:void 0);return n.forEach((e,t)=>{s.set(t,e)}),s.set(q.acceptPayment,r),t?(t.headers=s,{headers:s,init:t,input:e}):{headers:s,init:o?{headers:s}:void 0,input:e}}function Zw(e,t,n){if(!(!(e instanceof Request)||t?.body!==void 0||!e.body||e.bodyUsed)){if(!n.has(`mcp-method`)){let e=n.get(`accept`)?.toLowerCase()??``;if(!e.includes(`application/json`)||!e.includes(`text/event-stream`))return}try{return e.clone().text().catch(()=>void 0)}catch{return}}}function Qw(e,t){return t===void 0?e:{...e,body:t}}function $w(e,t){return t?new Headers(t):new Headers(e instanceof Request?e.headers:void 0)}function eT(e){let t=e;for(;t[fT];)t=t[fT];return t}function tT(e){if(!(e instanceof Request)||!e.body||e.bodyUsed)return e;try{return e.clone()}catch{return e}}function nT(e,t){if(t?.signal!==null)return t?.signal===void 0?e instanceof Request?e.signal:void 0:t.signal}function rT(e){if(!e.trim())throw Error(`Credential header value must be non-empty`);if(e.includes(`\r`)||e.includes(`
224
+ `))throw Error(`Credential header value contains illegal newline characters`)}async function iT(e,t,n,r){let i=t.context&&n!==void 0?t.context.parse(n):void 0,a=i===void 0?{challenge:e}:{challenge:e,context:i};return r&&yw(t,a,r),t.createCredential(a)}function aT(e,t){let n=e.get(q.acceptPayment);if(!n)return t;try{return{...t,entries:jS(n),header:n}}catch{return t}}async function oT(e,t){return t?t(e):e}function sT(e,t){if(t===`always`)return!0;if(t===`never`)return!1;let n=uT(e);return t===`same-origin`?!lT()||n.origin===globalThis.location.origin:t.origins.some(e=>cT(n,e))}function cT(e,t){if(t.startsWith(`*.`)){let n=t.slice(1);return e.hostname.endsWith(n)||e.hostname===t.slice(2)}return e.origin===new URL(t).origin}function lT(){return globalThis.location!==void 0}function uT(e){return e instanceof URL?e:e instanceof Request?new URL(e.url):new URL(e,lT()?globalThis.location.href:void 0)}function dT(e,t,n){if(!e.url)return t;let r=new URL(e.url),i=uT(n);if(r.origin!==i.origin)throw Error(`Refusing to send payment credential across redirect from ${i.origin} to ${r.origin}`);return e.url}var fT,pT,mT,hT,gT,_T,vT,yT=I((()=>{_S(),Fx(),SS(),wS(),JS(),uw(),gw(),Dw(),fT=Symbol.for(`mppx.fetch.wrapper`),pT=3,mT=65536,hT=2e3,gT=`Mppx-Body-Truncated`,vT=new WeakMap}));Ox(),yT();function bT(){let e=new Uint8Array(64);return crypto.getRandomValues(e),Object.freeze({created:Math.floor(Date.now()/1e3),nonce:k.fromBytes(e,{pad:!1,url:!0})})}function xT(...e){return{protocol:`composed`,async sign(t,n=bT()){for(let r of e)t=await r.sign(t,n);return t}}}function ST(e,t){return async(n,r)=>e(await t.sign(new Request(n,r)))}Fx(),wS(),JS(),gw(),uw();const CT=new WeakMap;function wT(e){let{attestation:t,maxPaymentRetries:n,onChallenge:r,orderChallenges:i,polyfill:a=!0,acceptPaymentPolicy:o=a&&globalThis.location!==void 0?`same-origin`:`always`,transport:s=lw()}=e,c=eT(e.fetch??globalThis.fetch),l=t?TT(t):void 0,u=l?ST(c,l):c,d=e.methods.flat(),f=AS(d,e.paymentPreferences),p=Nw(),m=r,h={acceptPayment:f,acceptPaymentPolicy:o,...(e.fetch||t)&&{fetch:u},eventDispatcher:p,...n!==void 0&&{maxPaymentRetries:n},...m&&{onChallenge:m},...i&&{orderChallenges:i},methods:d,transport:s},g=Aw(h);a&&jw(h);function _(e){return p.on(`challenge.received`,e)}function v(e){return p.on(`credential.created`,e)}function y(e){return p.on(`payment.failed`,e)}function b(e){return p.on(`payment.response`,e)}async function x(e,t){let n=zT(e),r=await s.getChallenges(e,t?.request),a=Object.freeze(r.map(e=>BT(e))),o=UT(f.entries,t?.acceptPayment),c,l;try{let e=(await WT(PS(r,d,o),t?.orderChallenges??i))[0];if(!e)throw Error(`No method found for challenges: ${r.map(e=>`${e.method}.${e.intent}`).join(`, `)}. Available: ${d.map(e=>`${e.name}.${e.intent}`).join(`, `)}`);let u=e.challenge;c=a[e.index],l=e.method,c.expires&&CS(c.expires,c.id);let f=c,m=l,h=PT(async e=>{try{f.expires&&CS(f.expires,f.id);let t=PT(t=>GT(f,m,t??e)),i=await p.emit(`challenge.received`,FT({challenge:f,challenges:r,createCredential:t,method:m,response:n}))??await t();return rT(i),await p.emit(`credential.created`,IT({challenge:f,credential:i,method:m,response:n})),i}catch(e){throw await p.emit(`payment.failed`,LT({challenge:f,challenges:r,error:e,method:m,response:n})),e}}),g=Object.freeze({challenge:f,challenges:a,createCredential:h,method:RT(m),setCredential(e,t){return rT(t),s.setCredential(e,t,{challenge:u})}});return CT.set(g,m),g}catch(e){throw await p.emit(`payment.failed`,LT({challenge:c,challenges:r,error:e,method:l,response:n})),e}}async function S(e,t,n){let{maxRedirects:r=20,requirePayment:i=!1,...a}=n??{},d=await kT({acceptPayment:f.header,acceptPaymentPolicy:o,fetch:c,init:t,input:e,maxRedirects:r,signer:l}),p=AT(d.replayRequest,d.body);if(!await s.isPaymentRequired(d.response,p)){if(i)throw Error(`Response does not require payment.`);return Object.freeze({payment:void 0,request:d.request,response:d.response,redirects:d.redirects})}let m=await x(d.response,{...a,request:p}),h=CT.get(m)??m.method,g=PT(async e=>(fw(h)&&await pw(h,{challenge:m.challenge,context:e,fetch:u,input:d.replayRequest,signal:d.replayRequest.signal}),m.createCredential(e))),_=Object.freeze({...m,createCredential:g,async pay(e){let t=await g(e),n=m.setCredential(AT(d.replayRequest,d.body),t);return u(d.replayRequest.url,{...n,redirect:`manual`})}});return Object.freeze({payment:_,request:d.request,response:d.response,redirects:d.redirects})}return{fetch:g,rawFetch:c,methods:d,transport:s,on:p.on,onChallengeReceived:_,onCredentialCreated:v,onPaymentFailed:y,onPaymentResponse:b,preparePayment:x,prepareRequest:S,async createCredential(e,t,n){return(await x(e,n)).createCredential(t)}}}function TT(e){let t=Object.values(e);if(t.length===0)throw TypeError(`Mppx client attestation must configure at least one signer.`);return xT(...t)}const ET=new Set([301,302,303,307,308]),DT=[`content-encoding`,`content-language`,`content-length`,`content-location`,`content-type`,`transfer-encoding`],OT=[`authorization`,`cookie`,`cookie2`,`host`,`payment-authorization`,`payment-signature`,`proxy-authorization`,`x-payment`];async function kT(e){let{acceptPayment:t,acceptPaymentPolicy:n,fetch:r,init:i,input:a,maxRedirects:o,signer:s}=e;if(!Number.isInteger(o)||o<0)throw TypeError(`maxRedirects must be a non-negative integer.`);let c=new Request(a,{...i,redirect:`manual`}),l=c.headers.has(q.acceptPayment),u=await jT(c,i?.body),d=[];for(;;){c=MT(c,t,l,n);let e=s?await s.sign(c.clone()):c.clone(),i=await r(e);if(i.type===`opaqueredirect`||i.status===0)throw Error(`prepareRequest requires a runtime that exposes manual redirect responses.`);if(!ET.has(i.status))return{body:u,replayRequest:c,request:e,response:i,redirects:Object.freeze(d)};let a=i.headers.get(`location`);if(!a)return{body:u,replayRequest:c,request:e,response:i,redirects:Object.freeze(d)};if(d.length>=o)throw await i.body?.cancel(),Error(`Payment request exceeded ${o} redirects.`);let f=new URL(c.url),p=new URL(a,f);if(f.protocol===`https:`&&p.protocol!==`https:`)throw await i.body?.cancel(),Error(`Payment request refused HTTPS downgrade redirect to ${p.href}`);let m=new Headers(c.headers),h=c.method;if((i.status===301||i.status===302)&&h===`POST`||i.status===303&&h!==`GET`&&h!==`HEAD`){h=`GET`,u=void 0;for(let e of DT)m.delete(e)}if(f.origin!==p.origin)for(let e of[...m.keys()]){let t=m.get(e)??``;(OT.includes(e)||t.startsWith(`Payment `))&&m.delete(e)}d.push(Object.freeze({from:f.href,status:i.status,to:p.href})),await i.body?.cancel(),c=new Request(p,NT(c,m,h,u))}}function AT(e,t){return NT(e,new Headers(e.headers),e.method,t)}async function jT(e,t){if(typeof t==`string`)return t;if(!e.body)return;let n=e.headers.get(`accept`)?.toLowerCase()??``;return e.headers.has(`mcp-method`)||n.includes(`application/json`)&&n.includes(`text/event-stream`)?e.clone().text():e.clone().arrayBuffer()}function MT(e,t,n,r){if(n)return e;let i=new Headers(e.headers);return i.delete(q.acceptPayment),t&&sT(e,r)&&i.set(q.acceptPayment,t),new Request(e,{headers:i})}function NT(e,t,n,r){return{...r?{body:r}:{},cache:e.cache,credentials:e.credentials,headers:t,integrity:e.integrity,keepalive:e.keepalive,method:n,mode:e.mode,redirect:`manual`,referrer:e.referrer,referrerPolicy:e.referrerPolicy,signal:e.signal}}function PT(e){let t;return n=>(t??=e(n),t)}function FT(e){return Object.freeze({challenge:BT(e.challenge),challenges:e.challenges.map(e=>BT(e)),createCredential:e.createCredential,method:RT(e.method),response:zT(e.response)})}function IT(e){return Object.freeze({challenge:BT(e.challenge),credential:e.credential,method:RT(e.method),response:zT(e.response)})}function LT(e){return Object.freeze({...e.challenge?{challenge:BT(e.challenge)}:{},...e.challenges?{challenges:e.challenges.map(e=>BT(e))}:{},error:e.error,...e.method?{method:RT(e.method)}:{},response:zT(e.response)})}function RT(e){return HT(Object.assign({},e))}function zT(e){return e instanceof Response?e.body===null?e.clone():new Response(null,{headers:e.headers,status:e.status,statusText:e.statusText}):BT(e)}function BT(e){try{let t=structuredClone(e);if(e&&t&&typeof e==`object`&&typeof t==`object`)for(let n of Object.getOwnPropertySymbols(e)){let r=Object.getOwnPropertyDescriptor(e,n);r&&Object.defineProperty(t,n,r)}return VT(t)}catch{return HT(e)}}function VT(e){if(!e||typeof e!=`object`||Object.isFrozen(e))return e;Object.freeze(e);for(let t of Object.values(e))VT(t);return e}function HT(e){return!e||typeof e!=`object`||Object.isFrozen(e)||Object.freeze(e),e}function UT(e,t){return t?typeof t==`string`?jS(t):t:e}async function WT(e,t){return t?t(e):e}async function GT(e,t,n){let r=t.context&&n!==void 0?t.context.parse(n):void 0;return t.createCredential(r===void 0?{challenge:e}:{challenge:e,context:r})}function KT(){return J.string().check(J.regex(qT,`Invalid URI or path`))}var qT,JT,YT,XT,ZT,QT,$T,eE,tE,nE=I((()=>{Zx(),qT=/^([a-zA-Z][a-zA-Z\d+.-]*:\/\/\S+|\/\S*)$/,JT=new Set([`amount`,`currency`,`description`,`intent`,`method`]),YT=J.looseObject({amount:J.optional(J.union([J.null(),J.string().check(J.regex(/^(0|[1-9][0-9]*)$/,`Invalid amount`))])),currency:J.optional(J.string()),description:J.optional(J.string()),intent:J.optional(J.string()),method:J.optional(J.string())}),XT=J.pipe(J.looseObject({amount:J.optional(J.union([J.null(),J.string().check(J.regex(/^(0|[1-9][0-9]*)$/,`Invalid amount`))])),currency:J.optional(J.string()),description:J.optional(J.string()),intent:J.optional(J.string()),method:J.optional(J.string()),offers:J.optional(J.array(YT).check(J.minLength(1)))}).check(J.refine(e=>e.offers===void 0||Object.keys(e).every(e=>e===`offers`||!JT.has(e)),`Cannot mix offers with flat payment info fields`)),J.transform(e=>{if(e.offers)return{offers:e.offers};let t={};for(let[n,r]of Object.entries(e))n!==`offers`&&(JT.has(n)||r!==void 0)&&(t[n]=r);return{offers:[t]}})),ZT=J.looseObject({apiReference:J.optional(KT()),homepage:J.optional(KT()),llms:J.optional(KT())}),QT=J.looseObject({categories:J.optional(J.array(J.string())),docs:J.optional(ZT)}),$T=J.looseObject({"x-payment-info":J.optional(XT),requestBody:J.optional(J.unknown()),responses:J.optional(J.record(J.string(),J.unknown())),summary:J.optional(J.string())}),eE=J.looseObject({delete:J.optional($T),get:J.optional($T),head:J.optional($T),options:J.optional($T),patch:J.optional($T),post:J.optional($T),put:J.optional($T),trace:J.optional($T)}),tE=J.looseObject({openapi:J.string(),info:J.looseObject({title:J.string(),version:J.string()}),"x-service-info":J.optional(QT),paths:J.optional(J.record(J.string(),eE))})}));nE();function rE(e){let t=[],n=tE.safeParse(e);if(!n.success){for(let e of n.error.issues)t.push({message:e.message,path:e.path.map(String).join(`.`)||`(root)`,severity:`error`});return t}let r=n.data.paths;if(!r)return t;for(let[e,n]of Object.entries(r))for(let[r,i]of Object.entries(n)){if(!i||typeof i!=`object`||Array.isArray(i))continue;let n=i,a=`paths.${e}.${r}`,o=n[`x-payment-info`];if(!o)continue;let s=XT.safeParse(o);if(!s.success){for(let e of s.error.issues){let n=e.path.length>0?`.${e.path.map(String).join(`.`)}`:``;t.push({message:e.message,path:`${a}.x-payment-info${n}`,severity:`error`})}continue}let c=n.responses;(!c||!(`402`in c))&&t.push({message:`Operation with x-payment-info MUST have a 402 response`,path:`${a}.responses`,severity:`error`});let l=r.toUpperCase();!n.requestBody&&(l===`POST`||l===`PUT`||l===`PATCH`)&&t.push({message:`Operation with x-payment-info has no requestBody`,path:a,severity:`warning`})}return t}function iE(e){return e}function aE(e,t){let{canHandleChallenge:n,context:r,createCredential:i}=t;return{...e,canHandleChallenge:n,context:r,createCredential:i}}var oE=I((()=>{}));function sE(e){return J.refine(e=>{let{amount:t,decimals:n}=e;return P(t,n)>0n},e)}function cE(e){let{periodCount:t,periodUnit:n}=e;try{let e=fE[n];return e!==void 0&&BigInt(t)*e<=dE}catch{return!1}}var lE,uE,dE,fE,pE,mE,hE,gE,_E,vE,yE,bE,xE,SE=I((()=>{Fx(),oE(),Zx(),lE=[`push`,`pull`],uE=J.object({amount:Vx(),memo:J.optional(qx()),recipient:J.pipe(J.string(),J.transform(e=>e))}),dE=(1n<<64n)-1n,fE={dev_second:1n,day:86400n,week:604800n},pE=J.pipe(Kx(),J.transform(e=>e.toLowerCase())),mE=J.object({accessKeyAddress:pE,keyType:J.enum([`p256`,`secp256k1`,`webAuthn`])}),hE=J.object({accessKey:J.optional(mE),chainId:J.optional(J.number())}),gE=Ux(`subscriptionExpires must be a valid date`).check(J.refine(e=>e.getTime()%1e3==0,`subscriptionExpires must be representable as whole seconds`)),_E=J.enum([`dev_second`,`day`,`week`]),vE=J.pipe(J.union([J.string(),J.bigint(),J.custom(e=>typeof e==`number`&&Number.isSafeInteger(e))]),J.transform(e=>e.toString())).check(J.regex(/^[1-9]\d*$/,`Invalid periodCount`),J.refine(e=>{try{return BigInt(e)<=dE}catch{return!1}},`periodCount exceeds uint64`)),yE=iE({name:`tempo`,intent:`charge`,schema:{credential:{payload:J.discriminatedUnion(`type`,[J.object({hash:qx(),type:J.literal(`hash`)}),J.object({signature:Yx(),type:J.literal(`transaction`)}),J.object({signature:Yx(),type:J.literal(`proof`)})])},request:J.pipe(J.object({machineTokenEnabled:J.optional(J.boolean()),amount:Vx(),chainId:J.optional(J.number()),currency:J.string(),decimals:J.number(),description:J.optional(J.string()),externalId:J.optional(J.string()),feePayer:J.optional(J.pipe(J.union([J.boolean(),J.custom()]),J.transform(e=>typeof e==`object`||e))),memo:J.optional(J.never()),recipient:J.optional(J.string()),splits:J.optional(J.array(uE).check(J.minLength(1),J.maxLength(10))),supportedModes:J.optional(J.array(J.enum(lE)).check(J.minLength(1)))}).check(J.refine(({amount:e,decimals:t,splits:n})=>{if(!n)return!0;let r=P(e,t),i=n.reduce((e,n)=>e+P(n.amount,t),0n);return n.every(e=>P(e.amount,t)>0n)&&i<r},`Invalid splits`)),J.transform(({machineTokenEnabled:e,amount:t,chainId:n,decimals:r,feePayer:i,memo:a,splits:o,supportedModes:s,...c})=>({...c,amount:P(t,r).toString(),...e!==void 0||n!==void 0||i!==void 0||o!==void 0||s!==void 0?{methodDetails:{...e!==void 0&&{machineTokenEnabled:e},...n!==void 0&&{chainId:n},...i!==void 0&&{feePayer:i},...o!==void 0&&{splits:o.map(e=>({...e,amount:P(e.amount,r).toString()}))},...s!==void 0&&{supportedModes:s}}}:{}})))}}),bE=iE({name:`tempo`,intent:`session`,schema:{credential:{payload:J.discriminatedUnion(`action`,[J.object({action:J.literal(`open`),authorizedSigner:J.optional(J.string()),channelId:qx(),cumulativeAmount:Vx(),descriptor:J.optional(J.custom()),signature:Yx(),transaction:Yx(),type:J.literal(`transaction`)}),J.object({action:J.literal(`topUp`),additionalDeposit:Vx(),channelId:qx(),descriptor:J.optional(J.custom()),transaction:Yx(),type:J.literal(`transaction`)}),J.object({action:J.literal(`voucher`),channelId:qx(),cumulativeAmount:Vx(),descriptor:J.optional(J.custom()),signature:Yx()}),J.object({action:J.literal(`close`),channelId:qx(),closeSignature:Yx(),cumulativeAmount:Vx(),descriptor:J.optional(J.custom()),signature:Yx()})])},request:J.pipe(J.object({amount:Vx(),chainId:J.optional(J.number()),channelId:J.optional(qx()),currency:J.string(),decimals:J.number(),escrowContract:J.optional(J.string()),feePayer:J.optional(J.pipe(J.union([J.boolean(),J.custom()]),J.transform(e=>typeof e==`object`||e))),feeToken:J.optional(Kx()),minVoucherDelta:J.optional(Vx()),operator:J.optional(Kx()),recipient:J.optional(J.string()),sessionProtocol:J.optional(J.enum([Px.v2,Px.v1])),sessionSnapshot:J.optional(J.custom()),suggestedDeposit:J.optional(Vx()),unitType:J.string()}).check(J.refine(({amount:e,decimals:t})=>P(e,t)>0n,`Session amount must be greater than 0`)),J.transform(({amount:e,chainId:t,channelId:n,decimals:r,escrowContract:i,feePayer:a,feeToken:o,minVoucherDelta:s,operator:c,sessionProtocol:l,sessionSnapshot:u,suggestedDeposit:d,...f})=>({...f,amount:P(e,r).toString(),...d?{suggestedDeposit:P(d,r).toString()}:{},methodDetails:{escrowContract:i,...n!==void 0&&{channelId:n},...s!==void 0&&{minVoucherDelta:P(s,r).toString()},...t!==void 0&&{chainId:t},...a!==void 0&&{feePayer:a},...o!==void 0&&{feeToken:o},...c!==void 0&&{operator:c},...l!==void 0&&{[Nx.sessionProtocol]:l},...u!==void 0&&{[Nx.sessionSnapshot]:u}}})))}}),xE=iE({name:`tempo`,intent:`subscription`,schema:{credential:{payload:J.object({signature:Yx(),type:J.literal(`keyAuthorization`)})},request:J.pipe(J.object({amount:Vx(),accessKey:J.optional(mE),chainId:J.optional(J.number()),currency:pE,decimals:J.number(),description:J.optional(J.string()),externalId:J.optional(J.string()),methodDetails:J.optional(hE),periodCount:vE,periodUnit:_E,recipient:pE,subscriptionExpires:gE}).check(sE(`Subscription amount must be greater than 0`),J.refine(cE,`Subscription period exceeds uint64`)),J.transform(({accessKey:e,amount:t,chainId:n,decimals:r,methodDetails:i,subscriptionExpires:a,...o})=>{let s={...i,...e!==void 0&&{accessKey:e},...n!==void 0&&{chainId:n}};return{...o,amount:P(t,r).toString(),subscriptionExpires:a.toISOString(),...Object.keys(s).length>0?{methodDetails:s}:{}}}))}})}));function CE(e){return e>=0n&&e<=HE}function wE(e){if(!/^\d{1,29}$/.test(e))return;let t=BigInt(e);return CE(t)?t:void 0}function TE(e){return EE(e),e}function EE(e){if(!CE(e))throw Error(`Value ${e} is outside uint96 bounds.`)}function DE(e){return typeof e==`object`&&!!e}function OE(e){return typeof e==`string`&&UE.has(e)}function kE(e){if(typeof e!=`object`||!e)return!1;let t=e;return!(typeof t.channelId!=`string`||t.action!==void 0&&!OE(t.action))}function AE(e,t=`No session credential context available.`){if(!kE(e))throw Error(t);return e}function jE(e){let t=e.request.amount;if(typeof t!=`string`)throw Error(`Session challenge is missing amount.`);return BigInt(t)}function ME(e){return DE(e)?typeof e.channelId==`string`&&typeof e.requiredCumulative==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.deposit==`string`:!1}function NE(e){return DE(e)?e.method===`tempo`&&e.intent===`session`&&e.status===`success`&&typeof e.timestamp==`string`&&typeof e.reference==`string`&&typeof e.challengeId==`string`&&typeof e.channelId==`string`&&typeof e.acceptedCumulative==`string`&&typeof e.spent==`string`&&(e.units===void 0||typeof e.units==`number`)&&(e.txHash===void 0||typeof e.txHash==`string`):!1}function PE(e){let t=k.toString(e),n=JSON.parse(t);if(!NE(n))throw Error(`Invalid session receipt.`);return n}function FE(e){return e.headers.get(`content-type`)?.toLowerCase().startsWith(`text/event-stream`)??!1}function IE(e){let t=`message`,n=[];for(let r of e.split(`
225
225
  `))r.startsWith(`event: `)?t=r.slice(7).trim():r.startsWith(`data: `)?n.push(r.slice(6)):r===`data:`&&n.push(``);if(n.length===0)return null;let r=n.join(`
226
- `);switch(t){case`message`:return{type:`message`,data:r};case`payment-need-voucher`:{let e=FE(r);return AE(e)?{type:`payment-need-voucher`,data:e}:null}case`payment-receipt`:{let e=FE(r);return jE(e)?{type:`payment-receipt`,data:e}:null}default:return{type:`message`,data:r}}}function FE(e){try{return JSON.parse(e)}catch{return null}}function IE(e){return JSON.stringify({mpp:`authorization`,authorization:e})}function LE(){return JSON.stringify({mpp:`payment-close-request`})}function RE(e){let t=zE(e);return t?t.mpp===`authorization`&&typeof t.authorization==`string`?{mpp:`authorization`,authorization:t.authorization}:t.mpp===`message`&&typeof t.data==`string`?{mpp:`message`,data:t.data}:t.mpp===`payment-close-request`?{mpp:`payment-close-request`}:t.mpp===`payment-close-ready`&&jE(t.data)?{mpp:`payment-close-ready`,data:t.data}:t.mpp===`payment-error`&&typeof t.status==`number`&&typeof t.message==`string`?{mpp:`payment-error`,status:t.status,message:t.message}:t.mpp===`payment-need-voucher`&&AE(t.data)?{mpp:`payment-need-voucher`,data:t.data}:t.mpp===`payment-receipt`&&jE(t.data)?{mpp:`payment-receipt`,data:t.data}:null:null}function zE(e){try{let t=JSON.parse(e);return typeof t!=`object`||!t?null:t}catch{return null}}var BE,VE,HE,UE=F((()=>{BE=(1n<<96n)-1n,VE=new Set([`open`,`topUp`,`voucher`,`close`]),HE=`0x4d50500000000000000000000000000000000000`}));function WE(e){return ZE.encode(e)}function GE(e){return ZE.decode(e)}var KE,qE,JE,YE,XE,ZE,QE=F((()=>{XC(),Zx(),KE=J.custom(e=>typeof e==`string`&&de(e,{strict:!1})),qE=J.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),JE=J.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]+$/.test(e)),YE=J.object({authorizedSigner:KE,expiringNonceHash:qE,operator:KE,payee:KE,payer:KE,salt:qE,token:KE}),XE=J.object({acceptedCumulative:J.string(),chainId:J.number(),channelId:qE,closeRequestedAt:J.optional(J.string()),deposit:J.string(),descriptor:YE,escrow:KE,highestVoucher:J.optional(J.object({channelId:qE,cumulativeAmount:J.string(),signature:JE})),requiredCumulative:J.string(),settled:J.string(),spent:J.string(),units:J.optional(J.number())}),ZE=JC(XE)}));function $E(e){return{status:`active`,...e}}function eD(e,t){switch(t.type){case`challengeReceived`:return e.status===`closing`||e.status===`closed`?aD(e,t):{state:{status:`challenged`,challengeId:t.challengeId},effects:[]};case`challenge`:return e.status!==`idle`&&e.status!==`active`?aD(e,t):t.snapshot?{state:{status:`hydrating`,challengeId:t.challengeId,snapshot:t.snapshot},effects:[{type:`hydrate`,snapshot:t.snapshot}]}:{state:{status:`opening`,challengeId:t.challengeId},effects:[{type:`open`}]};case`hydrated`:return e.status===`hydrating`?{state:rD(e.challengeId,t.snapshot),effects:[]}:aD(e,t);case`activated`:return e.status===`closing`||e.status===`closed`?aD(e,t):{state:_D({challengeId:t.challengeId,entry:t.entry,spent:t.spent,units:t.units??0}),effects:[]};case`opened`:return e.status===`opening`?{state:iD(e.challengeId,t.receipt,t.descriptor,t.deposit),effects:[]}:aD(e,t);case`receiptAccepted`:return e.status===`closing`||e.status===`closed`?aD(e,t):{state:bD(t.receipt,t.entry),effects:[]};case`needVoucher`:return e.status===`active`?nD({challengeId:e.challengeId,descriptor:t.descriptor,event:t.event}):aD(e,t);case`topUpStarted`:return e.status===`voucherNeeded`?{state:{status:`toppingUp`,challengeId:e.challengeId,channelId:e.channelId,descriptor:e.descriptor,deposit:e.deposit},effects:[]}:aD(e,t);case`voucherAccepted`:return e.status!==`voucherNeeded`&&e.status!==`toppingUp`?aD(e,t):{state:iD(e.challengeId,t.receipt,e.descriptor,t.deposit??e.deposit),effects:[]};case`settleStarted`:return e.status===`active`?{state:{status:`settling`,channelId:e.channelId,descriptor:e.descriptor,deposit:e.deposit},effects:[{type:`settle`,channelId:e.channelId}]}:aD(e,t);case`settled`:return e.status===`settling`?{state:iD(t.receipt.challengeId,t.receipt,e.descriptor,t.deposit??e.deposit),effects:[]}:aD(e,t);case`closeRequested`:return e.status===`active`?{state:{status:`closeRequested`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`requestClose`,channelId:e.channelId}]}:aD(e,t);case`withdrawable`:return e.status===`closeRequested`?{state:{status:`withdrawable`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`withdraw`,channelId:e.channelId}]}:aD(e,t);case`closeStarted`:return e.status!==`active`&&e.status!==`withdrawable`&&e.status!==`closeRequested`?aD(e,t):{state:{status:`closing`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`close`,channelId:e.channelId}]};case`closed`:return e.status!==`closing`&&e.status!==`withdrawable`?aD(e,t):{state:{status:`closed`,channelId:e.channelId,descriptor:e.descriptor},effects:[]}}}function tD(e,t){let n=eD(e.state,t);return e.state=n.state,n}function nD(e){let{challengeId:t,descriptor:n,event:r}=e,i=BigInt(r.requiredCumulative),a=BigInt(r.deposit);return i>a?{state:{status:`toppingUp`,challengeId:t,channelId:r.channelId,descriptor:n,deposit:r.deposit},effects:[{type:`topUp`,channelId:r.channelId,amount:(i-a).toString()}]}:{state:{status:`voucherNeeded`,challengeId:t,channelId:r.channelId,descriptor:n,requiredCumulative:r.requiredCumulative,deposit:r.deposit},effects:[{type:`voucher`}]}}function rD(e,t){return $E({challengeId:e,channelId:t.channelId,descriptor:t.descriptor,acceptedCumulative:t.acceptedCumulative,deposit:t.deposit,spent:t.spent,units:t.units??0})}function iD(e,t,n,r){return $E({challengeId:e,channelId:t.channelId,descriptor:n,acceptedCumulative:t.acceptedCumulative,deposit:r,spent:t.spent,units:t.units??0})}function aD(e,t){throw Error(`Invalid session transition: ${e.status} + ${t.type}`)}function oD(e){let{cumulativeAmount:t,maxVoucherCumulative:n}=e;if(n!==null&&!(t<=n))throw Error(`requested voucher amount ${t} exceeds local maxDeposit ${n}`)}function sD(e){let{channel:t,maxVoucherCumulative:n,receipt:r}=e;if(!t||r.channelId!==t.channelId)return;let i=BigInt(r.acceptedCumulative),a=BigInt(r.spent);if(a>i)throw Error(`receipt spent exceeds accepted cumulative voucher amount`);if(i>t.cumulativeAmount)throw Error(`receipt accepted cumulative exceeds local voucher state`);if(a>t.cumulativeAmount)throw Error(`receipt spent exceeds local voucher state`);oD({cumulativeAmount:i,maxVoucherCumulative:n}),oD({cumulativeAmount:a,maxVoucherCumulative:n})}function cD(e){let{channel:t,maxVoucherCumulative:n,receipt:r,spent:i}=e;if(!r||r.channelId!==t?.channelId)return i;sD({channel:t,maxVoucherCumulative:n,receipt:r});let a=BigInt(r.spent);return i>a?i:a}function lD(e,t){return typeof e==`bigint`?e:N(e,t)}function uD(e){let{contextDepositRaw:t,maxDeposit:n,requestAmount:r,suggestedDepositRaw:i}=e;if(fD(r,n),t!==void 0){let e=BigInt(t);if(e<r)throw Error(`opening deposit ${e} below request amount ${r}`);return e}let a=i===void 0?void 0:BigInt(i),o=a!==void 0&&a>r?a:r;return n===void 0||o<n?o:n}function dD(e){let{deposit:t,maxDeposit:n,requiredCumulative:r,suggestedDeposit:i,topUpAmount:a}=e;if(r<=t)return 0n;oD({cumulativeAmount:r,maxVoucherCumulative:n??null});let o=r-t,s=a??i??o,c=s>o?s:o;if(n==null)return c;let l=n-t;return c<l?c:l}function fD(e,t){oD({cumulativeAmount:e,maxVoucherCumulative:t??null})}function pD(e){let{channel:t,currentSocket:n,lastChallenge:r}=e;if(!t?.opened)return;let i=n?.challenge??r,a=n?.channelId??t.channelId;if(!i)throw Error(`Cannot close session: no challenge available. This usually means close() was called on a SessionManager instance that was recreated after the session was opened. Use the same SessionManager instance that opened the session, or make a request first to receive a fresh 402 challenge.`);if(!a)throw Error(`Cannot close session: no channel ID available. The session may not have been fully opened.`);return{challenge:i,channel:t,channelId:a}}function mD(e){let{cumulativeAmount:t,spent:n}=e;return t>n?t:n}function hD(e){let{cumulativeAmount:t,readySpent:n,spent:r}=e;if(!xE(n))throw Error(`close-ready spent is not a uint96 amount`);if(n<r)throw Error(`close-ready spent is below locally confirmed spend`);if(n>mD({cumulativeAmount:t,spent:r}))throw Error(`close-ready spent exceeds local voucher state`)}function gD(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:i=0n,receipt:a}=e,o=SE(r),s=SE(a.spent);return o===void 0||s===void 0||!xE(i)?!1:!!a.txHash&&a.challengeId===t&&a.channelId===n&&a.acceptedCumulative===r&&s>=i&&s<=o}function _D(e){return $E({challengeId:e.challengeId,channelId:e.entry.channelId,descriptor:e.entry.descriptor,acceptedCumulative:e.entry.cumulativeAmount.toString(),deposit:e.entry.deposit.toString(),spent:e.spent,units:e.units})}function vD(){return{channel:null,lastChallenge:null,lastUrl:null,spent:0n,socketSession:null,state:ED}}function yD(e){let{maxVoucherCumulative:t,receipt:n,runtime:r}=e;r.spent=cD({channel:r.channel,maxVoucherCumulative:t,receipt:n,spent:r.spent}),n&&r.channel?.channelId===n.channelId&&tD(r,{type:`receiptAccepted`,receipt:n,entry:r.channel})}function bD(e,t){return $E({challengeId:e.challengeId,channelId:e.channelId,descriptor:t.descriptor,acceptedCumulative:e.acceptedCumulative,deposit:t.deposit.toString(),spent:e.spent,units:e.units??0})}function xD(e){let{challengeId:t,channelId:n,closeReadyReceipt:r,cumulativeAmount:i,deliveredChunks:a=0n,socketChallengeId:o,socketChannelId:s,spent:c,tickCost:l=0n}=e;if(c>i)throw Error(`locally confirmed spend exceeds local voucher state`);if(r&&r.challengeId===t&&r.channelId===n){let e=SE(r.spent);if(e===void 0)throw Error(`close-ready spent is not a uint96 amount`);return e>c?e:c}if(o===t&&s===n&&l>0n){let e=a*l,t=c>e?c:e;return t>i?i:t}return i}function SD(e){let{channel:t,channelId:n,challengeId:r,cumulativeAmount:i,spent:a,state:o}=e;if(!(!t||t.channelId!==n)&&(t.cumulativeAmount=i,r))return eD(o,{type:`activated`,challengeId:r,entry:t,spent:a.toString(),units:o.status===`active`?o.units:0}).state}function CD(e){return{channel:e.channel===null?null:{entry:e.channel,cumulativeAmount:e.channel.cumulativeAmount,deposit:e.channel.deposit,opened:e.channel.opened},spent:e.spent,state:e.state}}function wD(e,t){return e.channel?(e.channel.entry.cumulativeAmount=e.channel.cumulativeAmount,e.channel.entry.deposit=e.channel.deposit,e.channel.entry.opened=e.channel.opened,{channel:e.channel.entry,spent:e.spent,state:e.state}):(t&&(t.opened=!1),{channel:null,spent:e.spent,state:e.state})}async function TD(e){let{activeSocket:t,currentSocket:n,target:r}=e,i=n.closeReadyReceipt??await(async()=>(t.send(LE()),e.waitForCloseReady()))(),a=BigInt(i.spent);hD({cumulativeAmount:r.channel.cumulativeAmount,readySpent:a,spent:e.spent});let o=await e.createSessionCredential(r.challenge,{action:`close`,channelId:r.channelId,descriptor:r.channel.descriptor,cumulativeAmountRaw:a.toString()}),s=a.toString();n.expectedCloseAmount=s;try{let i=e.waitForReceipt(e=>gD({challengeId:r.challenge.id,channelId:r.channelId,expectedCloseAmount:s,minimumSpent:a,receipt:e}));t.send(IE(o));let c=await i;return t.close(),n.closeReadyReceipt=null,c}finally{n.expectedCloseAmount=null}}var ED,DD=F((()=>{UE(),QE(),ED={status:`idle`}}));function OD(e){let t=new Map,n=!1,r=[],i=e.readyState,a=(e,n,i)=>{let a=t.get(e);if(a||(a=new Set,t.set(e,a)),a.add({once:typeof i==`object`&&i.once===!0,value:n}),e===`message`&&r){let e=r;r=null;for(let t of e)s(`message`,t)}},o=(e,n)=>{let r=t.get(e);if(r)for(let e of r)e.value===n&&r.delete(e)};function s(e,a){if(a.type===`close`){if(n)return;n=!0,i=dO.CLOSED,r=null}if(a.type===`open`&&(i=dO.OPEN),a.type===`message`&&r){r.push(a);return}switch(a.type){case`close`:l.onclose?.(a);break;case`error`:l.onerror?.(a);break;case`message`:l.onmessage?.(a);break;case`open`:l.onopen?.(a)}let o=t.get(e);if(o)for(let e of Array.from(o))typeof e.value==`function`?e.value(a):e.value.handleEvent(a),e.once&&o.delete(e)}let c=null,l={addEventListener:a,close(t,n){e.close(t,n)},get bufferedAmount(){return e.bufferedAmount},get extensions(){return e.extensions},on(e,t){a(e,t)},onclose:null,onerror:null,get onmessage(){return c},set onmessage(e){if(c=e,e&&r){let e=r;r=null;for(let t of e)s(`message`,t)}},onopen:null,off(e,t){o(e,t)},get protocol(){return e.protocol},get readyState(){return i},removeEventListener:o,send(t){e.send(t)},get url(){return e.url}};return{emit:s,socket:l}}function kD(e){return{acceptedCumulative:BigInt(e.acceptedCumulative),deposit:BigInt(e.deposit),requiredCumulative:BigInt(e.requiredCumulative)}}function AD(e){let{amount:t,assertVoucherWithinLocalLimit:n,channel:r,decimals:i,lastChallenge:a,lastUrl:o}=e;if(!r?.opened)throw Error(`Cannot top up session: no open channel.`);if(!a)throw Error(`Cannot top up session: no challenge available. Make a request first.`);if(!o)throw Error(`Cannot top up session: no URL available. Call fetch(), sse(), or ws() first.`);let s=lD(t,i);if(s<=0n)throw Error(`Top-up amount must be greater than zero.`);return n(r.cumulativeAmount+s),{additionalDeposit:s,challenge:a,channelId:r.channelId,input:o}}function jD(e){let{additionalDeposit:t,channel:n,channelId:r,challengeId:i,currentState:a,knownDeposit:o,receipt:s,spent:c}=e;if(n?.channelId!==r)return;let l=o!==void 0&&o>n.deposit?o:n.deposit,u={...n,deposit:l+t};return s?{channel:u,state:bD(s,u)}:i?{channel:u,state:_D({challengeId:i,entry:u,spent:c.toString(),units:a.status===`active`?a.units:0})}:{channel:u}}async function MD(e){if(e.event.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`channel-mismatch`};let t=kD(e.event);e.assertVoucherWithinLocalLimit(t.requiredCumulative),await e.topUpIfNeeded({challenge:e.challenge,input:e.input,channelId:e.expectedChannelId,deposit:t.deposit,requiredCumulative:t.requiredCumulative,...e.signal?{signal:e.signal}:{}});let n=e.getChannel();if(!n||n.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`missing-channel`};let r=n.cumulativeAmount>t.requiredCumulative?n.cumulativeAmount:CE(t.requiredCumulative);return{status:`ready`,context:{action:`voucher`,channelId:e.expectedChannelId,descriptor:n.descriptor,cumulativeAmountRaw:r.toString()}}}function ND(e){return e.method===jx.tempo&&e.intent===Mx.session}function PD(e){return ND(e)&&kx(e.request.methodDetails,Nx.sessionProtocol)===Px.v2}function FD(e){return kx(e.request.methodDetails,Nx.sessionSnapshot)}function ID(e,t,n){let r=e instanceof Request?e.headers:void 0;return{...t,headers:{...Aw(r),...Aw(t?.headers),[q.authorization]:n}}}function LD(e){try{let t=typeof location>`u`?void 0:location.href,n=e instanceof Request?new URL(e.url):e instanceof URL?new URL(e):new URL(String(e),t);return n.hash=``,n}catch{return e}}function RD(e){let t=new URL(e.toString());return t.protocol===`ws:`&&(t.protocol=`http:`),t.protocol===`wss:`&&(t.protocol=`https:`),t}async function zD(e){let t=await e.text().catch(()=>``);if(!t)return``;if(!e.headers.get(`Content-Type`)?.includes(`application/problem+json`))return t;try{return JSON.parse(t).detail??t}catch{return t}}async function BD(e){let{channel:t,channelId:n}=e;if(!t?.descriptor||t.channelId!==n)throw Error(`Cannot top up session: no local channel descriptor available.`);let r=await VD({challenge:e.challenge,context:{action:`topUp`,channelId:n,descriptor:t.descriptor,additionalDepositRaw:e.additionalDeposit.toString()},createSessionCredential:e.createSessionCredential,fetch:e.fetch,input:e.input,signal:e.signal});if(!r.ok)throw Error(`Top-up POST failed with status ${r.status}`);let i=r.headers.get(q.paymentReceipt);return i?ME(i):void 0}async function VD(e){let t=async t=>e.fetch(LD(e.input),{method:`POST`,...e.signal?{signal:e.signal}:{},headers:{[q.authorization]:await e.createSessionCredential(t,e.context)}}),n=await t(e.challenge);if(n.status!==402)return n;let r=cS(n).find(PD);return r?t(r):n}async function HD(e){let t=UD({channel:e.getChannel(),response:e.response});if(!t)return;let{channel:n,challenge:r,snapshot:i}=t;e.setChallenge(r);let a=BigInt(i.requiredCumulative),o=n.cumulativeAmount;await e.topUpIfNeeded({challenge:r,input:e.input,channelId:i.channelId,deposit:BigInt(i.deposit),requiredCumulative:a,signal:e.init?.signal??(e.input instanceof Request?e.input.signal:void 0)});let s=e.getChannel();if(!s?.descriptor||s.channelId!==i.channelId)return;let c=s.cumulativeAmount>a?s.cumulativeAmount:a,l=()=>e.restoreCumulative(i.channelId,o),u;try{let t=await e.createSessionCredential(r,{action:`voucher`,channelId:i.channelId,descriptor:s.descriptor,cumulativeAmountRaw:c.toString()});u=await e.fetch(e.input,ID(e.input,e.init,t))}catch(e){throw await l(),e}return!u.ok&&!u.headers.get(q.paymentReceipt)&&await l(),u}function UD(e){let t=cS(e.response).find(PD);if(!t)return;let n=FD(t);if(!n)return;let{channel:r}=e;if(!(!r?.descriptor||r.channelId!==n.channelId))return{channel:r,challenge:t,snapshot:n}}async function WD(e){if(!e.lastUrl)throw Error(`Cannot close session: no URL available. This usually means close() was called on a SessionManager instance that was recreated after the session was opened. Use the same SessionManager instance that opened the session, or call fetch()/sse() before close().`);let t=e.target.challenge,n=e.signedCloseAmount,r=async(r,i=!1)=>{t=r,n=(i?e.resolveSignedCloseAmount?.(r):void 0)??e.signedCloseAmount;let a=await e.createSessionCredential(r,{action:`close`,channelId:e.target.channelId,descriptor:e.target.channel.descriptor,cumulativeAmountRaw:n});return e.fetch(e.lastUrl,{method:`POST`,headers:{[q.authorization]:a}})},i=await r(e.target.challenge);if(i.status===402){let t=cS(i).find(PD);t&&(e.setChallenge?.(t),i=await r(t,!0))}if(!i.ok){let e=await zD(i),t=i.headers.get(q.wwwAuthenticate)??``;throw Error(`Close request failed with status ${i.status}${e?`: ${e}`:``}${t?` [${q.wwwAuthenticate}: ${t}]`:``}`)}let a=i.headers.get(q.paymentReceipt);if(!a)return;let o=ME(a);if(!o.txHash||!re.validate(o.txHash,{strict:!0})||re.size(o.txHash)!==32||!gD({challengeId:t.id,channelId:e.target.channelId,expectedCloseAmount:n,minimumSpent:e.getMinimumSpent?.()??0n,receipt:o}))throw Error(`Session close response included a mismatched payment receipt.`);return o}async function GD(e,t,n){let{onReceipt:r,signal:i,...a}=t??{},o=i??(e instanceof Request?e.signal:void 0),s={...a,headers:{...Aw(a.headers),Accept:`text/event-stream`},...o?{signal:o}:{}},c=await n.doFetch(e,s);return!NE(c)&&n.getChannel()?.opened&&(c=await n.doFetch(e,s)),KD(e,c,{onReceipt:r,signal:o},n)}function KD(e,t,n,r){if(!NE(t))throw Error(`SSE response is not an event stream.`);if(!t.body)throw Error(`Response has no body.`);let i=r.getChallenge();return qD({onNeedVoucher:t=>QD({challenge:i,driver:r,input:e,signal:n?.signal},t),onReceipt(e){r.acceptReceipt(e),n?.onReceipt?.(e)},response:t,signal:n?.signal})}async function*qD(e){for await(let t of JD(e))t.data!==void 0&&(yield t.data)}async function*JD(e){if(!e.response.body)throw Error(`Response has no body.`);let t=e.response.body.getReader(),n=new TextDecoder,r=``,i=!1,a=()=>{t.cancel(e.signal?.reason).catch(()=>void 0)};e.signal?.addEventListener(`abort`,a,{once:!0}),e.signal?.aborted&&a();try{for(;!e.signal?.aborted;){let{done:a,value:o}=await t.read();for(a?(i=!0,r+=n.decode()):r+=n.decode(o,{stream:!0});;){let t=YD(r,a);if(!t)break;let n=t.index+t.length,i=r.slice(0,t.index),o=r.slice(0,n);if(r=r.slice(n),!i.trim())continue;let s=PE(i.replace(/\r\n|\r/g,`
227
- `));if(!s){yield{raw:o};continue}switch(s.type){case`message`:yield{data:s.data,raw:o};break;case`payment-need-voucher`:await e.onNeedVoucher(s.data,e.signal);break;case`payment-receipt`:e.onReceipt(s.data)}}if(a)break}}finally{e.signal?.removeEventListener(`abort`,a),i||await t.cancel().catch(()=>void 0),t.releaseLock()}}function YD(e,t){for(let n=0;n<e.length;n++){let r=XD(e,n,t);if(!r)continue;let i=XD(e,n+r,t);if(i)return{index:n,length:r+i};n+=r-1}}function XD(e,t,n){return e[t]===`
226
+ `);switch(t){case`message`:return{type:`message`,data:r};case`payment-need-voucher`:{let e=LE(r);return ME(e)?{type:`payment-need-voucher`,data:e}:null}case`payment-receipt`:{let e=LE(r);return NE(e)?{type:`payment-receipt`,data:e}:null}default:return{type:`message`,data:r}}}function LE(e){try{return JSON.parse(e)}catch{return null}}function RE(e){return JSON.stringify({mpp:`authorization`,authorization:e})}function zE(){return JSON.stringify({mpp:`payment-close-request`})}function BE(e){let t=VE(e);return t?t.mpp===`authorization`&&typeof t.authorization==`string`?{mpp:`authorization`,authorization:t.authorization}:t.mpp===`message`&&typeof t.data==`string`?{mpp:`message`,data:t.data}:t.mpp===`payment-close-request`?{mpp:`payment-close-request`}:t.mpp===`payment-close-ready`&&NE(t.data)?{mpp:`payment-close-ready`,data:t.data}:t.mpp===`payment-error`&&typeof t.status==`number`&&typeof t.message==`string`?{mpp:`payment-error`,status:t.status,message:t.message}:t.mpp===`payment-need-voucher`&&ME(t.data)?{mpp:`payment-need-voucher`,data:t.data}:t.mpp===`payment-receipt`&&NE(t.data)?{mpp:`payment-receipt`,data:t.data}:null:null}function VE(e){try{let t=JSON.parse(e);return typeof t!=`object`||!t?null:t}catch{return null}}var HE,UE,WE,GE=I((()=>{HE=(1n<<96n)-1n,UE=new Set([`open`,`topUp`,`voucher`,`close`]),WE=`0x4d50500000000000000000000000000000000000`}));function KE(e){return $E.encode(e)}function qE(e){return $E.decode(e)}var JE,YE,XE,ZE,QE,$E,eD=I((()=>{ZC(),Zx(),JE=J.custom(e=>typeof e==`string`&&ue(e,{strict:!1})),YE=J.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),XE=J.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]+$/.test(e)),ZE=J.object({authorizedSigner:JE,expiringNonceHash:YE,operator:JE,payee:JE,payer:JE,salt:YE,token:JE}),QE=J.object({acceptedCumulative:J.string(),chainId:J.number(),channelId:YE,closeRequestedAt:J.optional(J.string()),deposit:J.string(),descriptor:ZE,escrow:JE,highestVoucher:J.optional(J.object({channelId:YE,cumulativeAmount:J.string(),signature:XE})),requiredCumulative:J.string(),settled:J.string(),spent:J.string(),units:J.optional(J.number())}),$E=YC(QE)}));function tD(e){return{status:`active`,...e}}function nD(e,t){switch(t.type){case`challengeReceived`:return e.status===`closing`||e.status===`closed`?sD(e,t):{state:{status:`challenged`,challengeId:t.challengeId},effects:[]};case`challenge`:return e.status!==`idle`&&e.status!==`active`?sD(e,t):t.snapshot?{state:{status:`hydrating`,challengeId:t.challengeId,snapshot:t.snapshot},effects:[{type:`hydrate`,snapshot:t.snapshot}]}:{state:{status:`opening`,challengeId:t.challengeId},effects:[{type:`open`}]};case`hydrated`:return e.status===`hydrating`?{state:aD(e.challengeId,t.snapshot),effects:[]}:sD(e,t);case`activated`:return e.status===`closing`||e.status===`closed`?sD(e,t):{state:yD({challengeId:t.challengeId,entry:t.entry,spent:t.spent,units:t.units??0}),effects:[]};case`opened`:return e.status===`opening`?{state:oD(e.challengeId,t.receipt,t.descriptor,t.deposit),effects:[]}:sD(e,t);case`receiptAccepted`:return e.status===`closing`||e.status===`closed`?sD(e,t):{state:SD(t.receipt,t.entry),effects:[]};case`needVoucher`:return e.status===`active`?iD({challengeId:e.challengeId,descriptor:t.descriptor,event:t.event}):sD(e,t);case`topUpStarted`:return e.status===`voucherNeeded`?{state:{status:`toppingUp`,challengeId:e.challengeId,channelId:e.channelId,descriptor:e.descriptor,deposit:e.deposit},effects:[]}:sD(e,t);case`voucherAccepted`:return e.status!==`voucherNeeded`&&e.status!==`toppingUp`?sD(e,t):{state:oD(e.challengeId,t.receipt,e.descriptor,t.deposit??e.deposit),effects:[]};case`settleStarted`:return e.status===`active`?{state:{status:`settling`,channelId:e.channelId,descriptor:e.descriptor,deposit:e.deposit},effects:[{type:`settle`,channelId:e.channelId}]}:sD(e,t);case`settled`:return e.status===`settling`?{state:oD(t.receipt.challengeId,t.receipt,e.descriptor,t.deposit??e.deposit),effects:[]}:sD(e,t);case`closeRequested`:return e.status===`active`?{state:{status:`closeRequested`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`requestClose`,channelId:e.channelId}]}:sD(e,t);case`withdrawable`:return e.status===`closeRequested`?{state:{status:`withdrawable`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`withdraw`,channelId:e.channelId}]}:sD(e,t);case`closeStarted`:return e.status!==`active`&&e.status!==`withdrawable`&&e.status!==`closeRequested`?sD(e,t):{state:{status:`closing`,channelId:e.channelId,descriptor:e.descriptor},effects:[{type:`close`,channelId:e.channelId}]};case`closed`:return e.status!==`closing`&&e.status!==`withdrawable`?sD(e,t):{state:{status:`closed`,channelId:e.channelId,descriptor:e.descriptor},effects:[]}}}function rD(e,t){let n=nD(e.state,t);return e.state=n.state,n}function iD(e){let{challengeId:t,descriptor:n,event:r}=e,i=BigInt(r.requiredCumulative),a=BigInt(r.deposit);return i>a?{state:{status:`toppingUp`,challengeId:t,channelId:r.channelId,descriptor:n,deposit:r.deposit},effects:[{type:`topUp`,channelId:r.channelId,amount:(i-a).toString()}]}:{state:{status:`voucherNeeded`,challengeId:t,channelId:r.channelId,descriptor:n,requiredCumulative:r.requiredCumulative,deposit:r.deposit},effects:[{type:`voucher`}]}}function aD(e,t){return tD({challengeId:e,channelId:t.channelId,descriptor:t.descriptor,acceptedCumulative:t.acceptedCumulative,deposit:t.deposit,spent:t.spent,units:t.units??0})}function oD(e,t,n,r){return tD({challengeId:e,channelId:t.channelId,descriptor:n,acceptedCumulative:t.acceptedCumulative,deposit:r,spent:t.spent,units:t.units??0})}function sD(e,t){throw Error(`Invalid session transition: ${e.status} + ${t.type}`)}function cD(e){let{cumulativeAmount:t,maxVoucherCumulative:n}=e;if(n!==null&&!(t<=n))throw Error(`requested voucher amount ${t} exceeds local maxDeposit ${n}`)}function lD(e){let{channel:t,maxVoucherCumulative:n,receipt:r}=e;if(!t||r.channelId!==t.channelId)return;let i=BigInt(r.acceptedCumulative),a=BigInt(r.spent);if(a>i)throw Error(`receipt spent exceeds accepted cumulative voucher amount`);if(i>t.cumulativeAmount)throw Error(`receipt accepted cumulative exceeds local voucher state`);if(a>t.cumulativeAmount)throw Error(`receipt spent exceeds local voucher state`);cD({cumulativeAmount:i,maxVoucherCumulative:n}),cD({cumulativeAmount:a,maxVoucherCumulative:n})}function uD(e){let{channel:t,maxVoucherCumulative:n,receipt:r,spent:i}=e;if(!r||r.channelId!==t?.channelId)return i;lD({channel:t,maxVoucherCumulative:n,receipt:r});let a=BigInt(r.spent);return i>a?i:a}function dD(e,t){return typeof e==`bigint`?e:P(e,t)}function fD(e){let{contextDepositRaw:t,maxDeposit:n,requestAmount:r,suggestedDepositRaw:i}=e;if(mD(r,n),t!==void 0){let e=BigInt(t);if(e<r)throw Error(`opening deposit ${e} below request amount ${r}`);return e}let a=i===void 0?void 0:BigInt(i),o=a!==void 0&&a>r?a:r;return n===void 0||o<n?o:n}function pD(e){let{deposit:t,maxDeposit:n,requiredCumulative:r,suggestedDeposit:i,topUpAmount:a}=e;if(r<=t)return 0n;cD({cumulativeAmount:r,maxVoucherCumulative:n??null});let o=r-t,s=a??i??o,c=s>o?s:o;if(n==null)return c;let l=n-t;return c<l?c:l}function mD(e,t){cD({cumulativeAmount:e,maxVoucherCumulative:t??null})}function hD(e){let{channel:t,currentSocket:n,lastChallenge:r}=e;if(!t?.opened)return;let i=n?.challenge??r,a=n?.channelId??t.channelId;if(!i)throw Error(`Cannot close session: no challenge available. This usually means close() was called on a SessionManager instance that was recreated after the session was opened. Use the same SessionManager instance that opened the session, or make a request first to receive a fresh 402 challenge.`);if(!a)throw Error(`Cannot close session: no channel ID available. The session may not have been fully opened.`);return{challenge:i,channel:t,channelId:a}}function gD(e){let{cumulativeAmount:t,spent:n}=e;return t>n?t:n}function _D(e){let{cumulativeAmount:t,readySpent:n,spent:r}=e;if(!CE(n))throw Error(`close-ready spent is not a uint96 amount`);if(n<r)throw Error(`close-ready spent is below locally confirmed spend`);if(n>gD({cumulativeAmount:t,spent:r}))throw Error(`close-ready spent exceeds local voucher state`)}function vD(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:i=0n,receipt:a}=e,o=wE(r),s=wE(a.spent);return o===void 0||s===void 0||!CE(i)?!1:!!a.txHash&&a.challengeId===t&&a.channelId===n&&a.acceptedCumulative===r&&s>=i&&s<=o}function yD(e){return tD({challengeId:e.challengeId,channelId:e.entry.channelId,descriptor:e.entry.descriptor,acceptedCumulative:e.entry.cumulativeAmount.toString(),deposit:e.entry.deposit.toString(),spent:e.spent,units:e.units})}function bD(){return{channel:null,lastChallenge:null,lastUrl:null,spent:0n,socketSession:null,state:OD}}function xD(e){let{maxVoucherCumulative:t,receipt:n,runtime:r}=e;r.spent=uD({channel:r.channel,maxVoucherCumulative:t,receipt:n,spent:r.spent}),n&&r.channel?.channelId===n.channelId&&rD(r,{type:`receiptAccepted`,receipt:n,entry:r.channel})}function SD(e,t){return tD({challengeId:e.challengeId,channelId:e.channelId,descriptor:t.descriptor,acceptedCumulative:e.acceptedCumulative,deposit:t.deposit.toString(),spent:e.spent,units:e.units??0})}function CD(e){let{challengeId:t,channelId:n,closeReadyReceipt:r,cumulativeAmount:i,deliveredChunks:a=0n,socketChallengeId:o,socketChannelId:s,spent:c,tickCost:l=0n}=e;if(c>i)throw Error(`locally confirmed spend exceeds local voucher state`);if(r&&r.challengeId===t&&r.channelId===n){let e=wE(r.spent);if(e===void 0)throw Error(`close-ready spent is not a uint96 amount`);return e>c?e:c}if(o===t&&s===n&&l>0n){let e=a*l,t=c>e?c:e;return t>i?i:t}return i}function wD(e){let{channel:t,channelId:n,challengeId:r,cumulativeAmount:i,spent:a,state:o}=e;if(!(!t||t.channelId!==n)&&(t.cumulativeAmount=i,r))return nD(o,{type:`activated`,challengeId:r,entry:t,spent:a.toString(),units:o.status===`active`?o.units:0}).state}function TD(e){return{channel:e.channel===null?null:{entry:e.channel,cumulativeAmount:e.channel.cumulativeAmount,deposit:e.channel.deposit,opened:e.channel.opened},spent:e.spent,state:e.state}}function ED(e,t){return e.channel?(e.channel.entry.cumulativeAmount=e.channel.cumulativeAmount,e.channel.entry.deposit=e.channel.deposit,e.channel.entry.opened=e.channel.opened,{channel:e.channel.entry,spent:e.spent,state:e.state}):(t&&(t.opened=!1),{channel:null,spent:e.spent,state:e.state})}async function DD(e){let{activeSocket:t,currentSocket:n,target:r}=e,i=n.closeReadyReceipt??await(async()=>(t.send(zE()),e.waitForCloseReady()))(),a=BigInt(i.spent);_D({cumulativeAmount:r.channel.cumulativeAmount,readySpent:a,spent:e.spent});let o=await e.createSessionCredential(r.challenge,{action:`close`,channelId:r.channelId,descriptor:r.channel.descriptor,cumulativeAmountRaw:a.toString()}),s=a.toString();n.expectedCloseAmount=s;try{let i=e.waitForReceipt(e=>vD({challengeId:r.challenge.id,channelId:r.channelId,expectedCloseAmount:s,minimumSpent:a,receipt:e}));t.send(RE(o));let c=await i;return t.close(),n.closeReadyReceipt=null,c}finally{n.expectedCloseAmount=null}}var OD,kD=I((()=>{GE(),eD(),OD={status:`idle`}}));function AD(e){let t=new Map,n=!1,r=[],i=e.readyState,a=(e,n,i)=>{let a=t.get(e);if(a||(a=new Set,t.set(e,a)),a.add({once:typeof i==`object`&&i.once===!0,value:n}),e===`message`&&r){let e=r;r=null;for(let t of e)s(`message`,t)}},o=(e,n)=>{let r=t.get(e);if(r)for(let e of r)e.value===n&&r.delete(e)};function s(e,a){if(a.type===`close`){if(n)return;n=!0,i=pO.CLOSED,r=null}if(a.type===`open`&&(i=pO.OPEN),a.type===`message`&&r){r.push(a);return}switch(a.type){case`close`:l.onclose?.(a);break;case`error`:l.onerror?.(a);break;case`message`:l.onmessage?.(a);break;case`open`:l.onopen?.(a)}let o=t.get(e);if(o)for(let e of Array.from(o))typeof e.value==`function`?e.value(a):e.value.handleEvent(a),e.once&&o.delete(e)}let c=null,l={addEventListener:a,close(t,n){e.close(t,n)},get bufferedAmount(){return e.bufferedAmount},get extensions(){return e.extensions},on(e,t){a(e,t)},onclose:null,onerror:null,get onmessage(){return c},set onmessage(e){if(c=e,e&&r){let e=r;r=null;for(let t of e)s(`message`,t)}},onopen:null,off(e,t){o(e,t)},get protocol(){return e.protocol},get readyState(){return i},removeEventListener:o,send(t){e.send(t)},get url(){return e.url}};return{emit:s,socket:l}}function jD(e){return{acceptedCumulative:BigInt(e.acceptedCumulative),deposit:BigInt(e.deposit),requiredCumulative:BigInt(e.requiredCumulative)}}function MD(e){let{amount:t,assertVoucherWithinLocalLimit:n,channel:r,decimals:i,lastChallenge:a,lastUrl:o}=e;if(!r?.opened)throw Error(`Cannot top up session: no open channel.`);if(!a)throw Error(`Cannot top up session: no challenge available. Make a request first.`);if(!o)throw Error(`Cannot top up session: no URL available. Call fetch(), sse(), or ws() first.`);let s=dD(t,i);if(s<=0n)throw Error(`Top-up amount must be greater than zero.`);return n(r.cumulativeAmount+s),{additionalDeposit:s,challenge:a,channelId:r.channelId,input:o}}function ND(e){let{additionalDeposit:t,channel:n,channelId:r,challengeId:i,currentState:a,knownDeposit:o,receipt:s,spent:c}=e;if(n?.channelId!==r)return;let l=o!==void 0&&o>n.deposit?o:n.deposit,u={...n,deposit:l+t};return s?{channel:u,state:SD(s,u)}:i?{channel:u,state:yD({challengeId:i,entry:u,spent:c.toString(),units:a.status===`active`?a.units:0})}:{channel:u}}async function PD(e){if(e.event.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`channel-mismatch`};let t=jD(e.event);e.assertVoucherWithinLocalLimit(t.requiredCumulative),await e.topUpIfNeeded({challenge:e.challenge,input:e.input,channelId:e.expectedChannelId,deposit:t.deposit,requiredCumulative:t.requiredCumulative,...e.signal?{signal:e.signal}:{}});let n=e.getChannel();if(!n||n.channelId!==e.expectedChannelId)return{status:`ignored`,reason:`missing-channel`};let r=n.cumulativeAmount>t.requiredCumulative?n.cumulativeAmount:TE(t.requiredCumulative);return{status:`ready`,context:{action:`voucher`,channelId:e.expectedChannelId,descriptor:n.descriptor,cumulativeAmountRaw:r.toString()}}}function FD(e){return e.method===jx.tempo&&e.intent===Mx.session}function ID(e){return FD(e)&&kx(e.request.methodDetails,Nx.sessionProtocol)===Px.v2}function LD(e){return kx(e.request.methodDetails,Nx.sessionSnapshot)}function RD(e,t,n){let r=e instanceof Request?e.headers:void 0;return{...t,headers:{...Mw(r),...Mw(t?.headers),[q.authorization]:n}}}function zD(e){try{let t=typeof location>`u`?void 0:location.href,n=e instanceof Request?new URL(e.url):e instanceof URL?new URL(e):new URL(String(e),t);return n.hash=``,n}catch{return e}}function BD(e){let t=new URL(e.toString());return t.protocol===`ws:`&&(t.protocol=`http:`),t.protocol===`wss:`&&(t.protocol=`https:`),t}async function VD(e){let t=await e.text().catch(()=>``);if(!t)return``;if(!e.headers.get(`Content-Type`)?.includes(`application/problem+json`))return t;try{return JSON.parse(t).detail??t}catch{return t}}async function HD(e){let{channel:t,channelId:n}=e;if(!t?.descriptor||t.channelId!==n)throw Error(`Cannot top up session: no local channel descriptor available.`);if(t.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before another top-up.`);let r=await UD({challenge:e.challenge,context:{action:`topUp`,channelId:n,descriptor:t.descriptor,additionalDepositRaw:e.additionalDeposit.toString()},createSessionCredential:e.createSessionCredential,fetch:e.fetch,input:e.input,signal:e.signal}).catch(async n=>{throw n instanceof gO&&(t.uncertainTopUp=!0,await e.onUncertainFunding?.(t)),n});if(!r.ok)throw Error(`Top-up POST failed with status ${r.status}`);let i=r.headers.get(q.paymentReceipt);return i?PE(i):void 0}async function UD(e){let t=async t=>{e.signal?.throwIfAborted();let n=await e.createSessionCredential(t,e.context);e.signal?.throwIfAborted();let r=new AbortController,i=()=>r.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,i,{once:!0});let a=setTimeout(()=>r.abort(new DOMException(`Session management request timed out; payment outcome unknown`,`TimeoutError`)),3e4),o,s=new Promise((e,t)=>{o=()=>t(r.signal.reason),r.signal.addEventListener(`abort`,o,{once:!0})});try{return await Promise.race([e.fetch(zD(e.input),{method:`POST`,signal:r.signal,headers:{[q.authorization]:n}}),s])}catch(t){throw e.context.action===`topUp`?new gO(t):t}finally{clearTimeout(a),e.signal?.removeEventListener(`abort`,i),r.signal.removeEventListener(`abort`,o)}},n=await t(e.challenge);if(n.status!==402)return n;let r=cS(n).find(ID);return r?t(r):n}async function WD(e){let t=GD({channel:e.getChannel(),response:e.response});if(!t)return;let{channel:n,challenge:r,snapshot:i}=t;e.setChallenge(r);let a=BigInt(i.requiredCumulative),o=n.cumulativeAmount;await e.topUpIfNeeded({challenge:r,input:e.input,channelId:i.channelId,deposit:BigInt(i.deposit),requiredCumulative:a,signal:e.init?.signal??(e.input instanceof Request?e.input.signal:void 0)});let s=e.getChannel();if(!s?.descriptor||s.channelId!==i.channelId)return;let c=s.cumulativeAmount>a?s.cumulativeAmount:a,l=()=>e.restoreCumulative(i.channelId,o),u;try{let t=await e.createSessionCredential(r,{action:`voucher`,channelId:i.channelId,descriptor:s.descriptor,cumulativeAmountRaw:c.toString()});u=await e.fetch(e.input,RD(e.input,e.init,t))}catch(e){throw await l(),e}return!u.ok&&!u.headers.get(q.paymentReceipt)&&await l(),u}function GD(e){let t=cS(e.response).find(ID);if(!t)return;let n=LD(t);if(!n)return;let{channel:r}=e;if(!(!r?.descriptor||r.channelId!==n.channelId))return{channel:r,challenge:t,snapshot:n}}async function KD(e){if(!e.lastUrl)throw Error(`Cannot close session: no URL available. This usually means close() was called on a SessionManager instance that was recreated after the session was opened. Use the same SessionManager instance that opened the session, or call fetch()/sse() before close().`);let t=e.target.challenge,n=e.signedCloseAmount,r=async(r,i=!1)=>{t=r,n=(i?e.resolveSignedCloseAmount?.(r):void 0)??e.signedCloseAmount;let a=await e.createSessionCredential(r,{action:`close`,channelId:e.target.channelId,descriptor:e.target.channel.descriptor,cumulativeAmountRaw:n});return e.fetch(e.lastUrl,{method:`POST`,headers:{[q.authorization]:a}})},i=await r(e.target.challenge);if(i.status===402){let t=cS(i).find(ID);t&&(e.setChallenge?.(t),i=await r(t,!0))}if(!i.ok){let e=await VD(i),t=i.headers.get(q.wwwAuthenticate)??``;throw Error(`Close request failed with status ${i.status}${e?`: ${e}`:``}${t?` [${q.wwwAuthenticate}: ${t}]`:``}`)}let a=i.headers.get(q.paymentReceipt);if(!a)return;let o=PE(a);if(!o.txHash||!ne.validate(o.txHash,{strict:!0})||ne.size(o.txHash)!==32||!vD({challengeId:t.id,channelId:e.target.channelId,expectedCloseAmount:n,minimumSpent:e.getMinimumSpent?.()??0n,receipt:o}))throw Error(`Session close response included a mismatched payment receipt.`);return o}async function qD(e,t,n){let{onReceipt:r,signal:i,...a}=t??{},o=i??(e instanceof Request?e.signal:void 0),s={...a,headers:{...Mw(a.headers),Accept:`text/event-stream`},...o?{signal:o}:{}},c=await n.doFetch(e,s);return!FE(c)&&n.getChannel()?.opened&&(c=await n.doFetch(e,s)),JD(e,c,{onReceipt:r,signal:o},n)}function JD(e,t,n,r){if(!FE(t))throw Error(`SSE response is not an event stream.`);if(!t.body)throw Error(`Response has no body.`);let i=r.getChallenge();return YD({onNeedVoucher:t=>eO({challenge:i,driver:r,input:e,signal:n?.signal},t),onReceipt(e){r.acceptReceipt(e),n?.onReceipt?.(e)},response:t,signal:n?.signal})}async function*YD(e){for await(let t of XD(e))t.data!==void 0&&(yield t.data)}async function*XD(e){if(!e.response.body)throw Error(`Response has no body.`);let t=e.response.body.getReader(),n=new TextDecoder,r=``,i=!1,a=()=>{t.cancel(e.signal?.reason).catch(()=>void 0)};e.signal?.addEventListener(`abort`,a,{once:!0}),e.signal?.aborted&&a();try{for(;!e.signal?.aborted;){let{done:a,value:o}=await t.read();for(a?(i=!0,r+=n.decode()):r+=n.decode(o,{stream:!0});;){let t=ZD(r,a);if(!t)break;let n=t.index+t.length,i=r.slice(0,t.index),o=r.slice(0,n);if(r=r.slice(n),!i.trim())continue;let s=IE(i.replace(/\r\n|\r/g,`
227
+ `));if(!s){yield{raw:o};continue}switch(s.type){case`message`:yield{data:s.data,raw:o};break;case`payment-need-voucher`:await e.onNeedVoucher(s.data,e.signal);break;case`payment-receipt`:e.onReceipt(s.data)}}if(a)break}}finally{e.signal?.removeEventListener(`abort`,a),i||await t.cancel().catch(()=>void 0),t.releaseLock()}}function ZD(e,t){for(let n=0;n<e.length;n++){let r=QD(e,n,t);if(!r)continue;let i=QD(e,n+r,t);if(i)return{index:n,length:r+i};n+=r-1}}function QD(e,t,n){return e[t]===`
228
228
  `?1:e[t]===`\r`?e[t+1]===`
229
- `?2:t+1===e.length&&!n?0:1:0}function ZD(e){let t=new AbortController,n=()=>t.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,n,{once:!0}),e.signal?.aborted&&n();let r=JD({...e,signal:t.signal}),i=new TextEncoder,a=new Headers(e.response.headers);a.delete(`content-length`);let o=()=>e.signal?.removeEventListener(`abort`,n),s=new Response(new ReadableStream({async pull(e){try{let t=await r.next();if(t.done)return o(),e.close();e.enqueue(i.encode(t.value.raw))}catch(e){throw o(),e}},async cancel(){o(),t.abort(),await r.return(void 0)}}),{headers:a,status:e.response.status,statusText:e.response.statusText});for(let t of[`redirected`,`type`,`url`])Object.defineProperty(s,t,{configurable:!0,get:()=>e.response[t]});return s}async function QD(e,t){let n=e.driver.getChannel();if(!n||!e.challenge)return;let r=await MD({assertVoucherWithinLocalLimit:e.driver.assertVoucherWithinLocalLimit,challenge:e.challenge,event:t,expectedChannelId:n.channelId,getChannel:e.driver.getChannel,input:e.input,signal:e.signal,topUpIfNeeded:e.driver.topUpIfNeeded});if(r.status!==`ready`)return;let i=await VD({challenge:e.challenge,context:r.context,createSessionCredential:e.driver.createSessionCredential,fetch:e.driver.fetch,input:e.input,signal:e.signal});if(!i.ok)throw Error(`Voucher POST failed with status ${i.status}`)}async function $D(e){let t=new URL(e.input.toString()),n=RD(t);e.onProbeUrl?.(n);let r=await e.fetch(n,{...e.probeInit,...e.signal?{signal:e.signal}:{}});if(r.status!==402)throw Error(`Expected a 402 payment challenge from ${n}, received ${r.status} instead.`);let i=cS(r).find(PD);if(!i)throw Error(`No payment challenge received from HTTP endpoint for this WebSocket URL. The server may not require payment or did not advertise a challenge.`);return{challenge:i,httpUrl:n,wsUrl:t}}async function eO(e){e.signal?.throwIfAborted();let t=await $D(e);e.signal?.throwIfAborted();let n=await e.createSessionCredential(t.challenge,{});return e.signal?.throwIfAborted(),{...t,credential:n}}function tO(e){let{challenge:t,credential:n,socket:r}=e;return{challenge:t,channelId:YS(n).payload.channelId,closeReadyReceipt:null,deliveredChunks:0n,expectedCloseAmount:null,socket:r,tickCost:kE(t)}}function nO(e){let{challengeId:t,channelId:n,receipt:r}=e;return r.challengeId===t&&r.channelId===n}function rO(e){if(!nO(e))return`received mismatched payment-close-ready frame`;let t=SE(e.receipt.spent);if(t===void 0)return`received invalid payment-close-ready spend`;if(t>e.cumulativeAmount)return`received payment-close-ready beyond local voucher state`}function iO(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,receipt:i}=e;if(!nO(e))return`received mismatched payment-receipt frame`;if(r!==null&&i.txHash&&!gD({challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:BigInt(r),receipt:i}))return`received mismatched payment-close receipt frame`}async function aO(e){let{challenge:t,credential:n,options:r,WebSocket:i,wsUrl:a}=e,o=r?.signal;o?.throwIfAborted();let s=new i(a,r?.protocols),c=tO({challenge:t,credential:n,socket:s});e.setSocketSession(c);let l=OD(s),u=t=>{e.rejectReceipt(Error(t)),e.rejectCloseReady(Error(t)),(s.readyState===dO.CONNECTING||s.readyState===dO.OPEN)&&s.close(fO,t)},d=()=>{e.rejectReceipt(Error(`WebSocket payment flow aborted.`)),e.rejectCloseReady(Error(`WebSocket payment flow aborted.`)),s.close()};s.addEventListener(`close`,t=>{o?.removeEventListener(`abort`,d),c.socket=null,c.expectedCloseAmount=null,e.rejectReceipt(Error(`WebSocket closed before the payment flow completed.`)),e.rejectCloseReady(Error(`WebSocket closed before the payment flow completed.`)),l.emit(`close`,{code:t.code??1e3,reason:t.reason??``,type:`close`,wasClean:!0})}),s.addEventListener(`error`,()=>{l.emit(`error`,{type:`error`})}),s.addEventListener(`message`,async t=>{let n=typeof t.data==`string`?t.data:void 0;n&&await sO({driver:e,failSocketFlow:u,managedEmit:l.emit,message:n,rawSocket:s,socketState:c})}),o?.addEventListener(`abort`,d,{once:!0});try{await oO(s,l.emit,a,o),o?.throwIfAborted()}catch(e){throw o?.removeEventListener(`abort`,d),s.close(),e}return s.send(IE(n)),await e.waitForReceipt(),l.socket}function oO(e,t,n,r){return new Promise((i,a)=>{let o=()=>{e.removeEventListener(`open`,s),e.removeEventListener(`error`,c),e.removeEventListener(`close`,c),r?.removeEventListener(`abort`,l)},s=()=>{o(),t(`open`,{type:`open`}),i()},c=()=>{o(),a(Error(`WebSocket connection to ${n} failed to open.`))},l=()=>{o(),a(r?.reason)};e.addEventListener(`open`,s,{once:!0}),e.addEventListener(`error`,c,{once:!0}),e.addEventListener(`close`,c,{once:!0}),r?.addEventListener(`abort`,l,{once:!0}),r?.aborted&&l()})}async function sO(e){let t=RE(e.message);if(!t){e.managedEmit(`message`,{data:e.message,type:`message`});return}switch(t.mpp){case`authorization`:return;case`message`:e.socketState.deliveredChunks+=1n,e.managedEmit(`message`,{data:t.data,type:`message`});return;case`payment-close-ready`:cO(e,t.data);return;case`payment-error`:e.driver.rejectReceipt(Error(t.message)),e.driver.rejectCloseReady(Error(t.message));return;case`payment-need-voucher`:await lO(e,t.data);return;case`payment-receipt`:uO(e,t.data);return}}function cO(e,t){let n=e.driver.getChannel()?.cumulativeAmount??0n,r=rO({challengeId:e.driver.challenge.id,channelId:e.socketState.channelId,cumulativeAmount:n,receipt:t});if(r){e.failSocketFlow(r);return}e.driver.acceptReceipt(t),e.driver.options?.onReceipt?.(t),e.driver.settleCloseReady(t),e.managedEmit(`close`,{code:1e3,reason:`stream complete`,type:`close`,wasClean:!0})}async function lO(e,t){try{let n=e.driver.challenge;n.expires&&new Date(n.expires).getTime()<=Date.now()+pO&&(n=await e.driver.refreshChallenge(),e.driver.challenge=n,e.socketState.challenge=n);let r=await MD({assertVoucherWithinLocalLimit:e.driver.assertVoucherWithinLocalLimit,challenge:n,event:t,expectedChannelId:e.socketState.channelId,getChannel:e.driver.getChannel,input:e.driver.httpUrl,signal:e.driver.options?.signal,topUpIfNeeded:e.driver.topUpIfNeeded});if(r.status===`ignored`){e.failSocketFlow(r.reason===`channel-mismatch`?`received mismatched payment-need-voucher frame`:`cannot create voucher: no active channel`);return}let i=await e.driver.createSessionCredential(n,r.context);e.rawSocket.send(IE(i))}catch(t){e.failSocketFlow(t instanceof Error?t.message:`failed to create websocket voucher`)}}function uO(e,t){let n=iO({challengeId:e.driver.challenge.id,channelId:e.socketState.channelId,expectedCloseAmount:e.socketState.expectedCloseAmount,receipt:t});if(n){e.failSocketFlow(n);return}e.driver.acceptReceipt(t),e.driver.options?.onReceipt?.(t),e.driver.settleReceipt(t)}var dO,fO,pO,mO=F((()=>{_S(),_T(),Fx(),nC(),UE(),DD(),dO={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3},fO=3008,pO=5e3})),hO,gO,_O,vO,yO,bO=F((()=>{hO={mainnet:4217,testnet:42431},gO={ousd:Ce(hO.mainnet).address,usdc:M(Te(hO.mainnet).address),pathUsd:we(hO.mainnet).address},_O={[hO.mainnet]:gO.usdc,[hO.testnet]:gO.pathUsd},vO=Object.freeze({[hO.mainnet]:Object.freeze({swap:`0xF72E5107c32C655ffA7539a3C8e97B7C3cE16A3F`,token:`0x20c000000000000000000000f37de3740ADec032`}),[hO.testnet]:Object.freeze({swap:`0xd05f8EdFBB54Da0d765C9fE9b2B3f7d2E3a8C466`,token:`0x20c000000000000000000000f37de3740ADec032`})}),hO.mainnet,hO.testnet,yO={[hO.mainnet]:`https://rpc.tempo.xyz`,[hO.testnet]:`https://rpc.moderato.tempo.xyz`}})),xO=Qe({chainName:()=>LO,confirm:()=>MO,decodeMemo:()=>TO,fetchBalanceLines:()=>VO,fetchTokenInfo:()=>BO,fmtBalance:()=>NO,fmtChallengeValue:()=>EO,fmtRequestValue:()=>wO,isAgentEnvironment:()=>kO,isTempoAccount:()=>AO,isTestnet:()=>zO,link:()=>DO,mainnetTokens:()=>KO,networkRpcUrls:()=>UO,parseMethodOpts:()=>OO,pathUsd:()=>WO,pc:()=>X,printRequestHeaders:()=>SO,printResponseHeaders:()=>CO,prompt:()=>jO,resolveChain:()=>IO,resolveFundingNetwork:()=>FO,resolveRpcUrl:()=>PO,testnetTokens:()=>qO,usdc:()=>GO});function SO(e,t,n){let{pathname:r,host:i}=new URL(e);n(`> ${(t.method??`GET`).toUpperCase()} ${r} HTTP/1.1\n`),n(`> Host: ${i}\n`);for(let[e,r]of Object.entries(t.headers??{}))n(`> ${e}: ${r}\n`);n(`>
230
- `)}function CO(e,t){if(!t.include&&t.verbose<2||t.silent)return;let n=`HTTP/1.1 ${e.status} ${e.statusText}`,r=t.verbose>=2?process.stderr:process.stdout,i=t.verbose>=2?`< `:``;r.write(`${i}${n}\n`);for(let[t,n]of e.headers)r.write(`${i}${t}: ${n}\n`);r.write(t.verbose>=2?`<
229
+ `?2:t+1===e.length&&!n?0:1:0}function $D(e){let t=new AbortController,n=()=>t.abort(e.signal?.reason);e.signal?.addEventListener(`abort`,n,{once:!0}),e.signal?.aborted&&n();let r=XD({...e,signal:t.signal}),i=new TextEncoder,a=new Headers(e.response.headers);a.delete(`content-length`);let o=()=>e.signal?.removeEventListener(`abort`,n),s=new Response(new ReadableStream({async pull(e){try{let t=await r.next();if(t.done)return o(),e.close();e.enqueue(i.encode(t.value.raw))}catch(e){throw o(),e}},async cancel(){o(),t.abort(),await r.return(void 0)}}),{headers:a,status:e.response.status,statusText:e.response.statusText});for(let t of[`redirected`,`type`,`url`])Object.defineProperty(s,t,{configurable:!0,get:()=>e.response[t]});return s}async function eO(e,t){let n=e.driver.getChannel();if(!n||!e.challenge)return;let r=await PD({assertVoucherWithinLocalLimit:e.driver.assertVoucherWithinLocalLimit,challenge:e.challenge,event:t,expectedChannelId:n.channelId,getChannel:e.driver.getChannel,input:e.input,signal:e.signal,topUpIfNeeded:e.driver.topUpIfNeeded});if(r.status!==`ready`)return;let i=await UD({challenge:e.challenge,context:r.context,createSessionCredential:e.driver.createSessionCredential,fetch:e.driver.fetch,input:e.input,signal:e.signal});if(!i.ok)throw Error(`Voucher POST failed with status ${i.status}`)}async function tO(e){let t=new URL(e.input.toString()),n=BD(t);e.onProbeUrl?.(n);let r=await e.fetch(n,{...e.probeInit,...e.signal?{signal:e.signal}:{}});if(r.status!==402)throw Error(`Expected a 402 payment challenge from ${n}, received ${r.status} instead.`);let i=cS(r).find(ID);if(!i)throw Error(`No payment challenge received from HTTP endpoint for this WebSocket URL. The server may not require payment or did not advertise a challenge.`);return{challenge:i,httpUrl:n,wsUrl:t}}async function nO(e){e.signal?.throwIfAborted();let t=await tO(e);e.signal?.throwIfAborted();let n=await e.createSessionCredential(t.challenge,{});return e.signal?.throwIfAborted(),{...t,credential:n}}function rO(e){let{challenge:t,credential:n,socket:r}=e;return{challenge:t,channelId:YS(n).payload.channelId,closeReadyReceipt:null,deliveredChunks:0n,expectedCloseAmount:null,socket:r,tickCost:jE(t)}}function iO(e){let{challengeId:t,channelId:n,receipt:r}=e;return r.challengeId===t&&r.channelId===n}function aO(e){if(!iO(e))return`received mismatched payment-close-ready frame`;let t=wE(e.receipt.spent);if(t===void 0)return`received invalid payment-close-ready spend`;if(t>e.cumulativeAmount)return`received payment-close-ready beyond local voucher state`}function oO(e){let{challengeId:t,channelId:n,expectedCloseAmount:r,receipt:i}=e;if(!iO(e))return`received mismatched payment-receipt frame`;if(r!==null&&i.txHash&&!vD({challengeId:t,channelId:n,expectedCloseAmount:r,minimumSpent:BigInt(r),receipt:i}))return`received mismatched payment-close receipt frame`}async function sO(e){let{challenge:t,credential:n,options:r,WebSocket:i,wsUrl:a}=e,o=r?.signal;o?.throwIfAborted();let s=new i(a,r?.protocols),c=rO({challenge:t,credential:n,socket:s});e.setSocketSession(c);let l=AD(s),u=t=>{e.rejectReceipt(Error(t)),e.rejectCloseReady(Error(t)),(s.readyState===pO.CONNECTING||s.readyState===pO.OPEN)&&s.close(mO,t)},d=()=>{e.rejectReceipt(Error(`WebSocket payment flow aborted.`)),e.rejectCloseReady(Error(`WebSocket payment flow aborted.`)),s.close()};s.addEventListener(`close`,t=>{o?.removeEventListener(`abort`,d),c.socket=null,c.expectedCloseAmount=null,e.rejectReceipt(Error(`WebSocket closed before the payment flow completed.`)),e.rejectCloseReady(Error(`WebSocket closed before the payment flow completed.`)),l.emit(`close`,{code:t.code??1e3,reason:t.reason??``,type:`close`,wasClean:!0})}),s.addEventListener(`error`,()=>{l.emit(`error`,{type:`error`})}),s.addEventListener(`message`,async t=>{let n=typeof t.data==`string`?t.data:void 0;n&&await lO({driver:e,failSocketFlow:u,managedEmit:l.emit,message:n,rawSocket:s,socketState:c})}),o?.addEventListener(`abort`,d,{once:!0});try{await cO(s,l.emit,a,o),o?.throwIfAborted()}catch(e){throw o?.removeEventListener(`abort`,d),s.close(),e}return s.send(RE(n)),await e.waitForReceipt(),l.socket}function cO(e,t,n,r){return new Promise((i,a)=>{let o=()=>{e.removeEventListener(`open`,s),e.removeEventListener(`error`,c),e.removeEventListener(`close`,c),r?.removeEventListener(`abort`,l)},s=()=>{o(),t(`open`,{type:`open`}),i()},c=()=>{o(),a(Error(`WebSocket connection to ${n} failed to open.`))},l=()=>{o(),a(r?.reason)};e.addEventListener(`open`,s,{once:!0}),e.addEventListener(`error`,c,{once:!0}),e.addEventListener(`close`,c,{once:!0}),r?.addEventListener(`abort`,l,{once:!0}),r?.aborted&&l()})}async function lO(e){let t=BE(e.message);if(!t){e.managedEmit(`message`,{data:e.message,type:`message`});return}switch(t.mpp){case`authorization`:return;case`message`:e.socketState.deliveredChunks+=1n,e.managedEmit(`message`,{data:t.data,type:`message`});return;case`payment-close-ready`:uO(e,t.data);return;case`payment-error`:e.driver.rejectReceipt(Error(t.message)),e.driver.rejectCloseReady(Error(t.message));return;case`payment-need-voucher`:await dO(e,t.data);return;case`payment-receipt`:fO(e,t.data);return}}function uO(e,t){let n=e.driver.getChannel()?.cumulativeAmount??0n,r=aO({challengeId:e.driver.challenge.id,channelId:e.socketState.channelId,cumulativeAmount:n,receipt:t});if(r){e.failSocketFlow(r);return}e.driver.acceptReceipt(t),e.driver.options?.onReceipt?.(t),e.driver.settleCloseReady(t),e.managedEmit(`close`,{code:1e3,reason:`stream complete`,type:`close`,wasClean:!0})}async function dO(e,t){try{let n=e.driver.challenge;n.expires&&new Date(n.expires).getTime()<=Date.now()+hO&&(n=await e.driver.refreshChallenge(),e.driver.challenge=n,e.socketState.challenge=n);let r=await PD({assertVoucherWithinLocalLimit:e.driver.assertVoucherWithinLocalLimit,challenge:n,event:t,expectedChannelId:e.socketState.channelId,getChannel:e.driver.getChannel,input:e.driver.httpUrl,signal:e.driver.options?.signal,topUpIfNeeded:e.driver.topUpIfNeeded});if(r.status===`ignored`){e.failSocketFlow(r.reason===`channel-mismatch`?`received mismatched payment-need-voucher frame`:`cannot create voucher: no active channel`);return}let i=await e.driver.createSessionCredential(n,r.context);e.rawSocket.send(RE(i))}catch(t){e.failSocketFlow(t instanceof Error?t.message:`failed to create websocket voucher`)}}function fO(e,t){let n=oO({challengeId:e.driver.challenge.id,channelId:e.socketState.channelId,expectedCloseAmount:e.socketState.expectedCloseAmount,receipt:t});if(n){e.failSocketFlow(n);return}e.driver.acceptReceipt(t),e.driver.options?.onReceipt?.(t),e.driver.settleReceipt(t)}var pO,mO,hO,gO,_O=I((()=>{_S(),yT(),Fx(),rC(),GE(),kD(),pO={CONNECTING:0,OPEN:1,CLOSING:2,CLOSED:3},mO=3008,hO=5e3,gO=class extends Error{constructor(e){let t=e instanceof Error||e instanceof DOMException?e.message:String(e);super(`${t}; payment outcome unknown`),this.name=`UncertainFundingError`}}})),vO,yO,bO,xO,SO,CO=I((()=>{vO={mainnet:4217,testnet:42431},yO={ousd:Se(vO.mainnet).address,usdc:N(we(vO.mainnet).address),pathUsd:Ce(vO.mainnet).address},bO={[vO.mainnet]:yO.usdc,[vO.testnet]:yO.pathUsd},xO=Object.freeze({[vO.mainnet]:Object.freeze({swap:`0xF72E5107c32C655ffA7539a3C8e97B7C3cE16A3F`,token:`0x20c000000000000000000000f37de3740ADec032`}),[vO.testnet]:Object.freeze({swap:`0xd05f8EdFBB54Da0d765C9fE9b2B3f7d2E3a8C466`,token:`0x20c000000000000000000000f37de3740ADec032`})}),vO.mainnet,vO.testnet,SO={[vO.mainnet]:`https://rpc.tempo.xyz`,[vO.testnet]:`https://rpc.moderato.tempo.xyz`}})),wO=Ze({chainName:()=>BO,confirm:()=>FO,decodeMemo:()=>OO,fetchBalanceLines:()=>WO,fetchTokenInfo:()=>UO,fmtBalance:()=>IO,fmtChallengeValue:()=>kO,fmtRequestValue:()=>DO,isAgentEnvironment:()=>MO,isTempoAccount:()=>NO,isTestnet:()=>HO,link:()=>AO,mainnetTokens:()=>YO,networkRpcUrls:()=>KO,parseMethodOpts:()=>jO,pathUsd:()=>qO,pc:()=>X,printRequestHeaders:()=>TO,printResponseHeaders:()=>EO,prompt:()=>PO,resolveChain:()=>zO,resolveFundingNetwork:()=>RO,resolveRpcUrl:()=>LO,testnetTokens:()=>XO,usdc:()=>JO});function TO(e,t,n){let{pathname:r,host:i}=new URL(e);n(`> ${(t.method??`GET`).toUpperCase()} ${r} HTTP/1.1\n`),n(`> Host: ${i}\n`);for(let[e,r]of Object.entries(t.headers??{}))n(`> ${e}: ${r}\n`);n(`>
230
+ `)}function EO(e,t){if(!t.include&&t.verbose<2||t.silent)return;let n=`HTTP/1.1 ${e.status} ${e.statusText}`,r=t.verbose>=2?process.stderr:process.stdout,i=t.verbose>=2?`< `:``;r.write(`${i}${n}\n`);for(let[t,n]of e.headers)r.write(`${i}${t}: ${n}\n`);r.write(t.verbose>=2?`<
231
231
  `:`
232
- `)}function wO(e,t,n){if(HO.has(e)&&typeof t==`string`)return`${t} ${X.dim(`(${NO(BigInt(t),n.tokenSymbol,n.tokenDecimals)})`)}`;if(e===`chainId`&&typeof t==`number`){let e=LO({id:t,name:``});return e?`${t} ${X.dim(`(${e})`)}`:String(t)}return typeof t==`string`&&/^0x[0-9a-fA-F]{40}$/.test(t)?n.explorerUrl?DO(`${n.explorerUrl}/address/${t}`,t):t:typeof t==`string`&&/^https?:\/\//.test(t)?X.link(t,t):String(t)}function TO(e){try{let t=e.replace(/^0x0*/,``);if(!t)return;let n=Uint8Array.from(t.match(/.{1,2}/g).map(e=>Number.parseInt(e,16))),r=new TextDecoder().decode(n);return/^[\x20-\x7e]+$/.test(r)?r:void 0}catch{return}}function EO(e,t){if(e===`realm`&&typeof t==`string`)try{let e=new URL(t.includes(`://`)?t:`https://${t}`);return X.link(e.href,t)}catch{}return String(t)}function DO(e,t){return X.link(e,t)}function OO(e){if(!e)return{};let t=Array.isArray(e)?e:[e],n={};for(let e of t){let t=e.indexOf(`=`);if(t===-1)throw Error(`Invalid method option format: ${e} (expected key=value)`);n[e.slice(0,t)]=e.slice(t+1)}return n}function kO(e=process.env){if(e.CLAUDECODE)return!0;for(let[t,n]of Object.entries(e))if(n&&(t===`CODEX`||t.startsWith(`CODEX_`)))return!0;return!1}function AO(e){return e.startsWith(`tempo:`)}function jO(e){let t=Se.createInterface({input:process.stdin,output:process.stderr});return new Promise(n=>{t.on(`close`,()=>n(void 0)),t.question(`${X.bold(`▸ ${e}:`)} `,e=>{t.close(),n(e.trim()||void 0)})})}function MO(e,t=!1){let n=Se.createInterface({input:process.stdin,output:process.stderr});return new Promise(r=>{let i=t?`(Y/n)`:`(y/N)`;n.question(`${X.bold(`▸ ${e}`)} ${X.dim(i)} `,e=>{n.close();let i=e.trim().toLowerCase();r(i===``?t:i===`y`)})})}function NO(e,t,n=6,r){let[i,a]=(Number(e)/10**n).toString().split(`.`),o=i.replace(/\B(?=(\d{3})+(?!\d))/g,`_`),s=r?.explorerUrl&&r.token?X.dim(X.link(`${r.explorerUrl}/token/${r.token}`,t,!0)):X.dim(t);return`${a?`${o}.${a}`:o} ${s}`}function PO(e,t={}){return e??(t.network?UO[t.network]:void 0)??(process.env.MPPX_RPC_URL?.trim()||process.env.RPC_URL?.trim()||void 0)}function FO(e={}){if(e.network)return e.network;if(!e.rpcUrl&&!(process.env.MPPX_RPC_URL?.trim()||process.env.RPC_URL?.trim()))return`testnet`}async function IO(e={}){let t=PO(e.rpcUrl,{network:e.network});if(!t)return ye;let{getChainId:n}=await import(`viem/actions`),r=await n(j({transport:ue(t)})),i=Object.values(await import(`viem/tempo/chains`)).filter(e=>typeof e==`object`&&!!e&&`id`in e&&e.id===r),a=i.find(e=>`serializers`in e&&e.serializers)??i[0];if(!a)throw Error(`Unknown chain ID ${r} from RPC ${t}`);return a}function LO(e){return{[ye.id]:`mainnet`,[be.id]:`testnet`}[e.id]??e.name}function RO(e){return typeof e==`bigint`?e:e.amount}function zO(e){return e.id!==ye.id}async function BO(e,t,n,r={}){let{Actions:i}=await import(`viem/tempo`),[a,o]=await Promise.all([i.token.getBalance(e,{account:n,token:t}).then(RO).catch(()=>0n),i.token.getMetadata(e,{token:t}).catch(e=>{if(r.requireDecimals)throw e;return{symbol:t}})]),s={"0x20c0000000000000000000000000000000000000":`PathUSD`,"0x20C000000000000000000000b9537d11c60E8b50":`USDC`}[t]??o.symbol,c=`decimals`in o&&typeof o.decimals==`number`?o.decimals:6;if(r.requireDecimals&&!(`decimals`in o&&typeof o.decimals==`number`))throw Error(`Token decimals are unavailable.`);return{balance:a,symbol:s,decimals:c,token:t}}async function VO(e,t){if(t?.chain){let n=j({chain:t.chain,transport:ue(t.rpcUrl)}),r=t.chain.blockExplorers?.default?.url,i=X.dim(`(${LO(t.chain)})`);return zO(t.chain)?(await Promise.all(qO.map(t=>BO(n,t,e)))).filter(e=>e.balance>0n).map(e=>`${NO(e.balance,e.symbol,e.decimals,{explorerUrl:r,token:e.token})} ${i}`):(await Promise.all(KO.map(t=>BO(n,t,e)))).map(e=>`${NO(e.balance,e.symbol,e.decimals,{explorerUrl:r,token:e.token})} ${i}`)}let n=j({chain:ye,transport:ue(PO())}),r=ye.blockExplorers?.default?.url,i=(await Promise.all(KO.map(t=>BO(n,t,e)))).map(e=>NO(e.balance,e.symbol,e.decimals,{explorerUrl:r,token:e.token}));if(t?.includeTestnet!==!1){let t=j({chain:be,transport:ue()}),n=be.blockExplorers?.default?.url,r=await Promise.all(qO.map(n=>BO(t,n,e)));for(let e of r)e.balance>0n&&i.push(`${NO(e.balance,e.symbol,e.decimals,{explorerUrl:n,token:e.token})} ${X.dim(`(testnet)`)}`)}return i}var X,HO,UO,WO,GO,KO,qO,JO=F((()=>{bO(),X=(()=>{let e=process||{},t=e.argv||[],n=e.env||{},r=!(n.NO_COLOR||t.includes(`--no-color`))&&(!!n.FORCE_COLOR||t.includes(`--color`)||(e.stdout||{}).isTTY&&n.TERM!==`dumb`||!!n.CI),i=(e,t,n,r)=>{let i=``,a=0,o=r;do i+=e.substring(a,o)+n,a=o+t.length,o=e.indexOf(t,a);while(~o);return i+e.substring(a)},a=r?(e,t,n=e)=>r=>{let a=`${r}`,o=a.indexOf(t,e.length);return~o?e+i(a,t,n,o)+t:e+a+t}:()=>String;return{isColorSupported:r,reset:a(`\x1B[0m`,`\x1B[0m`),bold:a(`\x1B[1m`,`\x1B[22m`,`\x1B[22m\x1B[1m`),dim:a(`\x1B[2m`,`\x1B[22m`,`\x1B[22m\x1B[2m`),italic:a(`\x1B[3m`,`\x1B[23m`),underline:a(`\x1B[4m`,`\x1B[24m`),inverse:a(`\x1B[7m`,`\x1B[27m`),hidden:a(`\x1B[8m`,`\x1B[28m`),strikethrough:a(`\x1B[9m`,`\x1B[29m`),black:a(`\x1B[30m`,`\x1B[39m`),red:a(`\x1B[31m`,`\x1B[39m`),green:a(`\x1B[32m`,`\x1B[39m`),yellow:a(`\x1B[33m`,`\x1B[39m`),blue:a(`\x1B[34m`,`\x1B[39m`),magenta:a(`\x1B[35m`,`\x1B[39m`),cyan:a(`\x1B[36m`,`\x1B[39m`),white:a(`\x1B[37m`,`\x1B[39m`),gray:a(`\x1B[90m`,`\x1B[39m`),bgBlack:a(`\x1B[40m`,`\x1B[49m`),bgRed:a(`\x1B[41m`,`\x1B[49m`),bgGreen:a(`\x1B[42m`,`\x1B[49m`),bgYellow:a(`\x1B[43m`,`\x1B[49m`),bgBlue:a(`\x1B[44m`,`\x1B[49m`),bgMagenta:a(`\x1B[45m`,`\x1B[49m`),bgCyan:a(`\x1B[46m`,`\x1B[49m`),bgWhite:a(`\x1B[47m`,`\x1B[49m`),blackBright:a(`\x1B[90m`,`\x1B[39m`),redBright:a(`\x1B[91m`,`\x1B[39m`),greenBright:a(`\x1B[92m`,`\x1B[39m`),yellowBright:a(`\x1B[93m`,`\x1B[39m`),blueBright:a(`\x1B[94m`,`\x1B[39m`),magentaBright:a(`\x1B[95m`,`\x1B[39m`),cyanBright:a(`\x1B[96m`,`\x1B[39m`),whiteBright:a(`\x1B[97m`,`\x1B[39m`),bgBlackBright:a(`\x1B[100m`,`\x1B[49m`),bgRedBright:a(`\x1B[101m`,`\x1B[49m`),bgGreenBright:a(`\x1B[102m`,`\x1B[49m`),bgYellowBright:a(`\x1B[103m`,`\x1B[49m`),bgBlueBright:a(`\x1B[104m`,`\x1B[49m`),bgMagentaBright:a(`\x1B[105m`,`\x1B[49m`),bgCyanBright:a(`\x1B[106m`,`\x1B[49m`),bgWhiteBright:a(`\x1B[107m`,`\x1B[49m`),link(e,t,n){return r?`\x1b]8;;${e}\x07${n?t:X.underline(t)}\x1b]8;;\x07`:t}}})(),HO=new Set([`amount`,`suggestedDeposit`,`minVoucherDelta`]),UO={mainnet:yO[hO.mainnet],testnet:yO[hO.testnet]},WO=`0x20c0000000000000000000000000000000000000`,GO=`0x20C000000000000000000000b9537d11c60E8b50`,KO=[WO,GO],qO=[`0x20c0000000000000000000000000000000000000`,`0x20c0000000000000000000000000000000000001`,`0x20c0000000000000000000000000000000000002`,`0x20c0000000000000000000000000000000000003`]}));function YO(){let e=Number.parseInt(process.env.MPPX_KEYCHAIN_COMMAND_TIMEOUT_MS??``,10);return Number.isFinite(e)&&e>0?e:sk}function XO(e,t){return`code`in e&&e.code===`ENOENT`&&e.message.includes(t)}function ZO(e){return new I({code:`KEYCHAIN_UNAVAILABLE`,message:`Linux keyring requires secret-tool. Install libsecret-tools.`,hint:`On Debian/Ubuntu, run: sudo apt install libsecret-tools gnome-keyring dbus-x11`,exitCode:69,cause:e})}function QO(e){if(e&&XO(e,`secret-tool`))throw ZO(e)}function $O(e,t){return new Promise(n=>{m.execFile(e,t,{timeout:YO()},(e,t,r)=>{n({stdout:t.trim(),stderr:r.trim(),error:e})})})}function ek(){let e=c.join(process.env.XDG_CONFIG_HOME||c.join(b.homedir(),`.config`),`mppx`,`default`);return{get(){try{return t.readFileSync(e,`utf-8`).trim()||`main`}catch{return`main`}},set(n){t.mkdirSync(c.dirname(e),{recursive:!0}),t.writeFileSync(e,n,`utf-8`)},clear(){try{t.unlinkSync(e)}catch{}}}}function tk(e){return e||(process.env.MPPX_ACCOUNT?.trim()?process.env.MPPX_ACCOUNT:ek().get())}function nk(e=`main`){let t=ok;return{async list(){let e=b.platform();if(e===`darwin`){let{stdout:e,error:n}=await $O(`security`,[`dump-keychain`]);if(n)return[];let r=[],i=e.split(`keychain:`);for(let e of i){let n=e.match(/"svce"<blob>="([^"]*)"/),i=e.match(/"acct"<blob>="([^"]*)"/);n?.[1]===t&&i?.[1]&&r.push(i[1])}return r}if(e===`linux`){let{stdout:e,stderr:n,error:r}=await $O(`secret-tool`,[`search`,`--all`,`--unlock`,`service`,t]);if(QO(r),r)return[];let i=`${e}\n${n}`,a=[],o=i.matchAll(/\baccount = (.+)/g);for(let e of o)e[1]&&a.push(e[1]);return a}throw Error(`Unsupported platform: ${e}`)},async get(){let n=b.platform();if(n===`darwin`){let{stdout:n,error:r}=await $O(`security`,[`find-generic-password`,`-s`,t,`-a`,e,`-w`]);return r?void 0:n}if(n===`linux`){let{stdout:n,error:r}=await $O(`secret-tool`,[`lookup`,`service`,t,`account`,e]);return QO(r),r?void 0:n||void 0}throw Error(`Unsupported platform: ${n}`)},async set(n){let r=b.platform();if(r===`darwin`){await $O(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);let{error:r}=await $O(`security`,[`add-generic-password`,`-s`,t,`-a`,e,`-w`,n]);if(r)throw r;return}if(r===`linux`){let r=m.execFile(`secret-tool`,[`store`,`--label`,`${t} ${e}`,`service`,t,`account`,e]),i=setTimeout(()=>r.kill(),YO());return r.stdin?.write(n),r.stdin?.end(),new Promise((e,t)=>{r.on(`close`,n=>{clearTimeout(i),n===0?e():t(Error(`secret-tool exited with code ${n}`))}),r.on(`error`,e=>{clearTimeout(i),t(XO(e,`secret-tool`)?ZO(e):e)})})}throw Error(`Unsupported platform: ${r}`)},async delete(){let n=b.platform();if(n===`darwin`){await $O(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);return}if(n===`linux`){let{error:n}=await $O(`secret-tool`,[`clear`,`service`,t,`account`,e]);QO(n);return}throw Error(`Unsupported platform: ${n}`)}}}async function rk(e){let{privateKeyToAccount:t}=await import(`viem/accounts`),n=process.env.MPPX_PRIVATE_KEY?.trim();if(n)return{account:t(n),source:`environment`};let r=tk(e),i=await nk(r).get();if(i)return{account:t(i),accountName:r,source:`keychain`};throw Error(`Account "${r}" not found.`)}async function ik(e){let t=tk(e);if(!process.env.MPPX_PRIVATE_KEY?.trim()&&AO(t))throw new I({code:`UNSUPPORTED_ACCOUNT`,message:`Persistent sessions require an mppx account or MPPX_PRIVATE_KEY.`,exitCode:2});return rk(e).catch(e=>{throw new I({code:`ACCOUNT_NOT_FOUND`,message:e instanceof Error?e.message:`No account found.`,exitCode:69,...e instanceof Error&&{cause:e}})})}async function ak(e){return(await rk(e)).account}var ok,sk,ck=F((()=>{JO(),ok=`mppx`,sk=1e4}));mO(),ck();const lk=[[`ANTIGRAVITY_CLI_ALIAS`,`antigravity`],[`CLAUDECODE`,`claude_code`],[`CLINE_ACTIVE`,`cline`],[`CODEX_SANDBOX`,`codex_cli`],[`CODEX_THREAD_ID`,`codex_cli`],[`CODEX_SANDBOX_NETWORK_DISABLED`,`codex_cli`],[`CODEX_CI`,`codex_cli`],[`CURSOR_AGENT`,`cursor`],[`GEMINI_CLI`,`gemini_cli`],[`OPENCODE`,`open_code`],[`OPENCLAW_SHELL`,`openclaw`],[`CLAUDE_CODE_ENTRYPOINT`,`claude_code`],[`CODEX_INTERNAL_ORIGINATOR_OVERRIDE`,`codex_cli`]];function uk(e=process.env){return lk.find(([t])=>e[t])?.[1]}const dk=Symbol(`mppx.x402.asset`);function fk(e){return{[dk]:!0,address:e.address,decimals:e.decimals,network:e.network,transfer:e.transfer}}function pk(e,t){let n=e(t.chainId);return fk({address:n.address,decimals:n.decimals,network:Ck(t.chainId),transfer:Tk(t.transfer,n)})}const mk={USDC:fk({address:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,decimals:6,network:`eip155:8453`,transfer:{name:`USD Coin`,type:`eip3009`,version:`2`}})},hk={USDC:fk({address:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,decimals:6,network:`eip155:84532`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})},gk={USDC:fk({address:`0xcebA9300f2b948710d2653dD7B07f33A8B32118C`,decimals:6,network:`eip155:42220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}}),USDT:fk({address:`0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e`,decimals:6,network:`eip155:42220`,transfer:{name:`Tether USD`,type:`eip3009`,version:`1`}})},_k={USDC:fk({address:`0x01C5C0122039549AD1493B8220cABEdD739BC44E`,decimals:6,network:`eip155:11142220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})};function vk(e){return typeof e!=`object`||!e?!1:e[dk]===!0}function yk(e){return typeof e==`function`&&typeof e.addresses==`object`&&typeof e.decimals==`number`}function bk(e){return typeof e==`string`}function xk(e,t){if(vk(e))return e.network===t?{address:e.address,decimals:e.decimals,transfer:e.transfer}:void 0;if(yk(e)){let n=e.addresses[wk(t)];return n?{address:n,decimals:e.decimals,name:e.name}:void 0}return{address:e}}function Sk(e,t,n){let r=xk(e,n);return r?M(r.address)===M(t):!1}function Ck(e){return`eip155:${e}`}function wk(e){return Number(e.slice(7))}function Tk(e,t){if(e.type!==`eip3009`)return e;if(e.name)return{...e,name:e.name};if(!t.name)throw Error(`EIP-3009 token assets require a token name.`);return{...e,name:t.name}}var Ek=Qe({base:()=>mk,baseSepolia:()=>hk,celo:()=>gk,celoSepolia:()=>_k,define:()=>fk,fromToken:()=>pk,isAsset:()=>vk,isRawAddress:()=>bk,isToken:()=>yk,matches:()=>Sk,resolve:()=>xk,toChainId:()=>wk,toNetwork:()=>Ck}),Dk=Qe({base:()=>Ok,baseSepolia:()=>kk,celo:()=>Ak,celoSepolia:()=>jk});const Ok=8453,kk=84532,Ak=42220,jk=11142220;zx();function Mk(e){let t=[Rx(e.accepted),Rx(e.resource),Rx(e.extensions)].join(`|`);return ne.sha256(te.fromString(t),{as:`Hex`})}iw(),kC();async function Nk(e){let t=e.context?.account??e.config.account;if(!t?.signTypedData)throw Error(`x402 exact requires a typed-data signer.`);let n=e.challenge.request,r=oC(n);if(Lk(e.config,r),!n.resource)throw Error(`x402 exact EIP-3009 requires resource information.`);let i=n.extensions?.mppx?zk(n.extensions):n.extensions,a=r.extra?.assetTransferMethod??`eip3009`;if(a!==`eip3009`)throw Error(`x402 exact ${String(a)} signing is not implemented yet.`);let o=r.extra?.name,s=r.extra?.version;if(typeof o!=`string`||typeof s!=`string`)throw Error(`x402 exact EIP-3009 requires token name and version.`);let c=Math.floor(Date.now()/1e3),l={from:M(t.address),nonce:i?.mppx?Mk({accepted:r,extensions:i,resource:n.resource}):Vk(),to:M(r.payTo),validAfter:(c-600).toString(),validBefore:(c+r.maxTimeoutSeconds).toString(),value:r.amount},u=await t.signTypedData({domain:{chainId:Ik(r.network),name:o,verifyingContract:M(r.asset),version:s},message:{...l,value:BigInt(l.value),validAfter:BigInt(l.validAfter),validBefore:BigInt(l.validBefore)},primaryType:`TransferWithAuthorization`,types:Fk});return nw({accepted:r,...i?{extensions:i}:{},payload:{authorization:l,signature:u},...n.resource?{resource:n.resource}:{},x402Version:2})}function Pk(e){let t=e.challenge.request,n;try{n=oC(t),Lk(e.config,n)}catch{return!1}if(!t.resource||(n.extra?.assetTransferMethod??`eip3009`)!==`eip3009`)return!1;let r=n.extra?.name,i=n.extra?.version;return typeof r==`string`&&typeof i==`string`}const Fk={TransferWithAuthorization:[{name:`from`,type:`address`},{name:`to`,type:`address`},{name:`value`,type:`uint256`},{name:`validAfter`,type:`uint256`},{name:`validBefore`,type:`uint256`},{name:`nonce`,type:`bytes32`}]};function Ik(e){return Number(e.slice(lC.length))}function Lk(e,t){let n=Ik(t.network);if(e.networks&&!e.networks.includes(n))throw Error(`x402 exact chain ID is not allowed: ${n}.`);let r=e.currencies??e.assets;if(r?.some(e=>bk(e))&&!e.networks?.length)throw Error(`x402 exact raw currency allowlists require networks.`);if(r){let e=M(t.asset);if(!r.some(n=>Sk(n,e,t.network)))throw Error(`x402 exact currency is not allowed: ${e}.`)}if(e.maxAtomicAmount!==void 0&&BigInt(t.amount)>BigInt(e.maxAtomicAmount))throw Error(`x402 exact amount exceeds maxAtomicAmount.`);if(e.maxAmount!==void 0){let n=Rk(e,t);if(n===void 0)throw Error(`x402 exact maxAmount requires currency decimals.`);if(BigInt(t.amount)>N(e.maxAmount,n))throw Error(`x402 exact amount exceeds maxAmount.`)}}function Rk(e,t){let n=e.currencies??e.assets,r=M(t.asset),i=n?.find(e=>Sk(e,r,t.network)),a=i?xk(i,t.network):void 0;return a?.decimals===void 0?e.decimals:a.decimals}function zk(e){let t=e.mppx;return t?{...e,mppx:{...t,info:{...t.info,nonce:Bk()}}}:e}function Bk(){return Hk().slice(2)}function Vk(){return Hk()}function Hk(){let e=globalThis.crypto;if(!e?.getRandomValues)throw Error(`x402 exact requires crypto randomness.`);let t=e.getRandomValues(new Uint8Array(32));return`0x${Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}`}Zx();const Uk=[`authorization`],Wk=J.string().check(J.regex(/^\d+$/,`Invalid atomic amount`));J.object({name:J.string().check(J.minLength(1)),version:J.string().check(J.minLength(1))});const Gk=J.object({chainId:J.number(),credentialTypes:J.optional(J.array(J.enum(Uk)).check(J.minLength(1))),decimals:J.optional(J.number()),permit2Address:J.optional(Kx()),splits:J.optional(J.array(J.object({amount:Wk,recipient:Kx()})))});J.object({amount:Wk,currency:Kx(),description:J.optional(J.string()),externalId:J.optional(J.string()),methodDetails:Gk,recipient:Kx()});const Kk=J.object({amount:Vx(),chainId:J.number(),currency:Kx(),credentialTypes:J.optional(J.array(J.enum(Uk)).check(J.minLength(1))),decimals:J.number(),description:J.optional(J.string()),externalId:J.optional(J.string()),permit2Address:J.optional(Kx()),recipient:Kx(),splits:J.optional(J.array(J.object({amount:Wk,recipient:Kx()})))}),qk=J.object({from:Kx(),nonce:qx(),signature:Yx(),to:Kx(),type:J.literal(`authorization`),validAfter:Wk,validBefore:Wk,value:Wk}),Jk={TransferWithAuthorization:[{name:`from`,type:`address`},{name:`to`,type:`address`},{name:`value`,type:`uint256`},{name:`validAfter`,type:`uint256`},{name:`validBefore`,type:`uint256`},{name:`nonce`,type:`bytes32`}]};function Yk(e){return{chainId:e.chainId,name:e.authorization.name,verifyingContract:e.currency,version:e.authorization.version}}function Xk(e){return ne.keccak256(te.fromString(JSON.stringify([e.id,e.realm])),{as:`Hex`})}function Zk(e){return`eip155:${e}`}function Qk(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}iE(),Zx();const $k=nE({name:`evm`,intent:`charge`,schema:{credential:{payload:qk},request:J.pipe(Kk,J.transform(({amount:e,chainId:t,credentialTypes:n=[`authorization`],currency:r,decimals:i,permit2Address:a,recipient:o,splits:s,...c})=>({...c,amount:N(e,i).toString(),currency:M(r),methodDetails:{chainId:t,credentialTypes:n,decimals:i,...a?{permit2Address:M(a)}:{},...s?{splits:s}:{}},recipient:M(o)})))}});nC(),iE(),OS(),Zx();function eA(e){return rE($k,{canHandleChallenge({challenge:t}){return!tA(t)||Pk({challenge:t,config:e})},context:J.object({account:J.optional(J.custom())}),async createCredential({challenge:t,context:n}){if(tA(t))return Nk({challenge:t,config:e,context:n});let r=n?.account??e.account;if(!r?.signTypedData)throw Error(`EVM authorization requires a typed-data signer.`);let i=t.request;if(nA(e,i),!i.methodDetails.credentialTypes?.includes(`authorization`))throw Error(`EVM authorization is not accepted by this challenge.`);if(i.methodDetails.splits?.length)throw Error(`EVM authorization does not support payment splits.`);let a=rA(e,i),o=t.expires?Math.floor(new Date(t.expires).getTime()/1e3).toString():(Math.floor(Date.now()/1e3)+300).toString();return $S(QS({challenge:t,payload:{from:M(r.address),nonce:Xk(t),signature:await r.signTypedData({domain:Yk({authorization:a,chainId:i.methodDetails.chainId,currency:i.currency}),message:{from:M(r.address),nonce:Xk(t),to:M(i.recipient),validAfter:0n,validBefore:BigInt(o),value:BigInt(i.amount)},primaryType:`TransferWithAuthorization`,types:Jk}),to:M(i.recipient),type:`authorization`,validAfter:`0`,validBefore:o,value:i.amount},source:Qk({address:M(r.address),chainId:i.methodDetails.chainId})}))}})}function tA(e){return ES(e)&&e.request.scheme===`exact`&&typeof e.request.network==`string`}function nA(e,t){let n=t.methodDetails.chainId,r=Zk(n);if(e.networks&&!e.networks.includes(n))throw Error(`EVM chain ID is not allowed: ${n}.`);let i=e.currencies??e.assets;if(i?.some(e=>bk(e))&&!e.networks?.length)throw Error(`EVM raw currency allowlists require networks.`);if(i){let e=M(t.currency);if(!i.some(t=>Sk(t,e,r)))throw Error(`EVM currency is not allowed: ${e}.`)}if(e.maxAtomicAmount!==void 0&&BigInt(t.amount)>BigInt(e.maxAtomicAmount))throw Error(`EVM charge amount exceeds maxAtomicAmount.`);if(e.maxAmount!==void 0){let n=iA(e,t);if(n===void 0)throw Error(`EVM charge maxAmount requires currency decimals.`);if(BigInt(t.amount)>N(e.maxAmount,n))throw Error(`EVM charge amount exceeds maxAmount.`)}}function rA(e,t){let n=e.currencies??e.assets,r=M(t.currency),i=Zk(t.methodDetails.chainId),a=n?.find(e=>Sk(e,r,i)),o=a?xk(a,i):void 0;if(o?.transfer?.type===`eip3009`)return{name:o.transfer.name,version:o.transfer.version};if(e.authorization)return e.authorization;throw Error(`EVM authorization requires token name and version.`)}function iA(e,t){let n=e.currencies??e.assets,r=M(t.currency),i=Zk(t.methodDetails.chainId),a=n?.find(e=>Sk(e,r,i)),o=a?xk(a,i):void 0;return o?.decimals===void 0?e.decimals:o.decimals}function aA(e){return[aA.charge(e)]}(function(e){e.charge=eA,e.assets=Ek,e.chains=Dk})(aA||={});function oA(e){return e}var sA=F((()=>{}));OS(),sA();function cA(){return oA({method:`evm`,supports:e=>e.method===`evm`&&!ES(e),async setup({challenge:e}){let t=e.request,n=t.methodDetails,r=n?.chainId,i=r?lA(r):void 0,a=t.currency,o=await ak(),s=[...Object.values(mk),...Object.values(hk),...Object.values(gk),...Object.values(_k)],c=a??``;if(i&&a)try{let e=j({chain:i,transport:ue()}),t=await Oe(e,{address:a,abi:se,functionName:`symbol`});t&&(c=t)}catch{}return{tokenSymbol:c,tokenDecimals:n?.decimals??6,explorerUrl:i?.blockExplorers?.default?.url,methods:[...aA({account:o,currencies:s})]}}})}function lA(e){return Object.values(Ve).find(t=>t.id===e)}function uA(e,t){if(!Number.isInteger(t)||t<0)throw RangeError(`Decimals must be a non-negative integer.`);if(!/^-?(?:\d+(?:\.\d*)?|\.\d+)$/.test(e))throw TypeError(`Value \`${e}\` is not a valid decimal number.`);let n=e.startsWith(`-`),[r=`0`,i=``]=(n?e.slice(1):e).split(`.`),a=i.slice(0,t).padEnd(t,`0`),o=BigInt(`${r||`0`}${a}`);return i.length>t&&i[t]>=`5`&&(o+=1n),n?-o:o}Zx();const dA=J.object({customer:J.optional(J.string().check(J.minLength(1))),hooks:J.optional(J.object({inputs:J.object({tax:J.object({calculation:J.string().check(J.minLength(1))})})})),metadata:J.optional(J.record(J.string(),J.string())),receipt_email:J.optional(J.string().check(J.minLength(1)))}),fA=J.custom(e=>typeof e==`function`),pA=J.union([dA,fA]);iE(),Zx();const mA=nE({name:`stripe`,intent:`charge`,schema:{credential:{payload:J.object({externalId:J.optional(J.string()),spt:J.string()})},request:J.pipe(J.object({amount:Vx(),currency:J.string(),decimals:J.number(),description:J.optional(J.string()),externalId:J.optional(J.string()),metadata:J.optional(J.record(J.string(),J.string())),networkId:J.string(),paymentIntentOptions:J.optional(pA),paymentMethodTypes:J.array(J.string()).check(J.minLength(1)),recipient:J.optional(J.string())}),J.transform(({amount:e,decimals:t,metadata:n,networkId:r,paymentIntentOptions:i,paymentMethodTypes:a,...o})=>({...o,amount:uA(e,t).toString(),methodDetails:{networkId:r,paymentMethodTypes:a,...n!==void 0&&{metadata:n}}})))}});nC(),iE(),Zx();function hA(e){let{client:t,createToken:n,externalId:r,paymentMethod:i}=e;return rE(mA,{context:J.object({paymentMethod:J.optional(J.string())}),async createCredential({challenge:e,context:a}){let o=a?.paymentMethod??i;if(!o)throw Error(`paymentMethod is required (pass via context or parameters)`);let s=e.request.amount,c=e.request.currency,l=typeof e.request.externalId==`string`?e.request.externalId:void 0,u=e.request.methodDetails?.networkId;if(!u)throw Error(`networkId is required in challenge.methodDetails`);let d=e.request.methodDetails?.metadata;if(d?.externalId)throw Error(`methodDetails.metadata.externalId is reserved; use credential externalId instead`);let f=e.expires?Math.floor(new Date(e.expires).getTime()/1e3):Math.floor(Date.now()/1e3)+3600,p=await n({amount:s,challenge:e,client:t,currency:c,expiresAt:f,metadata:d,networkId:u,paymentMethod:o}),m=l??r;return $S({challenge:e,payload:{spt:p,...m===void 0?{}:{externalId:m}}})}})}function gA(e){return[hA(e)]}(function(e){e.charge=hA})(gA||={}),Ox(),JO(),sA();function _A(){return oA({method:`stripe`,supports(e){return e.method===`stripe`&&e.intent===`charge`},async setup({challenge:e,methodOpts:t}){let n=e.request,r=n.currency,i=yA(p.object({paymentMethod:p.string(),secretKey:p.string().optional()}),t,[`paymentMethod`,`secretKey`]),a=i.secretKey??process.env.MPPX_STRIPE_SECRET_KEY;if(!a)throw new I({code:`MISSING_ENV`,message:`MPPX_STRIPE_SECRET_KEY environment variable is required for Stripe payments.`,exitCode:2});return{tokenSymbol:r?.toUpperCase()??``,tokenDecimals:n.decimals??2,methods:[gA.charge({paymentMethod:i.paymentMethod,createToken:async({paymentMethod:e,amount:t,currency:n,networkId:r,expiresAt:i,metadata:o})=>{let s=new URLSearchParams({payment_method:e,"usage_limits[currency]":n,"usage_limits[max_amount]":t,"usage_limits[expires_at]":i.toString()}),c=vA(a),l=process.env.MPPX_STRIPE_SPT_URL?process.env.MPPX_STRIPE_SPT_URL:c?`https://api.stripe.com/v1/test_helpers/shared_payment/granted_tokens`:`https://api.stripe.com/v1/shared_payment/issued_tokens`;if(r){let e=c?`seller_details[network_id]`:`seller_details[network_business_profile]`;s.set(e,r)}if(o)for(let[e,t]of Object.entries(o))s.set(`metadata[${e}]`,t);let u={Authorization:`Basic ${btoa(`${a}:`)}`,"Content-Type":`application/x-www-form-urlencoded`,"Stripe-Version":`2026-07-29.preview`},d=await globalThis.fetch(l,{method:`POST`,headers:u,body:s});if(!d.ok){let a=await d.json();if(c&&(o||r)&&a.error.message.includes(`Received unknown parameter`)){let r=new URLSearchParams({payment_method:e,"usage_limits[currency]":n,"usage_limits[max_amount]":t,"usage_limits[expires_at]":i.toString()});if(d=await globalThis.fetch(l,{method:`POST`,headers:u,body:r}),!d.ok){let e=await d.json();throw new I({code:`STRIPE_ERROR`,message:`Failed to create SPT: ${e.error.message}`,exitCode:77})}}else throw new I({code:`STRIPE_ERROR`,message:`Failed to create SPT: ${a.error.message}`,exitCode:77})}let{id:f}=await d.json();return f}})]}},formatReceiptField(e,t){if(e===`reference`&&typeof t==`string`&&t.startsWith(`pi_`)){let e=process.env.MPPX_STRIPE_SECRET_KEY,n=`https://dashboard.stripe.com${e!==void 0&&vA(e)?`/test`:``}/payments/${t}`;return X.link(n,t,!0)}}})}function vA(e){return e.startsWith(`sk_test_`)||e.startsWith(`rk_test_`)}function yA(e,t,n){if(t&&typeof t==`object`&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!n.includes(e));if(e.length)throw Error(`Unsupported CLI method option(s): ${e.join(`, `)}`)}let r=e.safeParse(t??{});if(r.success)return r.data;let i=r.error.issues.map(e=>`${e.path.length?e.path.join(`.`):`options`}: ${e.message}`).join(`, `);throw Error(`Invalid CLI options (${i})`)}function bA(e={}){let{account:t}=e;return(e,{account:n}={})=>{let r=n??t;if(!r){if(!e.account)throw Error("No `account` provided. Pass `account` to parameters or context.");return e.account}return _e(r)}}var xA=F((()=>{}));function SA(e){return Object.fromEntries(Object.entries(e.headers??{}).filter(([e])=>e.toLowerCase()!==`content-type`))}var CA=F((()=>{}));function wA(e,t={}){return ue(e.url,{fetchFn:e.fetch,fetchOptions:{headers:SA(e)},...t})}function TA(e){let{chain:t,getClient:n,remoteFeePayer:r,rpcUrl:i}=e;return n?!t?.serializers&&!r?n:async e=>{let i=await n(e),a=i;if(r&&i.transport.key!==`feePayer`){let e=i.request.bind(i),t=Be(ae({request:t=>e(t)},{retryCount:0}),wA(r,{retryCount:i.transport.retryCount}))({account:i.account,chain:i.chain,pollingInterval:i.pollingInterval,retryCount:0}),n=ie({...t.config,retryCount:0},t.value);a=Object.assign({},i,{request:n.request,transport:{...n.config,...n.value}})}return!t?.serializers||a.chain?.serializers?.transaction?a:Object.assign({},a,{chain:{...t,...e.chainId===void 0?{}:{id:e.chainId},...a.chain,formatters:a.chain?.formatters??t.formatters,prepareTransactionRequest:a.chain?.prepareTransactionRequest??t.prepareTransactionRequest,serializers:a.chain?.serializers?.transaction?a.chain.serializers:t.serializers}})}:({chainId:e})=>{if(!i)throw Error("No `rpcUrl` provided.");let n=e||Number(Object.keys(i)[0]),a=i[n];if(!a)throw Error(`No \`rpcUrl\` configured for \`chainId\` (${n}).`);let o=r?Be(ue(a),wA(r)):ue(a);return j({chain:OA[n]??{...t,id:n},transport:o})}}function EA(e,t){if(t!==void 0&&e.chain?.id!==void 0&&e.chain.id!==t)throw Error(`Chain ID mismatch: expected ${t}, got ${e.chain.id}.`)}function DA(e,t){if(e!==void 0&&(t===void 0||!e.includes(t)))throw Error(`Chain ID not allowed: ${t??`unknown`}.`)}var OA,kA=F((()=>{CA(),OA={[ye.id]:ye,[be.id]:be}}));function AA(e){let t=ne.keccak256(te.fromString(e),{as:`Hex`});return re.toBytes(re.slice(t,0,10))}function jA(e){let{serverId:t,clientId:n,challengeId:r}=e,i=new Uint8Array(32);return i.set(re.toBytes(NA),0),i[4]=PA,i.set(AA(t),5),n&&i.set(AA(n),15),i.set(MA(r),25),re.fromBytes(i)}function MA(e){let t=ne.keccak256(te.fromString(e),{as:`Hex`});return re.toBytes(re.slice(t,0,7))}var NA,PA,FA=F((()=>{NA=re.slice(ne.keccak256(te.fromString(`mpp`),{as:`Hex`}),0,4),PA=1}));function IA(e,t){return Ke.resolve(e).toLowerCase()===Ke.resolve(t).toLowerCase()}var LA=F((()=>{}));async function RA(e,t){let{account:n,amountOut:r,tokenOut:i,tokenIn:a,slippage:o}=t,s=a.filter(e=>!IA(e,i)),c=await Promise.allSettled([Oe(e,Ie.token.getBalance.call(e,{account:n,token:i})),...s.map(t=>Oe(e,Ie.token.getBalance.call(e,{account:n,token:t})))]),l=c[0];if(!(l.status===`fulfilled`&&l.value>=r)){for(let t=0;t<s.length;t++){let n=c[t+1];if(n.status!==`fulfilled`)continue;let a=n.value;if(a<=0n)continue;let l=s[t];try{let t=await Ie.dex.getBuyQuote(e,{tokenIn:l,tokenOut:i,amountOut:r});if(a>=t){let n=t+t*BigInt(Math.round(o*100))/BA;return[Ie.token.approve.call(e,{amount:n,spender:Le.stablecoinDex,token:l}),Ie.dex.buy.call({tokenIn:l,tokenOut:i,amountOut:r,maxAmountIn:n})]}}catch{}}throw new HA({currency:i})}}function zA(e,t){return e?e===!0?{tokenIn:t,slippage:1}:{tokenIn:e.tokenIn?[...e.tokenIn,...t.filter(t=>!e.tokenIn.some(e=>IA(e,t)))]:t,slippage:e.slippage??1}:!1}var BA,VA,HA,UA=F((()=>{LA(),bO(),BA=10000n,VA=[gO.pathUsd,gO.usdc],HA=class extends Error{name=`InsufficientFundsError`;constructor({currency:e}){super(`Insufficient funds: no balance in ${e} and no viable swap route from fallback currencies.`)}}}));function WA(e){let t=BigInt(e.amount),n=e.methodDetails?.splits??[],r=n.reduce((e,t)=>e+BigInt(t.amount),0n);if(r>=t)throw Error(`Invalid charge request: split total must be less than total amount.`);let i=t-r;if(i<=0n)throw Error(`Invalid charge request: primary transfer amount must be positive.`);return[{amount:i.toString(),memo:e.methodDetails?.memo,recipient:e.recipient},...n.map(e=>({amount:e.amount,memo:e.memo,recipient:e.recipient}))]}var GA=F((()=>{}));function KA(e,t,n){t&&(n&&!n.some(e=>IA(e,t))||e.some(e=>IA(e,t))||e.push(t))}async function qA(e,t,n){try{return(await Ie.token.getBalance(e,{account:t,token:n})).amount>0n}catch{return!1}}function JA(e){let t=e.chain?.feeToken;if(t)return Re.toAddress(t);let n=e.chain?.id;return n?_O[n]:void 0}function YA(e){let t=[];return KA(t,gO.pathUsd),KA(t,_O[e]),t}async function XA(e){let{account:t,allowedTokens:n,candidateTokens:r,client:i,prioritizeCandidates:a}=e,o=[];if(a)for(let e of r??[])KA(o,e,n);if(KA(o,await Ie.fee.getUserToken(i,{account:t}).then(e=>e?.address).catch(()=>void 0),n),KA(o,JA(i),n),!a)for(let e of r??[])KA(o,e,n);for(let e of o)if(await qA(i,t,e))return e;return o[0]}var ZA=F((()=>{LA(),bO()}));function QA(e){if(e!==void 0)return vO[e]}function $A(e){let t=QA(e.chainId);return!!t&&de(e.currency,{strict:!1})&&fe(e.currency,t.token)}function ej(e){let t=QA(e.chainId),n=e.transfers.length===1?e.transfers[0]:void 0;if(!t||!n?.memo)return;let r=BigInt(n.amount),i=n.memo;return{calls:[{data:oe({abi:Pe.tip20,functionName:`approve`,args:[t.swap,r]}),to:t.token},{data:oe({abi:nj,functionName:`swapTo`,args:[t.token,r,e.currency,n.recipient,i]}),to:t.swap}],settlementSender:t.swap,transfers:[{amount:r,memo:i,recipient:n.recipient}]}}async function tj(e,t){let n=ej(t);if(n)try{return await Oe(e,Ie.token.getBalance.call(e,{account:t.account,token:n.calls[0].to}))<n.transfers[0].amount?void 0:(await Ee(e,{account:t.account,calls:n.calls}),n)}catch{return}}var nj,rj=F((()=>{bO(),nj=me([`function swapTo(address inputToken,uint256 amount,address targetToken,address recipient,bytes32 memo)`])}));function ij(e){return{name:`MPP`,version:`3`,chainId:e}}function aj(e){let{account:t,challengeId:n,realm:r}=e;return{account:t,challengeId:n,realm:r}}function oj(e){let{account:t,chainId:n,challengeId:r,realm:i}=e;return{domain:ij(n),types:lj,primaryType:cj,message:aj({account:t,challengeId:r,realm:i})}}function sj(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}var cj,lj,uj=F((()=>{cj=`Proof`,lj={Proof:[{name:`account`,type:`address`},{name:`challengeId`,type:`string`},{name:`realm`,type:`string`}]}}));function dj(e={}){let{clientId:t}=e;if((e.maxAmount!==void 0||e.maxAtomicAmount!==void 0)&&e.currencies===void 0)throw Error(`Tempo charge maxAmount and maxAtomicAmount require currencies.`);let n={maxAmount:pj(e.maxAmount,e.decimals),maxAtomicAmount:e.maxAtomicAmount===void 0?void 0:BigInt(e.maxAtomicAmount)},r=TA({chain:ye,getClient:e.getClient,rpcUrl:yO}),i=bA({account:e.account}),a=rE(_E,{canHandleChallenge({challenge:t}){try{return mj(e,n,t.request),!0}catch{return!1}},context:hj,async createCredential({challenge:a,context:o}){mj(e,n,a.request);let s=a.request.methodDetails?.chainId??e.expectedChainId??(e.allowedChainIds?.length===1?e.allowedChainIds[0]:void 0),c=await r({chainId:s});EA(c,s);let l=s??c.chain?.id;if(DA(e.allowedChainIds,l),l===void 0)throw Error("No `chainId` provided. Pass a chain ID in the challenge or client.");let{request:u}=a,{amount:d,methodDetails:f}=u,p=f?.supportedModes??[`pull`,`push`],m=i(c,o),h=async t=>await e.resolveAccount?.({account:m,chainId:l,operation:t})??m;if(BigInt(d)===0n){let e=await h({kind:`signPaymentProof`});return $S({challenge:a,payload:{signature:await Me(c,{account:e,...oj({account:e.address,chainId:l,challengeId:a.id,realm:a.realm})}),type:`proof`},source:sj({address:e.address,chainId:l})})}let g=u.currency,_=$A({chainId:l,currency:g}),v=jA({challengeId:a.id,clientId:t,serverId:a.realm}),y=WA({amount:d,methodDetails:{...f,memo:v},recipient:u.recipient}),b=y.map(e=>Ie.token.transfer.call(c,{amount:BigInt(e.amount),...e.memo&&{memo:e.memo},to:e.recipient,token:g})),x=zA(o?.autoSwap??e.autoSwap,VA),S=f?.machineTokenEnabled===!0?ej({chainId:l,currency:g,transfers:y}):void 0,C=m,w;if(S){let e=await(async()=>{try{return await h({calls:S.calls,kind:`executeCalls`})}catch{return}})();e&&(w=await tj(c,{account:e.address,chainId:l,currency:g,transfers:y}),w&&(C=e))}let T;w||(C=await h({kind:`executeCalls`,...x?{}:{calls:b}}),T=x?await RA(c,{account:C.address,amountOut:BigInt(d),tokenOut:g,tokenIn:x.tokenIn,slippage:x.slippage}):void 0);let ee=w?.calls??[...T??[],...b],E=YA(l),D=w||_?await XA({account:C.address,allowedTokens:E,candidateTokens:E,client:c,prioritizeCandidates:!0}):void 0,O=(()=>{let t=o?.mode??e.mode;if(t){if(!p.includes(t))throw Error(`Challenge does not support ${t} mode.`);return t}let n=C.type===`json-rpc`?`push`:`pull`;return p.includes(n)?n:p[0]})(),k=(()=>{let e=Math.floor(Date.now()/1e3)+25;if(!a.expires)return e;let t=Math.floor(new Date(a.expires).getTime()/1e3)+1;return Math.min(e,t)})();if(O===`push`){let{receipts:e}=C.type===`local`?{receipts:[await Ae(c,{account:C,calls:ee,...D?{feeToken:D}:{},nonceKey:`expiring`,validBefore:k})]}:await ke(c,{account:C,...D?{capabilities:{feeToken:D}}:{},calls:ee,experimental_fallback:ee.length===1,forceAtomic:ee.length>1}),t=e?.[0]?.transactionHash;if(!t)throw Error(`No transaction receipt returned.`);return $S({challenge:a,payload:{hash:t,type:`hash`},source:sj({address:C.address,chainId:l})})}let te=await De(c,{account:C,calls:ee,...D?{feeToken:D}:{},nonceKey:`expiring`,validBefore:k});if(te.gas=(te.gas??0n)+5000n,f?.feePayer){let e=te;delete e.feePayerSignature,delete e.feeToken,e.feePayer=!0}return $S({challenge:a,payload:{signature:await je(c,te),type:`transaction`},source:sj({address:C.address,chainId:l})})}}),o=new Map,s=async t=>{mj(e,n,t.challenge.request);let r=t.context?.account??e.account,i=`${(typeof r==`string`?r:r?.address)?.toLowerCase()??``}:${t.challenge.id}`,s=o.get(i);return s||(s=a.createCredential(t).finally(()=>o.delete(i)),o.set(i,s)),s};return bw({...a,createCredential:s},fj)}function fj(e){let t=_E.schema.credential.payload.safeParse(YS(e).payload);if(!t.success)return;let n=t.data;if(n.type===`hash`)return n.hash;let r=n.signature;if(n.type!==`transaction`||!r.startsWith(qe.serializedType))return;let i=qe.deserialize(r);if(!(!i.signature||i.feePayerSignature===null)&&qe.serialize(i)===r)return pe(r)}function pj(e,t){if(e!==void 0){if(t===void 0)throw Error(`Tempo charge maxAmount requires currency decimals.`);if((e.split(`.`)[1]?.replace(/0+$/,``)??``).length>t)throw Error(`Tempo charge maxAmount ${e} has more fractional digits than ${t} decimals allow.`);return N(e,t)}}function mj(e,t,n){let{amount:r,methodDetails:i,recipient:a}=n,o=i?.chainId;if(e.expectedChainId!==void 0&&o!==void 0&&o!==e.expectedChainId)throw Error(`Chain ID mismatch: expected ${e.expectedChainId}, got ${o}.`);if((o!==void 0||e.allowedChainIds?.length===0)&&DA(e.allowedChainIds,o),e.currencies&&!e.currencies.some(e=>e.toLowerCase()===n.currency.toLowerCase()))throw Error(`Tempo charge currency is not allowed: ${n.currency}.`);if(e.expectedRecipients){let t=new Set(e.expectedRecipients.map(e=>e.toLowerCase()));if(!a||!t.has(a.toLowerCase()))throw Error(`Unexpected primary recipient: ${a}`);let n=i?.splits;if(n){for(let e of n)if(!t.has(e.recipient.toLowerCase()))throw Error(`Unexpected split recipient: ${e.recipient}`)}}if(t.maxAtomicAmount!==void 0&&BigInt(r)>t.maxAtomicAmount)throw Error(`Tempo charge amount exceeds maxAtomicAmount.`);if(t.maxAmount!==void 0&&BigInt(r)>t.maxAmount)throw Error(`Tempo charge amount exceeds maxAmount.`)}var hj,gj=F((()=>{Tw(),nC(),iE(),xA(),kA(),Zx(),FA(),UA(),GA(),bO(),ZA(),rj(),uj(),bE(),hj=J.object({account:J.optional(J.custom()),autoSwap:J.optional(J.custom()),mode:J.optional(J.enum(sE))})}));function _j(e){return BigInt(e.authorizedSigner)===0n?e.payer:e.authorizedSigner}function vj(e){let t=O.encode(O.from([`address payer`,`address payee`,`address operator`,`address token`,`bytes32 salt`,`address authorizedSigner`,`bytes32 expiringNonceHash`,`address escrow`,`uint256 chainId`]),[e.payer,e.payee,e.operator,e.token,e.salt,e.authorizedSigner,e.expiringNonceHash,e.escrow??`0x4d50500000000000000000000000000000000000`,BigInt(e.chainId)]);return ne.keccak256(t)}function yj(e){return qe.encodeForSigning(e)}function bj(e){let{feePayer:t,transaction:n}=e;return t?{...n,feePayerSignature:null}:n}function xj(e,t){return ne.keccak256(re.concat(yj(e),t.sender))}var Sj=F((()=>{UE()})),Cj,wj,Tj,Ej,Dj=F((()=>{Cj=[{name:`payer`,type:`address`},{name:`payee`,type:`address`},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`salt`,type:`bytes32`},{name:`authorizedSigner`,type:`address`},{name:`expiringNonceHash`,type:`bytes32`}],wj=[{name:`settled`,type:`uint96`},{name:`deposit`,type:`uint96`},{name:`closeRequestedAt`,type:`uint32`}],Tj={name:`descriptor`,type:`tuple`,components:Cj},Ej=[{type:`function`,name:`CLOSE_GRACE_PERIOD`,stateMutability:`view`,inputs:[],outputs:[{type:`uint64`}]},{type:`function`,name:`VOUCHER_TYPEHASH`,stateMutability:`view`,inputs:[],outputs:[{type:`bytes32`}]},{type:`function`,name:`open`,stateMutability:`nonpayable`,inputs:[{name:`payee`,type:`address`},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`deposit`,type:`uint96`},{name:`salt`,type:`bytes32`},{name:`authorizedSigner`,type:`address`}],outputs:[{name:`channelId`,type:`bytes32`}]},{type:`function`,name:`settle`,stateMutability:`nonpayable`,inputs:[Tj,{name:`cumulativeAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`topUp`,stateMutability:`nonpayable`,inputs:[Tj,{name:`additionalDeposit`,type:`uint96`}],outputs:[]},{type:`function`,name:`close`,stateMutability:`nonpayable`,inputs:[Tj,{name:`cumulativeAmount`,type:`uint96`},{name:`captureAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`requestClose`,stateMutability:`nonpayable`,inputs:[Tj],outputs:[]},{type:`function`,name:`withdraw`,stateMutability:`nonpayable`,inputs:[Tj],outputs:[]},{type:`function`,name:`getChannel`,stateMutability:`view`,inputs:[Tj],outputs:[{type:`tuple`,components:[{name:`descriptor`,type:`tuple`,components:Cj},{name:`state`,type:`tuple`,components:wj}]}]},{type:`function`,name:`getChannelState`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`}],outputs:[{type:`tuple`,components:wj}]},{type:`function`,name:`getChannelStatesBatch`,stateMutability:`view`,inputs:[{name:`channelIds`,type:`bytes32[]`}],outputs:[{type:`tuple[]`,components:wj}]},{type:`function`,name:`computeChannelId`,stateMutability:`view`,inputs:[{name:`payer`,type:`address`},{name:`payee`,type:`address`},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`salt`,type:`bytes32`},{name:`authorizedSigner`,type:`address`},{name:`expiringNonceHash`,type:`bytes32`}],outputs:[{type:`bytes32`}]},{type:`function`,name:`getVoucherDigest`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}],outputs:[{type:`bytes32`}]},{type:`function`,name:`domainSeparator`,stateMutability:`view`,inputs:[],outputs:[{type:`bytes32`}]},{type:`event`,name:`ChannelOpened`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`authorizedSigner`,type:`address`},{name:`salt`,type:`bytes32`},{name:`expiringNonceHash`,type:`bytes32`},{name:`deposit`,type:`uint96`}]},{type:`event`,name:`Settled`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`cumulativeAmount`,type:`uint96`},{name:`deltaPaid`,type:`uint96`},{name:`newSettled`,type:`uint96`}]},{type:`event`,name:`TopUp`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`additionalDeposit`,type:`uint96`},{name:`newDeposit`,type:`uint96`}]},{type:`event`,name:`CloseRequested`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`closeGraceEnd`,type:`uint256`}]},{type:`event`,name:`ChannelClosed`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`settledToPayee`,type:`uint96`},{name:`refundedToPayer`,type:`uint96`}]},{type:`event`,name:`CloseRequestCancelled`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0}]}]}));function Oj(e,t){return{name:Ij,version:Lj,chainId:t,verifyingContract:e}}function kj(e,t){return Ue.getVoucherSignPayload({chainId:e,channelId:t.channelId,cumulativeAmount:t.cumulativeAmount})}function Aj(e,t,n){return e.toLowerCase()===Ue.address.toLowerCase()?kj(t,n):le({domain:Oj(e,t),types:Rj,primaryType:`Voucher`,message:{channelId:n.channelId,cumulativeAmount:n.cumulativeAmount}})}function jj(e){return e===`secp256k1`||e===`p256`||e===`webAuthn`}function Mj(e,t){return Fe.signVoucher(e,{chainId:t.chainId,channel:t.channelId,cumulativeAmount:t.cumulativeAmount})}async function Nj(e,t,n,r,i){let a=await(async()=>{if(r.toLowerCase()===Ue.address.toLowerCase())try{return await Mj(t,{chainId:i,channelId:n.channelId,cumulativeAmount:n.cumulativeAmount})}catch{}return Me(e,{account:t,domain:Oj(r,i),types:Rj,primaryType:`Voucher`,message:n})})(),o=Ge.from(a);if(!jj(o.type))throw Error(`TIP-1034 vouchers require a TIP-1020 primitive signature; received "${o.type}".`);return Ge.serialize(o)}async function Pj(e,t,n,r,i){let a=await Me(e,{account:t,domain:Oj(r,i),types:zj,primaryType:`CloseAuthorization`,message:n}),o=Ge.from(a);if(!jj(o.type))throw Error(`TIP-1034 close authorizations require a TIP-1020 primitive signature; received "${o.type}".`);return Ge.serialize(o)}function Fj(e,t,n,r){try{let i=Ge.from(n.signature);if(!jj(i.type)||Ge.serialize(i).toLowerCase()!==n.signature.toLowerCase())return!1;let a=Aj(e,t,n),o=Ge.extractAddress({payload:a,signature:i});return Ge.verify(i,{address:o,payload:a})&&IA(o,r)}catch{return!1}}var Ij,Lj,Rj,zj,Bj=F((()=>{LA(),Ij=`TIP20 Channel Reserve`,Lj=`1`,Rj={Voucher:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]},zj={CloseAuthorization:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]}}));function Vj(e){return typeof e==`object`&&!!e}function Hj(e){return typeof e==`string`&&de(e,{strict:!1})?e:void 0}function Uj(e){return Hj(e.accessKeyAddress)}function Wj(){let e=BigInt(Math.floor(Date.now()/1e3))-60n;return e<=0n?0:Number(BigInt(re.random(8))%e)}function Gj(e){return Uj(e)??e.address}async function Kj(e,t){let{account:n,calls:r,feePayer:i,feeToken:a,validAfter:o}=t;return De(e,{account:n,calls:r,nonceKey:`expiring`,...i?{feePayer:!0}:{},feeToken:a,...o===void 0?{}:{validAfter:o}})}async function qj(e,t){return await je(e,t)}function Jj(e,t,n=!1){let r=e.request.methodDetails,i=Vj(r)?Hj(r.escrowContract)??Hj(r.escrow):void 0,a=t??`0x4d50500000000000000000000000000000000000`;if(i&&!Xj(i,a)&&(!n||t!==void 0))throw Error(`Tempo session escrow ${i} does not match client escrow ${a}.`);return i&&!Xj(i,a)?i:a}function Yj(e,t,n,r){return $S({challenge:e,payload:t,source:`did:pkh:eip155:${n}:${r.address}`})}function Xj(e,t){return e.toLowerCase()===t.toLowerCase()}async function Zj(e,t,n,r,i,a=HE){let o=vj({...n,chainId:i,escrow:a}),s=CE(r),c=await Nj(e,t,{channelId:o,cumulativeAmount:s},a,i);return{action:`voucher`,channelId:o,descriptor:n,cumulativeAmount:s.toString(),signature:c}}async function Qj(e,t,n,r,i,a=HE){let o=await Zj(e,t,n,r,i,a),s=await Pj(e,t,{channelId:o.channelId,cumulativeAmount:CE(BigInt(o.cumulativeAmount))},a,i);return{action:`close`,channelId:o.channelId,descriptor:n,cumulativeAmount:o.cumulativeAmount,signature:o.signature,closeSignature:s}}async function $j(e,t,n){let r=Gj(t),i=n.escrow??`0x4d50500000000000000000000000000000000000`,a=n.operator??`0x0000000000000000000000000000000000000000`,o=re.random(32),s=CE(n.deposit),c=CE(n.initialAmount),l=oe({abi:Ej,functionName:`open`,args:[n.payee,a,n.token,s,o,r]}),u=await qj(e,await Kj(e,{account:t,calls:[...n.prefixCalls??[],{to:i,data:l}],feePayer:n.feePayer,feeToken:n.feeToken??n.token})),d=ze.deserialize(u),f={authorizedSigner:r,expiringNonceHash:xj(bj({...n.feePayer?{feePayer:!0}:{},transaction:d}),{sender:t.address}),operator:a,payee:n.payee,payer:t.address,salt:o,token:n.token},p=vj({...f,chainId:n.chainId,escrow:i});return{action:`open`,type:`transaction`,channelId:p,transaction:u,signature:await Nj(e,t,{channelId:p,cumulativeAmount:c},i,n.chainId),descriptor:f,cumulativeAmount:c.toString(),authorizedSigner:f.authorizedSigner}}async function eM(e,t,n,r,i,a,o=HE,s=[],c=n.token){let l=vj({...n,chainId:i,escrow:o}),u=CE(r);return{action:`topUp`,type:`transaction`,channelId:l,transaction:await qj(e,await Kj(e,{account:t,calls:[...s,{to:o,data:oe({abi:Ej,functionName:`topUp`,args:[n,u]})}],feePayer:a,feeToken:c,validAfter:Wj()})),descriptor:n,additionalDeposit:u.toString()}}var tM=F((()=>{nC(),Sj(),Dj(),UE(),Bj()}));function nM(e){let{payee:t,token:n,escrow:r,chainId:i}=e;return`${t.toLowerCase()}:${n.toLowerCase()}:${r.toLowerCase()}:${i}`}function rM(e){return nM({payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId})}function iM(){let e=new Map;return{get:t=>e.get(t),set(t){e.set(rM(t),t)},delete(t){e.delete(t)}}}function aM(e){return{...e,cumulativeAmount:e.cumulativeAmount.toString(),deposit:e.deposit.toString()}}function oM(e){return{...e,cumulativeAmount:BigInt(e.cumulativeAmount),deposit:BigInt(e.deposit)}}var sM=F((()=>{}));function cM(e){if(e<0n||e>dM)throw new Y({reason:`amount exceeds uint96 range`})}async function lM(e,t,n=HE,r){return uM(await Oe(e,{address:n,abi:Ej,functionName:`getChannelState`,args:[t],...r===void 0?{}:{blockNumber:r}}))}function uM(e){return cM(e.settled),cM(e.deposit),{settled:e.settled,deposit:e.deposit,closeRequestedAt:e.closeRequestedAt}}var dM,fM=F((()=>{SS(),Dj(),UE(),dM=2n**96n-1n}));function pM(e){return`cumulativeAmount`in e}function mM(e){if(pM(e))return BigInt(e.cumulativeAmount)}async function hM(e,t){t.opened?await e.store.set(t):await e.store.delete(rM(t)),e.notifyUpdate(t)}async function gM(e,t,n){let r=mM(n);if(r===void 0)return;let i=await e.store.get(t);i&&i.channelId.toLowerCase()===n.channelId.toLowerCase()&&(i.cumulativeAmount=i.cumulativeAmount>r?i.cumulativeAmount:r,n.action===`close`&&(i.opened=!1),await hM(e,i))}function _M(e){return e?.action!==void 0}function vM(e){return _M(e)&&e.descriptor!==void 0}function yM(e,t,n){let r=n===`additionalDeposit`?e.additionalDepositRaw:e.cumulativeAmountRaw,i=n===`additionalDeposit`?e.additionalDeposit:e.cumulativeAmount;if(r)return BigInt(r);if(i)return N(i,t)}function bM(e,t,n,r){let i=yM(e,t,n);if(i===void 0)throw Error(`${n} required for ${r} action`);return i}function xM(e){return typeof e==`object`&&!!e}function SM(e){return typeof e==`string`&&de(e,{strict:!1})?e:void 0}function CM(e){let t=e.request.methodDetails;return xM(t)?{chainId:typeof t.chainId==`number`?t.chainId:void 0,escrowContract:SM(t.escrowContract),escrow:SM(t.escrow),feePayer:typeof t.feePayer==`boolean`?t.feePayer:void 0,feeToken:SM(t.feeToken),operator:SM(t.operator),sessionSnapshot:kx(t,Nx.sessionSnapshot)}:{}}function wM(e,t){if(typeof e==`string`&&de(e,{strict:!1}))return e;throw Error(`tempo session challenge missing ${t}`)}function TM(e){if(typeof e==`string`)return BigInt(e);throw Error(`tempo session challenge missing amount`)}function EM(e){return typeof e==`string`?e:void 0}async function DM(e){let{allowCustomEscrow:t,challenge:n,escrowOverride:r,allowedChainIds:i,getClient:a}=e,o=CM(n);(o.chainId!==void 0||i?.length===0)&&DA(i,o.chainId);let s=o.chainId??(i?.length===1?i[0]:void 0),c=await a({chainId:s});EA(c,s);let l=s??c.chain?.id;if(DA(i,l),!l)throw Error(`No chainId configured for TIP-1034 session challenge.`);let u=Jj(n,r,t),d=wM(n.request.recipient,`recipient`),f=wM(n.request.currency,`currency`);return{amount:TM(n.request.amount),challenge:n,chainId:l,client:c,escrow:u,feePayer:o.feePayer,feeToken:o.feeToken,key:nM({payee:d,token:f,escrow:u,chainId:l}),operator:o.operator,payee:d,snapshot:o.sessionSnapshot,suggestedDepositRaw:EM(n.request.suggestedDeposit),token:f}}async function OM(e){let{channelId:t,client:n,descriptor:r,expected:i,readChannelState:a=lM}=e,o=vj({...r,chainId:i.chainId,escrow:i.escrow});kM({channelId:t,descriptor:r,expectedChannelId:o,payee:i.payee,payer:i.payer,authorizedSigner:i.authorizedSigner,token:i.token});let s=await a(n,o,i.escrow);if(s.deposit===0n)throw Error(`Channel ${o} cannot be reused (closed or not found on-chain).`);if(s.closeRequestedAt!==0)throw Error(`Channel ${o} cannot be reused (pending close request).`);return{channelId:o,state:s}}function kM(e){let{authorizedSigner:t,channelId:n,descriptor:r,expectedChannelId:i,payee:a,payer:o,token:s}=e;if(n&&n.toLowerCase()!==i.toLowerCase())throw Error(`context channelId does not match descriptor`);if(!Xj(r.payee,a))throw Error(`context descriptor payee does not match challenge`);if(!Xj(r.token,s))throw Error(`context descriptor token does not match challenge`);if(!Xj(r.payer,o))throw Error(`context descriptor payer does not match account`);if(!Xj(_j(r),t))throw Error(`context descriptor authorizedSigner does not match account`)}function AM(e){let{context:t,snapshot:n}=e,r=t?.descriptor??n?.descriptor;if(r)return{...t,channelId:t?.channelId??n?.channelId,descriptor:r}}function jM(e){let{context:t,decimals:n,requestAmount:r,snapshot:i,settled:a}=e;if(i)return[BigInt(i.acceptedCumulative),BigInt(i.requiredCumulative),BigInt(i.spent)+r,a].reduce((e,t)=>t>e?t:e,0n);let o=yM(t,n,`cumulativeAmount`);return o===void 0?a+r:o+r}async function MM(e){let{account:t,client:n,readChannelState:r,snapshot:i}=e,a=i.highestVoucher;if(!a)throw Error(`session snapshot is missing its highest signed voucher`);if(a.channelId.toLowerCase()!==i.channelId.toLowerCase())throw Error(`session snapshot voucher channelId does not match snapshot channelId`);let o=BigInt(i.acceptedCumulative),s=BigInt(a.cumulativeAmount),c=BigInt(i.requiredCumulative),l=BigInt(i.deposit),u=BigInt(i.settled),d=BigInt(i.spent);if(s!==o)throw Error(`session snapshot voucher amount does not match acceptedCumulative`);if(d>o)throw Error(`session snapshot spent exceeds acceptedCumulative`);if(u>l)throw Error(`session snapshot settled amount exceeds deposit`);if(!Fj(i.escrow,i.chainId,{channelId:a.channelId,cumulativeAmount:s,signature:a.signature},_j(i.descriptor)))throw Error(`session snapshot highest voucher signature is invalid`);let f=await OM({channelId:i.channelId,client:n,descriptor:i.descriptor,expected:{chainId:i.chainId,escrow:i.escrow,payee:i.descriptor.payee,payer:t.address,authorizedSigner:Gj(t),token:i.descriptor.token},readChannelState:r}),p=[o,c,f.state.settled].reduce((e,t)=>t>e?t:e,0n);if(p>f.state.deposit)throw Error(`recovered session cumulative amount exceeds on-chain channel deposit`);return{entry:{channelId:f.channelId,cumulativeAmount:p,deposit:f.state.deposit,descriptor:i.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0},spent:d}}function NM(e,t){return Xj(e.address,t.payer)?Xj(Gj(e),_j(t)):!1}function PM(e){let{account:t,entry:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e;if(_M(r)){if(!vM(r))throw Error(`descriptor required for TIP-1034 session action`);return{type:`manual`,account:t,context:r,decimals:i,resolved:o}}if(!n&&r?.channelId&&!r.descriptor)throw Error(`descriptor required to reuse TIP-1034 channel`);let s=AM({context:r,snapshot:o.snapshot});return!n&&s&&NM(t,s.descriptor)?{type:`recover`,account:t,context:s,decimals:i,maxDeposit:a,resolved:o}:n?.opened&&NM(t,n.descriptor)?{type:`voucher`,account:t,entry:n,maxDeposit:a,resolved:o}:{type:`open`,account:t,context:r,maxDeposit:a,resolved:o}}async function FM(e,t,n=!1){switch(e.type){case`open`:return LM(e,t,n);case`recover`:return RM(e,t);case`voucher`:return zM(e,t);case`manual`:return BM(e,t,n)}}async function IM(e,t){if(e)return await RA(t.client,{account:t.account,amountOut:t.amountOut,tokenOut:t.tokenOut,tokenIn:e.tokenIn,slippage:e.slippage})}async function LM(e,t,n){let{account:r,resolved:i}=e,a=uD({contextDepositRaw:e.context?.depositRaw,maxDeposit:e.maxDeposit,requestAmount:i.amount,suggestedDepositRaw:i.suggestedDepositRaw}),o=await $j(i.client,r,{chainId:i.chainId,deposit:a,escrow:i.escrow,feePayer:i.feePayer,feeToken:i.feeToken,initialAmount:i.amount,operator:i.operator,payee:i.payee,prefixCalls:await IM(n,{account:r.address,amountOut:a,client:i.client,tokenOut:i.token}),token:i.token});return await hM(t,{channelId:o.channelId,cumulativeAmount:i.amount,deposit:a,descriptor:o.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0}),o}async function RM(e,t){let{account:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e,{descriptor:s}=r,c=await OM({channelId:r.channelId,client:o.client,descriptor:s,expected:{chainId:o.chainId,escrow:o.escrow,payee:o.payee,payer:n.address,authorizedSigner:Gj(n),token:o.token}}),l=jM({context:r,decimals:i,requestAmount:o.amount,settled:c.state.settled,snapshot:o.snapshot});if(l>c.state.deposit)throw Error(`recovered voucher amount exceeds on-chain channel deposit`);fD(l,a);let u=await Zj(o.client,n,s,l,o.chainId,o.escrow);return await hM(t,{channelId:c.channelId,cumulativeAmount:l,deposit:c.state.deposit,descriptor:s,escrow:o.escrow,chainId:o.chainId,opened:!0}),u}async function zM(e,t){let{account:n,entry:r,resolved:i}=e,a=r.cumulativeAmount+i.amount;fD(a,e.maxDeposit);let o=await Zj(i.client,n,r.descriptor,a,i.chainId,i.escrow);return r.cumulativeAmount=a,await hM(t,r),o}async function BM(e,t,n){let{account:r,context:i,decimals:a,resolved:o}=e,{descriptor:s}=i,c=vj({...s,chainId:o.chainId,escrow:o.escrow});kM({channelId:i.channelId,descriptor:s,expectedChannelId:c,payee:o.payee,payer:r.address,authorizedSigner:Gj(r),token:o.token});let l=await VM({account:r,channelId:c,context:i,decimals:a,descriptor:s,resolved:o},n);return await gM(t,o.key,l),l}async function VM(e,t){switch(e.context.action){case`open`:return HM(e);case`topUp`:return UM(e,t);case`voucher`:return WM(e);case`close`:return GM(e)}}async function HM(e){let{account:t,channelId:n,context:r,decimals:i,descriptor:a,resolved:o}=e;if(!r.transaction)throw Error(`transaction required for open action`);let s=bM(r,i,`cumulativeAmount`,`open`),c=await Zj(o.client,t,a,s,o.chainId,o.escrow);return{action:`open`,type:`transaction`,channelId:n,transaction:r.transaction,signature:c.signature,descriptor:a,cumulativeAmount:s.toString(),authorizedSigner:a.authorizedSigner}}async function UM(e,t){let{account:n,channelId:r,context:i,decimals:a,descriptor:o,resolved:s}=e,c=bM(i,a,`additionalDeposit`,`topUp`);return i.transaction?{action:`topUp`,type:`transaction`,channelId:r,transaction:i.transaction,descriptor:o,additionalDeposit:c.toString()}:eM(s.client,n,o,c,s.chainId,s.feePayer,s.escrow,await IM(t,{account:n.address,amountOut:c,client:s.client,tokenOut:s.token}),s.feeToken)}function WM(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return Zj(a.client,t,i,bM(n,r,`cumulativeAmount`,`voucher`),a.chainId,a.escrow)}function GM(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return Qj(a.client,t,i,bM(n,r,`cumulativeAmount`,`close`),a.chainId,a.escrow)}var KM,qM,JM,YM=F((()=>{Fx(),kA(),Zx(),UA(),fM(),Sj(),Bj(),tM(),sM(),DD(),KM=J.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]*$/.test(e)),qM=J.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),JM=J.object({account:J.optional(J.custom()),autoSwap:J.optional(J.custom()),action:J.optional(J.enum([`open`,`topUp`,`voucher`,`close`])),channelId:J.optional(qM),cumulativeAmount:J.optional(Vx()),cumulativeAmountRaw:J.optional(J.string()),transaction:J.optional(KM),descriptor:J.optional(J.custom()),additionalDeposit:J.optional(Vx()),additionalDepositRaw:J.optional(J.string()),depositRaw:J.optional(J.string())})}));async function XM(e,t){let n=eN.get(e)??new Map;eN.set(e,n);let r=n.get(t),i,a=new Promise(e=>{i=e});return n.set(t,a),await r,()=>{i(),n.get(t)===a&&n.delete(t)}}function ZM(e,t){try{return t?.channelId.toLowerCase()===e.channelId.toLowerCase()&&BigInt(t.acceptedCumulative)===e.cumulativeAmount}catch{return!1}}function QM(e,t,n){try{let r=e.response?.headers.get(q.paymentReceipt);if(r){let e=ME(r);if(e.challengeId===t.id&&ZM(n,e))return!0}}catch{}return e.challenges?.some(e=>PD(e)?ZM(n,FD(e)):!1)??!1}function $M(e={}){let{account:t,allowCustomEscrow:n=!1,autoSwap:r,channelStore:i,decimals:a=6,escrow:o,allowedChainIds:s,getClient:c,maxDeposit:l,topUpAmount:u,onChannelUpdate:d,resolveAccount:f}=e,p=TA({chain:He,getClient:c,rpcUrl:yO}),m=bA({account:t}),h=l===void 0?void 0:N(l,a),g=u===void 0?void 0:N(u,a),_=i??iM(),v={store:_,notifyUpdate:e=>d?.(e)},y=async(e,t,n)=>{let r=m(e.client,t),i=t?.action?t.descriptor:n?.descriptor??AM({context:t,snapshot:e.snapshot})?.descriptor;return await f?.({account:r,chainId:e.chainId,operation:{kind:`authorizePaymentChannel`,...i?{authority:_j(i)}:{}}})??r},b=async(e,t,n)=>PM({account:await y(e,t,n),entry:n,context:t,decimals:a,maxDeposit:h,resolved:e}),x=rE(vE,{canHandleChallenge:({challenge:e})=>PD(e),context:JM,async createCredential(e){let{challenge:t,context:i}=e,a=await DM({allowCustomEscrow:n,challenge:t,escrowOverride:o,allowedChainIds:s,getClient:p}),c=vw(e),l=()=>{};try{let e=!_M(i)&&i?.descriptor===void 0;e&&(l=await XM(_,a.key),c&&(await _.get(a.key))?.opened&&await c.prepare());let n=await _.get(a.key),o=await b(a,i,n);if(!e&&c&&o.type===`open`){l=await XM(_,a.key);let e=await _.get(a.key);e?.channelId!==n?.channelId&&(n=e,n?.opened&&(await c.prepare(),n=await _.get(a.key)),o=await b(a,i,n))}let s,u=c&&o.type===`open`?{store:{get:e=>_.get(e),async set(e){s=e},delete:e=>_.delete(e)},notifyUpdate(){}}:v,d=await Yj(t,await FM(o,u,zA(i?.autoSwap??r,VA)),a.chainId,o.account);if(c&&s){let e=s;c.settle=async n=>{let r=n.status===`accepted`||QM(n,t,e);if(!r&&n.status===`pending`)return!1;try{if(r){let t=await _.get(a.key);(!t?.opened||t.channelId.toLowerCase()!==e.channelId.toLowerCase())&&(await _.set(e),v.notifyUpdate(e))}return!0}finally{l()}}}else l();return d}catch(e){throw l(),e}}}),S=async({challenge:e,channel:t,deposit:n,fetch:r,input:i,requiredCumulative:a,signal:o})=>{let s=t.deposit>n?t.deposit:n,c=dD({deposit:s,maxDeposit:h,requiredCumulative:a,suggestedDeposit:e.request.suggestedDeposit===void 0?void 0:BigInt(e.request.suggestedDeposit),topUpAmount:g});c>0n&&await BD({additionalDeposit:c,challenge:e,channel:t,channelId:t.channelId,createSessionCredential:(e,t)=>x.createCredential({challenge:e,context:t}),fetch:r,input:i,signal:o});let l=s+c;if(l===t.deposit)return;let u=await _.get(rM(t)),d=u?.channelId.toLowerCase()===t.channelId.toLowerCase()?u:t,f={...d,deposit:d.deposit>l?d.deposit:l};await _.set(f),v.notifyUpdate(f)};return uw(x,async({challenge:e,context:t,fetch:r,input:i,signal:a})=>{if(!PD(e))return;let c=t===void 0?void 0:JM.parse(t);if(_M(c))return;let l=await DM({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:p}),u=await _.get(l.key);if(!u?.opened)return;let d=l.snapshot?.channelId.toLowerCase()===u.channelId.toLowerCase()?l.snapshot:void 0,f=u.cumulativeAmount+kE(e),m=d?BigInt(d.requiredCumulative):f,h=m>f?m:f,g=d?BigInt(d.deposit):u.deposit,v=g>u.deposit?g:u.deposit;h<=v&&v===u.deposit||!NM(await y(l,c,u),u.descriptor)||await S({challenge:e,channel:u,deposit:v,fetch:r,input:i,requiredCumulative:h,signal:a})}),hw(x,async({challenge:e,credential:t,fetch:r,headers:i,input:a,refetch:c,response:l,signal:u})=>{if(!PD(e))return l;if(!NE(l))return OE(YS(t).payload).action===`open`&&i.get(`accept`)?.toLowerCase().includes(`text/event-stream`)?await c?.()??l:l;let d=(await DM({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:p})).key,f=await _.get(d),m={assertVoucherWithinLocalLimit:e=>fD(e,h),createSessionCredential:(e,t)=>x.createCredential({challenge:e,context:t}),fetch:r,getChannel:()=>f??null,async topUpIfNeeded({deposit:t,requiredCumulative:n,signal:i}){f&&await S({challenge:e,channel:f,deposit:f.deposit>t?f.deposit:t,fetch:r,input:a,requiredCumulative:n,signal:i})}};return ZD({onNeedVoucher:(t,n)=>QD({challenge:e,driver:m,input:a,signal:n},t),onReceipt(){},response:l,signal:u})})}var eN,tN=F((()=>{mw(),Tw(),Fx(),nC(),iE(),xA(),kA(),UA(),bO(),bE(),Sj(),UE(),tM(),sM(),YM(),DD(),eN=new WeakMap}));function nN(e,t){iN.set(e,t)}function rN(e){let t=iN.get(e);if(!t)throw Error(`Session manager internals are unavailable.`);return t}var iN,aN=F((()=>{iN=new WeakMap}));function oN(e){let t=null;return{wait(n=()=>!0){if(t)throw Error(`${e} wait already in progress`);return new Promise((e,r)=>{t={predicate:n,resolve:e,reject:r}})},settle(e){if(!t||!t.predicate(e))return;let n=t;t=null,n.resolve(e)},reject(e){if(!t)return;let n=t;t=null,n.reject(e)}}}function sN(e){let t=oN(`close-ready`),n=oN(`receipt`);return{waitForReceipt(e){return n.wait(e)},waitForCloseReady(){let n=e.getSocketSession()?.closeReadyReceipt;return n?Promise.resolve(n):t.wait()},settleReceipt(e){n.settle(e)},settleCloseReady(n){let r=e.getSocketSession();r&&r.challenge.id===n.challengeId&&r.channelId===n.channelId&&(r.closeReadyReceipt=n),t.settle(n)},rejectReceipt(e){n.reject(e)},rejectCloseReady(e){t.reject(e)}}}var cN=F((()=>{}));function lN(e){return e.method===jx.tempo&&e.intent===Mx.charge}function uN(e){if(!lN(e)||typeof e.request.amount!=`string`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function dN(e,t,n){if(!n)return t;let r={...Aw(e instanceof Request?e.headers:void 0),...Aw(t?.headers)};return Object.keys(r).some(e=>e.toLowerCase()===q.paymentSession.toLowerCase())?t:{...t,headers:{...r,[q.paymentSession]:n}}}function fN(e,t){return e===void 0?t:{...JM.parse(e),...t}}function pN(e){let t=e.decimals??6,n=e.webSocket??globalThis.WebSocket;return{decimals:t,fetch:e.fetch??globalThis.fetch.bind(globalThis),maxVoucherCumulative:e.maxDeposit===void 0?null:N(e.maxDeposit,t),topUpAmount:e.topUpAmount===void 0?null:N(e.topUpAmount,t),WebSocket:n}}function mN(e){let t=e.client?.chain?.id;(t!==void 0||e.allowedChainIds?.length===0)&&DA(e.allowedChainIds,t);let n=e.allowCustomEscrow??!1,r=pN(e),i=TA({chain:He,getClient:e.client?()=>e.client:e.getClient,rpcUrl:yO}),a=bA({account:e.account}),o=vD(),s=e.credentialContext===void 0?void 0:fN(e.credentialContext,{}),c=sN({getSocketSession:()=>o.socketSession}),l=e.channelStore??iM(),u=new Set,d;async function f(e){let t=await l.get(e);if(t?.opened&&!u.has(t.channelId))return t}let p={async get(e){let t=await f(e);return t&&d&&(d.seenExisting.add(e),!d.committed&&!d.created.has(e)&&(d.resumed??=t)),t},async set(e){let t=rM(e);e.opened&&u.delete(e.channelId),d?.trackCreates&&!d.seenExisting.has(t)&&d.created.set(t,e),await l.set(e)},delete:e=>l.delete(e)};async function m(e){let t=rM(e);u.add(e.channelId),d?.seenExisting.delete(t),d?.resumed===e&&(d.resumed=void 0),await Promise.resolve(l.delete(t)).catch(()=>void 0)}async function h(){let e=d;if(e?.created.size){for(let[t,n]of e.created)u.add(n.channelId),await Promise.resolve(l.delete(t)).catch(()=>void 0);e.created.clear(),await ie(e.committed??e.previous)}}function g(e){let t=kx(e.request.methodDetails,Nx.sessionSnapshot);if(typeof t?.channelId!=`string`)return!1;let n=d;if(!n?.created.size||!o.channel)return!1;for(let[e,r]of n.created)if(r.channelId.toLowerCase()===t.channelId.toLowerCase()&&o.channel.channelId.toLowerCase()===t.channelId.toLowerCase())return n.created.delete(e),n.committed=CD({channel:o.channel,spent:o.spent,state:o.state}),!0;return!1}function _(e){return tD(o,e)}function v(){let e=o.state.status===`active`?o.state:d?.committed?.state??d?.previous.state;return e?.status===`active`?e.units:0}function y(e){let t=d,n=t?.committed?.channel?.entry??t?.resumed;!t||n?.channelId.toLowerCase()!==e.channelId.toLowerCase()||e.deposit<=n.deposit||(t.resumed=void 0,t.committed=CD({channel:o.channel,spent:o.spent,state:o.state}))}let b=$M({account:e.account,allowCustomEscrow:n,autoSwap:e.autoSwap,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount,escrow:e.escrow,allowedChainIds:e.allowedChainIds,decimals:r.decimals,maxDeposit:e.maxDeposit,topUpAmount:e.topUpAmount,channelStore:p,onChannelUpdate(e){e.channelId!==o.channel?.channelId&&(o.spent=0n),o.channel=e,o.lastChallenge&&_({type:`activated`,challengeId:o.lastChallenge.id,entry:e,spent:o.spent.toString(),units:v()}),y(e)}});gw(b);let x=dj({allowedChainIds:e.allowedChainIds,account:e.account,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount}),S=Ow({fetch:r.fetch,methods:[b],onChallenge:async(e,t)=>{if(!ND(e))return;let n=d,r=n&&n.challengesReceived>0&&e.id===o.lastChallenge?.id,i=r&&$x(e)===$x(o.lastChallenge);n&&n.challengesReceived++,!i&&(g(e)||(n?.created.size?await h():r&&await ie(n.committed??n.previous)),o.lastChallenge=e,_({type:`challengeReceived`,challengeId:e.id}))}});function C(e,t){return b.createCredential({challenge:e,context:fN(s,t)})}function w(e){yD({maxVoucherCumulative:r.maxVoucherCumulative,receipt:e,runtime:o})}function T(e=o.state.status===`active`?o.state.units:0){!o.channel||!o.lastChallenge||o.state.status!==`active`&&o.state.status!==`withdrawable`&&o.state.status!==`closeRequested`&&_({type:`activated`,challengeId:o.lastChallenge.id,entry:o.channel,spent:o.spent.toString(),units:e})}async function ee(t){let n=t.headers.get(q.paymentSessionSnapshot);if(!n)return;let r=GE(n);DA(e.allowedChainIds,r.chainId);let s=await i({chainId:r.chainId});EA(s,r.chainId);let c=a(s),{entry:l,spent:u}=await MM({account:await e.resolveAccount?.({account:c,chainId:r.chainId,operation:{authority:_j(r.descriptor),kind:`authorizePaymentChannel`}})??c,client:s,snapshot:r});return ne(l.cumulativeAmount),await Promise.resolve(p.set(l)).catch(()=>void 0),o.channel=l,o.spent=u,l}async function E(t,n){if(!e.bootstrap||o.channel?.opened)return;let i=t instanceof Request?t.headers:void 0,{body:a,method:s,...c}=n??{},l=t instanceof Request?t.url:t,u={...c,method:`HEAD`,headers:{...Aw(i),...Aw(n?.headers),[q.acceptPayment]:`${jx.tempo}/${Mx.charge}`}};try{let e=await r.fetch(l,u);if(e.status!==402)return await ee(e);let t=cS(e).find(lN);if(!t||!uN(t))return;let n=await x.createCredential({challenge:t,context:{}}),i=await r.fetch(l,{...u,headers:{...Aw(u.headers),[q.authorization]:n}});return i.ok?await ee(i):void 0}catch{return}}function D(e,t){let n=o.socketSession;return xD({challengeId:e.id,channelId:t,closeReadyReceipt:n?.closeReadyReceipt,cumulativeAmount:o.channel?.channelId===t?o.channel.cumulativeAmount:0n,deliveredChunks:n?.deliveredChunks,socketChallengeId:n?.challenge.id,socketChannelId:n?.channelId,spent:o.spent,tickCost:n?.tickCost})}function O(e,t){let n=FD(t);if(!n)return;if(vj({...n.descriptor,chainId:n.chainId,escrow:n.escrow}).toLowerCase()!==n.channelId.toLowerCase())throw Error(`close snapshot descriptor does not match its channel ID`);if(n.channelId.toLowerCase()!==e.channelId.toLowerCase())throw Error(`close snapshot channel ID does not match local session`);if(n.chainId!==e.chainId||n.escrow.toLowerCase()!==e.escrow.toLowerCase())throw Error(`close snapshot payment scope does not match local session`);let r=BigInt(n.acceptedCumulative),i=BigInt(n.spent);if(r<0n||i<0n)throw Error(`close snapshot amounts must not be negative`);if(i>r)throw Error(`close snapshot spent exceeds accepted cumulative amount`);if(r>e.cumulativeAmount)throw Error(`close snapshot accepted cumulative exceeds local voucher state`);return{acceptedCumulative:r,spent:i}}function k(e,t){let n=O(e.channel,t);if(!n)return;let{acceptedCumulative:r,spent:i}=n;if(o.spent>r)throw Error(`close snapshot accepted cumulative is below locally confirmed spend`);return i>o.spent&&(o.spent=i),n}function te(e,t=e.challenge,n=!1){let r=(n?k(e,t):O(e.channel,t))?.acceptedCumulative??D(t,e.channelId);if(r>e.channel.cumulativeAmount)throw Error(`fallback close amount exceeds local voucher state`);return ne(r),r.toString()}function ne(e){oD({cumulativeAmount:e,maxVoucherCumulative:r.maxVoucherCumulative})}async function re(e){let{knownDeposit:t,...n}=e,i=await BD({...n,channel:o.channel,createSessionCredential:C,fetch:r.fetch});w(i);let a=jD({additionalDeposit:e.additionalDeposit,channel:o.channel,channelId:e.channelId,challengeId:o.lastChallenge?.id,currentState:o.state,knownDeposit:t,receipt:i,spent:o.spent});return a?.channel&&o.lastChallenge&&(await p.set(a.channel),_({type:`activated`,challengeId:o.lastChallenge.id,entry:a.channel,spent:o.spent.toString(),units:v()}),y(a.channel)),i}async function A(e){let t=o.channel?.channelId===e.channelId?o.channel.deposit:0n,n=t>e.deposit?t:e.deposit,i=dD({deposit:n,maxDeposit:r.maxVoucherCumulative,requiredCumulative:e.requiredCumulative,suggestedDeposit:e.challenge.request.suggestedDeposit===void 0?void 0:BigInt(e.challenge.request.suggestedDeposit),topUpAmount:r.topUpAmount});i!==0n&&await re({challenge:e.challenge,input:e.input,channelId:e.channelId,additionalDeposit:i,knownDeposit:n,signal:e.signal})}async function j(e,t){let n=SD({channel:o.channel,channelId:e,challengeId:o.lastChallenge?.id,cumulativeAmount:t,spent:o.spent,state:o.state});n&&o.channel&&(_({type:`activated`,challengeId:n.challengeId,entry:o.channel,spent:n.spent,units:n.units}),await l.set(o.channel))}async function ie(e){let t=wD(e,o.channel);o.channel=t.channel,o.spent=t.spent,o.state=t.state,o.channel?.opened&&await l.set(o.channel)}function ae(e){let t=e.headers.get(q.paymentReceipt),n=t?ME(t):null;return w(n),Object.assign(e,{receipt:n,challenge:o.lastChallenge,channelId:o.channel?.channelId??null,cumulative:o.channel?.cumulativeAmount??0n})}async function oe(e,t){if(d)throw Error(`SessionManager: a request is already in flight; concurrent requests on one manager are not supported`);o.lastUrl=e;let n=CD({channel:o.channel,spent:o.spent,state:o.state}),i={challengesReceived:0,committed:void 0,created:new Map,previous:n,seenExisting:new Set,resumed:void 0,trackCreates:!1};d=i;try{await E(e,t),i.trackCreates=!0;let a=dN(e,t,o.channel?.opened?o.channel.channelId:void 0);s&&(a={...a,context:s});let c=!n.channel?.opened;async function l(){let n=i.resumed;return!c||!n?!1:(c=!1,await m(n),a=dN(e,t,void 0),!0)}for(;;){let t;try{t=await S(e,a)}catch(e){if(i.created.size?await h():await ie(i.committed??n),await l())continue;throw e}let s=ae(t),c=!1;if(s.status===402){let t=await HD({input:e,init:a,response:s,createSessionCredential:C,fetch:r.fetch,getChannel:()=>o.channel,restoreCumulative:j,setChallenge(e){o.lastChallenge=e},topUpIfNeeded:A});t&&(c=!0,s=ae(t))}if(!c&&!s.ok&&!s.receipt){if(i.created.size?await h():await ie(i.committed??n),await l())continue;return s}return s}}finally{d=void 0}}async function se(e){let t=await WD({createSessionCredential:C,fetch:r.fetch,getMinimumSpent:()=>o.spent,lastUrl:o.lastUrl,resolveSignedCloseAmount:t=>te(e,t,!0),signedCloseAmount:te(e),setChallenge(e){o.lastChallenge=e},target:e});return t&&(T(),_({type:`closeStarted`}),_({type:`closed`,receipt:t})),t}let ce={createSessionCredential:C,doFetch:oe,fetch:r.fetch,getChannel:()=>o.channel,getChallenge:()=>o.lastChallenge,assertVoucherWithinLocalLimit:ne,acceptReceipt(e){w(e)},topUpIfNeeded:A},M={get channelId(){return o.channel?.channelId},get cumulative(){return o.channel?.cumulativeAmount??0n},get opened(){return o.channel?.opened??!1},get state(){return o.state},fetch:oe,async topUp(e){let t=AD({amount:e,assertVoucherWithinLocalLimit:ne,channel:o.channel,decimals:r.decimals,lastChallenge:o.lastChallenge,lastUrl:o.lastUrl});return re({additionalDeposit:t.additionalDeposit,challenge:t.challenge,channelId:t.channelId,input:t.input})},async sse(e,t){return GD(e,t,ce)},async ws(e,t){if(!r.WebSocket)throw Error("No WebSocket implementation available. Pass `webSocket` to sessionManager() in this runtime.");let n=RD(e),i=t?.signal?{signal:t.signal}:void 0;await E(n,i);let a=o.channel?.opened?o.channel.channelId:void 0,{challenge:s,credential:l,httpUrl:u,wsUrl:d}=await eO({async createSessionCredential(e,i){return o.lastChallenge=e,await fw(b,{challenge:e,context:i,fetch:r.fetch,input:n,signal:t?.signal}),C(e,i)},fetch:r.fetch,input:e,onProbeUrl(e){o.lastUrl=e.toString()},probeInit:dN(n,i,a),signal:t?.signal});return o.lastChallenge=s,aO({challenge:s,credential:l,httpUrl:u,WebSocket:r.WebSocket,wsUrl:d,options:t,createSessionCredential:C,getChannel:()=>o.channel,setSocketSession(e){o.socketSession=e},async refreshChallenge(){let e=await $D({fetch:r.fetch,input:u,probeInit:dN(u,i,o.channel?.opened?o.channel.channelId:void 0),signal:t?.signal});return o.lastChallenge=e.challenge,e.challenge},assertVoucherWithinLocalLimit:ne,acceptReceipt:w,rejectCloseReady:c.rejectCloseReady,rejectReceipt:c.rejectReceipt,settleCloseReady:c.settleCloseReady,settleReceipt:c.settleReceipt,topUpIfNeeded:A,waitForReceipt:c.waitForReceipt})},async close(){let e=o.socketSession,t=pD({channel:o.channel,currentSocket:e,lastChallenge:o.lastChallenge});if(!t)return;let n=e?.socket;if(e&&n?.readyState===dO.OPEN){let r=await TD({activeSocket:n,createSessionCredential:C,currentSocket:e,spent:o.spent,target:t,waitForCloseReady:c.waitForCloseReady,waitForReceipt:c.waitForReceipt});return T(),_({type:`closeStarted`}),_({type:`closed`,receipt:r}),r}return se(t)}};return nN(M,{consumeSseResponse(e,t,n){return KD(e,t,n,ce)},rehydrate({channel:e,challenge:t,input:n,spent:r}){if(!e.opened)throw Error(`Cannot restore a closed session channel.`);if(!ND(t))throw Error(`Cannot restore session: challenge is not tempo/session.`);if(r<0n)throw Error(`Cannot restore session: spent must not be negative.`);if(r>e.cumulativeAmount)throw Error(`Cannot restore session: spent exceeds local voucher state.`);ne(e.cumulativeAmount);let i=O(e,t),a=i&&i.spent>r?i.spent:r;o.lastUrl=n,o.lastChallenge=t,o.channel=e,o.spent=a,_({type:`challengeReceived`,challengeId:t.id}),_({type:`activated`,challengeId:t.id,entry:e,spent:a.toString(),units:0})}}),M}var hN=F((()=>{_S(),_T(),mw(),Tw(),Fx(),xA(),kA(),gj(),bO(),sM(),YM(),tN(),Sj(),UE(),QE(),aN(),cN(),DD(),mO(),(function(e){e.serializeSnapshot=WE,e.deserializeSnapshot=GE})(mN||={})}));function gN(e){return e instanceof Date?e:new Date(e)}function _N(e){let t=e.getTime();if(!Number.isFinite(t))throw new Y({reason:`subscriptionExpires is invalid`});if(t%1e3!=0)throw new Y({reason:`subscriptionExpires must be representable as whole seconds`});let n=t/1e3;if(n<=0||!Number.isSafeInteger(n))throw new Y({reason:`subscriptionExpires cannot be represented in a Tempo key authorization`});return n}function vN(e){if(!/^[1-9]\d*$/.test(e.periodCount))throw new Y({reason:`periodCount is invalid`});let t=LN[e.periodUnit];if(t===void 0)throw new Y({reason:`periodUnit is invalid`});let n=BigInt(e.periodCount)*t;if(n>IN)throw new Y({reason:`subscription period cannot be represented as an unsigned 64-bit integer`});if(n>BigInt(2**53-1))throw new Y({reason:`subscription period cannot be represented exactly by this Tempo client`});return Number(n)}function yN(e){let{challengeExpires:t,request:n}=e;vN(n);let r=_N(gN(n.subscriptionExpires));if(t){let e=Math.floor(new Date(t).getTime()/1e3);if(!Number.isFinite(e)||r<=e)throw new Y({reason:`subscriptionExpires must be strictly later than challenge expires`})}}function bN(e){let t=NN(e.currency,`currency`),n=NN(e.recipient,`recipient`);return[{address:t,selector:FN,recipients:[n]}]}function xN(e){try{let t=re.fromBytes(k.toBytes(e));if(re.size(t)!==32)throw Error(`invalid challenge id size`);return t}catch{throw new Y({reason:`challenge id must encode 32 bytes`})}}async function SN(e){let{accessKey:t,account:n,challengeId:r,chainId:i,request:a}=e;if(typeof n.sign!=`function`)return;let o=wN({accessKey:t,challengeId:r,chainId:i,request:a}),s=await n.sign({hash:We.getSignPayload(o)}),c=Ge.from(s);if(c.type===`keychain`||c.type===`multisig`)throw new Y({reason:`keyAuthorization must use a primitive signature`});return We.from(o,{signature:s})}function CN(e){let{accessKey:t,challengeId:n,chainId:r,payload:i,request:a}=e;if(i.type!==`keyAuthorization`)throw new Y({reason:`invalid keyAuthorization payload`});let o=TN(i.signature),s=EN(o);if(DN({accessKey:t,authorization:o,chainId:r}),o.witness?.toLowerCase()!==xN(n))throw new Y({reason:`keyAuthorization challenge mismatch`});return ON(o,a),AN(kN(o),a),jN(o.scopes,a),{authorization:o,source:{address:MN(o,s),chainId:r}}}function wN(e){let{accessKey:t,challengeId:n,chainId:r,request:i}=e;return We.from({address:NN(t.accessKeyAddress,`accessKeyAddress`),chainId:BigInt(r),expiry:_N(gN(i.subscriptionExpires)),limits:[{token:NN(i.currency,`currency`),limit:BigInt(i.amount),period:vN(i)}],scopes:bN(i),type:t.keyType,witness:xN(n)})}function TN(e){try{return We.deserialize(e)}catch(e){throw e instanceof We.InvalidSignatureTypeError?new Y({reason:`keyAuthorization must use a primitive signature`}):new Y({reason:`invalid keyAuthorization payload`})}}function EN(e){let t=e.signature;if(!t)throw new Y({reason:`keyAuthorization must use a primitive signature`});return t}function DN(e){let{accessKey:t,authorization:n,chainId:r}=e;if(n.chainId!==BigInt(r))throw new Y({reason:`keyAuthorization chainId mismatch`});if(t){if(!fe(n.address,NN(t.accessKeyAddress,`accessKeyAddress`)))throw new Y({reason:`keyAuthorization access key mismatch`});if(n.type!==t.keyType)throw new Y({reason:`keyAuthorization key type mismatch`})}}function ON(e,t){if(yN({request:t}),e.expiry!==_N(gN(t.subscriptionExpires)))throw new Y({reason:`keyAuthorization expiry mismatch`})}function kN(e){let[t]=e.limits??[];if(!t||e.limits?.length!==1)throw new Y({reason:`keyAuthorization must contain exactly one token limit`});return t}function AN(e,t){if(!fe(e.token,NN(t.currency,`currency`)))throw new Y({reason:`keyAuthorization currency mismatch`});if(e.limit!==BigInt(t.amount))throw new Y({reason:`keyAuthorization amount mismatch`});if(e.period!==vN(t))throw new Y({reason:`keyAuthorization period mismatch`})}function jN(e,t){if(!e||e.length!==1)throw new Y({reason:`keyAuthorization must contain a recipient-scoped transferWithMemo call`});let n=NN(t.currency,`currency`),r=NN(t.recipient,`recipient`),i=new Set;for(let t of e){if(!fe(t.address,n))throw new Y({reason:`keyAuthorization call target mismatch`});let e=PN(t.selector);if(e!==`0xa9059cbb`&&e!==`0x95777d59`)throw new Y({reason:`keyAuthorization selector not allowed`});if(i.has(e))throw new Y({reason:`keyAuthorization duplicate selector`});if(i.add(e),t.recipients?.length!==1||!fe(t.recipients[0],r))throw new Y({reason:`keyAuthorization recipient mismatch`})}if(!i.has(`0x95777d59`))throw new Y({reason:`keyAuthorization must allow transferWithMemo`})}function MN(e,t){let n=We.getSignPayload(e);try{let e=Ge.extractAddress({payload:n,signature:t});if(!Ge.verify(t,{address:e,payload:n}))throw new Y({reason:`keyAuthorization signature is invalid`});return e}catch(e){throw e instanceof Y?e:new Y({reason:`keyAuthorization signature is invalid`})}}function NN(e,t){if(!de(e))throw new Y({reason:`${t} must be an address`});return e.toLowerCase()}function PN(e){return typeof e==`string`?e.toLowerCase():``}var FN,IN,LN,RN=F((()=>{SS(),FN=`0x95777d59`,IN=(1n<<64n)-1n,LN={dev_second:1n,day:86400n,week:604800n}}));function zN(e={}){let t=TA({chain:ye,getClient:e.getClient,rpcUrl:yO}),n=bA({account:e.account});return rE(yE,{context:HN,async createCredential({challenge:r,context:i}){let a=r.request.methodDetails?.chainId??hO.testnet,o=await t({chainId:a}),s=n(o,i),c=i?.accessKey??e.accessKey??r.request.methodDetails?.accessKey;if(!c)throw Error("No `accessKey` provided. The subscription challenge must include `accessKey`, or the client must pass one to parameters/context.");VN(r.request),await e.validateRequest?.(r.request);let l=await BN(o,{accessKey:c,account:s,challengeId:r.id,chainId:a,request:r.request}),u=CN({accessKey:c,challengeId:r.id,chainId:a,payload:{signature:We.serialize(l),type:`keyAuthorization`},request:r.request});if(!fe(u.source.address,s.address))throw Error(`keyAuthorization signer does not match the selected account`);return $S({challenge:r,payload:{signature:We.serialize(l),type:`keyAuthorization`},source:`did:pkh:eip155:${a}:${s.address.toLowerCase()}`})}})}async function BN(e,t){let{accessKey:n,account:r,challengeId:i,chainId:a,request:o}=t,s=await SN({accessKey:n,account:r,challengeId:i,chainId:a,request:o});if(s)return s;let c=await e.request({method:`wallet_authorizeAccessKey`,params:[{address:n.accessKeyAddress,expiry:_N(gN(o.subscriptionExpires)),keyType:n.keyType,limits:[{token:o.currency,limit:re.fromNumber(BigInt(o.amount)),period:vN(o)}],scopes:bN(o),witness:xN(i)}]});return We.fromRpc(c.keyAuthorization)}function VN(e){vN(e),_N(gN(e.subscriptionExpires))}var HN,UN=F((()=>{nC(),iE(),xA(),kA(),Zx(),bO(),bE(),RN(),HN=J.object({accessKey:J.optional(J.custom()),account:J.optional(J.custom())})}));function WN(e={}){let t=e.expectedChainId!==void 0&&(e.allowedChainIds===void 0||e.allowedChainIds.includes(e.expectedChainId)),n=e.expectedChainId===void 0?e:{...e,allowedChainIds:t?[e.expectedChainId]:[]};return[dj(e),GN(n)]}var GN,KN=F((()=>{tN(),hN(),gj(),UN(),GN=Object.assign($M,{manager:mN}),(function(e){e.charge=dj,e.common=WN,e.session=GN,e.subscription=zN})(WN||={})})),qN=F((()=>{gj(),KN(),UN(),tN(),hN()})),JN=Qe({orderTempoChargeChallengesByBalance:()=>XN,readTempoKeystore:()=>gP,resolveTempoAccount:()=>_P,tempo:()=>ZN});async function YN(e){process.stdout.write(Buffer.from(await e.arrayBuffer()))}async function XN(e,t){let n=[],r=[];for(let[t,i]of e.entries())iP(i)&&(n.push(t),r.push(i));if(r.length<2)return[...e];let i=await aP(t).catch(()=>void 0);if(!i)return[...e];let a=await Promise.all(r.map(async(e,t)=>({challenge:e,index:t,score:await oP(e,i)})));a.sort((e,t)=>TP.indexOf(e.score)-TP.indexOf(t.score)||e.index-t.index);let o=[...e];for(let[e,t]of n.entries())o[t]=a[e].challenge;return o}function ZN(){let e;return oA({method:`tempo`,supports(e){return e.method===`tempo`&&[`charge`,`session`].includes(e.intent)},async setup({challenge:t,options:n,methodOpts:r}){let i=tk(n.account),a=t.request,o=a.currency,s=rP(r),c=uP({autoSwap:s.autoSwap??n.autoSwap,payWith:s.payWith??n.payWith,slippage:s.slippage??n.slippage,tokenIn:s.tokenIn}),l=o??``,u=a.decimals??6,d,f,p,m=!1,h=process.env.MPPX_PRIVATE_KEY?.trim()||(AO(i)?void 0:await nk(i).get());if(!h&&AO(i)&&vP()){m=!0;let e=_P(i);if(e){let r=PO(n.rpcUrl,{network:n.network});p=j({chain:await IO({network:n.network,rpcUrl:r}),transport:ue(r)}),cP({challenge:t,clientChainId:p.chain?.id}),d=p.chain?.blockExplorers?.default?.url;let i=o?await BO(p,o,e.wallet_address).catch(()=>void 0):void 0;l=i?.symbol??o??``,u=i?.decimals??a.decimals??6}}else if(h)f=ve(h);else{let e=bP();if(e){let t=await nk(e).get();t&&(f=ve(t))}if(!f)throw n.account?new I({code:`ACCOUNT_NOT_FOUND`,message:`Account "${i}" not found.`,exitCode:69}):new I({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69})}if(!m&&f){let e=PO(n.rpcUrl,{network:n.network});p=j({chain:await IO({network:n.network,rpcUrl:e}),transport:ue(e)}),cP({challenge:t,clientChainId:p.chain?.id}),d=p.chain?.blockExplorers?.default?.url;let r=o?await BO(p,o,f.address).catch(()=>void 0):void 0;l=r?.symbol??o??``,u=r?.decimals??a.decimals??6}if(m)return{tokenSymbol:l,tokenDecimals:u,explorerUrl:d,methods:[],async createCredential(e){let t=e.headers.get(`www-authenticate`);if(!t)throw Error(`No WWW-Authenticate header in 402 response.`);return yP(t)}};if(!f||!p)throw new I({code:`ACCOUNT_NOT_FOUND`,message:`Tempo requires a configured account.`,exitCode:69});let g=WN({account:f,...s.allowCustomEscrow===void 0?{}:{allowCustomEscrow:s.allowCustomEscrow},getClient:()=>p,...c===void 0?{}:{autoSwap:c},maxDeposit:(()=>{if(t.intent!==`session`)return;let e=t.request.suggestedDeposit,n=(s.deposit===void 0?void 0:String(s.deposit))??e??(zO(p.chain)?`10`:void 0);if(!n)throw new I({code:`MISSING_DEPOSIT`,message:`Session payment requires a deposit. Use -M deposit=<amount> or connect to testnet.`,exitCode:2});return n})()}),_=(()=>{if(!s.channel)return;let e=s.channel,t=fP(e);return{channelId:e,...t!==void 0&&{cumulativeAmountRaw:t.toString()}}})();return e={descriptor:void 0,async signVoucher({channelId:n,cumulativeAmount:r,escrowContract:i,chainId:a,action:o=`voucher`}){let s=e?.descriptor;if(!s)throw Error(`session descriptor not available`);let c={channelId:n,cumulativeAmount:r},l=await Nj(p,f,c,i,a);return $S({challenge:t,payload:{action:o,channelId:n,...o===`close`?{closeSignature:await Pj(p,f,c,i,a)}:{},descriptor:s,cumulativeAmount:r.toString(),signature:l},source:`did:pkh:eip155:${a}:${f.address}`})},source:`did:pkh:eip155:${p.chain.id}:${f.address}`},{tokenSymbol:l,tokenDecimals:u,explorerUrl:d,methods:[...g],credentialContext:_}},prepareCredentialRequest({challenge:e,headers:t}){e.intent===`session`&&(t.Accept=`text/event-stream`)},async handleResponse(t){if(t.challenge.intent!==`session`||!e)return!1;let{challenge:n,credential:r,response:i,fetchUrl:a,fetchInit:o,verbose:s}=t,{silent:c,confirmEnabled:l,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,shownKeys:p}=t,m=c?e=>{}:e=>process.stderr.write(e),h=YS(r),g=n.request,_=g.methodDetails,v=h.payload.channelId,y=_?.escrowContract??_?.escrow??`0x4d50500000000000000000000000000000000000`,b=_?.chainId??0,x=BigInt(g.amount),S=`cumulativeAmount`in h.payload&&h.payload.cumulativeAmount?BigInt(h.payload.cumulativeAmount):0n;if(`descriptor`in h.payload&&(e.descriptor=h.payload.descriptor),s>=1){if(h.payload.action===`open`){let e=g.suggestedDeposit,t=e?` ${X.dim(`(deposit ${e} ${u})`)}`:``;m(`${l?``:`
232
+ `)}function DO(e,t,n){if(GO.has(e)&&typeof t==`string`)return`${t} ${X.dim(`(${IO(BigInt(t),n.tokenSymbol,n.tokenDecimals)})`)}`;if(e===`chainId`&&typeof t==`number`){let e=BO({id:t,name:``});return e?`${t} ${X.dim(`(${e})`)}`:String(t)}return typeof t==`string`&&/^0x[0-9a-fA-F]{40}$/.test(t)?n.explorerUrl?AO(`${n.explorerUrl}/address/${t}`,t):t:typeof t==`string`&&/^https?:\/\//.test(t)?X.link(t,t):String(t)}function OO(e){try{let t=e.replace(/^0x0*/,``);if(!t)return;let n=Uint8Array.from(t.match(/.{1,2}/g).map(e=>Number.parseInt(e,16))),r=new TextDecoder().decode(n);return/^[\x20-\x7e]+$/.test(r)?r:void 0}catch{return}}function kO(e,t){if(e===`realm`&&typeof t==`string`)try{let e=new URL(t.includes(`://`)?t:`https://${t}`);return X.link(e.href,t)}catch{}return String(t)}function AO(e,t){return X.link(e,t)}function jO(e){if(!e)return{};let t=Array.isArray(e)?e:[e],n={};for(let e of t){let t=e.indexOf(`=`);if(t===-1)throw Error(`Invalid method option format: ${e} (expected key=value)`);n[e.slice(0,t)]=e.slice(t+1)}return n}function MO(e=process.env){if(e.CLAUDECODE)return!0;for(let[t,n]of Object.entries(e))if(n&&(t===`CODEX`||t.startsWith(`CODEX_`)))return!0;return!1}function NO(e){return e.startsWith(`tempo:`)}function PO(e){let t=xe.createInterface({input:process.stdin,output:process.stderr});return new Promise(n=>{t.on(`close`,()=>n(void 0)),t.question(`${X.bold(`▸ ${e}:`)} `,e=>{t.close(),n(e.trim()||void 0)})})}function FO(e,t=!1){let n=xe.createInterface({input:process.stdin,output:process.stderr});return new Promise(r=>{let i=t?`(Y/n)`:`(y/N)`;n.question(`${X.bold(`▸ ${e}`)} ${X.dim(i)} `,e=>{n.close();let i=e.trim().toLowerCase();r(i===``?t:i===`y`)})})}function IO(e,t,n=6,r){let[i,a]=(Number(e)/10**n).toString().split(`.`),o=i.replace(/\B(?=(\d{3})+(?!\d))/g,`_`),s=r?.explorerUrl&&r.token?X.dim(X.link(`${r.explorerUrl}/token/${r.token}`,t,!0)):X.dim(t);return`${a?`${o}.${a}`:o} ${s}`}function LO(e,t={}){return e??(t.network?KO[t.network]:void 0)??(process.env.MPPX_RPC_URL?.trim()||process.env.RPC_URL?.trim()||void 0)}function RO(e={}){if(e.network)return e.network;if(!e.rpcUrl&&!(process.env.MPPX_RPC_URL?.trim()||process.env.RPC_URL?.trim()))return`testnet`}async function zO(e={}){let t=LO(e.rpcUrl,{network:e.network});if(!t)return ve;let{getChainId:n}=await import(`viem/actions`),r=await n(M({transport:le(t)})),i=Object.values(await import(`viem/tempo/chains`)).filter(e=>typeof e==`object`&&!!e&&`id`in e&&e.id===r),a=i.find(e=>`serializers`in e&&e.serializers)??i[0];if(!a)throw Error(`Unknown chain ID ${r} from RPC ${t}`);return a}function BO(e){return{[ve.id]:`mainnet`,[ye.id]:`testnet`}[e.id]??e.name}function VO(e){return typeof e==`bigint`?e:e.amount}function HO(e){return e.id!==ve.id}async function UO(e,t,n,r={}){let{Actions:i}=await import(`viem/tempo`),[a,o]=await Promise.all([i.token.getBalance(e,{account:n,token:t}).then(VO).catch(()=>0n),i.token.getMetadata(e,{token:t}).catch(e=>{if(r.requireDecimals)throw e;return{symbol:t}})]),s={"0x20c0000000000000000000000000000000000000":`PathUSD`,"0x20C000000000000000000000b9537d11c60E8b50":`USDC`}[t]??o.symbol,c=`decimals`in o&&typeof o.decimals==`number`?o.decimals:6;if(r.requireDecimals&&!(`decimals`in o&&typeof o.decimals==`number`))throw Error(`Token decimals are unavailable.`);return{balance:a,symbol:s,decimals:c,token:t}}async function WO(e,t){if(t?.chain){let n=M({chain:t.chain,transport:le(t.rpcUrl)}),r=t.chain.blockExplorers?.default?.url,i=X.dim(`(${BO(t.chain)})`);return HO(t.chain)?(await Promise.all(XO.map(t=>UO(n,t,e)))).filter(e=>e.balance>0n).map(e=>`${IO(e.balance,e.symbol,e.decimals,{explorerUrl:r,token:e.token})} ${i}`):(await Promise.all(YO.map(t=>UO(n,t,e)))).map(e=>`${IO(e.balance,e.symbol,e.decimals,{explorerUrl:r,token:e.token})} ${i}`)}let n=M({chain:ve,transport:le(LO())}),r=ve.blockExplorers?.default?.url,i=(await Promise.all(YO.map(t=>UO(n,t,e)))).map(e=>IO(e.balance,e.symbol,e.decimals,{explorerUrl:r,token:e.token}));if(t?.includeTestnet!==!1){let t=M({chain:ye,transport:le()}),n=ye.blockExplorers?.default?.url,r=await Promise.all(XO.map(n=>UO(t,n,e)));for(let e of r)e.balance>0n&&i.push(`${IO(e.balance,e.symbol,e.decimals,{explorerUrl:n,token:e.token})} ${X.dim(`(testnet)`)}`)}return i}var X,GO,KO,qO,JO,YO,XO,ZO=I((()=>{CO(),X=(()=>{let e=process||{},t=e.argv||[],n=e.env||{},r=!(n.NO_COLOR||t.includes(`--no-color`))&&(!!n.FORCE_COLOR||t.includes(`--color`)||(e.stdout||{}).isTTY&&n.TERM!==`dumb`||!!n.CI),i=(e,t,n,r)=>{let i=``,a=0,o=r;do i+=e.substring(a,o)+n,a=o+t.length,o=e.indexOf(t,a);while(~o);return i+e.substring(a)},a=r?(e,t,n=e)=>r=>{let a=`${r}`,o=a.indexOf(t,e.length);return~o?e+i(a,t,n,o)+t:e+a+t}:()=>String;return{isColorSupported:r,reset:a(`\x1B[0m`,`\x1B[0m`),bold:a(`\x1B[1m`,`\x1B[22m`,`\x1B[22m\x1B[1m`),dim:a(`\x1B[2m`,`\x1B[22m`,`\x1B[22m\x1B[2m`),italic:a(`\x1B[3m`,`\x1B[23m`),underline:a(`\x1B[4m`,`\x1B[24m`),inverse:a(`\x1B[7m`,`\x1B[27m`),hidden:a(`\x1B[8m`,`\x1B[28m`),strikethrough:a(`\x1B[9m`,`\x1B[29m`),black:a(`\x1B[30m`,`\x1B[39m`),red:a(`\x1B[31m`,`\x1B[39m`),green:a(`\x1B[32m`,`\x1B[39m`),yellow:a(`\x1B[33m`,`\x1B[39m`),blue:a(`\x1B[34m`,`\x1B[39m`),magenta:a(`\x1B[35m`,`\x1B[39m`),cyan:a(`\x1B[36m`,`\x1B[39m`),white:a(`\x1B[37m`,`\x1B[39m`),gray:a(`\x1B[90m`,`\x1B[39m`),bgBlack:a(`\x1B[40m`,`\x1B[49m`),bgRed:a(`\x1B[41m`,`\x1B[49m`),bgGreen:a(`\x1B[42m`,`\x1B[49m`),bgYellow:a(`\x1B[43m`,`\x1B[49m`),bgBlue:a(`\x1B[44m`,`\x1B[49m`),bgMagenta:a(`\x1B[45m`,`\x1B[49m`),bgCyan:a(`\x1B[46m`,`\x1B[49m`),bgWhite:a(`\x1B[47m`,`\x1B[49m`),blackBright:a(`\x1B[90m`,`\x1B[39m`),redBright:a(`\x1B[91m`,`\x1B[39m`),greenBright:a(`\x1B[92m`,`\x1B[39m`),yellowBright:a(`\x1B[93m`,`\x1B[39m`),blueBright:a(`\x1B[94m`,`\x1B[39m`),magentaBright:a(`\x1B[95m`,`\x1B[39m`),cyanBright:a(`\x1B[96m`,`\x1B[39m`),whiteBright:a(`\x1B[97m`,`\x1B[39m`),bgBlackBright:a(`\x1B[100m`,`\x1B[49m`),bgRedBright:a(`\x1B[101m`,`\x1B[49m`),bgGreenBright:a(`\x1B[102m`,`\x1B[49m`),bgYellowBright:a(`\x1B[103m`,`\x1B[49m`),bgBlueBright:a(`\x1B[104m`,`\x1B[49m`),bgMagentaBright:a(`\x1B[105m`,`\x1B[49m`),bgCyanBright:a(`\x1B[106m`,`\x1B[49m`),bgWhiteBright:a(`\x1B[107m`,`\x1B[49m`),link(e,t,n){return r?`\x1b]8;;${e}\x07${n?t:X.underline(t)}\x1b]8;;\x07`:t}}})(),GO=new Set([`amount`,`suggestedDeposit`,`minVoucherDelta`]),KO={mainnet:SO[vO.mainnet],testnet:SO[vO.testnet]},qO=`0x20c0000000000000000000000000000000000000`,JO=`0x20C000000000000000000000b9537d11c60E8b50`,YO=[qO,JO],XO=[`0x20c0000000000000000000000000000000000000`,`0x20c0000000000000000000000000000000000001`,`0x20c0000000000000000000000000000000000002`,`0x20c0000000000000000000000000000000000003`]}));function QO(){let e=Number.parseInt(process.env.MPPX_KEYCHAIN_COMMAND_TIMEOUT_MS??``,10);return Number.isFinite(e)&&e>0?e:uk}function $O(e,t){return`code`in e&&e.code===`ENOENT`&&e.message.includes(t)}function ek(e){return new L({code:`KEYCHAIN_UNAVAILABLE`,message:`Linux keyring requires secret-tool. Install libsecret-tools.`,hint:`On Debian/Ubuntu, run: sudo apt install libsecret-tools gnome-keyring dbus-x11`,exitCode:69,cause:e})}function tk(e){if(e&&$O(e,`secret-tool`))throw ek(e)}function nk(e,t){return new Promise(n=>{m.execFile(e,t,{timeout:QO()},(e,t,r)=>{n({stdout:t.trim(),stderr:r.trim(),error:e})})})}function rk(){let e=c.join(process.env.XDG_CONFIG_HOME||c.join(b.homedir(),`.config`),`mppx`,`default`);return{get(){try{return t.readFileSync(e,`utf-8`).trim()||`main`}catch{return`main`}},set(n){t.mkdirSync(c.dirname(e),{recursive:!0}),t.writeFileSync(e,n,`utf-8`)},clear(){try{t.unlinkSync(e)}catch{}}}}function ik(e){return e||(process.env.MPPX_ACCOUNT?.trim()?process.env.MPPX_ACCOUNT:rk().get())}function ak(e=`main`){let t=lk;return{async list(){let e=b.platform();if(e===`darwin`){let{stdout:e,error:n}=await nk(`security`,[`dump-keychain`]);if(n)return[];let r=[],i=e.split(`keychain:`);for(let e of i){let n=e.match(/"svce"<blob>="([^"]*)"/),i=e.match(/"acct"<blob>="([^"]*)"/);n?.[1]===t&&i?.[1]&&r.push(i[1])}return r}if(e===`linux`){let{stdout:e,stderr:n,error:r}=await nk(`secret-tool`,[`search`,`--all`,`--unlock`,`service`,t]);if(tk(r),r)return[];let i=`${e}\n${n}`,a=[],o=i.matchAll(/\baccount = (.+)/g);for(let e of o)e[1]&&a.push(e[1]);return a}throw Error(`Unsupported platform: ${e}`)},async get(){let n=b.platform();if(n===`darwin`){let{stdout:n,error:r}=await nk(`security`,[`find-generic-password`,`-s`,t,`-a`,e,`-w`]);return r?void 0:n}if(n===`linux`){let{stdout:n,error:r}=await nk(`secret-tool`,[`lookup`,`service`,t,`account`,e]);return tk(r),r?void 0:n||void 0}throw Error(`Unsupported platform: ${n}`)},async set(n){let r=b.platform();if(r===`darwin`){await nk(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);let{error:r}=await nk(`security`,[`add-generic-password`,`-s`,t,`-a`,e,`-w`,n]);if(r)throw r;return}if(r===`linux`){let r=m.execFile(`secret-tool`,[`store`,`--label`,`${t} ${e}`,`service`,t,`account`,e]),i=setTimeout(()=>r.kill(),QO());return r.stdin?.write(n),r.stdin?.end(),new Promise((e,t)=>{r.on(`close`,n=>{clearTimeout(i),n===0?e():t(Error(`secret-tool exited with code ${n}`))}),r.on(`error`,e=>{clearTimeout(i),t($O(e,`secret-tool`)?ek(e):e)})})}throw Error(`Unsupported platform: ${r}`)},async delete(){let n=b.platform();if(n===`darwin`){await nk(`security`,[`delete-generic-password`,`-s`,t,`-a`,e]);return}if(n===`linux`){let{error:n}=await nk(`secret-tool`,[`clear`,`service`,t,`account`,e]);tk(n);return}throw Error(`Unsupported platform: ${n}`)}}}async function ok(e){let{privateKeyToAccount:t}=await import(`viem/accounts`),n=process.env.MPPX_PRIVATE_KEY?.trim();if(n)return{account:t(n),source:`environment`};let r=ik(e),i=await ak(r).get();if(i)return{account:t(i),accountName:r,source:`keychain`};throw Error(`Account "${r}" not found.`)}async function sk(e){let t=ik(e);if(!process.env.MPPX_PRIVATE_KEY?.trim()&&NO(t))throw new L({code:`UNSUPPORTED_ACCOUNT`,message:`Persistent sessions require an mppx account or MPPX_PRIVATE_KEY.`,exitCode:2});return ok(e).catch(e=>{throw new L({code:`ACCOUNT_NOT_FOUND`,message:e instanceof Error?e.message:`No account found.`,exitCode:69,...e instanceof Error&&{cause:e}})})}async function ck(e){return(await ok(e)).account}var lk,uk,dk=I((()=>{ZO(),lk=`mppx`,uk=1e4}));_O(),dk();const fk=[[`ANTIGRAVITY_CLI_ALIAS`,`antigravity`],[`CLAUDECODE`,`claude_code`],[`CLINE_ACTIVE`,`cline`],[`CODEX_SANDBOX`,`codex_cli`],[`CODEX_THREAD_ID`,`codex_cli`],[`CODEX_SANDBOX_NETWORK_DISABLED`,`codex_cli`],[`CODEX_CI`,`codex_cli`],[`CURSOR_AGENT`,`cursor`],[`GEMINI_CLI`,`gemini_cli`],[`OPENCODE`,`open_code`],[`OPENCLAW_SHELL`,`openclaw`],[`CLAUDE_CODE_ENTRYPOINT`,`claude_code`],[`CODEX_INTERNAL_ORIGINATOR_OVERRIDE`,`codex_cli`]];function pk(e=process.env){return fk.find(([t])=>e[t])?.[1]}const mk=Symbol(`mppx.x402.asset`);function hk(e){return{[mk]:!0,address:e.address,decimals:e.decimals,network:e.network,transfer:e.transfer}}function gk(e,t){let n=e(t.chainId);return hk({address:n.address,decimals:n.decimals,network:Ek(t.chainId),transfer:Ok(t.transfer,n)})}const _k={USDC:hk({address:`0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913`,decimals:6,network:`eip155:8453`,transfer:{name:`USD Coin`,type:`eip3009`,version:`2`}})},vk={USDC:hk({address:`0x036CbD53842c5426634e7929541eC2318f3dCF7e`,decimals:6,network:`eip155:84532`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})},yk={USDC:hk({address:`0xcebA9300f2b948710d2653dD7B07f33A8B32118C`,decimals:6,network:`eip155:42220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}}),USDT:hk({address:`0x48065fbBE25f71C9282ddf5e1cD6D6A887483D5e`,decimals:6,network:`eip155:42220`,transfer:{name:`Tether USD`,type:`eip3009`,version:`1`}})},bk={USDC:hk({address:`0x01C5C0122039549AD1493B8220cABEdD739BC44E`,decimals:6,network:`eip155:11142220`,transfer:{name:`USDC`,type:`eip3009`,version:`2`}})};function xk(e){return typeof e!=`object`||!e?!1:e[mk]===!0}function Sk(e){return typeof e==`function`&&typeof e.addresses==`object`&&typeof e.decimals==`number`}function Ck(e){return typeof e==`string`}function wk(e,t){if(xk(e))return e.network===t?{address:e.address,decimals:e.decimals,transfer:e.transfer}:void 0;if(Sk(e)){let n=e.addresses[Dk(t)];return n?{address:n,decimals:e.decimals,name:e.name}:void 0}return{address:e}}function Tk(e,t,n){let r=wk(e,n);return r?N(r.address)===N(t):!1}function Ek(e){return`eip155:${e}`}function Dk(e){return Number(e.slice(7))}function Ok(e,t){if(e.type!==`eip3009`)return e;if(e.name)return{...e,name:e.name};if(!t.name)throw Error(`EIP-3009 token assets require a token name.`);return{...e,name:t.name}}var kk=Ze({base:()=>_k,baseSepolia:()=>vk,celo:()=>yk,celoSepolia:()=>bk,define:()=>hk,fromToken:()=>gk,isAsset:()=>xk,isRawAddress:()=>Ck,isToken:()=>Sk,matches:()=>Tk,resolve:()=>wk,toChainId:()=>Dk,toNetwork:()=>Ek}),Ak=Ze({base:()=>jk,baseSepolia:()=>Mk,celo:()=>Nk,celoSepolia:()=>Pk});const jk=8453,Mk=84532,Nk=42220,Pk=11142220;zx();function Fk(e){let t=[Rx(e.accepted),Rx(e.resource),Rx(e.extensions)].join(`|`);return te.sha256(A.fromString(t),{as:`Hex`})}aw(),AC();async function Ik(e){let t=e.context?.account??e.config.account;if(!t?.signTypedData)throw Error(`x402 exact requires a typed-data signer.`);let n=e.challenge.request,r=sC(n);if(Bk(e.config,r),!n.resource)throw Error(`x402 exact EIP-3009 requires resource information.`);let i=n.extensions?.mppx?Hk(n.extensions):n.extensions,a=r.extra?.assetTransferMethod??`eip3009`;if(a!==`eip3009`)throw Error(`x402 exact ${String(a)} signing is not implemented yet.`);let o=r.extra?.name,s=r.extra?.version;if(typeof o!=`string`||typeof s!=`string`)throw Error(`x402 exact EIP-3009 requires token name and version.`);let c=Math.floor(Date.now()/1e3),l={from:N(t.address),nonce:i?.mppx?Fk({accepted:r,extensions:i,resource:n.resource}):Wk(),to:N(r.payTo),validAfter:(c-600).toString(),validBefore:(c+r.maxTimeoutSeconds).toString(),value:r.amount},u=await t.signTypedData({domain:{chainId:zk(r.network),name:o,verifyingContract:N(r.asset),version:s},message:{...l,value:BigInt(l.value),validAfter:BigInt(l.validAfter),validBefore:BigInt(l.validBefore)},primaryType:`TransferWithAuthorization`,types:Rk});return rw({accepted:r,...i?{extensions:i}:{},payload:{authorization:l,signature:u},...n.resource?{resource:n.resource}:{},x402Version:2})}function Lk(e){let t=e.challenge.request,n;try{n=sC(t),Bk(e.config,n)}catch{return!1}if(!t.resource||(n.extra?.assetTransferMethod??`eip3009`)!==`eip3009`)return!1;let r=n.extra?.name,i=n.extra?.version;return typeof r==`string`&&typeof i==`string`}const Rk={TransferWithAuthorization:[{name:`from`,type:`address`},{name:`to`,type:`address`},{name:`value`,type:`uint256`},{name:`validAfter`,type:`uint256`},{name:`validBefore`,type:`uint256`},{name:`nonce`,type:`bytes32`}]};function zk(e){return Number(e.slice(uC.length))}function Bk(e,t){let n=zk(t.network);if(e.networks&&!e.networks.includes(n))throw Error(`x402 exact chain ID is not allowed: ${n}.`);let r=e.currencies??e.assets;if(r?.some(e=>Ck(e))&&!e.networks?.length)throw Error(`x402 exact raw currency allowlists require networks.`);if(r){let e=N(t.asset);if(!r.some(n=>Tk(n,e,t.network)))throw Error(`x402 exact currency is not allowed: ${e}.`)}if(e.maxAtomicAmount!==void 0&&BigInt(t.amount)>BigInt(e.maxAtomicAmount))throw Error(`x402 exact amount exceeds maxAtomicAmount.`);if(e.maxAmount!==void 0){let n=Vk(e,t);if(n===void 0)throw Error(`x402 exact maxAmount requires currency decimals.`);if(BigInt(t.amount)>P(e.maxAmount,n))throw Error(`x402 exact amount exceeds maxAmount.`)}}function Vk(e,t){let n=e.currencies??e.assets,r=N(t.asset),i=n?.find(e=>Tk(e,r,t.network)),a=i?wk(i,t.network):void 0;return a?.decimals===void 0?e.decimals:a.decimals}function Hk(e){let t=e.mppx;return t?{...e,mppx:{...t,info:{...t.info,nonce:Uk()}}}:e}function Uk(){return Gk().slice(2)}function Wk(){return Gk()}function Gk(){let e=globalThis.crypto;if(!e?.getRandomValues)throw Error(`x402 exact requires crypto randomness.`);let t=e.getRandomValues(new Uint8Array(32));return`0x${Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}`}Zx();const Kk=[`authorization`],qk=J.string().check(J.regex(/^\d+$/,`Invalid atomic amount`));J.object({name:J.string().check(J.minLength(1)),version:J.string().check(J.minLength(1))});const Jk=J.object({chainId:J.number(),credentialTypes:J.optional(J.array(J.enum(Kk)).check(J.minLength(1))),decimals:J.optional(J.number()),permit2Address:J.optional(Kx()),splits:J.optional(J.array(J.object({amount:qk,recipient:Kx()})))});J.object({amount:qk,currency:Kx(),description:J.optional(J.string()),externalId:J.optional(J.string()),methodDetails:Jk,recipient:Kx()});const Yk=J.object({amount:Vx(),chainId:J.number(),currency:Kx(),credentialTypes:J.optional(J.array(J.enum(Kk)).check(J.minLength(1))),decimals:J.number(),description:J.optional(J.string()),externalId:J.optional(J.string()),permit2Address:J.optional(Kx()),recipient:Kx(),splits:J.optional(J.array(J.object({amount:qk,recipient:Kx()})))}),Xk=J.object({from:Kx(),nonce:qx(),signature:Yx(),to:Kx(),type:J.literal(`authorization`),validAfter:qk,validBefore:qk,value:qk}),Zk={TransferWithAuthorization:[{name:`from`,type:`address`},{name:`to`,type:`address`},{name:`value`,type:`uint256`},{name:`validAfter`,type:`uint256`},{name:`validBefore`,type:`uint256`},{name:`nonce`,type:`bytes32`}]};function Qk(e){return{chainId:e.chainId,name:e.authorization.name,verifyingContract:e.currency,version:e.authorization.version}}function $k(e){return te.keccak256(A.fromString(JSON.stringify([e.id,e.realm])),{as:`Hex`})}function eA(e){return`eip155:${e}`}function tA(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}oE(),Zx();const nA=iE({name:`evm`,intent:`charge`,schema:{credential:{payload:Xk},request:J.pipe(Yk,J.transform(({amount:e,chainId:t,credentialTypes:n=[`authorization`],currency:r,decimals:i,permit2Address:a,recipient:o,splits:s,...c})=>({...c,amount:P(e,i).toString(),currency:N(r),methodDetails:{chainId:t,credentialTypes:n,decimals:i,...a?{permit2Address:N(a)}:{},...s?{splits:s}:{}},recipient:N(o)})))}});rC(),oE(),OS(),Zx();function rA(e){return aE(nA,{canHandleChallenge({challenge:t}){return!iA(t)||Lk({challenge:t,config:e})},context:J.object({account:J.optional(J.custom())}),async createCredential({challenge:t,context:n}){if(iA(t))return Ik({challenge:t,config:e,context:n});let r=n?.account??e.account;if(!r?.signTypedData)throw Error(`EVM authorization requires a typed-data signer.`);let i=t.request;if(aA(e,i),!i.methodDetails.credentialTypes?.includes(`authorization`))throw Error(`EVM authorization is not accepted by this challenge.`);if(i.methodDetails.splits?.length)throw Error(`EVM authorization does not support payment splits.`);let a=oA(e,i),o=t.expires?Math.floor(new Date(t.expires).getTime()/1e3).toString():(Math.floor(Date.now()/1e3)+300).toString();return $S(QS({challenge:t,payload:{from:N(r.address),nonce:$k(t),signature:await r.signTypedData({domain:Qk({authorization:a,chainId:i.methodDetails.chainId,currency:i.currency}),message:{from:N(r.address),nonce:$k(t),to:N(i.recipient),validAfter:0n,validBefore:BigInt(o),value:BigInt(i.amount)},primaryType:`TransferWithAuthorization`,types:Zk}),to:N(i.recipient),type:`authorization`,validAfter:`0`,validBefore:o,value:i.amount},source:tA({address:N(r.address),chainId:i.methodDetails.chainId})}))}})}function iA(e){return ES(e)&&e.request.scheme===`exact`&&typeof e.request.network==`string`}function aA(e,t){let n=t.methodDetails.chainId,r=eA(n);if(e.networks&&!e.networks.includes(n))throw Error(`EVM chain ID is not allowed: ${n}.`);let i=e.currencies??e.assets;if(i?.some(e=>Ck(e))&&!e.networks?.length)throw Error(`EVM raw currency allowlists require networks.`);if(i){let e=N(t.currency);if(!i.some(t=>Tk(t,e,r)))throw Error(`EVM currency is not allowed: ${e}.`)}if(e.maxAtomicAmount!==void 0&&BigInt(t.amount)>BigInt(e.maxAtomicAmount))throw Error(`EVM charge amount exceeds maxAtomicAmount.`);if(e.maxAmount!==void 0){let n=sA(e,t);if(n===void 0)throw Error(`EVM charge maxAmount requires currency decimals.`);if(BigInt(t.amount)>P(e.maxAmount,n))throw Error(`EVM charge amount exceeds maxAmount.`)}}function oA(e,t){let n=e.currencies??e.assets,r=N(t.currency),i=eA(t.methodDetails.chainId),a=n?.find(e=>Tk(e,r,i)),o=a?wk(a,i):void 0;if(o?.transfer?.type===`eip3009`)return{name:o.transfer.name,version:o.transfer.version};if(e.authorization)return e.authorization;throw Error(`EVM authorization requires token name and version.`)}function sA(e,t){let n=e.currencies??e.assets,r=N(t.currency),i=eA(t.methodDetails.chainId),a=n?.find(e=>Tk(e,r,i)),o=a?wk(a,i):void 0;return o?.decimals===void 0?e.decimals:o.decimals}function cA(e){return[cA.charge(e)]}(function(e){e.charge=rA,e.assets=kk,e.chains=Ak})(cA||={});function lA(e){return e}var uA=I((()=>{}));OS(),uA();function dA(){return lA({method:`evm`,supports:e=>e.method===`evm`&&!ES(e),async setup({challenge:e,options:t}){let n=e.request,r=n.methodDetails,i=r?.chainId,a=i?fA(i):void 0,o=n.currency,s=await ck(t.account),c=[...Object.values(_k),...Object.values(vk),...Object.values(yk),...Object.values(bk)],l=o??``;if(a&&o)try{let e=M({chain:a,transport:le()}),t=await De(e,{address:o,abi:oe,functionName:`symbol`});t&&(l=t)}catch{}return{tokenSymbol:l,tokenDecimals:r?.decimals??6,explorerUrl:a?.blockExplorers?.default?.url,methods:[...cA({account:s,currencies:c})]}}})}function fA(e){return Object.values(Be).find(t=>t.id===e)}function pA(e,t){if(!Number.isInteger(t)||t<0)throw RangeError(`Decimals must be a non-negative integer.`);if(!/^-?(?:\d+(?:\.\d*)?|\.\d+)$/.test(e))throw TypeError(`Value \`${e}\` is not a valid decimal number.`);let n=e.startsWith(`-`),[r=`0`,i=``]=(n?e.slice(1):e).split(`.`),a=i.slice(0,t).padEnd(t,`0`),o=BigInt(`${r||`0`}${a}`);return i.length>t&&i[t]>=`5`&&(o+=1n),n?-o:o}Zx();const mA=J.object({customer:J.optional(J.string().check(J.minLength(1))),hooks:J.optional(J.object({inputs:J.object({tax:J.object({calculation:J.string().check(J.minLength(1))})})})),metadata:J.optional(J.record(J.string(),J.string())),receipt_email:J.optional(J.string().check(J.minLength(1)))}),hA=J.custom(e=>typeof e==`function`),gA=J.union([mA,hA]);oE(),Zx();const _A=iE({name:`stripe`,intent:`charge`,schema:{credential:{payload:J.object({externalId:J.optional(J.string()),spt:J.string()})},request:J.pipe(J.object({amount:Vx(),currency:J.string(),decimals:J.number(),description:J.optional(J.string()),externalId:J.optional(J.string()),metadata:J.optional(J.record(J.string(),J.string())),networkId:J.string(),paymentIntentOptions:J.optional(gA),paymentMethodTypes:J.array(J.string()).check(J.minLength(1)),recipient:J.optional(J.string())}),J.transform(({amount:e,decimals:t,metadata:n,networkId:r,paymentIntentOptions:i,paymentMethodTypes:a,...o})=>({...o,amount:pA(e,t).toString(),methodDetails:{networkId:r,paymentMethodTypes:a,...n!==void 0&&{metadata:n}}})))}});rC(),oE(),Zx();function vA(e){let{client:t,createToken:n,externalId:r,paymentMethod:i}=e;return aE(_A,{context:J.object({paymentMethod:J.optional(J.string())}),async createCredential({challenge:e,context:a}){let o=a?.paymentMethod??i;if(!o)throw Error(`paymentMethod is required (pass via context or parameters)`);let s=e.request.amount,c=e.request.currency,l=typeof e.request.externalId==`string`?e.request.externalId:void 0,u=e.request.methodDetails?.networkId;if(!u)throw Error(`networkId is required in challenge.methodDetails`);let d=e.request.methodDetails?.metadata;if(d?.externalId)throw Error(`methodDetails.metadata.externalId is reserved; use credential externalId instead`);let f=e.expires?Math.floor(new Date(e.expires).getTime()/1e3):Math.floor(Date.now()/1e3)+3600,p=await n({amount:s,challenge:e,client:t,currency:c,expiresAt:f,metadata:d,networkId:u,paymentMethod:o}),m=l??r;return $S({challenge:e,payload:{spt:p,...m===void 0?{}:{externalId:m}}})}})}function yA(e){return[vA(e)]}(function(e){e.charge=vA})(yA||={}),Ox(),ZO(),uA();function bA(){return lA({method:`stripe`,supports(e){return e.method===`stripe`&&e.intent===`charge`},async setup({challenge:e,methodOpts:t}){let n=e.request,r=n.currency,i=SA(p.object({paymentMethod:p.string(),secretKey:p.string().optional()}),t,[`paymentMethod`,`secretKey`]),a=i.secretKey??process.env.MPPX_STRIPE_SECRET_KEY;if(!a)throw new L({code:`MISSING_ENV`,message:`MPPX_STRIPE_SECRET_KEY environment variable is required for Stripe payments.`,exitCode:2});return{tokenSymbol:r?.toUpperCase()??``,tokenDecimals:n.decimals??2,methods:[yA.charge({paymentMethod:i.paymentMethod,createToken:async({paymentMethod:e,amount:t,currency:n,networkId:r,expiresAt:i,metadata:o})=>{let s=new URLSearchParams({payment_method:e,"usage_limits[currency]":n,"usage_limits[max_amount]":t,"usage_limits[expires_at]":i.toString()}),c=xA(a),l=process.env.MPPX_STRIPE_SPT_URL?process.env.MPPX_STRIPE_SPT_URL:c?`https://api.stripe.com/v1/test_helpers/shared_payment/granted_tokens`:`https://api.stripe.com/v1/shared_payment/issued_tokens`;if(r){let e=c?`seller_details[network_id]`:`seller_details[network_business_profile]`;s.set(e,r)}if(o)for(let[e,t]of Object.entries(o))s.set(`metadata[${e}]`,t);let u={Authorization:`Basic ${btoa(`${a}:`)}`,"Content-Type":`application/x-www-form-urlencoded`,"Stripe-Version":`2026-07-29.preview`},d=await globalThis.fetch(l,{method:`POST`,headers:u,body:s});if(!d.ok){let a=await d.json();if(c&&(o||r)&&a.error.message.includes(`Received unknown parameter`)){let r=new URLSearchParams({payment_method:e,"usage_limits[currency]":n,"usage_limits[max_amount]":t,"usage_limits[expires_at]":i.toString()});if(d=await globalThis.fetch(l,{method:`POST`,headers:u,body:r}),!d.ok){let e=await d.json();throw new L({code:`STRIPE_ERROR`,message:`Failed to create SPT: ${e.error.message}`,exitCode:77})}}else throw new L({code:`STRIPE_ERROR`,message:`Failed to create SPT: ${a.error.message}`,exitCode:77})}let{id:f}=await d.json();return f}})]}},formatReceiptField(e,t){if(e===`reference`&&typeof t==`string`&&t.startsWith(`pi_`)){let e=process.env.MPPX_STRIPE_SECRET_KEY,n=`https://dashboard.stripe.com${e!==void 0&&xA(e)?`/test`:``}/payments/${t}`;return X.link(n,t,!0)}}})}function xA(e){return e.startsWith(`sk_test_`)||e.startsWith(`rk_test_`)}function SA(e,t,n){if(t&&typeof t==`object`&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!n.includes(e));if(e.length)throw Error(`Unsupported CLI method option(s): ${e.join(`, `)}`)}let r=e.safeParse(t??{});if(r.success)return r.data;let i=r.error.issues.map(e=>`${e.path.length?e.path.join(`.`):`options`}: ${e.message}`).join(`, `);throw Error(`Invalid CLI options (${i})`)}function CA(e={}){let{account:t}=e;return(e,{account:n}={})=>{let r=n??t;if(!r){if(!e.account)throw Error("No `account` provided. Pass `account` to parameters or context.");return e.account}return ge(r)}}var wA=I((()=>{}));function TA(e){return Object.fromEntries(Object.entries(e.headers??{}).filter(([e])=>e.toLowerCase()!==`content-type`))}var EA=I((()=>{}));function DA(e,t={}){return le(e.url,{fetchFn:e.fetch,fetchOptions:{headers:TA(e)},...t})}function OA(e){let{chain:t,getClient:n,remoteFeePayer:r,rpcUrl:i}=e;return n?!t?.serializers&&!r?n:async e=>{let i=await n(e),a=i;if(r&&i.transport.key!==`feePayer`){let e=i.request.bind(i),t=ze(ie({request:t=>e(t)},{retryCount:0}),DA(r,{retryCount:i.transport.retryCount}))({account:i.account,chain:i.chain,pollingInterval:i.pollingInterval,retryCount:0}),n=re({...t.config,retryCount:0},t.value);a=Object.assign({},i,{request:n.request,transport:{...n.config,...n.value}})}return!t?.serializers||a.chain?.serializers?.transaction?a:Object.assign({},a,{chain:{...t,...e.chainId===void 0?{}:{id:e.chainId},...a.chain,formatters:a.chain?.formatters??t.formatters,prepareTransactionRequest:a.chain?.prepareTransactionRequest??t.prepareTransactionRequest,serializers:a.chain?.serializers?.transaction?a.chain.serializers:t.serializers}})}:({chainId:e})=>{if(!i)throw Error("No `rpcUrl` provided.");let n=e||Number(Object.keys(i)[0]),a=i[n];if(!a)throw Error(`No \`rpcUrl\` configured for \`chainId\` (${n}).`);let o=r?ze(le(a),DA(r)):le(a);return M({chain:jA[n]??{...t,id:n},transport:o})}}function kA(e,t){if(t!==void 0&&e.chain?.id!==void 0&&e.chain.id!==t)throw Error(`Chain ID mismatch: expected ${t}, got ${e.chain.id}.`)}function AA(e,t){if(e!==void 0&&(t===void 0||!e.includes(t)))throw Error(`Chain ID not allowed: ${t??`unknown`}.`)}var jA,MA=I((()=>{EA(),jA={[ve.id]:ve,[ye.id]:ye}}));function NA(e){let t=te.keccak256(A.fromString(e),{as:`Hex`});return ne.toBytes(ne.slice(t,0,10))}function PA(e){let{serverId:t,clientId:n,challengeId:r}=e,i=new Uint8Array(32);return i.set(ne.toBytes(IA),0),i[4]=LA,i.set(NA(t),5),n&&i.set(NA(n),15),i.set(FA(r),25),ne.fromBytes(i)}function FA(e){let t=te.keccak256(A.fromString(e),{as:`Hex`});return ne.toBytes(ne.slice(t,0,7))}var IA,LA,RA=I((()=>{IA=ne.slice(te.keccak256(A.fromString(`mpp`),{as:`Hex`}),0,4),LA=1}));function zA(e,t){return Ge.resolve(e).toLowerCase()===Ge.resolve(t).toLowerCase()}var BA=I((()=>{}));async function VA(e,t){let{account:n,amountOut:r,tokenOut:i,tokenIn:a,slippage:o}=t;if(!Number.isFinite(o)||o<0||o>50)throw Error(`Auto-swap slippage must be between 0 and 50 percent.`);if(t.maxAmountIn!==void 0&&t.maxAmountIn<=0n)throw Error(`Auto-swap maxAmountIn must be positive.`);let s=a.filter(e=>!zA(e,i)),c=await Promise.allSettled([De(e,{...Fe.token.getBalance.call(e,{account:n,token:i}),account:null}),...s.map(t=>De(e,{...Fe.token.getBalance.call(e,{account:n,token:t}),account:null}))]),l=c[0];if(l.status!==`fulfilled`)throw l.reason;let u=l.value;if(u>=r)return;let d=r-u,f=BigInt(Math.round(o*100)),p=t.maxAmountIn??d+d*f/UA;for(let t=0;t<s.length;t++){let n=c[t+1];if(n.status!==`fulfilled`)continue;let r=n.value;if(r<=0n)continue;let a=s[t];try{let t=await Fe.dex.getBuyQuote(e,{account:null,tokenIn:a,tokenOut:i,amountOut:d});if(t<=0n||t>p)continue;let n=t+t*f/UA,o=n<p?n:p;if(r>=o)return[Fe.token.approve.call(e,{amount:o,spender:Ie.stablecoinDex,token:a}),Fe.dex.buy.call({tokenIn:a,tokenOut:i,amountOut:d,maxAmountIn:o})]}catch{}}throw new GA({currency:i})}function HA(e,t){return e?e===!0?{tokenIn:t,slippage:1}:{tokenIn:e.tokenIn?[...e.tokenIn,...e.fallback===!1?[]:t.filter(t=>!e.tokenIn.some(e=>zA(e,t)))]:t,slippage:e.slippage??1,...e.maxAmountIn===void 0?{}:{maxAmountIn:e.maxAmountIn}}:!1}var UA,WA,GA,KA=I((()=>{BA(),CO(),UA=10000n,WA=[yO.pathUsd,yO.usdc,yO.ousd],GA=class extends Error{name=`InsufficientFundsError`;constructor({currency:e}){super(`Insufficient funds: no balance in ${e} and no viable swap route from fallback currencies.`)}}}));function qA(e){let t=BigInt(e.amount),n=e.methodDetails?.splits??[],r=n.reduce((e,t)=>e+BigInt(t.amount),0n);if(r>=t)throw Error(`Invalid charge request: split total must be less than total amount.`);let i=t-r;if(i<=0n)throw Error(`Invalid charge request: primary transfer amount must be positive.`);return[{amount:i.toString(),memo:e.methodDetails?.memo,recipient:e.recipient},...n.map(e=>({amount:e.amount,memo:e.memo,recipient:e.recipient}))]}var JA=I((()=>{}));function YA(e,t,n){t&&(n&&!n.some(e=>zA(e,t))||e.some(e=>zA(e,t))||e.push(t))}async function XA(e,t,n){try{return(await Fe.token.getBalance(e,{account:t,token:n})).amount>0n}catch{return!1}}function ZA(e){let t=e.chain?.feeToken;if(t)return Le.toAddress(t);let n=e.chain?.id;return n?bO[n]:void 0}function QA(e){let t=[];return YA(t,yO.pathUsd),YA(t,bO[e]),t}async function $A(e){let{account:t,allowedTokens:n,candidateTokens:r,client:i,prioritizeCandidates:a}=e,o=[];if(a)for(let e of r??[])YA(o,e,n);if(YA(o,await Fe.fee.getUserToken(i,{account:t}).then(e=>e?.address).catch(()=>void 0),n),YA(o,ZA(i),n),!a)for(let e of r??[])YA(o,e,n);for(let e of o)if(await XA(i,t,e))return e;return o[0]}var ej=I((()=>{BA(),CO()}));function tj(e){if(e!==void 0)return xO[e]}function nj(e){let t=tj(e.chainId);return!!t&&ue(e.currency,{strict:!1})&&de(e.currency,t.token)}function rj(e){let t=tj(e.chainId),n=e.transfers.length===1?e.transfers[0]:void 0;if(!t||!n?.memo)return;let r=BigInt(n.amount),i=n.memo;return{calls:[{data:ae({abi:Ne.tip20,functionName:`approve`,args:[t.swap,r]}),to:t.token},{data:ae({abi:aj,functionName:`swapTo`,args:[t.token,r,e.currency,n.recipient,i]}),to:t.swap}],settlementSender:t.swap,transfers:[{amount:r,memo:i,recipient:n.recipient}]}}async function ij(e,t){let n=rj(t);if(n)try{return await De(e,Fe.token.getBalance.call(e,{account:t.account,token:n.calls[0].to}))<n.transfers[0].amount?void 0:(await Te(e,{account:t.account,calls:n.calls}),n)}catch{return}}var aj,oj=I((()=>{CO(),aj=pe([`function swapTo(address inputToken,uint256 amount,address targetToken,address recipient,bytes32 memo)`])}));function sj(e){return{name:`MPP`,version:`3`,chainId:e}}function cj(e){let{account:t,challengeId:n,realm:r}=e;return{account:t,challengeId:n,realm:r}}function lj(e){let{account:t,chainId:n,challengeId:r,realm:i}=e;return{domain:sj(n),types:fj,primaryType:dj,message:cj({account:t,challengeId:r,realm:i})}}function uj(e){return`did:pkh:eip155:${e.chainId}:${e.address}`}var dj,fj,pj=I((()=>{dj=`Proof`,fj={Proof:[{name:`account`,type:`address`},{name:`challengeId`,type:`string`},{name:`realm`,type:`string`}]}}));function mj(e={}){let{clientId:t}=e;if((e.maxAmount!==void 0||e.maxAtomicAmount!==void 0)&&e.currencies===void 0)throw Error(`Tempo charge maxAmount and maxAtomicAmount require currencies.`);let n={maxAmount:gj(e.maxAmount,e.decimals),maxAtomicAmount:e.maxAtomicAmount===void 0?void 0:BigInt(e.maxAtomicAmount)},r=OA({chain:ve,getClient:e.getClient,rpcUrl:SO}),i=CA({account:e.account}),a=aE(yE,{canHandleChallenge({challenge:t}){try{return _j(e,n,t.request),!0}catch{return!1}},context:vj,async createCredential({challenge:a,context:o}){_j(e,n,a.request);let s=a.request.methodDetails?.chainId??e.expectedChainId??(e.allowedChainIds?.length===1?e.allowedChainIds[0]:void 0),c=await r({chainId:s});kA(c,s);let l=s??c.chain?.id;if(AA(e.allowedChainIds,l),l===void 0)throw Error("No `chainId` provided. Pass a chain ID in the challenge or client.");let{request:u}=a,{amount:d,methodDetails:f}=u,p=f?.supportedModes??[`pull`,`push`],m=i(c,o),h=async t=>await e.resolveAccount?.({account:m,chainId:l,operation:t})??m;if(BigInt(d)===0n){let e=await h({kind:`signPaymentProof`});return $S({challenge:a,payload:{signature:await je(c,{account:e,...lj({account:e.address,chainId:l,challengeId:a.id,realm:a.realm})}),type:`proof`},source:uj({address:e.address,chainId:l})})}let g=u.currency,_=nj({chainId:l,currency:g}),v=PA({challengeId:a.id,clientId:t,serverId:a.realm}),y=qA({amount:d,methodDetails:{...f,memo:v},recipient:u.recipient}),b=y.map(e=>Fe.token.transfer.call(c,{amount:BigInt(e.amount),...e.memo&&{memo:e.memo},to:e.recipient,token:g})),x=HA(o?.autoSwap??e.autoSwap,WA),S=f?.machineTokenEnabled===!0?rj({chainId:l,currency:g,transfers:y}):void 0,C=m,w;if(S){let e=await(async()=>{try{return await h({calls:S.calls,kind:`executeCalls`})}catch{return}})();e&&(w=await ij(c,{account:e.address,chainId:l,currency:g,transfers:y}),w&&(C=e))}let T;w||(C=await h({kind:`executeCalls`,...x?{}:{calls:b}}),T=x?await VA(c,{account:C.address,amountOut:BigInt(d),tokenOut:g,tokenIn:x.tokenIn,slippage:x.slippage,maxAmountIn:x.maxAmountIn}):void 0);let ee=w?.calls??[...T??[],...b],E=QA(l),D=w||_?await $A({account:C.address,allowedTokens:E,candidateTokens:E,client:c,prioritizeCandidates:!0}):void 0,O=(()=>{let t=o?.mode??e.mode;if(t){if(!p.includes(t))throw Error(`Challenge does not support ${t} mode.`);return t}let n=C.type===`json-rpc`?`push`:`pull`;return p.includes(n)?n:p[0]})(),k=(()=>{let e=Math.floor(Date.now()/1e3)+25;if(!a.expires)return e;let t=Math.floor(new Date(a.expires).getTime()/1e3)+1;return Math.min(e,t)})();if(O===`push`){let{receipts:e}=C.type===`local`?{receipts:[await ke(c,{account:C,calls:ee,...D?{feeToken:D}:{},nonceKey:`expiring`,validBefore:k})]}:await Oe(c,{account:C,...D?{capabilities:{feeToken:D}}:{},calls:ee,experimental_fallback:ee.length===1,forceAtomic:ee.length>1}),t=e?.[0]?.transactionHash;if(!t)throw Error(`No transaction receipt returned.`);return $S({challenge:a,payload:{hash:t,type:`hash`},source:uj({address:C.address,chainId:l})})}let A=await Ee(c,{account:C,calls:ee,...D?{feeToken:D}:{},nonceKey:`expiring`,validBefore:k});if(A.gas=(A.gas??0n)+5000n,f?.feePayer){let e=A;delete e.feePayerSignature,delete e.feeToken,e.feePayer=!0}return $S({challenge:a,payload:{signature:await Ae(c,A),type:`transaction`},source:uj({address:C.address,chainId:l})})}}),o=new Map,s=async t=>{_j(e,n,t.challenge.request);let r=t.context?.account??e.account,i=`${(typeof r==`string`?r:r?.address)?.toLowerCase()??``}:${t.challenge.id}`,s=o.get(i);return s||(s=a.createCredential(t).finally(()=>o.delete(i)),o.set(i,s)),s};return Sw({...a,createCredential:s},hj)}function hj(e){let t=yE.schema.credential.payload.safeParse(YS(e).payload);if(!t.success)return;let n=t.data;if(n.type===`hash`)return n.hash;let r=n.signature;if(n.type!==`transaction`||!r.startsWith(Ke.serializedType))return;let i=Ke.deserialize(r);if(!(!i.signature||i.feePayerSignature===null)&&Ke.serialize(i)===r)return fe(r)}function gj(e,t){if(e!==void 0){if(t===void 0)throw Error(`Tempo charge maxAmount requires currency decimals.`);if((e.split(`.`)[1]?.replace(/0+$/,``)??``).length>t)throw Error(`Tempo charge maxAmount ${e} has more fractional digits than ${t} decimals allow.`);return P(e,t)}}function _j(e,t,n){let{amount:r,methodDetails:i,recipient:a}=n,o=i?.chainId;if(e.expectedChainId!==void 0&&o!==void 0&&o!==e.expectedChainId)throw Error(`Chain ID mismatch: expected ${e.expectedChainId}, got ${o}.`);if((o!==void 0||e.allowedChainIds?.length===0)&&AA(e.allowedChainIds,o),e.currencies&&!e.currencies.some(e=>e.toLowerCase()===n.currency.toLowerCase()))throw Error(`Tempo charge currency is not allowed: ${n.currency}.`);if(e.expectedRecipients){let t=new Set(e.expectedRecipients.map(e=>e.toLowerCase()));if(!a||!t.has(a.toLowerCase()))throw Error(`Unexpected primary recipient: ${a}`);let n=i?.splits;if(n){for(let e of n)if(!t.has(e.recipient.toLowerCase()))throw Error(`Unexpected split recipient: ${e.recipient}`)}}if(t.maxAtomicAmount!==void 0&&BigInt(r)>t.maxAtomicAmount)throw Error(`Tempo charge amount exceeds maxAtomicAmount.`);if(t.maxAmount!==void 0&&BigInt(r)>t.maxAmount)throw Error(`Tempo charge amount exceeds maxAmount.`)}var vj,yj=I((()=>{Dw(),rC(),oE(),wA(),MA(),Zx(),RA(),KA(),JA(),CO(),ej(),oj(),pj(),SE(),vj=J.object({account:J.optional(J.custom()),autoSwap:J.optional(J.custom()),mode:J.optional(J.enum(lE))})}));function bj(e){return BigInt(e.authorizedSigner)===0n?e.payer:e.authorizedSigner}function xj(e){let t=O.encode(O.from([`address payer`,`address payee`,`address operator`,`address token`,`bytes32 salt`,`address authorizedSigner`,`bytes32 expiringNonceHash`,`address escrow`,`uint256 chainId`]),[e.payer,e.payee,e.operator,e.token,e.salt,e.authorizedSigner,e.expiringNonceHash,e.escrow??`0x4d50500000000000000000000000000000000000`,BigInt(e.chainId)]);return te.keccak256(t)}function Sj(e){return Ke.encodeForSigning(e)}function Cj(e){let{feePayer:t,transaction:n}=e;return t?{...n,feePayerSignature:null}:n}function wj(e,t){return te.keccak256(ne.concat(Sj(e),t.sender))}var Tj=I((()=>{GE()})),Ej,Dj,Oj,kj,Aj=I((()=>{Ej=[{name:`payer`,type:`address`},{name:`payee`,type:`address`},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`salt`,type:`bytes32`},{name:`authorizedSigner`,type:`address`},{name:`expiringNonceHash`,type:`bytes32`}],Dj=[{name:`settled`,type:`uint96`},{name:`deposit`,type:`uint96`},{name:`closeRequestedAt`,type:`uint32`}],Oj={name:`descriptor`,type:`tuple`,components:Ej},kj=[{type:`function`,name:`CLOSE_GRACE_PERIOD`,stateMutability:`view`,inputs:[],outputs:[{type:`uint64`}]},{type:`function`,name:`VOUCHER_TYPEHASH`,stateMutability:`view`,inputs:[],outputs:[{type:`bytes32`}]},{type:`function`,name:`open`,stateMutability:`nonpayable`,inputs:[{name:`payee`,type:`address`},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`deposit`,type:`uint96`},{name:`salt`,type:`bytes32`},{name:`authorizedSigner`,type:`address`}],outputs:[{name:`channelId`,type:`bytes32`}]},{type:`function`,name:`settle`,stateMutability:`nonpayable`,inputs:[Oj,{name:`cumulativeAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`topUp`,stateMutability:`nonpayable`,inputs:[Oj,{name:`additionalDeposit`,type:`uint96`}],outputs:[]},{type:`function`,name:`close`,stateMutability:`nonpayable`,inputs:[Oj,{name:`cumulativeAmount`,type:`uint96`},{name:`captureAmount`,type:`uint96`},{name:`signature`,type:`bytes`}],outputs:[]},{type:`function`,name:`requestClose`,stateMutability:`nonpayable`,inputs:[Oj],outputs:[]},{type:`function`,name:`withdraw`,stateMutability:`nonpayable`,inputs:[Oj],outputs:[]},{type:`function`,name:`getChannel`,stateMutability:`view`,inputs:[Oj],outputs:[{type:`tuple`,components:[{name:`descriptor`,type:`tuple`,components:Ej},{name:`state`,type:`tuple`,components:Dj}]}]},{type:`function`,name:`getChannelState`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`}],outputs:[{type:`tuple`,components:Dj}]},{type:`function`,name:`getChannelStatesBatch`,stateMutability:`view`,inputs:[{name:`channelIds`,type:`bytes32[]`}],outputs:[{type:`tuple[]`,components:Dj}]},{type:`function`,name:`computeChannelId`,stateMutability:`view`,inputs:[{name:`payer`,type:`address`},{name:`payee`,type:`address`},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`salt`,type:`bytes32`},{name:`authorizedSigner`,type:`address`},{name:`expiringNonceHash`,type:`bytes32`}],outputs:[{type:`bytes32`}]},{type:`function`,name:`getVoucherDigest`,stateMutability:`view`,inputs:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}],outputs:[{type:`bytes32`}]},{type:`function`,name:`domainSeparator`,stateMutability:`view`,inputs:[],outputs:[{type:`bytes32`}]},{type:`event`,name:`ChannelOpened`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`operator`,type:`address`},{name:`token`,type:`address`},{name:`authorizedSigner`,type:`address`},{name:`salt`,type:`bytes32`},{name:`expiringNonceHash`,type:`bytes32`},{name:`deposit`,type:`uint96`}]},{type:`event`,name:`Settled`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`cumulativeAmount`,type:`uint96`},{name:`deltaPaid`,type:`uint96`},{name:`newSettled`,type:`uint96`}]},{type:`event`,name:`TopUp`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`additionalDeposit`,type:`uint96`},{name:`newDeposit`,type:`uint96`}]},{type:`event`,name:`CloseRequested`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`closeGraceEnd`,type:`uint256`}]},{type:`event`,name:`ChannelClosed`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0},{name:`settledToPayee`,type:`uint96`},{name:`refundedToPayer`,type:`uint96`}]},{type:`event`,name:`CloseRequestCancelled`,inputs:[{name:`channelId`,type:`bytes32`,indexed:!0},{name:`payer`,type:`address`,indexed:!0},{name:`payee`,type:`address`,indexed:!0}]}]}));function jj(e,t){return{name:zj,version:Bj,chainId:t,verifyingContract:e}}function Mj(e,t){return He.getVoucherSignPayload({chainId:e,channelId:t.channelId,cumulativeAmount:t.cumulativeAmount})}function Nj(e,t,n){return e.toLowerCase()===He.address.toLowerCase()?Mj(t,n):ce({domain:jj(e,t),types:Vj,primaryType:`Voucher`,message:{channelId:n.channelId,cumulativeAmount:n.cumulativeAmount}})}function Pj(e){return e===`secp256k1`||e===`p256`||e===`webAuthn`}function Fj(e,t){return Pe.signVoucher(e,{chainId:t.chainId,channel:t.channelId,cumulativeAmount:t.cumulativeAmount})}async function Ij(e,t,n,r,i){let a=await(async()=>{if(r.toLowerCase()===He.address.toLowerCase())try{return await Fj(t,{chainId:i,channelId:n.channelId,cumulativeAmount:n.cumulativeAmount})}catch{}return je(e,{account:t,domain:jj(r,i),types:Vj,primaryType:`Voucher`,message:n})})(),o=We.from(a);if(!Pj(o.type))throw Error(`TIP-1034 vouchers require a TIP-1020 primitive signature; received "${o.type}".`);return We.serialize(o)}async function Lj(e,t,n,r,i){let a=await je(e,{account:t,domain:jj(r,i),types:Hj,primaryType:`CloseAuthorization`,message:n}),o=We.from(a);if(!Pj(o.type))throw Error(`TIP-1034 close authorizations require a TIP-1020 primitive signature; received "${o.type}".`);return We.serialize(o)}function Rj(e,t,n,r){try{let i=We.from(n.signature);if(!Pj(i.type)||We.serialize(i).toLowerCase()!==n.signature.toLowerCase())return!1;let a=Nj(e,t,n),o=We.extractAddress({payload:a,signature:i});return We.verify(i,{address:o,payload:a})&&zA(o,r)}catch{return!1}}var zj,Bj,Vj,Hj,Uj=I((()=>{BA(),zj=`TIP20 Channel Reserve`,Bj=`1`,Vj={Voucher:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]},Hj={CloseAuthorization:[{name:`channelId`,type:`bytes32`},{name:`cumulativeAmount`,type:`uint96`}]}}));function Wj(e){return typeof e==`object`&&!!e}function Gj(e){return typeof e==`string`&&ue(e,{strict:!1})?e:void 0}function Kj(e){return Gj(e.accessKeyAddress)}function qj(){let e=BigInt(Math.floor(Date.now()/1e3))-60n;return e<=0n?0:Number(BigInt(ne.random(8))%e)}function Jj(e){return Kj(e)??e.address}async function Yj(e,t){let{account:n,calls:r,feePayer:i,feeToken:a,validAfter:o}=t;return Ee(e,{account:n,calls:r,nonceKey:`expiring`,...i?{feePayer:!0}:{},feeToken:a,...o===void 0?{}:{validAfter:o}})}async function Xj(e,t){return await Ae(e,t)}function Zj(e,t,n=!1){let r=e.request.methodDetails,i=Wj(r)?Gj(r.escrowContract)??Gj(r.escrow):void 0,a=t??`0x4d50500000000000000000000000000000000000`;if(i&&!$j(i,a)&&(!n||t!==void 0))throw Error(`Tempo session escrow ${i} does not match client escrow ${a}.`);return i&&!$j(i,a)?i:a}function Qj(e,t,n,r){return $S({challenge:e,payload:t,source:`did:pkh:eip155:${n}:${r.address}`})}function $j(e,t){return e.toLowerCase()===t.toLowerCase()}async function eM(e,t,n,r,i,a=WE){let o=xj({...n,chainId:i,escrow:a}),s=TE(r),c=await Ij(e,t,{channelId:o,cumulativeAmount:s},a,i);return{action:`voucher`,channelId:o,descriptor:n,cumulativeAmount:s.toString(),signature:c}}async function tM(e,t,n,r,i,a=WE){let o=await eM(e,t,n,r,i,a),s=await Lj(e,t,{channelId:o.channelId,cumulativeAmount:TE(BigInt(o.cumulativeAmount))},a,i);return{action:`close`,channelId:o.channelId,descriptor:n,cumulativeAmount:o.cumulativeAmount,signature:o.signature,closeSignature:s}}async function nM(e,t,n){let r=Jj(t),i=n.escrow??`0x4d50500000000000000000000000000000000000`,a=n.operator??`0x0000000000000000000000000000000000000000`,o=ne.random(32),s=TE(n.deposit),c=TE(n.initialAmount),l=ae({abi:kj,functionName:`open`,args:[n.payee,a,n.token,s,o,r]}),u=await Xj(e,await Yj(e,{account:t,calls:[...n.prefixCalls??[],{to:i,data:l}],feePayer:n.feePayer,feeToken:n.feeToken??n.token})),d=Re.deserialize(u),f={authorizedSigner:r,expiringNonceHash:wj(Cj({...n.feePayer?{feePayer:!0}:{},transaction:d}),{sender:t.address}),operator:a,payee:n.payee,payer:t.address,salt:o,token:n.token},p=xj({...f,chainId:n.chainId,escrow:i});return{action:`open`,type:`transaction`,channelId:p,transaction:u,signature:await Ij(e,t,{channelId:p,cumulativeAmount:c},i,n.chainId),descriptor:f,cumulativeAmount:c.toString(),authorizedSigner:f.authorizedSigner}}async function rM(e,t,n,r,i,a,o=WE,s=[],c=n.token){let l=xj({...n,chainId:i,escrow:o}),u=TE(r);return{action:`topUp`,type:`transaction`,channelId:l,transaction:await Xj(e,await Yj(e,{account:t,calls:[...s,{to:o,data:ae({abi:kj,functionName:`topUp`,args:[n,u]})}],feePayer:a,feeToken:c,validAfter:qj()})),descriptor:n,additionalDeposit:u.toString()}}var iM=I((()=>{rC(),Tj(),Aj(),GE(),Uj()}));function aM(e){let{payee:t,token:n,escrow:r,chainId:i}=e;return`${t.toLowerCase()}:${n.toLowerCase()}:${r.toLowerCase()}:${i}`}function oM(e){return aM({payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId})}function sM(){let e=new Map;return{get:t=>e.get(t),set(t){e.set(oM(t),t)},delete(t){e.delete(t)}}}function cM(e){return{...e,cumulativeAmount:e.cumulativeAmount.toString(),deposit:e.deposit.toString()}}function lM(e){return{...e,cumulativeAmount:BigInt(e.cumulativeAmount),deposit:BigInt(e.deposit)}}function uM(e,t){gM.set(e,gM.get(t)??t)}async function dM(e,t,n){let r=hM.get(e);r||(r=new Map,hM.set(e,r));let i=(r.get(t)??Promise.resolve()).catch(()=>{}).then(n);r.set(t,i);try{return await i}finally{r.get(t)===i&&r.delete(t)}}function fM(e,t,n){return dM(gM.get(e)??e,`funding:${t}`,n)}async function pM(e,t){await dM(e,`write:${oM(t)}`,async()=>{let n=await e.get(oM(t));if(n?.uncertainTopUp){if(n.channelId!==t.channelId)throw Error(`Session funding outcome is unknown; reconcile the pending payment before replacing the channel.`);t.uncertainTopUp=!0}await e.set(t)})}async function mM(e,t){await dM(e,`write:${t}`,async()=>{(await e.get(t))?.uncertainTopUp||await e.delete(t)})}var hM,gM,_M=I((()=>{hM=new WeakMap,gM=new WeakMap}));function vM(e){if(e<0n||e>xM)throw new Y({reason:`amount exceeds uint96 range`})}async function yM(e,t,n=WE,r){return bM(await De(e,{address:n,abi:kj,functionName:`getChannelState`,args:[t],...r===void 0?{}:{blockNumber:r}}))}function bM(e){return vM(e.settled),vM(e.deposit),{settled:e.settled,deposit:e.deposit,closeRequestedAt:e.closeRequestedAt}}var xM,SM=I((()=>{SS(),Aj(),GE(),xM=2n**96n-1n}));function CM(e){return`cumulativeAmount`in e}function wM(e){if(CM(e))return BigInt(e.cumulativeAmount)}async function TM(e,t){t.opened?await pM(e.store,t):await mM(e.store,oM(t)),e.notifyUpdate(t)}async function EM(e,t,n){let r=wM(n);if(r===void 0)return;let i=await e.store.get(t);i&&i.channelId.toLowerCase()===n.channelId.toLowerCase()&&(i.cumulativeAmount=i.cumulativeAmount>r?i.cumulativeAmount:r,n.action===`close`&&(i.opened=!1),await TM(e,i))}function DM(e){return e?.action!==void 0}function OM(e){return DM(e)&&e.descriptor!==void 0}function kM(e,t,n){let r=n===`additionalDeposit`?e.additionalDepositRaw:e.cumulativeAmountRaw,i=n===`additionalDeposit`?e.additionalDeposit:e.cumulativeAmount;if(r)return BigInt(r);if(i)return P(i,t)}function AM(e,t,n,r){let i=kM(e,t,n);if(i===void 0)throw Error(`${n} required for ${r} action`);return i}function jM(e){return typeof e==`object`&&!!e}function MM(e){return typeof e==`string`&&ue(e,{strict:!1})?e:void 0}function NM(e){let t=e.request.methodDetails;return jM(t)?{chainId:typeof t.chainId==`number`?t.chainId:void 0,escrowContract:MM(t.escrowContract),escrow:MM(t.escrow),feePayer:typeof t.feePayer==`boolean`?t.feePayer:void 0,feeToken:MM(t.feeToken),operator:MM(t.operator),sessionSnapshot:kx(t,Nx.sessionSnapshot)}:{}}function PM(e,t){if(typeof e==`string`&&ue(e,{strict:!1}))return e;throw Error(`tempo session challenge missing ${t}`)}function FM(e){if(typeof e==`string`)return BigInt(e);throw Error(`tempo session challenge missing amount`)}function IM(e){return typeof e==`string`?e:void 0}async function LM(e){let{allowCustomEscrow:t,challenge:n,escrowOverride:r,allowedChainIds:i,getClient:a}=e,o=NM(n);(o.chainId!==void 0||i?.length===0)&&AA(i,o.chainId);let s=o.chainId??(i?.length===1?i[0]:void 0),c=await a({chainId:s});kA(c,s);let l=s??c.chain?.id;if(AA(i,l),!l)throw Error(`No chainId configured for TIP-1034 session challenge.`);let u=Zj(n,r,t),d=PM(n.request.recipient,`recipient`),f=PM(n.request.currency,`currency`);return{amount:FM(n.request.amount),challenge:n,chainId:l,client:c,escrow:u,feePayer:o.feePayer,feeToken:o.feeToken,key:aM({payee:d,token:f,escrow:u,chainId:l}),operator:o.operator,payee:d,snapshot:o.sessionSnapshot,suggestedDepositRaw:IM(n.request.suggestedDeposit),token:f}}async function RM(e){let{channelId:t,client:n,descriptor:r,expected:i,readChannelState:a=yM}=e,o=xj({...r,chainId:i.chainId,escrow:i.escrow});zM({channelId:t,descriptor:r,expectedChannelId:o,payee:i.payee,payer:i.payer,authorizedSigner:i.authorizedSigner,token:i.token});let s=await a(n,o,i.escrow);if(s.deposit===0n)throw Error(`Channel ${o} cannot be reused (closed or not found on-chain).`);if(s.closeRequestedAt!==0)throw Error(`Channel ${o} cannot be reused (pending close request).`);return{channelId:o,state:s}}function zM(e){let{authorizedSigner:t,channelId:n,descriptor:r,expectedChannelId:i,payee:a,payer:o,token:s}=e;if(n&&n.toLowerCase()!==i.toLowerCase())throw Error(`context channelId does not match descriptor`);if(!$j(r.payee,a))throw Error(`context descriptor payee does not match challenge`);if(!$j(r.token,s))throw Error(`context descriptor token does not match challenge`);if(!$j(r.payer,o))throw Error(`context descriptor payer does not match account`);if(!$j(bj(r),t))throw Error(`context descriptor authorizedSigner does not match account`)}function BM(e){let{context:t,snapshot:n}=e,r=t?.descriptor??n?.descriptor;if(r)return{...t,channelId:t?.channelId??n?.channelId,descriptor:r}}function VM(e){let{context:t,decimals:n,requestAmount:r,snapshot:i,settled:a}=e;if(i)return[BigInt(i.acceptedCumulative),BigInt(i.requiredCumulative),BigInt(i.spent)+r,a].reduce((e,t)=>t>e?t:e,0n);let o=kM(t,n,`cumulativeAmount`);return o===void 0?a+r:o+r}async function HM(e){let{account:t,client:n,readChannelState:r,snapshot:i}=e,a=i.highestVoucher;if(!a)throw Error(`session snapshot is missing its highest signed voucher`);if(a.channelId.toLowerCase()!==i.channelId.toLowerCase())throw Error(`session snapshot voucher channelId does not match snapshot channelId`);let o=BigInt(i.acceptedCumulative),s=BigInt(a.cumulativeAmount),c=BigInt(i.requiredCumulative),l=BigInt(i.deposit),u=BigInt(i.settled),d=BigInt(i.spent);if(s!==o)throw Error(`session snapshot voucher amount does not match acceptedCumulative`);if(d>o)throw Error(`session snapshot spent exceeds acceptedCumulative`);if(u>l)throw Error(`session snapshot settled amount exceeds deposit`);if(!Rj(i.escrow,i.chainId,{channelId:a.channelId,cumulativeAmount:s,signature:a.signature},bj(i.descriptor)))throw Error(`session snapshot highest voucher signature is invalid`);let f=await RM({channelId:i.channelId,client:n,descriptor:i.descriptor,expected:{chainId:i.chainId,escrow:i.escrow,payee:i.descriptor.payee,payer:t.address,authorizedSigner:Jj(t),token:i.descriptor.token},readChannelState:r}),p=[o,c,f.state.settled].reduce((e,t)=>t>e?t:e,0n);if(p>f.state.deposit)throw Error(`recovered session cumulative amount exceeds on-chain channel deposit`);return{entry:{channelId:f.channelId,cumulativeAmount:p,deposit:f.state.deposit,descriptor:i.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0},spent:d}}function UM(e,t){return $j(e.address,t.payer)?$j(Jj(e),bj(t)):!1}function WM(e){let{account:t,entry:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e;if(DM(r)){if(!OM(r))throw Error(`descriptor required for TIP-1034 session action`);return{type:`manual`,account:t,context:r,decimals:i,resolved:o}}if(!n&&r?.channelId&&!r.descriptor)throw Error(`descriptor required to reuse TIP-1034 channel`);let s=BM({context:r,snapshot:o.snapshot});return!n&&s&&UM(t,s.descriptor)?{type:`recover`,account:t,context:s,decimals:i,maxDeposit:a,resolved:o}:n?.opened&&UM(t,n.descriptor)?{type:`voucher`,account:t,entry:n,maxDeposit:a,resolved:o}:{type:`open`,account:t,context:r,maxDeposit:a,resolved:o}}async function GM(e,t,n=!1){switch(e.type){case`open`:return qM(e,t,n);case`recover`:return JM(e,t);case`voucher`:return YM(e,t);case`manual`:return XM(e,t,n)}}async function KM(e,t){if(e)return await VA(t.client,{account:t.account,amountOut:t.amountOut,tokenOut:t.tokenOut,tokenIn:e.tokenIn,slippage:e.slippage,maxAmountIn:e.maxAmountIn})}async function qM(e,t,n){let{account:r,resolved:i}=e,a=fD({contextDepositRaw:e.context?.depositRaw,maxDeposit:e.maxDeposit,requestAmount:i.amount,suggestedDepositRaw:i.suggestedDepositRaw}),o=await nM(i.client,r,{chainId:i.chainId,deposit:a,escrow:i.escrow,feePayer:i.feePayer,feeToken:i.feeToken,initialAmount:i.amount,operator:i.operator,payee:i.payee,prefixCalls:await KM(n,{account:r.address,amountOut:a,client:i.client,tokenOut:i.token}),token:i.token});return await TM(t,{channelId:o.channelId,cumulativeAmount:i.amount,deposit:a,descriptor:o.descriptor,escrow:i.escrow,chainId:i.chainId,opened:!0}),o}async function JM(e,t){let{account:n,context:r,decimals:i,maxDeposit:a,resolved:o}=e,{descriptor:s}=r,c=await RM({channelId:r.channelId,client:o.client,descriptor:s,expected:{chainId:o.chainId,escrow:o.escrow,payee:o.payee,payer:n.address,authorizedSigner:Jj(n),token:o.token}}),l=VM({context:r,decimals:i,requestAmount:o.amount,settled:c.state.settled,snapshot:o.snapshot});if(l>c.state.deposit)throw Error(`recovered voucher amount exceeds on-chain channel deposit`);mD(l,a);let u=await eM(o.client,n,s,l,o.chainId,o.escrow),d=await t.store.get(o.key);return await TM(t,{...d?.channelId===c.channelId&&d.uncertainTopUp?{uncertainTopUp:!0}:{},channelId:c.channelId,cumulativeAmount:l,deposit:c.state.deposit,descriptor:s,escrow:o.escrow,chainId:o.chainId,opened:!0}),u}async function YM(e,t){let{account:n,entry:r,resolved:i}=e,a=r.cumulativeAmount+i.amount;mD(a,e.maxDeposit);let o=await eM(i.client,n,r.descriptor,a,i.chainId,i.escrow);return r.cumulativeAmount=a,await TM(t,r),o}async function XM(e,t,n){let{account:r,context:i,decimals:a,resolved:o}=e,{descriptor:s}=i,c=xj({...s,chainId:o.chainId,escrow:o.escrow});zM({channelId:i.channelId,descriptor:s,expectedChannelId:c,payee:o.payee,payer:r.address,authorizedSigner:Jj(r),token:o.token});let l=await ZM({account:r,channelId:c,context:i,decimals:a,descriptor:s,resolved:o},n);return await EM(t,o.key,l),l}async function ZM(e,t){switch(e.context.action){case`open`:return QM(e);case`topUp`:return $M(e,t);case`voucher`:return eN(e);case`close`:return tN(e)}}async function QM(e){let{account:t,channelId:n,context:r,decimals:i,descriptor:a,resolved:o}=e;if(!r.transaction)throw Error(`transaction required for open action`);let s=AM(r,i,`cumulativeAmount`,`open`),c=await eM(o.client,t,a,s,o.chainId,o.escrow);return{action:`open`,type:`transaction`,channelId:n,transaction:r.transaction,signature:c.signature,descriptor:a,cumulativeAmount:s.toString(),authorizedSigner:a.authorizedSigner}}async function $M(e,t){let{account:n,channelId:r,context:i,decimals:a,descriptor:o,resolved:s}=e,c=AM(i,a,`additionalDeposit`,`topUp`);return i.transaction?{action:`topUp`,type:`transaction`,channelId:r,transaction:i.transaction,descriptor:o,additionalDeposit:c.toString()}:rM(s.client,n,o,c,s.chainId,s.feePayer,s.escrow,await KM(t,{account:n.address,amountOut:c,client:s.client,tokenOut:s.token}),s.feeToken)}function eN(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return eM(a.client,t,i,AM(n,r,`cumulativeAmount`,`voucher`),a.chainId,a.escrow)}function tN(e){let{account:t,context:n,decimals:r,descriptor:i,resolved:a}=e;return tM(a.client,t,i,AM(n,r,`cumulativeAmount`,`close`),a.chainId,a.escrow)}var nN,rN,iN,aN=I((()=>{Fx(),MA(),Zx(),KA(),SM(),Tj(),Uj(),iM(),_M(),kD(),nN=J.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]*$/.test(e)),rN=J.custom(e=>typeof e==`string`&&/^0x[0-9a-fA-F]{64}$/.test(e)),iN=J.object({account:J.optional(J.custom()),autoSwap:J.optional(J.custom()),action:J.optional(J.enum([`open`,`topUp`,`voucher`,`close`])),channelId:J.optional(rN),cumulativeAmount:J.optional(Vx()),cumulativeAmountRaw:J.optional(J.string()),transaction:J.optional(nN),descriptor:J.optional(J.custom()),additionalDeposit:J.optional(Vx()),additionalDepositRaw:J.optional(J.string()),depositRaw:J.optional(J.string())})}));async function oN(e,t){let n=uN.get(e)??new Map;uN.set(e,n);let r=n.get(t),i,a=new Promise(e=>{i=e});return n.set(t,a),await r,()=>{i(),n.get(t)===a&&n.delete(t)}}function sN(e,t){try{return t?.channelId.toLowerCase()===e.channelId.toLowerCase()&&BigInt(t.acceptedCumulative)===e.cumulativeAmount}catch{return!1}}function cN(e,t,n){try{let r=e.response?.headers.get(q.paymentReceipt);if(r){let e=PE(r);if(e.challengeId===t.id&&sN(n,e))return!0}}catch{}return e.challenges?.some(e=>ID(e)?sN(n,LD(e)):!1)??!1}function lN(e={}){let{account:t,allowCustomEscrow:n=!1,autoSwap:r,channelStore:i,decimals:a=6,escrow:o,allowedChainIds:s,getClient:c,maxDeposit:l,topUpAmount:u,onChannelUpdate:d,resolveAccount:f}=e,p=OA({chain:Ve,getClient:c,rpcUrl:SO}),m=CA({account:t}),h=l===void 0?void 0:P(l,a),g=u===void 0?void 0:P(u,a),_=i??sM(),v={store:_,notifyUpdate:e=>d?.(e)},y=async(e,t,n)=>{let r=m(e.client,t),i=t?.action?t.descriptor:n?.descriptor??BM({context:t,snapshot:e.snapshot})?.descriptor;return await f?.({account:r,chainId:e.chainId,operation:{kind:`authorizePaymentChannel`,...i?{authority:bj(i)}:{}}})??r},b=async(e,t,n)=>WM({account:await y(e,t,n),entry:n,context:t,decimals:a,maxDeposit:h,resolved:e}),x=aE(bE,{canHandleChallenge:({challenge:e})=>ID(e),context:iN,async createCredential(e){let{challenge:t,context:i}=e,a=await LM({allowCustomEscrow:n,challenge:t,escrowOverride:o,allowedChainIds:s,getClient:p}),c=bw(e),l=()=>{};try{let e=!DM(i)&&i?.descriptor===void 0;e&&(l=await oN(_,a.key),c&&(await _.get(a.key))?.opened&&await c.prepare());let n=await _.get(a.key),o=await b(a,i,n);if(!e&&c&&o.type===`open`){l=await oN(_,a.key);let e=await _.get(a.key);e?.channelId!==n?.channelId&&(n=e,n?.opened&&(await c.prepare(),n=await _.get(a.key)),o=await b(a,i,n))}let s,u=c&&o.type===`open`?{store:{get:e=>_.get(e),async set(e){s=e},delete:e=>_.delete(e)},notifyUpdate(){}}:v,d=await Qj(t,await GM(o,u,HA(i?.autoSwap??r,WA)),a.chainId,o.account);if(c&&s){let e=s;c.settle=async n=>{let r=n.status===`accepted`||cN(n,t,e);if(!r&&n.status===`pending`)return!1;try{if(r){let t=await _.get(a.key);(!t?.opened||t.channelId.toLowerCase()!==e.channelId.toLowerCase())&&(await pM(_,e),v.notifyUpdate(e))}return!0}finally{l()}}}else l();return d}catch(e){throw l(),e}}}),S=async({challenge:e,channel:t,deposit:n,fetch:r,input:i,requiredCumulative:a,signal:o})=>fM(_,oM(t),async()=>{o?.throwIfAborted();let s=await _.get(oM(t));if(s?.channelId===t.channelId&&(t=s),t.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before another top-up.`);let c=t.deposit>n?t.deposit:n,l=pD({deposit:c,maxDeposit:h,requiredCumulative:a,suggestedDeposit:e.request.suggestedDeposit===void 0?void 0:BigInt(e.request.suggestedDeposit),topUpAmount:g});l>0n&&await HD({additionalDeposit:l,challenge:e,channel:t,channelId:t.channelId,createSessionCredential:(e,t)=>x.createCredential({challenge:e,context:t}),onUncertainFunding:async e=>{let t=await _.get(oM(e)),n={...t?.channelId===e.channelId?t:e,uncertainTopUp:!0};await pM(_,n),v.notifyUpdate(n)},fetch:r,input:i,signal:o});let u=c+l;if(u===t.deposit)return;let d=await _.get(oM(t)),f=d?.channelId.toLowerCase()===t.channelId.toLowerCase()?d:t,p={...f,deposit:f.deposit>u?f.deposit:u};await pM(_,p),v.notifyUpdate(p)});return dw(x,async({challenge:e,context:t,fetch:r,input:i,signal:a})=>{if(!ID(e))return;let c=t===void 0?void 0:iN.parse(t);if(DM(c))return;let l=await LM({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:p}),u=await _.get(l.key);if(!u?.opened)return;let d=l.snapshot?.channelId.toLowerCase()===u.channelId.toLowerCase()?l.snapshot:void 0,f=u.cumulativeAmount+jE(e),m=d?BigInt(d.requiredCumulative):f,h=m>f?m:f,g=d?BigInt(d.deposit):u.deposit,v=g>u.deposit?g:u.deposit;h<=v&&v===u.deposit||!UM(await y(l,c,u),u.descriptor)||await S({challenge:e,channel:u,deposit:v,fetch:r,input:i,requiredCumulative:h,signal:a})}),_w(x,async({challenge:e,credential:t,fetch:r,headers:i,input:a,refetch:c,response:l,signal:u})=>{if(!ID(e))return l;if(!FE(l))return AE(YS(t).payload).action===`open`&&i.get(`accept`)?.toLowerCase().includes(`text/event-stream`)?await c?.()??l:l;let d=(await LM({allowCustomEscrow:n,challenge:e,escrowOverride:o,allowedChainIds:s,getClient:p})).key,f=await _.get(d),m={assertVoucherWithinLocalLimit:e=>mD(e,h),createSessionCredential:(e,t)=>x.createCredential({challenge:e,context:t}),fetch:r,getChannel:()=>f??null,async topUpIfNeeded({deposit:t,requiredCumulative:n,signal:i}){f&&await S({challenge:e,channel:f,deposit:f.deposit>t?f.deposit:t,fetch:r,input:a,requiredCumulative:n,signal:i})}};return $D({onNeedVoucher:(t,n)=>eO({challenge:e,driver:m,input:a,signal:n},t),onReceipt(){},response:l,signal:u})})}var uN,dN=I((()=>{gw(),Dw(),Fx(),rC(),oE(),wA(),MA(),KA(),CO(),SE(),Tj(),GE(),iM(),_M(),aN(),kD(),uN=new WeakMap}));function fN(e,t){mN.set(e,t)}function pN(e){let t=mN.get(e);if(!t)throw Error(`Session manager internals are unavailable.`);return t}var mN,hN=I((()=>{mN=new WeakMap}));function gN(e){let t=null;return{wait(n=()=>!0){if(t)throw Error(`${e} wait already in progress`);return new Promise((e,r)=>{t={predicate:n,resolve:e,reject:r}})},settle(e){if(!t||!t.predicate(e))return;let n=t;t=null,n.resolve(e)},reject(e){if(!t)return;let n=t;t=null,n.reject(e)}}}function _N(e){let t=gN(`close-ready`),n=gN(`receipt`);return{waitForReceipt(e){return n.wait(e)},waitForCloseReady(){let n=e.getSocketSession()?.closeReadyReceipt;return n?Promise.resolve(n):t.wait()},settleReceipt(e){n.settle(e)},settleCloseReady(n){let r=e.getSocketSession();r&&r.challenge.id===n.challengeId&&r.channelId===n.channelId&&(r.closeReadyReceipt=n),t.settle(n)},rejectReceipt(e){n.reject(e)},rejectCloseReady(e){t.reject(e)}}}var vN=I((()=>{}));function yN(e){return e.method===jx.tempo&&e.intent===Mx.charge}function bN(e){if(!yN(e)||typeof e.request.amount!=`string`)return!1;try{return BigInt(e.request.amount)===0n}catch{return!1}}function xN(e,t,n){if(!n)return t;let r={...Mw(e instanceof Request?e.headers:void 0),...Mw(t?.headers)};return Object.keys(r).some(e=>e.toLowerCase()===q.paymentSession.toLowerCase())?t:{...t,headers:{...r,[q.paymentSession]:n}}}function SN(e,t){return e===void 0?t:{...iN.parse(e),...t}}function CN(e){let t=e.decimals??6,n=e.webSocket??globalThis.WebSocket;return{decimals:t,fetch:e.fetch??globalThis.fetch.bind(globalThis),maxVoucherCumulative:e.maxDeposit===void 0?null:P(e.maxDeposit,t),topUpAmount:e.topUpAmount===void 0?null:P(e.topUpAmount,t),WebSocket:n}}function wN(e){let t=e.client?.chain?.id;(t!==void 0||e.allowedChainIds?.length===0)&&AA(e.allowedChainIds,t);let n=e.allowCustomEscrow??!1,r=CN(e),i=OA({chain:Ve,getClient:e.client?()=>e.client:e.getClient,rpcUrl:SO}),a=CA({account:e.account}),o=bD(),s=e.credentialContext===void 0?void 0:SN(e.credentialContext,{}),c=_N({getSocketSession:()=>o.socketSession}),l=e.channelStore??sM(),u=new Set,d;async function f(e){let t=await l.get(e);if(t?.opened&&!u.has(t.channelId))return t}let p=e=>pM(l,e),m={async get(e){let t=await f(e);return t&&d&&(d.seenExisting.add(e),!d.committed&&!d.created.has(e)&&(d.resumed??=t)),t},async set(e){let t=oM(e);e.opened&&u.delete(e.channelId),d?.trackCreates&&!d.seenExisting.has(t)&&d.created.set(t,e),await p(e)},delete:e=>mM(l,e)};uM(m,l);async function h(e){let t=oM(e),n=await l.get(t);if(e.uncertainTopUp||n?.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before replacing the channel.`);u.add(e.channelId),d?.seenExisting.delete(t),d?.resumed===e&&(d.resumed=void 0),await Promise.resolve(mM(l,t)).catch(()=>void 0)}async function g(){let e=d;if(e?.created.size){for(let[t,n]of e.created){let e=await l.get(t);if(n.uncertainTopUp||e?.channelId===n.channelId&&e.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before discarding the channel.`);u.add(n.channelId),await Promise.resolve(mM(l,t)).catch(()=>void 0)}e.created.clear(),await N(e.committed??e.previous)}}function _(e){let t=kx(e.request.methodDetails,Nx.sessionSnapshot);if(typeof t?.channelId!=`string`)return!1;let n=d;if(!n?.created.size||!o.channel)return!1;for(let[e,r]of n.created)if(r.channelId.toLowerCase()===t.channelId.toLowerCase()&&o.channel.channelId.toLowerCase()===t.channelId.toLowerCase())return n.created.delete(e),n.committed=TD({channel:o.channel,spent:o.spent,state:o.state}),!0;return!1}function v(e){return rD(o,e)}function y(){let e=o.state.status===`active`?o.state:d?.committed?.state??d?.previous.state;return e?.status===`active`?e.units:0}function b(e){let t=d,n=t?.committed?.channel?.entry??t?.resumed;!t||n?.channelId.toLowerCase()!==e.channelId.toLowerCase()||e.deposit<=n.deposit&&!e.uncertainTopUp||(t.resumed=void 0,t.committed=TD({channel:o.channel,spent:o.spent,state:o.state}))}let x=lN({account:e.account,allowCustomEscrow:n,autoSwap:e.autoSwap,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount,escrow:e.escrow,allowedChainIds:e.allowedChainIds,decimals:r.decimals,maxDeposit:e.maxDeposit,topUpAmount:e.topUpAmount,channelStore:m,onChannelUpdate(e){e.channelId!==o.channel?.channelId&&(o.spent=0n),o.channel=e,o.lastChallenge&&v({type:`activated`,challengeId:o.lastChallenge.id,entry:e,spent:o.spent.toString(),units:y()}),b(e)}}),S=mw(x);S&&dw(x,e=>ie(()=>Promise.resolve(S(e)),e.signal)),vw(x);let C=mj({allowedChainIds:e.allowedChainIds,account:e.account,getClient:e.client?()=>e.client:e.getClient,resolveAccount:e.resolveAccount}),w=Aw({fetch:r.fetch,methods:[x],onChallenge:async(e,t)=>{if(!FD(e))return;let n=d,r=n&&n.challengesReceived>0&&e.id===o.lastChallenge?.id,i=r&&$x(e)===$x(o.lastChallenge);n&&n.challengesReceived++,!i&&(_(e)||(n?.created.size?await g():r&&await N(n.committed??n.previous)),o.lastChallenge=e,v({type:`challengeReceived`,challengeId:e.id}))}});function T(e,t){return x.createCredential({challenge:e,context:SN(s,t)})}function ee(e){xD({maxVoucherCumulative:r.maxVoucherCumulative,receipt:e,runtime:o})}function E(e=o.state.status===`active`?o.state.units:0){!o.channel||!o.lastChallenge||o.state.status!==`active`&&o.state.status!==`withdrawable`&&o.state.status!==`closeRequested`&&v({type:`activated`,challengeId:o.lastChallenge.id,entry:o.channel,spent:o.spent.toString(),units:e})}async function D(t){let n=t.headers.get(q.paymentSessionSnapshot);if(!n)return;let r=qE(n);AA(e.allowedChainIds,r.chainId);let s=await i({chainId:r.chainId});kA(s,r.chainId);let c=a(s),{entry:l,spent:u}=await HM({account:await e.resolveAccount?.({account:c,chainId:r.chainId,operation:{authority:bj(r.descriptor),kind:`authorizePaymentChannel`}})??c,client:s,snapshot:r});return j(l.cumulativeAmount),await Promise.resolve(m.set(l)).catch(()=>void 0),o.channel=l,o.spent=u,l}async function O(t,n){if(!e.bootstrap||o.channel?.opened)return;let i=t instanceof Request?t.headers:void 0,{body:a,method:s,...c}=n??{},l=t instanceof Request?t.url:t,u={...c,method:`HEAD`,headers:{...Mw(i),...Mw(n?.headers),[q.acceptPayment]:`${jx.tempo}/${Mx.charge}`}};try{let e=await r.fetch(l,u);if(e.status!==402)return await D(e);let t=cS(e).find(yN);if(!t||!bN(t))return;let n=await C.createCredential({challenge:t,context:{}}),i=await r.fetch(l,{...u,headers:{...Mw(u.headers),[q.authorization]:n}});return i.ok?await D(i):void 0}catch{return}}function k(e,t){let n=o.socketSession;return CD({challengeId:e.id,channelId:t,closeReadyReceipt:n?.closeReadyReceipt,cumulativeAmount:o.channel?.channelId===t?o.channel.cumulativeAmount:0n,deliveredChunks:n?.deliveredChunks,socketChallengeId:n?.challenge.id,socketChannelId:n?.channelId,spent:o.spent,tickCost:n?.tickCost})}function A(e,t){let n=LD(t);if(!n)return;if(xj({...n.descriptor,chainId:n.chainId,escrow:n.escrow}).toLowerCase()!==n.channelId.toLowerCase())throw Error(`close snapshot descriptor does not match its channel ID`);if(n.channelId.toLowerCase()!==e.channelId.toLowerCase())throw Error(`close snapshot channel ID does not match local session`);if(n.chainId!==e.chainId||n.escrow.toLowerCase()!==e.escrow.toLowerCase())throw Error(`close snapshot payment scope does not match local session`);let r=BigInt(n.acceptedCumulative),i=BigInt(n.spent);if(r<0n||i<0n)throw Error(`close snapshot amounts must not be negative`);if(i>r)throw Error(`close snapshot spent exceeds accepted cumulative amount`);if(r>e.cumulativeAmount)throw Error(`close snapshot accepted cumulative exceeds local voucher state`);return{acceptedCumulative:r,spent:i}}function te(e,t){let n=A(e.channel,t);if(!n)return;let{acceptedCumulative:r,spent:i}=n;if(o.spent>r)throw Error(`close snapshot accepted cumulative is below locally confirmed spend`);return i>o.spent&&(o.spent=i),n}function ne(e,t=e.challenge,n=!1){let r=(n?te(e,t):A(e.channel,t))?.acceptedCumulative??k(t,e.channelId);if(r>e.channel.cumulativeAmount)throw Error(`fallback close amount exceeds local voucher state`);return j(r),r.toString()}function j(e){cD({cumulativeAmount:e,maxVoucherCumulative:r.maxVoucherCumulative})}let M,re;async function ie(e,t){if(re)throw re;for(;;){let e=M;if(!e)break;if(!t)await e;else{t.throwIfAborted();let n;try{await Promise.race([e,new Promise((e,r)=>{n=()=>r(t.reason),t.addEventListener(`abort`,n,{once:!0})})])}finally{t.removeEventListener(`abort`,n)}}}if(t?.throwIfAborted(),re)throw re;let n=e();M=n;try{return await n}catch(e){throw e instanceof gO&&(re=Error(`Session funding outcome is unknown; reconcile the pending payment before creating a new session manager.`)),e}finally{M===n&&(M=void 0)}}async function ae(e){if(!o.channel)throw Error(`Cannot top up session: no active channel`);return fM(l,oM(o.channel),async()=>{let{knownDeposit:t,...n}=e,i=o.channel?await m.get(oM(o.channel)):void 0;if(i?.channelId===e.channelId&&i.uncertainTopUp)throw Error(`Session funding outcome is unknown; reconcile the pending payment before another top-up.`);let a=await HD({...n,channel:o.channel,createSessionCredential:T,fetch:r.fetch,onUncertainFunding:async e=>{let t=await m.get(oM(e)),n={...t?.channelId===e.channelId?t:e,uncertainTopUp:!0};o.channel?.channelId===e.channelId&&(o.channel=n),await m.set(n),b(n)}});ee(a);let s=o.channel,c=ND({additionalDeposit:e.additionalDeposit,channel:o.channel,channelId:e.channelId,challengeId:o.lastChallenge?.id,currentState:o.state,knownDeposit:t,receipt:a,spent:o.spent});if(c?.channel&&o.lastChallenge){let e=c.channel;for(;;){await m.set(e);let t=o.channel;if(t===s)break;if(!t)return a;let n=c.channel;e=t.channelId===n.channelId?{...t,deposit:t.deposit>n.deposit?t.deposit:n.deposit,cumulativeAmount:t.cumulativeAmount>n.cumulativeAmount?t.cumulativeAmount:n.cumulativeAmount}:t,s=t}if(e.channelId!==c.channel.channelId)return a;o.channel=e,v({type:`activated`,challengeId:o.lastChallenge.id,entry:e,spent:o.spent.toString(),units:y()}),b(e)}return a})}async function oe(e){return ie(async()=>{e.signal?.throwIfAborted();let t=o.channel?.channelId===e.channelId?o.channel.deposit:0n,n=t>e.deposit?t:e.deposit,i=pD({deposit:n,maxDeposit:r.maxVoucherCumulative,requiredCumulative:e.requiredCumulative,suggestedDeposit:e.challenge.request.suggestedDeposit===void 0?void 0:BigInt(e.challenge.request.suggestedDeposit),topUpAmount:r.topUpAmount});i!==0n&&await ae({challenge:e.challenge,input:e.input,channelId:e.channelId,additionalDeposit:i,knownDeposit:n,signal:e.signal})},e.signal)}async function se(e,t){let n=wD({channel:o.channel,channelId:e,challengeId:o.lastChallenge?.id,cumulativeAmount:t,spent:o.spent,state:o.state});n&&o.channel&&(v({type:`activated`,challengeId:n.challengeId,entry:o.channel,spent:n.spent,units:n.units}),await p(o.channel))}async function N(e){let t=ED(e,o.channel);o.channel=t.channel,o.spent=t.spent,o.state=t.state,o.channel?.opened&&await p(o.channel)}function ce(e){let t=e.headers.get(q.paymentReceipt),n=t?PE(t):null;return ee(n),Object.assign(e,{receipt:n,challenge:o.lastChallenge,channelId:o.channel?.channelId??null,cumulative:o.channel?.cumulativeAmount??0n})}async function le(e,t){if(d)throw Error(`SessionManager: a request is already in flight; concurrent requests on one manager are not supported`);o.lastUrl=e;let n=TD({channel:o.channel,spent:o.spent,state:o.state}),i={challengesReceived:0,committed:void 0,created:new Map,previous:n,seenExisting:new Set,resumed:void 0,trackCreates:!1};d=i;try{await O(e,t),i.trackCreates=!0;let a=xN(e,t,o.channel?.opened?o.channel.channelId:void 0);s&&(a={...a,context:s});let c=!n.channel?.opened;async function l(){let n=i.resumed;return!c||!n?!1:(c=!1,await h(n),a=xN(e,t,void 0),!0)}for(;;){let t;try{t=await w(e,a)}catch(e){if(i.created.size?await g():await N(i.committed??n),await l())continue;throw e}let s=ce(t),c=!1;if(s.status===402){let t=await WD({input:e,init:a,response:s,createSessionCredential:T,fetch:r.fetch,getChannel:()=>o.channel,restoreCumulative:se,setChallenge(e){o.lastChallenge=e},topUpIfNeeded:oe});t&&(c=!0,s=ce(t))}if(!c&&!s.ok&&!s.receipt){if(i.created.size?await g():await N(i.committed??n),await l())continue;return s}return s}}finally{d=void 0}}async function ue(e){let t=await KD({createSessionCredential:T,fetch:r.fetch,getMinimumSpent:()=>o.spent,lastUrl:o.lastUrl,resolveSignedCloseAmount:t=>ne(e,t,!0),signedCloseAmount:ne(e),setChallenge(e){o.lastChallenge=e},target:e});return t&&(E(),v({type:`closeStarted`}),v({type:`closed`,receipt:t})),t}let de={createSessionCredential:T,doFetch:le,fetch:r.fetch,getChannel:()=>o.channel,getChallenge:()=>o.lastChallenge,assertVoucherWithinLocalLimit:j,acceptReceipt(e){ee(e)},topUpIfNeeded:oe},fe={get channelId(){return o.channel?.channelId},get cumulative(){return o.channel?.cumulativeAmount??0n},get opened(){return o.channel?.opened??!1},get state(){return o.state},fetch:le,async topUp(e){let t=MD({amount:e,assertVoucherWithinLocalLimit:j,channel:o.channel,decimals:r.decimals,lastChallenge:o.lastChallenge,lastUrl:o.lastUrl});return ie(async()=>{if(o.channel?.channelId!==t.channelId||o.lastChallenge!==t.challenge||o.lastUrl!==t.input)throw Error(`Session changed while waiting to top up`);let n=MD({amount:e,assertVoucherWithinLocalLimit:j,channel:o.channel,decimals:r.decimals,lastChallenge:t.challenge,lastUrl:t.input});return ae({additionalDeposit:n.additionalDeposit,challenge:n.challenge,channelId:n.channelId,input:n.input})})},async sse(e,t){return qD(e,t,de)},async ws(e,t){if(!r.WebSocket)throw Error("No WebSocket implementation available. Pass `webSocket` to sessionManager() in this runtime.");let n=BD(e),i=t?.signal?{signal:t.signal}:void 0;await O(n,i);let a=o.channel?.opened?o.channel.channelId:void 0,{challenge:s,credential:l,httpUrl:u,wsUrl:d}=await nO({async createSessionCredential(e,i){return o.lastChallenge=e,await pw(x,{challenge:e,context:i,fetch:r.fetch,input:n,signal:t?.signal}),T(e,i)},fetch:r.fetch,input:e,onProbeUrl(e){o.lastUrl=e.toString()},probeInit:xN(n,i,a),signal:t?.signal});return o.lastChallenge=s,sO({challenge:s,credential:l,httpUrl:u,WebSocket:r.WebSocket,wsUrl:d,options:t,createSessionCredential:T,getChannel:()=>o.channel,setSocketSession(e){o.socketSession=e},async refreshChallenge(){let e=await tO({fetch:r.fetch,input:u,probeInit:xN(u,i,o.channel?.opened?o.channel.channelId:void 0),signal:t?.signal});return o.lastChallenge=e.challenge,e.challenge},assertVoucherWithinLocalLimit:j,acceptReceipt:ee,rejectCloseReady:c.rejectCloseReady,rejectReceipt:c.rejectReceipt,settleCloseReady:c.settleCloseReady,settleReceipt:c.settleReceipt,topUpIfNeeded:oe,waitForReceipt:c.waitForReceipt})},async close(){let e=o.socketSession,t=hD({channel:o.channel,currentSocket:e,lastChallenge:o.lastChallenge});if(!t)return;let n=e?.socket;if(e&&n?.readyState===pO.OPEN){let r=await DD({activeSocket:n,createSessionCredential:T,currentSocket:e,spent:o.spent,target:t,waitForCloseReady:c.waitForCloseReady,waitForReceipt:c.waitForReceipt});return E(),v({type:`closeStarted`}),v({type:`closed`,receipt:r}),r}return ue(t)}};return fN(fe,{consumeSseResponse(e,t,n){return JD(e,t,n,de)},rehydrate({channel:e,challenge:t,input:n,spent:r}){if(!e.opened)throw Error(`Cannot restore a closed session channel.`);if(!FD(t))throw Error(`Cannot restore session: challenge is not tempo/session.`);if(r<0n)throw Error(`Cannot restore session: spent must not be negative.`);if(r>e.cumulativeAmount)throw Error(`Cannot restore session: spent exceeds local voucher state.`);j(e.cumulativeAmount);let i=A(e,t),a=i&&i.spent>r?i.spent:r;o.lastUrl=n,o.lastChallenge=t,o.channel=e,o.spent=a,v({type:`challengeReceived`,challengeId:t.id}),v({type:`activated`,challengeId:t.id,entry:e,spent:a.toString(),units:0})}}),fe}var TN=I((()=>{_S(),yT(),gw(),Dw(),Fx(),wA(),MA(),yj(),CO(),_M(),aN(),dN(),Tj(),GE(),eD(),hN(),vN(),kD(),_O(),(function(e){e.serializeSnapshot=KE,e.deserializeSnapshot=qE})(wN||={})}));function EN(e){return e instanceof Date?e:new Date(e)}function DN(e){let t=e.getTime();if(!Number.isFinite(t))throw new Y({reason:`subscriptionExpires is invalid`});if(t%1e3!=0)throw new Y({reason:`subscriptionExpires must be representable as whole seconds`});let n=t/1e3;if(n<=0||!Number.isSafeInteger(n))throw new Y({reason:`subscriptionExpires cannot be represented in a Tempo key authorization`});return n}function ON(e){if(!/^[1-9]\d*$/.test(e.periodCount))throw new Y({reason:`periodCount is invalid`});let t=qN[e.periodUnit];if(t===void 0)throw new Y({reason:`periodUnit is invalid`});let n=BigInt(e.periodCount)*t;if(n>KN)throw new Y({reason:`subscription period cannot be represented as an unsigned 64-bit integer`});if(n>BigInt(2**53-1))throw new Y({reason:`subscription period cannot be represented exactly by this Tempo client`});return Number(n)}function kN(e){let{challengeExpires:t,request:n}=e;ON(n);let r=DN(EN(n.subscriptionExpires));if(t){let e=Math.floor(new Date(t).getTime()/1e3);if(!Number.isFinite(e)||r<=e)throw new Y({reason:`subscriptionExpires must be strictly later than challenge expires`})}}function AN(e){let t=UN(e.currency,`currency`),n=UN(e.recipient,`recipient`);return[{address:t,selector:GN,recipients:[n]}]}function jN(e){try{let t=ne.fromBytes(k.toBytes(e));if(ne.size(t)!==32)throw Error(`invalid challenge id size`);return t}catch{throw new Y({reason:`challenge id must encode 32 bytes`})}}async function MN(e){let{accessKey:t,account:n,challengeId:r,chainId:i,request:a}=e;if(typeof n.sign!=`function`)return;let o=PN({accessKey:t,challengeId:r,chainId:i,request:a}),s=await n.sign({hash:Ue.getSignPayload(o)}),c=We.from(s);if(c.type===`keychain`||c.type===`multisig`)throw new Y({reason:`keyAuthorization must use a primitive signature`});return Ue.from(o,{signature:s})}function NN(e){let{accessKey:t,challengeId:n,chainId:r,payload:i,request:a}=e;if(i.type!==`keyAuthorization`)throw new Y({reason:`invalid keyAuthorization payload`});let o=FN(i.signature),s=IN(o);if(LN({accessKey:t,authorization:o,chainId:r}),o.witness?.toLowerCase()!==jN(n))throw new Y({reason:`keyAuthorization challenge mismatch`});return RN(o,a),BN(zN(o),a),VN(o.scopes,a),{authorization:o,source:{address:HN(o,s),chainId:r}}}function PN(e){let{accessKey:t,challengeId:n,chainId:r,request:i}=e;return Ue.from({address:UN(t.accessKeyAddress,`accessKeyAddress`),chainId:BigInt(r),expiry:DN(EN(i.subscriptionExpires)),limits:[{token:UN(i.currency,`currency`),limit:BigInt(i.amount),period:ON(i)}],scopes:AN(i),type:t.keyType,witness:jN(n)})}function FN(e){try{return Ue.deserialize(e)}catch(e){throw e instanceof Ue.InvalidSignatureTypeError?new Y({reason:`keyAuthorization must use a primitive signature`}):new Y({reason:`invalid keyAuthorization payload`})}}function IN(e){let t=e.signature;if(!t)throw new Y({reason:`keyAuthorization must use a primitive signature`});return t}function LN(e){let{accessKey:t,authorization:n,chainId:r}=e;if(n.chainId!==BigInt(r))throw new Y({reason:`keyAuthorization chainId mismatch`});if(t){if(!de(n.address,UN(t.accessKeyAddress,`accessKeyAddress`)))throw new Y({reason:`keyAuthorization access key mismatch`});if(n.type!==t.keyType)throw new Y({reason:`keyAuthorization key type mismatch`})}}function RN(e,t){if(kN({request:t}),e.expiry!==DN(EN(t.subscriptionExpires)))throw new Y({reason:`keyAuthorization expiry mismatch`})}function zN(e){let[t]=e.limits??[];if(!t||e.limits?.length!==1)throw new Y({reason:`keyAuthorization must contain exactly one token limit`});return t}function BN(e,t){if(!de(e.token,UN(t.currency,`currency`)))throw new Y({reason:`keyAuthorization currency mismatch`});if(e.limit!==BigInt(t.amount))throw new Y({reason:`keyAuthorization amount mismatch`});if(e.period!==ON(t))throw new Y({reason:`keyAuthorization period mismatch`})}function VN(e,t){if(!e||e.length!==1)throw new Y({reason:`keyAuthorization must contain a recipient-scoped transferWithMemo call`});let n=UN(t.currency,`currency`),r=UN(t.recipient,`recipient`),i=new Set;for(let t of e){if(!de(t.address,n))throw new Y({reason:`keyAuthorization call target mismatch`});let e=WN(t.selector);if(e!==`0xa9059cbb`&&e!==`0x95777d59`)throw new Y({reason:`keyAuthorization selector not allowed`});if(i.has(e))throw new Y({reason:`keyAuthorization duplicate selector`});if(i.add(e),t.recipients?.length!==1||!de(t.recipients[0],r))throw new Y({reason:`keyAuthorization recipient mismatch`})}if(!i.has(`0x95777d59`))throw new Y({reason:`keyAuthorization must allow transferWithMemo`})}function HN(e,t){let n=Ue.getSignPayload(e);try{let e=We.extractAddress({payload:n,signature:t});if(!We.verify(t,{address:e,payload:n}))throw new Y({reason:`keyAuthorization signature is invalid`});return e}catch(e){throw e instanceof Y?e:new Y({reason:`keyAuthorization signature is invalid`})}}function UN(e,t){if(!ue(e))throw new Y({reason:`${t} must be an address`});return e.toLowerCase()}function WN(e){return typeof e==`string`?e.toLowerCase():``}var GN,KN,qN,JN=I((()=>{SS(),GN=`0x95777d59`,KN=(1n<<64n)-1n,qN={dev_second:1n,day:86400n,week:604800n}}));function YN(e={}){let t=OA({chain:ve,getClient:e.getClient,rpcUrl:SO}),n=CA({account:e.account});return aE(xE,{context:QN,async createCredential({challenge:r,context:i}){let a=r.request.methodDetails?.chainId??vO.testnet,o=await t({chainId:a}),s=n(o,i),c=i?.accessKey??e.accessKey??r.request.methodDetails?.accessKey;if(!c)throw Error("No `accessKey` provided. The subscription challenge must include `accessKey`, or the client must pass one to parameters/context.");ZN(r.request),await e.validateRequest?.(r.request);let l=await XN(o,{accessKey:c,account:s,challengeId:r.id,chainId:a,request:r.request}),u=NN({accessKey:c,challengeId:r.id,chainId:a,payload:{signature:Ue.serialize(l),type:`keyAuthorization`},request:r.request});if(!de(u.source.address,s.address))throw Error(`keyAuthorization signer does not match the selected account`);return $S({challenge:r,payload:{signature:Ue.serialize(l),type:`keyAuthorization`},source:`did:pkh:eip155:${a}:${s.address.toLowerCase()}`})}})}async function XN(e,t){let{accessKey:n,account:r,challengeId:i,chainId:a,request:o}=t,s=await MN({accessKey:n,account:r,challengeId:i,chainId:a,request:o});if(s)return s;let c=await e.request({method:`wallet_authorizeAccessKey`,params:[{address:n.accessKeyAddress,expiry:DN(EN(o.subscriptionExpires)),keyType:n.keyType,limits:[{token:o.currency,limit:ne.fromNumber(BigInt(o.amount)),period:ON(o)}],scopes:AN(o),witness:jN(i)}]});return Ue.fromRpc(c.keyAuthorization)}function ZN(e){ON(e),DN(EN(e.subscriptionExpires))}var QN,$N=I((()=>{rC(),oE(),wA(),MA(),Zx(),CO(),SE(),JN(),QN=J.object({accessKey:J.optional(J.custom()),account:J.optional(J.custom())})}));function eP(e={}){let t=e.expectedChainId!==void 0&&(e.allowedChainIds===void 0||e.allowedChainIds.includes(e.expectedChainId)),n=e.expectedChainId===void 0?e:{...e,allowedChainIds:t?[e.expectedChainId]:[]};return[mj(e),tP(n)]}var tP,nP=I((()=>{dN(),TN(),yj(),$N(),tP=Object.assign(lN,{manager:wN}),(function(e){e.charge=mj,e.common=eP,e.session=tP,e.subscription=YN})(eP||={})})),rP=I((()=>{yj(),nP(),$N(),dN(),TN()})),iP=Ze({orderTempoChargeChallengesByBalance:()=>oP,readTempoKeystore:()=>EP,resolveTempoAccount:()=>DP,tempo:()=>sP});async function aP(e){process.stdout.write(Buffer.from(await e.arrayBuffer()))}async function oP(e,t){let n=[],r=[];for(let[t,i]of e.entries())mP(i)&&(n.push(t),r.push(i));if(r.length<2)return[...e];let i=await hP(t).catch(()=>void 0);if(!i)return[...e];let a=await Promise.all(r.map(async(e,t)=>({challenge:e,index:t,score:await gP(e,i)})));a.sort((e,t)=>FP.indexOf(e.score)-FP.indexOf(t.score)||e.index-t.index);let o=[...e];for(let[e,t]of n.entries())o[t]=a[e].challenge;return o}function sP(){let e;return lA({method:`tempo`,supports(e){return e.method===`tempo`&&[`charge`,`session`].includes(e.intent)},async setup({challenge:t,options:n,methodOpts:r}){let i=ik(n.account),a=t.request,o=a.currency,s=pP(r),c=bP({autoSwap:s.autoSwap??n.autoSwap,payWith:s.payWith??n.payWith,slippage:s.slippage??n.slippage,tokenIn:s.tokenIn}),l=o??``,u=a.decimals??6,d,f,p,m=!1,h=process.env.MPPX_PRIVATE_KEY?.trim()||(NO(i)?void 0:await ak(i).get());if(!h&&NO(i)&&OP()){m=!0;let e=DP(i);if(e){let r=LO(n.rpcUrl,{network:n.network});p=M({chain:await zO({network:n.network,rpcUrl:r}),transport:le(r)}),vP({challenge:t,clientChainId:p.chain?.id}),d=p.chain?.blockExplorers?.default?.url;let i=o?await UO(p,o,e.wallet_address).catch(()=>void 0):void 0;l=i?.symbol??o??``,u=i?.decimals??a.decimals??6}}else if(h)f=_e(h);else{let e=AP();if(e){let t=await ak(e).get();t&&(f=_e(t))}if(!f)throw n.account?new L({code:`ACCOUNT_NOT_FOUND`,message:`Account "${i}" not found.`,exitCode:69}):new L({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69})}if(!m&&f){let e=LO(n.rpcUrl,{network:n.network});p=M({chain:await zO({network:n.network,rpcUrl:e}),transport:le(e)}),vP({challenge:t,clientChainId:p.chain?.id}),d=p.chain?.blockExplorers?.default?.url;let r=o?await UO(p,o,f.address).catch(()=>void 0):void 0;l=r?.symbol??o??``,u=r?.decimals??a.decimals??6}if(m)return{tokenSymbol:l,tokenDecimals:u,explorerUrl:d,methods:[],async createCredential(e){let t=e.headers.get(`www-authenticate`);if(!t)throw Error(`No WWW-Authenticate header in 402 response.`);return kP(t)}};if(!f||!p)throw new L({code:`ACCOUNT_NOT_FOUND`,message:`Tempo requires a configured account.`,exitCode:69});let g=eP({account:f,...s.allowCustomEscrow===void 0?{}:{allowCustomEscrow:s.allowCustomEscrow},getClient:()=>p,...c===void 0?{}:{autoSwap:c},maxDeposit:(()=>{if(t.intent!==`session`)return;let e=t.request.suggestedDeposit,n=(s.deposit===void 0?void 0:String(s.deposit))??e??(HO(p.chain)?`10`:void 0);if(!n)throw new L({code:`MISSING_DEPOSIT`,message:`Session payment requires a deposit. Use -M deposit=<amount> or connect to testnet.`,exitCode:2});return n})()}),_=(()=>{if(!s.channel)return;let e=s.channel,t=SP(e);return{channelId:e,...t!==void 0&&{cumulativeAmountRaw:t.toString()}}})();return e={descriptor:void 0,async signVoucher({channelId:n,cumulativeAmount:r,escrowContract:i,chainId:a,action:o=`voucher`}){let s=e?.descriptor;if(!s)throw Error(`session descriptor not available`);let c={channelId:n,cumulativeAmount:r},l=await Ij(p,f,c,i,a);return $S({challenge:t,payload:{action:o,channelId:n,...o===`close`?{closeSignature:await Lj(p,f,c,i,a)}:{},descriptor:s,cumulativeAmount:r.toString(),signature:l},source:`did:pkh:eip155:${a}:${f.address}`})},source:`did:pkh:eip155:${p.chain.id}:${f.address}`},{tokenSymbol:l,tokenDecimals:u,explorerUrl:d,methods:[...g],credentialContext:_}},prepareCredentialRequest({challenge:e,headers:t}){e.intent===`session`&&(t.Accept=`text/event-stream`)},async handleResponse(t){if(t.challenge.intent!==`session`||!e)return!1;let{challenge:n,credential:r,response:i,fetchUrl:a,fetchInit:o,verbose:s}=t,{silent:c,confirmEnabled:l,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,shownKeys:p}=t,m=c?e=>{}:e=>process.stderr.write(e),h=YS(r),g=n.request,_=g.methodDetails,v=h.payload.channelId,y=_?.escrowContract??_?.escrow??`0x4d50500000000000000000000000000000000000`,b=_?.chainId??0,x=BigInt(g.amount),S=`cumulativeAmount`in h.payload&&h.payload.cumulativeAmount?BigInt(h.payload.cumulativeAmount):0n;if(`descriptor`in h.payload&&(e.descriptor=h.payload.descriptor),s>=1){if(h.payload.action===`open`){let e=g.suggestedDeposit,t=e?` ${X.dim(`(deposit ${e} ${u})`)}`:``;m(`${l?``:`
233
233
  `}${X.dim(`Channel opened ${h.payload.channelId}`)}${t}\n`)}else m(`${l?``:`
234
- `}${X.dim(`Channel reused ${h.payload.channelId}`)}\n`)}let C=i;C.ok&&!C.headers.get(`Content-Type`)?.includes(`text/event-stream`)&&h.payload.action===`open`&&`cumulativeAmount`in h.payload&&(S=BigInt(h.payload.cumulativeAmount));let w=C.headers.get(q.paymentReceipt);if(w)try{let e=JSON.parse(k.toString(w));$N(e,S),typeof e.acceptedCumulative==`string`&&e.acceptedCumulative&&pP(v,S),s>=1&&QN(e,{info:m,shownKeys:p,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,handler:this,prefix:`
235
- `})}catch{}return(C.headers.get(`Content-Type`)??``).includes(`text/event-stream`)?await eP(C,{challenge:n,channelId:v,escrowContract:y,chainId:b,cumulativeAmount:S,tickCost:x,fetchUrl:a,fetchInit:o,session:e,info:m,verbose:s,shownKeys:p,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,handler:this}):(await YN(C),v&&y&&b&&(l&&m(`
236
- `),l&&!await t.confirm(`Close channel?`,!0)?s>=1&&m(`${X.dim(`Kept channel open.`)}\n`):await tP({channelId:v,cumulativeAmount:S,escrowContract:y,chainId:b,fetchUrl:a,fetchInit:o,session:e,info:m,verbose:s,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,confirmEnabled:l}))),!0},formatReceiptField(e,t){(e===`reference`||e===`txHash`)&&typeof t==`string`&&t.startsWith(`0x`)}})}function QN(e,t){t.info(`${t.prefix??``}${X.bold(X.green(`Payment Receipt`))}\n`);let n=[],r=e.channelId&&e.reference&&e.channelId===e.reference,i=new Set([`acceptedCumulative`,`spent`]);for(let[a,o]of Object.entries(e)){if(o===void 0||t.shownKeys.has(a)||a===`reference`&&r)continue;let e=t.handler.formatReceiptField?.(a,o);e===void 0?i.has(a)&&typeof o==`string`?n.push([a,`${o} ${X.dim(`(${NO(BigInt(o),t.tokenSymbol,t.tokenDecimals)})`)}`]):(a===`reference`||a===`txHash`)&&typeof o==`string`&&t.explorerUrl?n.push([a,DO(`${t.explorerUrl}/tx/${o}`,o)]):n.push([a,String(o)]):n.push([a,e])}n.sort(([e],[t])=>e.localeCompare(t));let a=Math.max(...n.map(([e])=>e.length));for(let[e,r]of n)t.info(` ${X.dim(e.padEnd(a))} ${r}\n`);t.prefix&&t.info(`
237
- `)}function $N(e,t){if(typeof e.acceptedCumulative!=`string`)return;let n=BigInt(e.acceptedCumulative),r=typeof e.spent==`string`?BigInt(e.spent):0n;if(r>n)throw Error(`receipt spent exceeds accepted cumulative voucher amount`);if(n>t)throw Error(`receipt accepted cumulative exceeds locally signed voucher amount`);if(r>t)throw Error(`receipt spent exceeds locally signed voucher amount`)}async function eP(e,t){let n=t.cumulativeAmount,r=e.body?.getReader();if(!r)throw Error(`No response body`);let i=new TextDecoder,a=``,o=``,s=t.verbose?await nP():void 0,c=(()=>{if(!s||!X.isColorSupported)return;let e=e=>Math.max(0,Math.min(255,Math.round(e))),t=.299*s.r+.587*s.g+.114*s.b<128?1:-1,n=n=>r=>`\x1b[48;2;${e(s.r+n*t)};${e(s.g+n*t)};${e(s.b+n*t)}m${r}\x1b[49m`;return[n(12),n(24)]})(),l=0,u=e=>{if(c){let t=c[l%c.length];process.stdout.write(e.replace(/[^\n]+/g,e=>t(e))),l++}else process.stdout.write(e)},d=async e=>{for(let r of e){if(r.startsWith(`event: `)){o=r.slice(7).trim();continue}if(!r.startsWith(`data: `)){r===``&&(o=``);continue}let e=r.slice(6);if(e.trim()!==`[DONE]`){if(o===`payment-need-voucher`&&t.channelId&&t.escrowContract&&t.chainId){try{let r=JSON.parse(e);if(r.channelId!==t.channelId)throw Error(`payment-need-voucher channelId does not match current session`);let i=BigInt(r.requiredCumulative);if(i>n+t.tickCost)throw Error(`payment-need-voucher exceeds next locally billable amount`);n=n>i?n:i;let a=await t.session.signVoucher({channelId:t.channelId,cumulativeAmount:n,escrowContract:t.escrowContract,chainId:t.chainId});await globalThis.fetch(t.fetchUrl,{method:`POST`,headers:{[q.authorization]:a}})}catch(e){t.info(X.dim(X.yellow(` [voucher failed: ${e instanceof Error?e.message:e}]`)))}o=``;continue}if(o===`payment-receipt`){if(t.verbose>=1)try{QN(JSON.parse(e),{info:t.info,shownKeys:t.shownKeys,tokenSymbol:t.tokenSymbol,tokenDecimals:t.tokenDecimals,explorerUrl:t.explorerUrl,handler:t.handler,prefix:`
234
+ `}${X.dim(`Channel reused ${h.payload.channelId}`)}\n`)}let C=i;C.ok&&!C.headers.get(`Content-Type`)?.includes(`text/event-stream`)&&h.payload.action===`open`&&`cumulativeAmount`in h.payload&&(S=BigInt(h.payload.cumulativeAmount));let w=C.headers.get(q.paymentReceipt);if(w)try{let e=JSON.parse(k.toString(w));lP(e,S),typeof e.acceptedCumulative==`string`&&e.acceptedCumulative&&CP(v,S),s>=1&&cP(e,{info:m,shownKeys:p,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,handler:this,prefix:`
235
+ `})}catch{}return(C.headers.get(`Content-Type`)??``).includes(`text/event-stream`)?await uP(C,{challenge:n,channelId:v,escrowContract:y,chainId:b,cumulativeAmount:S,tickCost:x,fetchUrl:a,fetchInit:o,session:e,info:m,verbose:s,shownKeys:p,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,handler:this}):(await aP(C),v&&y&&b&&(l&&m(`
236
+ `),l&&!await t.confirm(`Close channel?`,!0)?s>=1&&m(`${X.dim(`Kept channel open.`)}\n`):await dP({channelId:v,cumulativeAmount:S,escrowContract:y,chainId:b,fetchUrl:a,fetchInit:o,session:e,info:m,verbose:s,tokenSymbol:u,tokenDecimals:d,explorerUrl:f,confirmEnabled:l}))),!0},formatReceiptField(e,t){(e===`reference`||e===`txHash`)&&typeof t==`string`&&t.startsWith(`0x`)}})}function cP(e,t){t.info(`${t.prefix??``}${X.bold(X.green(`Payment Receipt`))}\n`);let n=[],r=e.channelId&&e.reference&&e.channelId===e.reference,i=new Set([`acceptedCumulative`,`spent`]);for(let[a,o]of Object.entries(e)){if(o===void 0||t.shownKeys.has(a)||a===`reference`&&r)continue;let e=t.handler.formatReceiptField?.(a,o);e===void 0?i.has(a)&&typeof o==`string`?n.push([a,`${o} ${X.dim(`(${IO(BigInt(o),t.tokenSymbol,t.tokenDecimals)})`)}`]):(a===`reference`||a===`txHash`)&&typeof o==`string`&&t.explorerUrl?n.push([a,AO(`${t.explorerUrl}/tx/${o}`,o)]):n.push([a,String(o)]):n.push([a,e])}n.sort(([e],[t])=>e.localeCompare(t));let a=Math.max(...n.map(([e])=>e.length));for(let[e,r]of n)t.info(` ${X.dim(e.padEnd(a))} ${r}\n`);t.prefix&&t.info(`
237
+ `)}function lP(e,t){if(typeof e.acceptedCumulative!=`string`)return;let n=BigInt(e.acceptedCumulative),r=typeof e.spent==`string`?BigInt(e.spent):0n;if(r>n)throw Error(`receipt spent exceeds accepted cumulative voucher amount`);if(n>t)throw Error(`receipt accepted cumulative exceeds locally signed voucher amount`);if(r>t)throw Error(`receipt spent exceeds locally signed voucher amount`)}async function uP(e,t){let n=t.cumulativeAmount,r=e.body?.getReader();if(!r)throw Error(`No response body`);let i=new TextDecoder,a=``,o=``,s=t.verbose?await fP():void 0,c=(()=>{if(!s||!X.isColorSupported)return;let e=e=>Math.max(0,Math.min(255,Math.round(e))),t=.299*s.r+.587*s.g+.114*s.b<128?1:-1,n=n=>r=>`\x1b[48;2;${e(s.r+n*t)};${e(s.g+n*t)};${e(s.b+n*t)}m${r}\x1b[49m`;return[n(12),n(24)]})(),l=0,u=e=>{if(c){let t=c[l%c.length];process.stdout.write(e.replace(/[^\n]+/g,e=>t(e))),l++}else process.stdout.write(e)},d=async e=>{for(let r of e){if(r.startsWith(`event: `)){o=r.slice(7).trim();continue}if(!r.startsWith(`data: `)){r===``&&(o=``);continue}let e=r.slice(6);if(e.trim()!==`[DONE]`){if(o===`payment-need-voucher`&&t.channelId&&t.escrowContract&&t.chainId){try{let r=JSON.parse(e);if(r.channelId!==t.channelId)throw Error(`payment-need-voucher channelId does not match current session`);let i=BigInt(r.requiredCumulative);if(i>n+t.tickCost)throw Error(`payment-need-voucher exceeds next locally billable amount`);n=n>i?n:i;let a=await t.session.signVoucher({channelId:t.channelId,cumulativeAmount:n,escrowContract:t.escrowContract,chainId:t.chainId});await globalThis.fetch(t.fetchUrl,{method:`POST`,headers:{[q.authorization]:a}})}catch(e){t.info(X.dim(X.yellow(` [voucher failed: ${e instanceof Error?e.message:e}]`)))}o=``;continue}if(o===`payment-receipt`){if(t.verbose>=1)try{cP(JSON.parse(e),{info:t.info,shownKeys:t.shownKeys,tokenSymbol:t.tokenSymbol,tokenDecimals:t.tokenDecimals,explorerUrl:t.explorerUrl,handler:t.handler,prefix:`
238
238
 
239
239
  `})}catch{}o=``;continue}if(e.length===0)u(`
240
240
  `);else try{let t=JSON.parse(e);u(t.token??t.choices?.[0]?.delta?.content??e)}catch{u(e)}o=``}}};for(;;){let{done:e,value:t}=await r.read();if(e)break;a+=i.decode(t,{stream:!0});let n=a.split(`
241
- `);a=n.pop(),await d(n)}a.trim()&&await d([a]),t.channelId&&t.escrowContract&&t.chainId&&await tP({channelId:t.channelId,cumulativeAmount:n,escrowContract:t.escrowContract,chainId:t.chainId,fetchUrl:t.fetchUrl,fetchInit:t.fetchInit,session:t.session,info:t.info,verbose:t.verbose,tokenSymbol:t.tokenSymbol,tokenDecimals:t.tokenDecimals,explorerUrl:t.explorerUrl,confirmEnabled:!1})}async function tP(e){let t=await e.session.signVoucher({channelId:e.channelId,cumulativeAmount:e.cumulativeAmount,escrowContract:e.escrowContract,chainId:e.chainId,action:`close`}),n=await globalThis.fetch(e.fetchUrl,{...e.fetchInit,headers:{...Aw(e.fetchInit.headers),Authorization:t}});if(n.ok){if(mP(e.channelId),e.verbose>=1){let t=n.headers.get(q.paymentReceipt),r;if(t)try{let e=JSON.parse(k.toString(t));typeof e.txHash==`string`&&(r=e.txHash)}catch{}let i=r&&e.explorerUrl?` ${X.dim(DO(`${e.explorerUrl}/tx/${r}`,r))}`:``;e.info(`${X.dim(`Channel closed.`)} ${X.dim(`Spent ${NO(e.cumulativeAmount,e.tokenSymbol,e.tokenDecimals)}.`)}${i}\n`)}}else{let t=await n.text().catch(()=>``);e.info(`\n${X.dim(X.yellow(`Channel close failed`))} ${X.dim(`(${n.status})`)}\n`),e.info(`${X.dim(` channelId: ${e.channelId}`)}\n${X.dim(` cumulativeAmount: ${e.cumulativeAmount}`)}\n${X.dim(` escrowContract: ${e.escrowContract}`)}\n${X.dim(` chainId: ${e.chainId}`)}\n${X.dim(` response: ${t||`(empty)`}`)}\n`)}}function nP(e=100){return!process.stdin.isTTY||!process.stdout.isTTY?Promise.resolve(void 0):new Promise(t=>{let n=process.stdin.isRaw,r=``,i=()=>{clearTimeout(a),process.stdin.removeListener(`data`,o),process.stdin.isTTY&&process.stdin.setRawMode(n??!1),process.stdin.pause()},a=setTimeout(()=>{i(),t(void 0)},e),o=e=>{r+=e.toString();let n=r.match(/\x1b\]11;rgb:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i);if(!n)return;i();let a=e=>Number.parseInt(e.slice(0,2),16);t({r:a(n[1]),g:a(n[2]),b:a(n[3])})};process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on(`data`,o),process.stdout.write(`\x1B]11;?\x07`)})}function rP(e){return sP(CP,e,wP)}function iP(e){return e.method===`tempo`&&e.intent===`charge`}async function aP(e){let t=tk(e.options.account),n=process.env.MPPX_PRIVATE_KEY?.trim()||(AO(t)?void 0:await nk(t).get()),r;if(n)r=ve(n).address;else if(AO(t)&&vP())r=_P(t)?.wallet_address;else{let e=bP();if(e){let t=await nk(e).get();t&&(r=ve(t).address)}}if(!r)return;let i=PO(e.options.rpcUrl,{network:e.options.network}),a=j({chain:await IO({network:e.options.network,rpcUrl:i}),transport:ue(i)});return{account:r,client:a}}async function oP(e,t){let n=e.request,r=n.currency,i=n.amount;if(typeof r!=`string`||typeof i!=`string`)return`unsupported`;let a=n.methodDetails?.chainId;if(a&&t.client.chain?.id&&a!==t.client.chain.id)return`unsupported`;let o=BigInt(i);if(o===0n)return`payable`;let s=await Ie.token.getBalance(t.client,{account:t.account,token:r}).then(e=>e.amount).catch(()=>void 0);return s===void 0?`unknownBalance`:s>=o?`payable`:`insufficientBalance`}function sP(e,t,n){if(t&&typeof t==`object`&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!n.includes(e));if(e.length)throw Error(`Unsupported CLI method option(s): ${e.join(`, `)}`)}let r=e.safeParse(t??{});if(r.success)return r.data;let i=r.error.issues.map(e=>`${e.path.length?e.path.join(`.`):`options`}: ${e.message}`).join(`, `);throw Error(`Invalid CLI options (${i})`)}function cP(e){let t=e.challenge.request.methodDetails?.chainId;if(!t||!e.clientChainId||t===e.clientChainId)return;let n=t===4217?` Use --network mainnet or --rpc-url https://rpc.tempo.xyz.`:t===42431?` Use --network testnet or --rpc-url https://rpc.moderato.tempo.xyz.`:``;throw new I({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${t}, but RPC is chainId ${e.clientChainId}.${n}`,exitCode:2})}function lP(e){if(e)return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function uP(e){let t=lP(e.tokenIn)??lP(e.payWith);if(!(!e.autoSwap&&!t&&e.slippage===void 0)){if(e.autoSwap===!1&&!t&&e.slippage===void 0)return!1;if(e.slippage!==void 0&&(!Number.isFinite(e.slippage)||e.slippage<0))throw Error(`Invalid CLI options (slippage: expected a non-negative number)`);return{...t?{tokenIn:t}:{},...e.slippage===void 0?{}:{slippage:e.slippage}}}}function dP(){return c.join(process.env.XDG_CONFIG_HOME||c.join(b.homedir(),`.config`),`mppx`,`channels`)}function fP(e){try{let n=t.readFileSync(c.join(dP(),e),`utf-8`).trim();return n?BigInt(n):void 0}catch{return}}function pP(e,n){let r=dP();t.mkdirSync(r,{recursive:!0}),t.writeFileSync(c.join(r,e),n.toString(),`utf-8`)}function mP(e){try{t.unlinkSync(c.join(dP(),e))}catch{}}function hP(){return b.platform()===`darwin`?c.join(b.homedir(),`Library`,`Application Support`,`tempo`,`wallet`,`keys.toml`):c.join(process.env.XDG_DATA_HOME||c.join(b.homedir(),`.local`,`share`),`tempo`,`wallet`,`keys.toml`)}function gP(){try{let e=t.readFileSync(hP(),`utf-8`),n=[],r;for(let t of e.split(`
242
- `)){let e=t.trim();if(e===`[[keys]]`){r?.wallet_address&&n.push(r),r={wallet_type:`local`,wallet_address:``,chain_id:0};continue}if(!r)continue;let i=e.match(/^(\w+)\s*=\s*"?([^"]*)"?$/);if(!i)continue;let[,a,o]=i;a===`wallet_type`?r.wallet_type=o:a===`wallet_address`?r.wallet_address=o:a===`chain_id`&&(r.chain_id=Number.parseInt(o,10))}return r?.wallet_address&&n.push(r),n}catch{return[]}}function _P(e){let t=gP();if(t.length===0)return;let n=e.slice(6);if(n==="default"||n===``)return t[0];let r=Number.parseInt(n,10);if(!Number.isNaN(r)&&r>=0&&r<t.length)return t[r]}function vP(){if(EP!==void 0)return EP;try{m.execFileSync(`which`,[`tempo`],{stdio:`ignore`}),EP=!0}catch{EP=!1}return EP}async function yP(e){return new Promise((t,n)=>{m.execFile(`tempo`,[`mpp`,`sign`,`--challenge`,e],(e,r,i)=>{if(e){let t=i?.trim()||e.message;n(Error(`tempo mpp sign failed: ${t}`));return}let a=r.trim();if(!a){n(Error(`tempo mpp sign returned empty output`));return}t(a)})})}function bP(){let e=ek();if(AO(e.get())&&!vP()&&b.platform()===`darwin`)try{let t=m.execFileSync(`security`,[`dump-keychain`],{encoding:`utf-8`}),n=[];for(let e of t.split(`keychain:`)){let t=e.match(/"svce"<blob>="([^"]*)"/),r=e.match(/"acct"<blob>="([^"]*)"/);t?.[1]===xP&&r?.[1]&&n.push(r[1])}if(n.length>0)return e.set(n[0]),n[0]}catch{}}var xP,SP,CP,wP,TP,EP,DP=F((()=>{Ox(),_T(),Fx(),nC(),qN(),UE(),Bj(),ck(),JO(),sA(),xP=`mppx`,SP=p.union([p.boolean(),p.literal(`true`).transform(()=>!0),p.literal(`false`).transform(()=>!1)]),CP=p.object({allowCustomEscrow:p.optional(SP),autoSwap:p.optional(SP),channel:p.optional(p.coerce.string()),deposit:p.optional(p.union([p.string(),p.number()])),payWith:p.optional(p.string()),slippage:p.optional(p.coerce.number()),tokenIn:p.optional(p.string())}),wP=[`allowCustomEscrow`,`autoSwap`,`channel`,`deposit`,`payWith`,`slippage`,`tokenIn`],TP=[`payable`,`unknownBalance`,`insufficientBalance`,`unsupported`]}));OS(),ck(),sA();const OP=[...Object.entries(mk),...Object.entries(hk),...Object.entries(gk),...Object.entries(_k)];function kP(){return oA({method:`evm`,supports:AP,async setup({challenge:e,options:t}){let n=e.request,r=n.network?jP(wk(n.network)):void 0,i=n.network&&n.asset?OP.find(([,e])=>Sk(e,n.asset,n.network)):void 0,a=n.extra?.name,o=n.extra?.version,s=n.asset&&n.network&&typeof a==`string`&&typeof o==`string`?fk({address:n.asset,decimals:i?.[1].decimals??6,network:n.network,transfer:{name:a,type:`eip3009`,version:o}}):void 0,c=await ak(t.account);return{explorerUrl:r?.blockExplorers?.default?.url,methods:[...aA({account:c,...s&&{currencies:[s]}})],tokenDecimals:i?.[1].decimals??6,tokenSymbol:i?.[0]??``}}})}function AP(e){if(!ES(e))return!1;let t=e.request,n=t.extra,r=n?.assetTransferMethod;return t.scheme===`exact`&&typeof t.asset==`string`&&typeof t.network==`string`&&typeof n?.name==`string`&&typeof n?.version==`string`&&(r===void 0||r===`eip3009`)}function jP(e){return Object.values(Ve).find(t=>t.id===e)}_S(),JS(),DP();const MP=[ZN(),_A(),cA(),kP()];async function NP(e,t,n){let r=n;for(let n of t??[]){let t=await n.preparePayment?.({challenge:e,...r===void 0?{}:{credentialContext:r}});t&&`credentialContext`in t&&(r=t.credentialContext)}return r}function PP(e,t){let n=t?.plugins?.find(t=>RP(t,e));if(n)return{plugin:n};let r=LP(t)?.filter(t=>t.name===e.method&&t.intent===e.intent),i=r?.find(t=>t.canHandleChallenge?.({challenge:e})??!0);if(i)return{method:i};if(r?.length)return{};let a=MP.find(t=>RP(t,e));return a?{plugin:a}:{}}function FP(e,t){let n=LP(t);if(n?.length){let r=NS(e,n,AS(n,t?.paymentPreferences).entries);if(r){let e=t?.plugins?.find(e=>RP(e,r.challenge));return{challenge:r.challenge,...e?{plugin:e}:{method:r.method}}}return}for(let n of e){let e=PP(n,t);if(e.plugin||e.method)return{challenge:n,...e}}}function IP(e){let t=LP(e);if(t?.length)return AS(t,e?.paymentPreferences).header}function LP(e){return Array.isArray(e?.methods)?e.methods.flat():void 0}function RP(e,t){return e.supports?e.supports(t):e.method===t.method}async function zP(e){let t=BP(e);if(!t)return;let n=await import(t);return{config:n.default??n,path:t}}function BP(e){if(e){let n=c.resolve(e);return t.existsSync(n)?n:void 0}let n=process.env.MPPX_CONFIG?.trim();if(n){let e=c.resolve(n);return t.existsSync(e)?e:void 0}}function VP(e,t){function n(t){let n={...t.request};if(t.method===`tempo`&&t.intent===`session`){let e={...n.methodDetails};delete e.sessionSnapshot,Object.keys(e).length?n.methodDetails=e:delete n.methodDetails}return $x({...t,request:n,id:e.id,expires:e.expires})}if(n(t)!==n(e))throw Error(`Payment request changed on retry. Run the command again to approve the new payment.`)}DP(),_S(),tM(),aN(),hN(),mO();function HP(e){return e??globalThis.fetch.bind(globalThis)}function UP(e,t){let n=e.request.methodDetails?.chainId;if(n!==void 0&&n!==t.chainId)throw Error(`Close challenge changed the session chain.`);if(typeof e.request.recipient!=`string`||e.request.recipient.toLowerCase()!==t.descriptor.payee.toLowerCase())throw Error(`Close challenge changed the session payee.`);if(typeof e.request.currency!=`string`||e.request.currency.toLowerCase()!==t.descriptor.token.toLowerCase())throw Error(`Close challenge changed the session token.`);if(Jj(e,t.escrow).toLowerCase()!==t.escrow.toLowerCase())throw Error(`Close challenge changed the session escrow.`);let r=FD(e);if(r&&r.channelId.toLowerCase()!==t.channelId.toLowerCase())throw Error(`Close challenge changed the session channel.`)}async function WP(e){UP(e.challenge,e.channel);let t=HP(e.fetch),n,r=async(r,i)=>{n&&=(await e.onChallenge?.(n),void 0);let a=await t(r,i);if(a.status!==402)return a;let o=cS(a).find(ND);if(!o)throw Error(`Refreshed close response did not include tempo/session.`);return UP(o,e.channel),n=o,a},i=mN({...e.manager,bootstrap:!1,escrow:e.channel.escrow,fetch:r});rN(i).rehydrate(e);let a=await i.close();if(!a)throw Error(`Session close response did not include a payment receipt.`);return{manager:i,receipt:a}}_S(),tM(),sM(),mO(),Sj(),Zx();var GP=class extends Error{name=`SessionStateError`;code=`SESSION_STATE_INVALID`;file;constructor(e,t={}){super(e,t.cause===void 0?void 0:{cause:t.cause}),this.file=t.file}},KP=class extends Error{name=`SessionBusyError`;code=`SESSION_BUSY`;exitCode=75;scope;owner;constructor(e,t){super(`Session scope is busy in process ${t.pid} on ${t.hostname}.`),this.scope=e,this.owner=t}};const qP=J.object({channelId:qx(),cumulativeAmount:J.string(),deposit:J.string(),descriptor:J.object({payer:Kx(),payee:Kx(),operator:Kx(),token:Kx(),salt:qx(),authorizedSigner:Kx(),expiringNonceHash:qx()}),escrow:Kx(),chainId:J.number(),opened:J.boolean()}),JP=J.object({name:J.optional(J.string()),address:Kx()}),YP=J.object({method:J.literal(`tempo`),intent:J.literal(`session`),status:J.literal(`success`),timestamp:J.string(),reference:J.string(),challengeId:J.string(),channelId:qx(),acceptedCumulative:J.string(),spent:J.string(),units:J.optional(J.number()),txHash:J.optional(qx())}),XP=J.object({version:J.literal(1),method:J.literal(`tempo`),intent:J.literal(`session`),status:J.enum([`opening`,`open`,`closing`,`stale`]),channel:qP,account:JP,endpoint:J.string(),challenge:gS,receipt:J.optional(YP),spent:J.string(),units:J.number(),createdAt:J.string(),updatedAt:J.string()}),ZP=J.object({version:J.literal(1),channelId:qx()}),QP=J.object({version:J.literal(1),scope:J.string(),hostname:J.string(),pid:J.number(),token:J.string(),createdAt:J.string()});function $P(e,t,n,r){let i=e.safeParse(t);if(!i.success)throw Z(n,r,i.error);return i.data}function eF(e){let t=uF(e);return[t.payer,t.payee,t.token,t.escrow,t.chainId].join(`:`)}function tF(e){return{payer:e.descriptor.payer,payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId}}function nF(e={}){let t=e.stateRoot??iF(),n={root:t,channels:c.join(t,`channels`),locks:c.join(t,`locks`),preferred:c.join(t,`preferred`)},r=e.hostname??b.hostname(),i=e.pid??process.pid,a=e.now??(()=>new Date),o=e.isProcessAlive??IF;async function s(){for(let e of[n.root,n.channels,n.locks,n.preferred])await C.mkdir(e,{recursive:!0,mode:448}),await C.chmod(e,448)}async function l(e){let t=cF(e),r=aF(n,t),i=await DF(r);if(i===void 0)return;let a=vF(i,r);if(a.channel.channelId.toLowerCase()!==t)throw Z(r,`Session filename does not match its channel ID.`);return yF(a)}async function u(){let e;try{e=await C.readdir(n.channels,{withFileTypes:!0})}catch(e){if(RF(e,`ENOENT`))return[];throw Z(n.channels,`Unable to list managed sessions.`,e)}let t=[];for(let n of e){if(!n.isFile()||n.name.includes(`.tmp-`)||!n.name.endsWith(`.json`))continue;let e=n.name.slice(0,-5);cF(e);let r=await l(e);r&&t.push(r)}return t.sort((e,t)=>e.createdAt.localeCompare(t.createdAt))}async function d(e){await s();let t=mF(e.channel),r=cF(t.channelId),i=aF(n,r),o=await DF(i),c=o===void 0?void 0:vF(o,i);c&&bF(c,e,i);let l=gF(e.challenge,i);SF(l,t,i);let u=e.receipt?_F(e.receipt,t.channelId,i):void 0,d=c?oM(c.channel):void 0,f=EF(t.cumulativeAmount,d?.cumulativeAmount??0n),p=EF(e.spent??0n,u?BigInt(u.spent):0n,c?BigInt(c.spent):0n);if(p>f)throw Z(i,`Session spend exceeds the locally authorized cumulative amount.`);let m=hF(aM({...t,cumulativeAmount:f}),i),h=TF(c?.updatedAt,a(),i),g=wF(c?.receipt,u),_=pF(e.account,i),v=vF({version:1,method:`tempo`,intent:`session`,status:e.status,channel:m,account:{..._.name===void 0?c?.account.name===void 0?{}:{name:c.account.name}:{name:_.name},address:_.address},endpoint:fF(e.endpoint,i),challenge:l,...g!==void 0&&{receipt:g},spent:p.toString(),units:Math.max(c?.units??0,e.units??0,u?.units??0),createdAt:c?.createdAt??h,updatedAt:h},i);return await OF(i,v),yF(v)}async function f(e){let t=sF(n,e),r=await DF(t);if(r===void 0)return;let{channelId:i}=$P(ZP,r,t,`Preferred session is invalid.`),a=await l(i);if(!a)throw Z(t,`Preferred session ${i} does not exist.`);return CF(a.channel,e,t),i}async function p(e,t){let r=cF(t),i=await l(r),a=sF(n,e);if(!i)throw Z(a,`Session ${r} does not exist.`);CF(i.channel,e,a),await OF(a,{version:1,channelId:r})}async function m(e,t){let r=sF(n,e),i=t===void 0?void 0:cF(t),a=await DF(r);if(a===void 0)return;let o=$P(ZP,a,r,`Preferred session is invalid.`).channelId;i&&o.toLowerCase()!==i||await PF(r,`Unable to clear preferred session.`)}async function h(e){let t=cF(e),r=await l(t);r&&(await m(tF(r.channel),t),await PF(aF(n,t),`Unable to remove session.`))}async function g(e){await s();let t=oF(n,e);for(let n=0;n<3;n++){let n={version:1,scope:e,hostname:r,pid:i,token:_(),createdAt:a().toISOString()};try{if(await kF(t,n),await MF(jF(t))){await NF(t,n);continue}return{async release(){await NF(t,n)}}}catch(e){if(!RF(e,`EEXIST`))throw e}let s=await DF(t);if(s===void 0)continue;let c=$P(QP,s,t,`Session lock is invalid.`);if(c.scope!==e)throw Z(t,`Session lock scope is invalid.`);if(c.hostname!==r||o(c.pid))throw new KP(e,c);await AF(t,c)}let c=await DF(t);throw c===void 0?Z(t,`Unable to acquire session lock.`):new KP(e,$P(QP,c,t,`Session lock is invalid.`))}async function v(e){return g(eF(e))}return{root:t,get:l,list:u,upsert:d,remove:h,getPreferred:f,setPreferred:p,clearPreferred:m,acquire:v}}function rF(e,t){let n=dF(t.scope),r=t.selection===`auto`||t.selection===`new`?void 0:cF(t.selection);function i(e){if(e.toLowerCase()!==n)throw new GP(`Session manager requested an unexpected payment scope.`)}async function a(n=!0){if(t.selection===`new`&&!r)return;let i=r??await e.getPreferred(t.scope);if(!i)return;let a=await e.get(i);if(!a)throw new GP(`Session ${i} does not exist.`);if(CF(a.channel,t.scope),!(n&&(a.status!==`open`||!a.channel.opened)))return r=i,a}return{async get(e){return i(e),(await a())?.channel},async set(n){if(i(rM(n)),CF(n,t.scope),r&&r.toLowerCase()!==n.channelId.toLowerCase())throw new GP(`Session manager selected ${r}, but attempted to store ${n.channelId}.`);r||t.onNewChannel?.(n);let a=await e.upsert({...t.context(),channel:n});r=a.channel.channelId,await e.setPreferred(t.scope,a.channel.channelId)},async delete(n){i(n);let o=await a(!1);if(!o)return;let s=t.context();await e.upsert({...o,...s,status:s.status===`closing`?`closing`:`stale`,channel:o.channel,spent:s.spent??o.spent,units:s.units??o.units}),s.status!==`closing`&&await e.clearPreferred(t.scope,o.channel.channelId),r=void 0}}}function iF(){let e=process.env.XDG_STATE_HOME||c.join(b.homedir(),`.local`,`state`);return c.join(e,`mppx`,`sessions`,`v1`)}function aF(e,t){return c.join(e.channels,`${t}.json`)}function oF(e,t){let n=g(`sha256`).update(t).digest(`hex`);return c.join(e.locks,`${n}.lock`)}function sF(e,t){let n=g(`sha256`).update(eF(t)).digest(`hex`);return c.join(e.preferred,`${n}.json`)}function cF(e){return $P(qx(),e,void 0,`Invalid session channel ID: ${e}.`).toLowerCase()}function lF(e,t,n){return $P(Kx(),e,n,`Invalid ${t}.`).toLowerCase()}function uF(e){if(!Number.isSafeInteger(e.chainId)||e.chainId<0)throw new GP(`Invalid session chain ID.`);return{payer:lF(e.payer,`session payer`),payee:lF(e.payee,`session payee`),token:lF(e.token,`session token`),escrow:lF(e.escrow,`session escrow`),chainId:e.chainId}}function dF(e){let t=uF(e);return[t.payee,t.token,t.escrow,t.chainId].join(`:`)}function fF(e,t){if(typeof e!=`string`)throw Z(t,`Session endpoint is invalid.`);let n;try{n=new URL(e)}catch(e){throw Z(t,`Session endpoint is invalid.`,e)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw Z(t,`Session endpoint must use HTTP or HTTPS.`);if(n.username||n.password)throw Z(t,`Session endpoint must not contain credentials.`);let r=e.indexOf(`#`);return r===-1?e:e.slice(0,r)}function pF(e,t){return $P(JP,e,t,`Session account is invalid.`)}function mF(e){return oM(hF(aM(e)))}function hF(e,t){return $P(qP,e,t,`Stored session channel is invalid.`)}function gF(e,t){let n=gS.safeParse(e);if(!n.success||!ND(n.data))throw Z(t,`Stored session challenge is invalid.`);return n.data}function _F(e,t,n){let r=$P(YP,e,n,`Stored session receipt is invalid.`);if(r.channelId!==t.toLowerCase())throw Z(n,`Stored session receipt has a different channel ID.`);if(r.reference.toLowerCase()!==t.toLowerCase())throw Z(n,`Stored session receipt has a different reference.`);if(BigInt(r.spent)>BigInt(r.acceptedCumulative))throw Z(n,`Stored session receipt spend exceeds its accepted amount.`);return r}function vF(e,t){let n=$P(XP,e,t,`Stored session is invalid.`),{receipt:r,...i}=n,a=n.channel,o=n.account;if(o.address.toLowerCase()!==a.descriptor.payer.toLowerCase())throw Z(t,`Stored session account does not match the channel payer.`);let s=r?_F(r,a.channelId,t):void 0,c=n.spent,l=BigInt(a.cumulativeAmount);if(BigInt(c)>l)throw Z(t,`Stored session spend exceeds its cumulative authorization.`);if(s&&BigInt(s.acceptedCumulative)>l)throw Z(t,`Stored receipt exceeds the cumulative authorization.`);if(Date.parse(n.updatedAt)<Date.parse(n.createdAt))throw Z(t,`Stored session timestamps are not monotonic.`);let u=fF(n.endpoint,t);if(u!==n.endpoint)throw Z(t,`Stored session endpoint contains a fragment.`);let d=gF(n.challenge,t);return SF(d,oM(a),t),{...i,account:o,channel:a,endpoint:u,challenge:d,...s&&{receipt:s}}}function yF(e){return{version:1,status:e.status,channel:oM(e.channel),account:e.account,endpoint:e.endpoint,challenge:e.challenge,...e.receipt&&{receipt:e.receipt},spent:BigInt(e.spent),units:e.units,createdAt:e.createdAt,updatedAt:e.updatedAt}}function bF(e,t,n){let r=mF(t.channel),i=pF(t.account,n),a=oM(e.channel);if(JSON.stringify(xF(r))!==JSON.stringify(xF(a)))throw Z(n,`Session update changed immutable channel identity.`);if(i.address.toLowerCase()!==e.account.address.toLowerCase())throw Z(n,`Session update changed the payer account.`)}function xF(e){return{channelId:e.channelId.toLowerCase(),descriptor:Object.fromEntries(Object.entries(e.descriptor).map(([e,t])=>[e,typeof t==`string`?t.toLowerCase():t])),escrow:e.escrow.toLowerCase(),chainId:e.chainId}}function SF(e,t,n){if(vj({...t.descriptor,chainId:t.chainId,escrow:t.escrow}).toLowerCase()!==t.channelId.toLowerCase())throw Z(n,`Session channel ID does not match its descriptor.`);let r=lF(e.request.recipient,`challenge recipient`,n),i=lF(e.request.currency,`challenge currency`,n);if(r!==t.descriptor.payee.toLowerCase())throw Z(n,`Session challenge payee does not match the channel.`);if(i!==t.descriptor.token.toLowerCase())throw Z(n,`Session challenge token does not match the channel.`);if(Jj(e,t.escrow).toLowerCase()!==t.escrow.toLowerCase())throw Z(n,`Session challenge escrow does not match the channel.`);if(LF(e.request.methodDetails)){let r=e.request.methodDetails;if(r.chainId!==void 0&&r.chainId!==t.chainId)throw Z(n,`Session challenge chain does not match the channel.`)}}function CF(e,t,n){let r=uF(t);if(e.descriptor.payer.toLowerCase()!==r.payer||e.descriptor.payee.toLowerCase()!==r.payee||e.descriptor.token.toLowerCase()!==r.token||e.escrow.toLowerCase()!==r.escrow||e.chainId!==r.chainId)throw Z(n,`Session channel does not match the selected payment scope.`)}function wF(e,t){return e?t&&Date.parse(t.timestamp)>=Date.parse(e.timestamp)?t:e:t}function TF(e,t,n){if(!Number.isFinite(t.getTime()))throw Z(n,`Session clock is invalid.`);let r=t.toISOString();return!e||Date.parse(r)>=Date.parse(e)?r:e}function EF(...e){return e.reduce((e,t)=>t>e?t:e,0n)}async function DF(e){let t;try{t=await C.readFile(e,`utf8`)}catch(t){if(RF(t,`ENOENT`))return;throw Z(e,`Unable to read session state.`,t)}try{return JSON.parse(t)}catch(t){throw Z(e,`Session state contains invalid JSON.`,t)}}async function OF(e,t){await C.mkdir(c.dirname(e),{recursive:!0,mode:448}),await C.chmod(c.dirname(e),448);let n=`${e}.tmp-${process.pid}-${_()}`,r;try{r=await C.open(n,`wx`,384),await r.writeFile(`${JSON.stringify(t,null,2)}\n`,`utf8`),await r.sync(),await r.close(),r=void 0,await C.rename(n,e),await C.chmod(e,384),await FF(c.dirname(e))}catch(t){throw await r?.close().catch(()=>void 0),await C.unlink(n).catch(()=>void 0),t instanceof GP?t:Z(e,`Unable to write session state.`,t)}}async function kF(e,t){let n;try{n=await C.open(e,`wx`,384),await n.writeFile(`${JSON.stringify(t)}\n`,`utf8`),await n.sync(),await n.close(),n=void 0,await FF(c.dirname(e))}catch(t){throw await n?.close().catch(()=>void 0),n&&await C.unlink(e).catch(()=>void 0),t}}async function AF(e,t){let n=jF(e);try{await C.link(e,n)}catch(t){if(RF(t,`EEXIST`)||RF(t,`ENOENT`))return;throw Z(e,`Unable to claim dead lock.`,t)}try{let r=await DF(n);if(r===void 0||$P(QP,r,n,`Session lock is invalid.`).token!==t.token)return;await PF(e,`Unable to reclaim dead lock.`)}finally{await PF(n,`Unable to release dead lock claim.`)}}function jF(e){return`${e}.reclaim`}async function MF(e){try{return await C.access(e),!0}catch(t){if(RF(t,`ENOENT`))return!1;throw Z(e,`Unable to inspect session lock.`,t)}}async function NF(e,t){let n=await DF(e);n!==void 0&&$P(QP,n,e,`Session lock is invalid.`).token===t.token&&await PF(e,`Unable to release session lock.`)}async function PF(e,t){try{await C.unlink(e),await FF(c.dirname(e))}catch(n){if(!RF(n,`ENOENT`))throw Z(e,t,n)}}async function FF(e){let t=await C.open(e,`r`);try{await t.sync()}finally{await t.close()}}function IF(e){try{return process.kill(e,0),!0}catch(e){if(RF(e,`ESRCH`))return!1;if(RF(e,`EPERM`))return!0;throw e}}function LF(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function RF(e,t){return e instanceof Error&&`code`in e&&e.code===t}function Z(e,t,n){return new GP(t,{...n!==void 0&&{cause:n},file:e})}Ox(),_T(),YM(),fM(),Sj(),ck(),JO();const zF=p.object({status:p.enum([`opening`,`open`,`closing`,`stale`]),channelId:p.string(),account:p.string().optional(),payer:p.string(),payee:p.string(),authorizedSigner:p.string(),token:p.string(),escrow:p.string(),chainId:p.number(),cumulativeAmount:p.string(),confirmedSpend:p.string(),deposit:p.string(),units:p.number(),resourceUrl:p.string(),createdAt:p.string(),updatedAt:p.string()}),BF=p.object({channelId:p.string(),status:p.enum([`closed`,`already-closed`]),spent:p.string(),txHash:p.string().optional()}),VF=p.object({closed:p.array(BF),failed:p.array(p.object({channelId:p.string(),message:p.string()}))});function HF(e){return e===`mainnet`?ye.id:be.id}function UF(e){if(e===ye.id)return`mainnet`;if(e===be.id)return`testnet`}function WF(e){let t={};for(let n of e??[]){let e=n.indexOf(`:`);if(e===-1)throw new I({code:`INVALID_HEADER`,message:`Invalid header format: ${n}`,exitCode:2});t[n.slice(0,e).trim()]=n.slice(e+1).trim()}return t}function GF(e){return{status:e.status,channelId:e.channel.channelId,...e.account.name&&{account:e.account.name},payer:e.channel.descriptor.payer,payee:e.channel.descriptor.payee,authorizedSigner:e.channel.descriptor.authorizedSigner,token:e.channel.descriptor.token,escrow:e.channel.escrow,chainId:e.channel.chainId,cumulativeAmount:e.channel.cumulativeAmount.toString(),confirmedSpend:e.spent.toString(),deposit:e.channel.deposit.toString(),units:e.units,resourceUrl:e.endpoint,createdAt:e.createdAt,updatedAt:e.updatedAt}}function KF(e,t){throw e instanceof I?e:e instanceof KP?new I({code:e.code,message:e.message,exitCode:e.exitCode,cause:e}):e instanceof GP?new I({code:e.code,message:e.message,exitCode:65,cause:e}):new I({code:t,message:e instanceof Error?e.message:String(e),exitCode:75,...e instanceof Error&&{cause:e}})}async function qF(e,t){let n=await ik(t??e.account.name);if(!NM(n.account,e.channel.descriptor))throw new I({code:`SESSION_ACCOUNT_MISMATCH`,message:`Account ${n.account.address} cannot sign for session ${e.channel.channelId}.`,exitCode:2});return n}async function JF(e,t){if(t.network&&HF(t.network)!==e)throw new I({code:`CHAIN_MISMATCH`,message:`Session uses chainId ${e}, not ${t.network}.`,exitCode:2});let n=t.network??UF(e),r=PO(t.rpcUrl,{network:n}),i=await IO({network:n,rpcUrl:r});if(i.id!==e)throw new I({code:`CHAIN_MISMATCH`,message:`Session uses chainId ${e}, but RPC is chainId ${i.id}.`,exitCode:2});return j({chain:i,transport:ue(r)})}const YF=cb(`sessions`,{description:`Manage persistent payment sessions (list, view, close)`}).command(`list`,{description:`List persistent payment sessions`,options:p.object({account:p.string().optional().describe(`Filter by account name`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Filter by Tempo network`)}),output:p.object({sessions:p.array(zF)}),alias:{account:`a`},async run(e){try{let t=(await nF().list()).filter(t=>!(e.options.account&&t.account.name!==e.options.account||e.options.network&&t.channel.chainId!==HF(e.options.network))).map(GF),n={sessions:t};if(e.format===`json`&&e.formatExplicit)return e.ok(n);t.length===0&&console.log(`No sessions.`);for(let[e,n]of t.entries())e>0&&console.log(``),XF(n);return}catch(e){return KF(e,`SESSION_LIST_FAILED`)}}}).command(`view`,{description:`View a persistent payment session`,args:p.object({channelId:p.string().describe(`Full session channel ID`)}),output:zF,async run(e){try{let t=await nF().get(e.args.channelId);if(!t)throw new I({code:`SESSION_NOT_FOUND`,message:`Session ${e.args.channelId} was not found.`,exitCode:2});let n=GF(t);if(e.format===`json`&&e.formatExplicit)return e.ok(n);XF(n);return}catch(e){return KF(e,`SESSION_VIEW_FAILED`)}}}).command(`close`,{description:`Cooperatively close persistent payment sessions`,usage:[{suffix:`<channel-id> [options]`},{suffix:`--all --yes [options]`}],args:p.object({channelId:p.string().optional().describe(`Full session channel ID`)}),options:p.object({account:p.string().optional().describe(`Account name`),all:p.boolean().optional().default(!1).describe(`Close every matching session`),header:p.array(p.string()).optional().describe(`Add close request header (repeatable)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),rpcUrl:p.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`),url:p.string().optional().describe(`Override the stored resource URL`),yes:p.boolean().optional().default(!1).describe(`Confirm closing every session`)}),output:p.union([BF,VF]),alias:{account:`a`,header:`H`,rpcUrl:`r`},async run(e){if(e.options.all&&e.args.channelId)return e.error({code:`INVALID_SESSION_CLOSE`,message:`Specify a channel ID or --all, not both.`,exitCode:2});if(!e.options.all&&!e.args.channelId)return e.error({code:`INVALID_SESSION_CLOSE`,message:`Specify a channel ID or --all.`,exitCode:2});if(e.options.all&&!e.options.yes)return e.error({code:`CONFIRMATION_REQUIRED`,message:`Closing all sessions requires --yes.`,exitCode:2});if(e.options.all&&(e.options.header||e.options.rpcUrl||e.options.url))return e.error({code:`INVALID_SESSION_CLOSE`,message:`--header, --rpc-url, and --url only apply to a single session.`,exitCode:2});let t=nF();async function n(e,n={}){let r=await t.get(e);if(!r)throw new I({code:`SESSION_NOT_FOUND`,message:`Session ${e} was not found.`,exitCode:2});let i=tF(r.channel),a=await t.acquire(i);try{let r=await t.get(e);if(!r)throw new I({code:`SESSION_NOT_FOUND`,message:`Session ${e} was not found.`,exitCode:2});let a=await qF(r,n.account),o=await JF(r.channel.chainId,n);if(vj({...r.channel.descriptor,escrow:r.channel.escrow,chainId:r.channel.chainId}).toLowerCase()!==r.channel.channelId.toLowerCase())throw new I({code:`SESSION_STATE_INVALID`,message:`Stored descriptor does not derive the session channel ID.`,exitCode:65});if((await lM(o,r.channel.channelId,r.channel.escrow)).deposit===0n)return await t.remove(r.channel.channelId),{channelId:r.channel.channelId,status:`already-closed`,spent:r.spent.toString()};let s=fF(n.resourceUrl??r.endpoint),c={...a.source===`keychain`&&{name:a.accountName},address:a.account.address},l=(e=r.challenge)=>({status:`closing`,account:c,endpoint:s,challenge:e,...r.receipt&&{receipt:r.receipt},spent:r.spent,units:r.units}),u=await t.upsert({...l(),channel:r.channel}),d=WF(n.headers),f=u.challenge,p=await WP({channel:u.channel,challenge:u.challenge,fetch:async(e,t)=>globalThis.fetch(e,{...t,headers:{...d,...Aw(t?.headers)}}),input:s,spent:u.spent,async onChallenge(e){f=e,await t.upsert({...l(e),channel:u.channel})},manager:{account:a.account,client:o,channelStore:rF(t,{scope:i,selection:u.channel.channelId,context:()=>l(f)})}});return await t.remove(u.channel.channelId),{channelId:u.channel.channelId,status:`closed`,spent:p.receipt.spent,txHash:p.receipt.txHash}}finally{await a.release()}}try{if(e.options.all){let r=(await t.list()).filter(t=>(!e.options.account||t.account.name===e.options.account)&&(!e.options.network||t.channel.chainId===HF(e.options.network))),i=[],a=[];for(let t of r)try{i.push(await n(t.channel.channelId,{account:e.options.account,network:e.options.network}))}catch(e){a.push({channelId:t.channel.channelId,message:e instanceof Error?e.message:String(e)})}let o={closed:i,failed:a};if(a.length>0){for(let e of a)process.stderr.write(`${e.channelId}: ${e.message}\n`);process.exitCode=1}if(e.format===`json`&&e.formatExplicit)return e.ok(o);for(let e of i)console.log(`${e.channelId} ${e.status} ${e.spent}`);for(let e of a)console.log(`${e.channelId} failed ${e.message}`);return}let r=await n(e.args.channelId,{account:e.options.account,headers:e.options.header,network:e.options.network,resourceUrl:e.options.url,rpcUrl:e.options.rpcUrl});if(e.format===`json`&&e.formatExplicit)return e.ok(r);console.log(`${r.channelId} ${r.status} ${r.spent}`),r.txHash&&console.log(` transaction ${r.txHash}`);return}catch(e){return KF(e,`SESSION_CLOSE_FAILED`)}}});function XF(e){console.log(e.channelId),console.log(` status ${e.status}`),console.log(` cumulative amount ${e.cumulativeAmount}`),console.log(` confirmed spend ${e.confirmedSpend}`),console.log(` deposit ${e.deposit}`),console.log(` chain ${e.chainId}`),console.log(` payer ${e.payer}`),console.log(` payee ${e.payee}`),console.log(` token ${e.token}`),console.log(` resource ${e.resourceUrl}`)}Ox(),YM(),aN(),hN(),UE(),ck(),JO();function ZF(e,t){if(t&&e!==`auto`&&t.toLowerCase()!==e.toLowerCase())throw new I({code:`SESSION_SELECTION_CONFLICT`,message:`--session and -M channel= select different sessions.`,exitCode:2});let n=t??e;if(n===`auto`||n===`new`)return n;if(/^0x[0-9a-fA-F]{64}$/.test(n))return n.toLowerCase();throw new I({code:`INVALID_SESSION`,message:`Session must be auto, new, or a 32-byte channel ID.`,exitCode:2})}function QF(e){let t=e.allowCustomEscrow;if(t!==void 0){if(t===`true`)return!0;if(t===`false`)return!1;throw new I({code:`INVALID_ALLOW_CUSTOM_ESCROW`,message:`allowCustomEscrow must be true or false.`,exitCode:2})}}function $F(e,t,n,r){if(t.deposit!==void 0)return t.deposit;let i=e.request.suggestedDeposit;return typeof i==`string`?ce(BigInt(i),r):n?`10`:void 0}function eI(e,t){if(!e)return;if(e.challengeId!==t.challenge.id)throw Error(`Session receipt challenge does not match the paid request.`);if(e.channelId.toLowerCase()!==t.channelId.toLowerCase())throw Error(`Session receipt channel does not match the selected channel.`);let n=BigInt(e.acceptedCumulative),r=BigInt(e.spent);if(n>t.cumulative)throw Error(`Session receipt exceeds the local cumulative authorization.`);if(r>n)throw Error(`Session receipt spend exceeds its accepted authorization.`);return e}function tI(e,t){return e.channel.channelId.toLowerCase()===t.toLowerCase()}function nI(e){if(e.trim()!==`[DONE]`){if(e.length===0){process.stdout.write(`
243
- `);return}try{let t=JSON.parse(e);process.stdout.write(t.token??t.choices?.[0]?.delta?.content??e)}catch{process.stdout.write(e)}}}async function rI(e){let{options:t}=e,n=await ik(t.account),r=PO(t.rpcUrl,{network:t.network}),i=await IO({network:t.network,rpcUrl:r}),a=j({chain:i,transport:ue(r)}),o=QF(e.methodOptions),s=await DM({allowCustomEscrow:o,challenge:e.challenge,getClient:async()=>a});if(s.chainId!==i.id)throw new I({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${s.chainId}, but RPC is chainId ${i.id}.`,exitCode:2});let{decimals:c}=await BO(a,s.token,n.account.address,{requireDecimals:!0}),l={payer:n.account.address,payee:s.payee,token:s.token,escrow:s.escrow,chainId:s.chainId},u=ZF(t.session,e.methodOptions.channel),d=e.registry??nF(),f=await d.acquire(l).catch(e=>{throw e instanceof KP?new I({code:e.code,message:e.message,exitCode:e.exitCode,cause:e}):e});try{let r=u===`auto`?await d.getPreferred(l):u===`new`?void 0:u,s=r?await d.get(r):void 0;if(r&&!s)throw new I({code:`SESSION_NOT_FOUND`,message:`Session ${r} was not found.`,exitCode:2});if(s&&u!==`auto`&&(s.status!==`open`||!s.channel.opened||eF(tF(s.channel))!==eF(l)||!NM(n.account,s.channel.descriptor)))throw new I({code:`SESSION_MISMATCH`,message:`Session ${s.channel.channelId} cannot be used for this account and challenge.`,exitCode:2});let f=s?.status===`open`&&s.channel.opened?s:void 0,p=f?`open`:`opening`,m=e.challenge,h=f?.receipt,g=f?.spent??0n,_=f?.units??0,v=fF(e.endpoint),y={...n.source===`keychain`&&{name:n.accountName},address:n.account.address},b=rF(d,{scope:l,selection:u,context:()=>({status:p,account:y,endpoint:v,challenge:m,...h&&{receipt:h},spent:g,units:_}),onNewChannel(){p=`opening`,h=void 0,g=0n,_=0}}),{signal:x,...S}=e.init,C={...S,...x&&{signal:x},onReceipt(e){h=e,g=g>BigInt(e.spent)?g:BigInt(e.spent),_=Math.max(_,e.units??0)}};if(e.challengeResponse.status!==402||e.challengeResponse.bodyUsed)throw Error(`Session manager requires an unconsumed 402 challenge response.`);let w=!0,T=mN({account:n.account,allowCustomEscrow:o,bootstrap:!1,client:a,channelStore:b,credentialContext:e.credentialContext,decimals:c,maxDeposit:$F(e.challenge,e.methodOptions,zO(i),c),fetch:async(t,n)=>w?(w=!1,e.challengeResponse):e.fetch(t,n)});f&&rN(T).rehydrate({channel:f.channel,challenge:e.challenge,input:e.fetchInput,spent:f.spent});let{onReceipt:ee,...E}=C,D=await T.fetch(e.fetchInput,E);if(t.fail&&D.status>=400)throw new I({code:`HTTP_ERROR`,message:`HTTP error ${D.status}`,exitCode:22});if(D.status===402)throw new I({code:`PAYMENT_REJECTED`,message:`Payment rejected.`,exitCode:75});CO(D,{include:!1,verbose:t.include?Math.max(t.verbose,2):t.verbose,silent:t.silent}),m=D.challenge??e.challenge;let O=T.channelId;if(!O)throw Error(`Session manager did not select a channel.`);if(h=eI(D.receipt,{challenge:m,channelId:O,cumulative:T.cumulative})??h,NE(D)){let t=rN(T).consumeSseResponse(e.fetchInput,D,{onReceipt:ee,signal:e.init.signal??void 0});for await(let e of t)nI(e)}else process.stdout.write(Buffer.from(await D.arrayBuffer()));let k=await d.get(O);if(!k||!tI(k,O))throw Error(`Session ${O} was not persisted.`);if(h){let e=eI(h,{challenge:m,channelId:O,cumulative:T.cumulative});if(!e)throw Error(`Session receipt validation failed.`);h=e,g=g>BigInt(e.spent)?g:BigInt(e.spent),_=Math.max(_,e.units??0),p=`open`}await d.upsert({status:p,channel:k.channel,account:y,endpoint:v,challenge:m,...h&&{receipt:h},spent:g,units:_}),t.silent||(e.info(`Session retained ${O}\n`),e.info(`Close with: mppx sessions close ${O}\n`))}finally{await f.release()}}JO();function Q(e,t){return t?{label:e,detail:t,severity:`pass`}:{label:e,severity:`pass`}}function $(e,t,n){let r={label:e,severity:`fail`};return t&&(r.detail=t),n&&(r.hint=n),r}function iI(e,t,n){let r={label:e,severity:`warn`};return t&&(r.detail=t),n&&(r.hint=n),r}function aI(e,t,n){let r=t?{label:e,detail:t,severity:`skip`}:{label:e,severity:`skip`};return n&&(r.hint=n),r}const oI={pass:X.green(`✓`),fail:X.red(`✗`),warn:X.yellow(`⚠`),suggested:X.cyan(`◇`),skip:X.dim(`○`)};function sI(e){let t=oI[e.severity],n=e.detail?`${e.label} (${e.detail})`:e.label;console.log(` ${t} ${n}`),e.hint&&e.severity!==`pass`&&console.log(X.dim(` → ${e.hint}`))}function cI(e){console.log(`\n${X.bold(e)}`)}function lI(e,t){for(let n of e)sI(n),n.severity===`pass`?t.passed++:n.severity===`fail`?t.failed++:n.severity===`warn`?t.warnings++:n.severity===`suggested`?t.suggested++:n.severity===`skip`&&t.skipped++}async function uI(e,t,n=15e3){let r=new AbortController,i=setTimeout(()=>r.abort(),n);try{return await fetch(e,{...t,redirect:`error`,signal:r.signal})}finally{clearTimeout(i)}}function dI(e){return e<1024?`${e}B`:e<1048576?`${(e/1024).toFixed(1)}KB`:`${(e/1048576).toFixed(1)}MB`}const fI=new Set([`get`,`post`,`put`,`patch`,`delete`,`head`,`options`,`trace`]);function pI(e){return typeof e==`string`&&/^0x[0-9a-fA-F]{40}$/.test(e)}function mI(e){return typeof e==`string`&&/^(0|[1-9][0-9]*)$/.test(e)}function hI(e){let t=e.indexOf(`:`);if(t<1)return null;let n=e.slice(0,t).toLowerCase();if(!fI.has(n))return null;let r=e.slice(t+1);if(!r)return null;let i=r.startsWith(`/`)?r:`/`+r;return{method:n.toUpperCase(),path:i}}function gI(e,t){if(e){try{let n=JSON.parse(e);if(n&&typeof n==`object`&&!Array.isArray(n)){let e=Object.keys(n);if(e.length>0&&e.every(e=>e.startsWith(`/`))){let e=n[t];return e===void 0?void 0:typeof e==`string`?e:JSON.stringify(e)}}}catch{}return e}}function _I(e){if(!e)return{};let t={};for(let n of e){let e=n.indexOf(`:`);e>0&&(t[n.slice(0,e).trim().toLowerCase()]=n.slice(e+1).trim())}return t}async function vI(e){let t=new URL(`openapi.json`,e.replace(/\/?$/,`/`)).href;try{let e=await uI(t,{});if(!e.ok)return{error:`HTTP ${e.status}`};let n=await e.text();return{doc:JSON.parse(n),raw:n}}catch(e){return e instanceof DOMException&&e.name===`AbortError`?{error:`Request timed out after 15s`}:e instanceof SyntaxError?{error:`Invalid JSON`}:{error:e.message}}}async function yI(e){let t=new URL(`/llms.txt`,e).href,n=`llms.txt found and nonempty`;try{let e=await uI(t,{});if(!e.ok)throw Error(`HTTP ${e.status}`);let r=(await e.text()).trim();if(!r)throw Error(`Empty document`);let i=e.headers.get(`content-type`)?.split(`;`)[0]?.trim().toLowerCase();if(i&&!i.startsWith(`text/`)||i===`text/html`||/^<(?:!doctype html|html|head|body)\b/i.test(r))throw Error(`Expected text documentation, received non-text or HTML content`);return Q(n,t)}catch(e){return{label:n,detail:`${t}: ${e.message}`,severity:`suggested`,hint:`Serve nonempty text documentation at /llms.txt.`}}}function bI(e){let t=[],n=[],r=e.paths;if(!r)return[];for(let[e,i]of Object.entries(r)){let r=CI(i.parameters);for(let[a,o]of Object.entries(i)){if(!fI.has(a)||!o||typeof o!=`object`||Array.isArray(o))continue;let i=o,s=wI(r,CI(i.parameters)),c=s.length>0?s:void 0;if(i[`x-payment-info`]){let n=i[`x-payment-info`];t.push({method:a.toUpperCase(),path:e,amount:n.amount,parameters:c})}else{let t=i.responses;t&&`402`in t&&n.push({method:a.toUpperCase(),path:e,parameters:c})}}}return t.length>0?t:n}function xI(e,t){let n=e.paths;if(!n)return;let r=n[t.path];if(!r)return;let i=r[t.method.toLowerCase()];if(!i?.requestBody)return;let a=i.requestBody.content?.[`application/json`];if(!a)return;if(a.example)return JSON.stringify(a.example);if(a.examples&&typeof a.examples==`object`){let e=Object.values(a.examples)[0];if(e?.value)return JSON.stringify(e.value)}let o=a.schema,s=new Set;if(o=EI(o,e,s),!o||o.type!==`object`)return;let c=DI(o,e,s);if(c&&typeof c==`object`&&Object.keys(c).length>0)return JSON.stringify(c)}function SI(e,t,n){if(!t.path.startsWith(`/`)||t.path.startsWith(`//`)||t.path.includes(`\\`))throw Error(`OpenAPI path must be an origin-relative path: ${t.path}`);let r=t.path;t.parameters&&(r=TI(r,t.parameters));let i=r.startsWith(`/`)?r.slice(1):r,a=new URL(e.replace(/\/?$/,`/`)),o=new URL(i,a);if(o.origin!==a.origin)throw Error(`OpenAPI path must be an origin-relative path: ${t.path}`);let s=o.href;if(n){let e=new URL(s);for(let t of n){let[n,...r]=t.split(`=`);n&&e.searchParams.set(n,r.join(`=`))}s=e.href}return s}function CI(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!=`object`)continue;let e=n;e.in===`path`&&typeof e.name==`string`&&t.push(e.schema&&typeof e.schema==`object`?{name:e.name,in:`path`,schema:e.schema,example:e.example}:{name:e.name,in:`path`,example:e.example})}return t}function wI(e,t){let n=[...e];for(let e of t){let t=n.findIndex(t=>t.name===e.name);t>=0?n[t]=e:n.push(e)}return n}function TI(e,t){return e.replace(/\{([^}]+)\}/g,(e,n)=>{let r=t.find(e=>e.name===n&&e.in===`path`);if(!r)return e;let i=r.example??r.schema?.example??r.schema?.default;return i===void 0?e:encodeURIComponent(String(i))})}function EI(e,t,n){if(!e||typeof e.$ref!=`string`)return e;if(n?.has(e.$ref))return;let r=e.$ref.replace(/^#\//,``).split(`/`),i=t;for(let e of r)if(i&&typeof i==`object`)i=i[e];else return;return i}function DI(e,t,n){let r=EI(e,t,n)??e;if(r.const!==void 0)return r.const;if(r.example!==void 0)return r.example;if(r.default!==void 0)return r.default;switch(r.type){case`string`:return r.enum&&Array.isArray(r.enum)?r.enum[0]:r.format===`email`?`test@example.com`:r.format===`uuid`?`00000000-0000-0000-0000-000000000000`:r.format===`uri`||r.format===`url`?`https://example.com`:r.format===`date`?`2026-01-01`:r.pattern===`^\\d{5}(?:-\\d{4})?$`?`10001`:r.pattern===`^[A-Z]{2}$`?`US`:`test`;case`number`:case`integer`:return r.minimum??1;case`boolean`:return!0;case`array`:return[];case`object`:{let e=r.properties;if(!e)return{};let i=r.required||[],a={};for(let r of i){let i=e[r];i&&(a[r]=DI(i,t,n))}return a}default:return null}}_S(),Fx(),iw(),JO();const OI=Object.values(Ve);function kI(e){let t=e.request.methodDetails;return typeof t?.chainId==`number`&&OI.find(e=>e.id===t.chainId)?.testnet===!0}async function AI(e,t,n,r){let i=[],a;try{a=SI(e,t,r?.query)}catch(e){return i.push($(`Request URL valid`,e.message)),{results:i}}let o=_I(r?.extraHeaders),s;r?.body&&!r.bodyIsAutogenerated&&(s=r.body,o[`content-type`]||=`application/json`);let c;try{let e={method:t.method};Object.keys(o).length>0&&(e.headers=o),s&&(e.body=s),c=await uI(a,e)}catch(e){return i.push($(`Request failed`,e.message)),{results:i}}if(!s&&(c.status===400||c.status===422)){let e=r?.body??(r?.discoveryDoc?xI(r.discoveryDoc,t):void 0);if(e){n&&console.log(X.dim(` Retrying with body: ${e}`)),s=e,o[`content-type`]=`application/json`;try{c=await uI(a,{method:t.method,headers:o,body:s})}catch(e){return i.push($(`Request failed`,e.message)),{results:i}}}}if(c.status!==402)return c.status===200?i.push(aI(`Returns 402 without credentials`,`Got 200 (endpoint may not require payment in all cases)`)):c.status===401||c.status===403?i.push(aI(`Returns 402 without credentials`,`Got ${c.status} (endpoint requires auth before payment gate)`)):i.push($(`Returns 402 without credentials`,`Got ${c.status} instead`,c.status===400||c.status===422?`Server requires a valid request body before returning 402. Add a requestBody schema with examples to your OpenAPI doc, or use --body.`:`Endpoints that require payment must return HTTP 402 with a WWW-Authenticate: Payment header when no valid credential is provided.`)),{results:i};i.push(Q(`Returns 402 without credentials`));let l=c.headers.get(q.wwwAuthenticate),u=VI(c);if(!l)return u.length>0?(i.push(aI(`Not an MPP endpoint`,`No WWW-Authenticate header — x402 protocol detected`)),i.push(...u)):i.push(aI(`Not an MPP endpoint`,`No WWW-Authenticate header (may be x402 or other protocol)`)),{results:i};if(u.length>0&&i.push(...u),!l.startsWith(`${Ax.payment} `))return i.push(aI(`Not an MPP endpoint`,`WWW-Authenticate scheme is not Payment`)),{results:i};i.push(Q(`WWW-Authenticate header present`,`Payment scheme`));let d;try{d=cS(c)}catch(e){let t=e.message;i.push($(`Challenge parseable`,t,`The Payment challenge must include a request="<base64url>" parameter containing JSON-encoded payment details.`));let n=l.slice(l.indexOf(` `)+1);return i.push(iI(`Received`,n.length>200?n.slice(0,200)+`...`:n)),{results:i}}if(d.length===0)return i.push($(`Challenge parseable`,`No Payment challenges found in header`)),{results:i};let f=d.map(e=>`${e.method}/${e.intent}`).join(`, `);i.push(Q(`Challenge parseable`,d.length===1?f:`${d.length} methods: ${f}`));let p=new URL(e).hostname;jI(d,i),MI(d,i),NI(d,i),PI(d,p,i);let m=d.length>1;for(let e of d){let t=e.request;FI(e,t,i,m)}if(n)for(let e of d)console.log(X.dim(` Challenge (${e.method}/${e.intent}): ${JSON.stringify(e,null,2)}`));return{results:i,resolvedBody:s,challenges:d}}function jI(e,t){let n=e.filter(e=>!e.id);n.length===0?t.push(Q(`Challenge has id`)):t.push($(`Challenge has id`,`${n.length} missing`,`Every challenge must include a unique id field.`))}function MI(e,t){let n=e.filter(e=>!e.realm);n.length===0?t.push(Q(`Challenge has realm`)):t.push($(`Challenge has realm`,`${n.length} missing`,`Set realm to your server's hostname.`))}function NI(e,t){let n=new Date;for(let r of e){if(!r.expires){t.push(iI(`Challenge has expiration`,`missing expires field`,`Add an expires field (ISO 8601) to prevent replay attacks.`));return}if(new Date(r.expires)<=n){t.push($(`Challenge expires in the future`,`Expired at ${r.expires}`,`The expires timestamp must be in the future.`));return}}let r=Math.min(...e.map(e=>new Date(e.expires).getTime()-n.getTime()));t.push(Q(`Challenge expires in the future`,`${Math.round(r/6e4)}m from now`))}function PI(e,t,n){let r=e=>e.toLowerCase().replace(/\.$/,``),i=r(t),a=[...new Set(e.map(e=>e.realm??``))].filter(e=>{let t=r(e);return!t||t!==i&&!i.endsWith(`.${t}`)});a.length>0?n.push($(`Realm matches server hostname`,`realm="${a[0]}" vs host="${t}"`,`Set the realm to your production hostname (or base domain) in the challenge.`)):n.push(Q(`Realm matches server hostname`))}function FI(e,t,n,r){let i=r?`[${e.method}] `:``;e.method===jx.tempo?II(t,i,n,e):e.method===jx.stripe?LI(t,i,n):e.method===jx.evm&&RI(e,t,i,n)}function II(e,t,n,r){let i=e.methodDetails,a=Array.isArray(i?.splits)&&i.splits.length>0;if(pI(e.recipient)?n.push(Q(`${t}Valid recipient address`)):e.recipient===void 0&&a?n.push(Q(`${t}Uses splits (no single recipient)`)):e.recipient===void 0?n.push($(`${t}Valid recipient address`,`Missing recipient (and no splits defined)`,`Set request.recipient to a valid 0x address, or use methodDetails.splits for multiple recipients.`)):n.push($(`${t}Valid recipient address`,`Got: ${String(e.recipient)}`,`Set request.recipient to a valid 0x-prefixed 40-hex-char address.`)),pI(e.currency)){let e=kI(r)?`testnet`:`mainnet`;n.push(Q(`${t}Valid currency address`,e))}else n.push($(`${t}Valid currency address`,`Got: ${String(e.currency)}`,`Set request.currency to a valid token address.`));zI(e,t,n,`token's smallest unit (e.g. "10000" = $0.01 for 6-decimal tokens)`)}function LI(e,t,n){zI(e,t,n,`currency's smallest unit (e.g. "100" = $1.00 for USD)`);let r=e.currency;typeof r==`string`&&/^[a-z]{3}$/i.test(r)?n.push(Q(`${t}Valid currency code`,r.toUpperCase())):n.push($(`${t}Valid currency code`,r?`Got: ${r}`:`missing`,`Must be a three-letter ISO currency code (e.g. "usd").`));let i=e.methodDetails,a=i?.networkId;a?n.push(Q(`${t}Has networkId`,a.slice(0,20))):n.push($(`${t}Has networkId`,`Missing methodDetails.networkId`,`Set methodDetails.networkId to your Stripe Business Network profile ID.`));let o=i?.paymentMethodTypes;Array.isArray(o)&&o.length>0?n.push(Q(`${t}Has paymentMethodTypes`,o.join(`, `))):n.push($(`${t}Has paymentMethodTypes`,`Missing or empty`,`Set methodDetails.paymentMethodTypes to an array (e.g. ["card"]).`))}function RI(e,t,n,r){if(pI(t.recipient)?r.push(Q(`${n}Valid recipient address`)):r.push($(`${n}Valid recipient address`,`Got: ${String(t.recipient)}`,`Set request.recipient to a valid 0x-prefixed Ethereum address.`)),pI(t.currency)){let t=kI(e)?`testnet`:`mainnet`;r.push(Q(`${n}Valid currency address`,t))}else r.push($(`${n}Valid currency address`,`Got: ${String(t.currency)}`,`Set request.currency to a valid ERC-20 token contract address.`));zI(t,n,r,`token's smallest unit`);let i=t.methodDetails?.chainId;typeof i==`number`&&i>0?r.push(Q(`${n}Has chainId`,String(i))):r.push($(`${n}Has chainId`,`Missing methodDetails.chainId`,`Set methodDetails.chainId to the EVM chain ID.`))}function zI(e,t,n,r){mI(e.amount)?n.push(Q(`${t}Amount is valid integer string`)):e.amount===void 0||e.amount===null?n.push($(`${t}Amount is valid integer string`,`Missing amount`,`Set request.amount to a string of digits in the ${r}.`)):n.push($(`${t}Amount is valid integer string`,`Got: ${String(e.amount)}`,`request.amount must be a string of digits (no decimals, no prefix).`))}async function BI(e,t,n){let r=[],i=SI(e,t,n?.query),a={[q.authorization]:`${Ax.payment} dGhpcyBpcyBnYXJiYWdl`},o;n?.body&&(o=n.body,a[`content-type`]=`application/json`);try{let e=await uI(i,{method:t.method,headers:a,body:o??null});e.status===402?(r.push(Q(`Malformed credential returns 402`,`not 500`)),e.headers.get(q.wwwAuthenticate)?.startsWith(`${Ax.payment} `)?r.push(Q(`Error response includes fresh challenge`)):r.push(iI(`Error response includes fresh challenge`,`No WWW-Authenticate header`,`When rejecting an invalid credential, respond with 402 and include a fresh WWW-Authenticate: Payment challenge so the client can retry.`))):e.status>=500?r.push($(`Malformed credential returns 402`,`Got ${e.status} (server error)`,`When the Authorization header contains an invalid credential, respond with 402 (not 500). Catch credential validation errors and return a fresh challenge.`)):r.push(iI(`Malformed credential returns 402`,`Got ${e.status}`,`When the Authorization header contains an invalid Payment credential, respond with 402 and a fresh WWW-Authenticate challenge. Returning ${e.status} prevents the client from retrying with a valid payment.`))}catch(e){r.push($(`Error handling test`,e.message))}return r}function VI(e){let t=[],n=e.headers.get(`payment-required`)??e.headers.get(`x-payment-required`);if(!n)return t;let r=e.headers.get(`payment-required`)?`PAYMENT-REQUIRED`:`X-Payment-Required`;try{let e=ZC(n);t.push(Q(`x402 payment challenge`,`${r} with valid x402 v${e.x402Version} payload`))}catch{t.push(iI(`x402 payment challenge`,`${r} header present but failed schema validation`,`Ensure the PAYMENT-REQUIRED header contains a valid base64-encoded JSON payload matching the x402 schema.`))}return t}const HI=[`No discovery document found, endpoints could not be automatically found.`,`MPP servers must serve an OpenAPI document at /openapi.json with x-payment-info extensions.`,`The MPP SDKs can automatically expose this endpoint. See https://mpp.dev/sdk.`,``,`To test a specific endpoint: mppx validate <url> --endpoint POST:/your/path`].join(`
244
- `);Zx();const UI={fundingCurrency:J.optional(J.string()),method:J.string(),reference:J.string(),externalId:J.optional(J.string()),subscriptionId:J.optional(J.string()),status:J.literal(`success`),timestamp:Hx()};J.object(UI);const WI=J.looseObject(UI);function GI(e){let t=k.toString(e);return KI(JSON.parse(t))}function KI(e){return WI.parse(e)}_S(),Fx(),qN(),bO(),mO(),ck(),JO();async function qI(e,t,n){try{n||console.log(X.dim(` Provisioning testnet wallet and funding via faucet...`));let t=ge(),r=ve(t),i=j({chain:be,transport:ue()});if(ND(e)){let{chainId:t,operator:n}=e.request.methodDetails??{};if(t===be.id&&typeof n==`string`&&de(n)&&n!==he){let e=await Ie.faucet.fund(i,{account:n});await Promise.all(e.map(e=>Ne(i,{hash:e})))}}let a=await Ie.faucet.fund(i,{account:r});await Promise.all(a.map(e=>Ne(i,{hash:e}))),n||console.log(X.dim(` Using wallet: ${r.address}`));let o=e.request.currency;if(typeof o==`string`)for(let e=0;e<10;e++){let e=await Ie.token.getBalance(i,{account:r.address,token:o}).catch(()=>void 0);if(e&&e.amount>0n)break;await new Promise(e=>setTimeout(e,500))}return{methods:[...WN({account:r})]}}catch(e){t&&console.log(X.dim(` Provisioning failed: ${e.message}`));return}}async function JI(){let e=tk(),{isTempoAccount:t}=await Promise.resolve().then(()=>(JO(),xO)),{resolveTempoAccount:n}=await Promise.resolve().then(()=>(DP(),JN));if(t(e)){let t=n(e);if(t)return t.wallet_address}try{return(await ak()).address}catch{return}}function YI(e){try{let{execSync:t}=m,n=t(`stripe config --list`,{encoding:`utf8`,timeout:5e3}).match(/test_mode_api_key\s*=\s*'([^']+)'/);if(n?.[1])return e&&console.log(X.dim(` Using Stripe test key from stripe CLI`)),n[1]}catch{}}async function XI(e,t,n){let r=j({chain:e,transport:ue()}),[i,a,o]=await Promise.all([n?Oe(r,{address:t,abi:se,functionName:`balanceOf`,args:[n]}):0n,Oe(r,{address:t,abi:se,functionName:`decimals`}),Oe(r,{address:t,abi:se,functionName:`symbol`}).catch(()=>void 0)]);return{balance:i,decimals:a,symbol:o??void 0}}function ZI(e){return Object.values(Ve).find(t=>t.id===e)}function QI(e,t){return`$${(Number(e)/10**t).toFixed(2)}`}function $I(e){switch(e.method){case jx.evm:return`no EVM payment plugin yet`;case`solana`:return`no Solana payment plugin yet`;default:return`no plugin for ${e.method}/${e.intent}`}}async function eL(e,t,n,r){let i=[],a=SI(e,t,r.query),o=_I(r.extraHeaders),s;r.body&&(s=r.body,o[`content-type`]=`application/json`);let c;try{c=await uI(a,{method:t.method,headers:o,body:s??null})}catch(e){return i.push($(`Payment: fetch challenge`,e.message)),i}if(c.status!==402)return i.push(aI(`Payment: skipped`,`Endpoint returned ${c.status}`)),i;let l;try{l=cS(c)}catch(e){return i.push($(`Payment: parse challenge`,e.message)),i}if(l.length===0)return i.push($(`Payment: parse challenge`,`No Payment challenges in response`)),i;let u=[];PI(l,new URL(a).hostname,u);let d=u.filter(e=>e.severity===`fail`);if(d.length>0)return i.push(...d),r.onResults?.(d),i;let f=await zP().catch(()=>void 0),p=l.find(e=>{if(e.method!==jx.tempo||LP(f?.config)?.some(t=>t.name===e.method&&t.intent===e.intent))return!1;let t=e.request.methodDetails;return typeof t?.chainId==`number`&&t.chainId!==hO.mainnet});if(p){let e=await qI(p,n,r.silent);if(e)try{await aL(i,await ST({methods:e.methods,polyfill:!1,async onChallenge(e,{createCredential:t}){VP(p,e);let n=await t(await NP(e,f?.config.extensions));return i.push(Q(`Payment: submitted`,`ephemeral testnet wallet`)),n},fetch:(e,t)=>uI(e,t??{},3e4)}).fetch(a,{method:t.method,headers:o,body:s??null}),n,be)}catch(e){i.push($(`Payment: create credential`,e.message))}else i.push($(`Payment: auto-provision wallet`,`Failed to create and fund testnet wallet`));r.onResults?.(i)}let m=r.interactive,h=process.env.MPPX_STRIPE_SECRET_KEY??YI(n),g=h?.startsWith(`sk_test_`)||h?.startsWith(`rk_test_`),_=new Set([jx.tempo,jx.evm,jx.stripe]);for(let e of l){if(e===p||!_.has(e.method))continue;r.silent||console.log(``);let c=i.length,l=()=>{r.onResults&&i.length>c&&r.onResults(i.slice(c))},u=`Payment [${e.method}]`;try{switch(e.method){case jx.tempo:case jx.evm:await tL(e,u,{results:i,url:a,endpoint:t,fetchHeaders:o,fetchBody:s,verbose:n,loaded:f,isInteractive:m,options:r});break;case jx.stripe:await nL(e,u,{results:i,url:a,endpoint:t,fetchHeaders:o,fetchBody:s,verbose:n,loaded:f,isInteractive:m,isStripeTestKey:g??!1,stripeKey:h,options:r})}}finally{l()}}return i}async function tL(e,t,n){let{results:r,url:i,endpoint:a,fetchHeaders:o,fetchBody:s,verbose:c,loaded:l,options:u}=n,d=e.request,f=d.methodDetails,p=mI(d.amount)?BigInt(d.amount):void 0,m=f?.decimals??d.decimals??6,h=d.currency,{plugin:g,method:_}=PP(e,l?.config);if(!g&&!_){r.push(aI(t,$I(e)));return}let v;if(!_){try{v=await JI()}catch{}if(!v){r.push(aI(t,`no wallet configured. Run "mppx account create" to create one.`));return}}let y;if(e.method===jx.tempo){let e=f?.chainId??(_?void 0:ye.id);e!==void 0&&(y=e===be.id?be:ZI(e))}else if(e.method===jx.evm){let e=f?.chainId;e&&(y=ZI(e))}if(p&&h&&!y){r.push(aI(t,`unable to resolve payment chain and verify token decimals`));return}let b;if(p&&h&&y)try{let n;if(e.method===jx.tempo){let e=await BO(j({chain:y,transport:ue()}),h,v??he,{requireDecimals:!0});n=e.balance,m=e.decimals,b=e.symbol}else{let e=await XI(y,h,v);n=e.balance,m=e.decimals,b=e.symbol}if(v&&n<p){let e=QI(p,m),i=QI(n,m),a=b??`tokens`;r.push(aI(t,`insufficient balance (have ${i}, need ${e} ${a} on ${y.name})`,`Fund wallet ${v} with at least ${e} ${a} on ${y.name}.`));return}}catch(e){c&&console.log(X.dim(` Balance check skipped: ${e.message}`)),r.push(aI(t,`unable to verify token balance and decimals from the payment chain`));return}let x=p?QI(p,m):`unknown amount`,S=b??(h?.length===3?h.toUpperCase():``),C=y?.name,w=`${x}${S?` ${S}`:``}${C?` on ${C}`:``}`;if(u.silent||console.log(X.dim(v?` Attempting payment with wallet ${v}`:` Attempting payment with configured method`)),!_&&y?.testnet)u.silent||console.log(X.dim(` Auto-approved: ${w} (testnet)`));else if(!u.yes&&!n.isInteractive){r.push(aI(t,`non-interactive mode, use --yes to approve`));return}else if(u.yes)u.silent||console.log(X.dim(` Auto-approved: ${w}`));else if(!await MO(` ${X.yellow(`Pay`)} ${w}. Continue?`,!1)){r.push(aI(t,`declined`));return}let T,ee,E;if(g)try{let t=await g.setup({challenge:e,options:{network:`mainnet`},methodOpts:{}});T=t.methods,ee=t.createCredential,E=t.credentialContext}catch(e){r.push(aI(t,e.message));return}else T=[_];if(_&&ND(e)){let n=!0,u=ST({methods:[_],polyfill:!1,async onChallenge(n,{createCredential:i}){let a=await NP(n,l?.config.extensions);VP(e,n);let o=await i(a);return r.push(Q(`${t}: submitted`)),o},fetch:async(t,r)=>n?(n=!1,new Response(null,{status:402,headers:{[q.wwwAuthenticate]:$x(e)}})):uI(t,r??{},3e4)});try{await aL(r,await u.fetch(i,{method:a.method,headers:o,body:s??null}),c,y)}catch(e){r.push($(t,e.message))}return}let D=await rL(e,T,ee,t,r,l?.config.extensions,E);D&&(g?.prepareCredentialRequest?.({challenge:e,credential:D,headers:o}),await iL(r,i,a,D,o,s,c,y,fS(e)))}async function nL(e,t,n){let{results:r,url:i,endpoint:a,fetchHeaders:o,fetchBody:s,verbose:c,loaded:l,options:u,stripeKey:d}=n,{plugin:f,method:p}=PP(e,l?.config);if(!f&&!p){r.push(aI(t,`no Stripe payment method available`));return}let m=!!(f&&!l?.config.plugins?.includes(f)&&n.isStripeTestKey),h=e.request,g=mI(h.amount)?BigInt(h.amount):void 0,_=h.decimals??2,v=h.currency,y=g?QI(g,_):`unknown amount`,b=v?.length===3?v.toUpperCase():``,x=`${y}${b?` ${b}`:``} via Stripe${m?` (testmode)`:``}`;if(m)u.silent||console.log(X.dim(` Attempting: ${x}`));else if(!u.yes&&!n.isInteractive){r.push(aI(t,`non-interactive mode, use --yes to approve`));return}else if(u.yes)u.silent||console.log(X.dim(` Auto-approved: ${x}`));else if(!await MO(` ${X.yellow(`Pay`)} ${x}. Continue?`,!1)){r.push(aI(t,`declined`));return}let S,C,w;if(f)try{let t={paymentMethod:`pm_card_visa`};d&&(t.secretKey=d);let n=await f.setup({challenge:e,options:{},methodOpts:t});S=n.methods,C=n.createCredential,w=n.credentialContext}catch(e){r.push(aI(t,e.message));return}else S=[p];let T=await rL(e,S,C,t,r,l?.config.extensions,w);if(T){if(f?.prepareCredentialRequest?.({challenge:e,credential:T,headers:o}),m){let n=await uI(i,{method:a.method,headers:{...o,[fS(e)]:T},body:s??null},3e4);n.status>=200&&n.status<300?r.push(Q(`${t}: successful`,`HTTP ${n.status}`)):r.push(aI(`${t}: server is in livemode`,void 0,`Run your server with a Stripe test key to automatically validate Stripe payments in testmode.`));return}await iL(r,i,a,T,o,s,c,void 0,fS(e))}}async function rL(e,t,n,r,i,a,o){let s=new Response(null,{status:402,headers:{[q.wwwAuthenticate]:$x(e)}});try{let c=await NP(e,a,o),l;return l=n?await n(s,c):await ST({methods:t,polyfill:!1}).createCredential(s,c),i.push(Q(`${r}: submitted`)),l}catch(e){let t=e.message;t.toLowerCase().includes(`insufficient`)?i.push(aI(r,`insufficient balance: ${t}`)):i.push($(r,t));return}}async function iL(e,t,n,r,i,a,o,s,c=q.authorization){let l;try{l=await uI(t,{method:n.method,headers:{...i,[c]:r},body:a??null},3e4)}catch(t){return e.push($(`Payment: send credential`,t.message)),e}return aL(e,l,o,s)}async function aL(e,t,n,r){if(t.status===402){let n=await t.text().catch(()=>``),r=`Payment rejected`;try{let e=JSON.parse(n);r=e.detail??e.title??r}catch{}return e.push($(`Payment: accepted`,r,`The server rejected a valid credential. Check that your payment verification logic accepts the credential format and that the payment was processed on-chain.`)),e}if(t.status>=400&&t.status<500)e.push(iI(`Payment: post-payment response`,`Got ${t.status}`,`Payment succeeded but the endpoint returned a client error. The endpoint likely requires request body parameters. Use --body to provide them.`));else if(t.status>=500)return e.push($(`Payment: server response`,`Got ${t.status}`,`Payment was accepted but the server errored while generating the response. Check server logs for the underlying error.`)),e;else e.push(Q(`Payment: successful`,`HTTP ${t.status}`));let i=t.headers.get(q.paymentReceipt);if(!i)e.push($(`Payment-Receipt header present`,void 0,`After accepting payment, include a Payment-Receipt header with a base64url-encoded JSON object containing: method, reference, status ("success"), and timestamp (ISO 8601).`));else{e.push(Q(`Payment-Receipt header present`));try{let t=GI(i);if(e.push(Q(`Receipt parseable`)),t.status===`success`?e.push(Q(`Receipt status is "success"`)):e.push($(`Receipt status is "success"`,`Got: ${t.status}`)),t.reference){let n=/^0x[0-9a-fA-F]{64}$/.test(t.reference),r=t.reference.startsWith(`pi_`);n||r?e.push(Q(`Receipt reference valid`,t.reference.slice(0,20)+`...`)):e.push(iI(`Receipt reference format`,t.reference.slice(0,40)))}else e.push(iI(`Receipt has reference`,`No reference field`));if(t.timestamp){let n=new Date(t.timestamp),r=Date.now()-n.getTime();r<6e4?e.push(Q(`Receipt timestamp recent`,`${Math.round(r/1e3)}s ago`)):e.push(iI(`Receipt timestamp recent`,`${Math.round(r/6e4)}m ago`))}n&&console.log(X.dim(` Receipt: ${JSON.stringify(t,null,2)}`))}catch(t){e.push($(`Receipt parseable`,t.message))}}let a=t.headers.get(`content-type`)??``,o=await t.text().catch(()=>``);if(o.length>0)e.push(Q(`Response body non-empty`,`${a.split(`;`)[0]}, ${dI(o.length)}`));else{let n=[...t.headers.entries()].filter(([e])=>!e.startsWith(`x-`)&&![`content-type`,`content-length`,`date`,`server`,`connection`,`keep-alive`,`cache-control`,`vary`,`access-control-allow-origin`,`payment-receipt`,`payment-session`,`payment-session-snapshot`].includes(e.toLowerCase()));n.length>0?e.push(iI(`Response body empty -- data may be in headers only`,n.map(([e])=>e).join(`, `))):e.push(iI(`Response body empty`))}if(a?e.push(Q(`Content-Type header set`,a.split(`;`)[0])):e.push(iI(`Content-Type header set`)),i)try{let t=GI(i);if(t.reference&&/^0x[0-9a-fA-F]{64}$/.test(t.reference)){let n=r?.blockExplorers?.default?.url;if(n){let r=n.includes(`tempo`)?`receipt`:`tx`;e.push(Q(`On-chain transaction`,`${n}/${r}/${t.reference}`))}}}catch{}return e}async function*oL(e){let t=e.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``),n=e.verbose??!1,r=await dL(t,e);yield{phase:`discovery`,discovery:r,results:r.checks};for(let i of r.endpoints){yield{phase:`endpoint`,endpoint:i};let a,o=!1;e.endpoint?a=e.body:(a=gI(e.body,i.path),!a&&r.doc&&(a=xI(r.doc,i),o=!!a));let{results:s,resolvedBody:c,challenges:l}=await AI(t,i,n,{body:a,bodyIsAutogenerated:o,query:e.query,extraHeaders:e.headers,discoveryDoc:r.doc??void 0}),u=c??a,d=s.some(e=>e.severity===`pass`&&e.label===`Challenge parseable`),f=!s.some(e=>e.severity===`fail`),p=(l??[]).filter(e=>e.method!==`stripe`).map(e=>e.request.methodDetails?.chainId).filter(e=>typeof e==`number`),m=p.some(uL),h=p.some(e=>!uL(e)),g=!d&&s.some(e=>e.label===`Not an MPP endpoint`),_=s.some(e=>e.severity===`pass`&&e.label===`WWW-Authenticate header present`),v=s.some(e=>e.severity===`fail`&&e.label===`Challenge parseable`);if(yield{phase:`challenge`,endpoint:i,results:s,isMpp:d,isTestnet:m,isMainnet:h,isNonMppPayment:g,isMalformedChallenge:!d&&_&&v,methods:l?.map(e=>e.method)??[]},d&&(yield{phase:`errorHandling`,endpoint:i,results:await BI(t,i,{body:u,query:e.query})},!e.skipPayment&&f)){let r=e.onPaymentResults,a=await eL(t,i,n,{body:u,query:e.query,extraHeaders:e.headers,yes:e.yes,silent:!r,interactive:e.interactive,...r&&{onResults:r}});yield{phase:`payment`,endpoint:i,results:a,succeeded:a.some(e=>e.severity===`pass`&&e.label===`Payment: successful`)}}}}async function sL(e){let t=e.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``),n,r=[],i,a=!1,o=!1;for await(let t of oL(e))switch(t.phase){case`discovery`:n=t.discovery;break;case`endpoint`:i={method:t.endpoint.method,path:t.endpoint.path,challenge:[],errorHandling:[],payment:[]},r.push(i);break;case`challenge`:i&&(i.challenge=t.results),t.isMpp&&(t.isTestnet&&(a=!0),t.isMainnet&&(o=!0));break;case`errorHandling`:i&&(i.errorHandling=t.results);break;case`payment`:i&&(i.payment=t.results)}let s={passed:0,failed:0,warnings:0,suggested:0,skipped:0};if(n)for(let e of n.checks)e.severity===`pass`?s.passed++:e.severity===`fail`?s.failed++:e.severity===`warn`?s.warnings++:e.severity===`suggested`?s.suggested++:e.severity===`skip`&&s.skipped++;for(let e of r)for(let t of[...e.challenge,...e.errorHandling,...e.payment])t.severity===`pass`?s.passed++:t.severity===`fail`?s.failed++:t.severity===`warn`?s.warnings++:t.severity===`suggested`?s.suggested++:t.severity===`skip`&&s.skipped++;if(!n)throw Error(`Discovery phase did not complete`);let c=cL(r,n,{sawTestnet:a,sawMainnet:o});return{url:t,discovery:n,endpoints:r,summary:s,suggestions:c}}function cL(e,t,n){let r=[],i=e.flatMap(e=>[...e.challenge,...e.payment]);t.found||r.push(HI);let a=n.sawMainnet,o=n.sawTestnet,s=i.some(e=>e.label.includes(`[stripe]`)&&e.label.includes(`livemode`));return a&&!o?r.push(`Validate your testnet server to test without real funds (Tempo wallets are automatically provisioned).`):o&&!a&&r.push(`Validate your mainnet server to confirm real payments work end-to-end.`),s&&r.push(`Validate your testmode Stripe server to test card payments end-to-end (auto-pays with test card).`),r}const lL=Object.values(Ve);function uL(e){return lL.find(t=>t.id===e)?.testnet===!0}async function dL(e,t){let n=[],r=[],i=null,a=!1,o=!1;n.push(await yI(e));let s=new URL(e).origin,c;t.discoveryPath?c=[new URL(t.discoveryPath,e+`/`).href.replace(/\/openapi\.json$/i,``)]:(c=[e,s,`${s}/api`],c=[...new Set(c)]);let l,u=[];for(let e of c)if(l=await vI(e),`error`in l)u.push(`${e}/openapi.json: ${l.error}`);else break;if(!l||`error`in l)n.push({label:`Document found`,detail:u.join(`; `),hint:`MPP servers must serve an OpenAPI document at /openapi.json with x-payment-info extensions.`,severity:`fail`});else{a=!0,n.push({label:`Document found and parseable`,severity:`pass`});let e=tE(l.doc),t=e.filter(e=>e.severity===`error`),r=e.filter(e=>e.severity===`warning`);if(t.length>0){n.push({label:`Valid OpenAPI structure`,detail:`${t.length} error(s)`,severity:`fail`});for(let e of t)n.push({label:e.message,detail:e.path,severity:`fail`})}else o=!0,n.push({label:`Valid OpenAPI structure`,severity:`pass`});for(let e of r)n.push({label:e.message,detail:e.path,severity:`warn`});i=l.doc}if(t.endpoint){let e=hI(t.endpoint);e&&r.push(e)}else if(i){r=bI(i);let e=BigInt(`999999999999999999`);r.sort((t,n)=>{let r=mI(t.amount)?BigInt(t.amount):e,i=mI(n.amount)?BigInt(n.amount):e;return r<i?-1:+(r>i)}),r.length>0?n.push({label:`Paid endpoints found`,detail:`${r.length} endpoint(s)`,severity:`pass`}):n.push({label:`Paid endpoints found`,detail:`No endpoints with x-payment-info`,severity:`warn`})}return{found:a,valid:o,endpoints:r,checks:n,doc:i}}Ox(),JO();const fL=cb(`validate`,{description:`Validate an MPP server implementation end-to-end`,args:p.object({url:p.string().describe(`Base URL of the MPP server to validate`)}),options:p.object({endpoint:p.string().optional().describe(`Endpoint to test (METHOD:path). Skips discovery.`),body:p.string().optional().describe(`Request body. With --endpoint, used directly. In discovery mode, JSON with / keys is a per-path mapping.`),query:p.array(p.string()).optional().describe(`Query parameter (key=value, repeatable)`),header:p.array(p.string()).optional().describe(`Request header (key:value, repeatable)`),verbose:p.number().default(0).meta({count:!0}).describe(`Verbosity level`),yes:p.boolean().default(!1).describe(`Auto-approve mainnet payments`),outputJson:p.boolean().default(!1).describe(`Output results as JSON (auto-enabled in known agent environments)`)}),alias:{endpoint:`e`,header:`H`,verbose:`v`,yes:`y`,outputJson:`j`},async run(e){if(e.options.outputJson||kO()){let t=await sL({url:e.args.url,endpoint:e.options.endpoint,body:e.options.body,query:e.options.query,headers:e.options.header,verbose:e.options.verbose>0,yes:e.options.yes,interactive:!1});console.log(JSON.stringify(t,null,2));let n=t.endpoints.length===0&&!e.options.endpoint;(t.summary.failed>0||!t.discovery.found||n)&&process.exit(1);return}let t=e.args.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``);console.log(`\n${X.bold(`mppx validate`)} ${X.dim(t)}\n`);let n={passed:0,failed:0,warnings:0,suggested:0,skipped:0},r=!1,i=!1,a=!1,o=!1,s=!1,c=!1,l=!1,u=0;for await(let t of oL({url:e.args.url,endpoint:e.options.endpoint,body:e.options.body,query:e.options.query,headers:e.options.header,verbose:e.options.verbose>0,yes:e.options.yes,interactive:!!process.stdin.isTTY,onPaymentResults:e=>lI(e,n)}))switch(t.phase){case`discovery`:if(cI(`Discovery (/openapi.json)`),lI(t.results,n),l=t.discovery.found,!l&&!e.options.endpoint){console.log(``);let[e,...t]=HI.split(`
245
- `);console.log(X.yellow(` ${e}`));for(let e of t)console.log(e?X.dim(` ${e}`):``);console.log(``),process.exit(1)}t.discovery.endpoints.length===0&&!e.options.endpoint&&l&&(console.log(X.dim(` Use --endpoint to specify endpoints manually.`)),console.log(``),process.exit(1));break;case`endpoint`:u++,cI(`${t.endpoint.method} ${t.endpoint.path}`);break;case`challenge`:console.log(X.dim(` Challenge`)),lI(t.results,n),t.isMpp&&(r=!0,t.isTestnet&&(o=!0),t.isMainnet&&(s=!0)),t.isNonMppPayment&&(i=!0),t.isMalformedChallenge&&(a=!0);break;case`errorHandling`:console.log(X.dim(` Error Handling`)),lI(t.results,n);break;case`payment`:t.succeeded&&(c=!0)}pL(n,{sawMppEndpoint:r,sawNonMppPaymentEndpoint:i,sawMalformedChallenge:a,sawTestnet:o,sawMainnet:s,paymentSucceeded:c},u)}});function pL(e,t,n){!t.sawMppEndpoint&&n>0&&(console.log(``),t.sawMalformedChallenge?(console.log(X.yellow(` Payment scheme detected but challenge format is invalid on ${n} endpoint(s).`)),console.log(X.dim(` The server uses WWW-Authenticate: Payment but the challenge parameters do not conform to MPP.`)),console.log(X.dim(` Fix: encode payment details as base64url JSON in a request="..." parameter. See errors above.`))):t.sawNonMppPaymentEndpoint?(console.log(X.yellow(` No MPP endpoints found. Tested ${n} endpoint(s) but none use WWW-Authenticate: Payment.`)),console.log(X.dim(` This server may use x402 or another payment protocol.`))):e.skipped>0&&e.failed===0?(console.log(X.yellow(` Could not reach payment gate on any endpoint (all returned 401/403/200).`)),console.log(X.dim(` The server may require authentication before payment. Try providing auth or use --endpoint with a public path.`))):(console.log(X.yellow(` No MPP endpoints found. Tested ${n} endpoint(s) but none use WWW-Authenticate: Payment.`)),console.log(X.dim(` This server may use x402 or another payment protocol.`))),console.log(``),process.exit(1)),console.log(``);let r=[];e.passed>0&&r.push(X.green(`${e.passed} passed`)),e.failed>0&&r.push(X.red(`${e.failed} failed`)),e.warnings>0&&r.push(X.yellow(`${e.warnings} warning(s)`)),e.suggested>0&&r.push(X.cyan(`${e.suggested} suggested`)),e.skipped>0&&r.push(X.yellow(`${e.skipped} skipped`)),console.log(`${X.bold(`Summary:`)} ${r.join(`, `)}`),t.paymentSucceeded&&t.sawTestnet&&!t.sawMainnet?(console.log(``),console.log(X.dim(` Tip: also validate your mainnet server to confirm real payments work end-to-end.`))):t.sawMainnet&&!t.sawTestnet&&(console.log(``),console.log(X.dim(` Tip: also validate your testnet server for free. This CLI automatically provisions and funds a testnet wallet for testing.`))),console.log(``),e.failed>0&&process.exit(1)}function mL(e){return gL(e)?e.offers:[e]}function hL(e){let{_canonicalRequest:t,intent:n,name:r}=e,i=t.methodDetails??{},a=_L(t.amount)??_L(i.amount)??null,o=_L(t.currency)??_L(i.currency),s=_L(e.description)??_L(t.description),c={amount:a,...o?{currency:o}:{},...s?{description:s}:{},intent:n,method:r},l=new Set([`amount`,`currency`,`description`,`methodDetails`]);for(let[e,n]of Object.entries(t))!l.has(e)&&n!==void 0&&(c[e]=n);return c}function gL(e){return`offers`in e&&!(`_canonicalRequest`in e)}function _L(e){return typeof e==`string`?e:void 0}var vL=F((()=>{})),yL=Qe({generate:()=>bL,generateProxy:()=>xL});function bL(e,t){let n=e.methods,r=new Map,i={};for(let e of n)r.set(`${e.name}/${e.intent}`,e),i[e.intent]=(i[e.intent]??0)+1;for(let e of n)i[e.intent]===1&&r.set(e.intent,e);let a=t.routes.map(e=>CL(e,r));return SL({info:{title:t.info?.title??e.realm,version:t.info?.version??`1.0.0`},routes:a,serviceInfo:t.serviceInfo})}function xL(e){let t=e.routes.map(t=>({...t,path:wL(e.basePath,t.path)}));return SL({info:{title:e.info?.title??`API Proxy`,version:e.info?.version??`1.0.0`},routes:t,serviceInfo:e.serviceInfo})}function SL(e){let t={};for(let n of e.routes){let e=n.method.toLowerCase(),r={responses:{...n.payment?{402:{description:`Payment Required`}}:{},200:{description:`Successful response`}}};n.payment&&(r[`x-payment-info`]=JT.parse(n.payment)),n.summary&&(r.summary=n.summary),n.requestBody&&(r.requestBody=n.requestBody),t[n.path]||(t[n.path]={}),t[n.path][e]=r}let n={info:e.info,openapi:`3.1.0`,paths:t};return e.serviceInfo&&(n[`x-service-info`]=e.serviceInfo),n}function CL(e,t){if(`handler`in e){let t=e.handler._internal;if(!t)throw Error(`Route ${e.method.toUpperCase()} ${e.path} is missing discovery metadata`);return{method:e.method,path:e.path,payment:{offers:mL(t).map(hL)},...e.requestBody?{requestBody:e.requestBody}:{},...e.summary?{summary:e.summary}:{}}}let n=t.get(e.intent);if(!n)throw Error(`Unknown intent "${e.intent}" for route ${e.method.toUpperCase()} ${e.path}. Available: ${[...t.keys()].join(`, `)}`);let{description:r,...i}=e.options,a={_canonicalRequest:Lx(n,i),...typeof r==`string`?{description:r}:{},intent:n.intent,name:n.name};return{method:e.method,path:e.path,payment:hL(a),...e.requestBody?{requestBody:e.requestBody}:{},...e.summary?{summary:e.summary}:{}}}function wL(e,t){if(!e)return t;let n=e.startsWith(`/`)?e:`/${e}`;return`${n.endsWith(`/`)?n.slice(0,-1):n}${t}`}var TL=F((()=>{zx(),eE(),vL()}));Ox(),_S(),_T(),qC(),ow(),lw(),Fx(),mO(),iw(),OS(),kC(),ck(),JO();const EL=`0.13.5`,DL=p.object({address:p.string(),isDefault:p.boolean().optional(),name:p.string(),source:p.string().optional()}),OL=p.object({address:p.string(),balances:p.array(p.string()).optional(),name:p.string(),type:p.string().optional()}),kL=p.object({message:p.string(),path:p.string(),severity:p.string()}),AL=p.object({description:p.string().optional(),id:p.string(),name:p.string().optional(),paidEndpoints:p.number(),status:p.string().optional(),url:p.string().optional()}),jL=p.object({description:p.string().optional(),method:p.string(),path:p.string(),payment:p.unknown().optional()});function ML(e){return e.format===`json`&&e.formatExplicit}function NL(e,t,n){if(ML(e))return e.ok(t);n()}async function PL(t){if(!t.body)return;let n=t.body.getReader();try{for(;;){let{done:t,value:r}=await n.read();if(t)break;process.stdout.write(Buffer.from(r))||await e(process.stdout,`drain`)}}finally{n.releaseLock()}}function FL(){return process.stdin.isTTY===!1&&process.stdin.listenerCount(`data`)===0&&process.stdin.listenerCount(`readable`)===0}function IL(e){return typeof e==`string`?e:void 0}function LL(e){return Array.isArray(e.endpoints)?e.endpoints.filter(e=>typeof e==`object`&&!!e):[]}function RL(e){let t=LL(e);return{...IL(e.description)?{description:IL(e.description)}:{},id:IL(e.id)??IL(e.name)??`unknown`,...IL(e.name)?{name:IL(e.name)}:{},paidEndpoints:t.filter(e=>e.payment).length,...IL(e.status)?{status:IL(e.status)}:{},...IL(e.serviceUrl)||IL(e.url)?{url:IL(e.serviceUrl)??IL(e.url)}:{}}}function zL(e){return{...IL(e.description)?{description:IL(e.description)}:{},method:IL(e.method)??`GET`,path:IL(e.path)??`/`,...e.payment===void 0?{}:{payment:e.payment}}}function BL(e){if(!e)return`free`;if(typeof e!=`object`)return String(e);let t=e,n=IL(t.amount),r=IL(t.currency),i=IL(t.method),a=IL(t.intent);return[n,r,i&&a?`${i}/${a}`:i??a].filter(Boolean).join(` `)}function VL(e){return e.request.currency??e.request.asset}function HL(e,t){if(!t)return[...e];let n=t.toLowerCase();return e.filter(e=>{let t=VL(e);return typeof t==`string`&&t.toLowerCase()===n})}async function UL(e,t,n={}){let r=()=>KC().getChallenges(e),i=()=>aw().getChallenges(n.ignoreX402ResponseUrl?new Response(null,{headers:e.headers,status:e.status}):e);if(t===`mpp`)return r();if(t===`x402`)return i();let a=[],o;try{a=await r()}catch(e){o=e}let s=[],c;try{s=await i()}catch(e){c=e}if(a.length||s.length)return[...a,...s];if(o)throw o;if(c)throw c;return[]}function WL(e){return sw({name:`selected-challenge`,isPaymentRequired:e=>e.status===402,getChallenges:()=>[e],setCredential:e=>e})}function GL(e,t){if(!ES(e))return new Response(null,{status:402,headers:{[q.wwwAuthenticate]:$x(e)}});let n=e.request;return n.resource?new Response(null,{status:402,headers:{[dC]:tw({accepts:[oC(n)],...n.extensions&&{extensions:n.extensions},resource:n.resource,x402Version:2})}}):t}function KL(e){let{host:t,hostname:n}=new URL(e);return!n.endsWith(`.localhost`)||n===`localhost`?{url:e}:{host:t,url:e.replace(n,`127.0.0.1`)}}async function qL(e,t,n,r){let i=t,a=KL(i),o={...n,redirect:`manual`,headers:Aw(n.headers)};a.host&&XL(o.headers,a.host);for(let t=0;t<=20;t++){let n=await e(a.url,o),s=n.headers.get(`location`);if(!r||!s||![301,302,303,307,308].includes(n.status))return{init:o,logicalUrl:i,response:n,target:a};if(t===20)throw TypeError(`Too many redirects`);await n.body?.cancel().catch(()=>{});let c=new URL(s,i),l=new URL(i),u=Aw(o.headers);if(c.origin!==l.origin)for(let e of[`authorization`,`cookie`,`host`,`proxy-authorization`])for(let t of Object.keys(u))t.toLowerCase()===e&&delete u[t];let d=(o.method??(o.body?`POST`:`GET`)).toUpperCase(),f=n.status===303&&d!==`GET`&&d!==`HEAD`||(n.status===301||n.status===302)&&d===`POST`;if(f)for(let e of[`content-encoding`,`content-language`,`content-length`,`content-location`,`content-type`])for(let t of Object.keys(u))t.toLowerCase()===e&&delete u[t];i=c.href,a=KL(i),a.host&&XL(u,a.host);let p={...o};f&&(delete p.body,p.method=`GET`),o={...p,headers:u,redirect:`manual`}}throw TypeError(`Too many redirects`)}function JL(e,t,n){let r=new URL(e),i=new URL(n||e);return i.origin!==r.origin&&YL(i),KL(i.href)}function YL(e){throw new I({code:`UNSAFE_PAYMENT_REDIRECT`,message:`Refusing to send a payment credential to redirected origin ${e.origin}.`,exitCode:1})}function XL(e,t){for(let t of Object.keys(e))t.toLowerCase()===`host`&&delete e[t];t&&(e.Host=t)}function ZL(e){let t=e.request.resource;return typeof t?.url==`string`?t.url:void 0}async function QL(){let e=process.env.MPPX_SERVICES_URL??`https://mpp.dev/api/services`,t=await globalThis.fetch(e);if(!t.ok)throw new I({code:`SERVICES_FETCH_FAILED`,message:`Failed to fetch services registry: HTTP ${t.status}`,exitCode:1});let n=await t.json();if(!n||typeof n!=`object`||!Array.isArray(n.services))throw new I({code:`SERVICES_INVALID`,message:`Services registry response did not contain a services array.`,exitCode:1});return n.services}function $L(e,t){let n=t.toLowerCase();return e.find(e=>{let t=IL(e.id)?.toLowerCase(),r=IL(e.name)?.toLowerCase();return t===n||r===n})}const eR=cb(`mppx`,{mcp:{tools:{discovery:`direct`}},version:EL,description:`Make HTTP requests with automatic payment handling`,usage:[{suffix:`<url> [options]`}],args:p.object({url:p.string().describe(`URL to make request to`)}),options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),autoSwap:p.boolean().optional().describe(`Auto-swap source tokens into payment currency`),config:p.string().optional().describe(`Path to config file`),confirm:p.boolean().optional().default(!1).describe(`Show confirmation prompts`),currency:p.string().optional().describe(`Payment currency/token address to select`),data:p.string().optional().describe(`Send request body (implies POST unless -X is set)`),fail:p.boolean().optional().describe(`Fail silently on HTTP errors (exit 22)`),header:p.array(p.string()).optional().describe(`Add header (repeatable)`),include:p.boolean().optional().describe(`Include response headers in output`),insecure:p.boolean().optional().describe(`Skip TLS certificate verification (true for localhost/.local)`),jsonBody:p.string().optional().describe(`Send JSON body (sets Content-Type and Accept, implies POST)`),location:p.boolean().optional().describe(`Follow redirects`),method:p.string().optional().describe(`HTTP method`),methodOpt:p.array(p.string()).optional().describe(`Method-specific option (key=value, repeatable)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),payWith:p.string().optional().describe(`Source token for Tempo auto-swap`),protocol:p.enum([`auto`,`mpp`,`x402`]).default(`auto`).describe(`Payment protocol to use`),rpcUrl:p.string().optional().describe(`RPC endpoint, defaults to public RPC for chain (env: MPPX_RPC_URL)`),session:p.string().optional().default(`auto`).refine(e=>e===`auto`||e===`new`||/^0x[0-9a-fA-F]{64}$/.test(e),`Expected auto, new, or a 32-byte channel ID`).describe(`Session selection: auto, new, or channel ID`),silent:p.boolean().default(!1).describe(`Silent mode (suppress progress and info)`),slippage:p.number().optional().describe(`Tempo auto-swap max slippage percentage`),userAgent:p.string().optional().describe(`Set User-Agent header`),verbose:p.number().default(0).meta({count:!0}).describe(`Verbosity (-v details, -vv headers)`)}),alias:{account:`a`,config:`c`,data:`d`,fail:`f`,header:`H`,include:`i`,insecure:`k`,jsonBody:`J`,location:`L`,method:`X`,methodOpt:`M`,rpcUrl:`r`,silent:`s`,userAgent:`A`,verbose:`v`},examples:[{args:{url:`mpp.dev/api/ping/paid`},description:`Make a payment request`}],async run(e){let t=e.options.silent?e=>{}:e=>process.stderr.write(e),n=await zP(e.options.config);n&&e.options.verbose>=1&&t(`${X.dim(`Using config`)} ${X.blue(c.relative(process.cwd(),n.path))}\n`);let r=uk(),i={"User-Agent":e.options.userAgent??`mppx/${EL}${r?` AIAgent/${r}`:``}`};if(e.options.header)for(let t of e.options.header){let n=t.indexOf(`:`);if(n===-1)return e.error({code:`INVALID_HEADER`,message:`Invalid header format: ${t}`,exitCode:2});i[t.slice(0,n).trim()]=t.slice(n+1).trim()}let a=IP(n?.config);a&&!Object.keys(i).some(e=>e.toLowerCase()===`accept-payment`)&&(i[`Accept-Payment`]=a);let o=(()=>{let t=/^https?:\/\//.test(e.args.url),n=/^(localhost|.*\.localhost|127\.0\.0\.1|\[::1\])(:\d+)?/.test(e.args.url);return t?e.args.url:`${n?`http`:`https`}://${e.args.url}`})(),{hostname:s}=new URL(o),l=e.options.insecure||s===`localhost`||s.endsWith(`.localhost`)||s.endsWith(`.local`)?async(e,t)=>{let n=process.env.NODE_TLS_REJECT_UNAUTHORIZED;process.env.NODE_TLS_REJECT_UNAUTHORIZED=`0`;try{return await globalThis.fetch(e,t)}finally{n===void 0?delete process.env.NODE_TLS_REJECT_UNAUTHORIZED:process.env.NODE_TLS_REJECT_UNAUTHORIZED=n}}:globalThis.fetch,u=KL(o),d=u.url;u.host&&(i.Host=u.host);try{let r=OO(e.options.methodOpt),a=nF(),s={redirect:e.options.location?`follow`:`manual`};e.options.jsonBody?(s.body=e.options.jsonBody,i[`Content-Type`]??=`application/json`,i.Accept??=`application/json`):e.options.data&&(s.body=e.options.data),e.options.method?s.method=e.options.method.toUpperCase():s.body&&(s.method=`POST`),Object.keys(i).length>0&&(s.headers=i);let c={include:e.options.include??!1,verbose:e.options.verbose,silent:e.options.silent};e.options.verbose>=2&&SO(o,s,t);let f=await qL(l,o,s,e.options.location??!1),p=f.response;if(p.status!==402){if(e.options.session!==`auto`)return e.error({code:`UNSUPPORTED_SESSION`,message:`--session requires a tempo/session payment challenge.`,exitCode:2});if(e.options.fail&&p.status>=400)return e.error({code:`HTTP_ERROR`,message:`HTTP error ${p.status}`,exitCode:22});CO(p,c),await PL(p);return}let m=p.url?new URL(p.url):void 0,h=u.host!==void 0&&m?.hostname===`127.0.0.1`,g=await UL(p,e.options.protocol,{ignoreX402ResponseUrl:h});if(g.length===0)return e.error({code:`UNSUPPORTED_PROTOCOL`,message:e.options.protocol===`auto`?`Server did not offer a payment challenge.`:`Server did not offer an ${e.options.protocol} payment challenge.`,exitCode:2});let _=HL(g,e.options.currency);if(e.options.currency&&_.length===0){let t=g.map(VL).filter(e=>typeof e==`string`).join(`, `);return e.error({code:`UNSUPPORTED_CURRENCY`,message:`Server did not offer payment currency ${e.options.currency}.${t?` Offered currencies: ${t}.`:``}`,exitCode:2})}let v=LP(n?.config)?.length?_:await XN(_,{options:{account:e.options.account,network:e.options.network,rpcUrl:e.options.rpcUrl}}),y=FP(v,n?.config);if(!y){let t=v.map(e=>`${e.method}/${e.intent}`).join(`, `);return e.error({code:`UNSUPPORTED_METHOD`,message:`Unsupported payment method. Server offers: ${t}. Add it to mppx.config.ts using defineConfig().`,exitCode:2})}let{challenge:b,plugin:x,method:S}=y,C=ES(b),w=C?void 0:JL(o,u,f.logicalUrl),T=GL(b,p),ee=b.request.currency??``,E=b.request.decimals??6,D,O;x&&(O=await x.setup({challenge:b,options:{account:e.options.account,autoSwap:e.options.autoSwap,network:e.options.network,payWith:e.options.payWith,rpcUrl:e.options.rpcUrl,slippage:e.options.slippage},methodOpts:r}),ee=O.tokenSymbol,E=O.tokenDecimals,D=O.explorerUrl);let te=!e.options.silent&&e.options.confirm,ne=new Set;{CO(p,b.method===`tempo`&&b.intent===`session`&&e.options.include?{...c,include:!1,verbose:Math.max(c.verbose,2)}:c);let n=(()=>{let e=new Set([`id`,`request`]),t=[];for(let[n,r]of Object.entries(b))e.has(n)||r===void 0||t.push([n,EO(n,r)]);return t.sort(([e],[t])=>e.localeCompare(t))})(),r={tokenSymbol:ee,tokenDecimals:E,explorerUrl:D},i=(()=>{let e=new Set([`decimals`,`currency`,`methodDetails`]),t=[];for(let[n,i]of Object.entries(b.request))e.has(n)||i===void 0||t.push([n,wO(n,i,r)]);return t.sort(([e],[t])=>e.localeCompare(t))})(),a=(()=>{let e=b.request.methodDetails;if(!e)return[];let t=[];for(let[n,i]of Object.entries(e))if(i!==void 0){if(n===`memo`&&typeof i==`string`){let e=TO(i);t.push([n,e?`${e}\n${X.dim(i)}`:i])}else t.push([n,wO(n,i,r)])}return t.sort(([e],[t])=>e.localeCompare(t))})(),o=[[`Challenge`,n],[`Request`,i],...a.length?[[`Details`,a]]:[]];for(let[,e]of o)for(let[t]of e)ne.add(t);let s=Math.max(...o.flatMap(([,e])=>e.map(([e])=>e.length))),l=` ${``.padEnd(s)} `;if(e.options.verbose>=1||te){t(`${X.bold(X.yellow(`Payment Required`))}\n`);for(let[e,n]of o){t(`${X.bold(e)}\n`);for(let[e,r]of n){let[n,...i]=r.split(`
246
- `);t(` ${X.dim(e.padEnd(s))} ${n}\n`);for(let e of i)t(`${l}${e}\n`)}}}if(te&&(t(`
247
- `),!await MO(`Proceed with ${b.intent}?`,!0))){t(`Aborted.
248
- `);return}}let re=process.env.MPPX_PRIVATE_KEY?.trim()||!AO(tk(e.options.account));if(ND(b)&&re&&!S){try{await rI({challenge:b,challengeResponse:T,credentialContext:await NP(b,n?.config.extensions,O?.credentialContext),endpoint:f.logicalUrl,fetch:l,fetchInput:w.url,init:{...f.init,redirect:`manual`},info:t,methodOptions:r,options:{account:e.options.account,fail:e.options.fail,include:e.options.include,network:e.options.network,rpcUrl:e.options.rpcUrl,session:e.options.session,silent:e.options.silent,verbose:e.options.verbose},registry:a})}catch(e){return KF(e,`SESSION_REQUEST_FAILED`)}return}if(e.options.session!==`auto`)return e.error({code:`UNSUPPORTED_SESSION`,message:S&&ND(b)?`--session cannot override a configured session method. Configure its channelStore instead.`:`--session requires a tempo/session payment challenge.`,exitCode:2});let A=S&&ND(b)?void 0:await NP(b,n?.config.extensions,O?.credentialContext),j,ie;if(S&&ND(b)){let e=T;j=await ST({methods:[S],polyfill:!1,async onChallenge(e,{createCredential:t}){let r=await NP(e,n?.config.extensions,O?.credentialContext);return VP(b,e),t(r)},fetch:async(t,n)=>{if(e){let t=e;return e=void 0,t}return l(t,n)}}).fetch(w.url,{...f.init,context:A,redirect:`manual`})}else{if(O?.createCredential)ie=await O.createCredential(T,A);else if(O)ie=await ST({methods:O.methods,polyfill:!1,transport:WL(b)}).createCredential(T,A);else if(S)ie=await ST({methods:[S],polyfill:!1,transport:WL(b)}).createCredential(T,A);else throw Error(`unreachable`);let n=C?fC:fS(b),r={...Aw(f.init.headers),[n]:ie},i=C?KL((ZL(b)??p.url)||o):w;C&&XL(r,i.host),x?.prepareCredentialRequest?.({challenge:b,credential:ie,headers:r});let a={...f.init,redirect:`manual`,headers:r};e.options.verbose>=2&&SO(i.url,a,t),j=await l(i.url,a)}if(e.options.fail&&j.status>=400)return e.error({code:`HTTP_ERROR`,message:`HTTP error ${j.status}`,exitCode:22});if(j.status===402){let n=await j.text();t(`${X.bold(X.red(`Payment Rejected`))}\n`);try{let e=JSON.parse(n),r=[];for(let[t,n]of Object.entries(e))n!==void 0&&r.push([t,String(n)]);r.sort(([e],[t])=>e.localeCompare(t));let i=Math.max(...r.map(([e])=>e.length));for(let[e,n]of r)t(` ${X.dim(e.padEnd(i))} ${n}\n`)}catch{n&&t(` ${n}\n`)}return e.error({code:`PAYMENT_REJECTED`,message:`Payment rejected`,exitCode:75})}if(CO(j,c),!(ie&&await x?.handleResponse?.({challenge:b,credential:ie,response:j,fetchUrl:d,fetchInit:s,silent:e.options.silent,verbose:e.options.verbose,confirmEnabled:te,confirm:MO,tokenSymbol:ee,tokenDecimals:E,explorerUrl:D,shownKeys:ne}))){let n=j.headers.get(q.paymentReceipt);if(n&&e.options.verbose>=1)try{let e=JSON.parse(k.toString(n));t(`\n${X.bold(X.green(`Payment Receipt`))}\n`);let r=[],i=e.channelId,a=e.reference,o=i&&a&&i===a,s=new Set([`acceptedCumulative`,`spent`]);for(let[t,n]of Object.entries(e)){if(n===void 0||ne.has(t)||t===`reference`&&o)continue;let e=x?.formatReceiptField?.(t,n);e===void 0?s.has(t)&&typeof n==`string`?r.push([t,`${n} ${X.dim(`(${NO(BigInt(n),ee,E)})`)}`]):(t===`reference`||t===`txHash`)&&typeof n==`string`&&D?r.push([t,DO(`${D}/tx/${n}`,n)]):r.push([t,String(n)]):r.push([t,e])}r.sort(([e],[t])=>e.localeCompare(t));let c=Math.max(...r.map(([e])=>e.length));for(let[e,n]of r)t(` ${X.dim(e.padEnd(c))} ${n}\n`);t(`
249
- `)}catch{}await PL(j)}}catch(t){if(t instanceof I)throw t;let n=t instanceof Error?t.cause:void 0,r=n instanceof Error?n:void 0;if(r&&`code`in r){let t=r.code;return t===`ENOTFOUND`?e.error({code:`DNS_ERROR`,message:`Could not resolve host "${s}". Check the URL and try again.`,exitCode:6}):t===`ECONNREFUSED`?e.error({code:`CONNECTION_REFUSED`,message:`Connection refused by "${s}". Is the server running?`,retryable:!0,exitCode:7}):t===`ECONNRESET`?e.error({code:`CONNECTION_RESET`,message:`Connection to "${s}" was reset.`,retryable:!0,exitCode:56}):t===`ETIMEDOUT`?e.error({code:`CONNECTION_TIMEOUT`,message:`Connection to "${s}" timed out.`,retryable:!0,exitCode:28}):t===`CERT_HAS_EXPIRED`||t===`UNABLE_TO_VERIFY_LEAF_SIGNATURE`?e.error({code:`TLS_ERROR`,message:`TLS certificate error for "${s}". Use --insecure to skip verification.`,exitCode:60}):e.error({code:`REQUEST_FAILED`,message:`Request to "${s}" failed: ${r.message}`})}{let n=t instanceof Error?t.message:String(t);return e.error({code:`REQUEST_FAILED`,message:r?`Request failed: ${n} (Cause: ${r.message})`:`Request failed: ${n}`})}}}}),tR=cb(`account`,{description:`Manage accounts (create, default, delete, export, fund, list, view)`}).command(`create`,{description:`Create new account`,options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),rpcUrl:p.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`)}),output:p.object({address:p.string(),name:p.string()}),alias:{account:`a`,rpcUrl:`r`},async run(e){let t=ML(e),n=e.options.account;if(!n){if((await nk().list()).length===0)n=`main`;else{if(t)return e.error({code:`ACCOUNT_REQUIRED`,message:`Account name is required in structured mode.`,exitCode:2});let r=await jO(`Account name`);if(!r)return;n=r}}let r=nk(n);for(;await r.get();){if(t)return e.error({code:`ACCOUNT_EXISTS`,message:`Account "${n}" already exists.`,exitCode:1});process.stderr.write(`${X.dim(`Account "${n}" already exists.`)}\n\n`);let i=await jO(`Enter different name`);if(!i)return;n=i,r=nk(n)}let i=ge(),a=ve(i);await r.set(i),(await nk().list()).length===1&&ek().set(n);let o=ye.blockExplorers?.default?.url,s=o?DO(`${o}/address/${a.address}`,a.address):a.address,c=FO(e.options),l=PO(e.options.rpcUrl,{network:c});return IO({network:c,rpcUrl:l}).then(e=>j({chain:e,transport:ue(l)})).then(e=>import(`viem/tempo`).then(({Actions:t})=>t.faucet.fund(e,{account:a}).catch(()=>{}))),NL(e,{address:a.address,name:n},()=>{console.log(`Account "${n}" saved to keychain.`),console.log(X.dim(`Address ${s}`)),console.log(X.dim(`Fund testnet tokens: mppx account fund --account ${n} --network testnet`))})}}).command(`default`,{description:`Set default account`,options:p.object({account:p.string().describe(`Account name`)}),output:p.object({name:p.string()}),alias:{account:`a`},async run(e){let t=e.options.account;return AO(t)?_P(t)?(ek().set(t),NL(e,{name:t},()=>{console.log(`Default account set to "${t}"`)})):e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found. Is Tempo wallet configured?`,exitCode:69}):await nk(t).get()?(ek().set(t),NL(e,{name:t},()=>{console.log(`Default account set to "${t}"`)})):e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found.`,exitCode:69})}}).command(`delete`,{description:`Delete account`,options:p.object({account:p.string().describe(`Account name`),yes:p.boolean().optional().describe(`DANGER!! Skip confirmation prompts`)}),output:p.object({defaultAccount:p.string().optional(),name:p.string()}),alias:{account:`a`},async run(e){let t=nk(e.options.account),n=await t.get();if(!n)return e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${e.options.account}" not found.`,exitCode:69});let r=ve(n),i=await VO(r.address,{includeTestnet:!1});if(!e.options.yes){if(ML(e))return e.error({code:`CONFIRMATION_REQUIRED`,message:`Pass --yes to delete an account in structured mode.`,exitCode:2});let t=ye.blockExplorers?.default?.url,n=t?DO(`${t}/address/${r.address}`,r.address):r.address;process.stderr.write(X.dim(`Delete account "${e.options.account}"\n`)),process.stderr.write(X.dim(` Address ${n}\n`));for(let e=0;e<i.length;e++)process.stderr.write(X.dim(` ${e===0?`Balance`:` `} ${i[e]}\n`));if(process.stderr.write(X.dim(`This action cannot be undone
241
+ `);a=n.pop(),await d(n)}a.trim()&&await d([a]),t.channelId&&t.escrowContract&&t.chainId&&await dP({channelId:t.channelId,cumulativeAmount:n,escrowContract:t.escrowContract,chainId:t.chainId,fetchUrl:t.fetchUrl,fetchInit:t.fetchInit,session:t.session,info:t.info,verbose:t.verbose,tokenSymbol:t.tokenSymbol,tokenDecimals:t.tokenDecimals,explorerUrl:t.explorerUrl,confirmEnabled:!1})}async function dP(e){let t=await e.session.signVoucher({channelId:e.channelId,cumulativeAmount:e.cumulativeAmount,escrowContract:e.escrowContract,chainId:e.chainId,action:`close`}),n=await globalThis.fetch(e.fetchUrl,{...e.fetchInit,headers:{...Mw(e.fetchInit.headers),Authorization:t}});if(n.ok){if(wP(e.channelId),e.verbose>=1){let t=n.headers.get(q.paymentReceipt),r;if(t)try{let e=JSON.parse(k.toString(t));typeof e.txHash==`string`&&(r=e.txHash)}catch{}let i=r&&e.explorerUrl?` ${X.dim(AO(`${e.explorerUrl}/tx/${r}`,r))}`:``;e.info(`${X.dim(`Channel closed.`)} ${X.dim(`Spent ${IO(e.cumulativeAmount,e.tokenSymbol,e.tokenDecimals)}.`)}${i}\n`)}}else{let t=await n.text().catch(()=>``);e.info(`\n${X.dim(X.yellow(`Channel close failed`))} ${X.dim(`(${n.status})`)}\n`),e.info(`${X.dim(` channelId: ${e.channelId}`)}\n${X.dim(` cumulativeAmount: ${e.cumulativeAmount}`)}\n${X.dim(` escrowContract: ${e.escrowContract}`)}\n${X.dim(` chainId: ${e.chainId}`)}\n${X.dim(` response: ${t||`(empty)`}`)}\n`)}}function fP(e=100){return!process.stdin.isTTY||!process.stdout.isTTY?Promise.resolve(void 0):new Promise(t=>{let n=process.stdin.isRaw,r=``,i=()=>{clearTimeout(a),process.stdin.removeListener(`data`,o),process.stdin.isTTY&&process.stdin.setRawMode(n??!1),process.stdin.pause()},a=setTimeout(()=>{i(),t(void 0)},e),o=e=>{r+=e.toString();let n=r.match(/\x1b\]11;rgb:([0-9a-f]+)\/([0-9a-f]+)\/([0-9a-f]+)/i);if(!n)return;i();let a=e=>Number.parseInt(e.slice(0,2),16);t({r:a(n[1]),g:a(n[2]),b:a(n[3])})};process.stdin.setRawMode(!0),process.stdin.resume(),process.stdin.on(`data`,o),process.stdout.write(`\x1B]11;?\x07`)})}function pP(e){return _P(NP,e,PP)}function mP(e){return e.method===`tempo`&&e.intent===`charge`}async function hP(e){let t=ik(e.options.account),n=process.env.MPPX_PRIVATE_KEY?.trim()||(NO(t)?void 0:await ak(t).get()),r;if(n)r=_e(n).address;else if(NO(t)&&OP())r=DP(t)?.wallet_address;else{let e=AP();if(e){let t=await ak(e).get();t&&(r=_e(t).address)}}if(!r)return;let i=LO(e.options.rpcUrl,{network:e.options.network}),a=M({chain:await zO({network:e.options.network,rpcUrl:i}),transport:le(i)});return{account:r,client:a}}async function gP(e,t){let n=e.request,r=n.currency,i=n.amount;if(typeof r!=`string`||typeof i!=`string`)return`unsupported`;let a=n.methodDetails?.chainId;if(a&&t.client.chain?.id&&a!==t.client.chain.id)return`unsupported`;let o=BigInt(i);if(o===0n)return`payable`;let s=await Fe.token.getBalance(t.client,{account:t.account,token:r}).then(e=>e.amount).catch(()=>void 0);return s===void 0?`unknownBalance`:s>=o?`payable`:`insufficientBalance`}function _P(e,t,n){if(t&&typeof t==`object`&&!Array.isArray(t)){let e=Object.keys(t).filter(e=>!n.includes(e));if(e.length)throw Error(`Unsupported CLI method option(s): ${e.join(`, `)}`)}let r=e.safeParse(t??{});if(r.success)return r.data;let i=r.error.issues.map(e=>`${e.path.length?e.path.join(`.`):`options`}: ${e.message}`).join(`, `);throw Error(`Invalid CLI options (${i})`)}function vP(e){let t=e.challenge.request.methodDetails?.chainId;if(!t||!e.clientChainId||t===e.clientChainId)return;let n=t===4217?` Use --network mainnet or --rpc-url https://rpc.tempo.xyz.`:t===42431?` Use --network testnet or --rpc-url https://rpc.moderato.tempo.xyz.`:``;throw new L({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${t}, but RPC is chainId ${e.clientChainId}.${n}`,exitCode:2})}function yP(e){if(e)return e.split(`,`).map(e=>e.trim()).filter(Boolean)}function bP(e){let t=yP(e.tokenIn)??yP(e.payWith);if(!(!e.autoSwap&&!t&&e.slippage===void 0)){if(e.autoSwap===!1&&!t&&e.slippage===void 0)return!1;if(e.slippage!==void 0&&(!Number.isFinite(e.slippage)||e.slippage<0))throw Error(`Invalid CLI options (slippage: expected a non-negative number)`);return{...t?{tokenIn:t}:{},...e.slippage===void 0?{}:{slippage:e.slippage}}}}function xP(){return c.join(process.env.XDG_CONFIG_HOME||c.join(b.homedir(),`.config`),`mppx`,`channels`)}function SP(e){try{let n=t.readFileSync(c.join(xP(),e),`utf-8`).trim();return n?BigInt(n):void 0}catch{return}}function CP(e,n){let r=xP();t.mkdirSync(r,{recursive:!0}),t.writeFileSync(c.join(r,e),n.toString(),`utf-8`)}function wP(e){try{t.unlinkSync(c.join(xP(),e))}catch{}}function TP(){return b.platform()===`darwin`?c.join(b.homedir(),`Library`,`Application Support`,`tempo`,`wallet`,`keys.toml`):c.join(process.env.XDG_DATA_HOME||c.join(b.homedir(),`.local`,`share`),`tempo`,`wallet`,`keys.toml`)}function EP(){try{let e=t.readFileSync(TP(),`utf-8`),n=[],r;for(let t of e.split(`
242
+ `)){let e=t.trim();if(e===`[[keys]]`){r?.wallet_address&&n.push(r),r={wallet_type:`local`,wallet_address:``,chain_id:0};continue}if(!r)continue;let i=e.match(/^(\w+)\s*=\s*"?([^"]*)"?$/);if(!i)continue;let[,a,o]=i;a===`wallet_type`?r.wallet_type=o:a===`wallet_address`?r.wallet_address=o:a===`chain_id`&&(r.chain_id=Number.parseInt(o,10))}return r?.wallet_address&&n.push(r),n}catch{return[]}}function DP(e){let t=EP();if(t.length===0)return;let n=e.slice(6);if(n==="default"||n===``)return t[0];let r=Number.parseInt(n,10);if(!Number.isNaN(r)&&r>=0&&r<t.length)return t[r]}function OP(){if(IP!==void 0)return IP;try{m.execFileSync(`which`,[`tempo`],{stdio:`ignore`}),IP=!0}catch{IP=!1}return IP}async function kP(e){return new Promise((t,n)=>{m.execFile(`tempo`,[`mpp`,`sign`,`--challenge`,e],(e,r,i)=>{if(e){let t=i?.trim()||e.message;n(Error(`tempo mpp sign failed: ${t}`));return}let a=r.trim();if(!a){n(Error(`tempo mpp sign returned empty output`));return}t(a)})})}function AP(){let e=rk();if(NO(e.get())&&!OP()&&b.platform()===`darwin`)try{let t=m.execFileSync(`security`,[`dump-keychain`],{encoding:`utf-8`}),n=[];for(let e of t.split(`keychain:`)){let t=e.match(/"svce"<blob>="([^"]*)"/),r=e.match(/"acct"<blob>="([^"]*)"/);t?.[1]===jP&&r?.[1]&&n.push(r[1])}if(n.length>0)return e.set(n[0]),n[0]}catch{}}var jP,MP,NP,PP,FP,IP,LP=I((()=>{Ox(),yT(),Fx(),rC(),rP(),GE(),Uj(),dk(),ZO(),uA(),jP=`mppx`,MP=p.union([p.boolean(),p.literal(`true`).transform(()=>!0),p.literal(`false`).transform(()=>!1)]),NP=p.object({allowCustomEscrow:p.optional(MP),autoSwap:p.optional(MP),channel:p.optional(p.coerce.string()),deposit:p.optional(p.union([p.string(),p.number()])),payWith:p.optional(p.string()),slippage:p.optional(p.coerce.number()),tokenIn:p.optional(p.string())}),PP=[`allowCustomEscrow`,`autoSwap`,`channel`,`deposit`,`payWith`,`slippage`,`tokenIn`],FP=[`payable`,`unknownBalance`,`insufficientBalance`,`unsupported`]}));OS(),dk(),uA();const RP=[...Object.entries(_k),...Object.entries(vk),...Object.entries(yk),...Object.entries(bk)];function zP(){return lA({method:`evm`,supports:BP,async setup({challenge:e,options:t}){let n=e.request,r=n.network?VP(Dk(n.network)):void 0,i=n.network&&n.asset?RP.find(([,e])=>Tk(e,n.asset,n.network)):void 0,a=n.extra?.name,o=n.extra?.version,s=n.asset&&n.network&&typeof a==`string`&&typeof o==`string`?hk({address:n.asset,decimals:i?.[1].decimals??6,network:n.network,transfer:{name:a,type:`eip3009`,version:o}}):void 0,c=await ck(t.account);return{explorerUrl:r?.blockExplorers?.default?.url,methods:[...cA({account:c,...s&&{currencies:[s]}})],tokenDecimals:i?.[1].decimals??6,tokenSymbol:i?.[0]??``}}})}function BP(e){if(!ES(e))return!1;let t=e.request,n=t.extra,r=n?.assetTransferMethod;return t.scheme===`exact`&&typeof t.asset==`string`&&typeof t.network==`string`&&typeof n?.name==`string`&&typeof n?.version==`string`&&(r===void 0||r===`eip3009`)}function VP(e){return Object.values(Be).find(t=>t.id===e)}_S(),JS(),LP();const HP=[sP(),bA(),dA(),zP()];async function UP(e,t,n){let r=n;for(let n of t??[]){let t=await n.preparePayment?.({challenge:e,...r===void 0?{}:{credentialContext:r}});t&&`credentialContext`in t&&(r=t.credentialContext)}return r}function WP(e,t){let n=t?.plugins?.find(t=>JP(t,e));if(n)return{plugin:n};let r=qP(t)?.filter(t=>t.name===e.method&&t.intent===e.intent),i=r?.find(t=>t.canHandleChallenge?.({challenge:e})??!0);if(i)return{method:i};if(r?.length)return{};let a=HP.find(t=>JP(t,e));return a?{plugin:a}:{}}function GP(e,t){let n=qP(t);if(n?.length){let r=NS(e,n,AS(n,t?.paymentPreferences).entries);if(r){let e=t?.plugins?.find(e=>JP(e,r.challenge));return{challenge:r.challenge,...e?{plugin:e}:{method:r.method}}}return}for(let n of e){let e=WP(n,t);if(e.plugin||e.method)return{challenge:n,...e}}}function KP(e){let t=qP(e);if(t?.length)return AS(t,e?.paymentPreferences).header}function qP(e){return Array.isArray(e?.methods)?e.methods.flat():void 0}function JP(e,t){return e.supports?e.supports(t):e.method===t.method}async function YP(e){let t=XP(e);if(!t)return;let n=await import(t);return{config:n.default??n,path:t}}function XP(e){if(e){let n=c.resolve(e);return t.existsSync(n)?n:void 0}let n=process.env.MPPX_CONFIG?.trim();if(n){let e=c.resolve(n);return t.existsSync(e)?e:void 0}}function ZP(e,t){function n(t){let n={...t.request};if(t.method===`tempo`&&t.intent===`session`){let e={...n.methodDetails};delete e.sessionSnapshot,Object.keys(e).length?n.methodDetails=e:delete n.methodDetails}return $x({...t,request:n,id:e.id,expires:e.expires})}if(n(t)!==n(e))throw Error(`Payment request changed on retry. Run the command again to approve the new payment.`)}LP(),_S(),iM(),hN(),TN(),_O();function QP(e){return e??globalThis.fetch.bind(globalThis)}function $P(e,t){let n=e.request.methodDetails?.chainId;if(n!==void 0&&n!==t.chainId)throw Error(`Close challenge changed the session chain.`);if(typeof e.request.recipient!=`string`||e.request.recipient.toLowerCase()!==t.descriptor.payee.toLowerCase())throw Error(`Close challenge changed the session payee.`);if(typeof e.request.currency!=`string`||e.request.currency.toLowerCase()!==t.descriptor.token.toLowerCase())throw Error(`Close challenge changed the session token.`);if(Zj(e,t.escrow).toLowerCase()!==t.escrow.toLowerCase())throw Error(`Close challenge changed the session escrow.`);let r=LD(e);if(r&&r.channelId.toLowerCase()!==t.channelId.toLowerCase())throw Error(`Close challenge changed the session channel.`)}async function eF(e){$P(e.challenge,e.channel);let t=QP(e.fetch),n,r=async(r,i)=>{n&&=(await e.onChallenge?.(n),void 0);let a=await t(r,i);if(a.status!==402)return a;let o=cS(a).find(FD);if(!o)throw Error(`Refreshed close response did not include tempo/session.`);return $P(o,e.channel),n=o,a},i=wN({...e.manager,bootstrap:!1,escrow:e.channel.escrow,fetch:r});pN(i).rehydrate(e);let a=await i.close();if(!a)throw Error(`Session close response did not include a payment receipt.`);return{manager:i,receipt:a}}_S(),iM(),_M(),_O(),Tj(),Zx();var tF=class extends Error{name=`SessionStateError`;code=`SESSION_STATE_INVALID`;file;constructor(e,t={}){super(e,t.cause===void 0?void 0:{cause:t.cause}),this.file=t.file}},nF=class extends Error{name=`SessionBusyError`;code=`SESSION_BUSY`;exitCode=75;scope;owner;constructor(e,t){super(`Session scope is busy in process ${t.pid} on ${t.hostname}.`),this.scope=e,this.owner=t}};const rF=J.object({channelId:qx(),cumulativeAmount:J.string(),deposit:J.string(),descriptor:J.object({payer:Kx(),payee:Kx(),operator:Kx(),token:Kx(),salt:qx(),authorizedSigner:Kx(),expiringNonceHash:qx()}),escrow:Kx(),chainId:J.number(),opened:J.boolean()}),iF=J.object({name:J.optional(J.string()),address:Kx()}),aF=J.object({method:J.literal(`tempo`),intent:J.literal(`session`),status:J.literal(`success`),timestamp:J.string(),reference:J.string(),challengeId:J.string(),channelId:qx(),acceptedCumulative:J.string(),spent:J.string(),units:J.optional(J.number()),txHash:J.optional(qx())}),oF=J.object({version:J.literal(1),method:J.literal(`tempo`),intent:J.literal(`session`),status:J.enum([`opening`,`open`,`closing`,`stale`]),channel:rF,account:iF,endpoint:J.string(),challenge:gS,receipt:J.optional(aF),spent:J.string(),units:J.number(),createdAt:J.string(),updatedAt:J.string()}),sF=J.object({version:J.literal(1),channelId:qx()}),cF=J.object({version:J.literal(1),scope:J.string(),hostname:J.string(),pid:J.number(),token:J.string(),createdAt:J.string()});function lF(e,t,n,r){let i=e.safeParse(t);if(!i.success)throw Z(n,r,i.error);return i.data}function uF(e){let t=bF(e);return[t.payer,t.payee,t.token,t.escrow,t.chainId].join(`:`)}function dF(e){return{payer:e.descriptor.payer,payee:e.descriptor.payee,token:e.descriptor.token,escrow:e.escrow,chainId:e.chainId}}function fF(e={}){let t=e.stateRoot??mF(),n={root:t,channels:c.join(t,`channels`),locks:c.join(t,`locks`),preferred:c.join(t,`preferred`)},r=e.hostname??b.hostname(),i=e.pid??process.pid,a=e.now??(()=>new Date),o=e.isProcessAlive??KF;async function s(){for(let e of[n.root,n.channels,n.locks,n.preferred])await C.mkdir(e,{recursive:!0,mode:448}),await C.chmod(e,448)}async function l(e){let t=vF(e),r=hF(n,t),i=await LF(r);if(i===void 0)return;let a=OF(i,r);if(a.channel.channelId.toLowerCase()!==t)throw Z(r,`Session filename does not match its channel ID.`);return kF(a)}async function u(){let e;try{e=await C.readdir(n.channels,{withFileTypes:!0})}catch(e){if(JF(e,`ENOENT`))return[];throw Z(n.channels,`Unable to list managed sessions.`,e)}let t=[];for(let n of e){if(!n.isFile()||n.name.includes(`.tmp-`)||!n.name.endsWith(`.json`))continue;let e=n.name.slice(0,-5);vF(e);let r=await l(e);r&&t.push(r)}return t.sort((e,t)=>e.createdAt.localeCompare(t.createdAt))}async function d(e){await s();let t=wF(e.channel),r=vF(t.channelId),i=hF(n,r),o=await LF(i),c=o===void 0?void 0:OF(o,i);c&&AF(c,e,i);let l=EF(e.challenge,i);MF(l,t,i);let u=e.receipt?DF(e.receipt,t.channelId,i):void 0,d=c?lM(c.channel):void 0,f=IF(t.cumulativeAmount,d?.cumulativeAmount??0n),p=IF(e.spent??0n,u?BigInt(u.spent):0n,c?BigInt(c.spent):0n);if(p>f)throw Z(i,`Session spend exceeds the locally authorized cumulative amount.`);let m=TF(cM({...t,cumulativeAmount:f}),i),h=FF(c?.updatedAt,a(),i),g=PF(c?.receipt,u),_=CF(e.account,i),v=OF({version:1,method:`tempo`,intent:`session`,status:e.status,channel:m,account:{..._.name===void 0?c?.account.name===void 0?{}:{name:c.account.name}:{name:_.name},address:_.address},endpoint:SF(e.endpoint,i),challenge:l,...g!==void 0&&{receipt:g},spent:p.toString(),units:Math.max(c?.units??0,e.units??0,u?.units??0),createdAt:c?.createdAt??h,updatedAt:h},i);return await RF(i,v),kF(v)}async function f(e){let t=_F(n,e),r=await LF(t);if(r===void 0)return;let{channelId:i}=lF(sF,r,t,`Preferred session is invalid.`),a=await l(i);if(!a)throw Z(t,`Preferred session ${i} does not exist.`);return NF(a.channel,e,t),i}async function p(e,t){let r=vF(t),i=await l(r),a=_F(n,e);if(!i)throw Z(a,`Session ${r} does not exist.`);NF(i.channel,e,a),await RF(a,{version:1,channelId:r})}async function m(e,t){let r=_F(n,e),i=t===void 0?void 0:vF(t),a=await LF(r);if(a===void 0)return;let o=lF(sF,a,r,`Preferred session is invalid.`).channelId;i&&o.toLowerCase()!==i||await WF(r,`Unable to clear preferred session.`)}async function h(e){let t=vF(e),r=await l(t);r&&(await m(dF(r.channel),t),await WF(hF(n,t),`Unable to remove session.`))}async function g(e){await s();let t=gF(n,e);for(let n=0;n<3;n++){let n={version:1,scope:e,hostname:r,pid:i,token:_(),createdAt:a().toISOString()};try{if(await zF(t,n),await HF(VF(t))){await UF(t,n);continue}return{async release(){await UF(t,n)}}}catch(e){if(!JF(e,`EEXIST`))throw e}let s=await LF(t);if(s===void 0)continue;let c=lF(cF,s,t,`Session lock is invalid.`);if(c.scope!==e)throw Z(t,`Session lock scope is invalid.`);if(c.hostname!==r||o(c.pid))throw new nF(e,c);await BF(t,c)}let c=await LF(t);throw c===void 0?Z(t,`Unable to acquire session lock.`):new nF(e,lF(cF,c,t,`Session lock is invalid.`))}async function v(e){return g(uF(e))}return{root:t,get:l,list:u,upsert:d,remove:h,getPreferred:f,setPreferred:p,clearPreferred:m,acquire:v}}function pF(e,t){let n=xF(t.scope),r=t.selection===`auto`||t.selection===`new`?void 0:vF(t.selection);function i(e){if(e.toLowerCase()!==n)throw new tF(`Session manager requested an unexpected payment scope.`)}async function a(n=!0){if(t.selection===`new`&&!r)return;let i=r??await e.getPreferred(t.scope);if(!i)return;let a=await e.get(i);if(!a)throw new tF(`Session ${i} does not exist.`);if(NF(a.channel,t.scope),!(n&&(a.status!==`open`||!a.channel.opened)))return r=i,a}return{async get(e){return i(e),(await a())?.channel},async set(n){if(i(oM(n)),NF(n,t.scope),r&&r.toLowerCase()!==n.channelId.toLowerCase())throw new tF(`Session manager selected ${r}, but attempted to store ${n.channelId}.`);r||t.onNewChannel?.(n);let a=await e.upsert({...t.context(),channel:n});r=a.channel.channelId,await e.setPreferred(t.scope,a.channel.channelId)},async delete(n){i(n);let o=await a(!1);if(!o)return;let s=t.context();await e.upsert({...o,...s,status:s.status===`closing`?`closing`:`stale`,channel:o.channel,spent:s.spent??o.spent,units:s.units??o.units}),s.status!==`closing`&&await e.clearPreferred(t.scope,o.channel.channelId),r=void 0}}}function mF(){let e=process.env.XDG_STATE_HOME||c.join(b.homedir(),`.local`,`state`);return c.join(e,`mppx`,`sessions`,`v1`)}function hF(e,t){return c.join(e.channels,`${t}.json`)}function gF(e,t){let n=g(`sha256`).update(t).digest(`hex`);return c.join(e.locks,`${n}.lock`)}function _F(e,t){let n=g(`sha256`).update(uF(t)).digest(`hex`);return c.join(e.preferred,`${n}.json`)}function vF(e){return lF(qx(),e,void 0,`Invalid session channel ID: ${e}.`).toLowerCase()}function yF(e,t,n){return lF(Kx(),e,n,`Invalid ${t}.`).toLowerCase()}function bF(e){if(!Number.isSafeInteger(e.chainId)||e.chainId<0)throw new tF(`Invalid session chain ID.`);return{payer:yF(e.payer,`session payer`),payee:yF(e.payee,`session payee`),token:yF(e.token,`session token`),escrow:yF(e.escrow,`session escrow`),chainId:e.chainId}}function xF(e){let t=bF(e);return[t.payee,t.token,t.escrow,t.chainId].join(`:`)}function SF(e,t){if(typeof e!=`string`)throw Z(t,`Session endpoint is invalid.`);let n;try{n=new URL(e)}catch(e){throw Z(t,`Session endpoint is invalid.`,e)}if(n.protocol!==`http:`&&n.protocol!==`https:`)throw Z(t,`Session endpoint must use HTTP or HTTPS.`);if(n.username||n.password)throw Z(t,`Session endpoint must not contain credentials.`);let r=e.indexOf(`#`);return r===-1?e:e.slice(0,r)}function CF(e,t){return lF(iF,e,t,`Session account is invalid.`)}function wF(e){return lM(TF(cM(e)))}function TF(e,t){return lF(rF,e,t,`Stored session channel is invalid.`)}function EF(e,t){let n=gS.safeParse(e);if(!n.success||!FD(n.data))throw Z(t,`Stored session challenge is invalid.`);return n.data}function DF(e,t,n){let r=lF(aF,e,n,`Stored session receipt is invalid.`);if(r.channelId!==t.toLowerCase())throw Z(n,`Stored session receipt has a different channel ID.`);if(r.reference.toLowerCase()!==t.toLowerCase())throw Z(n,`Stored session receipt has a different reference.`);if(BigInt(r.spent)>BigInt(r.acceptedCumulative))throw Z(n,`Stored session receipt spend exceeds its accepted amount.`);return r}function OF(e,t){let n=lF(oF,e,t,`Stored session is invalid.`),{receipt:r,...i}=n,a=n.channel,o=n.account;if(o.address.toLowerCase()!==a.descriptor.payer.toLowerCase())throw Z(t,`Stored session account does not match the channel payer.`);let s=r?DF(r,a.channelId,t):void 0,c=n.spent,l=BigInt(a.cumulativeAmount);if(BigInt(c)>l)throw Z(t,`Stored session spend exceeds its cumulative authorization.`);if(s&&BigInt(s.acceptedCumulative)>l)throw Z(t,`Stored receipt exceeds the cumulative authorization.`);if(Date.parse(n.updatedAt)<Date.parse(n.createdAt))throw Z(t,`Stored session timestamps are not monotonic.`);let u=SF(n.endpoint,t);if(u!==n.endpoint)throw Z(t,`Stored session endpoint contains a fragment.`);let d=EF(n.challenge,t);return MF(d,lM(a),t),{...i,account:o,channel:a,endpoint:u,challenge:d,...s&&{receipt:s}}}function kF(e){return{version:1,status:e.status,channel:lM(e.channel),account:e.account,endpoint:e.endpoint,challenge:e.challenge,...e.receipt&&{receipt:e.receipt},spent:BigInt(e.spent),units:e.units,createdAt:e.createdAt,updatedAt:e.updatedAt}}function AF(e,t,n){let r=wF(t.channel),i=CF(t.account,n),a=lM(e.channel);if(JSON.stringify(jF(r))!==JSON.stringify(jF(a)))throw Z(n,`Session update changed immutable channel identity.`);if(i.address.toLowerCase()!==e.account.address.toLowerCase())throw Z(n,`Session update changed the payer account.`)}function jF(e){return{channelId:e.channelId.toLowerCase(),descriptor:Object.fromEntries(Object.entries(e.descriptor).map(([e,t])=>[e,typeof t==`string`?t.toLowerCase():t])),escrow:e.escrow.toLowerCase(),chainId:e.chainId}}function MF(e,t,n){if(xj({...t.descriptor,chainId:t.chainId,escrow:t.escrow}).toLowerCase()!==t.channelId.toLowerCase())throw Z(n,`Session channel ID does not match its descriptor.`);let r=yF(e.request.recipient,`challenge recipient`,n),i=yF(e.request.currency,`challenge currency`,n);if(r!==t.descriptor.payee.toLowerCase())throw Z(n,`Session challenge payee does not match the channel.`);if(i!==t.descriptor.token.toLowerCase())throw Z(n,`Session challenge token does not match the channel.`);if(Zj(e,t.escrow).toLowerCase()!==t.escrow.toLowerCase())throw Z(n,`Session challenge escrow does not match the channel.`);if(qF(e.request.methodDetails)){let r=e.request.methodDetails;if(r.chainId!==void 0&&r.chainId!==t.chainId)throw Z(n,`Session challenge chain does not match the channel.`)}}function NF(e,t,n){let r=bF(t);if(e.descriptor.payer.toLowerCase()!==r.payer||e.descriptor.payee.toLowerCase()!==r.payee||e.descriptor.token.toLowerCase()!==r.token||e.escrow.toLowerCase()!==r.escrow||e.chainId!==r.chainId)throw Z(n,`Session channel does not match the selected payment scope.`)}function PF(e,t){return e?t&&Date.parse(t.timestamp)>=Date.parse(e.timestamp)?t:e:t}function FF(e,t,n){if(!Number.isFinite(t.getTime()))throw Z(n,`Session clock is invalid.`);let r=t.toISOString();return!e||Date.parse(r)>=Date.parse(e)?r:e}function IF(...e){return e.reduce((e,t)=>t>e?t:e,0n)}async function LF(e){let t;try{t=await C.readFile(e,`utf8`)}catch(t){if(JF(t,`ENOENT`))return;throw Z(e,`Unable to read session state.`,t)}try{return JSON.parse(t)}catch(t){throw Z(e,`Session state contains invalid JSON.`,t)}}async function RF(e,t){await C.mkdir(c.dirname(e),{recursive:!0,mode:448}),await C.chmod(c.dirname(e),448);let n=`${e}.tmp-${process.pid}-${_()}`,r;try{r=await C.open(n,`wx`,384),await r.writeFile(`${JSON.stringify(t,null,2)}\n`,`utf8`),await r.sync(),await r.close(),r=void 0,await C.rename(n,e),await C.chmod(e,384),await GF(c.dirname(e))}catch(t){throw await r?.close().catch(()=>void 0),await C.unlink(n).catch(()=>void 0),t instanceof tF?t:Z(e,`Unable to write session state.`,t)}}async function zF(e,t){let n;try{n=await C.open(e,`wx`,384),await n.writeFile(`${JSON.stringify(t)}\n`,`utf8`),await n.sync(),await n.close(),n=void 0,await GF(c.dirname(e))}catch(t){throw await n?.close().catch(()=>void 0),n&&await C.unlink(e).catch(()=>void 0),t}}async function BF(e,t){let n=VF(e);try{await C.link(e,n)}catch(t){if(JF(t,`EEXIST`)||JF(t,`ENOENT`))return;throw Z(e,`Unable to claim dead lock.`,t)}try{let r=await LF(n);if(r===void 0||lF(cF,r,n,`Session lock is invalid.`).token!==t.token)return;await WF(e,`Unable to reclaim dead lock.`)}finally{await WF(n,`Unable to release dead lock claim.`)}}function VF(e){return`${e}.reclaim`}async function HF(e){try{return await C.access(e),!0}catch(t){if(JF(t,`ENOENT`))return!1;throw Z(e,`Unable to inspect session lock.`,t)}}async function UF(e,t){let n=await LF(e);n!==void 0&&lF(cF,n,e,`Session lock is invalid.`).token===t.token&&await WF(e,`Unable to release session lock.`)}async function WF(e,t){try{await C.unlink(e),await GF(c.dirname(e))}catch(n){if(!JF(n,`ENOENT`))throw Z(e,t,n)}}async function GF(e){let t=await C.open(e,`r`);try{await t.sync()}finally{await t.close()}}function KF(e){try{return process.kill(e,0),!0}catch(e){if(JF(e,`ESRCH`))return!1;if(JF(e,`EPERM`))return!0;throw e}}function qF(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function JF(e,t){return e instanceof Error&&`code`in e&&e.code===t}function Z(e,t,n){return new tF(t,{...n!==void 0&&{cause:n},file:e})}Ox(),yT(),aN(),SM(),Tj(),dk(),ZO();const YF=p.object({status:p.enum([`opening`,`open`,`closing`,`stale`]),channelId:p.string(),account:p.string().optional(),payer:p.string(),payee:p.string(),authorizedSigner:p.string(),token:p.string(),escrow:p.string(),chainId:p.number(),cumulativeAmount:p.string(),confirmedSpend:p.string(),deposit:p.string(),units:p.number(),resourceUrl:p.string(),createdAt:p.string(),updatedAt:p.string()}),XF=p.object({channelId:p.string(),status:p.enum([`closed`,`already-closed`]),spent:p.string(),txHash:p.string().optional()}),ZF=p.object({closed:p.array(XF),failed:p.array(p.object({channelId:p.string(),message:p.string()}))});function QF(e){return e===`mainnet`?ve.id:ye.id}function $F(e){if(e===ve.id)return`mainnet`;if(e===ye.id)return`testnet`}function eI(e){let t={};for(let n of e??[]){let e=n.indexOf(`:`);if(e===-1)throw new L({code:`INVALID_HEADER`,message:`Invalid header format: ${n}`,exitCode:2});t[n.slice(0,e).trim()]=n.slice(e+1).trim()}return t}function tI(e){return{status:e.status,channelId:e.channel.channelId,...e.account.name&&{account:e.account.name},payer:e.channel.descriptor.payer,payee:e.channel.descriptor.payee,authorizedSigner:e.channel.descriptor.authorizedSigner,token:e.channel.descriptor.token,escrow:e.channel.escrow,chainId:e.channel.chainId,cumulativeAmount:e.channel.cumulativeAmount.toString(),confirmedSpend:e.spent.toString(),deposit:e.channel.deposit.toString(),units:e.units,resourceUrl:e.endpoint,createdAt:e.createdAt,updatedAt:e.updatedAt}}function nI(e,t){throw e instanceof L?e:e instanceof nF?new L({code:e.code,message:e.message,exitCode:e.exitCode,cause:e}):e instanceof tF?new L({code:e.code,message:e.message,exitCode:65,cause:e}):new L({code:t,message:e instanceof Error?e.message:String(e),exitCode:75,...e instanceof Error&&{cause:e}})}async function rI(e,t){let n=await sk(t??e.account.name);if(!UM(n.account,e.channel.descriptor))throw new L({code:`SESSION_ACCOUNT_MISMATCH`,message:`Account ${n.account.address} cannot sign for session ${e.channel.channelId}.`,exitCode:2});return n}async function iI(e,t){if(t.network&&QF(t.network)!==e)throw new L({code:`CHAIN_MISMATCH`,message:`Session uses chainId ${e}, not ${t.network}.`,exitCode:2});let n=t.network??$F(e),r=LO(t.rpcUrl,{network:n}),i=await zO({network:n,rpcUrl:r});if(i.id!==e)throw new L({code:`CHAIN_MISMATCH`,message:`Session uses chainId ${e}, but RPC is chainId ${i.id}.`,exitCode:2});return M({chain:i,transport:le(r)})}const aI=cb(`sessions`,{description:`Manage persistent payment sessions (list, view, close)`}).command(`list`,{description:`List persistent payment sessions`,options:p.object({account:p.string().optional().describe(`Filter by account name`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Filter by Tempo network`)}),output:p.object({sessions:p.array(YF)}),alias:{account:`a`},async run(e){try{let t=(await fF().list()).filter(t=>!(e.options.account&&t.account.name!==e.options.account||e.options.network&&t.channel.chainId!==QF(e.options.network))).map(tI),n={sessions:t};if(e.format===`json`&&e.formatExplicit)return e.ok(n);t.length===0&&console.log(`No sessions.`);for(let[e,n]of t.entries())e>0&&console.log(``),oI(n);return}catch(e){return nI(e,`SESSION_LIST_FAILED`)}}}).command(`view`,{description:`View a persistent payment session`,args:p.object({channelId:p.string().describe(`Full session channel ID`)}),output:YF,async run(e){try{let t=await fF().get(e.args.channelId);if(!t)throw new L({code:`SESSION_NOT_FOUND`,message:`Session ${e.args.channelId} was not found.`,exitCode:2});let n=tI(t);if(e.format===`json`&&e.formatExplicit)return e.ok(n);oI(n);return}catch(e){return nI(e,`SESSION_VIEW_FAILED`)}}}).command(`close`,{description:`Cooperatively close persistent payment sessions`,usage:[{suffix:`<channel-id> [options]`},{suffix:`--all --yes [options]`}],args:p.object({channelId:p.string().optional().describe(`Full session channel ID`)}),options:p.object({account:p.string().optional().describe(`Account name`),all:p.boolean().optional().default(!1).describe(`Close every matching session`),header:p.array(p.string()).optional().describe(`Add close request header (repeatable)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),rpcUrl:p.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`),url:p.string().optional().describe(`Override the stored resource URL`),yes:p.boolean().optional().default(!1).describe(`Confirm closing every session`)}),output:p.union([XF,ZF]),alias:{account:`a`,header:`H`,rpcUrl:`r`},async run(e){if(e.options.all&&e.args.channelId)return e.error({code:`INVALID_SESSION_CLOSE`,message:`Specify a channel ID or --all, not both.`,exitCode:2});if(!e.options.all&&!e.args.channelId)return e.error({code:`INVALID_SESSION_CLOSE`,message:`Specify a channel ID or --all.`,exitCode:2});if(e.options.all&&!e.options.yes)return e.error({code:`CONFIRMATION_REQUIRED`,message:`Closing all sessions requires --yes.`,exitCode:2});if(e.options.all&&(e.options.header||e.options.rpcUrl||e.options.url))return e.error({code:`INVALID_SESSION_CLOSE`,message:`--header, --rpc-url, and --url only apply to a single session.`,exitCode:2});let t=fF();async function n(e,n={}){let r=await t.get(e);if(!r)throw new L({code:`SESSION_NOT_FOUND`,message:`Session ${e} was not found.`,exitCode:2});let i=dF(r.channel),a=await t.acquire(i);try{let r=await t.get(e);if(!r)throw new L({code:`SESSION_NOT_FOUND`,message:`Session ${e} was not found.`,exitCode:2});let a=await rI(r,n.account),o=await iI(r.channel.chainId,n);if(xj({...r.channel.descriptor,escrow:r.channel.escrow,chainId:r.channel.chainId}).toLowerCase()!==r.channel.channelId.toLowerCase())throw new L({code:`SESSION_STATE_INVALID`,message:`Stored descriptor does not derive the session channel ID.`,exitCode:65});if((await yM(o,r.channel.channelId,r.channel.escrow)).deposit===0n)return await t.remove(r.channel.channelId),{channelId:r.channel.channelId,status:`already-closed`,spent:r.spent.toString()};let s=SF(n.resourceUrl??r.endpoint),c={...a.source===`keychain`&&{name:a.accountName},address:a.account.address},l=(e=r.challenge)=>({status:`closing`,account:c,endpoint:s,challenge:e,...r.receipt&&{receipt:r.receipt},spent:r.spent,units:r.units}),u=await t.upsert({...l(),channel:r.channel}),d=eI(n.headers),f=u.challenge,p=await eF({channel:u.channel,challenge:u.challenge,fetch:async(e,t)=>globalThis.fetch(e,{...t,headers:{...d,...Mw(t?.headers)}}),input:s,spent:u.spent,async onChallenge(e){f=e,await t.upsert({...l(e),channel:u.channel})},manager:{account:a.account,client:o,channelStore:pF(t,{scope:i,selection:u.channel.channelId,context:()=>l(f)})}});return await t.remove(u.channel.channelId),{channelId:u.channel.channelId,status:`closed`,spent:p.receipt.spent,txHash:p.receipt.txHash}}finally{await a.release()}}try{if(e.options.all){let r=(await t.list()).filter(t=>(!e.options.account||t.account.name===e.options.account)&&(!e.options.network||t.channel.chainId===QF(e.options.network))),i=[],a=[];for(let t of r)try{i.push(await n(t.channel.channelId,{account:e.options.account,network:e.options.network}))}catch(e){a.push({channelId:t.channel.channelId,message:e instanceof Error?e.message:String(e)})}let o={closed:i,failed:a};if(a.length>0){for(let e of a)process.stderr.write(`${e.channelId}: ${e.message}\n`);process.exitCode=1}if(e.format===`json`&&e.formatExplicit)return e.ok(o);for(let e of i)console.log(`${e.channelId} ${e.status} ${e.spent}`);for(let e of a)console.log(`${e.channelId} failed ${e.message}`);return}let r=await n(e.args.channelId,{account:e.options.account,headers:e.options.header,network:e.options.network,resourceUrl:e.options.url,rpcUrl:e.options.rpcUrl});if(e.format===`json`&&e.formatExplicit)return e.ok(r);console.log(`${r.channelId} ${r.status} ${r.spent}`),r.txHash&&console.log(` transaction ${r.txHash}`);return}catch(e){return nI(e,`SESSION_CLOSE_FAILED`)}}});function oI(e){console.log(e.channelId),console.log(` status ${e.status}`),console.log(` cumulative amount ${e.cumulativeAmount}`),console.log(` confirmed spend ${e.confirmedSpend}`),console.log(` deposit ${e.deposit}`),console.log(` chain ${e.chainId}`),console.log(` payer ${e.payer}`),console.log(` payee ${e.payee}`),console.log(` token ${e.token}`),console.log(` resource ${e.resourceUrl}`)}Ox(),aN(),hN(),TN(),GE(),dk(),ZO();function sI(e,t){if(t&&e!==`auto`&&t.toLowerCase()!==e.toLowerCase())throw new L({code:`SESSION_SELECTION_CONFLICT`,message:`--session and -M channel= select different sessions.`,exitCode:2});let n=t??e;if(n===`auto`||n===`new`)return n;if(/^0x[0-9a-fA-F]{64}$/.test(n))return n.toLowerCase();throw new L({code:`INVALID_SESSION`,message:`Session must be auto, new, or a 32-byte channel ID.`,exitCode:2})}function cI(e){let t=e.allowCustomEscrow;if(t!==void 0){if(t===`true`)return!0;if(t===`false`)return!1;throw new L({code:`INVALID_ALLOW_CUSTOM_ESCROW`,message:`allowCustomEscrow must be true or false.`,exitCode:2})}}function lI(e,t,n,r){if(t.deposit!==void 0)return t.deposit;let i=e.request.suggestedDeposit;return typeof i==`string`?se(BigInt(i),r):n?`10`:void 0}function uI(e,t){if(!e)return;if(e.challengeId!==t.challenge.id)throw Error(`Session receipt challenge does not match the paid request.`);if(e.channelId.toLowerCase()!==t.channelId.toLowerCase())throw Error(`Session receipt channel does not match the selected channel.`);let n=BigInt(e.acceptedCumulative),r=BigInt(e.spent);if(n>t.cumulative)throw Error(`Session receipt exceeds the local cumulative authorization.`);if(r>n)throw Error(`Session receipt spend exceeds its accepted authorization.`);return e}function dI(e,t){return e.channel.channelId.toLowerCase()===t.toLowerCase()}function fI(e){if(e.trim()!==`[DONE]`){if(e.length===0){process.stdout.write(`
243
+ `);return}try{let t=JSON.parse(e);process.stdout.write(t.token??t.choices?.[0]?.delta?.content??e)}catch{process.stdout.write(e)}}}async function pI(e){let{options:t}=e,n=await sk(t.account),r=LO(t.rpcUrl,{network:t.network}),i=await zO({network:t.network,rpcUrl:r}),a=M({chain:i,transport:le(r)}),o=cI(e.methodOptions),s=await LM({allowCustomEscrow:o,challenge:e.challenge,getClient:async()=>a});if(s.chainId!==i.id)throw new L({code:`CHAIN_MISMATCH`,message:`Challenge requires chainId ${s.chainId}, but RPC is chainId ${i.id}.`,exitCode:2});let{decimals:c}=await UO(a,s.token,n.account.address,{requireDecimals:!0}),l={payer:n.account.address,payee:s.payee,token:s.token,escrow:s.escrow,chainId:s.chainId},u=sI(t.session,e.methodOptions.channel),d=e.registry??fF(),f=await d.acquire(l).catch(e=>{throw e instanceof nF?new L({code:e.code,message:e.message,exitCode:e.exitCode,cause:e}):e});try{let r=u===`auto`?await d.getPreferred(l):u===`new`?void 0:u,s=r?await d.get(r):void 0;if(r&&!s)throw new L({code:`SESSION_NOT_FOUND`,message:`Session ${r} was not found.`,exitCode:2});if(s&&u!==`auto`&&(s.status!==`open`||!s.channel.opened||uF(dF(s.channel))!==uF(l)||!UM(n.account,s.channel.descriptor)))throw new L({code:`SESSION_MISMATCH`,message:`Session ${s.channel.channelId} cannot be used for this account and challenge.`,exitCode:2});let f=s?.status===`open`&&s.channel.opened?s:void 0,p=f?`open`:`opening`,m=e.challenge,h=f?.receipt,g=f?.spent??0n,_=f?.units??0,v=SF(e.endpoint),y={...n.source===`keychain`&&{name:n.accountName},address:n.account.address},b=pF(d,{scope:l,selection:u,context:()=>({status:p,account:y,endpoint:v,challenge:m,...h&&{receipt:h},spent:g,units:_}),onNewChannel(){p=`opening`,h=void 0,g=0n,_=0}}),{signal:x,...S}=e.init,C={...S,...x&&{signal:x},onReceipt(e){h=e,g=g>BigInt(e.spent)?g:BigInt(e.spent),_=Math.max(_,e.units??0)}};if(e.challengeResponse.status!==402||e.challengeResponse.bodyUsed)throw Error(`Session manager requires an unconsumed 402 challenge response.`);let w=!0,T=wN({account:n.account,allowCustomEscrow:o,bootstrap:!1,client:a,channelStore:b,credentialContext:e.credentialContext,decimals:c,maxDeposit:lI(e.challenge,e.methodOptions,HO(i),c),fetch:async(t,n)=>w?(w=!1,e.challengeResponse):e.fetch(t,n)});f&&pN(T).rehydrate({channel:f.channel,challenge:e.challenge,input:e.fetchInput,spent:f.spent});let{onReceipt:ee,...E}=C,D=await T.fetch(e.fetchInput,E);if(t.fail&&D.status>=400)throw new L({code:`HTTP_ERROR`,message:`HTTP error ${D.status}`,exitCode:22});if(D.status===402)throw new L({code:`PAYMENT_REJECTED`,message:`Payment rejected.`,exitCode:75});EO(D,{include:!1,verbose:t.include?Math.max(t.verbose,2):t.verbose,silent:t.silent}),m=D.challenge??e.challenge;let O=T.channelId;if(!O)throw Error(`Session manager did not select a channel.`);if(h=uI(D.receipt,{challenge:m,channelId:O,cumulative:T.cumulative})??h,FE(D)){let t=pN(T).consumeSseResponse(e.fetchInput,D,{onReceipt:ee,signal:e.init.signal??void 0});for await(let e of t)fI(e)}else process.stdout.write(Buffer.from(await D.arrayBuffer()));let k=await d.get(O);if(!k||!dI(k,O))throw Error(`Session ${O} was not persisted.`);if(h){let e=uI(h,{challenge:m,channelId:O,cumulative:T.cumulative});if(!e)throw Error(`Session receipt validation failed.`);h=e,g=g>BigInt(e.spent)?g:BigInt(e.spent),_=Math.max(_,e.units??0),p=`open`}await d.upsert({status:p,channel:k.channel,account:y,endpoint:v,challenge:m,...h&&{receipt:h},spent:g,units:_}),t.silent||(e.info(`Session retained ${O}\n`),e.info(`Close with: mppx sessions close ${O}\n`))}finally{await f.release()}}ZO();function Q(e,t){return t?{label:e,detail:t,severity:`pass`}:{label:e,severity:`pass`}}function $(e,t,n){let r={label:e,severity:`fail`};return t&&(r.detail=t),n&&(r.hint=n),r}function mI(e,t,n){let r={label:e,severity:`warn`};return t&&(r.detail=t),n&&(r.hint=n),r}function hI(e,t,n){let r=t?{label:e,detail:t,severity:`skip`}:{label:e,severity:`skip`};return n&&(r.hint=n),r}const gI={pass:X.green(`✓`),fail:X.red(`✗`),warn:X.yellow(`⚠`),suggested:X.cyan(`◇`),skip:X.dim(`○`)};function _I(e){let t=gI[e.severity],n=e.detail?`${e.label} (${e.detail})`:e.label;console.log(` ${t} ${n}`),e.hint&&e.severity!==`pass`&&console.log(X.dim(` → ${e.hint}`))}function vI(e){console.log(`\n${X.bold(e)}`)}function yI(e,t){for(let n of e)_I(n),n.severity===`pass`?t.passed++:n.severity===`fail`?t.failed++:n.severity===`warn`?t.warnings++:n.severity===`suggested`?t.suggested++:n.severity===`skip`&&t.skipped++}async function bI(e,t,n=15e3){let r=new AbortController,i=setTimeout(()=>r.abort(),n);try{return await fetch(e,{...t,redirect:`error`,signal:r.signal})}finally{clearTimeout(i)}}function xI(e){return e<1024?`${e}B`:e<1048576?`${(e/1024).toFixed(1)}KB`:`${(e/1048576).toFixed(1)}MB`}const SI=new Set([`get`,`post`,`put`,`patch`,`delete`,`head`,`options`,`trace`]);function CI(e){return typeof e==`string`&&/^0x[0-9a-fA-F]{40}$/.test(e)}function wI(e){return typeof e==`string`&&/^(0|[1-9][0-9]*)$/.test(e)}function TI(e){let t=e.indexOf(`:`);if(t<1)return null;let n=e.slice(0,t).toLowerCase();if(!SI.has(n))return null;let r=e.slice(t+1);if(!r)return null;let i=r.startsWith(`/`)?r:`/`+r;return{method:n.toUpperCase(),path:i}}function EI(e,t){if(e){try{let n=JSON.parse(e);if(n&&typeof n==`object`&&!Array.isArray(n)){let e=Object.keys(n);if(e.length>0&&e.every(e=>e.startsWith(`/`))){let e=n[t];return e===void 0?void 0:typeof e==`string`?e:JSON.stringify(e)}}}catch{}return e}}function DI(e){if(!e)return{};let t={};for(let n of e){let e=n.indexOf(`:`);e>0&&(t[n.slice(0,e).trim().toLowerCase()]=n.slice(e+1).trim())}return t}async function OI(e){let t=new URL(`openapi.json`,e.replace(/\/?$/,`/`)).href;try{let e=await bI(t,{});if(!e.ok)return{error:`HTTP ${e.status}`};let n=await e.text();return{doc:JSON.parse(n),raw:n}}catch(e){return e instanceof DOMException&&e.name===`AbortError`?{error:`Request timed out after 15s`}:e instanceof SyntaxError?{error:`Invalid JSON`}:{error:e.message}}}async function kI(e){let t=new URL(`/llms.txt`,e).href,n=`llms.txt found and nonempty`;try{let e=await bI(t,{});if(!e.ok)throw Error(`HTTP ${e.status}`);let r=(await e.text()).trim();if(!r)throw Error(`Empty document`);let i=e.headers.get(`content-type`)?.split(`;`)[0]?.trim().toLowerCase();if(i&&!i.startsWith(`text/`)||i===`text/html`||/^<(?:!doctype html|html|head|body)\b/i.test(r))throw Error(`Expected text documentation, received non-text or HTML content`);return Q(n,t)}catch(e){return{label:n,detail:`${t}: ${e.message}`,severity:`suggested`,hint:`Serve nonempty text documentation at /llms.txt.`}}}function AI(e){let t=[],n=[],r=e.paths;if(!r)return[];for(let[e,i]of Object.entries(r)){let r=NI(i.parameters);for(let[a,o]of Object.entries(i)){if(!SI.has(a)||!o||typeof o!=`object`||Array.isArray(o))continue;let i=o,s=PI(r,NI(i.parameters)),c=s.length>0?s:void 0;if(i[`x-payment-info`]){let n=i[`x-payment-info`];t.push({method:a.toUpperCase(),path:e,amount:n.amount,parameters:c})}else{let t=i.responses;t&&`402`in t&&n.push({method:a.toUpperCase(),path:e,parameters:c})}}}return t.length>0?t:n}function jI(e,t){let n=e.paths;if(!n)return;let r=n[t.path];if(!r)return;let i=r[t.method.toLowerCase()];if(!i?.requestBody)return;let a=i.requestBody.content?.[`application/json`];if(!a)return;if(a.example)return JSON.stringify(a.example);if(a.examples&&typeof a.examples==`object`){let e=Object.values(a.examples)[0];if(e?.value)return JSON.stringify(e.value)}let o=a.schema,s=new Set;if(o=II(o,e,s),!o||o.type!==`object`)return;let c=LI(o,e,s);if(c&&typeof c==`object`&&Object.keys(c).length>0)return JSON.stringify(c)}function MI(e,t,n){if(!t.path.startsWith(`/`)||t.path.startsWith(`//`)||t.path.includes(`\\`))throw Error(`OpenAPI path must be an origin-relative path: ${t.path}`);let r=t.path;t.parameters&&(r=FI(r,t.parameters));let i=r.startsWith(`/`)?r.slice(1):r,a=new URL(e.replace(/\/?$/,`/`)),o=new URL(i,a);if(o.origin!==a.origin)throw Error(`OpenAPI path must be an origin-relative path: ${t.path}`);let s=o.href;if(n){let e=new URL(s);for(let t of n){let[n,...r]=t.split(`=`);n&&e.searchParams.set(n,r.join(`=`))}s=e.href}return s}function NI(e){if(!Array.isArray(e))return[];let t=[];for(let n of e){if(!n||typeof n!=`object`)continue;let e=n;e.in===`path`&&typeof e.name==`string`&&t.push(e.schema&&typeof e.schema==`object`?{name:e.name,in:`path`,schema:e.schema,example:e.example}:{name:e.name,in:`path`,example:e.example})}return t}function PI(e,t){let n=[...e];for(let e of t){let t=n.findIndex(t=>t.name===e.name);t>=0?n[t]=e:n.push(e)}return n}function FI(e,t){return e.replace(/\{([^}]+)\}/g,(e,n)=>{let r=t.find(e=>e.name===n&&e.in===`path`);if(!r)return e;let i=r.example??r.schema?.example??r.schema?.default;return i===void 0?e:encodeURIComponent(String(i))})}function II(e,t,n){if(!e||typeof e.$ref!=`string`)return e;if(n?.has(e.$ref))return;let r=e.$ref.replace(/^#\//,``).split(`/`),i=t;for(let e of r)if(i&&typeof i==`object`)i=i[e];else return;return i}function LI(e,t,n){let r=II(e,t,n)??e;if(r.const!==void 0)return r.const;if(r.example!==void 0)return r.example;if(r.default!==void 0)return r.default;switch(r.type){case`string`:return r.enum&&Array.isArray(r.enum)?r.enum[0]:r.format===`email`?`test@example.com`:r.format===`uuid`?`00000000-0000-0000-0000-000000000000`:r.format===`uri`||r.format===`url`?`https://example.com`:r.format===`date`?`2026-01-01`:r.pattern===`^\\d{5}(?:-\\d{4})?$`?`10001`:r.pattern===`^[A-Z]{2}$`?`US`:`test`;case`number`:case`integer`:return r.minimum??1;case`boolean`:return!0;case`array`:return[];case`object`:{let e=r.properties;if(!e)return{};let i=r.required||[],a={};for(let r of i){let i=e[r];i&&(a[r]=LI(i,t,n))}return a}default:return null}}_S(),Fx(),aw(),ZO();const RI=Object.values(Be);function zI(e){let t=e.request.methodDetails;return typeof t?.chainId==`number`&&RI.find(e=>e.id===t.chainId)?.testnet===!0}async function BI(e,t,n,r){let i=[],a;try{a=MI(e,t,r?.query)}catch(e){return i.push($(`Request URL valid`,e.message)),{results:i}}let o=DI(r?.extraHeaders),s;r?.body&&!r.bodyIsAutogenerated&&(s=r.body,o[`content-type`]||=`application/json`);let c;try{let e={method:t.method};Object.keys(o).length>0&&(e.headers=o),s&&(e.body=s),c=await bI(a,e)}catch(e){return i.push($(`Request failed`,e.message)),{results:i}}if(!s&&(c.status===400||c.status===422)){let e=r?.body??(r?.discoveryDoc?jI(r.discoveryDoc,t):void 0);if(e){n&&console.log(X.dim(` Retrying with body: ${e}`)),s=e,o[`content-type`]=`application/json`;try{c=await bI(a,{method:t.method,headers:o,body:s})}catch(e){return i.push($(`Request failed`,e.message)),{results:i}}}}if(c.status!==402)return c.status===200?i.push(hI(`Returns 402 without credentials`,`Got 200 (endpoint may not require payment in all cases)`)):c.status===401||c.status===403?i.push(hI(`Returns 402 without credentials`,`Got ${c.status} (endpoint requires auth before payment gate)`)):i.push($(`Returns 402 without credentials`,`Got ${c.status} instead`,c.status===400||c.status===422?`Server requires a valid request body before returning 402. Add a requestBody schema with examples to your OpenAPI doc, or use --body.`:`Endpoints that require payment must return HTTP 402 with a WWW-Authenticate: Payment header when no valid credential is provided.`)),{results:i};i.push(Q(`Returns 402 without credentials`));let l=c.headers.get(q.wwwAuthenticate),u=ZI(c);if(!l)return u.length>0?(i.push(hI(`Not an MPP endpoint`,`No WWW-Authenticate header — x402 protocol detected`)),i.push(...u)):i.push(hI(`Not an MPP endpoint`,`No WWW-Authenticate header (may be x402 or other protocol)`)),{results:i};if(u.length>0&&i.push(...u),!l.startsWith(`${Ax.payment} `))return i.push(hI(`Not an MPP endpoint`,`WWW-Authenticate scheme is not Payment`)),{results:i};i.push(Q(`WWW-Authenticate header present`,`Payment scheme`));let d;try{d=cS(c)}catch(e){let t=e.message;i.push($(`Challenge parseable`,t,`The Payment challenge must include a request="<base64url>" parameter containing JSON-encoded payment details.`));let n=l.slice(l.indexOf(` `)+1);return i.push(mI(`Received`,n.length>200?n.slice(0,200)+`...`:n)),{results:i}}if(d.length===0)return i.push($(`Challenge parseable`,`No Payment challenges found in header`)),{results:i};let f=d.map(e=>`${e.method}/${e.intent}`).join(`, `);i.push(Q(`Challenge parseable`,d.length===1?f:`${d.length} methods: ${f}`));let p=new URL(e).hostname;VI(d,i),HI(d,i),UI(d,i),WI(d,p,i);let m=d.length>1;for(let e of d){let t=e.request;GI(e,t,i,m)}if(n)for(let e of d)console.log(X.dim(` Challenge (${e.method}/${e.intent}): ${JSON.stringify(e,null,2)}`));return{results:i,resolvedBody:s,challenges:d}}function VI(e,t){let n=e.filter(e=>!e.id);n.length===0?t.push(Q(`Challenge has id`)):t.push($(`Challenge has id`,`${n.length} missing`,`Every challenge must include a unique id field.`))}function HI(e,t){let n=e.filter(e=>!e.realm);n.length===0?t.push(Q(`Challenge has realm`)):t.push($(`Challenge has realm`,`${n.length} missing`,`Set realm to your server's hostname.`))}function UI(e,t){let n=new Date;for(let r of e){if(!r.expires){t.push(mI(`Challenge has expiration`,`missing expires field`,`Add an expires field (ISO 8601) to prevent replay attacks.`));return}if(new Date(r.expires)<=n){t.push($(`Challenge expires in the future`,`Expired at ${r.expires}`,`The expires timestamp must be in the future.`));return}}let r=Math.min(...e.map(e=>new Date(e.expires).getTime()-n.getTime()));t.push(Q(`Challenge expires in the future`,`${Math.round(r/6e4)}m from now`))}function WI(e,t,n){let r=e=>e.toLowerCase().replace(/\.$/,``),i=r(t),a=[...new Set(e.map(e=>e.realm??``))].filter(e=>{let t=r(e);return!t||t!==i&&!i.endsWith(`.${t}`)});a.length>0?n.push($(`Realm matches server hostname`,`realm="${a[0]}" vs host="${t}"`,`Set the realm to your production hostname (or base domain) in the challenge.`)):n.push(Q(`Realm matches server hostname`))}function GI(e,t,n,r){let i=r?`[${e.method}] `:``;e.method===jx.tempo?KI(t,i,n,e):e.method===jx.stripe?qI(t,i,n):e.method===jx.evm&&JI(e,t,i,n)}function KI(e,t,n,r){let i=e.methodDetails,a=Array.isArray(i?.splits)&&i.splits.length>0;if(CI(e.recipient)?n.push(Q(`${t}Valid recipient address`)):e.recipient===void 0&&a?n.push(Q(`${t}Uses splits (no single recipient)`)):e.recipient===void 0?n.push($(`${t}Valid recipient address`,`Missing recipient (and no splits defined)`,`Set request.recipient to a valid 0x address, or use methodDetails.splits for multiple recipients.`)):n.push($(`${t}Valid recipient address`,`Got: ${String(e.recipient)}`,`Set request.recipient to a valid 0x-prefixed 40-hex-char address.`)),CI(e.currency)){let e=zI(r)?`testnet`:`mainnet`;n.push(Q(`${t}Valid currency address`,e))}else n.push($(`${t}Valid currency address`,`Got: ${String(e.currency)}`,`Set request.currency to a valid token address.`));YI(e,t,n,`token's smallest unit (e.g. "10000" = $0.01 for 6-decimal tokens)`)}function qI(e,t,n){YI(e,t,n,`currency's smallest unit (e.g. "100" = $1.00 for USD)`);let r=e.currency;typeof r==`string`&&/^[a-z]{3}$/i.test(r)?n.push(Q(`${t}Valid currency code`,r.toUpperCase())):n.push($(`${t}Valid currency code`,r?`Got: ${r}`:`missing`,`Must be a three-letter ISO currency code (e.g. "usd").`));let i=e.methodDetails,a=i?.networkId;a?n.push(Q(`${t}Has networkId`,a.slice(0,20))):n.push($(`${t}Has networkId`,`Missing methodDetails.networkId`,`Set methodDetails.networkId to your Stripe Business Network profile ID.`));let o=i?.paymentMethodTypes;Array.isArray(o)&&o.length>0?n.push(Q(`${t}Has paymentMethodTypes`,o.join(`, `))):n.push($(`${t}Has paymentMethodTypes`,`Missing or empty`,`Set methodDetails.paymentMethodTypes to an array (e.g. ["card"]).`))}function JI(e,t,n,r){if(CI(t.recipient)?r.push(Q(`${n}Valid recipient address`)):r.push($(`${n}Valid recipient address`,`Got: ${String(t.recipient)}`,`Set request.recipient to a valid 0x-prefixed Ethereum address.`)),CI(t.currency)){let t=zI(e)?`testnet`:`mainnet`;r.push(Q(`${n}Valid currency address`,t))}else r.push($(`${n}Valid currency address`,`Got: ${String(t.currency)}`,`Set request.currency to a valid ERC-20 token contract address.`));YI(t,n,r,`token's smallest unit`);let i=t.methodDetails?.chainId;typeof i==`number`&&i>0?r.push(Q(`${n}Has chainId`,String(i))):r.push($(`${n}Has chainId`,`Missing methodDetails.chainId`,`Set methodDetails.chainId to the EVM chain ID.`))}function YI(e,t,n,r){wI(e.amount)?n.push(Q(`${t}Amount is valid integer string`)):e.amount===void 0||e.amount===null?n.push($(`${t}Amount is valid integer string`,`Missing amount`,`Set request.amount to a string of digits in the ${r}.`)):n.push($(`${t}Amount is valid integer string`,`Got: ${String(e.amount)}`,`request.amount must be a string of digits (no decimals, no prefix).`))}async function XI(e,t,n){let r=[],i=MI(e,t,n?.query),a={[q.authorization]:`${Ax.payment} dGhpcyBpcyBnYXJiYWdl`},o;n?.body&&(o=n.body,a[`content-type`]=`application/json`);try{let e=await bI(i,{method:t.method,headers:a,body:o??null});e.status===402?(r.push(Q(`Malformed credential returns 402`,`not 500`)),e.headers.get(q.wwwAuthenticate)?.startsWith(`${Ax.payment} `)?r.push(Q(`Error response includes fresh challenge`)):r.push(mI(`Error response includes fresh challenge`,`No WWW-Authenticate header`,`When rejecting an invalid credential, respond with 402 and include a fresh WWW-Authenticate: Payment challenge so the client can retry.`))):e.status>=500?r.push($(`Malformed credential returns 402`,`Got ${e.status} (server error)`,`When the Authorization header contains an invalid credential, respond with 402 (not 500). Catch credential validation errors and return a fresh challenge.`)):r.push(mI(`Malformed credential returns 402`,`Got ${e.status}`,`When the Authorization header contains an invalid Payment credential, respond with 402 and a fresh WWW-Authenticate challenge. Returning ${e.status} prevents the client from retrying with a valid payment.`))}catch(e){r.push($(`Error handling test`,e.message))}return r}function ZI(e){let t=[],n=e.headers.get(`payment-required`)??e.headers.get(`x-payment-required`);if(!n)return t;let r=e.headers.get(`payment-required`)?`PAYMENT-REQUIRED`:`X-Payment-Required`;try{let e=QC(n);t.push(Q(`x402 payment challenge`,`${r} with valid x402 v${e.x402Version} payload`))}catch{t.push(mI(`x402 payment challenge`,`${r} header present but failed schema validation`,`Ensure the PAYMENT-REQUIRED header contains a valid base64-encoded JSON payload matching the x402 schema.`))}return t}const QI=[`No discovery document found, endpoints could not be automatically found.`,`MPP servers must serve an OpenAPI document at /openapi.json with x-payment-info extensions.`,`The MPP SDKs can automatically expose this endpoint. See https://mpp.dev/sdk.`,``,`To test a specific endpoint: mppx validate <url> --endpoint POST:/your/path`].join(`
244
+ `);Zx();const $I={fundingCurrency:J.optional(J.string()),method:J.string(),reference:J.string(),externalId:J.optional(J.string()),subscriptionId:J.optional(J.string()),status:J.literal(`success`),timestamp:Hx()};J.object($I);const eL=J.looseObject($I);function tL(e){let t=k.toString(e);return nL(JSON.parse(t))}function nL(e){return eL.parse(e)}_S(),Fx(),rP(),CO(),_O(),dk(),ZO();async function rL(e,t,n){try{n||console.log(X.dim(` Provisioning testnet wallet and funding via faucet...`));let t=he(),r=_e(t),i=M({chain:ye,transport:le()});if(FD(e)){let{chainId:t,operator:n}=e.request.methodDetails??{};if(t===ye.id&&typeof n==`string`&&ue(n)&&n!==me){let e=await Fe.faucet.fund(i,{account:n});await Promise.all(e.map(e=>Me(i,{hash:e})))}}let a=await Fe.faucet.fund(i,{account:r});await Promise.all(a.map(e=>Me(i,{hash:e}))),n||console.log(X.dim(` Using wallet: ${r.address}`));let o=e.request.currency;if(typeof o==`string`)for(let e=0;e<10;e++){let e=await Fe.token.getBalance(i,{account:r.address,token:o}).catch(()=>void 0);if(e&&e.amount>0n)break;await new Promise(e=>setTimeout(e,500))}return{methods:[...eP({account:r})]}}catch(e){t&&console.log(X.dim(` Provisioning failed: ${e.message}`));return}}async function iL(){let e=ik(),{isTempoAccount:t}=await Promise.resolve().then(()=>(ZO(),wO)),{resolveTempoAccount:n}=await Promise.resolve().then(()=>(LP(),iP));if(t(e)){let t=n(e);if(t)return t.wallet_address}try{return(await ck()).address}catch{return}}function aL(e){try{let{execSync:t}=m,n=t(`stripe config --list`,{encoding:`utf8`,timeout:5e3}).match(/test_mode_api_key\s*=\s*'([^']+)'/);if(n?.[1])return e&&console.log(X.dim(` Using Stripe test key from stripe CLI`)),n[1]}catch{}}async function oL(e,t,n){let r=M({chain:e,transport:le()}),[i,a,o]=await Promise.all([n?De(r,{address:t,abi:oe,functionName:`balanceOf`,args:[n]}):0n,De(r,{address:t,abi:oe,functionName:`decimals`}),De(r,{address:t,abi:oe,functionName:`symbol`}).catch(()=>void 0)]);return{balance:i,decimals:a,symbol:o??void 0}}function sL(e){return Object.values(Be).find(t=>t.id===e)}function cL(e,t){return`$${(Number(e)/10**t).toFixed(2)}`}function lL(e){switch(e.method){case jx.evm:return`no EVM payment plugin yet`;case`solana`:return`no Solana payment plugin yet`;default:return`no plugin for ${e.method}/${e.intent}`}}async function uL(e,t,n,r){let i=[],a=MI(e,t,r.query),o=DI(r.extraHeaders),s;r.body&&(s=r.body,o[`content-type`]=`application/json`);let c;try{c=await bI(a,{method:t.method,headers:o,body:s??null})}catch(e){return i.push($(`Payment: fetch challenge`,e.message)),i}if(c.status!==402)return i.push(hI(`Payment: skipped`,`Endpoint returned ${c.status}`)),i;let l;try{l=cS(c)}catch(e){return i.push($(`Payment: parse challenge`,e.message)),i}if(l.length===0)return i.push($(`Payment: parse challenge`,`No Payment challenges in response`)),i;let u=[];WI(l,new URL(a).hostname,u);let d=u.filter(e=>e.severity===`fail`);if(d.length>0)return i.push(...d),r.onResults?.(d),i;let f=await YP().catch(()=>void 0),p=l.find(e=>{if(e.method!==jx.tempo||qP(f?.config)?.some(t=>t.name===e.method&&t.intent===e.intent))return!1;let t=e.request.methodDetails;return typeof t?.chainId==`number`&&t.chainId!==vO.mainnet});if(p){let e=await rL(p,n,r.silent);if(e)try{await hL(i,await wT({methods:e.methods,polyfill:!1,async onChallenge(e,{createCredential:t}){ZP(p,e);let n=await t(await UP(e,f?.config.extensions));return i.push(Q(`Payment: submitted`,`ephemeral testnet wallet`)),n},fetch:(e,t)=>bI(e,t??{},3e4)}).fetch(a,{method:t.method,headers:o,body:s??null}),n,ye)}catch(e){i.push($(`Payment: create credential`,e.message))}else i.push($(`Payment: auto-provision wallet`,`Failed to create and fund testnet wallet`));r.onResults?.(i)}let m=r.interactive,h=process.env.MPPX_STRIPE_SECRET_KEY??aL(n),g=h?.startsWith(`sk_test_`)||h?.startsWith(`rk_test_`),_=new Set([jx.tempo,jx.evm,jx.stripe]);for(let e of l){if(e===p||!_.has(e.method))continue;r.silent||console.log(``);let c=i.length,l=()=>{r.onResults&&i.length>c&&r.onResults(i.slice(c))},u=`Payment [${e.method}]`;try{switch(e.method){case jx.tempo:case jx.evm:await dL(e,u,{results:i,url:a,endpoint:t,fetchHeaders:o,fetchBody:s,verbose:n,loaded:f,isInteractive:m,options:r});break;case jx.stripe:await fL(e,u,{results:i,url:a,endpoint:t,fetchHeaders:o,fetchBody:s,verbose:n,loaded:f,isInteractive:m,isStripeTestKey:g??!1,stripeKey:h,options:r})}}finally{l()}}return i}async function dL(e,t,n){let{results:r,url:i,endpoint:a,fetchHeaders:o,fetchBody:s,verbose:c,loaded:l,options:u}=n,d=e.request,f=d.methodDetails,p=wI(d.amount)?BigInt(d.amount):void 0,m=f?.decimals??d.decimals??6,h=d.currency,{plugin:g,method:_}=WP(e,l?.config);if(!g&&!_){r.push(hI(t,lL(e)));return}let v;if(!_){try{v=await iL()}catch{}if(!v){r.push(hI(t,`no wallet configured. Run "mppx account create" to create one.`));return}}let y;if(e.method===jx.tempo){let e=f?.chainId??(_?void 0:ve.id);e!==void 0&&(y=e===ye.id?ye:sL(e))}else if(e.method===jx.evm){let e=f?.chainId;e&&(y=sL(e))}if(p&&h&&!y){r.push(hI(t,`unable to resolve payment chain and verify token decimals`));return}let b;if(p&&h&&y)try{let n;if(e.method===jx.tempo){let e=await UO(M({chain:y,transport:le()}),h,v??me,{requireDecimals:!0});n=e.balance,m=e.decimals,b=e.symbol}else{let e=await oL(y,h,v);n=e.balance,m=e.decimals,b=e.symbol}if(v&&n<p){let e=cL(p,m),i=cL(n,m),a=b??`tokens`;r.push(hI(t,`insufficient balance (have ${i}, need ${e} ${a} on ${y.name})`,`Fund wallet ${v} with at least ${e} ${a} on ${y.name}.`));return}}catch(e){c&&console.log(X.dim(` Balance check skipped: ${e.message}`)),r.push(hI(t,`unable to verify token balance and decimals from the payment chain`));return}let x=p?cL(p,m):`unknown amount`,S=b??(h?.length===3?h.toUpperCase():``),C=y?.name,w=`${x}${S?` ${S}`:``}${C?` on ${C}`:``}`;if(u.silent||console.log(X.dim(v?` Attempting payment with wallet ${v}`:` Attempting payment with configured method`)),!_&&y?.testnet)u.silent||console.log(X.dim(` Auto-approved: ${w} (testnet)`));else if(!u.yes&&!n.isInteractive){r.push(hI(t,`non-interactive mode, use --yes to approve`));return}else if(u.yes)u.silent||console.log(X.dim(` Auto-approved: ${w}`));else if(!await FO(` ${X.yellow(`Pay`)} ${w}. Continue?`,!1)){r.push(hI(t,`declined`));return}let T,ee,E;if(g)try{let t=await g.setup({challenge:e,options:{network:`mainnet`},methodOpts:{}});T=t.methods,ee=t.createCredential,E=t.credentialContext}catch(e){r.push(hI(t,e.message));return}else T=[_];if(_&&FD(e)){let n=!0,u=wT({methods:[_],polyfill:!1,async onChallenge(n,{createCredential:i}){let a=await UP(n,l?.config.extensions);ZP(e,n);let o=await i(a);return r.push(Q(`${t}: submitted`)),o},fetch:async(t,r)=>n?(n=!1,new Response(null,{status:402,headers:{[q.wwwAuthenticate]:$x(e)}})):bI(t,r??{},3e4)});try{await hL(r,await u.fetch(i,{method:a.method,headers:o,body:s??null}),c,y)}catch(e){r.push($(t,e.message))}return}let D=await pL(e,T,ee,t,r,l?.config.extensions,E);D&&(g?.prepareCredentialRequest?.({challenge:e,credential:D,headers:o}),await mL(r,i,a,D,o,s,c,y,fS(e)))}async function fL(e,t,n){let{results:r,url:i,endpoint:a,fetchHeaders:o,fetchBody:s,verbose:c,loaded:l,options:u,stripeKey:d}=n,{plugin:f,method:p}=WP(e,l?.config);if(!f&&!p){r.push(hI(t,`no Stripe payment method available`));return}let m=!!(f&&!l?.config.plugins?.includes(f)&&n.isStripeTestKey),h=e.request,g=wI(h.amount)?BigInt(h.amount):void 0,_=h.decimals??2,v=h.currency,y=g?cL(g,_):`unknown amount`,b=v?.length===3?v.toUpperCase():``,x=`${y}${b?` ${b}`:``} via Stripe${m?` (testmode)`:``}`;if(m)u.silent||console.log(X.dim(` Attempting: ${x}`));else if(!u.yes&&!n.isInteractive){r.push(hI(t,`non-interactive mode, use --yes to approve`));return}else if(u.yes)u.silent||console.log(X.dim(` Auto-approved: ${x}`));else if(!await FO(` ${X.yellow(`Pay`)} ${x}. Continue?`,!1)){r.push(hI(t,`declined`));return}let S,C,w;if(f)try{let t={paymentMethod:`pm_card_visa`};d&&(t.secretKey=d);let n=await f.setup({challenge:e,options:{},methodOpts:t});S=n.methods,C=n.createCredential,w=n.credentialContext}catch(e){r.push(hI(t,e.message));return}else S=[p];let T=await pL(e,S,C,t,r,l?.config.extensions,w);if(T){if(f?.prepareCredentialRequest?.({challenge:e,credential:T,headers:o}),m){let n=await bI(i,{method:a.method,headers:{...o,[fS(e)]:T},body:s??null},3e4);n.status>=200&&n.status<300?r.push(Q(`${t}: successful`,`HTTP ${n.status}`)):r.push(hI(`${t}: server is in livemode`,void 0,`Run your server with a Stripe test key to automatically validate Stripe payments in testmode.`));return}await mL(r,i,a,T,o,s,c,void 0,fS(e))}}async function pL(e,t,n,r,i,a,o){let s=new Response(null,{status:402,headers:{[q.wwwAuthenticate]:$x(e)}});try{let c=await UP(e,a,o),l;return l=n?await n(s,c):await wT({methods:t,polyfill:!1}).createCredential(s,c),i.push(Q(`${r}: submitted`)),l}catch(e){let t=e.message;t.toLowerCase().includes(`insufficient`)?i.push(hI(r,`insufficient balance: ${t}`)):i.push($(r,t));return}}async function mL(e,t,n,r,i,a,o,s,c=q.authorization){let l;try{l=await bI(t,{method:n.method,headers:{...i,[c]:r},body:a??null},3e4)}catch(t){return e.push($(`Payment: send credential`,t.message)),e}return hL(e,l,o,s)}async function hL(e,t,n,r){if(t.status===402){let n=await t.text().catch(()=>``),r=`Payment rejected`;try{let e=JSON.parse(n);r=e.detail??e.title??r}catch{}return e.push($(`Payment: accepted`,r,`The server rejected a valid credential. Check that your payment verification logic accepts the credential format and that the payment was processed on-chain.`)),e}if(t.status>=400&&t.status<500)e.push(mI(`Payment: post-payment response`,`Got ${t.status}`,`Payment succeeded but the endpoint returned a client error. The endpoint likely requires request body parameters. Use --body to provide them.`));else if(t.status>=500)return e.push($(`Payment: server response`,`Got ${t.status}`,`Payment was accepted but the server errored while generating the response. Check server logs for the underlying error.`)),e;else e.push(Q(`Payment: successful`,`HTTP ${t.status}`));let i=t.headers.get(q.paymentReceipt);if(!i)e.push($(`Payment-Receipt header present`,void 0,`After accepting payment, include a Payment-Receipt header with a base64url-encoded JSON object containing: method, reference, status ("success"), and timestamp (ISO 8601).`));else{e.push(Q(`Payment-Receipt header present`));try{let t=tL(i);if(e.push(Q(`Receipt parseable`)),t.status===`success`?e.push(Q(`Receipt status is "success"`)):e.push($(`Receipt status is "success"`,`Got: ${t.status}`)),t.reference){let n=/^0x[0-9a-fA-F]{64}$/.test(t.reference),r=t.reference.startsWith(`pi_`);n||r?e.push(Q(`Receipt reference valid`,t.reference.slice(0,20)+`...`)):e.push(mI(`Receipt reference format`,t.reference.slice(0,40)))}else e.push(mI(`Receipt has reference`,`No reference field`));if(t.timestamp){let n=new Date(t.timestamp),r=Date.now()-n.getTime();r<6e4?e.push(Q(`Receipt timestamp recent`,`${Math.round(r/1e3)}s ago`)):e.push(mI(`Receipt timestamp recent`,`${Math.round(r/6e4)}m ago`))}n&&console.log(X.dim(` Receipt: ${JSON.stringify(t,null,2)}`))}catch(t){e.push($(`Receipt parseable`,t.message))}}let a=t.headers.get(`content-type`)??``,o=await t.text().catch(()=>``);if(o.length>0)e.push(Q(`Response body non-empty`,`${a.split(`;`)[0]}, ${xI(o.length)}`));else{let n=[...t.headers.entries()].filter(([e])=>!e.startsWith(`x-`)&&![`content-type`,`content-length`,`date`,`server`,`connection`,`keep-alive`,`cache-control`,`vary`,`access-control-allow-origin`,`payment-receipt`,`payment-session`,`payment-session-snapshot`].includes(e.toLowerCase()));n.length>0?e.push(mI(`Response body empty -- data may be in headers only`,n.map(([e])=>e).join(`, `))):e.push(mI(`Response body empty`))}if(a?e.push(Q(`Content-Type header set`,a.split(`;`)[0])):e.push(mI(`Content-Type header set`)),i)try{let t=tL(i);if(t.reference&&/^0x[0-9a-fA-F]{64}$/.test(t.reference)){let n=r?.blockExplorers?.default?.url;if(n){let r=n.includes(`tempo`)?`receipt`:`tx`;e.push(Q(`On-chain transaction`,`${n}/${r}/${t.reference}`))}}}catch{}return e}async function*gL(e){let t=e.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``),n=e.verbose??!1,r=await xL(t,e);yield{phase:`discovery`,discovery:r,results:r.checks};for(let i of r.endpoints){yield{phase:`endpoint`,endpoint:i};let a,o=!1;e.endpoint?a=e.body:(a=EI(e.body,i.path),!a&&r.doc&&(a=jI(r.doc,i),o=!!a));let{results:s,resolvedBody:c,challenges:l}=await BI(t,i,n,{body:a,bodyIsAutogenerated:o,query:e.query,extraHeaders:e.headers,discoveryDoc:r.doc??void 0}),u=c??a,d=s.some(e=>e.severity===`pass`&&e.label===`Challenge parseable`),f=!s.some(e=>e.severity===`fail`),p=(l??[]).filter(e=>e.method!==`stripe`).map(e=>e.request.methodDetails?.chainId).filter(e=>typeof e==`number`),m=p.some(bL),h=p.some(e=>!bL(e)),g=!d&&s.some(e=>e.label===`Not an MPP endpoint`),_=s.some(e=>e.severity===`pass`&&e.label===`WWW-Authenticate header present`),v=s.some(e=>e.severity===`fail`&&e.label===`Challenge parseable`);if(yield{phase:`challenge`,endpoint:i,results:s,isMpp:d,isTestnet:m,isMainnet:h,isNonMppPayment:g,isMalformedChallenge:!d&&_&&v,methods:l?.map(e=>e.method)??[]},d&&(yield{phase:`errorHandling`,endpoint:i,results:await XI(t,i,{body:u,query:e.query})},!e.skipPayment&&f)){let r=e.onPaymentResults,a=await uL(t,i,n,{body:u,query:e.query,extraHeaders:e.headers,yes:e.yes,silent:!r,interactive:e.interactive,...r&&{onResults:r}});yield{phase:`payment`,endpoint:i,results:a,succeeded:a.some(e=>e.severity===`pass`&&e.label===`Payment: successful`)}}}}async function _L(e){let t=e.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``),n,r=[],i,a=!1,o=!1;for await(let t of gL(e))switch(t.phase){case`discovery`:n=t.discovery;break;case`endpoint`:i={method:t.endpoint.method,path:t.endpoint.path,challenge:[],errorHandling:[],payment:[]},r.push(i);break;case`challenge`:i&&(i.challenge=t.results),t.isMpp&&(t.isTestnet&&(a=!0),t.isMainnet&&(o=!0));break;case`errorHandling`:i&&(i.errorHandling=t.results);break;case`payment`:i&&(i.payment=t.results)}let s={passed:0,failed:0,warnings:0,suggested:0,skipped:0};if(n)for(let e of n.checks)e.severity===`pass`?s.passed++:e.severity===`fail`?s.failed++:e.severity===`warn`?s.warnings++:e.severity===`suggested`?s.suggested++:e.severity===`skip`&&s.skipped++;for(let e of r)for(let t of[...e.challenge,...e.errorHandling,...e.payment])t.severity===`pass`?s.passed++:t.severity===`fail`?s.failed++:t.severity===`warn`?s.warnings++:t.severity===`suggested`?s.suggested++:t.severity===`skip`&&s.skipped++;if(!n)throw Error(`Discovery phase did not complete`);let c=vL(r,n,{sawTestnet:a,sawMainnet:o});return{url:t,discovery:n,endpoints:r,summary:s,suggestions:c}}function vL(e,t,n){let r=[],i=e.flatMap(e=>[...e.challenge,...e.payment]);t.found||r.push(QI);let a=n.sawMainnet,o=n.sawTestnet,s=i.some(e=>e.label.includes(`[stripe]`)&&e.label.includes(`livemode`));return a&&!o?r.push(`Validate your testnet server to test without real funds (Tempo wallets are automatically provisioned).`):o&&!a&&r.push(`Validate your mainnet server to confirm real payments work end-to-end.`),s&&r.push(`Validate your testmode Stripe server to test card payments end-to-end (auto-pays with test card).`),r}const yL=Object.values(Be);function bL(e){return yL.find(t=>t.id===e)?.testnet===!0}async function xL(e,t){let n=[],r=[],i=null,a=!1,o=!1;n.push(await kI(e));let s=new URL(e).origin,c;t.discoveryPath?c=[new URL(t.discoveryPath,e+`/`).href.replace(/\/openapi\.json$/i,``)]:(c=[e,s,`${s}/api`],c=[...new Set(c)]);let l,u=[];for(let e of c)if(l=await OI(e),`error`in l)u.push(`${e}/openapi.json: ${l.error}`);else break;if(!l||`error`in l)n.push({label:`Document found`,detail:u.join(`; `),hint:`MPP servers must serve an OpenAPI document at /openapi.json with x-payment-info extensions.`,severity:`fail`});else{a=!0,n.push({label:`Document found and parseable`,severity:`pass`});let e=rE(l.doc),t=e.filter(e=>e.severity===`error`),r=e.filter(e=>e.severity===`warning`);if(t.length>0){n.push({label:`Valid OpenAPI structure`,detail:`${t.length} error(s)`,severity:`fail`});for(let e of t)n.push({label:e.message,detail:e.path,severity:`fail`})}else o=!0,n.push({label:`Valid OpenAPI structure`,severity:`pass`});for(let e of r)n.push({label:e.message,detail:e.path,severity:`warn`});i=l.doc}if(t.endpoint){let e=TI(t.endpoint);e&&r.push(e)}else if(i){r=AI(i);let e=BigInt(`999999999999999999`);r.sort((t,n)=>{let r=wI(t.amount)?BigInt(t.amount):e,i=wI(n.amount)?BigInt(n.amount):e;return r<i?-1:+(r>i)}),r.length>0?n.push({label:`Paid endpoints found`,detail:`${r.length} endpoint(s)`,severity:`pass`}):n.push({label:`Paid endpoints found`,detail:`No endpoints with x-payment-info`,severity:`warn`})}return{found:a,valid:o,endpoints:r,checks:n,doc:i}}Ox(),ZO();const SL=cb(`validate`,{description:`Validate an MPP server implementation end-to-end`,args:p.object({url:p.string().describe(`Base URL of the MPP server to validate`)}),options:p.object({endpoint:p.string().optional().describe(`Endpoint to test (METHOD:path). Skips discovery.`),body:p.string().optional().describe(`Request body. With --endpoint, used directly. In discovery mode, JSON with / keys is a per-path mapping.`),query:p.array(p.string()).optional().describe(`Query parameter (key=value, repeatable)`),header:p.array(p.string()).optional().describe(`Request header (key:value, repeatable)`),verbose:p.number().default(0).meta({count:!0}).describe(`Verbosity level`),yes:p.boolean().default(!1).describe(`Auto-approve mainnet payments`),outputJson:p.boolean().default(!1).describe(`Output results as JSON (auto-enabled in known agent environments)`)}),alias:{endpoint:`e`,header:`H`,verbose:`v`,yes:`y`,outputJson:`j`},async run(e){if(e.options.outputJson||MO()){let t=await _L({url:e.args.url,endpoint:e.options.endpoint,body:e.options.body,query:e.options.query,headers:e.options.header,verbose:e.options.verbose>0,yes:e.options.yes,interactive:!1});console.log(JSON.stringify(t,null,2));let n=t.endpoints.length===0&&!e.options.endpoint;(t.summary.failed>0||!t.discovery.found||n)&&process.exit(1);return}let t=e.args.url.replace(/\/$/,``).replace(/\/openapi\.json$/i,``);console.log(`\n${X.bold(`mppx validate`)} ${X.dim(t)}\n`);let n={passed:0,failed:0,warnings:0,suggested:0,skipped:0},r=!1,i=!1,a=!1,o=!1,s=!1,c=!1,l=!1,u=0;for await(let t of gL({url:e.args.url,endpoint:e.options.endpoint,body:e.options.body,query:e.options.query,headers:e.options.header,verbose:e.options.verbose>0,yes:e.options.yes,interactive:!!process.stdin.isTTY,onPaymentResults:e=>yI(e,n)}))switch(t.phase){case`discovery`:if(vI(`Discovery (/openapi.json)`),yI(t.results,n),l=t.discovery.found,!l&&!e.options.endpoint){console.log(``);let[e,...t]=QI.split(`
245
+ `);console.log(X.yellow(` ${e}`));for(let e of t)console.log(e?X.dim(` ${e}`):``);console.log(``),process.exit(1)}t.discovery.endpoints.length===0&&!e.options.endpoint&&l&&(console.log(X.dim(` Use --endpoint to specify endpoints manually.`)),console.log(``),process.exit(1));break;case`endpoint`:u++,vI(`${t.endpoint.method} ${t.endpoint.path}`);break;case`challenge`:console.log(X.dim(` Challenge`)),yI(t.results,n),t.isMpp&&(r=!0,t.isTestnet&&(o=!0),t.isMainnet&&(s=!0)),t.isNonMppPayment&&(i=!0),t.isMalformedChallenge&&(a=!0);break;case`errorHandling`:console.log(X.dim(` Error Handling`)),yI(t.results,n);break;case`payment`:t.succeeded&&(c=!0)}CL(n,{sawMppEndpoint:r,sawNonMppPaymentEndpoint:i,sawMalformedChallenge:a,sawTestnet:o,sawMainnet:s,paymentSucceeded:c},u)}});function CL(e,t,n){!t.sawMppEndpoint&&n>0&&(console.log(``),t.sawMalformedChallenge?(console.log(X.yellow(` Payment scheme detected but challenge format is invalid on ${n} endpoint(s).`)),console.log(X.dim(` The server uses WWW-Authenticate: Payment but the challenge parameters do not conform to MPP.`)),console.log(X.dim(` Fix: encode payment details as base64url JSON in a request="..." parameter. See errors above.`))):t.sawNonMppPaymentEndpoint?(console.log(X.yellow(` No MPP endpoints found. Tested ${n} endpoint(s) but none use WWW-Authenticate: Payment.`)),console.log(X.dim(` This server may use x402 or another payment protocol.`))):e.skipped>0&&e.failed===0?(console.log(X.yellow(` Could not reach payment gate on any endpoint (all returned 401/403/200).`)),console.log(X.dim(` The server may require authentication before payment. Try providing auth or use --endpoint with a public path.`))):(console.log(X.yellow(` No MPP endpoints found. Tested ${n} endpoint(s) but none use WWW-Authenticate: Payment.`)),console.log(X.dim(` This server may use x402 or another payment protocol.`))),console.log(``),process.exit(1)),console.log(``);let r=[];e.passed>0&&r.push(X.green(`${e.passed} passed`)),e.failed>0&&r.push(X.red(`${e.failed} failed`)),e.warnings>0&&r.push(X.yellow(`${e.warnings} warning(s)`)),e.suggested>0&&r.push(X.cyan(`${e.suggested} suggested`)),e.skipped>0&&r.push(X.yellow(`${e.skipped} skipped`)),console.log(`${X.bold(`Summary:`)} ${r.join(`, `)}`),t.paymentSucceeded&&t.sawTestnet&&!t.sawMainnet?(console.log(``),console.log(X.dim(` Tip: also validate your mainnet server to confirm real payments work end-to-end.`))):t.sawMainnet&&!t.sawTestnet&&(console.log(``),console.log(X.dim(` Tip: also validate your testnet server for free. This CLI automatically provisions and funds a testnet wallet for testing.`))),console.log(``),e.failed>0&&process.exit(1)}function wL(e){return EL(e)?e.offers:[e]}function TL(e){let{_canonicalRequest:t,intent:n,name:r}=e,i=t.methodDetails??{},a=DL(t.amount)??DL(i.amount)??null,o=DL(t.currency)??DL(i.currency),s=DL(e.description)??DL(t.description),c={amount:a,...o?{currency:o}:{},...s?{description:s}:{},intent:n,method:r},l=new Set([`amount`,`currency`,`description`,`methodDetails`]);for(let[e,n]of Object.entries(t))!l.has(e)&&n!==void 0&&(c[e]=n);return c}function EL(e){return`offers`in e&&!(`_canonicalRequest`in e)}function DL(e){return typeof e==`string`?e:void 0}var OL=I((()=>{})),kL=Ze({generate:()=>AL,generateProxy:()=>jL});function AL(e,t){let n=e.methods,r=new Map,i={};for(let e of n)r.set(`${e.name}/${e.intent}`,e),i[e.intent]=(i[e.intent]??0)+1;for(let e of n)i[e.intent]===1&&r.set(e.intent,e);let a=t.routes.map(e=>NL(e,r));return ML({info:{title:t.info?.title??e.realm,version:t.info?.version??`1.0.0`},routes:a,serviceInfo:t.serviceInfo})}function jL(e){let t=e.routes.map(t=>({...t,path:PL(e.basePath,t.path)}));return ML({info:{title:e.info?.title??`API Proxy`,version:e.info?.version??`1.0.0`},routes:t,serviceInfo:e.serviceInfo})}function ML(e){let t={};for(let n of e.routes){let e=n.method.toLowerCase(),r={responses:{...n.payment?{402:{description:`Payment Required`}}:{},200:{description:`Successful response`}}};n.payment&&(r[`x-payment-info`]=XT.parse(n.payment)),n.summary&&(r.summary=n.summary),n.requestBody&&(r.requestBody=n.requestBody),t[n.path]||(t[n.path]={}),t[n.path][e]=r}let n={info:e.info,openapi:`3.1.0`,paths:t};return e.serviceInfo&&(n[`x-service-info`]=e.serviceInfo),n}function NL(e,t){if(`handler`in e){let t=e.handler._internal;if(!t)throw Error(`Route ${e.method.toUpperCase()} ${e.path} is missing discovery metadata`);return{method:e.method,path:e.path,payment:{offers:wL(t).map(TL)},...e.requestBody?{requestBody:e.requestBody}:{},...e.summary?{summary:e.summary}:{}}}let n=t.get(e.intent);if(!n)throw Error(`Unknown intent "${e.intent}" for route ${e.method.toUpperCase()} ${e.path}. Available: ${[...t.keys()].join(`, `)}`);let{description:r,...i}=e.options,a={_canonicalRequest:Lx(n,i),...typeof r==`string`?{description:r}:{},intent:n.intent,name:n.name};return{method:e.method,path:e.path,payment:TL(a),...e.requestBody?{requestBody:e.requestBody}:{},...e.summary?{summary:e.summary}:{}}}function PL(e,t){if(!e)return t;let n=e.startsWith(`/`)?e:`/${e}`;return`${n.endsWith(`/`)?n.slice(0,-1):n}${t}`}var FL=I((()=>{zx(),nE(),OL()}));Ox(),_S(),yT(),JC(),sw(),uw(),Fx(),_O(),aw(),OS(),AC(),dk(),ZO();const IL=`0.13.6`,LL=p.object({address:p.string(),isDefault:p.boolean().optional(),name:p.string(),source:p.string().optional()}),RL=p.object({address:p.string(),balances:p.array(p.string()).optional(),name:p.string(),type:p.string().optional()}),zL=p.object({message:p.string(),path:p.string(),severity:p.string()}),BL=p.object({description:p.string().optional(),id:p.string(),name:p.string().optional(),paidEndpoints:p.number(),status:p.string().optional(),url:p.string().optional()}),VL=p.object({description:p.string().optional(),method:p.string(),path:p.string(),payment:p.unknown().optional()});function HL(e){return e.format===`json`&&e.formatExplicit}function UL(e,t,n){if(HL(e))return e.ok(t);n()}async function WL(t){if(!t.body)return;let n=t.body.getReader();try{for(;;){let{done:t,value:r}=await n.read();if(t)break;process.stdout.write(Buffer.from(r))||await e(process.stdout,`drain`)}}finally{n.releaseLock()}}function GL(){return process.stdin.isTTY===!1&&process.stdin.listenerCount(`data`)===0&&process.stdin.listenerCount(`readable`)===0}function KL(e){return typeof e==`string`?e:void 0}function qL(e){return Array.isArray(e.endpoints)?e.endpoints.filter(e=>typeof e==`object`&&!!e):[]}function JL(e){let t=qL(e);return{...KL(e.description)?{description:KL(e.description)}:{},id:KL(e.id)??KL(e.name)??`unknown`,...KL(e.name)?{name:KL(e.name)}:{},paidEndpoints:t.filter(e=>e.payment).length,...KL(e.status)?{status:KL(e.status)}:{},...KL(e.serviceUrl)||KL(e.url)?{url:KL(e.serviceUrl)??KL(e.url)}:{}}}function YL(e){return{...KL(e.description)?{description:KL(e.description)}:{},method:KL(e.method)??`GET`,path:KL(e.path)??`/`,...e.payment===void 0?{}:{payment:e.payment}}}function XL(e){if(!e)return`free`;if(typeof e!=`object`)return String(e);let t=e,n=KL(t.amount),r=KL(t.currency),i=KL(t.method),a=KL(t.intent);return[n,r,i&&a?`${i}/${a}`:i??a].filter(Boolean).join(` `)}function ZL(e){return e.request.currency??e.request.asset}function QL(e,t){if(!t)return[...e];let n=t.toLowerCase();return e.filter(e=>{let t=ZL(e);return typeof t==`string`&&t.toLowerCase()===n})}async function $L(e,t,n={}){let r=()=>qC().getChallenges(e),i=()=>ow().getChallenges(n.ignoreX402ResponseUrl?new Response(null,{headers:e.headers,status:e.status}):e);if(t===`mpp`)return r();if(t===`x402`)return i();let a=[],o;try{a=await r()}catch(e){o=e}let s=[],c;try{s=await i()}catch(e){c=e}if(a.length||s.length)return[...a,...s];if(o)throw o;if(c)throw c;return[]}function eR(e){return cw({name:`selected-challenge`,isPaymentRequired:e=>e.status===402,getChallenges:()=>[e],setCredential:e=>e})}function tR(e,t){if(!ES(e))return new Response(null,{status:402,headers:{[q.wwwAuthenticate]:$x(e)}});let n=e.request;return n.resource?new Response(null,{status:402,headers:{[fC]:nw({accepts:[sC(n)],...n.extensions&&{extensions:n.extensions},resource:n.resource,x402Version:2})}}):t}function nR(e){let{host:t,hostname:n}=new URL(e);return!n.endsWith(`.localhost`)||n===`localhost`?{url:e}:{host:t,url:e.replace(n,`127.0.0.1`)}}async function rR(e,t,n,r){let i=t,a=nR(i),o={...n,redirect:`manual`,headers:Mw(n.headers)};a.host&&oR(o.headers,a.host);for(let t=0;t<=20;t++){let n=await e(a.url,o),s=n.headers.get(`location`);if(!r||!s||![301,302,303,307,308].includes(n.status))return{init:o,logicalUrl:i,response:n,target:a};if(t===20)throw TypeError(`Too many redirects`);await n.body?.cancel().catch(()=>{});let c=new URL(s,i),l=new URL(i),u=Mw(o.headers);if(c.origin!==l.origin)for(let e of[`authorization`,`cookie`,`host`,`proxy-authorization`])for(let t of Object.keys(u))t.toLowerCase()===e&&delete u[t];let d=(o.method??(o.body?`POST`:`GET`)).toUpperCase(),f=n.status===303&&d!==`GET`&&d!==`HEAD`||(n.status===301||n.status===302)&&d===`POST`;if(f)for(let e of[`content-encoding`,`content-language`,`content-length`,`content-location`,`content-type`])for(let t of Object.keys(u))t.toLowerCase()===e&&delete u[t];i=c.href,a=nR(i),a.host&&oR(u,a.host);let p={...o};f&&(delete p.body,p.method=`GET`),o={...p,headers:u,redirect:`manual`}}throw TypeError(`Too many redirects`)}function iR(e,t,n){let r=new URL(e),i=new URL(n||e);return i.origin!==r.origin&&aR(i),nR(i.href)}function aR(e){throw new L({code:`UNSAFE_PAYMENT_REDIRECT`,message:`Refusing to send a payment credential to redirected origin ${e.origin}.`,exitCode:1})}function oR(e,t){for(let t of Object.keys(e))t.toLowerCase()===`host`&&delete e[t];t&&(e.Host=t)}function sR(e){let t=e.request.resource;return typeof t?.url==`string`?t.url:void 0}async function cR(){let e=process.env.MPPX_SERVICES_URL??`https://mpp.dev/api/services`,t=await globalThis.fetch(e);if(!t.ok)throw new L({code:`SERVICES_FETCH_FAILED`,message:`Failed to fetch services registry: HTTP ${t.status}`,exitCode:1});let n=await t.json();if(!n||typeof n!=`object`||!Array.isArray(n.services))throw new L({code:`SERVICES_INVALID`,message:`Services registry response did not contain a services array.`,exitCode:1});return n.services}function lR(e,t){let n=t.toLowerCase();return e.find(e=>{let t=KL(e.id)?.toLowerCase(),r=KL(e.name)?.toLowerCase();return t===n||r===n})}const uR=cb(`mppx`,{mcp:{tools:{discovery:`direct`}},version:IL,description:`Make HTTP requests with automatic payment handling`,usage:[{suffix:`<url> [options]`}],args:p.object({url:p.string().describe(`URL to make request to`)}),options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),autoSwap:p.boolean().optional().describe(`Auto-swap source tokens into payment currency`),config:p.string().optional().describe(`Path to config file`),confirm:p.boolean().optional().default(!1).describe(`Show confirmation prompts`),currency:p.string().optional().describe(`Payment currency/token address to select`),data:p.string().optional().describe(`Send request body (implies POST unless -X is set)`),fail:p.boolean().optional().describe(`Fail silently on HTTP errors (exit 22)`),header:p.array(p.string()).optional().describe(`Add header (repeatable)`),include:p.boolean().optional().describe(`Include response headers in output`),insecure:p.boolean().optional().describe(`Skip TLS certificate verification (true for localhost/.local)`),jsonBody:p.string().optional().describe(`Send JSON body (sets Content-Type and Accept, implies POST)`),location:p.boolean().optional().describe(`Follow redirects`),method:p.string().optional().describe(`HTTP method`),methodOpt:p.array(p.string()).optional().describe(`Method-specific option (key=value, repeatable)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),payWith:p.string().optional().describe(`Source token for Tempo auto-swap`),protocol:p.enum([`auto`,`mpp`,`x402`]).default(`auto`).describe(`Payment protocol to use`),rpcUrl:p.string().optional().describe(`RPC endpoint, defaults to public RPC for chain (env: MPPX_RPC_URL)`),session:p.string().optional().default(`auto`).refine(e=>e===`auto`||e===`new`||/^0x[0-9a-fA-F]{64}$/.test(e),`Expected auto, new, or a 32-byte channel ID`).describe(`Session selection: auto, new, or channel ID`),silent:p.boolean().default(!1).describe(`Silent mode (suppress progress and info)`),slippage:p.number().optional().describe(`Tempo auto-swap max slippage percentage`),userAgent:p.string().optional().describe(`Set User-Agent header`),verbose:p.number().default(0).meta({count:!0}).describe(`Verbosity (-v details, -vv headers)`)}),alias:{account:`a`,config:`c`,data:`d`,fail:`f`,header:`H`,include:`i`,insecure:`k`,jsonBody:`J`,location:`L`,method:`X`,methodOpt:`M`,rpcUrl:`r`,silent:`s`,userAgent:`A`,verbose:`v`},examples:[{args:{url:`mpp.dev/api/ping/paid`},description:`Make a payment request`}],async run(e){let t=e.options.silent?e=>{}:e=>process.stderr.write(e),n=await YP(e.options.config);n&&e.options.verbose>=1&&t(`${X.dim(`Using config`)} ${X.blue(c.relative(process.cwd(),n.path))}\n`);let r=pk(),i={"User-Agent":e.options.userAgent??`mppx/${IL}${r?` AIAgent/${r}`:``}`};if(e.options.header)for(let t of e.options.header){let n=t.indexOf(`:`);if(n===-1)return e.error({code:`INVALID_HEADER`,message:`Invalid header format: ${t}`,exitCode:2});i[t.slice(0,n).trim()]=t.slice(n+1).trim()}let a=KP(n?.config);a&&!Object.keys(i).some(e=>e.toLowerCase()===`accept-payment`)&&(i[`Accept-Payment`]=a);let o=(()=>{let t=/^https?:\/\//.test(e.args.url),n=/^(localhost|.*\.localhost|127\.0\.0\.1|\[::1\])(:\d+)?/.test(e.args.url);return t?e.args.url:`${n?`http`:`https`}://${e.args.url}`})(),{hostname:s}=new URL(o),l=e.options.insecure||s===`localhost`||s.endsWith(`.localhost`)||s.endsWith(`.local`)?async(e,t)=>{let n=process.env.NODE_TLS_REJECT_UNAUTHORIZED;process.env.NODE_TLS_REJECT_UNAUTHORIZED=`0`;try{return await globalThis.fetch(e,t)}finally{n===void 0?delete process.env.NODE_TLS_REJECT_UNAUTHORIZED:process.env.NODE_TLS_REJECT_UNAUTHORIZED=n}}:globalThis.fetch,u=nR(o),d=u.url;u.host&&(i.Host=u.host);try{let r=jO(e.options.methodOpt),a=fF(),s={redirect:e.options.location?`follow`:`manual`};e.options.jsonBody?(s.body=e.options.jsonBody,i[`Content-Type`]??=`application/json`,i.Accept??=`application/json`):e.options.data&&(s.body=e.options.data),e.options.method?s.method=e.options.method.toUpperCase():s.body&&(s.method=`POST`),Object.keys(i).length>0&&(s.headers=i);let c={include:e.options.include??!1,verbose:e.options.verbose,silent:e.options.silent};e.options.verbose>=2&&TO(o,s,t);let f=await rR(l,o,s,e.options.location??!1),p=f.response;if(p.status!==402){if(e.options.session!==`auto`)return e.error({code:`UNSUPPORTED_SESSION`,message:`--session requires a tempo/session payment challenge.`,exitCode:2});if(e.options.fail&&p.status>=400)return e.error({code:`HTTP_ERROR`,message:`HTTP error ${p.status}`,exitCode:22});EO(p,c),await WL(p);return}let m=p.url?new URL(p.url):void 0,h=u.host!==void 0&&m?.hostname===`127.0.0.1`,g=await $L(p,e.options.protocol,{ignoreX402ResponseUrl:h});if(g.length===0)return e.error({code:`UNSUPPORTED_PROTOCOL`,message:e.options.protocol===`auto`?`Server did not offer a payment challenge.`:`Server did not offer an ${e.options.protocol} payment challenge.`,exitCode:2});let _=QL(g,e.options.currency);if(e.options.currency&&_.length===0){let t=g.map(ZL).filter(e=>typeof e==`string`).join(`, `);return e.error({code:`UNSUPPORTED_CURRENCY`,message:`Server did not offer payment currency ${e.options.currency}.${t?` Offered currencies: ${t}.`:``}`,exitCode:2})}let v=qP(n?.config)?.length?_:await oP(_,{options:{account:e.options.account,network:e.options.network,rpcUrl:e.options.rpcUrl}}),y=GP(v,n?.config);if(!y){let t=v.map(e=>`${e.method}/${e.intent}`).join(`, `);return e.error({code:`UNSUPPORTED_METHOD`,message:`Unsupported payment method. Server offers: ${t}. Add it to mppx.config.ts using defineConfig().`,exitCode:2})}let{challenge:b,plugin:x,method:S}=y,C=ES(b),w=C?void 0:iR(o,u,f.logicalUrl),T=tR(b,p),ee=b.request.currency??``,E=b.request.decimals??6,D,O;x&&(O=await x.setup({challenge:b,options:{account:e.options.account,autoSwap:e.options.autoSwap,network:e.options.network,payWith:e.options.payWith,rpcUrl:e.options.rpcUrl,slippage:e.options.slippage},methodOpts:r}),ee=O.tokenSymbol,E=O.tokenDecimals,D=O.explorerUrl);let A=!e.options.silent&&e.options.confirm,te=new Set;{EO(p,b.method===`tempo`&&b.intent===`session`&&e.options.include?{...c,include:!1,verbose:Math.max(c.verbose,2)}:c);let n=(()=>{let e=new Set([`id`,`request`]),t=[];for(let[n,r]of Object.entries(b))e.has(n)||r===void 0||t.push([n,kO(n,r)]);return t.sort(([e],[t])=>e.localeCompare(t))})(),r={tokenSymbol:ee,tokenDecimals:E,explorerUrl:D},i=(()=>{let e=new Set([`decimals`,`currency`,`methodDetails`]),t=[];for(let[n,i]of Object.entries(b.request))e.has(n)||i===void 0||t.push([n,DO(n,i,r)]);return t.sort(([e],[t])=>e.localeCompare(t))})(),a=(()=>{let e=b.request.methodDetails;if(!e)return[];let t=[];for(let[n,i]of Object.entries(e))if(i!==void 0){if(n===`memo`&&typeof i==`string`){let e=OO(i);t.push([n,e?`${e}\n${X.dim(i)}`:i])}else t.push([n,DO(n,i,r)])}return t.sort(([e],[t])=>e.localeCompare(t))})(),o=[[`Challenge`,n],[`Request`,i],...a.length?[[`Details`,a]]:[]];for(let[,e]of o)for(let[t]of e)te.add(t);let s=Math.max(...o.flatMap(([,e])=>e.map(([e])=>e.length))),l=` ${``.padEnd(s)} `;if(e.options.verbose>=1||A){t(`${X.bold(X.yellow(`Payment Required`))}\n`);for(let[e,n]of o){t(`${X.bold(e)}\n`);for(let[e,r]of n){let[n,...i]=r.split(`
246
+ `);t(` ${X.dim(e.padEnd(s))} ${n}\n`);for(let e of i)t(`${l}${e}\n`)}}}if(A&&(t(`
247
+ `),!await FO(`Proceed with ${b.intent}?`,!0))){t(`Aborted.
248
+ `);return}}let ne=process.env.MPPX_PRIVATE_KEY?.trim()||!NO(ik(e.options.account));if(FD(b)&&ne&&!S){try{await pI({challenge:b,challengeResponse:T,credentialContext:await UP(b,n?.config.extensions,O?.credentialContext),endpoint:f.logicalUrl,fetch:l,fetchInput:w.url,init:{...f.init,redirect:`manual`},info:t,methodOptions:r,options:{account:e.options.account,fail:e.options.fail,include:e.options.include,network:e.options.network,rpcUrl:e.options.rpcUrl,session:e.options.session,silent:e.options.silent,verbose:e.options.verbose},registry:a})}catch(e){return nI(e,`SESSION_REQUEST_FAILED`)}return}if(e.options.session!==`auto`)return e.error({code:`UNSUPPORTED_SESSION`,message:S&&FD(b)?`--session cannot override a configured session method. Configure its channelStore instead.`:`--session requires a tempo/session payment challenge.`,exitCode:2});let j=S&&FD(b)?void 0:await UP(b,n?.config.extensions,O?.credentialContext),M,re;if(S&&FD(b)){let e=T;M=await wT({methods:[S],polyfill:!1,async onChallenge(e,{createCredential:t}){let r=await UP(e,n?.config.extensions,O?.credentialContext);return ZP(b,e),t(r)},fetch:async(t,n)=>{if(e){let t=e;return e=void 0,t}return l(t,n)}}).fetch(w.url,{...f.init,context:j,redirect:`manual`})}else{if(O?.createCredential)re=await O.createCredential(T,j);else if(O)re=await wT({methods:O.methods,polyfill:!1,transport:eR(b)}).createCredential(T,j);else if(S)re=await wT({methods:[S],polyfill:!1,transport:eR(b)}).createCredential(T,j);else throw Error(`unreachable`);let n=C?pC:fS(b),r={...Mw(f.init.headers),[n]:re},i=C?nR((sR(b)??p.url)||o):w;C&&oR(r,i.host),x?.prepareCredentialRequest?.({challenge:b,credential:re,headers:r});let a={...f.init,redirect:`manual`,headers:r};e.options.verbose>=2&&TO(i.url,a,t),M=await l(i.url,a)}if(e.options.fail&&M.status>=400)return e.error({code:`HTTP_ERROR`,message:`HTTP error ${M.status}`,exitCode:22});if(M.status===402){let n=await M.text();t(`${X.bold(X.red(`Payment Rejected`))}\n`);try{let e=JSON.parse(n),r=[];for(let[t,n]of Object.entries(e))n!==void 0&&r.push([t,String(n)]);r.sort(([e],[t])=>e.localeCompare(t));let i=Math.max(...r.map(([e])=>e.length));for(let[e,n]of r)t(` ${X.dim(e.padEnd(i))} ${n}\n`)}catch{n&&t(` ${n}\n`)}return e.error({code:`PAYMENT_REJECTED`,message:`Payment rejected`,exitCode:75})}if(EO(M,c),!(re&&await x?.handleResponse?.({challenge:b,credential:re,response:M,fetchUrl:d,fetchInit:s,silent:e.options.silent,verbose:e.options.verbose,confirmEnabled:A,confirm:FO,tokenSymbol:ee,tokenDecimals:E,explorerUrl:D,shownKeys:te}))){let n=M.headers.get(q.paymentReceipt);if(n&&e.options.verbose>=1)try{let e=JSON.parse(k.toString(n));t(`\n${X.bold(X.green(`Payment Receipt`))}\n`);let r=[],i=e.channelId,a=e.reference,o=i&&a&&i===a,s=new Set([`acceptedCumulative`,`spent`]);for(let[t,n]of Object.entries(e)){if(n===void 0||te.has(t)||t===`reference`&&o)continue;let e=x?.formatReceiptField?.(t,n);e===void 0?s.has(t)&&typeof n==`string`?r.push([t,`${n} ${X.dim(`(${IO(BigInt(n),ee,E)})`)}`]):(t===`reference`||t===`txHash`)&&typeof n==`string`&&D?r.push([t,AO(`${D}/tx/${n}`,n)]):r.push([t,String(n)]):r.push([t,e])}r.sort(([e],[t])=>e.localeCompare(t));let c=Math.max(...r.map(([e])=>e.length));for(let[e,n]of r)t(` ${X.dim(e.padEnd(c))} ${n}\n`);t(`
249
+ `)}catch{}await WL(M)}}catch(t){if(t instanceof L)throw t;let n=t instanceof Error?t.cause:void 0,r=n instanceof Error?n:void 0;if(r&&`code`in r){let t=r.code;return t===`ENOTFOUND`?e.error({code:`DNS_ERROR`,message:`Could not resolve host "${s}". Check the URL and try again.`,exitCode:6}):t===`ECONNREFUSED`?e.error({code:`CONNECTION_REFUSED`,message:`Connection refused by "${s}". Is the server running?`,retryable:!0,exitCode:7}):t===`ECONNRESET`?e.error({code:`CONNECTION_RESET`,message:`Connection to "${s}" was reset.`,retryable:!0,exitCode:56}):t===`ETIMEDOUT`?e.error({code:`CONNECTION_TIMEOUT`,message:`Connection to "${s}" timed out.`,retryable:!0,exitCode:28}):t===`CERT_HAS_EXPIRED`||t===`UNABLE_TO_VERIFY_LEAF_SIGNATURE`?e.error({code:`TLS_ERROR`,message:`TLS certificate error for "${s}". Use --insecure to skip verification.`,exitCode:60}):e.error({code:`REQUEST_FAILED`,message:`Request to "${s}" failed: ${r.message}`})}{let n=t instanceof Error?t.message:String(t);return e.error({code:`REQUEST_FAILED`,message:r?`Request failed: ${n} (Cause: ${r.message})`:`Request failed: ${n}`})}}}}),dR=cb(`account`,{description:`Manage accounts (create, default, delete, export, fund, list, view)`}).command(`create`,{description:`Create new account`,options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),rpcUrl:p.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`)}),output:p.object({address:p.string(),name:p.string()}),alias:{account:`a`,rpcUrl:`r`},async run(e){let t=HL(e),n=e.options.account;if(!n){if((await ak().list()).length===0)n=`main`;else{if(t)return e.error({code:`ACCOUNT_REQUIRED`,message:`Account name is required in structured mode.`,exitCode:2});let r=await PO(`Account name`);if(!r)return;n=r}}let r=ak(n);for(;await r.get();){if(t)return e.error({code:`ACCOUNT_EXISTS`,message:`Account "${n}" already exists.`,exitCode:1});process.stderr.write(`${X.dim(`Account "${n}" already exists.`)}\n\n`);let i=await PO(`Enter different name`);if(!i)return;n=i,r=ak(n)}let i=he(),a=_e(i);await r.set(i),(await ak().list()).length===1&&rk().set(n);let o=ve.blockExplorers?.default?.url,s=o?AO(`${o}/address/${a.address}`,a.address):a.address,c=RO(e.options),l=LO(e.options.rpcUrl,{network:c});return zO({network:c,rpcUrl:l}).then(e=>M({chain:e,transport:le(l)})).then(e=>import(`viem/tempo`).then(({Actions:t})=>t.faucet.fund(e,{account:a}).catch(()=>{}))),UL(e,{address:a.address,name:n},()=>{console.log(`Account "${n}" saved to keychain.`),console.log(X.dim(`Address ${s}`)),console.log(X.dim(`Fund testnet tokens: mppx account fund --account ${n} --network testnet`))})}}).command(`default`,{description:`Set default account`,options:p.object({account:p.string().describe(`Account name`)}),output:p.object({name:p.string()}),alias:{account:`a`},async run(e){let t=e.options.account;return NO(t)?DP(t)?(rk().set(t),UL(e,{name:t},()=>{console.log(`Default account set to "${t}"`)})):e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found. Is Tempo wallet configured?`,exitCode:69}):await ak(t).get()?(rk().set(t),UL(e,{name:t},()=>{console.log(`Default account set to "${t}"`)})):e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found.`,exitCode:69})}}).command(`delete`,{description:`Delete account`,options:p.object({account:p.string().describe(`Account name`),yes:p.boolean().optional().describe(`DANGER!! Skip confirmation prompts`)}),output:p.object({defaultAccount:p.string().optional(),name:p.string()}),alias:{account:`a`},async run(e){let t=ak(e.options.account),n=await t.get();if(!n)return e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${e.options.account}" not found.`,exitCode:69});let r=_e(n),i=await WO(r.address,{includeTestnet:!1});if(!e.options.yes){if(HL(e))return e.error({code:`CONFIRMATION_REQUIRED`,message:`Pass --yes to delete an account in structured mode.`,exitCode:2});let t=ve.blockExplorers?.default?.url,n=t?AO(`${t}/address/${r.address}`,r.address):r.address;process.stderr.write(X.dim(`Delete account "${e.options.account}"\n`)),process.stderr.write(X.dim(` Address ${n}\n`));for(let e=0;e<i.length;e++)process.stderr.write(X.dim(` ${e===0?`Balance`:` `} ${i[e]}\n`));if(process.stderr.write(X.dim(`This action cannot be undone
250
250
 
251
- `)),!await MO(`Confirm delete?`)){console.log(`Canceled`);return}}await t.delete();let a=ek().get(),o;if(a===e.options.account){let e=await nk().list();e.length>0?(o=e[0],ek().set(o)):ek().clear()}return NL(e,{defaultAccount:o,name:e.options.account},()=>{o&&console.log(`Default account set to "${o}"`),console.log(`Account "${e.options.account}" deleted`)})}}).command(`fund`,{description:`Fund account with testnet tokens`,options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),network:p.enum([`testnet`]).optional().describe(`Tempo network`),rpcUrl:p.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`)}),output:p.object({account:p.string(),chain:p.string(),transactions:p.array(p.string())}),alias:{account:`a`,rpcUrl:`r`},async run(e){let t=ML(e),n=tk(e.options.account),r=await nk(n).get();if(!r)return e.options.account?e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${n}" not found.`,exitCode:69}):e.error({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69});let i=ve(r),a=FO(e.options),o=PO(e.options.rpcUrl,{network:a}),s=await IO({network:a,rpcUrl:o}),c=j({chain:s,transport:ue(o)});t||console.log(`Funding "${n}" on ${LO(s)}`);try{let{Actions:r}=await import(`viem/tempo`),a=await r.faucet.fund(c,{account:i}),o=s.blockExplorers?.default?.url;if(!t)for(let e of a){let t=o?DO(`${o}/tx/${e}`,X.gray(e)):e;console.log(` ${t}`)}let{waitForTransactionReceipt:l}=await import(`viem/actions`);return await Promise.all(a.map(e=>l(c,{hash:e}))),NL(e,{account:n,chain:LO(s),transactions:[...a]},()=>{console.log(`Funded successfully`)})}catch(n){let r=n instanceof Error?n.message:String(n);return t?e.error({code:`FUNDING_FAILED`,message:r,exitCode:1}):e.error({code:`FUNDING_FAILED`,message:`Funding failed: ${r}`,exitCode:1})}}}).command(`list`,{description:`List all accounts`,output:p.object({accounts:p.array(DL)}),async run(e){let t=ek().get(),n=(await nk().list()).sort(),r=[];for(let e of n){let t=await nk(e).get();t&&r.push({name:e,address:ve(t).address})}let i=gP();for(let e=0;e<i.length;e++){let t=i[e],n=e===0?`tempo:default`:`tempo:${e}`;t.wallet_address&&r.push({name:n,address:t.wallet_address,source:`tempo wallet`})}if(r.length===0)return NL(e,{accounts:[]},()=>{console.log(`No accounts found.`)});let a=ye.blockExplorers?.default?.url,o=Math.max(...r.map(e=>e.name.length+ +(e.name===t)));return NL(e,{accounts:r.map(e=>({...e,...e.name===t?{isDefault:!0}:void 0}))},()=>{for(let e of r){let n=e.name===t,r=n?`${e.name}${X.dim(`*`)}`:e.name,i=e.name.length+ +!!n,s=a?DO(`${a}/address/${e.address}`,e.address):e.address,c=e.source?` ${X.dim(`(${e.source})`)}`:``;console.log(`${r}${` `.repeat(o-i+2)}${X.dim(s)}${c}`)}})}}).command(`export`,{description:`Export the private key for a local account`,options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`)}),output:p.object({privateKey:p.string()}),alias:{account:`a`},async run(e){let t=tk(e.options.account);if(AO(t))return e.error({code:`UNSUPPORTED_ACCOUNT`,message:`Account "${t}" is managed by Tempo wallet and does not expose a private key via mppx.`,exitCode:2});let n=await nk(t).get();return n?NL(e,{privateKey:n},()=>{console.log(n)}):e.options.account?e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found.`,exitCode:69}):e.error({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69})}}).command(`view`,{description:`View account address`,options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),rpcUrl:p.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`)}),output:OL,alias:{account:`a`,rpcUrl:`r`},async run(e){let t=tk(e.options.account);if(AO(t)){let n=_P(t);if(!n)return e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found. Is Tempo wallet configured?`,exitCode:69});let r=n.wallet_address,i=PO(e.options.rpcUrl,{network:e.options.network}),a=await IO({network:e.options.network,rpcUrl:i}),o=a.blockExplorers?.default?.url,s=o?DO(`${o}/address/${r}`,r):r,c=await VO(r,a&&i?{chain:a,rpcUrl:i}:void 0);return NL(e,{address:r,balances:c,name:t,type:`${n.wallet_type} (tempo wallet)`},()=>{console.log(`${X.dim(`Address`)} ${s}`);for(let e=0;e<c.length;e++)console.log(`${X.dim(e===0?`Balance`:` `)} ${c[e]}`);console.log(`${X.dim(`Name`)} ${t}`),console.log(`${X.dim(`Type`)} ${n.wallet_type} ${X.dim(`(tempo wallet)`)}`)})}let n=await nk(t).get();if(!n)return e.options.account?e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found.`,exitCode:69}):e.error({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69});let r=ve(n),i=PO(e.options.rpcUrl,{network:e.options.network}),a=await IO({network:e.options.network,rpcUrl:i}),o=a.blockExplorers?.default?.url,s=o?DO(`${o}/address/${r.address}`,r.address):r.address,c=await VO(r.address,a&&i?{chain:a,rpcUrl:i}:void 0);return NL(e,{address:r.address,balances:c,name:t},()=>{console.log(`${X.dim(`Address`)} ${s}`);for(let e=0;e<c.length;e++)console.log(`${X.dim(e===0?`Balance`:` `)} ${c[e]}`);console.log(`${X.dim(`Name`)} ${t}`)})}}),nR=cb(`sign`,{description:`Sign a payment challenge and output the Authorization header`,usage:[{suffix:`--challenge <value> [options]`},{prefix:`echo <challenge> |`,suffix:`[options]`}],options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),challenge:p.string().optional().describe(`WWW-Authenticate challenge value`),config:p.string().optional().describe(`Path to config file`),dryRun:p.boolean().optional().describe(`Validate and parse the challenge without signing`),autoSwap:p.boolean().optional().describe(`Auto-swap source tokens into payment currency`),methodOpt:p.array(p.string()).optional().describe(`Method-specific option (key=value, repeatable)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),payWith:p.string().optional().describe(`Source token for Tempo auto-swap`),rpcUrl:p.string().optional().describe(`RPC endpoint, defaults to public RPC for chain (env: MPPX_RPC_URL)`),slippage:p.number().optional().describe(`Tempo auto-swap max slippage percentage`)}),output:p.object({authorization:p.string()}),alias:{account:`a`,challenge:`C`,config:`c`,methodOpt:`M`,rpcUrl:`r`},async run(e){let t=e.options.challenge||(FL()?await new Promise((e,t)=>{let n=``;process.stdin.setEncoding(`utf-8`),process.stdin.on(`data`,e=>{n+=e}),process.stdin.on(`end`,()=>e(n.trim())),process.stdin.on(`error`,t)}):void 0);if(!t)return e.error({code:`NO_CHALLENGE`,message:`No challenge provided. Use --challenge or pipe via stdin.`,exitCode:2});let n;try{n=uS(t)}catch(t){return e.error({code:`INVALID_CHALLENGE`,message:`Failed to parse challenge: ${t instanceof Error?t.message:t}`,exitCode:2})}if(e.options.dryRun){process.stderr.write(`Challenge is valid.
252
- `);return}let r=await zP(e.options.config),i=FP(n,r?.config);if(!i){let t=n.map(e=>`${e.method}/${e.intent}`).join(`, `);return e.error({code:`UNSUPPORTED_METHOD`,message:`Unsupported payment method. Server offers: ${t}. Add it to mppx.config.ts using defineConfig().`,exitCode:2})}let{challenge:a,plugin:o,method:s}=i,c=OO(e.options.methodOpt),l=$x(a),u=new Response(null,{status:402,headers:{[q.wwwAuthenticate]:l}}),d;o&&(d=await o.setup({challenge:a,options:{account:e.options.account,autoSwap:e.options.autoSwap,network:e.options.network,payWith:e.options.payWith,rpcUrl:e.options.rpcUrl,slippage:e.options.slippage},methodOpts:c}));let f=await NP(a,r?.config.extensions,d?.credentialContext),p;if(d)p=d.createCredential?await d.createCredential(u,f):await ST({methods:d.methods,polyfill:!1}).createCredential(u,f);else if(s)p=await ST({methods:[s],polyfill:!1}).createCredential(u,f);else return e.error({code:`UNSUPPORTED_METHOD`,message:`Unsupported payment method: ${a.method}/${a.intent}. Add it to mppx.config.ts using defineConfig().`,exitCode:2});return NL(e,{authorization:p},()=>{console.log(p)})}}),rR=cb(`init`,{description:`Create an mppx.config.ts file in the current directory`,options:p.object({force:p.boolean().optional().describe(`Overwrite existing config file`)}),output:p.object({file:p.string()}),alias:{force:`f`},async run(e){let n=process.cwd(),r=`mppx.config${(()=>{if(t.existsSync(c.join(n,`tsconfig.json`)))return`.ts`;try{if(JSON.parse(t.readFileSync(c.join(n,`package.json`),`utf-8`)).type===`module`)return`.mjs`}catch{}return`.js`})()}`,i=c.join(n,r);return t.existsSync(i)&&!e.options.force?e.error({code:`CONFIG_EXISTS`,message:`${r} already exists. Use --force to overwrite.`,exitCode:1}):(t.writeFileSync(i,`import { defineConfig } from 'mppx/cli'
251
+ `)),!await FO(`Confirm delete?`)){console.log(`Canceled`);return}}await t.delete();let a=rk().get(),o;if(a===e.options.account){let e=await ak().list();e.length>0?(o=e[0],rk().set(o)):rk().clear()}return UL(e,{defaultAccount:o,name:e.options.account},()=>{o&&console.log(`Default account set to "${o}"`),console.log(`Account "${e.options.account}" deleted`)})}}).command(`fund`,{description:`Fund account with testnet tokens`,options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),network:p.enum([`testnet`]).optional().describe(`Tempo network`),rpcUrl:p.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`)}),output:p.object({account:p.string(),chain:p.string(),transactions:p.array(p.string())}),alias:{account:`a`,rpcUrl:`r`},async run(e){let t=HL(e),n=ik(e.options.account),r=await ak(n).get();if(!r)return e.options.account?e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${n}" not found.`,exitCode:69}):e.error({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69});let i=_e(r),a=RO(e.options),o=LO(e.options.rpcUrl,{network:a}),s=await zO({network:a,rpcUrl:o}),c=M({chain:s,transport:le(o)});t||console.log(`Funding "${n}" on ${BO(s)}`);try{let{Actions:r}=await import(`viem/tempo`),a=await r.faucet.fund(c,{account:i}),o=s.blockExplorers?.default?.url;if(!t)for(let e of a){let t=o?AO(`${o}/tx/${e}`,X.gray(e)):e;console.log(` ${t}`)}let{waitForTransactionReceipt:l}=await import(`viem/actions`);return await Promise.all(a.map(e=>l(c,{hash:e}))),UL(e,{account:n,chain:BO(s),transactions:[...a]},()=>{console.log(`Funded successfully`)})}catch(n){let r=n instanceof Error?n.message:String(n);return t?e.error({code:`FUNDING_FAILED`,message:r,exitCode:1}):e.error({code:`FUNDING_FAILED`,message:`Funding failed: ${r}`,exitCode:1})}}}).command(`list`,{description:`List all accounts`,output:p.object({accounts:p.array(LL)}),async run(e){let t=rk().get(),n=(await ak().list()).sort(),r=[];for(let e of n){let t=await ak(e).get();t&&r.push({name:e,address:_e(t).address})}let i=EP();for(let e=0;e<i.length;e++){let t=i[e],n=e===0?`tempo:default`:`tempo:${e}`;t.wallet_address&&r.push({name:n,address:t.wallet_address,source:`tempo wallet`})}if(r.length===0)return UL(e,{accounts:[]},()=>{console.log(`No accounts found.`)});let a=ve.blockExplorers?.default?.url,o=Math.max(...r.map(e=>e.name.length+ +(e.name===t)));return UL(e,{accounts:r.map(e=>({...e,...e.name===t?{isDefault:!0}:void 0}))},()=>{for(let e of r){let n=e.name===t,r=n?`${e.name}${X.dim(`*`)}`:e.name,i=e.name.length+ +!!n,s=a?AO(`${a}/address/${e.address}`,e.address):e.address,c=e.source?` ${X.dim(`(${e.source})`)}`:``;console.log(`${r}${` `.repeat(o-i+2)}${X.dim(s)}${c}`)}})}}).command(`export`,{description:`Export the private key for a local account`,options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`)}),output:p.object({privateKey:p.string()}),alias:{account:`a`},async run(e){let t=ik(e.options.account);if(NO(t))return e.error({code:`UNSUPPORTED_ACCOUNT`,message:`Account "${t}" is managed by Tempo wallet and does not expose a private key via mppx.`,exitCode:2});let n=await ak(t).get();return n?UL(e,{privateKey:n},()=>{console.log(n)}):e.options.account?e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found.`,exitCode:69}):e.error({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69})}}).command(`view`,{description:`View account address`,options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),rpcUrl:p.string().optional().describe(`RPC endpoint (env: MPPX_RPC_URL)`)}),output:RL,alias:{account:`a`,rpcUrl:`r`},async run(e){let t=ik(e.options.account);if(NO(t)){let n=DP(t);if(!n)return e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found. Is Tempo wallet configured?`,exitCode:69});let r=n.wallet_address,i=LO(e.options.rpcUrl,{network:e.options.network}),a=await zO({network:e.options.network,rpcUrl:i}),o=a.blockExplorers?.default?.url,s=o?AO(`${o}/address/${r}`,r):r,c=await WO(r,a&&i?{chain:a,rpcUrl:i}:void 0);return UL(e,{address:r,balances:c,name:t,type:`${n.wallet_type} (tempo wallet)`},()=>{console.log(`${X.dim(`Address`)} ${s}`);for(let e=0;e<c.length;e++)console.log(`${X.dim(e===0?`Balance`:` `)} ${c[e]}`);console.log(`${X.dim(`Name`)} ${t}`),console.log(`${X.dim(`Type`)} ${n.wallet_type} ${X.dim(`(tempo wallet)`)}`)})}let n=await ak(t).get();if(!n)return e.options.account?e.error({code:`ACCOUNT_NOT_FOUND`,message:`Account "${t}" not found.`,exitCode:69}):e.error({code:`ACCOUNT_NOT_FOUND`,message:`No account found.`,exitCode:69});let r=_e(n),i=LO(e.options.rpcUrl,{network:e.options.network}),a=await zO({network:e.options.network,rpcUrl:i}),o=a.blockExplorers?.default?.url,s=o?AO(`${o}/address/${r.address}`,r.address):r.address,c=await WO(r.address,a&&i?{chain:a,rpcUrl:i}:void 0);return UL(e,{address:r.address,balances:c,name:t},()=>{console.log(`${X.dim(`Address`)} ${s}`);for(let e=0;e<c.length;e++)console.log(`${X.dim(e===0?`Balance`:` `)} ${c[e]}`);console.log(`${X.dim(`Name`)} ${t}`)})}}),fR=cb(`sign`,{description:`Sign a payment challenge and output the Authorization header`,usage:[{suffix:`--challenge <value> [options]`},{prefix:`echo <challenge> |`,suffix:`[options]`}],options:p.object({account:p.string().optional().describe(`Account name (env: MPPX_ACCOUNT)`),challenge:p.string().optional().describe(`WWW-Authenticate challenge value`),config:p.string().optional().describe(`Path to config file`),dryRun:p.boolean().optional().describe(`Validate and parse the challenge without signing`),autoSwap:p.boolean().optional().describe(`Auto-swap source tokens into payment currency`),methodOpt:p.array(p.string()).optional().describe(`Method-specific option (key=value, repeatable)`),network:p.enum([`mainnet`,`testnet`]).optional().describe(`Tempo network`),payWith:p.string().optional().describe(`Source token for Tempo auto-swap`),rpcUrl:p.string().optional().describe(`RPC endpoint, defaults to public RPC for chain (env: MPPX_RPC_URL)`),slippage:p.number().optional().describe(`Tempo auto-swap max slippage percentage`)}),output:p.object({authorization:p.string()}),alias:{account:`a`,challenge:`C`,config:`c`,methodOpt:`M`,rpcUrl:`r`},async run(e){let t=e.options.challenge||(GL()?await new Promise((e,t)=>{let n=``;process.stdin.setEncoding(`utf-8`),process.stdin.on(`data`,e=>{n+=e}),process.stdin.on(`end`,()=>e(n.trim())),process.stdin.on(`error`,t)}):void 0);if(!t)return e.error({code:`NO_CHALLENGE`,message:`No challenge provided. Use --challenge or pipe via stdin.`,exitCode:2});let n;try{n=uS(t)}catch(t){return e.error({code:`INVALID_CHALLENGE`,message:`Failed to parse challenge: ${t instanceof Error?t.message:t}`,exitCode:2})}if(e.options.dryRun){process.stderr.write(`Challenge is valid.
252
+ `);return}let r=await YP(e.options.config),i=GP(n,r?.config);if(!i){let t=n.map(e=>`${e.method}/${e.intent}`).join(`, `);return e.error({code:`UNSUPPORTED_METHOD`,message:`Unsupported payment method. Server offers: ${t}. Add it to mppx.config.ts using defineConfig().`,exitCode:2})}let{challenge:a,plugin:o,method:s}=i,c=jO(e.options.methodOpt),l=$x(a),u=new Response(null,{status:402,headers:{[q.wwwAuthenticate]:l}}),d;o&&(d=await o.setup({challenge:a,options:{account:e.options.account,autoSwap:e.options.autoSwap,network:e.options.network,payWith:e.options.payWith,rpcUrl:e.options.rpcUrl,slippage:e.options.slippage},methodOpts:c}));let f=await UP(a,r?.config.extensions,d?.credentialContext),p;if(d)p=d.createCredential?await d.createCredential(u,f):await wT({methods:d.methods,polyfill:!1}).createCredential(u,f);else if(s)p=await wT({methods:[s],polyfill:!1}).createCredential(u,f);else return e.error({code:`UNSUPPORTED_METHOD`,message:`Unsupported payment method: ${a.method}/${a.intent}. Add it to mppx.config.ts using defineConfig().`,exitCode:2});return UL(e,{authorization:p},()=>{console.log(p)})}}),pR=cb(`init`,{description:`Create an mppx.config.ts file in the current directory`,options:p.object({force:p.boolean().optional().describe(`Overwrite existing config file`)}),output:p.object({file:p.string()}),alias:{force:`f`},async run(e){let n=process.cwd(),r=`mppx.config${(()=>{if(t.existsSync(c.join(n,`tsconfig.json`)))return`.ts`;try{if(JSON.parse(t.readFileSync(c.join(n,`package.json`),`utf-8`)).type===`module`)return`.mjs`}catch{}return`.js`})()}`,i=c.join(n,r);return t.existsSync(i)&&!e.options.force?e.error({code:`CONFIG_EXISTS`,message:`${r} already exists. Use --force to overwrite.`,exitCode:1}):(t.writeFileSync(i,`import { defineConfig } from 'mppx/cli'
253
253
 
254
254
  export default defineConfig({
255
255
  methods: [],
256
256
  plugins: [],
257
257
  })
258
- `),NL(e,{file:i},()=>{console.log(`Created ${r}`)}))}}),iR=cb(`services`,{description:`Browse the MPP services registry`}).command(`list`,{description:`List registered MPP services`,options:p.object({query:p.string().optional().describe(`Filter by id, name, category, tag, or description`)}),output:p.object({services:p.array(AL)}),alias:{query:`q`},async run(e){let t=e.options.query?.toLowerCase(),n=await QL(),r=(t?n.filter(e=>[e.id,e.name,e.description,...Array.isArray(e.categories)?e.categories:[],...Array.isArray(e.tags)?e.tags:[]].filter(e=>typeof e==`string`).some(e=>e.toLowerCase().includes(t))):n).map(RL).sort((e,t)=>e.id.localeCompare(t.id));return NL(e,{services:r},()=>{if(r.length===0){console.log(`No services found.`);return}let e=Math.max(...r.map(e=>e.id.length)),t=Math.max(...r.map(e=>String(e.paidEndpoints).length));for(let n of r){let r=n.name&&n.name!==n.id?` ${n.name}`:``,i=n.url?` ${X.dim(n.url)}`:``;console.log(`${n.id.padEnd(e)} ${String(n.paidEndpoints).padStart(t)} paid${r}${i}`)}})}}).command(`show`,{description:`Show one registered MPP service`,args:p.object({service:p.string().describe(`Service id or name`)}),output:p.object({service:p.record(p.string(),p.unknown())}),async run(e){let t=$L(await QL(),e.args.service);if(!t)return e.error({code:`SERVICE_NOT_FOUND`,message:`Service not found: ${e.args.service}`,exitCode:1});let n=RL(t),r=LL(t);return NL(e,{service:t},()=>{console.log(`${n.name??n.id} ${X.dim(`(${n.id})`)}`),n.description&&console.log(n.description),n.url&&console.log(`${X.dim(`URL`)} ${DO(n.url,n.url)}`),n.status&&console.log(`${X.dim(`Status`)} ${n.status}`),console.log(`${X.dim(`Endpoints`)} ${r.length} (${n.paidEndpoints} paid)`);let e=t.docs,i=e&&IL(e.homepage);i&&console.log(`${X.dim(`Docs`)} ${DO(i,i)}`)})}}).command(`endpoints`,{description:`List endpoints for a registered MPP service`,args:p.object({service:p.string().describe(`Service id or name`)}),output:p.object({endpoints:p.array(jL),service:AL}),async run(e){let t=$L(await QL(),e.args.service);if(!t)return e.error({code:`SERVICE_NOT_FOUND`,message:`Service not found: ${e.args.service}`,exitCode:1});let n=RL(t),r=LL(t).map(zL);return NL(e,{endpoints:r,service:n},()=>{if(r.length===0){console.log(`No endpoints found for ${n.id}.`);return}let e=Math.max(...r.map(e=>e.method.length)),t=Math.max(...r.map(e=>e.path.length));for(let n of r){let r=BL(n.payment),i=n.description?` ${X.dim(n.description)}`:``;console.log(`${n.method.padEnd(e)} ${n.path.padEnd(t)} ${r}${i}`)}})}}),aR=cb(`discover`,{description:`Discovery tooling`}).command(`generate`,{description:`Generate a static OpenAPI discovery document from a module`,args:p.object({module:p.string().describe(`Path to a module that default-exports a discovery config`)}),options:p.object({output:p.string().optional().describe(`Write output to a file instead of stdout`)}),output:p.record(p.string(),p.unknown()),alias:{output:`o`},async run(e){let n=c.resolve(e.args.module);if(!t.existsSync(n))return e.error({code:`MODULE_NOT_FOUND`,message:`Module not found: ${n}`,exitCode:1});let r;try{r=await import(n)}catch(t){return e.error({code:`MODULE_IMPORT_FAILED`,message:`Failed to import module: ${t.message}`,exitCode:1})}let i=r.default??r,a;if(typeof i.openapi==`string`)a=i;else{let{generate:t}=await Promise.resolve().then(()=>(TL(),yL)),n=i.mppx;if(!n)return e.error({code:`INVALID_MODULE`,message:"Module must default-export an OpenAPI document (with `openapi` key) or an object with `mppx` (server instance) and `routes`.",exitCode:1});a=t(n,i)}let o=JSON.stringify(a,null,2);if(e.options.output){let n=c.resolve(e.options.output);return t.writeFileSync(n,`${o}\n`),process.stderr.write(`Wrote ${n}\n`),NL(e,a,()=>{})}return NL(e,a,()=>{console.log(o)})}}).command(`validate`,{description:`Validate an OpenAPI discovery document from a file or URL`,args:p.object({input:p.string().describe(`Path or URL to a discovery document`)}),output:p.object({errorCount:p.number(),issues:p.array(kL),valid:p.boolean(),warningCount:p.number()}),async run(e){let n=e.args.input,r;if(/^https?:\/\//.test(n)){let t=new AbortController,i=setTimeout(()=>t.abort(),3e4),a;try{a=await globalThis.fetch(n,{signal:t.signal})}catch(t){clearTimeout(i);let n=t instanceof DOMException&&t.name===`AbortError`?`Request timed out after 30s`:t.message;return e.error({code:`DISCOVERY_FETCH_FAILED`,message:`Failed to fetch discovery document: ${n}`,exitCode:1})}if(clearTimeout(i),!a.ok)return e.error({code:`DISCOVERY_FETCH_FAILED`,message:`Failed to fetch discovery document: HTTP ${a.status}`,exitCode:1});let o=10485760,s=a.headers.get(`content-length`);if(s&&Number(s)>o||(r=await a.text(),r.length>o))return e.error({code:`DISCOVERY_TOO_LARGE`,message:`Discovery document exceeds 10 MB limit`,exitCode:1})}else{let i=c.resolve(n);if(!t.existsSync(i))return e.error({code:`DISCOVERY_NOT_FOUND`,message:`Discovery document not found: ${i}`,exitCode:1});r=t.readFileSync(i,`utf-8`)}let i;try{i=JSON.parse(r)}catch(t){return e.error({code:`DISCOVERY_INVALID_JSON`,message:`Invalid discovery JSON: ${t.message}`,exitCode:1})}let a=tE(i);if(!ML(e))for(let e of a)console.log(`[${e.severity}] ${e.path}: ${e.message}`);let o=a.filter(e=>e.severity===`error`).length,s=a.filter(e=>e.severity===`warning`).length;return o>0?e.error({code:`DISCOVERY_INVALID`,message:`Discovery document has ${o} error(s) and ${s} warning(s).`,exitCode:1}):NL(e,{errorCount:o,issues:a,valid:!0,warningCount:s},()=>{console.log(s>0?`Discovery document is valid with ${s} warning(s).`:`Discovery document is valid.`)})}});eR.command(tR),eR.command(aR),eR.command(rR),eR.command(iR),eR.command(YF),eR.command(nR),eR.command(fL);export{eR as default,JL as resolveMppCredentialTarget};
258
+ `),UL(e,{file:i},()=>{console.log(`Created ${r}`)}))}}),mR=cb(`services`,{description:`Browse the MPP services registry`}).command(`list`,{description:`List registered MPP services`,options:p.object({query:p.string().optional().describe(`Filter by id, name, category, tag, or description`)}),output:p.object({services:p.array(BL)}),alias:{query:`q`},async run(e){let t=e.options.query?.toLowerCase(),n=await cR(),r=(t?n.filter(e=>[e.id,e.name,e.description,...Array.isArray(e.categories)?e.categories:[],...Array.isArray(e.tags)?e.tags:[]].filter(e=>typeof e==`string`).some(e=>e.toLowerCase().includes(t))):n).map(JL).sort((e,t)=>e.id.localeCompare(t.id));return UL(e,{services:r},()=>{if(r.length===0){console.log(`No services found.`);return}let e=Math.max(...r.map(e=>e.id.length)),t=Math.max(...r.map(e=>String(e.paidEndpoints).length));for(let n of r){let r=n.name&&n.name!==n.id?` ${n.name}`:``,i=n.url?` ${X.dim(n.url)}`:``;console.log(`${n.id.padEnd(e)} ${String(n.paidEndpoints).padStart(t)} paid${r}${i}`)}})}}).command(`show`,{description:`Show one registered MPP service`,args:p.object({service:p.string().describe(`Service id or name`)}),output:p.object({service:p.record(p.string(),p.unknown())}),async run(e){let t=lR(await cR(),e.args.service);if(!t)return e.error({code:`SERVICE_NOT_FOUND`,message:`Service not found: ${e.args.service}`,exitCode:1});let n=JL(t),r=qL(t);return UL(e,{service:t},()=>{console.log(`${n.name??n.id} ${X.dim(`(${n.id})`)}`),n.description&&console.log(n.description),n.url&&console.log(`${X.dim(`URL`)} ${AO(n.url,n.url)}`),n.status&&console.log(`${X.dim(`Status`)} ${n.status}`),console.log(`${X.dim(`Endpoints`)} ${r.length} (${n.paidEndpoints} paid)`);let e=t.docs,i=e&&KL(e.homepage);i&&console.log(`${X.dim(`Docs`)} ${AO(i,i)}`)})}}).command(`endpoints`,{description:`List endpoints for a registered MPP service`,args:p.object({service:p.string().describe(`Service id or name`)}),output:p.object({endpoints:p.array(VL),service:BL}),async run(e){let t=lR(await cR(),e.args.service);if(!t)return e.error({code:`SERVICE_NOT_FOUND`,message:`Service not found: ${e.args.service}`,exitCode:1});let n=JL(t),r=qL(t).map(YL);return UL(e,{endpoints:r,service:n},()=>{if(r.length===0){console.log(`No endpoints found for ${n.id}.`);return}let e=Math.max(...r.map(e=>e.method.length)),t=Math.max(...r.map(e=>e.path.length));for(let n of r){let r=XL(n.payment),i=n.description?` ${X.dim(n.description)}`:``;console.log(`${n.method.padEnd(e)} ${n.path.padEnd(t)} ${r}${i}`)}})}}),hR=cb(`discover`,{description:`Discovery tooling`}).command(`generate`,{description:`Generate a static OpenAPI discovery document from a module`,args:p.object({module:p.string().describe(`Path to a module that default-exports a discovery config`)}),options:p.object({output:p.string().optional().describe(`Write output to a file instead of stdout`)}),output:p.record(p.string(),p.unknown()),alias:{output:`o`},async run(e){let n=c.resolve(e.args.module);if(!t.existsSync(n))return e.error({code:`MODULE_NOT_FOUND`,message:`Module not found: ${n}`,exitCode:1});let r;try{r=await import(n)}catch(t){return e.error({code:`MODULE_IMPORT_FAILED`,message:`Failed to import module: ${t.message}`,exitCode:1})}let i=r.default??r,a;if(typeof i.openapi==`string`)a=i;else{let{generate:t}=await Promise.resolve().then(()=>(FL(),kL)),n=i.mppx;if(!n)return e.error({code:`INVALID_MODULE`,message:"Module must default-export an OpenAPI document (with `openapi` key) or an object with `mppx` (server instance) and `routes`.",exitCode:1});a=t(n,i)}let o=JSON.stringify(a,null,2);if(e.options.output){let n=c.resolve(e.options.output);return t.writeFileSync(n,`${o}\n`),process.stderr.write(`Wrote ${n}\n`),UL(e,a,()=>{})}return UL(e,a,()=>{console.log(o)})}}).command(`validate`,{description:`Validate an OpenAPI discovery document from a file or URL`,args:p.object({input:p.string().describe(`Path or URL to a discovery document`)}),output:p.object({errorCount:p.number(),issues:p.array(zL),valid:p.boolean(),warningCount:p.number()}),async run(e){let n=e.args.input,r;if(/^https?:\/\//.test(n)){let t=new AbortController,i=setTimeout(()=>t.abort(),3e4),a;try{a=await globalThis.fetch(n,{signal:t.signal})}catch(t){clearTimeout(i);let n=t instanceof DOMException&&t.name===`AbortError`?`Request timed out after 30s`:t.message;return e.error({code:`DISCOVERY_FETCH_FAILED`,message:`Failed to fetch discovery document: ${n}`,exitCode:1})}if(clearTimeout(i),!a.ok)return e.error({code:`DISCOVERY_FETCH_FAILED`,message:`Failed to fetch discovery document: HTTP ${a.status}`,exitCode:1});let o=10485760,s=a.headers.get(`content-length`);if(s&&Number(s)>o||(r=await a.text(),r.length>o))return e.error({code:`DISCOVERY_TOO_LARGE`,message:`Discovery document exceeds 10 MB limit`,exitCode:1})}else{let i=c.resolve(n);if(!t.existsSync(i))return e.error({code:`DISCOVERY_NOT_FOUND`,message:`Discovery document not found: ${i}`,exitCode:1});r=t.readFileSync(i,`utf-8`)}let i;try{i=JSON.parse(r)}catch(t){return e.error({code:`DISCOVERY_INVALID_JSON`,message:`Invalid discovery JSON: ${t.message}`,exitCode:1})}let a=rE(i);if(!HL(e))for(let e of a)console.log(`[${e.severity}] ${e.path}: ${e.message}`);let o=a.filter(e=>e.severity===`error`).length,s=a.filter(e=>e.severity===`warning`).length;return o>0?e.error({code:`DISCOVERY_INVALID`,message:`Discovery document has ${o} error(s) and ${s} warning(s).`,exitCode:1}):UL(e,{errorCount:o,issues:a,valid:!0,warningCount:s},()=>{console.log(s>0?`Discovery document is valid with ${s} warning(s).`:`Discovery document is valid.`)})}});uR.command(dR),uR.command(hR),uR.command(pR),uR.command(mR),uR.command(aI),uR.command(fR),uR.command(SL);export{uR as default,iR as resolveMppCredentialTarget};