quirl-cli 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (3) hide show
  1. package/dist/quirl.mjs +350 -0
  2. package/package.json +28 -3
  3. package/README.md +0 -3
package/dist/quirl.mjs ADDED
@@ -0,0 +1,350 @@
1
+ #!/usr/bin/env node
2
+ import{createRequire as e}from"node:module";import{parseArgs as t,promisify as n}from"node:util";import r from"node:process";import{execFile as i,execFileSync as a,spawn as o}from"node:child_process";import{chmod as s,lstat as c,mkdir as l,readFile as u,readdir as d,rm as f,stat as p,writeFile as m}from"node:fs/promises";import{homedir as h,hostname as g}from"node:os";import _,{basename as v,dirname as y,isAbsolute as b,join as x,relative as S}from"node:path";import{createHash as C,randomUUID as w}from"node:crypto";import{existsSync as T}from"node:fs";import{createInterface as E}from"node:readline/promises";var ee=Object.create,te=Object.defineProperty,ne=Object.getOwnPropertyDescriptor,re=Object.getOwnPropertyNames,ie=Object.getPrototypeOf,ae=Object.prototype.hasOwnProperty,oe=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},D=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports),se=(e,t)=>{let n={};for(var r in e)te(n,r,{get:e[r],enumerable:!0});return t||te(n,Symbol.toStringTag,{value:`Module`}),n},ce=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=re(t),a=0,o=i.length,s;a<o;a++)s=i[a],!ae.call(e,s)&&s!==n&&te(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=ne(t,s))||r.enumerable});return e},le=(e,t,n)=>(n=e==null?{}:ee(ie(e)),ce(t||!e||!e.__esModule||!ae.call(e,`default`)?te(n,`default`,{value:e,enumerable:!0}):n,e)),ue=e=>ae.call(e,`module.exports`)?e[`module.exports`]:ce(te({},`__esModule`,{value:!0}),e),de=/* @__PURE__ */ e(import.meta.url);const fe=Symbol.for(`@supabase/supabase-js.traceContextExtractor`);function pe(){return globalThis[fe]}var me=/* @__PURE__ */ se({__addDisposableResource:()=>He,__assign:()=>Ke,__asyncDelegator:()=>Pe,__asyncGenerator:()=>Ne,__asyncValues:()=>Fe,__await:()=>Me,__awaiter:()=>we,__classPrivateFieldGet:()=>ze,__classPrivateFieldIn:()=>Ve,__classPrivateFieldSet:()=>Be,__createBinding:()=>qe,__decorate:()=>_e,__disposeResources:()=>Ue,__esDecorate:()=>ye,__exportStar:()=>Ee,__extends:()=>he,__generator:()=>Te,__importDefault:()=>Re,__importStar:()=>Le,__makeTemplateObject:()=>Ie,__metadata:()=>Ce,__param:()=>ve,__propKey:()=>xe,__read:()=>Oe,__rest:()=>ge,__rewriteRelativeImportExtension:()=>We,__runInitializers:()=>be,__setFunctionName:()=>Se,__spread:()=>ke,__spreadArray:()=>je,__spreadArrays:()=>Ae,__values:()=>De,default:()=>Ze});function he(e,t){if(typeof t!=`function`&&t!==null)throw TypeError(`Class extends value `+String(t)+` is not a constructor or null`);Ge(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}function ge(e,t){var n={};for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&t.indexOf(r)<0&&(n[r]=e[r]);if(e!=null&&typeof Object.getOwnPropertySymbols==`function`)for(var i=0,r=Object.getOwnPropertySymbols(e);i<r.length;i++)t.indexOf(r[i])<0&&Object.prototype.propertyIsEnumerable.call(e,r[i])&&(n[r[i]]=e[r[i]]);return n}function _e(e,t,n,r){var i=arguments.length,a=i<3?t:r===null?r=Object.getOwnPropertyDescriptor(t,n):r,o;if(typeof Reflect==`object`&&typeof Reflect.decorate==`function`)a=Reflect.decorate(e,t,n,r);else for(var s=e.length-1;s>=0;s--)(o=e[s])&&(a=(i<3?o(a):i>3?o(t,n,a):o(t,n))||a);return i>3&&a&&Object.defineProperty(t,n,a),a}function ve(e,t){return function(n,r){t(n,r,e)}}function ye(e,t,n,r,i,a){function o(e){if(e!==void 0&&typeof e!=`function`)throw TypeError(`Function expected`);return e}for(var s=r.kind,c=s===`getter`?`get`:s===`setter`?`set`:`value`,l=!t&&e?r.static?e:e.prototype:null,u=t||(l?Object.getOwnPropertyDescriptor(l,r.name):{}),d,f=!1,p=n.length-1;p>=0;p--){var m={};for(var h in r)m[h]=h===`access`?{}:r[h];for(var h in r.access)m.access[h]=r.access[h];m.addInitializer=function(e){if(f)throw TypeError(`Cannot add initializers after decoration has completed`);a.push(o(e||null))};var g=(0,n[p])(s===`accessor`?{get:u.get,set:u.set}:u[c],m);if(s===`accessor`){if(g===void 0)continue;if(typeof g!=`object`||!g)throw TypeError(`Object expected`);(d=o(g.get))&&(u.get=d),(d=o(g.set))&&(u.set=d),(d=o(g.init))&&i.unshift(d)}else(d=o(g))&&(s===`field`?i.unshift(d):u[c]=d)}l&&Object.defineProperty(l,r.name,u),f=!0}function be(e,t,n){for(var r=arguments.length>2,i=0;i<t.length;i++)n=r?t[i].call(e,n):t[i].call(e);return r?n:void 0}function xe(e){return typeof e==`symbol`?e:`${e}`}function Se(e,t,n){return typeof t==`symbol`&&(t=t.description?`[${t.description}]`:``),Object.defineProperty(e,"name",{configurable:!0,value:n?`${n} ${t}`:t})}function Ce(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)}function we(e,t,n,r){function i(e){return e instanceof n?e:new n(function(t){t(e)})}return new(n||=Promise)(function(n,a){function o(e){try{c(r.next(e))}catch(e){a(e)}}function s(e){try{c(r.throw(e))}catch(e){a(e)}}function c(e){e.done?n(e.value):i(e.value).then(o,s)}c((r=r.apply(e,t||[])).next())})}function Te(e,t){var n={label:0,sent:function(){if(a[0]&1)throw a[1];return a[1]},trys:[],ops:[]},r,i,a,o=Object.create((typeof Iterator==`function`?Iterator:Object).prototype);return o.next=s(0),o.throw=s(1),o.return=s(2),typeof Symbol==`function`&&(o[Symbol.iterator]=function(){return this}),o;function s(e){return function(t){return c([e,t])}}function c(s){if(r)throw TypeError(`Generator is already executing.`);for(;o&&(o=0,s[0]&&(n=0)),n;)try{if(r=1,i&&(a=s[0]&2?i.return:s[0]?i.throw||((a=i.return)&&a.call(i),0):i.next)&&!(a=a.call(i,s[1])).done)return a;switch(i=0,a&&(s=[s[0]&2,a.value]),s[0]){case 0:case 1:a=s;break;case 4:return n.label++,{value:s[1],done:!1};case 5:n.label++,i=s[1],s=[0];continue;case 7:s=n.ops.pop(),n.trys.pop();continue;default:if(a=n.trys,!(a=a.length>0&&a[a.length-1])&&(s[0]===6||s[0]===2)){n=0;continue}if(s[0]===3&&(!a||s[1]>a[0]&&s[1]<a[3])){n.label=s[1];break}if(s[0]===6&&n.label<a[1]){n.label=a[1],a=s;break}if(a&&n.label<a[2]){n.label=a[2],n.ops.push(s);break}a[2]&&n.ops.pop(),n.trys.pop();continue}s=t.call(e,n)}catch(e){s=[6,e],i=0}finally{r=a=0}if(s[0]&5)throw s[1];return{value:s[0]?s[1]:void 0,done:!0}}}function Ee(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&qe(t,e,n)}function De(e){var t=typeof Symbol==`function`&&Symbol.iterator,n=t&&e[t],r=0;if(n)return n.call(e);if(e&&typeof e.length==`number`)return{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}};throw TypeError(t?`Object is not iterable.`:`Symbol.iterator is not defined.`)}function Oe(e,t){var n=typeof Symbol==`function`&&e[Symbol.iterator];if(!n)return e;var r=n.call(e),i,a=[],o;try{for(;(t===void 0||t-->0)&&!(i=r.next()).done;)a.push(i.value)}catch(e){o={error:e}}finally{try{i&&!i.done&&(n=r.return)&&n.call(r)}finally{if(o)throw o.error}}return a}function ke(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(Oe(arguments[t]));return e}function Ae(){for(var e=0,t=0,n=arguments.length;t<n;t++)e+=arguments[t].length;for(var r=Array(e),i=0,t=0;t<n;t++)for(var a=arguments[t],o=0,s=a.length;o<s;o++,i++)r[i]=a[o];return r}function je(e,t,n){if(n||arguments.length===2)for(var r=0,i=t.length,a;r<i;r++)(a||!(r in t))&&(a||=Array.prototype.slice.call(t,0,r),a[r]=t[r]);return e.concat(a||Array.prototype.slice.call(t))}function Me(e){return this instanceof Me?(this.v=e,this):new Me(e)}function Ne(e,t,n){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var r=n.apply(e,t||[]),i,a=[];return i=Object.create((typeof AsyncIterator==`function`?AsyncIterator:Object).prototype),s(`next`),s(`throw`),s(`return`,o),i[Symbol.asyncIterator]=function(){return this},i;function o(e){return function(t){return Promise.resolve(t).then(e,d)}}function s(e,t){r[e]&&(i[e]=function(t){return new Promise(function(n,r){a.push([e,t,n,r])>1||c(e,t)})},t&&(i[e]=t(i[e])))}function c(e,t){try{l(r[e](t))}catch(e){f(a[0][3],e)}}function l(e){e.value instanceof Me?Promise.resolve(e.value.v).then(u,d):f(a[0][2],e)}function u(e){c(`next`,e)}function d(e){c(`throw`,e)}function f(e,t){e(t),a.shift(),a.length&&c(a[0][0],a[0][1])}}function Pe(e){var t={},n;return r(`next`),r(`throw`,function(e){throw e}),r(`return`),t[Symbol.iterator]=function(){return this},t;function r(r,i){t[r]=e[r]?function(t){return(n=!n)?{value:Me(e[r](t)),done:!1}:i?i(t):t}:i}}function Fe(e){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof De==`function`?De(e):e[Symbol.iterator](),n={},r(`next`),r(`throw`),r(`return`),n[Symbol.asyncIterator]=function(){return this},n);function r(t){n[t]=e[t]&&function(n){return new Promise(function(r,a){n=e[t](n),i(r,a,n.done,n.value)})}}function i(e,t,n,r){Promise.resolve(r).then(function(t){e({value:t,done:n})},t)}}function Ie(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}function Le(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=Ye(e),r=0;r<n.length;r++)n[r]!=="default"&&qe(t,e,n[r]);return Je(t,e),t}function Re(e){return e&&e.__esModule?e:{default:e}}function ze(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}function Be(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function Ve(e,t){if(t===null||typeof t!=`object`&&typeof t!=`function`)throw TypeError(`Cannot use 'in' operator on non-object`);return typeof e==`function`?t===e:e.has(t)}function He(e,t,n){if(t!=null){if(typeof t!=`object`&&typeof t!=`function`)throw TypeError(`Object expected.`);var r,i;if(n){if(!Symbol.asyncDispose)throw TypeError(`Symbol.asyncDispose is not defined.`);r=t[Symbol.asyncDispose]}if(r===void 0){if(!Symbol.dispose)throw TypeError(`Symbol.dispose is not defined.`);r=t[Symbol.dispose],n&&(i=r)}if(typeof r!=`function`)throw TypeError(`Object not disposable.`);i&&(r=function(){try{i.call(this)}catch(e){return Promise.reject(e)}}),e.stack.push({value:t,dispose:r,async:n})}else n&&e.stack.push({async:!0});return t}function Ue(e){function t(t){e.error=e.hasError?new Xe(t,e.error,`An error was suppressed during disposal.`):t,e.hasError=!0}var n,r=0;function i(){for(;n=e.stack.pop();)try{if(!n.async&&r===1)return r=0,e.stack.push(n),Promise.resolve().then(i);if(n.dispose){var a=n.dispose.call(n.value);if(n.async)return r|=2,Promise.resolve(a).then(i,function(e){return t(e),i()})}else r|=1}catch(e){t(e)}if(r===1)return e.hasError?Promise.reject(e.error):Promise.resolve();if(e.hasError)throw e.error}return i()}function We(e,t){return typeof e==`string`&&/^\.\.?\//.test(e)?e.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i,function(e,n,r,i,a){return n?t?`.jsx`:`.js`:r&&(!i||!a)?e:r+i+`.`+a.toLowerCase()+`js`}):e}var Ge,Ke,qe,Je,Ye,Xe,Ze,Qe=oe((()=>{Ge=function(e,t){return Ge=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,t){e.__proto__=t}||function(e,t){for(var n in t)Object.prototype.hasOwnProperty.call(t,n)&&(e[n]=t[n])},Ge(e,t)},Ke=function(){return Ke=Object.assign||function(e){for(var t,n=1,r=arguments.length;n<r;n++)for(var i in t=arguments[n],t)Object.prototype.hasOwnProperty.call(t,i)&&(e[i]=t[i]);return e},Ke.apply(this,arguments)},qe=Object.create?(function(e,t,n,r){r===void 0&&(r=n);var i=Object.getOwnPropertyDescriptor(t,n);(!i||(`get`in i?!t.__esModule:i.writable||i.configurable))&&(i={enumerable:!0,get:function(){return t[n]}}),Object.defineProperty(e,r,i)}):(function(e,t,n,r){r===void 0&&(r=n),e[r]=t[n]}),Je=Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t},Ye=function(e){return Ye=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},Ye(e)},Xe=typeof SuppressedError==`function`?SuppressedError:function(e,t,n){var r=Error(n);return r.name=`SuppressedError`,r.error=e,r.suppressed=t,r},Ze={__extends:he,__assign:Ke,__rest:ge,__decorate:_e,__param:ve,__esDecorate:ye,__runInitializers:be,__propKey:xe,__setFunctionName:Se,__metadata:Ce,__awaiter:we,__generator:Te,__createBinding:qe,__exportStar:Ee,__values:De,__read:Oe,__spread:ke,__spreadArrays:Ae,__spreadArray:je,__await:Me,__asyncGenerator:Ne,__asyncDelegator:Pe,__asyncValues:Fe,__makeTemplateObject:Ie,__importStar:Le,__importDefault:Re,__classPrivateFieldGet:ze,__classPrivateFieldSet:Be,__classPrivateFieldIn:Ve,__addDisposableResource:He,__disposeResources:Ue,__rewriteRelativeImportExtension:We}})),$e=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveFetch=void 0,e.resolveFetch=e=>e?(...t)=>e(...t):(...e)=>fetch(...e)})),et=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.FunctionRegion=e.FunctionsHttpError=e.FunctionsRelayError=e.FunctionsFetchError=e.FunctionsError=void 0;var t=class extends Error{constructor(e,t=`FunctionsError`,n){super(e),this.name=t,this.context=n}toJSON(){return{name:this.name,message:this.message,context:this.context}}};e.FunctionsError=t,e.FunctionsFetchError=class extends t{constructor(e){super(`Failed to send a request to the Edge Function`,`FunctionsFetchError`,e)}},e.FunctionsRelayError=class extends t{constructor(e){super(`Relay Error invoking the Edge Function`,`FunctionsRelayError`,e)}},e.FunctionsHttpError=class extends t{constructor(e){super(`Edge Function returned a non-2xx status code`,`FunctionsHttpError`,e)}};var n;(function(e){e.Any=`any`,e.ApNortheast1=`ap-northeast-1`,e.ApNortheast2=`ap-northeast-2`,e.ApSouth1=`ap-south-1`,e.ApSoutheast1=`ap-southeast-1`,e.ApSoutheast2=`ap-southeast-2`,e.CaCentral1=`ca-central-1`,e.EuCentral1=`eu-central-1`,e.EuWest1=`eu-west-1`,e.EuWest2=`eu-west-2`,e.EuWest3=`eu-west-3`,e.SaEast1=`sa-east-1`,e.UsEast1=`us-east-1`,e.UsWest1=`us-west-1`,e.UsWest2=`us-west-2`})(n||(e.FunctionRegion=n={}))})),tt=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.FunctionsClient=void 0;let t=(Qe(),ue(me)),n=$e(),r=et();e.FunctionsClient=class{constructor(e,{headers:t={},customFetch:i,region:a=r.FunctionRegion.Any}={}){this.url=e,this.headers=t,this.region=a,this.fetch=(0,n.resolveFetch)(i)}setAuth(e){this.headers.Authorization=`Bearer ${e}`}invoke(e){return t.__awaiter(this,arguments,void 0,function*(e,t={}){var n;let i,a,o;try{let{headers:n,method:s,body:c,signal:l,timeout:u}=t,d={},{region:f}=t;f||=this.region;let p=new URL(`${this.url}/${e}`);f&&f!==`any`&&(d[`x-region`]=f,p.searchParams.set(`forceFunctionRegion`,f));let m,h=!!n&&Object.keys(n).some(e=>e.toLowerCase()===`content-type`);c&&!h?typeof Blob<`u`&&c instanceof Blob||c instanceof ArrayBuffer?(d[`Content-Type`]=c.type||`application/octet-stream`,m=c):typeof c==`string`?(d[`Content-Type`]=`text/plain`,m=c):typeof FormData<`u`&&c instanceof FormData?m=c:(d[`Content-Type`]=`application/json`,m=JSON.stringify(c)):m=c&&typeof c!=`string`&&!(typeof Blob<`u`&&c instanceof Blob)&&!(c instanceof ArrayBuffer)&&!(typeof FormData<`u`&&c instanceof FormData)?JSON.stringify(c):c;let g=l;u&&(a=new AbortController,i=setTimeout(()=>a.abort(),u),l?(g=a.signal,o=()=>a.abort(),l.addEventListener(`abort`,o)):g=a.signal);let _=yield this.fetch(p.toString(),{method:s||`POST`,headers:Object.assign(Object.assign(Object.assign({},d),this.headers),n),body:m,signal:g}).catch(e=>{throw new r.FunctionsFetchError(e)}),v=_.headers.get(`x-relay-error`);if(v&&v===`true`)throw new r.FunctionsRelayError(_);if(!_.ok)throw new r.FunctionsHttpError(_);let y=(_.headers.get(`Content-Type`)??`text/plain`).split(`;`)[0].trim().toLowerCase(),b;return b=y===`application/json`?yield _.json():y===`application/octet-stream`||y===`application/pdf`?yield _.blob():y===`text/event-stream`?_:y===`multipart/form-data`?yield _.formData():yield _.text(),{data:b,error:null,response:_}}catch(e){return{data:null,error:e,response:e instanceof r.FunctionsHttpError||e instanceof r.FunctionsRelayError?e.context:void 0}}finally{i&&clearTimeout(i),o&&((n=t.signal)==null||n.removeEventListener(`abort`,o))}})}}})),nt=(/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.FunctionRegion=e.FunctionsRelayError=e.FunctionsHttpError=e.FunctionsFetchError=e.FunctionsError=e.FunctionsClient=void 0;var t=tt();Object.defineProperty(e,"FunctionsClient",{enumerable:!0,get:function(){return t.FunctionsClient}});var n=et();Object.defineProperty(e,"FunctionsError",{enumerable:!0,get:function(){return n.FunctionsError}}),Object.defineProperty(e,"FunctionsFetchError",{enumerable:!0,get:function(){return n.FunctionsFetchError}}),Object.defineProperty(e,"FunctionsHttpError",{enumerable:!0,get:function(){return n.FunctionsHttpError}}),Object.defineProperty(e,"FunctionsRelayError",{enumerable:!0,get:function(){return n.FunctionsRelayError}}),Object.defineProperty(e,"FunctionRegion",{enumerable:!0,get:function(){return n.FunctionRegion}})})))(),rt=class extends Error{constructor(e){super(e.message),this.name=`PostgrestError`,this.details=e.details,this.hint=e.hint,this.code=e.code}toJSON(){return{name:this.name,message:this.message,details:this.details,hint:this.hint,code:this.code}}};const it=e=>Math.min(1e3*2**e,3e4),at=[520,503],ot=[`GET`,`HEAD`,`OPTIONS`];function st(e){"@babel/helpers - typeof";return st=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},st(e)}function ct(e,t){if(st(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(st(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function lt(e){var t=ct(e,`string`);return st(t)==`symbol`?t:t+``}function ut(e,t,n){return(t=lt(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function dt(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function ft(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?dt(Object(n),!0).forEach(function(t){ut(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):dt(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function pt(e,t){return new Promise(n=>{if(t?.aborted){n();return}let r=setTimeout(()=>{t?.removeEventListener(`abort`,i),n()},e);function i(){clearTimeout(r),n()}t?.addEventListener(`abort`,i)})}function mt(e,t,n,r){return!(!r||n>=3||!ot.includes(e)||!at.includes(t))}async function ht(e,t,n,r){let i=0;for(;;){let a=ft({},n.headers);i>0&&(a[`X-Retry-Count`]=String(i));let o;try{o=await e(t,{method:n.method,headers:a,body:n.body,signal:n.signal})}catch(e){if(e?.name===`AbortError`||e?.code===`ABORT_ERR`||e?.name===`TimeoutError`&&n.signal?.aborted||!ot.includes(n.method))throw e;if(r&&i<3){let e=it(i);i++,await pt(e,n.signal);continue}throw e}if(mt(n.method,o.status,i,r)){let e=o.headers?.get(`Retry-After`)??null,t=e===null?it(i):Math.max(0,parseInt(e,10)||0)*1e3;await o.text(),i++,await pt(t,n.signal)}else return o}}var gt=class{constructor(e){this.shouldThrowOnError=!1,this.retryEnabled=!0,this.method=e.method,this.url=e.url,this.headers=new Headers(e.headers),this.schema=e.schema,this.body=e.body,this.shouldThrowOnError=e.shouldThrowOnError??!1,this.signal=e.signal,this.isMaybeSingle=e.isMaybeSingle??!1,this.shouldStripNulls=e.shouldStripNulls??!1,this.urlLengthLimit=e.urlLengthLimit??8e3,this.retryEnabled=e.retry??!0,this.fetch=e.fetch?e.fetch:fetch}throwOnError(){return this.shouldThrowOnError=!0,this}stripNulls(){if(this.headers.get(`Accept`)===`text/csv`)throw Error(`stripNulls() cannot be used with csv()`);return this.shouldStripNulls=!0,this}setHeader(e,t){return this.headers=new Headers(this.headers),this.headers.set(e,t),this}retry(e){return this.retryEnabled=e,this}then(e,t){var n=this;if(this.schema===void 0||([`GET`,`HEAD`].includes(this.method)?this.headers.set(`Accept-Profile`,this.schema):this.headers.set(`Content-Profile`,this.schema)),this.method!==`GET`&&this.method!==`HEAD`&&this.headers.set(`Content-Type`,`application/json`),this.shouldStripNulls){let e=this.headers.get(`Accept`);e===`application/vnd.pgrst.object+json`?this.headers.set(`Accept`,`application/vnd.pgrst.object+json;nulls=stripped`):e&&e!==`application/json`||this.headers.set(`Accept`,`application/vnd.pgrst.array+json;nulls=stripped`)}let r=this.fetch,i=(async()=>{let e={};n.headers.forEach((t,n)=>{e[n]=t});let t=await ht(r,n.url.toString(),{method:n.method,headers:e,body:JSON.stringify(n.body,(e,t)=>typeof t==`bigint`?t.toString():t),signal:n.signal},n.retryEnabled);return await n.processResponse(t)})();return this.shouldThrowOnError||(i=i.catch(e=>{let t=``,n=``,r=``,i=e?.cause;if(i){let n=i?.message??``,r=i?.code??``;t=`${e?.name??`FetchError`}: ${e?.message}`,t+=`\n\nCaused by: ${i?.name??`Error`}: ${n}`,r&&(t+=` (${r})`),i?.stack&&(t+=`\n${i.stack}`)}else t=e?.stack??``;let a=this.url.toString().length;return e?.name===`AbortError`||e?.code===`ABORT_ERR`?(r=``,n=`Request was aborted (timeout or manual cancellation)`,a>this.urlLengthLimit&&(n+=`. Note: Your request URL is ${a} characters, which may exceed server limits. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [many IDs])), consider using an RPC function to pass values server-side.`)):(i?.name===`HeadersOverflowError`||i?.code===`UND_ERR_HEADERS_OVERFLOW`)&&(r=``,n=`HTTP headers exceeded server limits (typically 16KB)`,a>this.urlLengthLimit&&(n+=`. Your request URL is ${a} characters. If selecting many fields, consider using views. If filtering with large arrays (e.g., .in('id', [200+ IDs])), consider using an RPC function instead.`)),{success:!1,error:{message:`${e?.name??`FetchError`}: ${e?.message}`,details:t,hint:n,code:r},data:null,count:null,status:0,statusText:``}})),i.then(e,t)}async processResponse(e){var t=this;let n=null,r=null,i=null,a=e.status,o=e.statusText;if(e.ok){if(t.method!==`HEAD`){let i=await e.text();if(i!==``){if(t.headers.get(`Accept`)===`text/csv`)r=i;else if(t.headers.get(`Accept`)&&t.headers.get(`Accept`)?.includes(`application/vnd.pgrst.plan+text`))r=i;else try{r=JSON.parse(i)}catch{if(n={message:i},r=null,t.shouldThrowOnError)throw new rt({message:i,details:``,hint:``,code:``})}}}let s=t.headers.get(`Prefer`)?.match(/count=(exact|planned|estimated)/),c=e.headers.get(`content-range`)?.split(`/`);if(s&&c&&c.length>1&&(i=parseInt(c[1])),t.isMaybeSingle&&Array.isArray(r)){if(r.length>1){if(n={code:`PGRST116`,details:`Results contain ${r.length} rows, application/vnd.pgrst.object+json requires 1 row`,hint:null,message:`JSON object requested, multiple (or no) rows returned`},r=null,i=null,a=406,o=`Not Acceptable`,t.shouldThrowOnError)throw new rt(ft(ft({},n),{},{hint:n.hint??``}))}else r=r.length===1?r[0]:null}}else{let i=await e.text();try{n=JSON.parse(i),Array.isArray(n)&&e.status===404&&(r=[],n=null,a=200,o=`OK`)}catch{e.status===404&&i===``?(a=204,o=`No Content`):n={message:i}}if(n&&t.shouldThrowOnError)throw new rt(n)}return{success:n===null,error:n,data:r,count:i,status:a,statusText:o}}returns(){
3
+ /* istanbul ignore next */
4
+ return this}overrideTypes(){return this}},_t=class extends gt{throwOnError(){return super.throwOnError()}select(e){let t=!1,n=(e??`*`).split(``).map(e=>/\s/.test(e)&&!t?``:(e===`"`&&(t=!t),e)).join(``);return this.url.searchParams.set(`select`,n),this.headers.append(`Prefer`,`return=representation`),this}order(e,{ascending:t=!0,nullsFirst:n,foreignTable:r,referencedTable:i=r}={}){let a=i?`${i}.order`:`order`,o=this.url.searchParams.get(a);return this.url.searchParams.set(a,`${o?`${o},`:``}${e}.${t?`asc`:`desc`}${n===void 0?``:n?`.nullsfirst`:`.nullslast`}`),this}limit(e,{foreignTable:t,referencedTable:n=t}={}){let r=n===void 0?`limit`:`${n}.limit`;return this.url.searchParams.set(r,`${e}`),this}range(e,t,{foreignTable:n,referencedTable:r=n}={}){let i=r===void 0?`offset`:`${r}.offset`,a=r===void 0?`limit`:`${r}.limit`;return this.url.searchParams.set(i,`${e}`),this.url.searchParams.set(a,`${t-e+1}`),this}abortSignal(e){return this.signal=e,this}single(){return this.headers.set(`Accept`,`application/vnd.pgrst.object+json`),this}maybeSingle(){return this.isMaybeSingle=!0,this}csv(){return this.headers.set(`Accept`,`text/csv`),this}geojson(){return this.headers.set(`Accept`,`application/geo+json`),this}explain({analyze:e=!1,verbose:t=!1,settings:n=!1,buffers:r=!1,wal:i=!1,format:a=`text`}={}){let o=[e?`analyze`:null,t?`verbose`:null,n?`settings`:null,r?`buffers`:null,i?`wal`:null].filter(Boolean).join(`|`),s=this.headers.get(`Accept`)??`application/json`;return this.headers.set(`Accept`,`application/vnd.pgrst.plan+${a}; for="${s}"; options=${o};`),this}rollback(){return this.headers.append(`Prefer`,`tx=rollback`),this}returns(){return this}maxAffected(e){return this.headers.append(`Prefer`,`handling=strict`),this.headers.append(`Prefer`,`max-affected=${e}`),this}};const vt=/* @__PURE__ */ RegExp(`[,()]`);var yt=class extends _t{throwOnError(){return super.throwOnError()}eq(e,t){return this.url.searchParams.append(e,`eq.${t}`),this}neq(e,t){return this.url.searchParams.append(e,`neq.${t}`),this}gt(e,t){return this.url.searchParams.append(e,`gt.${t}`),this}gte(e,t){return this.url.searchParams.append(e,`gte.${t}`),this}lt(e,t){return this.url.searchParams.append(e,`lt.${t}`),this}lte(e,t){return this.url.searchParams.append(e,`lte.${t}`),this}like(e,t){return this.url.searchParams.append(e,`like.${t}`),this}likeAllOf(e,t){return this.url.searchParams.append(e,`like(all).{${t.join(`,`)}}`),this}likeAnyOf(e,t){return this.url.searchParams.append(e,`like(any).{${t.join(`,`)}}`),this}ilike(e,t){return this.url.searchParams.append(e,`ilike.${t}`),this}ilikeAllOf(e,t){return this.url.searchParams.append(e,`ilike(all).{${t.join(`,`)}}`),this}ilikeAnyOf(e,t){return this.url.searchParams.append(e,`ilike(any).{${t.join(`,`)}}`),this}regexMatch(e,t){return this.url.searchParams.append(e,`match.${t}`),this}regexIMatch(e,t){return this.url.searchParams.append(e,`imatch.${t}`),this}is(e,t){return this.url.searchParams.append(e,`is.${t}`),this}isDistinct(e,t){return this.url.searchParams.append(e,`isdistinct.${t}`),this}in(e,t){let n=Array.from(new Set(t)).map(e=>typeof e==`string`&&vt.test(e)?`"${e}"`:`${e}`).join(`,`);return this.url.searchParams.append(e,`in.(${n})`),this}notIn(e,t){let n=Array.from(new Set(t)).map(e=>typeof e==`string`&&vt.test(e)?`"${e}"`:`${e}`).join(`,`);return this.url.searchParams.append(e,`not.in.(${n})`),this}contains(e,t){return typeof t==`string`?this.url.searchParams.append(e,`cs.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cs.{${t.join(`,`)}}`):this.url.searchParams.append(e,`cs.${JSON.stringify(t)}`),this}containedBy(e,t){return typeof t==`string`?this.url.searchParams.append(e,`cd.${t}`):Array.isArray(t)?this.url.searchParams.append(e,`cd.{${t.join(`,`)}}`):this.url.searchParams.append(e,`cd.${JSON.stringify(t)}`),this}rangeGt(e,t){return this.url.searchParams.append(e,`sr.${t}`),this}rangeGte(e,t){return this.url.searchParams.append(e,`nxl.${t}`),this}rangeLt(e,t){return this.url.searchParams.append(e,`sl.${t}`),this}rangeLte(e,t){return this.url.searchParams.append(e,`nxr.${t}`),this}rangeAdjacent(e,t){return this.url.searchParams.append(e,`adj.${t}`),this}overlaps(e,t){return typeof t==`string`?this.url.searchParams.append(e,`ov.${t}`):this.url.searchParams.append(e,`ov.{${t.join(`,`)}}`),this}textSearch(e,t,{config:n,type:r}={}){let i=``;r===`plain`?i=`pl`:r===`phrase`?i=`ph`:r===`websearch`&&(i=`w`);let a=n===void 0?``:`(${n})`;return this.url.searchParams.append(e,`${i}fts${a}.${t}`),this}match(e){return Object.entries(e).filter(([e,t])=>t!==void 0).forEach(([e,t])=>{this.url.searchParams.append(e,`eq.${t}`)}),this}not(e,t,n){return this.url.searchParams.append(e,`not.${t}.${n}`),this}or(e,{foreignTable:t,referencedTable:n=t}={}){let r=n?`${n}.or`:`or`;return this.url.searchParams.append(r,`(${e})`),this}filter(e,t,n){return this.url.searchParams.append(e,`${t}.${n}`),this}},bt=class{constructor(e,{headers:t={},schema:n,fetch:r,urlLengthLimit:i=8e3,retry:a}){this.url=e,this.headers=new Headers(t),this.schema=n,this.fetch=r,this.urlLengthLimit=i,this.retry=a}cloneRequestState(){return{url:new URL(this.url.toString()),headers:new Headers(this.headers)}}select(e,t){let{head:n=!1,count:r}=t??{},i=n?`HEAD`:`GET`,a=!1,o=(e??`*`).split(``).map(e=>/\s/.test(e)&&!a?``:(e===`"`&&(a=!a),e)).join(``),{url:s,headers:c}=this.cloneRequestState();return s.searchParams.set(`select`,o),r&&c.append(`Prefer`,`count=${r}`),new yt({method:i,url:s,headers:c,schema:this.schema,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}insert(e,{count:t,defaultToNull:n=!0}={}){let{url:r,headers:i}=this.cloneRequestState();if(t&&i.append(`Prefer`,`count=${t}`),n||i.append(`Prefer`,`missing=default`),Array.isArray(e)){let t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){let e=[...new Set(t)].map(e=>`"${e}"`);r.searchParams.set(`columns`,e.join(`,`))}}return new yt({method:`POST`,url:r,headers:i,schema:this.schema,body:e,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}upsert(e,{onConflict:t,ignoreDuplicates:n=!1,count:r,defaultToNull:i=!0}={}){let{url:a,headers:o}=this.cloneRequestState();if(o.append(`Prefer`,`resolution=${n?`ignore`:`merge`}-duplicates`),t!==void 0&&a.searchParams.set(`on_conflict`,t),r&&o.append(`Prefer`,`count=${r}`),i||o.append(`Prefer`,`missing=default`),Array.isArray(e)){let t=e.reduce((e,t)=>e.concat(Object.keys(t)),[]);if(t.length>0){let e=[...new Set(t)].map(e=>`"${e}"`);a.searchParams.set(`columns`,e.join(`,`))}}return new yt({method:`POST`,url:a,headers:o,schema:this.schema,body:e,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}update(e,{count:t}={}){let{url:n,headers:r}=this.cloneRequestState();return t&&r.append(`Prefer`,`count=${t}`),new yt({method:`PATCH`,url:n,headers:r,schema:this.schema,body:e,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}delete({count:e}={}){let{url:t,headers:n}=this.cloneRequestState();return e&&n.append(`Prefer`,`count=${e}`),new yt({method:`DELETE`,url:t,headers:n,schema:this.schema,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};function xt(e,t){try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return new rt({message:String(t.message??e),details:t.details??``,hint:t.hint??``,code:t.code??``})}catch{}return new rt({message:e||t,details:``,hint:``,code:``})}function St(e,t,n){let r=e;return{success:!1,error:new rt({message:`${r?.name??`FetchError`}: ${r?.message}`,details:``,hint:``,code:``}),data:null,count:null,status:t,statusText:n}}var Ct=class e{constructor(e,{headers:t={},schema:n,fetch:r,timeout:i,urlLengthLimit:a=8e3,retry:o}={}){this.url=e,this.headers=new Headers(t),this.schemaName=n,this.urlLengthLimit=a;let s=r??globalThis.fetch;this.fetch=i!==void 0&&i>0?(e,t)=>{let n=new AbortController,r=setTimeout(()=>n.abort(),i),a=t?.signal;if(a){if(a.aborted)return clearTimeout(r),s(e,t);let i=()=>{clearTimeout(r),n.abort()};return a.addEventListener(`abort`,i,{once:!0}),s(e,ft(ft({},t),{},{signal:n.signal})).finally(()=>{clearTimeout(r),a.removeEventListener(`abort`,i)})}return s(e,ft(ft({},t),{},{signal:n.signal})).finally(()=>clearTimeout(r))}:s,this.retry=o}from(e){if(!e||typeof e!=`string`||e.trim()===``)throw Error(`Invalid relation name: relation must be a non-empty string.`);return new bt(new URL(`${this.url}/${e}`),{headers:new Headers(this.headers),schema:this.schemaName,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}schema(t){return new e(this.url,{headers:this.headers,schema:t,fetch:this.fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}async getOpenApiSpec(){var e=this;let t=new Headers(e.headers);t.set(`Accept`,`application/openapi+json`),e.schemaName&&t.set(`Accept-Profile`,e.schemaName);let n={};t.forEach((e,t)=>{n[t]=e});let r=e.fetch??globalThis.fetch,i;try{i=await ht(r,`${e.url}/`,{method:`GET`,headers:n},e.retry??!0)}catch(e){return St(e,0,``)}let a;try{a=await i.text()}catch(e){return St(e,i.status,i.statusText)}if(i.ok)try{return{success:!0,error:null,data:JSON.parse(a),count:null,status:i.status,statusText:i.statusText}}catch{}return{success:!1,error:xt(a,i.statusText),data:null,count:null,status:i.status,statusText:i.statusText}}rpc(e,t={},{head:n=!1,get:r=!1,count:i}={}){let a,o=new URL(`${this.url}/rpc/${e}`),s,c=e=>typeof e==`object`&&!!e&&(!Array.isArray(e)||e.some(c)),l=n&&Object.values(t).some(c);l?(a=`POST`,s=t):n||r?(a=n?`HEAD`:`GET`,Object.entries(t).filter(([e,t])=>t!==void 0).map(([e,t])=>[e,Array.isArray(t)?`{${t.join(`,`)}}`:`${t}`]).forEach(([e,t])=>{o.searchParams.append(e,t)})):(a=`POST`,s=t);let u=new Headers(this.headers);return l?u.set(`Prefer`,i?`count=${i},return=minimal`:`return=minimal`):i&&u.set(`Prefer`,`count=${i}`),new yt({method:a,url:o,headers:u,schema:this.schemaName,body:s,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}},wt=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.WebSocketFactory=void 0;var t=class{constructor(){}static detectEnvironment(){if(typeof WebSocket<`u`)return{type:`native`,wsConstructor:WebSocket};let e=globalThis;if(typeof globalThis<`u`&&e.WebSocket!==void 0)return{type:`native`,wsConstructor:e.WebSocket};let t=typeof global<`u`?global:void 0;if(t&&t.WebSocket!==void 0)return{type:`native`,wsConstructor:t.WebSocket};if(typeof globalThis<`u`&&e.WebSocketPair!==void 0&&globalThis.WebSocket===void 0)return{type:`cloudflare`,error:`Cloudflare Workers detected. WebSocket clients are not supported in Cloudflare Workers.`,workaround:`Use Cloudflare Workers WebSocket API for server-side WebSocket handling, or deploy to a different runtime.`};if(typeof globalThis<`u`&&e.EdgeRuntime||typeof navigator<`u`&&navigator.userAgent?.includes(`Vercel-Edge`))return{type:`unsupported`,error:`Edge runtime detected (Vercel Edge/Netlify Edge). WebSockets are not supported in edge functions.`,workaround:`Use serverless functions or a different deployment target for WebSocket functionality.`};let n=globalThis.process;if(n){let e=n.versions;if(e&&e.node)return{type:`unsupported`,error:`Node.js detected but native WebSocket not found.`,workaround:`Ensure you are running Node.js 22+ or provide a WebSocket implementation via the transport option.`}}return{type:`unsupported`,error:`Unknown JavaScript runtime without WebSocket support.`,workaround:`Ensure you're running in a supported environment (browser, Node.js, Deno) or provide a custom WebSocket implementation.`}}static getWebSocketConstructor(){let e=this.detectEnvironment();if(e.wsConstructor)return e.wsConstructor;let t=e.error||`WebSocket not supported in this environment.`;throw e.workaround&&(t+=`\n\nSuggested solution: ${e.workaround}`),Error(t)}static isWebSocketSupported(){try{return this.detectEnvironment().type===`native`}catch{return!1}}};e.WebSocketFactory=t,e.default=t})),Tt=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.version=void 0,e.version=`2.118.0`})),Et=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CONNECTION_STATE=e.TRANSPORTS=e.CHANNEL_EVENTS=e.CHANNEL_STATES=e.SOCKET_STATES=e.MAX_PUSH_BUFFER_SIZE=e.WS_CLOSE_NORMAL=e.POSTGRES_CHANGES_WAIT_ERROR_GRACE=e.DEFAULT_POSTGRES_CHANGES_WAIT_TIMEOUT=e.DEFAULT_TIMEOUT=e.VERSION=e.DEFAULT_VSN=e.VSN_2_0_0=e.VSN_1_0_0=e.DEFAULT_VERSION=void 0;let t=Tt();e.DEFAULT_VERSION=`realtime-js/${t.version}`,e.VSN_1_0_0=`1.0.0`,e.VSN_2_0_0=`2.0.0`,e.DEFAULT_VSN=e.VSN_2_0_0,e.VERSION=t.version,e.DEFAULT_TIMEOUT=1e4,e.DEFAULT_POSTGRES_CHANGES_WAIT_TIMEOUT=15e3,e.POSTGRES_CHANGES_WAIT_ERROR_GRACE=1e4,e.WS_CLOSE_NORMAL=1e3,e.MAX_PUSH_BUFFER_SIZE=100,e.SOCKET_STATES={connecting:0,open:1,closing:2,closed:3},e.CHANNEL_STATES={closed:`closed`,errored:`errored`,joined:`joined`,joining:`joining`,leaving:`leaving`},e.CHANNEL_EVENTS={close:`phx_close`,error:`phx_error`,join:`phx_join`,reply:`phx_reply`,leave:`phx_leave`,access_token:`access_token`},e.TRANSPORTS={websocket:`websocket`},e.CONNECTION_STATE={connecting:`connecting`,open:`open`,closing:`closing`,closed:`closed`}})),Dt=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=class{constructor(e){this.HEADER_LENGTH=1,this.USER_BROADCAST_PUSH_META_LENGTH=6,this.KINDS={userBroadcastPush:3,userBroadcast:4},this.BINARY_ENCODING=0,this.JSON_ENCODING=1,this.BROADCAST_EVENT=`broadcast`,this.allowedMetadataKeys=[],this.allowedMetadataKeys=e??[]}encode(e,t){if(e.event===this.BROADCAST_EVENT&&!(e.payload instanceof ArrayBuffer)&&typeof e.payload.event==`string`)return t(this._binaryEncodeUserBroadcastPush(e));let n=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(n))}_binaryEncodeUserBroadcastPush(e){return this._isArrayBuffer(e.payload?.payload)?this._encodeBinaryUserBroadcastPush(e):this._encodeJsonUserBroadcastPush(e)}_encodeBinaryUserBroadcastPush(e){let t=e.payload?.payload??/* @__PURE__ */ new ArrayBuffer(0);return this._encodeUserBroadcastPush(e,this.BINARY_ENCODING,t)}_encodeJsonUserBroadcastPush(e){let t=e.payload?.payload??{},n=new TextEncoder().encode(JSON.stringify(t)).buffer;return this._encodeUserBroadcastPush(e,this.JSON_ENCODING,n)}_encodeUserBroadcastPush(e,t,n){let r=new TextEncoder,i=r.encode(e.topic),a=r.encode(e.ref??``),o=r.encode(e.join_ref??``),s=r.encode(e.payload.event),c=this.allowedMetadataKeys?this._pick(e.payload,this.allowedMetadataKeys):{},l=r.encode(Object.keys(c).length===0?``:JSON.stringify(c));if(o.length>255)throw Error(`joinRef length ${o.length} exceeds maximum of 255`);if(a.length>255)throw Error(`ref length ${a.length} exceeds maximum of 255`);if(i.length>255)throw Error(`topic length ${i.length} exceeds maximum of 255`);if(s.length>255)throw Error(`userEvent length ${s.length} exceeds maximum of 255`);if(l.length>255)throw Error(`metadata length ${l.length} exceeds maximum of 255`);let u=this.USER_BROADCAST_PUSH_META_LENGTH+o.length+a.length+i.length+s.length+l.length,d=new ArrayBuffer(this.HEADER_LENGTH+u),f=new DataView(d),p=new Uint8Array(d),m=0;f.setUint8(m++,this.KINDS.userBroadcastPush),f.setUint8(m++,o.length),f.setUint8(m++,a.length),f.setUint8(m++,i.length),f.setUint8(m++,s.length),f.setUint8(m++,l.length),f.setUint8(m++,t),p.set(o,m),m+=o.length,p.set(a,m),m+=a.length,p.set(i,m),m+=i.length,p.set(s,m),m+=s.length,p.set(l,m),m+=l.length;var h=new Uint8Array(d.byteLength+n.byteLength);return h.set(new Uint8Array(d),0),h.set(new Uint8Array(n),d.byteLength),h.buffer}decode(e,t){if(this._isArrayBuffer(e))return t(this._binaryDecode(e));if(typeof e==`string`){let[n,r,i,a,o]=JSON.parse(e);return t({join_ref:n,ref:r,topic:i,event:a,payload:o})}return t({})}_binaryDecode(e){let t=new DataView(e),n=t.getUint8(0),r=new TextDecoder;switch(n){case this.KINDS.userBroadcast:return this._decodeUserBroadcast(e,t,r)}}_decodeUserBroadcast(e,t,n){let r=t.getUint8(1),i=t.getUint8(2),a=t.getUint8(3),o=t.getUint8(4),s=this.HEADER_LENGTH+4,c=n.decode(e.slice(s,s+r));s+=r;let l=n.decode(e.slice(s,s+i));s+=i;let u=n.decode(e.slice(s,s+a));s+=a;let d=e.slice(s,e.byteLength),f=o===this.JSON_ENCODING?JSON.parse(n.decode(d)):d,p={type:this.BROADCAST_EVENT,event:l,payload:f};return a>0&&(p.meta=JSON.parse(u)),{join_ref:null,ref:null,topic:c,event:this.BROADCAST_EVENT,payload:p}}_isArrayBuffer(e){return e instanceof ArrayBuffer||e?.constructor?.name===`ArrayBuffer`}_pick(e,t){return!e||typeof e!=`object`?{}:Object.fromEntries(Object.entries(e).filter(([e])=>t.includes(e)))}}})),Ot=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.httpEndpointURL=e.toTimestampString=e.toArray=e.toJson=e.toNumber=e.toBoolean=e.convertCell=e.convertColumn=e.convertChangeData=e.PostgresTypes=void 0;var t;(function(e){e.abstime=`abstime`,e.bool=`bool`,e.date=`date`,e.daterange=`daterange`,e.float4=`float4`,e.float8=`float8`,e.int2=`int2`,e.int4=`int4`,e.int4range=`int4range`,e.int8=`int8`,e.int8range=`int8range`,e.json=`json`,e.jsonb=`jsonb`,e.money=`money`,e.numeric=`numeric`,e.oid=`oid`,e.reltime=`reltime`,e.text=`text`,e.time=`time`,e.timestamp=`timestamp`,e.timestamptz=`timestamptz`,e.timetz=`timetz`,e.tsrange=`tsrange`,e.tstzrange=`tstzrange`})(t||(e.PostgresTypes=t={})),e.convertChangeData=(t,n,r={})=>{let i=r.skipTypes??[];return n?Object.keys(n).reduce((r,a)=>(r[a]=(0,e.convertColumn)(a,t,n,i),r),{}):{}},e.convertColumn=(t,r,i,a)=>{let o=r.find(e=>e.name===t)?.type,s=i[t];return o&&!a.includes(o)?(0,e.convertCell)(o,s):n(s)},e.convertCell=(r,i)=>{if(r.charAt(0)===`_`){let t=r.slice(1,r.length);return(0,e.toArray)(i,t)}switch(r){case t.bool:return(0,e.toBoolean)(i);case t.float4:case t.float8:case t.int2:case t.int4:case t.int8:case t.numeric:case t.oid:return(0,e.toNumber)(i);case t.json:case t.jsonb:return(0,e.toJson)(i);case t.timestamp:return(0,e.toTimestampString)(i);case t.abstime:case t.date:case t.daterange:case t.int4range:case t.int8range:case t.money:case t.reltime:case t.text:case t.time:case t.timestamptz:case t.timetz:case t.tsrange:case t.tstzrange:return n(i);default:return n(i)}};let n=e=>e;e.toBoolean=e=>{switch(e){case`t`:return!0;case`f`:return!1;default:return e}},e.toNumber=e=>{if(typeof e==`string`){let t=parseFloat(e);if(!Number.isNaN(t))return t}return e},e.toJson=e=>{if(typeof e==`string`)try{return JSON.parse(e)}catch{return e}return e},e.toArray=(t,n)=>{if(typeof t!=`string`)return t;let r=t.length-1,i=t[r];if(t[0]===`{`&&i===`}`){let i,a=t.slice(1,r);try{i=JSON.parse(`[`+a+`]`)}catch{i=a?a.split(`,`):[]}return i.map(t=>(0,e.convertCell)(n,t))}return t},e.toTimestampString=e=>typeof e==`string`?e.replace(` `,`T`):e,e.httpEndpointURL=e=>{let t=new URL(e);return t.protocol=t.protocol.replace(/^ws/i,`http`),t.pathname=t.pathname.replace(/\/+$/,``).replace(/\/socket\/websocket$/i,``).replace(/\/socket$/i,``).replace(/\/websocket$/i,``),t.pathname===``||t.pathname===`/`?t.pathname=`/api/broadcast`:t.pathname+=`/api/broadcast`,t.href}})),kt=/* @__PURE__ */ D(((e,t)=>{var n=Object.defineProperty,r=Object.getOwnPropertyDescriptor,i=Object.getOwnPropertyNames,a=Object.prototype.hasOwnProperty,o=(e,t)=>{for(var r in t)n(e,r,{get:t[r],enumerable:!0})},s=(e,t,o,s)=>{if(t&&typeof t==`object`||typeof t==`function`)for(let c of i(t))!a.call(e,c)&&c!==o&&n(e,c,{get:()=>t[c],enumerable:!(s=r(t,c))||s.enumerable});return e},c=e=>s(n({},`__esModule`,{value:!0}),e),l={};o(l,{Channel:()=>E,LongPoll:()=>ne,Presence:()=>re,Push:()=>w,Serializer:()=>ie,Socket:()=>ae,Timer:()=>T}),t.exports=c(l);var u=e=>typeof e==`function`?e:function(){return e},d=typeof self<`u`?self:null,f=typeof window<`u`?window:null,p=d||f||globalThis,m=`2.0.0`,h=1e4,g=1e3,_=100,v={connecting:0,open:1,closing:2,closed:3},y={closed:`closed`,errored:`errored`,joined:`joined`,joining:`joining`,leaving:`leaving`},b={close:`phx_close`,error:`phx_error`,join:`phx_join`,reply:`phx_reply`,leave:`phx_leave`},x={longpoll:`longpoll`,websocket:`websocket`},S={complete:4},C=`base64url.bearer.phx.`,w=class{constructor(e,t,n,r){this.channel=e,this.event=t,this.payload=n||function(){return{}},this.receivedResp=null,this.timeout=r,this.timeoutTimer=null,this.recHooks=[],this.sent=!1,this.ref=void 0}resend(e){this.timeout=e,this.reset(),this.send()}send(){this.hasReceived(`timeout`)||(this.startTimeout(),this.sent=!0,this.channel.socket.push({topic:this.channel.topic,event:this.event,payload:this.payload(),ref:this.ref,join_ref:this.channel.joinRef()}))}receive(e,t){return this.hasReceived(e)&&t(this.receivedResp.response),this.recHooks.push({status:e,callback:t}),this}reset(){this.cancelRefEvent(),this.ref=null,this.refEvent=null,this.receivedResp=null,this.sent=!1}destroy(){this.cancelRefEvent(),this.cancelTimeout()}matchReceive({status:e,response:t,_ref:n}){this.recHooks.filter(t=>t.status===e).forEach(e=>e.callback(t))}cancelRefEvent(){this.refEvent&&this.channel.off(this.refEvent)}cancelTimeout(){clearTimeout(this.timeoutTimer),this.timeoutTimer=null}startTimeout(){this.timeoutTimer&&this.cancelTimeout(),this.ref=this.channel.socket.makeRef(),this.refEvent=this.channel.replyEventName(this.ref),this.channel.on(this.refEvent,e=>{this.cancelRefEvent(),this.cancelTimeout(),this.receivedResp=e,this.matchReceive(e)}),this.timeoutTimer=setTimeout(()=>{this.trigger(`timeout`,{})},this.timeout)}hasReceived(e){return this.receivedResp&&this.receivedResp.status===e}trigger(e,t){this.channel.trigger(this.refEvent,{status:e,response:t})}},T=class{constructor(e,t){this.callback=e,this.timerCalc=t,this.timer=void 0,this.tries=0}reset(){this.tries=0,clearTimeout(this.timer)}scheduleTimeout(){clearTimeout(this.timer),this.timer=setTimeout(()=>{this.tries+=1,this.callback()},this.timerCalc(this.tries+1))}},E=class{constructor(e,t,n){this.state=y.closed,this.topic=e,this.params=u(t||{}),this.socket=n,this.bindings=[],this.bindingRef=0,this.timeout=this.socket.timeout,this.joinedOnce=!1,this.joinPush=new w(this,b.join,this.params,this.timeout),this.pushBuffer=[],this.stateChangeRefs=[],this.rejoinTimer=new T(()=>{this.socket.isConnected()&&this.rejoin()},this.socket.rejoinAfterMs),this.stateChangeRefs.push(this.socket.onError(()=>this.rejoinTimer.reset())),this.stateChangeRefs.push(this.socket.onOpen(()=>{this.rejoinTimer.reset(),this.isErrored()&&this.rejoin()})),this.joinPush.receive(`ok`,()=>{this.state=y.joined,this.rejoinTimer.reset(),this.pushBuffer.forEach(e=>e.send()),this.pushBuffer=[]}),this.joinPush.receive(`error`,e=>{this.state=y.errored,this.socket.hasLogger()&&this.socket.log(`channel`,`error ${this.topic}`,e),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.onClose(()=>{this.rejoinTimer.reset(),this.socket.hasLogger()&&this.socket.log(`channel`,`close ${this.topic}`),this.state=y.closed,this.socket.remove(this)}),this.onError(e=>{this.socket.hasLogger()&&this.socket.log(`channel`,`error ${this.topic}`,e),this.isJoining()&&this.joinPush.reset(),this.state=y.errored,this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.joinPush.receive(`timeout`,()=>{this.socket.hasLogger()&&this.socket.log(`channel`,`timeout ${this.topic}`,this.joinPush.timeout),new w(this,b.leave,u({}),this.timeout).send(),this.state=y.errored,this.joinPush.reset(),this.socket.isConnected()&&this.rejoinTimer.scheduleTimeout()}),this.on(b.reply,(e,t)=>{this.trigger(this.replyEventName(t),e)})}join(e=this.timeout){if(this.joinedOnce)throw Error(`tried to join multiple times. 'join' can only be called a single time per channel instance`);return this.timeout=e,this.joinedOnce=!0,this.rejoin(),this.joinPush}teardown(){this.pushBuffer.forEach(e=>e.destroy()),this.pushBuffer=[],this.rejoinTimer.reset(),this.joinPush.destroy(),this.state=y.closed,this.bindings=[]}onClose(e){this.on(b.close,e)}onError(e){return this.on(b.error,t=>e(t))}on(e,t){let n=this.bindingRef++;return this.bindings.push({event:e,ref:n,callback:t}),n}off(e,t){this.bindings=this.bindings.filter(n=>n.event!==e||t!==void 0&&t!==n.ref)}canPush(){return this.socket.isConnected()&&this.isJoined()}push(e,t,n=this.timeout){if(t||={},!this.joinedOnce)throw Error(`tried to push '${e}' to '${this.topic}' before joining. Use channel.join() before pushing events`);let r=new w(this,e,function(){return t},n);return this.canPush()?r.send():(r.startTimeout(),this.pushBuffer.push(r)),r}leave(e=this.timeout){this.rejoinTimer.reset(),this.joinPush.cancelTimeout(),this.state=y.leaving;let t=()=>{this.socket.hasLogger()&&this.socket.log(`channel`,`leave ${this.topic}`),this.trigger(b.close,`leave`)},n=new w(this,b.leave,u({}),e);return n.receive(`ok`,()=>t()).receive(`timeout`,()=>t()),n.send(),this.canPush()||n.trigger(`ok`,{}),n}onMessage(e,t,n){return t}filterBindings(e,t,n){return!0}isMember(e,t,n,r){return this.topic===e?r&&r!==this.joinRef()?(this.socket.hasLogger()&&this.socket.log(`channel`,`dropping outdated message`,{topic:e,event:t,payload:n,joinRef:r}),!1):!0:!1}joinRef(){return this.joinPush.ref}rejoin(e=this.timeout){this.isLeaving()||(this.socket.leaveOpenTopic(this.topic),this.state=y.joining,this.joinPush.resend(e))}trigger(e,t,n,r){let i=this.onMessage(e,t,n,r);if(t&&!i)throw Error(`channel onMessage callbacks must return the payload, modified or unmodified`);let a=this.bindings.filter(r=>r.event===e&&this.filterBindings(r,t,n));for(let e=0;e<a.length;e++)a[e].callback(i,n,r||this.joinRef())}replyEventName(e){return`chan_reply_${e}`}isClosed(){return this.state===y.closed}isErrored(){return this.state===y.errored}isJoined(){return this.state===y.joined}isJoining(){return this.state===y.joining}isLeaving(){return this.state===y.leaving}},ee=class{static request(e,t,n,r,i,a,o){if(p.XDomainRequest){let n=new p.XDomainRequest;return this.xdomainRequest(n,e,t,r,i,a,o)}if(p.XMLHttpRequest){let s=new p.XMLHttpRequest;return this.xhrRequest(s,e,t,n,r,i,a,o)}if(p.fetch&&p.AbortController)return this.fetchRequest(e,t,n,r,i,a,o);throw Error(`No suitable XMLHttpRequest implementation found`)}static fetchRequest(e,t,n,r,i,a,o){let s={method:e,headers:n,body:r},c=null;return i&&(c=new AbortController,setTimeout(()=>c.abort(),i),s.signal=c.signal),p.fetch(t,s).then(e=>e.text()).then(e=>this.parseJSON(e)).then(e=>o&&o(e)).catch(e=>{e.name===`AbortError`&&a?a():o&&o(null)}),c}static xdomainRequest(e,t,n,r,i,a,o){return e.timeout=i,e.open(t,n),e.onload=()=>{let t=this.parseJSON(e.responseText);o&&o(t)},a&&(e.ontimeout=a),e.onprogress=()=>{},e.send(r),e}static xhrRequest(e,t,n,r,i,a,o,s){e.open(t,n,!0),e.timeout=a;for(let[t,n]of Object.entries(r))e.setRequestHeader(t,n);return e.onerror=()=>s&&s(null),e.onreadystatechange=()=>{e.readyState===S.complete&&s&&s(this.parseJSON(e.responseText))},o&&(e.ontimeout=o),e.send(i),e}static parseJSON(e){if(!e||e===``)return null;try{return JSON.parse(e)}catch{return console&&console.log(`failed to parse JSON response`,e),null}}static serialize(e,t){let n=[];for(var r in e){if(!Object.prototype.hasOwnProperty.call(e,r))continue;let i=t?`${t}[${r}]`:r,a=e[r];typeof a==`object`?n.push(this.serialize(a,i)):n.push(encodeURIComponent(i)+`=`+encodeURIComponent(a))}return n.join(`&`)}static appendParams(e,t){return Object.keys(t).length===0?e:`${e}${e.match(/\?/)?`&`:`?`}${this.serialize(t)}`}},te=e=>{let t=``,n=new Uint8Array(e),r=n.byteLength;for(let e=0;e<r;e++)t+=String.fromCharCode(n[e]);return btoa(t)},ne=class{constructor(e,t){t&&t.length===2&&t[1].startsWith(C)&&(this.authToken=atob(t[1].slice(C.length))),this.endPoint=null,this.token=null,this.skipHeartbeat=!0,this.reqs=/* @__PURE__ */ new Set,this.awaitingBatchAck=!1,this.currentBatch=null,this.currentBatchTimer=null,this.batchBuffer=[],this.onopen=function(){},this.onerror=function(){},this.onmessage=function(){},this.onclose=function(){},this.pollEndpoint=this.normalizeEndpoint(e),this.readyState=v.connecting,setTimeout(()=>this.poll(),0)}normalizeEndpoint(e){return e.replace(`ws://`,`http://`).replace(`wss://`,`https://`).replace(RegExp(`(.*)/`+x.websocket),`$1/`+x.longpoll)}endpointURL(){return ee.appendParams(this.pollEndpoint,{token:this.token})}closeAndRetry(e,t,n){this.close(e,t,n),this.readyState=v.connecting}ontimeout(){this.onerror(`timeout`),this.closeAndRetry(1005,`timeout`,!1)}isActive(){return this.readyState===v.open||this.readyState===v.connecting}poll(){let e={Accept:`application/json`};this.authToken&&(e[`X-Phoenix-AuthToken`]=this.authToken),this.ajax(`GET`,e,null,()=>this.ontimeout(),e=>{if(e){var{status:t,token:n,messages:r}=e;if(t===410&&this.token!==null){this.onerror(410),this.closeAndRetry(3410,`session_gone`,!1);return}this.token=n}else t=0;switch(t){case 200:r.forEach(e=>{setTimeout(()=>this.onmessage({data:e}),0)}),this.poll();break;case 204:this.poll();break;case 410:this.readyState=v.open,this.onopen({}),this.poll();break;case 403:this.onerror(403),this.close(1008,`forbidden`,!1);break;case 0:case 500:this.onerror(500),this.closeAndRetry(1011,`internal server error`,500);break;default:throw Error(`unhandled poll status ${t}`)}})}send(e){typeof e!=`string`&&(e=te(e)),this.currentBatch?this.currentBatch.push(e):this.awaitingBatchAck?this.batchBuffer.push(e):(this.currentBatch=[e],this.currentBatchTimer=setTimeout(()=>{this.batchSend(this.currentBatch),this.currentBatch=null},0))}batchSend(e,t=0){this.awaitingBatchAck=!0;let n=t+_,r=e.slice(t,n);this.ajax(`POST`,{"Content-Type":`application/x-ndjson`},r.join(`
5
+ `),()=>this.onerror(`timeout`),t=>{!t||t.status!==200?(this.awaitingBatchAck=!1,this.onerror(t&&t.status),this.closeAndRetry(1011,`internal server error`,!1)):n<e.length?this.batchSend(e,n):this.batchBuffer.length>0?(this.batchSend(this.batchBuffer),this.batchBuffer=[]):this.awaitingBatchAck=!1})}close(e,t,n){for(let e of this.reqs)e.abort();this.readyState=v.closed;let r=Object.assign({code:1e3,reason:void 0,wasClean:!0},{code:e,reason:t,wasClean:n});this.batchBuffer=[],clearTimeout(this.currentBatchTimer),this.currentBatchTimer=null,typeof CloseEvent<`u`?this.onclose(new CloseEvent(`close`,r)):this.onclose(r)}ajax(e,t,n,r,i){let a;a=ee.request(e,this.endpointURL(),t,n,this.timeout,()=>{this.reqs.delete(a),r()},e=>{this.reqs.delete(a),this.isActive()&&i(e)}),this.reqs.add(a)}},re=class e{constructor(t,n={}){let r=n.events||{state:`presence_state`,diff:`presence_diff`};this.state=/* @__PURE__ */ Object.create(null),this.pendingDiffs=[],this.channel=t,this.joinRef=null,this.caller={onJoin:function(){},onLeave:function(){},onSync:function(){}},this.channel.on(r.state,t=>{let{onJoin:n,onLeave:r,onSync:i}=this.caller;this.joinRef=this.channel.joinRef(),this.state=e.syncState(this.state,t,n,r),this.pendingDiffs.forEach(t=>{this.state=e.syncDiff(this.state,t,n,r)}),this.pendingDiffs=[],i()}),this.channel.on(r.diff,t=>{let{onJoin:n,onLeave:r,onSync:i}=this.caller;this.inPendingSyncState()?this.pendingDiffs.push(t):(this.state=e.syncDiff(this.state,t,n,r),i())})}onJoin(e){this.caller.onJoin=e}onLeave(e){this.caller.onLeave=e}onSync(e){this.caller.onSync=e}list(t){return e.list(this.state,t)}inPendingSyncState(){return!this.joinRef||this.joinRef!==this.channel.joinRef()}static syncState(e,t,n,r){let i=this.toNullProtoObj(this.clone(e));t=this.toNullProtoObj(t);let a=/* @__PURE__ */ Object.create(null),o=/* @__PURE__ */ Object.create(null);return this.map(i,(e,n)=>{t[e]||(o[e]=n)}),this.map(t,(e,t)=>{let n=i[e];if(n){let r=t.metas.map(e=>e.phx_ref),i=n.metas.map(e=>e.phx_ref),s=t.metas.filter(e=>i.indexOf(e.phx_ref)<0),c=n.metas.filter(e=>r.indexOf(e.phx_ref)<0);s.length>0&&(a[e]=t,a[e].metas=s),c.length>0&&(o[e]=this.clone(n),o[e].metas=c)}else a[e]=t}),this.syncDiff(i,{joins:a,leaves:o},n,r)}static syncDiff(e,t,n,r){e=this.toNullProtoObj(e);let{joins:i,leaves:a}=this.clone(t);return n||=function(){},r||=function(){},this.map(i,(t,r)=>{let i=e[t];if(e[t]=this.clone(r),i){let n=e[t].metas.map(e=>e.phx_ref),r=i.metas.filter(e=>n.indexOf(e.phx_ref)<0);e[t].metas.unshift(...r)}n(t,i,r)}),this.map(a,(t,n)=>{let i=e[t];if(!i)return;let a=n.metas.map(e=>e.phx_ref);i.metas=i.metas.filter(e=>a.indexOf(e.phx_ref)<0),r(t,i,n),i.metas.length===0&&delete e[t]}),e}static list(e,t){return t||=function(e,t){return t},this.map(e,(e,n)=>t(e,n))}static map(e,t){return Object.getOwnPropertyNames(e).map(n=>t(n,e[n]))}static toNullProtoObj(e){if(Object.getPrototypeOf(e)===null)return e;let t=/* @__PURE__ */ Object.create(null);return Object.getOwnPropertyNames(e).forEach(n=>{t[n]=e[n]}),t}static clone(e){return JSON.parse(JSON.stringify(e))}},ie={HEADER_LENGTH:1,META_LENGTH:4,KINDS:{push:0,reply:1,broadcast:2},encode(e,t){if(e.payload.constructor===ArrayBuffer)return t(this.binaryEncode(e));{let n=[e.join_ref,e.ref,e.topic,e.event,e.payload];return t(JSON.stringify(n))}},decode(e,t){if(e.constructor===ArrayBuffer)return t(this.binaryDecode(e));{let[n,r,i,a,o]=JSON.parse(e);return t({join_ref:n,ref:r,topic:i,event:a,payload:o})}},binaryEncode(e){let{join_ref:t,ref:n,event:r,topic:i,payload:a}=e,o=new TextEncoder,s=o.encode(t),c=o.encode(n),l=o.encode(i),u=o.encode(r);this.assertFieldSize(s.byteLength,`join_ref`),this.assertFieldSize(c.byteLength,`ref`),this.assertFieldSize(l.byteLength,`topic`),this.assertFieldSize(u.byteLength,`event`);let d=this.META_LENGTH+s.byteLength+c.byteLength+l.byteLength+u.byteLength,f=new ArrayBuffer(this.HEADER_LENGTH+d),p=new Uint8Array(f),m=new DataView(f),h=0;m.setUint8(h++,this.KINDS.push),m.setUint8(h++,s.byteLength),m.setUint8(h++,c.byteLength),m.setUint8(h++,l.byteLength),m.setUint8(h++,u.byteLength),p.set(s,h),h+=s.byteLength,p.set(c,h),h+=c.byteLength,p.set(l,h),h+=l.byteLength,p.set(u,h),h+=u.byteLength;var g=new Uint8Array(f.byteLength+a.byteLength);return g.set(p,0),g.set(new Uint8Array(a),f.byteLength),g.buffer},assertFieldSize(e,t){if(e>255)throw Error(`unable to convert ${t} to binary: must be less than or equal to 255 bytes, but is ${e} bytes`)},binaryDecode(e){let t=new DataView(e),n=t.getUint8(0),r=new TextDecoder;switch(n){case this.KINDS.push:return this.decodePush(e,t,r);case this.KINDS.reply:return this.decodeReply(e,t,r);case this.KINDS.broadcast:return this.decodeBroadcast(e,t,r)}},decodePush(e,t,n){let r=t.getUint8(1),i=t.getUint8(2),a=t.getUint8(3),o=this.HEADER_LENGTH+this.META_LENGTH-1,s=n.decode(e.slice(o,o+r));o+=r;let c=n.decode(e.slice(o,o+i));o+=i;let l=n.decode(e.slice(o,o+a));return o+=a,{join_ref:s,ref:null,topic:c,event:l,payload:e.slice(o,e.byteLength)}},decodeReply(e,t,n){let r=t.getUint8(1),i=t.getUint8(2),a=t.getUint8(3),o=t.getUint8(4),s=this.HEADER_LENGTH+this.META_LENGTH,c=n.decode(e.slice(s,s+r));s+=r;let l=n.decode(e.slice(s,s+i));s+=i;let u=n.decode(e.slice(s,s+a));s+=a;let d=n.decode(e.slice(s,s+o));s+=o;let f={status:d,response:e.slice(s,e.byteLength)};return{join_ref:c,ref:l,topic:u,event:b.reply,payload:f}},decodeBroadcast(e,t,n){let r=t.getUint8(1),i=t.getUint8(2),a=this.HEADER_LENGTH+2,o=n.decode(e.slice(a,a+r));a+=r;let s=n.decode(e.slice(a,a+i));return a+=i,{join_ref:null,ref:null,topic:o,event:s,payload:e.slice(a,e.byteLength)}}},ae=class{constructor(e,t={}){this.stateChangeCallbacks={open:[],close:[],error:[],message:[]},this.channels=[],this.sendBuffer=[],this.ref=0,this.fallbackRef=null,this.timeout=t.timeout||h,this.transport=t.transport||p.WebSocket||ne,this.conn=void 0,this.primaryPassedHealthCheck=!1,this.longPollFallbackMs=t.longPollFallbackMs,this.fallbackTimer=null;let n=null;try{n=p&&p.sessionStorage}catch{}this.sessionStore=t.sessionStorage||n,this.establishedConnections=0,this.defaultEncoder=ie.encode.bind(ie),this.defaultDecoder=ie.decode.bind(ie),this.closeWasClean=!0,this.disconnecting=!1,this.binaryType=t.binaryType||`arraybuffer`,this.connectClock=1,this.pageHidden=!1,this.encode=void 0,this.decode=void 0,this.transport===ne?(this.encode=this.defaultEncoder,this.decode=this.defaultDecoder):(this.encode=t.encode||this.defaultEncoder,this.decode=t.decode||this.defaultDecoder);let r=null;f&&f.addEventListener&&(f.addEventListener(`pagehide`,e=>{this.conn&&(this.disconnect(),r=this.connectClock)}),f.addEventListener(`pageshow`,e=>{r===this.connectClock&&(r=null,this.connect())}),f.addEventListener(`visibilitychange`,()=>{document.visibilityState===`hidden`?this.pageHidden=!0:(this.pageHidden=!1,!this.isConnected()&&!this.closeWasClean&&this.teardown(()=>this.connect()))})),this.heartbeatIntervalMs=t.heartbeatIntervalMs||3e4,this.autoSendHeartbeat=t.autoSendHeartbeat??!0,this.heartbeatCallback=t.heartbeatCallback??(()=>{}),this.rejoinAfterMs=e=>t.rejoinAfterMs?t.rejoinAfterMs(e):[1e3,2e3,5e3][e-1]||1e4,this.reconnectAfterMs=e=>t.reconnectAfterMs?t.reconnectAfterMs(e):[10,50,100,150,200,250,500,1e3,2e3][e-1]||5e3,this.logger=t.logger||null,!this.logger&&t.debug&&(this.logger=(e,t,n)=>{console.log(`${e}: ${t}`,n)}),this.longpollerTimeout=t.longpollerTimeout||2e4,this.params=u(t.params||{}),this.endPoint=`${e}/${x.websocket}`,this.vsn=t.vsn||m,this.heartbeatTimeoutTimer=null,this.heartbeatTimer=null,this.heartbeatSentAt=null,this.pendingHeartbeatRef=null,this.reconnectTimer=new T(()=>{this.pageHidden?(this.log(`Not reconnecting as page is hidden!`),this.teardown()):this.teardown(async()=>{t.beforeReconnect&&await t.beforeReconnect(),this.connect()})},this.reconnectAfterMs),this.authToken=t.authToken&&u(t.authToken)}getLongPollTransport(){return ne}replaceTransport(e){this.connectClock++,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.conn&&=(this.conn.close(),null),this.transport=e}protocol(){return location.protocol.match(/^https/)?`wss`:`ws`}endPointURL(){let e=ee.appendParams(ee.appendParams(this.endPoint,this.params()),{vsn:this.vsn});return e.charAt(0)===`/`?e.charAt(1)===`/`?`${this.protocol()}:${e}`:`${this.protocol()}://${location.host}${e}`:e}disconnect(e,t,n){this.connectClock++,this.disconnecting=!0,this.closeWasClean=!0,clearTimeout(this.fallbackTimer),this.reconnectTimer.reset(),this.teardown(()=>{this.disconnecting=!1,e&&e()},t,n)}connect(e){e&&(console&&console.log(`passing params to connect is deprecated. Instead pass :params to the Socket constructor`),this.params=u(e)),(!this.conn||this.disconnecting)&&(this.longPollFallbackMs&&this.transport!==ne?this.connectWithFallback(ne,this.longPollFallbackMs):this.transportConnect())}log(e,t,n){this.logger&&this.logger(e,t,n)}hasLogger(){return this.logger!==null}onOpen(e){let t=this.makeRef();return this.stateChangeCallbacks.open.push([t,e]),t}onClose(e){let t=this.makeRef();return this.stateChangeCallbacks.close.push([t,e]),t}onError(e){let t=this.makeRef();return this.stateChangeCallbacks.error.push([t,e]),t}onMessage(e){let t=this.makeRef();return this.stateChangeCallbacks.message.push([t,e]),t}onHeartbeat(e){this.heartbeatCallback=e}ping(e){if(!this.isConnected())return!1;let t=this.makeRef(),n=Date.now();this.push({topic:`phoenix`,event:`heartbeat`,payload:{},ref:t});let r=this.onMessage(i=>{i.ref===t&&(this.off([r]),e(Date.now()-n))});return!0}transportName(e){switch(e){case ne:return`LongPoll`;default:return e.name}}transportConnect(){this.connectClock++,this.closeWasClean=!1;let e;this.authToken&&(e=[`phoenix`,`${C}${btoa(this.authToken()).replace(/=/g,``)}`]),this.conn=new this.transport(this.endPointURL(),e),this.conn.binaryType=this.binaryType,this.conn.timeout=this.longpollerTimeout,this.conn.onopen=()=>this.onConnOpen(),this.conn.onerror=e=>this.onConnError(e),this.conn.onmessage=e=>this.onConnMessage(e),this.conn.onclose=e=>this.onConnClose(e)}getSession(e){return this.sessionStore&&this.sessionStore.getItem(e)}storeSession(e,t){this.sessionStore&&this.sessionStore.setItem(e,t)}connectWithFallback(e,t=2500){clearTimeout(this.fallbackTimer);let n=!1,r=!0,i,a,o=this.transportName(e),s=t=>{this.log(`transport`,`falling back to ${o}...`,t),this.off([i,a]),r=!1,this.replaceTransport(e),this.transportConnect()};if(this.getSession(`phx:fallback:${o}`))return s(`memorized`);this.fallbackTimer=setTimeout(s,t),a=this.onError(e=>{this.log(`transport`,`error`,e),r&&!n&&(clearTimeout(this.fallbackTimer),s(e))}),this.fallbackRef&&this.off([this.fallbackRef]),this.fallbackRef=this.onOpen(()=>{if(n=!0,!r){let t=this.transportName(e);return this.primaryPassedHealthCheck||this.storeSession(`phx:fallback:${t}`,`true`),this.log(`transport`,`established ${t} fallback`)}clearTimeout(this.fallbackTimer),this.fallbackTimer=setTimeout(s,t),this.ping(e=>{this.log(`transport`,`connected to primary after`,e),this.primaryPassedHealthCheck=!0,clearTimeout(this.fallbackTimer)})}),this.transportConnect()}clearHeartbeats(){clearTimeout(this.heartbeatTimer),clearTimeout(this.heartbeatTimeoutTimer)}onConnOpen(){this.hasLogger()&&this.log(`transport`,`connected to ${this.endPointURL()}`),this.closeWasClean=!1,this.disconnecting=!1,this.establishedConnections++,this.flushSendBuffer(),this.reconnectTimer.reset(),this.autoSendHeartbeat&&this.resetHeartbeat(),this.triggerStateCallbacks(`open`)}heartbeatTimeout(){if(this.pendingHeartbeatRef){this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.hasLogger()&&this.log(`transport`,`heartbeat timeout. Attempting to re-establish connection`);try{this.heartbeatCallback(`timeout`)}catch(e){this.log(`error`,`error in heartbeat callback`,e)}this.triggerChanError(/* @__PURE__ */ Error(`heartbeat timeout`)),this.closeWasClean=!1,this.teardown(()=>this.reconnectTimer.scheduleTimeout(),g,`heartbeat timeout`)}}resetHeartbeat(){this.conn&&this.conn.skipHeartbeat||(this.pendingHeartbeatRef=null,this.clearHeartbeats(),this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}teardown(e,t,n){if(!this.conn)return e&&e();let r=this.conn;this.waitForBufferDone(r,()=>{t?r.close(t,n||``):r.close(),this.waitForSocketClosed(r,()=>{this.conn===r&&(this.conn.onopen=function(){},this.conn.onerror=function(){},this.conn.onmessage=function(){},this.conn.onclose=function(){},this.conn=null),e&&e()})})}waitForBufferDone(e,t,n=1){n===5||!e.bufferedAmount?t():setTimeout(()=>{this.waitForBufferDone(e,t,n+1)},150*n)}waitForSocketClosed(e,t,n=1){n===5||e.readyState===v.closed?t():setTimeout(()=>{this.waitForSocketClosed(e,t,n+1)},150*n)}onConnClose(e){this.conn&&(this.conn.onclose=()=>{}),this.hasLogger()&&this.log(`transport`,`close`,e),this.triggerChanError(e),this.clearHeartbeats(),this.closeWasClean||this.reconnectTimer.scheduleTimeout(),this.triggerStateCallbacks(`close`,e)}onConnError(e){this.hasLogger()&&this.log(`transport`,`error`,e);let t=this.transport,n=this.establishedConnections;this.triggerStateCallbacks(`error`,e,t,n),(t===this.transport||n>0)&&this.triggerChanError(e)}triggerChanError(e){this.channels.forEach(t=>{t.isErrored()||t.isLeaving()||t.isClosed()||t.trigger(b.error,e)})}connectionState(){switch(this.conn&&this.conn.readyState){case v.connecting:return`connecting`;case v.open:return`open`;case v.closing:return`closing`;default:return`closed`}}isConnected(){return this.connectionState()===`open`}remove(e){this.off(e.stateChangeRefs),this.channels=this.channels.filter(t=>t!==e)}off(e){for(let t in this.stateChangeCallbacks)this.stateChangeCallbacks[t]=this.stateChangeCallbacks[t].filter(([t])=>e.indexOf(t)===-1)}channel(e,t={}){let n=new E(e,t,this);return this.channels.push(n),n}push(e){if(this.hasLogger()){let{topic:t,event:n,payload:r,ref:i,join_ref:a}=e;this.log(`push`,`${t} ${n} (${a}, ${i})`,r)}this.isConnected()?this.encode(e,e=>this.conn.send(e)):this.sendBuffer.push(()=>this.encode(e,e=>this.conn.send(e)))}makeRef(){let e=this.ref+1;return this.ref=e===this.ref?0:e,this.ref.toString()}sendHeartbeat(){if(!this.isConnected())try{this.heartbeatCallback(`disconnected`)}catch(e){this.log(`error`,`error in heartbeat callback`,e)}else if(this.pendingHeartbeatRef)this.heartbeatTimeout();else{this.pendingHeartbeatRef=this.makeRef(),this.heartbeatSentAt=Date.now(),this.push({topic:`phoenix`,event:`heartbeat`,payload:{},ref:this.pendingHeartbeatRef});try{this.heartbeatCallback(`sent`)}catch(e){this.log(`error`,`error in heartbeat callback`,e)}this.heartbeatTimeoutTimer=setTimeout(()=>this.heartbeatTimeout(),this.heartbeatIntervalMs)}}flushSendBuffer(){this.isConnected()&&this.sendBuffer.length>0&&(this.sendBuffer.forEach(e=>e()),this.sendBuffer=[])}onConnMessage(e){this.decode(e.data,e=>{let{topic:t,event:n,payload:r,ref:i,join_ref:a}=e;if(i&&i===this.pendingHeartbeatRef){let e=this.heartbeatSentAt?Date.now()-this.heartbeatSentAt:void 0;this.clearHeartbeats();try{this.heartbeatCallback(r.status===`ok`?`ok`:`error`,e)}catch(e){this.log(`error`,`error in heartbeat callback`,e)}this.pendingHeartbeatRef=null,this.heartbeatSentAt=null,this.autoSendHeartbeat&&(this.heartbeatTimer=setTimeout(()=>this.sendHeartbeat(),this.heartbeatIntervalMs))}this.hasLogger()&&this.log(`receive`,`${r.status||``} ${t} ${n} ${i&&`(`+i+`)`||``}`.trim(),r);for(let e=0;e<this.channels.length;e++){let o=this.channels[e];o.isMember(t,n,r,a)&&o.trigger(n,r,i,a)}this.triggerStateCallbacks(`message`,e)})}triggerStateCallbacks(e,...t){try{this.stateChangeCallbacks[e].forEach(([n,r])=>{try{r(...t)}catch(t){this.log(`error`,`error in ${e} callback`,t)}})}catch(t){this.log(`error`,`error triggering ${e} callbacks`,t)}}leaveOpenTopic(e){let t=this.channels.find(t=>t.topic===e&&(t.isJoined()||t.isJoining()));t&&(this.hasLogger()&&this.log(`transport`,`leaving duplicate topic "${e}"`),t.leave())}}})),At=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=kt();e.default=class e{constructor(n,r){let a=i(r);this.presence=new t.Presence(n.getChannel(),a),this.presence.onJoin((t,r,i)=>{let a=e.onJoinPayload(t,r,i);n.getChannel().trigger(`presence`,a)}),this.presence.onLeave((t,r,i)=>{let a=e.onLeavePayload(t,r,i);n.getChannel().trigger(`presence`,a)}),this.presence.onSync(()=>{n.getChannel().trigger(`presence`,{event:`sync`})})}get state(){return e.transformState(this.presence.state)}static transformState(e){return e=r(e),Object.getOwnPropertyNames(e).reduce((t,r)=>{let i=e[r];return t[r]=n(i),t},{})}static onJoinPayload(e,t,r){return{event:`join`,key:e,currentPresences:a(t),newPresences:n(r)}}static onLeavePayload(e,t,r){return{event:`leave`,key:e,currentPresences:a(t),leftPresences:n(r)}}};function n(e){return e.metas.map(e=>{let t=Object.getOwnPropertyDescriptors(e),n=Object.defineProperties({},t);return n.presence_ref=n.phx_ref,delete n.phx_ref,delete n.phx_ref_prev,n})}function r(e){return JSON.parse(JSON.stringify(e))}function i(e){return e?.events&&{events:e.events}}function a(e){return e?.metas?n(e):[]}})),jt=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.REALTIME_PRESENCE_LISTEN_EVENTS=void 0;let t=(Qe(),ue(me)).__importDefault(At());var n;(function(e){e.SYNC=`sync`,e.JOIN=`join`,e.LEAVE=`leave`})(n||(e.REALTIME_PRESENCE_LISTEN_EVENTS=n={})),e.default=class{get state(){return this.presenceAdapter.state}constructor(e,n){this.channel=e,this.presenceAdapter=new t.default(this.channel.channelAdapter,n)}}})),Mt=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.normalizeChannelError=t;function t(e){if(e instanceof Error)return e;if(typeof e==`string`)return Error(e);if(e&&typeof e==`object`){let t=e;if(typeof t.code==`number`){let n=typeof t.reason==`string`&&t.reason?` (${t.reason})`:``;return Error(`socket closed: ${t.code}${n}`,{cause:e})}return Error(`channel error: transport failure`,{cause:e})}return/* @__PURE__ */ Error(`channel error: connection lost`)}})),Nt=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Et();e.default=class{constructor(e,t,r){let i=n(r);this.channel=e.getSocket().channel(t,i),this.socket=e}get state(){return this.channel.state}set state(e){this.channel.state=e}get joinedOnce(){return this.channel.joinedOnce}get joinPush(){return this.channel.joinPush}get rejoinTimer(){return this.channel.rejoinTimer}on(e,t){return this.channel.on(e,t)}off(e,t){this.channel.off(e,t)}subscribe(e){return this.channel.join(e)}unsubscribe(e){return this.channel.leave(e)}teardown(){this.channel.teardown()}onClose(e){this.channel.onClose(e)}onError(e){return this.channel.onError(e)}push(e,n,r){let i;try{i=this.channel.push(e,n,r)}catch{throw Error(`tried to push '${e}' to '${this.channel.topic}' before joining. Use channel.subscribe() before pushing events`)}if(this.channel.pushBuffer.length>t.MAX_PUSH_BUFFER_SIZE){let e=this.channel.pushBuffer.shift();e.cancelTimeout(),this.socket.log(`channel`,`discarded push due to buffer overflow: ${e.event}`,e.payload())}return i}updateJoinPayload(e){let t=this.channel.joinPush.payload();this.channel.joinPush.payload=()=>Object.assign(Object.assign({},t),e)}canPush(){return this.socket.isConnected()&&this.state===t.CHANNEL_STATES.joined}isJoined(){return this.state===t.CHANNEL_STATES.joined}isJoining(){return this.state===t.CHANNEL_STATES.joining}isClosed(){return this.state===t.CHANNEL_STATES.closed}isLeaving(){return this.state===t.CHANNEL_STATES.leaving}updateFilterBindings(e){this.channel.filterBindings=e}updatePayloadTransform(e){this.channel.onMessage=e}getChannel(){return this.channel}};function n(e){return{config:Object.assign({broadcast:{ack:!1,self:!1},presence:{key:``,enabled:!1},private:!1},e.config)}}})),Pt=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.postgresChangesFilter=e.RealtimePostgresFilterBuilder=void 0;let t=/[,()"\\]/,n=e=>t.test(e)||e!==e.trim(),r=e=>`"${e.replace(/\\/g,`\\\\`).replace(/"/g,`\\"`)}"`,i=e=>{let t=e===null?`null`:String(e);return n(t)?r(t):t},a=e=>e===null?`null`:String(e),o=(e,t)=>{if(e===`in`){let e=Array.isArray(t)?t:[t];if(e.length===0)throw Error("Realtime `in` filter requires at least one value.");return`in.(${Array.from(new Set(e)).map(e=>i(e)).join(`,`)})`}return e===`is`?`is.${a(t)}`:`${e}.${i(t)}`};var s=class{constructor(){this.filters=[]}add(e,t,n,r=!1){let i=r?`not.`:``;return this.filters.push(`${e}=${i}${o(t,n)}`),this}eq(e,t){return this.add(e,`eq`,t)}neq(e,t){return this.add(e,`neq`,t)}gt(e,t){return this.add(e,`gt`,t)}gte(e,t){return this.add(e,`gte`,t)}lt(e,t){return this.add(e,`lt`,t)}lte(e,t){return this.add(e,`lte`,t)}in(e,t){return this.add(e,`in`,t)}like(e,t){return this.add(e,`like`,t)}ilike(e,t){return this.add(e,`ilike`,t)}match(e,t){return this.add(e,`match`,t)}imatch(e,t){return this.add(e,`imatch`,t)}is(e,t){return this.add(e,`is`,t)}isDistinct(e,t){return this.add(e,`isdistinct`,t)}not(e,t,n){return this.add(e,t,n,!0)}build(){return this.filters.join(`,`)}toString(){return this.build()}};e.RealtimePostgresFilterBuilder=s,e.postgresChangesFilter=()=>new s})),Ft=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.REALTIME_CHANNEL_STATES=e.REALTIME_SUBSCRIBE_STATES=e.REALTIME_LISTEN_TYPES=e.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT=e.postgresChangesFilter=e.RealtimePostgresFilterBuilder=void 0;let t=(Qe(),ue(me)),n=Et(),r=t.__importDefault(jt()),i=t.__importStar(Ot()),a=Ot(),o=Mt(),s=t.__importDefault(Nt()),c=Pt();var l=Pt();Object.defineProperty(e,"RealtimePostgresFilterBuilder",{enumerable:!0,get:function(){return l.RealtimePostgresFilterBuilder}}),Object.defineProperty(e,"postgresChangesFilter",{enumerable:!0,get:function(){return l.postgresChangesFilter}});var u;(function(e){e.ALL=`*`,e.INSERT=`INSERT`,e.UPDATE=`UPDATE`,e.DELETE=`DELETE`})(u||(e.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT=u={}));var d;(function(e){e.BROADCAST=`broadcast`,e.PRESENCE=`presence`,e.POSTGRES_CHANGES=`postgres_changes`,e.SYSTEM=`system`})(d||(e.REALTIME_LISTEN_TYPES=d={}));var f;(function(e){e.SUBSCRIBED=`SUBSCRIBED`,e.TIMED_OUT=`TIMED_OUT`,e.CLOSED=`CLOSED`,e.CHANNEL_ERROR=`CHANNEL_ERROR`})(f||(e.REALTIME_SUBSCRIBE_STATES=f={})),e.REALTIME_CHANNEL_STATES=n.CHANNEL_STATES,e.default=class e{get state(){return this.channelAdapter.state}set state(e){this.channelAdapter.state=e}get joinedOnce(){return this.channelAdapter.joinedOnce}get timeout(){return this.socket.timeout}get joinPush(){return this.channelAdapter.joinPush}get rejoinTimer(){return this.channelAdapter.rejoinTimer}constructor(e,t={config:{}},n){if(this.topic=e,this.params=t,this.socket=n,this.bindings={},this.subTopic=e.replace(/^realtime:/i,``),this.params.config=Object.assign({broadcast:{ack:!1,self:!1},presence:{key:``,enabled:!1},private:!1},t.config),this.channelAdapter=new s.default(this.socket.socketAdapter,e,this.params),this.presence=new r.default(this),this._onClose(()=>{this.socket._remove(this)}),this._updateFilterTransform(),this.broadcastEndpointURL=(0,a.httpEndpointURL)(this.socket.socketAdapter.endPointURL()),this.private=this.params.config.private||!1,!this.private&&this.params.config?.broadcast?.replay)throw Error(`tried to use replay on public channel '${this.topic}'. It must be a private channel.`)}subscribe(e,t=this.timeout){if(this.socket.isConnected()||this.socket.connect(),this.channelAdapter.isClosed()){let{config:{broadcast:r,presence:i,private:a,postgres_changes_options:s}}=this.params,c=this.bindings.postgres_changes?.map(e=>e.filter)??[],l=!!this.bindings[d.PRESENCE]&&this.bindings[d.PRESENCE].length>0||this.params.config.presence?.enabled===!0,u={},p=Object.assign({broadcast:r,presence:Object.assign(Object.assign({},i),{enabled:l}),postgres_changes:c,private:a},s?{postgres_changes_options:s}:{});this.socket.accessTokenValue&&(u.access_token=this.socket.accessTokenValue),this._onError(t=>{e?.(f.CHANNEL_ERROR,(0,o.normalizeChannelError)(t))}),this._onClose(()=>e?.(f.CLOSED)),this.updateJoinPayload(Object.assign({config:p},u)),this._updateFilterMessage();let m=s?.wait&&c.length>0?Math.max(t,(s.timeout??n.DEFAULT_POSTGRES_CHANGES_WAIT_TIMEOUT)+n.POSTGRES_CHANGES_WAIT_ERROR_GRACE):t;this.channelAdapter.subscribe(m).receive(`ok`,async({postgres_changes:t})=>{this.socket._isManualToken()||this.socket.setAuth(),t===void 0?e?.(f.SUBSCRIBED):this._updatePostgresBindings(t,e)}).receive(`error`,t=>{this.state=n.CHANNEL_STATES.errored;let r=Object.values(t).join(`, `)||`error`;e?.(f.CHANNEL_ERROR,Error(r,{cause:t}))}).receive(`timeout`,()=>{e?.(f.TIMED_OUT)})}return this}_updatePostgresBindings(t,r){let i=this.bindings.postgres_changes,a=i?.length??0,o=[];for(let s=0;s<a;s++){let a=i[s],{filter:{event:c,schema:l,table:u,filter:d}}=a,p=t&&t[s];if(p&&p.event===c&&e.isFilterValueEqual(p.schema,l)&&e.isFilterValueEqual(p.table,u)&&e.isFilterValueEqual(p.filter,d))o.push(Object.assign(Object.assign({},a),{id:p.id}));else{this.unsubscribe(),this.state=n.CHANNEL_STATES.errored,r?.(f.CHANNEL_ERROR,/* @__PURE__ */ Error(`mismatch between server and client bindings for postgres changes`));return}}this.bindings.postgres_changes=o,this.state!=n.CHANNEL_STATES.errored&&r&&r(f.SUBSCRIBED)}presenceState(){return this.presence.state}async track(e,t={}){return await this.send({type:`presence`,event:`track`,payload:e},t)}async untrack(e={}){return await this.send({type:`presence`,event:`untrack`},e)}on(e,t,n){let r=this.channelAdapter.isJoined()||this.channelAdapter.isJoining(),i=e===d.PRESENCE||e===d.POSTGRES_CHANGES;if(r&&i)throw this.socket.log(`channel`,`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`),Error(`cannot add \`${e}\` callbacks for ${this.topic} after \`subscribe()\`.`);return this._on(e,t,n)}async httpSend(e,t,n={}){if(t==null)return Promise.reject(/* @__PURE__ */ Error(`Payload is required for httpSend()`));let r=t instanceof ArrayBuffer||ArrayBuffer.isView(t),i={apikey:this.socket.apiKey?this.socket.apiKey:``,"Content-Type":r?`application/octet-stream`:`application/json`};this.socket.accessTokenValue&&(i.Authorization=`Bearer ${this.socket.accessTokenValue}`);let a=new URL(this.broadcastEndpointURL);a.pathname+=`/${encodeURIComponent(this.subTopic)}/events/${encodeURIComponent(e)}`,this.private&&a.searchParams.set(`private`,`true`);let o={method:`POST`,headers:i,body:r?t:JSON.stringify(t)},s=await this._fetchWithTimeout(a.toString(),o,n.timeout??this.timeout);if(s.status===202)return{success:!0};if(s.status===404)return Promise.reject(/* @__PURE__ */ Error(`httpSend() requires Realtime server v2.97.0 or newer; the endpoint returned 404. Update your Supabase CLI to a recent version, or upgrade the Realtime server in your self-hosted setup. See https://github.com/supabase/supabase-js/blob/master/packages/core/realtime-js/migrations/httpsend-server-version.md`));let c=s.statusText;try{let e=await s.json();c=e.error||e.message||c}catch{}return Promise.reject(Error(c))}async send(e,t={}){if(!this.channelAdapter.canPush()&&e.type===`broadcast`){let n=`Realtime send() is automatically falling back to REST API. This behavior will be deprecated in the future. Please use httpSend() explicitly for REST delivery.`;this.socket.hasLogger()?this.socket.log(`channel`,n):console.warn(n);let{event:r,payload:i}=e,a={apikey:this.socket.apiKey?this.socket.apiKey:``,"Content-Type":`application/json`};this.socket.accessTokenValue&&(a.Authorization=`Bearer ${this.socket.accessTokenValue}`);let o={method:`POST`,headers:a,body:JSON.stringify({messages:[{topic:this.subTopic,event:r,payload:i,private:this.private}]})};try{let e=await this._fetchWithTimeout(this.broadcastEndpointURL,o,t.timeout??this.timeout);return await e.body?.cancel(),e.ok?`ok`:`error`}catch(e){return e instanceof Error&&e.name===`AbortError`?`timed out`:`error`}}return new Promise(n=>{let r=this.channelAdapter.push(e.type,e,t.timeout||this.timeout);e.type===`broadcast`&&!this.params?.config?.broadcast?.ack&&n(`ok`),r.receive(`ok`,()=>n(`ok`)),r.receive(`error`,()=>n(`error`)),r.receive(`timeout`,()=>n(`timed out`))})}updateJoinPayload(e){this.channelAdapter.updateJoinPayload(e)}async unsubscribe(e=this.timeout){return new Promise(t=>{this.channelAdapter.unsubscribe(e).receive(`ok`,()=>t(`ok`)).receive(`timeout`,()=>t(`timed out`)).receive(`error`,()=>t(`error`))})}teardown(){this.channelAdapter.teardown()}async _fetchWithTimeout(e,t,n){let r=new AbortController,i=setTimeout(()=>r.abort(),n),a=await this.socket.fetch(e,Object.assign(Object.assign({},t),{signal:r.signal}));return clearTimeout(i),a}_on(t,n,r){let i=t.toLocaleLowerCase(),a=n?.filter;if((a instanceof c.RealtimePostgresFilterBuilder||typeof a==`object`&&a&&typeof a.build==`function`)&&(n=Object.assign(Object.assign({},n),{filter:a.build()})),i===d.POSTGRES_CHANGES&&this.bindings[i]?.find(t=>e.isSamePostgresFilter(t.filter,n)))return this.socket.log(`error`,`duplicate \`postgres_changes\` binding for ${this.topic} ignored`,n),this;let o=this.channelAdapter.on(t,r),s={type:i,filter:n,callback:r,ref:o};return this.bindings[i]?this.bindings[i].push(s):this.bindings[i]=[s],this._updateFilterMessage(),this}_onClose(e){this.channelAdapter.onClose(e)}_onError(e){this.channelAdapter.onError(e)}_updateFilterMessage(){this.channelAdapter.updateFilterBindings((e,t,n)=>{let r=e.event.toLocaleLowerCase();if(this._notThisChannelEvent(r,n))return!1;let i=this.bindings[r]?.find(t=>t.ref===e.ref);if(!i)return!0;if([`broadcast`,`presence`,`postgres_changes`].includes(r)){if(`id`in i){let e=i.id,n=i.filter?.event;return e&&t.ids?.includes(e)&&(n===`*`||n?.toLocaleLowerCase()===t.data?.type.toLocaleLowerCase())}{let e=(i?.filter?.event)?.toLocaleLowerCase();return e===`*`||e===(t?.event)?.toLocaleLowerCase()}}return i.type.toLocaleLowerCase()===r})}_notThisChannelEvent(e,t){let{close:r,error:i,leave:a,join:o}=n.CHANNEL_EVENTS;return t&&[r,i,a,o].includes(e)&&t!==this.joinPush.ref}_updateFilterTransform(){this.channelAdapter.updatePayloadTransform((e,t,n)=>{if(typeof t==`object`&&`ids`in t){let e=t.data,{schema:n,table:r,commit_timestamp:i,type:a,errors:o}=e;return Object.assign(Object.assign({},{schema:n,table:r,commit_timestamp:i,eventType:a,new:{},old:{},errors:o}),this._getPayloadRecords(e))}return t})}copyBindings(e){if(this.joinedOnce)throw Error(`cannot copy bindings into joined channel`);for(let t in e.bindings)for(let n of e.bindings[t])this._on(n.type,n.filter,n.callback)}static isFilterValueEqual(e,t){return(e??void 0)===(t??void 0)}static isSamePostgresFilter(t,n){let r=(t?.select)?.join()??void 0,i=(n?.select)?.join()??void 0;return t?.event===n?.event&&e.isFilterValueEqual(t?.schema,n?.schema)&&e.isFilterValueEqual(t?.table,n?.table)&&e.isFilterValueEqual(t?.filter,n?.filter)&&r===i}_getPayloadRecords(e){let t={new:{},old:{}};return(e.type===`INSERT`||e.type===`UPDATE`)&&(t.new=i.convertChangeData(e.columns,e.record)),(e.type===`UPDATE`||e.type===`DELETE`)&&(t.old=i.convertChangeData(e.columns,e.old_record)),t}}})),It=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=kt(),n=Et();e.default=class{constructor(e,n){this.socket=new t.Socket(e,n)}get timeout(){return this.socket.timeout}get endPoint(){return this.socket.endPoint}get transport(){return this.socket.transport}get heartbeatIntervalMs(){return this.socket.heartbeatIntervalMs}get heartbeatCallback(){return this.socket.heartbeatCallback}set heartbeatCallback(e){this.socket.heartbeatCallback=e}get heartbeatTimer(){return this.socket.heartbeatTimer}get pendingHeartbeatRef(){return this.socket.pendingHeartbeatRef}get reconnectTimer(){return this.socket.reconnectTimer}get vsn(){return this.socket.vsn}get encode(){return this.socket.encode}get decode(){return this.socket.decode}get reconnectAfterMs(){return this.socket.reconnectAfterMs}get sendBuffer(){return this.socket.sendBuffer}get stateChangeCallbacks(){return this.socket.stateChangeCallbacks}connect(){this.socket.connect()}disconnect(e,t,n,r=1e4){return new Promise(i=>{setTimeout(()=>i(`timeout`),r),this.socket.disconnect(()=>{e(),i(`ok`)},t,n)})}push(e){this.socket.push(e)}log(e,t,n){this.socket.log(e,t,n)}hasLogger(){return this.socket.hasLogger()}makeRef(){return this.socket.makeRef()}onOpen(e){this.socket.onOpen(e)}onClose(e){this.socket.onClose(e)}onError(e){this.socket.onError(e)}onMessage(e){this.socket.onMessage(e)}isConnected(){return this.socket.isConnected()}isConnecting(){return this.socket.connectionState()==n.CONNECTION_STATE.connecting}isDisconnecting(){return this.socket.connectionState()==n.CONNECTION_STATE.closing}connectionState(){return this.socket.connectionState()}endPointURL(){return this.socket.endPointURL()}sendHeartbeat(){this.socket.sendHeartbeat()}getSocket(){return this.socket}}})),Lt=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=(Qe(),ue(me)),n=t.__importDefault(wt()),r=Et(),i=t.__importDefault(Dt()),a=Ot(),o=t.__importDefault(Ft()),s=t.__importDefault(It()),c={HEARTBEAT_INTERVAL:25e3,RECONNECT_DELAY:10,HEARTBEAT_TIMEOUT_FALLBACK:100},l=[1e3,2e3,5e3,1e4];function u(){let e=/* @__PURE__ */ new Map;return{get length(){return e.size},clear(){e.clear()},getItem(t){return e.has(t)?e.get(t):null},key(t){return Array.from(e.keys())[t]??null},removeItem(t){e.delete(t)},setItem(t,n){e.set(t,String(n))}}}function d(){try{if(typeof globalThis<`u`&&globalThis.sessionStorage)return globalThis.sessionStorage}catch{}return u()}e.default=class{get endPoint(){return this.socketAdapter.endPoint}get timeout(){return this.socketAdapter.timeout}get transport(){return this.socketAdapter.transport}get heartbeatCallback(){return this.socketAdapter.heartbeatCallback}get heartbeatIntervalMs(){return this.socketAdapter.heartbeatIntervalMs}get heartbeatTimer(){return this.worker?this._workerHeartbeatTimer:this.socketAdapter.heartbeatTimer}get pendingHeartbeatRef(){return this.worker?this._pendingWorkerHeartbeatRef:this.socketAdapter.pendingHeartbeatRef}get reconnectTimer(){return this.socketAdapter.reconnectTimer}get vsn(){return this.socketAdapter.vsn}get encode(){return this.socketAdapter.encode}get decode(){return this.socketAdapter.decode}get reconnectAfterMs(){return this.socketAdapter.reconnectAfterMs}get sendBuffer(){return this.socketAdapter.sendBuffer}get stateChangeCallbacks(){return this.socketAdapter.stateChangeCallbacks}constructor(e,t){if(this.channels=[],this.accessTokenValue=null,this.accessToken=null,this.apiKey=null,this.httpEndpoint=``,this.headers={},this.params={},this.ref=0,this.serializer=new i.default,this._manuallySetToken=!1,this._authPromise=null,this._authGeneration=0,this._workerHeartbeatTimer=void 0,this._pendingWorkerHeartbeatRef=null,this._pendingDisconnectTimer=null,this._disconnectOnEmptyChannelsAfterMs=0,this._resolveFetch=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),!t?.params?.apikey)throw Error(`API key is required to connect to Realtime`);this.apiKey=t.params.apikey;let n=this._initializeOptions(t);this.socketAdapter=new s.default(e,n),this.httpEndpoint=(0,a.httpEndpointURL)(e),this.fetch=this._resolveFetch(t?.fetch)}connect(){if(!(this.isConnecting()||this.isDisconnecting()||this.isConnected())){this.accessToken&&!this._authPromise&&this._setAuthSafely(`connect`),this._setupConnectionHandlers();try{this.socketAdapter.connect()}catch(e){let t=e.message;throw Error(`WebSocket not available: ${t}`)}this._handleNodeJsRaceCondition()}}endpointURL(){return this.socketAdapter.endPointURL()}async disconnect(e,t){return this._cancelPendingDisconnect(),this.isDisconnecting()?`ok`:await this.socketAdapter.disconnect(()=>{clearInterval(this._workerHeartbeatTimer),this._terminateWorker()},e,t)}getChannels(){return this.channels}async removeChannel(e){let t=await e.unsubscribe();return t===`ok`&&e.teardown(),t}async removeAllChannels(){let e=this.channels.map(async e=>{let t=await e.unsubscribe();return e.teardown(),t}),t=await Promise.all(e);return await this.disconnect(),t}log(e,t,n){this.socketAdapter.log(e,t,n)}hasLogger(){return this.socketAdapter.hasLogger()}connectionState(){return this.socketAdapter.connectionState()||r.CONNECTION_STATE.closed}isConnected(){return this.socketAdapter.isConnected()}isConnecting(){return this.socketAdapter.isConnecting()}isDisconnecting(){return this.socketAdapter.isDisconnecting()}channel(e,t={config:{}}){let n=`realtime:${e}`,r=this.getChannels().find(e=>e.topic===n);if(r)return r;{let n=new o.default(`realtime:${e}`,t,this);return this._cancelPendingDisconnect(),this.channels.push(n),n}}push(e){this.socketAdapter.push(e)}async setAuth(e=null){let t=++this._authGeneration,n=this._performAuth(e,t);t===this._authGeneration&&(this._authPromise=n);try{await n}finally{this._authPromise===n&&(this._authPromise=null)}}_isManualToken(){return this._manuallySetToken}async sendHeartbeat(){this.socketAdapter.sendHeartbeat()}onHeartbeat(e){this.socketAdapter.heartbeatCallback=this._wrapHeartbeatCallback(e)}_makeRef(){return this.socketAdapter.makeRef()}_remove(e){this.channels=this.channels.filter(t=>t.topic!==e.topic),this.channels.length===0&&(this.log(`transport`,`no channels remaining, scheduling disconnect`),this._schedulePendingDisconnect())}_schedulePendingDisconnect(){this._cancelPendingDisconnect(),this._disconnectOnEmptyChannelsAfterMs===0?(this.log(`transport`,`disconnecting immediately - no channels`),this.disconnect()):(this._pendingDisconnectTimer=setTimeout(()=>{this._pendingDisconnectTimer=null,this.channels.length===0&&(this.log(`transport`,`deferred disconnect fired - no channels, disconnecting`),this.disconnect())},this._disconnectOnEmptyChannelsAfterMs),this.log(`transport`,`deferred disconnect scheduled in ${this._disconnectOnEmptyChannelsAfterMs}ms`))}_cancelPendingDisconnect(){this._pendingDisconnectTimer!==null&&(this.log(`transport`,`pending disconnect cancelled - channel activity detected`),clearTimeout(this._pendingDisconnectTimer),this._pendingDisconnectTimer=null)}async _performAuth(e,t){let n,i=!1;if(e)n=e,i=!0;else if(this.accessToken)try{n=await this.accessToken()}catch(e){this.log(`error`,`Error fetching access token from callback`,e),n=this.accessTokenValue}else n=this.accessTokenValue;t===this._authGeneration&&(this.accessToken?this._manuallySetToken=!1:i&&(this._manuallySetToken=!0),this.accessTokenValue!=n&&(this.accessTokenValue=n,this.channels.forEach(e=>{let t={access_token:n,version:r.DEFAULT_VERSION};e.updateJoinPayload(t),e.joinedOnce&&e.channelAdapter.isJoined()&&e.channelAdapter.push(r.CHANNEL_EVENTS.access_token,{access_token:n})})))}async _waitForAuthIfNeeded(){this._authPromise&&await this._authPromise}_setAuthSafely(e=`general`){this._isManualToken()||this.setAuth().catch(t=>{this.log(`error`,`Error setting auth in ${e}`,t)})}_setupConnectionHandlers(){this.socketAdapter.onOpen(()=>{(this._authPromise||(this.accessToken&&!this.accessTokenValue?this.setAuth():Promise.resolve())).catch(e=>{this.log(`error`,`error waiting for auth on connect`,e)}),this.worker&&!this.workerRef&&this._startWorkerHeartbeat()}),this.socketAdapter.onClose(()=>{this.worker&&this.workerRef&&this._terminateWorker()}),this.socketAdapter.onMessage(e=>{e.ref&&e.ref===this._pendingWorkerHeartbeatRef&&(this._pendingWorkerHeartbeatRef=null)})}_handleNodeJsRaceCondition(){this.socketAdapter.isConnected()&&this.socketAdapter.getSocket().onConnOpen()}_wrapHeartbeatCallback(e){return(t,n)=>{t!==`disconnected`&&(t==`sent`&&this._setAuthSafely(),e&&e(t,n))}}_startWorkerHeartbeat(){this.workerUrl?this.log(`worker`,`starting worker for from ${this.workerUrl}`):this.log(`worker`,`starting default worker`);let e=this._workerObjectUrl(this.workerUrl);this.workerRef=new Worker(e),this.workerRef.onerror=e=>{this.log(`worker`,`worker error`,e.message),this._terminateWorker(),this.disconnect()},this.workerRef.onmessage=e=>{e.data.event===`keepAlive`&&this.sendHeartbeat()},this.workerRef.postMessage({event:`start`,interval:this.heartbeatIntervalMs})}_terminateWorker(){this.workerRef&&=(this.log(`worker`,`terminating worker`),this.workerRef.terminate(),void 0)}_workerObjectUrl(e){let t;if(e)t=e;else{let e=new Blob([`
6
+ addEventListener("message", (e) => {
7
+ if (e.data.event === "start") {
8
+ setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
9
+ }
10
+ });`],{type:`application/javascript`});t=URL.createObjectURL(e)}return t}_initializeOptions(e){this.worker=e?.worker??!1,this.accessToken=e?.accessToken??null;let t={};t.timeout=e?.timeout??r.DEFAULT_TIMEOUT,t.heartbeatIntervalMs=e?.heartbeatIntervalMs??c.HEARTBEAT_INTERVAL,this._disconnectOnEmptyChannelsAfterMs=e?.disconnectOnEmptyChannelsAfterMs??2*(e?.heartbeatIntervalMs??c.HEARTBEAT_INTERVAL),t.transport=e?.transport??n.default.getWebSocketConstructor(),t.params=e?.params,t.logger=e?.logger,t.heartbeatCallback=this._wrapHeartbeatCallback(e?.heartbeatCallback),t.sessionStorage=e?.sessionStorage??d(),t.reconnectAfterMs=e?.reconnectAfterMs??(e=>l[e-1]||1e4);let i,a,o=e?.vsn??r.DEFAULT_VSN;switch(o){case r.VSN_1_0_0:i=(e,t)=>t(JSON.stringify(e)),a=(e,t)=>t(JSON.parse(e));break;case r.VSN_2_0_0:i=this.serializer.encode.bind(this.serializer),a=this.serializer.decode.bind(this.serializer);break;default:throw Error(`Unsupported serializer version: ${t.vsn}`)}if(t.vsn=o,t.encode=e?.encode??i,t.decode=e?.decode??a,t.beforeReconnect=this._reconnectAuth.bind(this),(e?.logLevel||e?.log_level)&&(this.logLevel=e.logLevel||e.log_level,t.params=Object.assign(Object.assign({},t.params),{log_level:this.logLevel})),this.worker){if(typeof window<`u`&&!window.Worker)throw Error(`Web Worker is not supported`);this.workerUrl=e?.workerUrl,t.autoSendHeartbeat=!this.worker}return t}async _reconnectAuth(){await this._waitForAuthIfNeeded(),this.isConnected()||this.connect()}}})),Rt=(/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.WebSocketFactory=e.REALTIME_CHANNEL_STATES=e.REALTIME_SUBSCRIBE_STATES=e.REALTIME_PRESENCE_LISTEN_EVENTS=e.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT=e.REALTIME_LISTEN_TYPES=e.postgresChangesFilter=e.RealtimePostgresFilterBuilder=e.RealtimeClient=e.RealtimeChannel=e.RealtimePresence=void 0;let t=(Qe(),ue(me));e.RealtimeClient=t.__importDefault(Lt()).default;let n=t.__importStar(Ft());e.RealtimeChannel=n.default,Object.defineProperty(e,"RealtimePostgresFilterBuilder",{enumerable:!0,get:function(){return n.RealtimePostgresFilterBuilder}}),Object.defineProperty(e,"postgresChangesFilter",{enumerable:!0,get:function(){return n.postgresChangesFilter}}),Object.defineProperty(e,"REALTIME_LISTEN_TYPES",{enumerable:!0,get:function(){return n.REALTIME_LISTEN_TYPES}}),Object.defineProperty(e,"REALTIME_POSTGRES_CHANGES_LISTEN_EVENT",{enumerable:!0,get:function(){return n.REALTIME_POSTGRES_CHANGES_LISTEN_EVENT}}),Object.defineProperty(e,"REALTIME_SUBSCRIBE_STATES",{enumerable:!0,get:function(){return n.REALTIME_SUBSCRIBE_STATES}}),Object.defineProperty(e,"REALTIME_CHANNEL_STATES",{enumerable:!0,get:function(){return n.REALTIME_CHANNEL_STATES}});let r=t.__importStar(jt());e.RealtimePresence=r.default,Object.defineProperty(e,"REALTIME_PRESENCE_LISTEN_EVENTS",{enumerable:!0,get:function(){return r.REALTIME_PRESENCE_LISTEN_EVENTS}}),e.WebSocketFactory=t.__importDefault(wt()).default})))(),zt=class extends Error{constructor(e,t){super(e),this.name=`IcebergError`,this.status=t.status,this.icebergType=t.icebergType,this.icebergCode=t.icebergCode,this.details=t.details,this.isCommitStateUnknown=t.icebergType===`CommitStateUnknownException`||[500,502,504].includes(t.status)&&t.icebergType?.includes(`CommitState`)===!0}isNotFound(){return this.status===404}isConflict(){return this.status===409}isAuthenticationTimeout(){return this.status===419}};function Bt(e,t,n){let r=new URL(t,e);if(n)for(let[e,t]of Object.entries(n))t!==void 0&&r.searchParams.set(e,t);return r.toString()}async function Vt(e){return!e||e.type===`none`?{}:e.type===`bearer`?{Authorization:`Bearer ${e.token}`}:e.type===`header`?{[e.name]:e.value}:e.type===`custom`?await e.getHeaders():{}}function Ht(e){let t=e.fetchImpl??globalThis.fetch;return{async request({method:n,path:r,query:i,body:a,headers:o}){let s=Bt(e.baseUrl,r,i),c=await Vt(e.auth),l=await t(s,{method:n,headers:{...a?{"Content-Type":`application/json`}:{},...c,...o},body:a?JSON.stringify(a):void 0}),u=await l.text(),d=(l.headers.get(`content-type`)||``).includes(`application/json`),f=d&&u?JSON.parse(u):u;if(!l.ok){let e=d?f:void 0,t=e?.error;throw new zt(t?.message??`Request failed with status ${l.status}`,{status:l.status,icebergType:t?.type,icebergCode:t?.code,details:e})}return{status:l.status,headers:l.headers,data:f}}}}function Ut(e){return e.join(``)}var Wt=class{constructor(e,t=``){this.client=e,this.prefix=t}async listNamespaces(e){let t=e?{parent:Ut(e.namespace)}:void 0;return(await this.client.request({method:`GET`,path:`${this.prefix}/namespaces`,query:t})).data.namespaces.map(e=>({namespace:e}))}async createNamespace(e,t){let n={namespace:e.namespace,properties:t?.properties};return(await this.client.request({method:`POST`,path:`${this.prefix}/namespaces`,body:n})).data}async dropNamespace(e){await this.client.request({method:`DELETE`,path:`${this.prefix}/namespaces/${Ut(e.namespace)}`})}async loadNamespaceMetadata(e){return{properties:(await this.client.request({method:`GET`,path:`${this.prefix}/namespaces/${Ut(e.namespace)}`})).data.properties}}async namespaceExists(e){try{return await this.client.request({method:`HEAD`,path:`${this.prefix}/namespaces/${Ut(e.namespace)}`}),!0}catch(e){if(e instanceof zt&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(e,t){try{return await this.createNamespace(e,t)}catch(e){if(e instanceof zt&&e.status===409)return;throw e}}};function Gt(e){return e.join(``)}var Kt=class{constructor(e,t=``,n){this.client=e,this.prefix=t,this.accessDelegation=n}async listTables(e){return(await this.client.request({method:`GET`,path:`${this.prefix}/namespaces/${Gt(e.namespace)}/tables`})).data.identifiers}async createTable(e,t){let n={};return this.accessDelegation&&(n[`X-Iceberg-Access-Delegation`]=this.accessDelegation),(await this.client.request({method:`POST`,path:`${this.prefix}/namespaces/${Gt(e.namespace)}/tables`,body:t,headers:n})).data.metadata}async updateTable(e,t){let n=await this.client.request({method:`POST`,path:`${this.prefix}/namespaces/${Gt(e.namespace)}/tables/${e.name}`,body:t});return{"metadata-location":n.data[`metadata-location`],metadata:n.data.metadata}}async dropTable(e,t){await this.client.request({method:`DELETE`,path:`${this.prefix}/namespaces/${Gt(e.namespace)}/tables/${e.name}`,query:{purgeRequested:String(t?.purge??!1)}})}async loadTable(e){let t={};return this.accessDelegation&&(t[`X-Iceberg-Access-Delegation`]=this.accessDelegation),(await this.client.request({method:`GET`,path:`${this.prefix}/namespaces/${Gt(e.namespace)}/tables/${e.name}`,headers:t})).data.metadata}async tableExists(e){let t={};this.accessDelegation&&(t[`X-Iceberg-Access-Delegation`]=this.accessDelegation);try{return await this.client.request({method:`HEAD`,path:`${this.prefix}/namespaces/${Gt(e.namespace)}/tables/${e.name}`,headers:t}),!0}catch(e){if(e instanceof zt&&e.status===404)return!1;throw e}}async createTableIfNotExists(e,t){try{return await this.createTable(e,t)}catch(n){if(n instanceof zt&&n.status===409)return await this.loadTable({namespace:e.namespace,name:t.name});throw n}}},qt=class{constructor(e){let t=`v1`;e.catalogName&&(t+=`/${e.catalogName}`);let n=e.baseUrl.endsWith(`/`)?e.baseUrl:`${e.baseUrl}/`;this.client=Ht({baseUrl:n,auth:e.auth,fetchImpl:e.fetch}),this.accessDelegation=e.accessDelegation?.join(`,`),this.namespaceOps=new Wt(this.client,t),this.tableOps=new Kt(this.client,t,this.accessDelegation)}async listNamespaces(e){return this.namespaceOps.listNamespaces(e)}async createNamespace(e,t){return this.namespaceOps.createNamespace(e,t)}async dropNamespace(e){await this.namespaceOps.dropNamespace(e)}async loadNamespaceMetadata(e){return this.namespaceOps.loadNamespaceMetadata(e)}async listTables(e){return this.tableOps.listTables(e)}async createTable(e,t){return this.tableOps.createTable(e,t)}async updateTable(e,t){return this.tableOps.updateTable(e,t)}async dropTable(e,t){await this.tableOps.dropTable(e,t)}async loadTable(e){return this.tableOps.loadTable(e)}async namespaceExists(e){return this.namespaceOps.namespaceExists(e)}async tableExists(e){return this.tableOps.tableExists(e)}async createNamespaceIfNotExists(e,t){return this.namespaceOps.createNamespaceIfNotExists(e,t)}async createTableIfNotExists(e,t){return this.tableOps.createTableIfNotExists(e,t)}};function Jt(e){"@babel/helpers - typeof";return Jt=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},Jt(e)}function Yt(e,t){if(Jt(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(Jt(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function Xt(e){var t=Yt(e,`string`);return Jt(t)==`symbol`?t:t+``}function Zt(e,t,n){return(t=Xt(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Qt(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function O(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Qt(Object(n),!0).forEach(function(t){Zt(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Qt(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}var $t=class extends Error{constructor(e,t=`storage`,n,r){super(e),this.__isStorageError=!0,this.namespace=t,this.name=t===`vectors`?`StorageVectorsError`:`StorageError`,this.status=n,this.statusCode=r}toJSON(){return{name:this.name,message:this.message,status:this.status,statusCode:this.statusCode}}};function en(e){return typeof e==`object`&&!!e&&`__isStorageError`in e}var tn=class extends $t{constructor(e,t,n,r=`storage`,i){super(e,r,t,n),this.name=r===`vectors`?`StorageVectorsApiError`:`StorageApiError`,this.status=t,this.statusCode=n,this.code=i}toJSON(){return O(O({},super.toJSON()),{},{code:this.code})}},nn=class extends $t{constructor(e,t,n=`storage`){super(e,n),this.name=n===`vectors`?`StorageVectorsUnknownError`:`StorageUnknownError`,this.originalError=t}};function rn(e,t,n){let r=O({},e),i=t.toLowerCase();for(let e of Object.keys(r))e.toLowerCase()===i&&delete r[e];return r[i]=n,r}function an(e){let t={};for(let[n,r]of Object.entries(e))t[n.toLowerCase()]=r;return t}const on=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),sn=e=>{if(typeof e!=`object`||!e)return!1;let t=Object.getPrototypeOf(e);return(t===null||t===Object.prototype||Object.getPrototypeOf(t)===null)&&!(Symbol.toStringTag in e)&&!(Symbol.iterator in e)},cn=e=>{if(Array.isArray(e))return e.map(e=>cn(e));if(typeof e==`function`||e!==Object(e))return e;let t={};return Object.entries(e).forEach(([e,n])=>{let r=e.replace(/([-_][a-z])/gi,e=>e.toUpperCase().replace(/[-_]/g,``));t[r]=cn(n)}),t},ln=e=>!e||typeof e!=`string`||e.length===0||e.length>100||e.trim()!==e||e.includes(`/`)||e.includes(`\\`)?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(e),un=e=>e.split(`/`).map(encodeURIComponent).join(`/`),dn=e=>{if(typeof e==`object`&&e){let t=e;if(typeof t.msg==`string`)return t.msg;if(typeof t.message==`string`)return t.message;if(typeof t.error_description==`string`)return t.error_description;if(typeof t.error==`string`)return t.error;if(typeof t.error==`object`&&t.error!==null){let e=t.error;if(typeof e.message==`string`)return e.message}}return JSON.stringify(e)},fn=async(e,t,n,r)=>{if(typeof e==`object`&&e&&`json`in e&&typeof e.json==`function`){let n=e,i=parseInt(String(n.status),10);Number.isFinite(i)||(i=500),n.json().then(e=>{let n=e?.statusCode||e?.code||i+``;t(new tn(dn(e),i,n,r,e?.code))}).catch(()=>{let e=i+``;t(new tn(n.statusText||`HTTP ${i} error`,i,e,r))})}else t(new nn(dn(e),e,r))},pn=(e,t,n,r)=>{let i={method:e,headers:t?.headers||{}};if(e===`GET`||e===`HEAD`||!r)return O(O({},i),n);if(sn(r)){let e=t?.headers||{},n;for(let[t,r]of Object.entries(e))t.toLowerCase()===`content-type`&&(n=r);i.headers=rn(e,`Content-Type`,n??`application/json`),i.body=JSON.stringify(r)}else i.body=r;return t?.duplex&&(i.duplex=t.duplex),O(O({},i),n)};async function mn(e,t,n,r,i,a,o){return new Promise((s,c)=>{e(n,pn(t,r,i,a)).then(e=>{if(!e.ok)throw e;if(r?.noResolveJson)return e;if(o===`vectors`){let t=e.headers.get(`content-type`);if(e.headers.get(`content-length`)===`0`||e.status===204||!t||!t.includes(`application/json`))return{}}return e.json()}).then(e=>s(e)).catch(e=>fn(e,c,r,o))})}function hn(e=`storage`){return{get:async(t,n,r,i)=>mn(t,`GET`,n,r,i,void 0,e),post:async(t,n,r,i,a)=>mn(t,`POST`,n,i,a,r,e),put:async(t,n,r,i,a)=>mn(t,`PUT`,n,i,a,r,e),head:async(t,n,r,i)=>mn(t,`HEAD`,n,O(O({},r),{},{noResolveJson:!0}),i,void 0,e),remove:async(t,n,r,i,a)=>mn(t,`DELETE`,n,i,a,r,e)}}const{get:gn,post:_n,put:vn,head:yn,remove:bn}=hn(`storage`),xn=hn(`vectors`);var Sn=class{constructor(e,t={},n,r=`storage`){this.shouldThrowOnError=!1,this.url=e,this.headers=an(t),this.fetch=on(n),this.namespace=r}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=rn(this.headers,e,t),this}async handleOperation(e){var t=this;try{return{data:await e(),error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(en(e))return{data:null,error:e};throw e}}};let Cn;Cn=Symbol.toStringTag;var wn=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[Cn]=`StreamDownloadBuilder`,this.promise=null}then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||=this.execute(),this.promise}async execute(){var e=this;try{return{data:(await e.downloadFn()).body,error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(en(t))return{data:null,error:t};throw t}}};let Tn;Tn=Symbol.toStringTag;var En=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[Tn]=`BlobDownloadBuilder`,this.promise=null}asStream(){return new wn(this.downloadFn,this.shouldThrowOnError)}then(e,t){return this.getPromise().then(e,t)}catch(e){return this.getPromise().catch(e)}finally(e){return this.getPromise().finally(e)}getPromise(){return this.promise||=this.execute(),this.promise}async execute(){var e=this;try{return{data:await(await e.downloadFn()).blob(),error:null}}catch(t){if(e.shouldThrowOnError)throw t;if(en(t))return{data:null,error:t};throw t}}};const Dn={limit:100,offset:0,sortBy:{column:`name`,order:`asc`}},On={cacheControl:`3600`,contentType:`text/plain;charset=UTF-8`,upsert:!1};var kn=class extends Sn{constructor(e,t={},n,r){super(e,t,r,`storage`),this.bucketId=n}async uploadOrUpdate(e,t,n,r){var i=this;return i.handleOperation(async()=>{let a,o=O(O({},On),r),s=O(O({},i.headers),e===`POST`&&{"x-upsert":String(o.upsert)}),c=o.metadata;if(typeof Blob<`u`&&n instanceof Blob||typeof FormData<`u`&&n instanceof FormData?a=i.prepareUploadFormData(n,o):(a=n,s[`cache-control`]=`max-age=${o.cacheControl}`,s[`content-type`]=o.contentType,o.contentEncoding&&(s[`content-encoding`]=o.contentEncoding),c&&(s[`x-metadata`]=i.toBase64(i.encodeMetadata(c))),(typeof ReadableStream<`u`&&a instanceof ReadableStream||a&&typeof a==`object`&&`pipe`in a&&typeof a.pipe==`function`)&&!o.duplex&&(o.duplex=`half`)),r?.headers)for(let[e,t]of Object.entries(r.headers))s=rn(s,e,t);let l=i._removeEmptyFolders(t),u=i._getFinalPath(l),d=await(e==`PUT`?vn:_n)(i.fetch,`${i.url}/object/${u}`,a,O({headers:s},o?.duplex?{duplex:o.duplex}:{}));return{path:l,id:d.Id,fullPath:d.Key}})}async upload(e,t,n){return this.uploadOrUpdate(`POST`,e,t,n)}async uploadToSignedUrl(e,t,n,r){var i=this;let a=i._removeEmptyFolders(e),o=i._getFinalPath(a),s=new URL(i.url+`/object/upload/sign/${o}`);return s.searchParams.set(`token`,t),i.handleOperation(async()=>{let e,t=O(O({},On),r),o=O(O({},i.headers),{"x-upsert":String(t.upsert)}),c=t.metadata;if(typeof Blob<`u`&&n instanceof Blob||typeof FormData<`u`&&n instanceof FormData?e=i.prepareUploadFormData(n,t):(e=n,o[`cache-control`]=`max-age=${t.cacheControl}`,o[`content-type`]=t.contentType,t.contentEncoding&&(o[`content-encoding`]=t.contentEncoding),c&&(o[`x-metadata`]=i.toBase64(i.encodeMetadata(c))),(typeof ReadableStream<`u`&&e instanceof ReadableStream||e&&typeof e==`object`&&`pipe`in e&&typeof e.pipe==`function`)&&!t.duplex&&(t.duplex=`half`)),r?.headers)for(let[e,t]of Object.entries(r.headers))o=rn(o,e,t);return{path:a,fullPath:(await vn(i.fetch,s.toString(),e,O({headers:o},t?.duplex?{duplex:t.duplex}:{}))).Key}})}async createSignedUploadUrl(e,t){var n=this;return n.handleOperation(async()=>{let r=n._getFinalPath(e),i=O({},n.headers);t?.upsert&&(i[`x-upsert`]=`true`);let a=await _n(n.fetch,`${n.url}/object/upload/sign/${r}`,{},{headers:i}),o=new URL(n.url+a.url),s=o.searchParams.get(`token`);if(!s)throw new $t(`No token returned by API`);return{signedUrl:o.toString(),path:e,token:s}})}async update(e,t,n){return this.uploadOrUpdate(`PUT`,e,t,n)}async move(e,t,n){var r=this;return r.handleOperation(async()=>await _n(r.fetch,`${r.url}/object/move`,{bucketId:r.bucketId,sourceKey:e,destinationKey:t,destinationBucket:n?.destinationBucket,sourceVersionId:n?.sourceVersionId},{headers:r.headers}))}async copy(e,t,n){var r=this;return r.handleOperation(async()=>{let i=n;return{path:(await _n(r.fetch,`${r.url}/object/copy`,{bucketId:r.bucketId,sourceKey:e,destinationKey:t,destinationBucket:n?.destinationBucket,sourceVersionId:n?.sourceVersionId,copyMetadata:typeof i?.copyMetadata==`boolean`?i.copyMetadata:void 0,metadata:i?.copyMetadata===!1?i.metadata:void 0},{headers:r.headers})).Key}})}async createSignedUrl(e,t,n){var r=this;return r.handleOperation(async()=>{let i=r._getFinalPath(e),a=typeof n?.transform==`object`&&n.transform!==null&&Object.keys(n.transform).length>0,o=await _n(r.fetch,`${r.url}/object/sign/${i}`,O(O({expiresIn:t},a?{transform:n.transform}:{}),n?.versionId==null?{}:{versionId:n.versionId}),{headers:r.headers}),s=new URLSearchParams;n?.download&&s.set(`download`,n.download===!0?``:n.download),n?.cacheNonce!=null&&s.set(`cacheNonce`,String(n.cacheNonce));let c=s.toString();return{signedUrl:encodeURI(`${r.url}${o.signedURL}${c?`&${c}`:``}`)}})}async createSignedUrls(e,t,n){var r=this;return r.handleOperation(async()=>{let i=await _n(r.fetch,`${r.url}/object/sign/${r.bucketId}`,{expiresIn:t,paths:e},{headers:r.headers}),a=new URLSearchParams;n?.download&&a.set(`download`,n.download===!0?``:n.download),n?.cacheNonce!=null&&a.set(`cacheNonce`,String(n.cacheNonce));let o=a.toString();return i.map(e=>O(O({},e),{},{signedUrl:e.signedURL?encodeURI(`${r.url}${e.signedURL}${o?`&${o}`:``}`):null}))})}download(e,t,n){let r=typeof t?.transform==`object`&&t.transform!==null&&Object.keys(t.transform).length>0?`render/image/authenticated`:`object`,i=new URLSearchParams;t?.transform&&this.applyTransformOptsToQuery(i,t.transform),t?.cacheNonce!=null&&i.set(`cacheNonce`,String(t.cacheNonce)),t?.versionId!=null&&i.set(`versionId`,String(t.versionId));let a=i.toString(),o=this._getFinalPath(e);return new En(()=>gn(this.fetch,`${this.url}/${r}/${o}${a?`?${a}`:``}`,{headers:this.headers,noResolveJson:!0},n),this.shouldThrowOnError)}async info(e,t){var n=this;let r=n._getFinalPath(e),i=new URLSearchParams;t?.versionId!=null&&i.set(`versionId`,String(t.versionId));let a=i.toString();return n.handleOperation(async()=>cn(await gn(n.fetch,`${n.url}/object/info/${r}${a?`?${a}`:``}`,{headers:n.headers})))}async exists(e){var t=this;let n=t._getFinalPath(e);try{return await yn(t.fetch,`${t.url}/object/${n}`,{headers:t.headers}),{data:!0,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(en(e)){let t=e instanceof tn?e.status:e instanceof nn?e.originalError?.status:void 0;if(t!==void 0&&[400,404].includes(t))return{data:!1,error:e}}throw e}}getPublicUrl(e,t){let n=this._getFinalPath(e),r=new URLSearchParams;t?.download&&r.set(`download`,t.download===!0?``:t.download),t?.transform&&this.applyTransformOptsToQuery(r,t.transform),t?.cacheNonce!=null&&r.set(`cacheNonce`,String(t.cacheNonce)),t?.versionId!=null&&r.set(`versionId`,String(t.versionId));let i=r.toString(),a=typeof t?.transform==`object`&&t.transform!==null&&Object.keys(t.transform).length>0?`render/image`:`object`;return{data:{publicUrl:encodeURI(`${this.url}/${a}/public/${n}`)+(i?`?${i}`:``)}}}async remove(e){var t=this;return t.handleOperation(async()=>await bn(t.fetch,`${t.url}/object/${t.bucketId}`,{prefixes:e},{headers:t.headers}))}async purgeCache(e,t,n){var r=this;return r.handleOperation(async()=>{let i=un(r._getFinalPath(e)),a=new URLSearchParams;t?.transformations&&a.set(`transformations`,`true`);let o=a.toString();return await bn(r.fetch,`${r.url}/cdn/${i}${o?`?${o}`:``}`,{},{headers:r.headers},n)})}async list(e,t,n){var r=this;return r.handleOperation(async()=>{let i=t?.sortBy?O(O({},Dn.sortBy),t.sortBy):Dn.sortBy,a=O(O(O({},Dn),t),{},{sortBy:i,prefix:e||``});return await _n(r.fetch,`${r.url}/object/list/${r.bucketId}`,a,{headers:r.headers},n)})}async listV2(e,t){var n=this;return n.handleOperation(async()=>{let r=O({},e);return await _n(n.fetch,`${n.url}/object/list-v2/${n.bucketId}`,r,{headers:n.headers},t)})}prepareUploadFormData(e,t){let n=new FormData,r=[];e instanceof FormData?e.forEach((e,t)=>{typeof e==`string`?n.append(t,e):r.push([t,e])}):r.push([``,e]),n.has(`cacheControl`)||n.append(`cacheControl`,t.cacheControl),t.metadata&&!n.has(`metadata`)&&n.append(`metadata`,this.encodeMetadata(t.metadata)),t.contentEncoding&&!n.has(`contentEncoding`)&&n.append(`contentEncoding`,t.contentEncoding);for(let[e,t]of r)n.append(e,t);return n}encodeMetadata(e){return JSON.stringify(e)}toBase64(e){return typeof Buffer<`u`?Buffer.from(e).toString(`base64`):btoa(e)}_getFinalPath(e){return`${this.bucketId}/${e.replace(/^\/+/,``)}`}_removeEmptyFolders(e){return e.replace(/^\/|\/$/g,``).replace(/\/+/g,`/`)}applyTransformOptsToQuery(e,t){return t.width&&e.set(`width`,t.width.toString()),t.height&&e.set(`height`,t.height.toString()),t.resize&&e.set(`resize`,t.resize),t.format&&e.set(`format`,t.format),t.quality&&e.set(`quality`,t.quality.toString()),e}};const An={"X-Client-Info":`storage-js/2.118.0`};var jn=class extends Sn{constructor(e,t={},n,r){let i=new URL(e);r?.useNewHostname&&/supabase\.(co|in|red)$/.test(i.hostname)&&!i.hostname.includes(`storage.supabase.`)&&(i.hostname=i.hostname.replace(`supabase.`,`storage.supabase.`));let a=i.href.replace(/\/$/,``),o=O(O({},An),t);super(a,o,n,`storage`)}async listBuckets(e){var t=this;return t.handleOperation(async()=>{let n=t.listBucketOptionsToQueryString(e);return await gn(t.fetch,`${t.url}/bucket${n}`,{headers:t.headers})})}async getBucket(e){var t=this;return t.handleOperation(async()=>await gn(t.fetch,`${t.url}/bucket/${e}`,{headers:t.headers}))}async createBucket(e,t={public:!1}){var n=this;return n.handleOperation(async()=>await _n(n.fetch,`${n.url}/bucket`,{id:e,name:e,type:t.type,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes,versioning_status:t.versioningStatus},{headers:n.headers}))}async updateBucket(e,t){var n=this;return n.handleOperation(async()=>await vn(n.fetch,`${n.url}/bucket/${e}`,{id:e,name:e,public:t.public,file_size_limit:t.fileSizeLimit,allowed_mime_types:t.allowedMimeTypes,versioning_status:t.versioningStatus},{headers:n.headers}))}async emptyBucket(e){var t=this;return t.handleOperation(async()=>await _n(t.fetch,`${t.url}/bucket/${e}/empty`,{},{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await bn(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}))}async getBucketLifecycle(e){var t=this;return t.handleOperation(async()=>await gn(t.fetch,t.bucketLifecycleUrl(e),{headers:t.headers}))}async updateBucketLifecycle(e,t){var n=this;return n.handleOperation(async()=>await vn(n.fetch,n.bucketLifecycleUrl(e),t,{headers:n.headers}))}async deleteBucketLifecycle(e){var t=this;return t.handleOperation(async()=>await bn(t.fetch,t.bucketLifecycleUrl(e),{},{headers:t.headers}))}async purgeBucketCache(e,t,n){var r=this;return r.handleOperation(async()=>{let i=new URLSearchParams;t?.transformations&&i.set(`transformations`,`true`);let a=i.toString();return await bn(r.fetch,`${r.url}/cdn/${un(e)}${a?`?${a}`:``}`,{},{headers:r.headers},n)})}bucketLifecycleUrl(e){return`${this.url}/bucket/${un(e)}/lifecycle`}listBucketOptionsToQueryString(e){let t={};return e&&(`limit`in e&&(t.limit=String(e.limit)),`offset`in e&&(t.offset=String(e.offset)),e.search&&(t.search=e.search),e.sortColumn&&(t.sortColumn=e.sortColumn),e.sortOrder&&(t.sortOrder=e.sortOrder)),Object.keys(t).length>0?`?`+new URLSearchParams(t).toString():``}},Mn=class extends Sn{constructor(e,t={},n){let r=e.replace(/\/$/,``),i=O(O({},An),t);super(r,i,n,`storage`)}async createBucket(e){var t=this;return t.handleOperation(async()=>await _n(t.fetch,`${t.url}/bucket`,{name:e},{headers:t.headers}))}async listBuckets(e){var t=this;return t.handleOperation(async()=>{let n=new URLSearchParams;e?.limit!==void 0&&n.set(`limit`,e.limit.toString()),e?.offset!==void 0&&n.set(`offset`,e.offset.toString()),e?.sortColumn&&n.set(`sortColumn`,e.sortColumn),e?.sortOrder&&n.set(`sortOrder`,e.sortOrder),e?.search&&n.set(`search`,e.search);let r=n.toString(),i=r?`${t.url}/bucket?${r}`:`${t.url}/bucket`;return await gn(t.fetch,i,{headers:t.headers})})}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await bn(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}))}from(e){var t=this;if(!ln(e))throw new $t(`Invalid bucket name: File, folder, and bucket names must follow AWS object key naming guidelines and should avoid the use of any other characters.`);let n=new qt({baseUrl:this.url,catalogName:e,auth:{type:`custom`,getHeaders:async()=>t.headers},fetch:this.fetch}),r=this.shouldThrowOnError;return new Proxy(n,{get(e,t){let n=e[t];return typeof n==`function`?async(...t)=>{try{return{data:await n.apply(e,t),error:null}}catch(e){if(r)throw e;return{data:null,error:e}}}:n}})}},Nn=class extends Sn{constructor(e,t={},n){let r=e.replace(/\/$/,``),i=O(O({},An),{},{"Content-Type":`application/json`},t);super(r,i,n,`vectors`)}async createIndex(e){var t=this;return t.handleOperation(async()=>await xn.post(t.fetch,`${t.url}/CreateIndex`,e,{headers:t.headers})||{})}async getIndex(e,t){var n=this;return n.handleOperation(async()=>await xn.post(n.fetch,`${n.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:n.headers}))}async listIndexes(e){var t=this;return t.handleOperation(async()=>await xn.post(t.fetch,`${t.url}/ListIndexes`,e,{headers:t.headers}))}async deleteIndex(e,t){var n=this;return n.handleOperation(async()=>await xn.post(n.fetch,`${n.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:n.headers})||{})}},Pn=class extends Sn{constructor(e,t={},n){let r=e.replace(/\/$/,``),i=O(O({},An),{},{"Content-Type":`application/json`},t);super(r,i,n,`vectors`)}async putVectors(e){var t=this;if(e.vectors.length<1||e.vectors.length>500)throw Error(`Vector batch size must be between 1 and 500 items`);return t.handleOperation(async()=>await xn.post(t.fetch,`${t.url}/PutVectors`,e,{headers:t.headers})||{})}async getVectors(e){var t=this;return t.handleOperation(async()=>await xn.post(t.fetch,`${t.url}/GetVectors`,e,{headers:t.headers}))}async listVectors(e){var t=this;if(e.segmentCount!==void 0){if(e.segmentCount<1||e.segmentCount>16)throw Error(`segmentCount must be between 1 and 16`);if(e.segmentIndex!==void 0&&(e.segmentIndex<0||e.segmentIndex>=e.segmentCount))throw Error(`segmentIndex must be between 0 and ${e.segmentCount-1}`)}return t.handleOperation(async()=>await xn.post(t.fetch,`${t.url}/ListVectors`,e,{headers:t.headers}))}async queryVectors(e){var t=this;return t.handleOperation(async()=>await xn.post(t.fetch,`${t.url}/QueryVectors`,e,{headers:t.headers}))}async deleteVectors(e){var t=this;if(e.keys.length<1||e.keys.length>500)throw Error(`Keys batch size must be between 1 and 500 items`);return t.handleOperation(async()=>await xn.post(t.fetch,`${t.url}/DeleteVectors`,e,{headers:t.headers})||{})}},Fn=class extends Sn{constructor(e,t={},n){let r=e.replace(/\/$/,``),i=O(O({},An),{},{"Content-Type":`application/json`},t);super(r,i,n,`vectors`)}async createBucket(e){var t=this;return t.handleOperation(async()=>await xn.post(t.fetch,`${t.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{})}async getBucket(e){var t=this;return t.handleOperation(async()=>await xn.post(t.fetch,`${t.url}/GetVectorBucket`,{vectorBucketName:e},{headers:t.headers}))}async listBuckets(e={}){var t=this;return t.handleOperation(async()=>await xn.post(t.fetch,`${t.url}/ListVectorBuckets`,e,{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await xn.post(t.fetch,`${t.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{})}},In=class extends Fn{constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new Ln(this.url,this.headers,e,this.fetch)}async createBucket(e){var t=()=>super.createBucket,n=this;return t().call(n,e)}async getBucket(e){var t=()=>super.getBucket,n=this;return t().call(n,e)}async listBuckets(e={}){var t=()=>super.listBuckets,n=this;return t().call(n,e)}async deleteBucket(e){var t=()=>super.deleteBucket,n=this;return t().call(n,e)}},Ln=class extends Nn{constructor(e,t,n,r){super(e,t,r),this.vectorBucketName=n}async createIndex(e){var t=()=>super.createIndex,n=this;return t().call(n,O(O({},e),{},{vectorBucketName:n.vectorBucketName}))}async listIndexes(e={}){var t=()=>super.listIndexes,n=this;return t().call(n,O(O({},e),{},{vectorBucketName:n.vectorBucketName}))}async getIndex(e){var t=()=>super.getIndex,n=this;return t().call(n,n.vectorBucketName,e)}async deleteIndex(e){var t=()=>super.deleteIndex,n=this;return t().call(n,n.vectorBucketName,e)}index(e){return new Rn(this.url,this.headers,this.vectorBucketName,e,this.fetch)}},Rn=class extends Pn{constructor(e,t,n,r,i){super(e,t,i),this.vectorBucketName=n,this.indexName=r}async putVectors(e){var t=()=>super.putVectors,n=this;return t().call(n,O(O({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async getVectors(e){var t=()=>super.getVectors,n=this;return t().call(n,O(O({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async listVectors(e={}){var t=()=>super.listVectors,n=this;return t().call(n,O(O({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async queryVectors(e){var t=()=>super.queryVectors,n=this;return t().call(n,O(O({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async deleteVectors(e){var t=()=>super.deleteVectors,n=this;return t().call(n,O(O({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}},zn=class extends jn{constructor(e,t={},n,r){super(e,t,n,r)}from(e){return new kn(this.url,this.headers,e,this.fetch)}get vectors(){return new In(this.url+`/vector`,{headers:this.headers,fetch:this.fetch})}get analytics(){return new Mn(this.url+`/iceberg`,this.headers,this.fetch)}},Bn=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.version=void 0,e.version=`2.118.0`})),Vn=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.JWKS_TTL=e.PKCE_MAX_CONCURRENT_FLOWS=e.PKCE_FLOW_ID_PARAM=e.BASE64URL_REGEX=e.API_VERSIONS=e.API_VERSION_HEADER_NAME=e.NETWORK_FAILURE=e.DEFAULT_HEADERS=e.AUDIENCE=e.STORAGE_KEY=e.GOTRUE_URL=e.REFRESH_FAILURE_COOLDOWN_MS=e.EXPIRY_MARGIN_MS=e.AUTO_REFRESH_TICK_THRESHOLD=e.AUTO_REFRESH_TICK_DURATION_MS=void 0;let t=Bn();e.AUTO_REFRESH_TICK_DURATION_MS=3e4,e.AUTO_REFRESH_TICK_THRESHOLD=3,e.EXPIRY_MARGIN_MS=e.AUTO_REFRESH_TICK_THRESHOLD*e.AUTO_REFRESH_TICK_DURATION_MS,e.REFRESH_FAILURE_COOLDOWN_MS=2*e.AUTO_REFRESH_TICK_DURATION_MS,e.GOTRUE_URL=`http://localhost:9999`,e.STORAGE_KEY=`supabase.auth.token`,e.AUDIENCE=``,e.DEFAULT_HEADERS={"X-Client-Info":`gotrue-js/${t.version}`},e.NETWORK_FAILURE={MAX_RETRIES:10,RETRY_INTERVAL:2},e.API_VERSION_HEADER_NAME=`X-Supabase-Api-Version`,e.API_VERSIONS={"2024-01-01":{timestamp:Date.parse(`2024-01-01T00:00:00.0Z`),name:`2024-01-01`}},e.BASE64URL_REGEX=/^([a-z0-9_-]{4})*($|[a-z0-9_-]{3}$|[a-z0-9_-]{2}$)$/i,e.PKCE_FLOW_ID_PARAM=`sb_flow_id`,e.PKCE_MAX_CONCURRENT_FLOWS=5,e.JWKS_TTL=6e5})),Hn=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.AuthInvalidJwtError=e.AuthWeakPasswordError=e.AuthRefreshDiscardedError=e.AuthRetryableFetchError=e.AuthPKCECodeVerifierMissingError=e.AuthPKCEGrantCodeExchangeError=e.AuthImplicitGrantRedirectError=e.AuthInvalidCredentialsError=e.AuthInvalidTokenResponseError=e.AuthSessionMissingError=e.CustomAuthError=e.AuthUnknownError=e.AuthApiError=e.AuthError=void 0,e.isAuthError=n,e.isAuthApiError=r,e.isAuthSessionMissingError=a,e.isAuthImplicitGrantRedirectError=o,e.isAuthPKCECodeVerifierMissingError=s,e.isAuthRetryableFetchError=c,e.isAuthRefreshDiscardedError=l,e.isAuthWeakPasswordError=u;var t=class extends Error{constructor(e,t,n){super(e),this.__isAuthError=!0,this.name=`AuthError`,this.status=t,this.code=n}toJSON(){return{name:this.name,message:this.message,status:this.status,code:this.code}}};e.AuthError=t;function n(e){return typeof e==`object`&&!!e&&`__isAuthError`in e}e.AuthApiError=class extends t{constructor(e,t,n){super(e,t,n),this.name=`AuthApiError`,this.status=t,this.code=n}};function r(e){return n(e)&&e.name===`AuthApiError`}e.AuthUnknownError=class extends t{constructor(e,t){super(e),this.name=`AuthUnknownError`,this.originalError=t}};var i=class extends t{constructor(e,t,n,r){super(e,n,r),this.name=t,this.status=n}};e.CustomAuthError=i,e.AuthSessionMissingError=class extends i{constructor(){super(`Auth session missing!`,`AuthSessionMissingError`,400,void 0)}};function a(e){return n(e)&&e.name===`AuthSessionMissingError`}e.AuthInvalidTokenResponseError=class extends i{constructor(){super(`Auth session or user missing`,`AuthInvalidTokenResponseError`,500,void 0)}},e.AuthInvalidCredentialsError=class extends i{constructor(e){super(e,`AuthInvalidCredentialsError`,400,void 0)}},e.AuthImplicitGrantRedirectError=class extends i{constructor(e,t=null){super(e,`AuthImplicitGrantRedirectError`,500,void 0),this.details=null,this.details=t}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}};function o(e){return n(e)&&e.name===`AuthImplicitGrantRedirectError`}e.AuthPKCEGrantCodeExchangeError=class extends i{constructor(e,t=null){super(e,`AuthPKCEGrantCodeExchangeError`,500,void 0),this.details=null,this.details=t}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{details:this.details})}},e.AuthPKCECodeVerifierMissingError=class extends i{constructor(){super(`PKCE code verifier not found in storage. This can happen if the auth flow was initiated in a different browser or device, or if the storage was cleared. For SSR frameworks (Next.js, SvelteKit, etc.), use @supabase/ssr on both the server and client to store the code verifier in cookies.`,`AuthPKCECodeVerifierMissingError`,400,`pkce_code_verifier_not_found`)}};function s(e){return n(e)&&e.name===`AuthPKCECodeVerifierMissingError`}e.AuthRetryableFetchError=class extends i{constructor(e,t){super(e,`AuthRetryableFetchError`,t,void 0)}};function c(e){return n(e)&&e.name===`AuthRetryableFetchError`}e.AuthRefreshDiscardedError=class extends i{constructor(e=`Refresh result discarded: session state changed mid-flight (e.g., concurrent signOut)`){super(e,`AuthRefreshDiscardedError`,409,void 0)}};function l(e){return n(e)&&e.name===`AuthRefreshDiscardedError`}e.AuthWeakPasswordError=class extends i{constructor(e,t,n){super(e,`AuthWeakPasswordError`,t,`weak_password`),this.reasons=n}toJSON(){return Object.assign(Object.assign({},super.toJSON()),{reasons:this.reasons})}};function u(e){return n(e)&&e.name===`AuthWeakPasswordError`}e.AuthInvalidJwtError=class extends i{constructor(e){super(e,`AuthInvalidJwtError`,400,`invalid_jwt`)}}})),Un=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.byteToBase64URL=i,e.byteFromBase64URL=a,e.stringToBase64URL=o,e.stringFromBase64URL=s,e.codepointToUTF8=c,e.stringToUTF8=l,e.stringFromUTF8=u,e.base64UrlToUint8Array=d,e.stringToUint8Array=f,e.bytesToBase64URL=p;let t=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_`.split(``),n=`
11
+ \r=`.split(``),r=(()=>{let e=Array(128);for(let t=0;t<e.length;t+=1)e[t]=-1;for(let t=0;t<n.length;t+=1)e[n[t].charCodeAt(0)]=-2;for(let n=0;n<t.length;n+=1)e[t[n].charCodeAt(0)]=n;return e})();function i(e,n,r){if(e!==null)for(n.queue=n.queue<<8|e,n.queuedBits+=8;n.queuedBits>=6;){let e=n.queue>>n.queuedBits-6&63;r(t[e]),n.queuedBits-=6}else if(n.queuedBits>0)for(n.queue<<=6-n.queuedBits,n.queuedBits=6;n.queuedBits>=6;){let e=n.queue>>n.queuedBits-6&63;r(t[e]),n.queuedBits-=6}}function a(e,t,n){let i=r[e];if(i>-1)for(t.queue=t.queue<<6|i,t.queuedBits+=6;t.queuedBits>=8;)n(t.queue>>t.queuedBits-8&255),t.queuedBits-=8;else if(i===-2)return;else throw Error(`Invalid Base64-URL character "${String.fromCharCode(e)}"`)}function o(e){let t=[],n=e=>{t.push(e)},r={queue:0,queuedBits:0};return l(e,e=>{i(e,r,n)}),i(null,r,n),t.join(``)}function s(e){let t=[],n=e=>{t.push(String.fromCodePoint(e))},r={utf8seq:0,codepoint:0},i={queue:0,queuedBits:0},o=e=>{u(e,r,n)};for(let t=0;t<e.length;t+=1)a(e.charCodeAt(t),i,o);return t.join(``)}function c(e,t){if(e<=127)t(e);else if(e<=2047)t(192|e>>6),t(128|e&63);else if(e<=65535)t(224|e>>12),t(128|e>>6&63),t(128|e&63);else if(e<=1114111)t(240|e>>18),t(128|e>>12&63),t(128|e>>6&63),t(128|e&63);else throw Error(`Unrecognized Unicode codepoint: ${e.toString(16)}`)}function l(e,t){for(let n=0;n<e.length;n+=1){let r=e.charCodeAt(n);if(r>55295&&r<=56319){let t=(r-55296)*1024&65535;r=(e.charCodeAt(n+1)-56320&65535|t)+65536,n+=1}c(r,t)}}function u(e,t,n){if(t.utf8seq===0){if(e<=127){n(e);return}for(let n=1;n<6;n+=1)if(!(e>>7-n&1)){t.utf8seq=n;break}if(t.utf8seq===2)t.codepoint=e&31;else if(t.utf8seq===3)t.codepoint=e&15;else if(t.utf8seq===4)t.codepoint=e&7;else throw Error(`Invalid UTF-8 sequence`);--t.utf8seq}else if(t.utf8seq>0){if(e<=127)throw Error(`Invalid UTF-8 sequence`);t.codepoint=t.codepoint<<6|e&63,--t.utf8seq,t.utf8seq===0&&n(t.codepoint)}}function d(e){let t=[],n={queue:0,queuedBits:0},r=e=>{t.push(e)};for(let t=0;t<e.length;t+=1)a(e.charCodeAt(t),n,r);return new Uint8Array(t)}function f(e){let t=[];return l(e,e=>t.push(e)),new Uint8Array(t)}function p(e){let t=[],n={queue:0,queuedBits:0},r=e=>{t.push(e)};return e.forEach(e=>i(e,n,r)),i(null,n,r),t.join(``)}})),Wn=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.pkceVerifierSlotKey=e.Deferred=e.removeItemAsync=e.getItemAsync=e.setItemAsync=e.looksLikeFetchResponse=e.resolveFetch=e.supportsLocalStorage=e.isBrowser=void 0,e.expiresAt=i,e.generateCallbackId=a,e.parseParametersFromURL=s,e.decodeJWT=l,e.sleep=u,e.retryable=d,e.generatePKCEVerifier=p,e.generatePKCEChallenge=h,e.validatePKCEFlowId=_,e.generatePKCEFlowId=v,e.storePKCEVerifier=x,e.retrievePKCEVerifier=S,e.removePKCEVerifier=C,e.removeAllPKCEVerifiers=w,e.appendFlowIdToRedirectTo=T,e.getCodeChallengeAndMethod=E,e.parseResponseAPIVersion=te,e.validateExp=ne,e.getAlgorithm=re,e.validateUUID=ae,e.assertRecoveryCodesExperimentalEnabled=oe,e.userNotAvailableProxy=D,e.insecureUserWarningProxy=se,e.deepClone=ce;let t=Vn(),n=Hn(),r=Un();function i(e){return Math.round(Date.now()/1e3)+e}function a(){return Symbol(`auth-callback`)}e.isBrowser=()=>typeof window<`u`&&typeof document<`u`;let o={tested:!1,writable:!1};e.supportsLocalStorage=()=>{if(!(0,e.isBrowser)())return!1;try{if(typeof globalThis.localStorage!=`object`)return!1}catch{return!1}if(o.tested)return o.writable;let t=`lswt-${Math.random()}${Math.random()}`;try{globalThis.localStorage.setItem(t,t),globalThis.localStorage.removeItem(t),o.tested=!0,o.writable=!0}catch{o.tested=!0,o.writable=!1}return o.writable};function s(e){let t={},n=new URL(e);if(n.hash&&n.hash[0]===`#`)try{new URLSearchParams(n.hash.substring(1)).forEach((e,n)=>{t[n]=e})}catch{}return n.searchParams.forEach((e,n)=>{t[n]=e}),t}e.resolveFetch=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),e.looksLikeFetchResponse=e=>typeof e==`object`&&!!e&&`status`in e&&`ok`in e&&`json`in e&&typeof e.json==`function`,e.setItemAsync=async(e,t,n)=>{await e.setItem(t,JSON.stringify(n))},e.getItemAsync=async(e,t)=>{let n=await e.getItem(t);if(!n)return null;try{return JSON.parse(n)}catch{return null}},e.removeItemAsync=async(e,t)=>{await e.removeItem(t)};var c=class e{constructor(){this.promise=new e.promiseConstructor((e,t)=>{this.resolve=e,this.reject=t})}};e.Deferred=c,c.promiseConstructor=Promise;function l(e){let i=e.split(`.`);if(i.length!==3)throw new n.AuthInvalidJwtError(`Invalid JWT structure`);for(let e=0;e<i.length;e++)if(!t.BASE64URL_REGEX.test(i[e]))throw new n.AuthInvalidJwtError(`JWT not in base64url format`);return{header:JSON.parse((0,r.stringFromBase64URL)(i[0])),payload:JSON.parse((0,r.stringFromBase64URL)(i[1])),signature:(0,r.base64UrlToUint8Array)(i[2]),raw:{header:i[0],payload:i[1]}}}async function u(e){return await new Promise(t=>{setTimeout(()=>t(null),e)})}function d(e,t){return new Promise((n,r)=>{(async()=>{for(let i=0;i<1/0;i++)try{let r=await e(i);if(!t(i,null,r)){n(r);return}}catch(e){if(!t(i,e)){r(e);return}}})()})}function f(e){return(`0`+e.toString(16)).substr(-2)}function p(){let e=/* @__PURE__ */ new Uint32Array(56);if(typeof crypto>`u`){let e=``;for(let t=0;t<56;t++)e+=`ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-._~`.charAt(Math.floor(Math.random()*66));return e}return crypto.getRandomValues(e),Array.from(e,f).join(``)}async function m(e){let t=new TextEncoder().encode(e),n=await crypto.subtle.digest(`SHA-256`,t),r=new Uint8Array(n);return Array.from(r).map(e=>String.fromCharCode(e)).join(``)}async function h(e){if(typeof crypto>`u`||crypto.subtle===void 0||typeof TextEncoder>`u`)return console.warn(`WebCrypto API is not supported. Code challenge method will default to use plain instead of sha256.`),e;let t=await m(e);return btoa(t).replace(/\+/g,`-`).replace(/\//g,`_`).replace(/=+$/,``)}let g=/^[a-zA-Z0-9_-]{8,64}$/;function _(e){return typeof e==`string`&&g.test(e)?e:null}function v(){if(typeof crypto<`u`&&typeof crypto.getRandomValues==`function`){let e=/* @__PURE__ */ new Uint8Array(16);return crypto.getRandomValues(e),Array.from(e,f).join(``)}let e=``;for(let t=0;t<32;t++)e+=Math.floor(Math.random()*16).toString(16);return e}e.pkceVerifierSlotKey=(e,t)=>`${e}-flow-${t}-code-verifier`;let y=e=>`${e}-flows-code-verifier`;async function b(t,n){let r=await(0,e.getItemAsync)(t,y(n));return Array.isArray(r)?r.filter(e=>_(e)!==null):[]}async function x(n,r,i,a,o){await(0,e.setItemAsync)(n,(0,e.pkceVerifierSlotKey)(r,i),a);let s=(await b(n,r)).filter(e=>e!==i);for(s.push(i);s.length>t.PKCE_MAX_CONCURRENT_FLOWS;){let t=s.shift();await(0,e.removeItemAsync)(n,(0,e.pkceVerifierSlotKey)(r,t)),o?.(t)}await(0,e.setItemAsync)(n,y(r),s),await(0,e.setItemAsync)(n,`${r}-code-verifier`,a)}async function S(t,n,r){if(r){let i=await(0,e.getItemAsync)(t,(0,e.pkceVerifierSlotKey)(n,r));return{verifier:typeof i==`string`?i:null,flowId:r}}let i=await(0,e.getItemAsync)(t,`${n}-code-verifier`);return{verifier:typeof i==`string`?i:null,flowId:null}}async function C(t,n,r){let i=`${n}-code-verifier`;if(!r){await(0,e.removeItemAsync)(t,i);return}let a=(0,e.pkceVerifierSlotKey)(n,r),o=await(0,e.getItemAsync)(t,a);await(0,e.removeItemAsync)(t,a);let s=await b(t,n),c=s.filter(e=>e!==r);c.length!==s.length&&(c.length>0?await(0,e.setItemAsync)(t,y(n),c):await(0,e.removeItemAsync)(t,y(n))),o!=null&&o===await(0,e.getItemAsync)(t,i)&&await(0,e.removeItemAsync)(t,i)}async function w(t,n){let r=await b(t,n);for(let i of r)await(0,e.removeItemAsync)(t,(0,e.pkceVerifierSlotKey)(n,i));await(0,e.removeItemAsync)(t,y(n)),await(0,e.removeItemAsync)(t,`${n}-code-verifier`)}function T(e,n){let r=e.indexOf(`#`),i=r===-1?e:e.slice(0,r),a=r===-1?``:e.slice(r),o=i.indexOf(`?`);if(o!==-1){let e=i.slice(0,o),n=i.slice(o+1).split(`&`).filter(e=>e!==``&&e!==t.PKCE_FLOW_ID_PARAM&&!e.startsWith(`${t.PKCE_FLOW_ID_PARAM}=`));i=n.length>0?`${e}?${n.join(`&`)}`:e}let s=i.includes(`?`)?`&`:`?`;return`${i}${s}${t.PKCE_FLOW_ID_PARAM}=${encodeURIComponent(n)}${a}`}async function E(e,t,n=!1,r){let i=p(),a=i;n&&(a+=`/recovery`);let o=v();await x(e,t,o,a,r);let s=await h(i);return[s,i===s?`plain`:`s256`,o]}let ee=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function te(e){let n=e.headers.get(t.API_VERSION_HEADER_NAME);if(!n||!n.match(ee))return null;try{return/* @__PURE__ */ new Date(`${n}T00:00:00.0Z`)}catch{return null}}function ne(e){if(!e)throw Error(`Missing exp claim`);if(e<=Math.floor(Date.now()/1e3))throw Error(`JWT has expired`)}function re(e){switch(e){case`RS256`:return{name:`RSASSA-PKCS1-v1_5`,hash:{name:`SHA-256`}};case`ES256`:return{name:`ECDSA`,namedCurve:`P-256`,hash:{name:`SHA-256`}};default:throw Error(`Invalid alg claim`)}}let ie=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function ae(e){if(!ie.test(e))throw Error(`@supabase/auth-js: Expected parameter to be UUID but is not`)}function oe(e){if(!e.recoveryCodes)throw Error("@supabase/auth-js: the MFA recovery codes API is experimental and disabled by default. Enable it by passing `auth: { experimental: { recoveryCodes: true } }` to createClient (or to the GoTrueClient constructor).")}function D(){return new Proxy({},{get:(e,t)=>{if(t===`__isUserNotAvailableProxy`)return!0;if(typeof t==`symbol`){let e=t.toString();if(e===`Symbol(Symbol.toPrimitive)`||e===`Symbol(Symbol.toStringTag)`||e===`Symbol(util.inspect.custom)`)return}throw Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Accessing the "${t}" property of the session object is not supported. Please use getUser() instead.`)},set:(e,t)=>{throw Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Setting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)},deleteProperty:(e,t)=>{throw Error(`@supabase/auth-js: client was created with userStorage option and there was no user stored in the user storage. Deleting the "${t}" property of the session object is not supported. Please use getUser() to fetch a user object you can manipulate.`)}})}function se(e,t){return new Proxy(e,{get:(e,n,r)=>{if(n===`__isInsecureUserWarningProxy`)return!0;if(typeof n==`symbol`){let t=n.toString();if(t===`Symbol(Symbol.toPrimitive)`||t===`Symbol(Symbol.toStringTag)`||t===`Symbol(util.inspect.custom)`||t===`Symbol(nodejs.util.inspect.custom)`)return Reflect.get(e,n,r)}return!t.value&&typeof n==`string`&&(console.warn(`Using the user object as returned from supabase.auth.getSession() or from some supabase.auth.onAuthStateChange() events could be insecure! This value comes directly from the storage medium (usually cookies on the server) and may not be authentic. Use supabase.auth.getUser() instead which authenticates the data by contacting the Supabase Auth server.`),t.value=!0),Reflect.get(e,n,r)}})}function ce(e){return JSON.parse(JSON.stringify(e))}})),Gn=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.handleError=s,e._request=l,e._sessionResponse=d,e._sessionResponsePassword=f,e._userResponse=p,e._ssoResponse=m,e._generateLinkResponse=h,e._noResolveJsonResponse=g;let t=(Qe(),ue(me)),n=Vn(),r=Wn(),i=Hn(),a=e=>{if(typeof e==`object`&&e){let t=e;if(typeof t.msg==`string`)return t.msg;if(typeof t.message==`string`)return t.message;if(typeof t.error_description==`string`)return t.error_description;if(typeof t.error==`string`)return t.error}return JSON.stringify(e)},o=[500,501,502,503,504,520,521,522,523,524,525,526,527,528,529,530];async function s(e){if(!(0,r.looksLikeFetchResponse)(e))throw new i.AuthRetryableFetchError(a(e),0);let t;try{t=await e.json()}catch(t){throw o.includes(e.status)?new i.AuthRetryableFetchError(e.statusText||`HTTP ${e.status}`,e.status):new i.AuthUnknownError(a(t),t)}if(o.includes(e.status))throw new i.AuthRetryableFetchError(a(t),e.status);let s,c=(0,r.parseResponseAPIVersion)(e);if(c&&c.getTime()>=n.API_VERSIONS[`2024-01-01`].timestamp&&typeof t==`object`&&t&&typeof t.code==`string`?s=t.code:typeof t==`object`&&t&&typeof t.error_code==`string`&&(s=t.error_code),!s){if(typeof t==`object`&&t&&typeof t.weak_password==`object`&&t.weak_password&&Array.isArray(t.weak_password.reasons)&&t.weak_password.reasons.length&&t.weak_password.reasons.reduce((e,t)=>e&&typeof t==`string`,!0))throw new i.AuthWeakPasswordError(a(t),e.status,t.weak_password.reasons)}else if(s===`weak_password`)throw new i.AuthWeakPasswordError(a(t),e.status,t.weak_password?.reasons||[]);else if(s===`session_not_found`)throw new i.AuthSessionMissingError;throw new i.AuthApiError(a(t),e.status||500,s)}let c=(e,t,n,r)=>{let i={method:e,headers:t?.headers||{}};return e===`GET`?i:(i.headers=Object.assign({"Content-Type":`application/json;charset=UTF-8`},t?.headers),i.body=JSON.stringify(r),Object.assign(Object.assign({},i),n))};async function l(e,t,r,i){let a=Object.assign({},i?.headers);a[n.API_VERSION_HEADER_NAME]||(a[n.API_VERSION_HEADER_NAME]=n.API_VERSIONS[`2024-01-01`].name),i?.jwt&&(a.Authorization=`Bearer ${i.jwt}`);let o=i?.query??{};i?.redirectTo&&(o.redirect_to=i.redirectTo);let s=await u(e,t,r+(Object.keys(o).length?`?`+new URLSearchParams(o).toString():``),{headers:a,noResolveJson:i?.noResolveJson},{},i?.body);return i?.xform?i?.xform(s):{data:Object.assign({},s),error:null}}async function u(e,t,n,r,o,l){let u=c(t,r,o,l),d;try{d=await e(n,Object.assign({},u))}catch(e){throw new i.AuthRetryableFetchError(a(e),0)}if(d.ok||await s(d),r?.noResolveJson)return d;try{return await d.json()}catch(e){await s(e)}}function d(e){let t=null;_(e)&&(t=Object.assign({},e),e.expires_at||(t.expires_at=(0,r.expiresAt)(e.expires_in)));let n=e.user??(typeof e?.id==`string`?e:null);return{data:{session:t,user:n},error:null}}function f(e){let t=d(e);return!t.error&&e.weak_password&&typeof e.weak_password==`object`&&Array.isArray(e.weak_password.reasons)&&e.weak_password.reasons.length&&e.weak_password.message&&typeof e.weak_password.message==`string`&&e.weak_password.reasons.reduce((e,t)=>e&&typeof t==`string`,!0)&&(t.data.weak_password=e.weak_password),t}function p(e){return{data:{user:e.user??e},error:null}}function m(e){return{data:e,error:null}}function h(e){let{action_link:n,email_otp:r,hashed_token:i,redirect_to:a,verification_type:o}=e,s=t.__rest(e,[`action_link`,`email_otp`,`hashed_token`,`redirect_to`,`verification_type`]);return{data:{properties:{action_link:n,email_otp:r,hashed_token:i,redirect_to:a,verification_type:o},user:Object.assign({},s)},error:null}}function g(e){return e}function _(e){return!!e.access_token&&!!e.refresh_token&&!!e.expires_in}})),Kn=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SIGN_OUT_SCOPES=void 0,e.SIGN_OUT_SCOPES=[`global`,`local`,`others`]})),qn=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=(Qe(),ue(me)),n=Gn(),r=Wn(),i=Kn(),a=Hn();e.default=class{constructor({url:e=``,headers:t={},fetch:n,experimental:i}){this.url=e,this.headers=t,this.fetch=(0,r.resolveFetch)(n),this.experimental=i??{},this.mfa={listFactors:this._listFactors.bind(this),deleteFactor:this._deleteFactor.bind(this)},this.oauth={listClients:this._listOAuthClients.bind(this),createClient:this._createOAuthClient.bind(this),getClient:this._getOAuthClient.bind(this),updateClient:this._updateOAuthClient.bind(this),deleteClient:this._deleteOAuthClient.bind(this),regenerateClientSecret:this._regenerateOAuthClientSecret.bind(this)},this.customProviders={listProviders:this._listCustomProviders.bind(this),createProvider:this._createCustomProvider.bind(this),getProvider:this._getCustomProvider.bind(this),updateProvider:this._updateCustomProvider.bind(this),deleteProvider:this._deleteCustomProvider.bind(this)},this.passkey={listPasskeys:this._adminListPasskeys.bind(this),deletePasskey:this._adminDeletePasskey.bind(this)}}async signOut(e,t=i.SIGN_OUT_SCOPES[0]){if(i.SIGN_OUT_SCOPES.indexOf(t)<0)throw Error(`@supabase/auth-js: Parameter scope must be one of ${i.SIGN_OUT_SCOPES.join(`, `)}`);try{return await(0,n._request)(this.fetch,`POST`,`${this.url}/logout?scope=${t}`,{headers:this.headers,jwt:e,noResolveJson:!0}),{data:null,error:null}}catch(e){if((0,a.isAuthError)(e))return{data:null,error:e};throw e}}async inviteUserByEmail(e,t={}){try{return await(0,n._request)(this.fetch,`POST`,`${this.url}/invite`,{body:{email:e,data:t.data},headers:this.headers,redirectTo:t.redirectTo,xform:n._userResponse})}catch(e){if((0,a.isAuthError)(e))return{data:{user:null},error:e};throw e}}async generateLink(e){try{let{options:r}=e,i=t.__rest(e,[`options`]),a=Object.assign(Object.assign({},i),r);return`newEmail`in i&&(a.new_email=i?.newEmail,delete a.newEmail),await(0,n._request)(this.fetch,`POST`,`${this.url}/admin/generate_link`,{body:a,headers:this.headers,xform:n._generateLinkResponse,redirectTo:r?.redirectTo})}catch(e){if((0,a.isAuthError)(e))return{data:{properties:null,user:null},error:e};throw e}}async createUser(e){try{return await(0,n._request)(this.fetch,`POST`,`${this.url}/admin/users`,{body:e,headers:this.headers,xform:n._userResponse})}catch(e){if((0,a.isAuthError)(e))return{data:{user:null},error:e};throw e}}async listUsers(e){try{let t={nextPage:null,lastPage:0,total:0},r=await(0,n._request)(this.fetch,`GET`,`${this.url}/admin/users`,{headers:this.headers,noResolveJson:!0,query:{page:(e?.page)?.toString()??``,per_page:(e?.perPage)?.toString()??``},xform:n._noResolveJsonResponse});if(r.error)throw r.error;let i=await r.json(),a=r.headers.get(`x-total-count`)??0,o=r.headers.get(`link`)?.split(`,`)??[];return o.length>0&&(o.forEach(e=>{let n=parseInt(e.split(`;`)[0].split(`=`)[1].substring(0,1)),r=JSON.parse(e.split(`;`)[1].split(`=`)[1]);t[`${r}Page`]=n}),t.total=parseInt(a)),{data:Object.assign(Object.assign({},i),t),error:null}}catch(e){if((0,a.isAuthError)(e))return{data:{users:[]},error:e};throw e}}async getUserById(e){(0,r.validateUUID)(e);try{return await(0,n._request)(this.fetch,`GET`,`${this.url}/admin/users/${e}`,{headers:this.headers,xform:n._userResponse})}catch(e){if((0,a.isAuthError)(e))return{data:{user:null},error:e};throw e}}async updateUserById(e,t){(0,r.validateUUID)(e);try{return await(0,n._request)(this.fetch,`PUT`,`${this.url}/admin/users/${e}`,{body:t,headers:this.headers,xform:n._userResponse})}catch(e){if((0,a.isAuthError)(e))return{data:{user:null},error:e};throw e}}async deleteUser(e,t=!1){(0,r.validateUUID)(e);try{return await(0,n._request)(this.fetch,`DELETE`,`${this.url}/admin/users/${e}`,{headers:this.headers,body:{should_soft_delete:t},xform:n._userResponse})}catch(e){if((0,a.isAuthError)(e))return{data:{user:null},error:e};throw e}}async _listFactors(e){(0,r.validateUUID)(e.userId);try{let{data:t,error:r}=await(0,n._request)(this.fetch,`GET`,`${this.url}/admin/users/${e.userId}/factors`,{headers:this.headers,xform:e=>({data:{factors:e},error:null})});return{data:t,error:r}}catch(e){if((0,a.isAuthError)(e))return{data:null,error:e};throw e}}async _deleteFactor(e){(0,r.validateUUID)(e.userId),(0,r.validateUUID)(e.id);try{return{data:await(0,n._request)(this.fetch,`DELETE`,`${this.url}/admin/users/${e.userId}/factors/${e.id}`,{headers:this.headers}),error:null}}catch(e){if((0,a.isAuthError)(e))return{data:null,error:e};throw e}}async _listOAuthClients(e){try{let t={nextPage:null,lastPage:0,total:0},r=await(0,n._request)(this.fetch,`GET`,`${this.url}/admin/oauth/clients`,{headers:this.headers,noResolveJson:!0,query:{page:(e?.page)?.toString()??``,per_page:(e?.perPage)?.toString()??``},xform:n._noResolveJsonResponse});if(r.error)throw r.error;let i=await r.json(),a=r.headers.get(`x-total-count`)??0,o=r.headers.get(`link`)?.split(`,`)??[];return o.length>0&&(o.forEach(e=>{let n=parseInt(e.split(`;`)[0].split(`=`)[1].substring(0,1)),r=JSON.parse(e.split(`;`)[1].split(`=`)[1]);t[`${r}Page`]=n}),t.total=parseInt(a)),{data:Object.assign(Object.assign({},i),t),error:null}}catch(e){if((0,a.isAuthError)(e))return{data:{clients:[]},error:e};throw e}}async _createOAuthClient(e){try{return await(0,n._request)(this.fetch,`POST`,`${this.url}/admin/oauth/clients`,{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if((0,a.isAuthError)(e))return{data:null,error:e};throw e}}async _getOAuthClient(e){try{return await(0,n._request)(this.fetch,`GET`,`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if((0,a.isAuthError)(e))return{data:null,error:e};throw e}}async _updateOAuthClient(e,t){try{return await(0,n._request)(this.fetch,`PUT`,`${this.url}/admin/oauth/clients/${e}`,{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if((0,a.isAuthError)(e))return{data:null,error:e};throw e}}async _deleteOAuthClient(e){try{return await(0,n._request)(this.fetch,`DELETE`,`${this.url}/admin/oauth/clients/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if((0,a.isAuthError)(e))return{data:null,error:e};throw e}}async _regenerateOAuthClientSecret(e){try{return await(0,n._request)(this.fetch,`POST`,`${this.url}/admin/oauth/clients/${e}/regenerate_secret`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if((0,a.isAuthError)(e))return{data:null,error:e};throw e}}async _listCustomProviders(e){try{let t={};return e?.type&&(t.type=e.type),await(0,n._request)(this.fetch,`GET`,`${this.url}/admin/custom-providers`,{headers:this.headers,query:t,xform:e=>({data:{providers:e?.providers??[]},error:null})})}catch(e){if((0,a.isAuthError)(e))return{data:{providers:[]},error:e};throw e}}async _createCustomProvider(e){try{return await(0,n._request)(this.fetch,`POST`,`${this.url}/admin/custom-providers`,{body:e,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if((0,a.isAuthError)(e))return{data:null,error:e};throw e}}async _getCustomProvider(e){try{return await(0,n._request)(this.fetch,`GET`,`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if((0,a.isAuthError)(e))return{data:null,error:e};throw e}}async _updateCustomProvider(e,t){try{return await(0,n._request)(this.fetch,`PUT`,`${this.url}/admin/custom-providers/${e}`,{body:t,headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if((0,a.isAuthError)(e))return{data:null,error:e};throw e}}async _deleteCustomProvider(e){try{return await(0,n._request)(this.fetch,`DELETE`,`${this.url}/admin/custom-providers/${e}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if((0,a.isAuthError)(e))return{data:null,error:e};throw e}}async _adminListPasskeys(e){(0,r.validateUUID)(e.userId);try{return await(0,n._request)(this.fetch,`GET`,`${this.url}/admin/users/${e.userId}/passkeys`,{headers:this.headers,xform:e=>({data:e,error:null})})}catch(e){if((0,a.isAuthError)(e))return{data:null,error:e};throw e}}async _adminDeletePasskey(e){(0,r.validateUUID)(e.userId),(0,r.validateUUID)(e.passkeyId);try{return await(0,n._request)(this.fetch,`DELETE`,`${this.url}/admin/users/${e.userId}/passkeys/${e.passkeyId}`,{headers:this.headers,noResolveJson:!0}),{data:null,error:null}}catch(e){if((0,a.isAuthError)(e))return{data:null,error:e};throw e}}}})),Jn=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.memoryLocalStorageAdapter=t;function t(e={}){return{getItem:t=>e[t]||null,setItem:(t,n)=>{e[t]=n},removeItem:t=>{delete e[t]}}}})),Yn=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ProcessLockAcquireTimeoutError=e.NavigatorLockAcquireTimeoutError=e.LockAcquireTimeoutError=e.internals=void 0,e.navigatorLock=a,e.processLock=s;let t=Wn();e.internals={debug:!!(globalThis&&(0,t.supportsLocalStorage)()&&globalThis.localStorage&&globalThis.localStorage.getItem(`supabase.gotrue-js.locks.debug`)===`true`)};var n=class extends Error{constructor(e){super(e),this.isAcquireTimeout=!0}};e.LockAcquireTimeoutError=n;var r=class extends n{};e.NavigatorLockAcquireTimeoutError=r;var i=class extends n{};e.ProcessLockAcquireTimeoutError=i;async function a(t,n,i){e.internals.debug&&console.log(`@supabase/gotrue-js: navigatorLock: acquire lock`,t,n);let a=new globalThis.AbortController,o;n>0&&(o=setTimeout(()=>{a.abort(),e.internals.debug&&console.log(`@supabase/gotrue-js: navigatorLock acquire timed out`,t)},n)),await Promise.resolve();try{return await globalThis.navigator.locks.request(t,n===0?{mode:`exclusive`,ifAvailable:!0}:{mode:`exclusive`,signal:a.signal},async a=>{if(a){clearTimeout(o),e.internals.debug&&console.log(`@supabase/gotrue-js: navigatorLock: acquired`,t,a.name);try{return await i()}finally{e.internals.debug&&console.log(`@supabase/gotrue-js: navigatorLock: released`,t,a.name)}}else if(n===0)throw e.internals.debug&&console.log(`@supabase/gotrue-js: navigatorLock: not immediately available`,t),new r(`Acquiring an exclusive Navigator LockManager lock "${t}" immediately failed`);else{if(e.internals.debug)try{let e=await globalThis.navigator.locks.query();console.log(`@supabase/gotrue-js: Navigator LockManager state`,JSON.stringify(e,null,` `))}catch(e){console.warn(`@supabase/gotrue-js: Error when querying Navigator LockManager state`,e)}return console.warn(`@supabase/gotrue-js: Navigator LockManager returned a null lock when using #request without ifAvailable set to true, it appears this browser is not following the LockManager spec https://developer.mozilla.org/en-US/docs/Web/API/LockManager/request`),clearTimeout(o),await i()}})}catch(s){if(clearTimeout(o),typeof s==`object`&&s&&`name`in s&&s.name===`AbortError`){if(a.signal.aborted)return e.internals.debug&&console.log(`@supabase/gotrue-js: navigatorLock: acquire timeout, recovering by stealing lock`,t),console.warn(`@supabase/gotrue-js: Lock "${t}" was not released within ${n}ms. This may indicate an orphaned lock from a component unmount (e.g., React Strict Mode). Forcefully acquiring the lock to recover.`),await Promise.resolve().then(()=>globalThis.navigator.locks.request(t,{mode:`exclusive`,steal:!0},async n=>{if(n){e.internals.debug&&console.log(`@supabase/gotrue-js: navigatorLock: recovered (stolen)`,t,n.name);try{return await i()}finally{e.internals.debug&&console.log(`@supabase/gotrue-js: navigatorLock: released (stolen)`,t,n.name)}}else return console.warn(`@supabase/gotrue-js: Navigator LockManager returned null lock even with steal: true`),await i()}));throw e.internals.debug&&console.log(`@supabase/gotrue-js: navigatorLock: lock was stolen by another request`,t),new r(`Lock "${t}" was released because another request stole it`)}throw s}}let o={};async function s(e,t,r){let a=o[e]??Promise.resolve(),s=(async()=>{try{return await a,null}catch{return null}})(),c=(async()=>{let a=null;try{let n=t>=0?new Promise((n,r)=>{a=setTimeout(()=>{console.warn(`@supabase/gotrue-js: Lock "${e}" acquisition timed out after ${t}ms. This may be caused by another operation holding the lock. Consider increasing lockAcquireTimeout or checking for stuck operations.`),r(new i(`Acquiring process lock with name "${e}" timed out`))},t)}):null;await Promise.race([s,n].filter(e=>e)),a!==null&&clearTimeout(a)}catch(e){if(a!==null&&clearTimeout(a),e instanceof n)throw e}return await r()})();return o[e]=(async()=>{try{return await c}catch(e){if(e instanceof n){try{await a}catch{}return null}throw e}})(),await c}})),Xn=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.polyfillGlobalThis=t;function t(){if(typeof globalThis!=`object`)try{Object.defineProperty(Object.prototype,"__magic__",{get:function(){return this},configurable:!0}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__}catch{typeof self<`u`&&(self.globalThis=self)}}})),Zn=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getAddress=t,e.fromHex=n,e.toHex=r,e.createSiweMessage=i;function t(e){if(!/^0x[a-fA-F0-9]{40}$/.test(e))throw Error(`@supabase/auth-js: Address "${e}" is invalid.`);return e.toLowerCase()}function n(e){return parseInt(e,16)}function r(e){let t=new TextEncoder().encode(e);return`0x`+Array.from(t,e=>e.toString(16).padStart(2,`0`)).join(``)}function i(e){let{chainId:n,domain:r,expirationTime:i,issuedAt:a=/* @__PURE__ */ new Date,nonce:o,notBefore:s,requestId:c,resources:l,scheme:u,uri:d,version:f}=e;if(!Number.isInteger(n))throw Error(`@supabase/auth-js: Invalid SIWE message field "chainId". Chain ID must be a EIP-155 chain ID. Provided value: ${n}`);if(!r)throw Error(`@supabase/auth-js: Invalid SIWE message field "domain". Domain must be provided.`);if(o&&o.length<8)throw Error(`@supabase/auth-js: Invalid SIWE message field "nonce". Nonce must be at least 8 characters. Provided value: ${o}`);if(!d)throw Error(`@supabase/auth-js: Invalid SIWE message field "uri". URI must be provided.`);if(f!==`1`)throw Error(`@supabase/auth-js: Invalid SIWE message field "version". Version must be '1'. Provided value: ${f}`);if(e.statement?.includes(`
12
+ `))throw Error(`@supabase/auth-js: Invalid SIWE message field "statement". Statement must not include '\\n'. Provided value: ${e.statement}`);let p=t(e.address),m=`${u?`${u}://${r}`:r} wants you to sign in with your Ethereum account:\n${p}\n\n${e.statement?`${e.statement}\n`:``}`,h=`URI: ${d}\nVersion: ${f}\nChain ID: ${n}${o?`\nNonce: ${o}`:``}\nIssued At: ${a.toISOString()}`;if(i&&(h+=`\nExpiration Time: ${i.toISOString()}`),s&&(h+=`\nNot Before: ${s.toISOString()}`),c&&(h+=`\nRequest ID: ${c}`),l){let e=`
13
+ Resources:`;for(let t of l){if(!t||typeof t!=`string`)throw Error(`@supabase/auth-js: Invalid SIWE message field "resources". Every resource must be a valid string. Provided value: ${t}`);e+=`\n- ${t}`}h+=e}return`${m}\n${h}`}})),Qn=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.WebAuthnUnknownError=e.WebAuthnError=void 0,e.isWebAuthnError=r,e.identifyRegistrationError=i,e.identifyAuthenticationError=a;let t=$n();var n=class extends Error{constructor({message:e,code:t,cause:n,name:r}){super(e,{cause:n}),this.__isWebAuthnError=!0,this.name=r??(n instanceof Error?n.name:void 0)??`Unknown Error`,this.code=t}toJSON(){return{name:this.name,message:this.message,code:this.code}}};e.WebAuthnError=n,e.WebAuthnUnknownError=class extends n{constructor(e,t){super({code:`ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY`,cause:t,message:e}),this.name=`WebAuthnUnknownError`,this.originalError=t}};function r(e){return typeof e==`object`&&!!e&&`__isWebAuthnError`in e}function i({error:e,options:r}){let{publicKey:i}=r;if(!i)throw Error(`options was missing required publicKey property`);if(e.name===`AbortError`){if(r.signal instanceof AbortSignal)return new n({message:`Registration ceremony was sent an abort signal`,code:`ERROR_CEREMONY_ABORTED`,cause:e})}else if(e.name===`ConstraintError`){if(i.authenticatorSelection?.requireResidentKey===!0)return new n({message:`Discoverable credentials were required but no available authenticator supported it`,code:`ERROR_AUTHENTICATOR_MISSING_DISCOVERABLE_CREDENTIAL_SUPPORT`,cause:e});if(r.mediation===`conditional`&&i.authenticatorSelection?.userVerification===`required`)return new n({message:`User verification was required during automatic registration but it could not be performed`,code:`ERROR_AUTO_REGISTER_USER_VERIFICATION_FAILURE`,cause:e});if(i.authenticatorSelection?.userVerification===`required`)return new n({message:`User verification was required but no available authenticator supported it`,code:`ERROR_AUTHENTICATOR_MISSING_USER_VERIFICATION_SUPPORT`,cause:e})}else if(e.name===`InvalidStateError`)return new n({message:`The authenticator was previously registered`,code:`ERROR_AUTHENTICATOR_PREVIOUSLY_REGISTERED`,cause:e});else if(e.name===`NotAllowedError`)return new n({message:e.message,code:`ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY`,cause:e});else if(e.name===`NotSupportedError`)return i.pubKeyCredParams.filter(e=>e.type===`public-key`).length===0?new n({message:`No entry in pubKeyCredParams was of type "public-key"`,code:`ERROR_MALFORMED_PUBKEYCREDPARAMS`,cause:e}):new n({message:`No available authenticator supported any of the specified pubKeyCredParams algorithms`,code:`ERROR_AUTHENTICATOR_NO_SUPPORTED_PUBKEYCREDPARAMS_ALG`,cause:e});else if(e.name===`SecurityError`){let r=window.location.hostname;if(!(0,t.isValidDomain)(r))return new n({message:`${window.location.hostname} is an invalid domain`,code:`ERROR_INVALID_DOMAIN`,cause:e});if(i.rp.id!==r)return new n({message:`The RP ID "${i.rp.id}" is invalid for this domain`,code:`ERROR_INVALID_RP_ID`,cause:e})}else if(e.name===`TypeError`){if(i.user.id.byteLength<1||i.user.id.byteLength>64)return new n({message:`User ID was not between 1 and 64 characters`,code:`ERROR_INVALID_USER_ID_LENGTH`,cause:e})}else if(e.name===`UnknownError`)return new n({message:`The authenticator was unable to process the specified options, or could not create a new credential`,code:`ERROR_AUTHENTICATOR_GENERAL_ERROR`,cause:e});return new n({message:`a Non-Webauthn related error has occurred`,code:`ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY`,cause:e})}function a({error:e,options:r}){let{publicKey:i}=r;if(!i)throw Error(`options was missing required publicKey property`);if(e.name===`AbortError`){if(r.signal instanceof AbortSignal)return new n({message:`Authentication ceremony was sent an abort signal`,code:`ERROR_CEREMONY_ABORTED`,cause:e})}else if(e.name===`NotAllowedError`)return new n({message:e.message,code:`ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY`,cause:e});else if(e.name===`SecurityError`){let r=window.location.hostname;if(!(0,t.isValidDomain)(r))return new n({message:`${window.location.hostname} is an invalid domain`,code:`ERROR_INVALID_DOMAIN`,cause:e});if(i.rpId!==r)return new n({message:`The RP ID "${i.rpId}" is invalid for this domain`,code:`ERROR_INVALID_RP_ID`,cause:e})}else if(e.name===`UnknownError`)return new n({message:`The authenticator was unable to process the specified options, or could not create a new assertion signature`,code:`ERROR_AUTHENTICATOR_GENERAL_ERROR`,cause:e});return new n({message:`a Non-Webauthn related error has occurred`,code:`ERROR_PASSTHROUGH_SEE_CAUSE_PROPERTY`,cause:e})}})),$n=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.WebAuthnApi=e.DEFAULT_REQUEST_OPTIONS=e.DEFAULT_CREATION_OPTIONS=e.webAuthnAbortService=e.WebAuthnAbortService=e.identifyAuthenticationError=e.identifyRegistrationError=e.isWebAuthnError=e.WebAuthnError=void 0,e.deserializeCredentialCreationOptions=s,e.deserializeCredentialRequestOptions=c,e.serializeCredentialCreationResponse=l,e.serializeCredentialRequestResponse=u,e.isValidDomain=d,e.browserSupportsWebAuthn=f,e.createCredential=p,e.getCredential=m,e.mergeCredentialCreationOptions=g,e.mergeCredentialRequestOptions=_;let t=(Qe(),ue(me)),n=Un(),r=Hn(),i=Wn(),a=Qn();Object.defineProperty(e,"identifyAuthenticationError",{enumerable:!0,get:function(){return a.identifyAuthenticationError}}),Object.defineProperty(e,"identifyRegistrationError",{enumerable:!0,get:function(){return a.identifyRegistrationError}}),Object.defineProperty(e,"isWebAuthnError",{enumerable:!0,get:function(){return a.isWebAuthnError}}),Object.defineProperty(e,"WebAuthnError",{enumerable:!0,get:function(){return a.WebAuthnError}});var o=class{createNewAbortSignal(){if(this.controller){let e=/* @__PURE__ */ Error(`Cancelling existing WebAuthn API call for new one`);e.name=`AbortError`,this.controller.abort(e)}let e=new AbortController;return this.controller=e,e.signal}cancelCeremony(){if(this.controller){let e=/* @__PURE__ */ Error(`Manually cancelling existing WebAuthn API call`);e.name=`AbortError`,this.controller.abort(e),this.controller=void 0}}};e.WebAuthnAbortService=o,e.webAuthnAbortService=new o;function s(e){if(!e)throw Error(`Credential creation options are required`);if(typeof PublicKeyCredential<`u`&&`parseCreationOptionsFromJSON`in PublicKeyCredential&&typeof PublicKeyCredential.parseCreationOptionsFromJSON==`function`)return PublicKeyCredential.parseCreationOptionsFromJSON(e);let{challenge:r,user:i,excludeCredentials:a}=e,o=t.__rest(e,[`challenge`,`user`,`excludeCredentials`]),s=(0,n.base64UrlToUint8Array)(r).buffer,c=Object.assign(Object.assign({},i),{id:(0,n.base64UrlToUint8Array)(i.id).buffer}),l=Object.assign(Object.assign({},o),{challenge:s,user:c});if(a&&a.length>0){l.excludeCredentials=Array(a.length);for(let e=0;e<a.length;e++){let t=a[e];l.excludeCredentials[e]=Object.assign(Object.assign({},t),{id:(0,n.base64UrlToUint8Array)(t.id).buffer,type:t.type||`public-key`,transports:t.transports})}}return l}function c(e){if(!e)throw Error(`Credential request options are required`);if(typeof PublicKeyCredential<`u`&&`parseRequestOptionsFromJSON`in PublicKeyCredential&&typeof PublicKeyCredential.parseRequestOptionsFromJSON==`function`)return PublicKeyCredential.parseRequestOptionsFromJSON(e);let{challenge:r,allowCredentials:i}=e,a=t.__rest(e,[`challenge`,`allowCredentials`]),o=(0,n.base64UrlToUint8Array)(r).buffer,s=Object.assign(Object.assign({},a),{challenge:o});if(i&&i.length>0){s.allowCredentials=Array(i.length);for(let e=0;e<i.length;e++){let t=i[e];s.allowCredentials[e]=Object.assign(Object.assign({},t),{id:(0,n.base64UrlToUint8Array)(t.id).buffer,type:t.type||`public-key`,transports:t.transports})}}return s}function l(e){if(`toJSON`in e&&typeof e.toJSON==`function`)return e.toJSON();let t=e;return{id:e.id,rawId:e.id,response:{attestationObject:(0,n.bytesToBase64URL)(new Uint8Array(e.response.attestationObject)),clientDataJSON:(0,n.bytesToBase64URL)(new Uint8Array(e.response.clientDataJSON))},type:`public-key`,clientExtensionResults:e.getClientExtensionResults(),authenticatorAttachment:t.authenticatorAttachment??void 0}}function u(e){if(`toJSON`in e&&typeof e.toJSON==`function`)return e.toJSON();let t=e,r=e.getClientExtensionResults(),i=e.response;return{id:e.id,rawId:e.id,response:{authenticatorData:(0,n.bytesToBase64URL)(new Uint8Array(i.authenticatorData)),clientDataJSON:(0,n.bytesToBase64URL)(new Uint8Array(i.clientDataJSON)),signature:(0,n.bytesToBase64URL)(new Uint8Array(i.signature)),userHandle:i.userHandle?(0,n.bytesToBase64URL)(new Uint8Array(i.userHandle)):void 0},type:`public-key`,clientExtensionResults:r,authenticatorAttachment:t.authenticatorAttachment??void 0}}function d(e){return e===`localhost`||/^([a-z0-9]+(-[a-z0-9]+)*\.)+[a-z]{2,}$/i.test(e)}function f(){return!!((0,i.isBrowser)()&&`PublicKeyCredential`in window&&window.PublicKeyCredential&&`credentials`in navigator&&typeof(navigator==null?void 0:navigator.credentials)?.create==`function`&&typeof(navigator==null?void 0:navigator.credentials)?.get==`function`)}async function p(e){try{let t=await navigator.credentials.create(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new a.WebAuthnUnknownError(`Browser returned unexpected credential type`,t)}:{data:null,error:new a.WebAuthnUnknownError(`Empty credential response`,t)}}catch(t){return{data:null,error:(0,a.identifyRegistrationError)({error:t,options:e})}}}async function m(e){try{let t=await navigator.credentials.get(e);return t?t instanceof PublicKeyCredential?{data:t,error:null}:{data:null,error:new a.WebAuthnUnknownError(`Browser returned unexpected credential type`,t)}:{data:null,error:new a.WebAuthnUnknownError(`Empty credential response`,t)}}catch(t){return{data:null,error:(0,a.identifyAuthenticationError)({error:t,options:e})}}}e.DEFAULT_CREATION_OPTIONS={hints:[`security-key`],authenticatorSelection:{authenticatorAttachment:`cross-platform`,requireResidentKey:!1,userVerification:`preferred`,residentKey:`discouraged`},attestation:`direct`},e.DEFAULT_REQUEST_OPTIONS={userVerification:`preferred`,hints:[`security-key`],attestation:`direct`};function h(...e){let t=e=>typeof e==`object`&&!!e&&!Array.isArray(e),n=e=>e instanceof ArrayBuffer||ArrayBuffer.isView(e),r={};for(let i of e)if(i)for(let e in i){let a=i[e];if(a!==void 0){if(Array.isArray(a))r[e]=a;else if(n(a))r[e]=a;else if(t(a)){let n=r[e];r[e]=t(n)?h(n,a):h(a)}else r[e]=a}}return r}function g(t,n){return h(e.DEFAULT_CREATION_OPTIONS,t,n||{})}function _(t,n){return h(e.DEFAULT_REQUEST_OPTIONS,t,n||{})}e.WebAuthnApi=class{constructor(e){this.client=e,this.enroll=this._enroll.bind(this),this.challenge=this._challenge.bind(this),this.verify=this._verify.bind(this),this.authenticate=this._authenticate.bind(this),this.register=this._register.bind(this)}async _enroll(e){return this.client.mfa.enroll(Object.assign(Object.assign({},e),{factorType:`webauthn`}))}async _challenge({factorId:t,webauthn:n,friendlyName:i,signal:a},o){try{let{data:r,error:s}=await this.client.mfa.challenge({factorId:t,webauthn:n});if(!r)return{data:null,error:s};let c=a??e.webAuthnAbortService.createNewAbortSignal();if(r.webauthn.type===`create`){let{user:e}=r.webauthn.credential_options.publicKey;if(!e.name){let t=i;if(t)e.name=`${e.id}:${t}`;else{let t=(await this.client.getUser()).data.user,n=t?.user_metadata?.name||t?.email||t?.id||`User`;e.name=`${e.id}:${n}`}}e.displayName||=e.name}switch(r.webauthn.type){case`create`:{let{data:e,error:n}=await p({publicKey:g(r.webauthn.credential_options.publicKey,o?.create),signal:c});return e?{data:{factorId:t,challengeId:r.id,webauthn:{type:r.webauthn.type,credential_response:e}},error:null}:{data:null,error:n}}case`request`:{let e=_(r.webauthn.credential_options.publicKey,o?.request),{data:n,error:i}=await m(Object.assign(Object.assign({},r.webauthn.credential_options),{publicKey:e,signal:c}));return n?{data:{factorId:t,challengeId:r.id,webauthn:{type:r.webauthn.type,credential_response:n}},error:null}:{data:null,error:i}}}}catch(e){return(0,r.isAuthError)(e)?{data:null,error:e}:{data:null,error:new r.AuthUnknownError(`Unexpected error in challenge`,e)}}}async _verify({challengeId:e,factorId:t,webauthn:n}){return this.client.mfa.verify({factorId:t,challengeId:e,webauthn:n})}async _authenticate({factorId:e,webauthn:{rpId:t=typeof window<`u`?window.location.hostname:void 0,rpOrigins:n=typeof window<`u`?[window.location.origin]:void 0,signal:i}={}},a){if(!t)return{data:null,error:new r.AuthError(`rpId is required for WebAuthn authentication`)};try{if(!f())return{data:null,error:new r.AuthUnknownError(`Browser does not support WebAuthn`,null)};let{data:o,error:s}=await this.challenge({factorId:e,webauthn:{rpId:t,rpOrigins:n},signal:i},{request:a});if(!o)return{data:null,error:s};let{webauthn:c}=o;return this._verify({factorId:e,challengeId:o.challengeId,webauthn:{type:c.type,rpId:t,rpOrigins:n,credential_response:c.credential_response}})}catch(e){return(0,r.isAuthError)(e)?{data:null,error:e}:{data:null,error:new r.AuthUnknownError(`Unexpected error in authenticate`,e)}}}async _register({friendlyName:e,webauthn:{rpId:t=typeof window<`u`?window.location.hostname:void 0,rpOrigins:n=typeof window<`u`?[window.location.origin]:void 0,signal:i}={}},a){if(!t)return{data:null,error:new r.AuthError(`rpId is required for WebAuthn registration`)};try{if(!f())return{data:null,error:new r.AuthUnknownError(`Browser does not support WebAuthn`,null)};let{data:o,error:s}=await this._enroll({friendlyName:e});if(!o)return await this.client.mfa.listFactors().then(t=>t.data?.all.find(t=>t.factor_type===`webauthn`&&t.friendly_name===e&&t.status===`unverified`)).then(e=>e?this.client.mfa.unenroll({factorId:e?.id}):void 0),{data:null,error:s};let{data:c,error:l}=await this._challenge({factorId:o.id,friendlyName:o.friendly_name,webauthn:{rpId:t,rpOrigins:n},signal:i},{create:a});return c?this._verify({factorId:o.id,challengeId:c.challengeId,webauthn:{rpId:t,rpOrigins:n,type:c.webauthn.type,credential_response:c.webauthn.credential_response}}):{data:null,error:l}}catch(e){return(0,r.isAuthError)(e)?{data:null,error:e}:{data:null,error:new r.AuthUnknownError(`Unexpected error in register`,e)}}}}})),er=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=(Qe(),ue(me)).__importDefault(qn()),n=Vn(),r=Hn(),i=Gn(),a=Wn(),o=Jn(),s=Yn(),c=Xn(),l=Bn(),u=Un(),d=Zn(),f=$n();(0,c.polyfillGlobalThis)();let p={url:n.GOTRUE_URL,storageKey:n.STORAGE_KEY,autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,headers:n.DEFAULT_HEADERS,flowType:`implicit`,debug:!1,hasCustomAuthorizationHeader:!1,throwOnError:!1,lockAcquireTimeout:5e3,skipAutoInitialize:!1,experimental:{}},m={},h=!1;var g=class e{get jwks(){return m[this.storageKey]?.jwks??{keys:[]}}set jwks(e){m[this.storageKey]=Object.assign(Object.assign({},m[this.storageKey]),{jwks:e})}get jwks_cached_at(){return m[this.storageKey]?.cachedAt??-(2**53-1)}set jwks_cached_at(e){m[this.storageKey]=Object.assign(Object.assign({},m[this.storageKey]),{cachedAt:e})}constructor(n){var r;this.userStorage=null,this.memoryStorage=null,this.stateChangeEmitters=/* @__PURE__ */ new Map,this.autoRefreshTicker=null,this.autoRefreshTickTimeout=null,this.visibilityChangedCallback=null,this.refreshingDeferred=null,this.lastRefreshFailure=null,this._sessionRemovalEpoch=0,this.initializePromise=null,this._pendingInitNotifications=null,this.detectSessionInUrl=!0,this.hasCustomAuthorizationHeader=!1,this.suppressGetSessionWarning=!1,this.lock=null,this.lockAcquired=!1,this.pendingInLock=[],this.broadcastChannel=null,this.logger=console.log;let i=Object.assign(Object.assign({},p),n);if(this.storageKey=i.storageKey,this.instanceID=e.nextInstanceID[this.storageKey]??0,e.nextInstanceID[this.storageKey]=this.instanceID+1,this.logDebugMessages=!!i.debug,typeof i.debug==`function`&&(this.logger=i.debug),this.instanceID>0&&(0,a.isBrowser)()){let e=`${this._logPrefix()} Multiple GoTrueClient instances detected in the same browser context. It is not an error, but this should be avoided as it may produce undefined behavior when used concurrently under the same storage key.`;console.warn(e),this.logDebugMessages&&console.trace(e)}if(this.persistSession=i.persistSession,this.autoRefreshToken=i.autoRefreshToken,this.experimental=i.experimental??{},this.admin=new t.default({url:i.url,headers:i.headers,fetch:i.fetch,experimental:this.experimental}),this.url=i.url,this.headers=i.headers,this.fetch=(0,a.resolveFetch)(i.fetch),this.detectSessionInUrl=i.detectSessionInUrl,this.flowType=i.flowType,this.hasCustomAuthorizationHeader=i.hasCustomAuthorizationHeader,this.throwOnError=i.throwOnError,this.lockAcquireTimeout=i.lockAcquireTimeout,i.lock!=null&&(this.lock=i.lock,h||(h=!0,console.warn(`${this._logPrefix()} The "lock" option is deprecated and will be removed in v3. The client now coordinates session refreshes without a lock, so most apps can drop the option. See https://github.com/supabase/supabase-js/blob/master/packages/core/auth-js/migrations/lockless-coordination.md`))),this.jwks||(this.jwks={keys:[]},this.jwks_cached_at=-(2**53-1)),this.mfa={verify:this._verify.bind(this),enroll:this._enroll.bind(this),unenroll:this._unenroll.bind(this),challenge:this._challenge.bind(this),listFactors:this._listFactors.bind(this),challengeAndVerify:this._challengeAndVerify.bind(this),getAuthenticatorAssuranceLevel:this._getAuthenticatorAssuranceLevel.bind(this),webauthn:new f.WebAuthnApi(this),recoveryCodes:{getStatus:this._getRecoveryCodesStatus.bind(this),generate:this._generateRecoveryCodes.bind(this),verify:this._verifyRecoveryCode.bind(this),regenerate:this._regenerateRecoveryCodes.bind(this),unenroll:this._unenrollRecoveryCodes.bind(this)}},this.oauth={getAuthorizationDetails:this._getAuthorizationDetails.bind(this),approveAuthorization:this._approveAuthorization.bind(this),denyAuthorization:this._denyAuthorization.bind(this),listGrants:this._listOAuthGrants.bind(this),revokeGrant:this._revokeOAuthGrant.bind(this)},this.passkey={startRegistration:this._startPasskeyRegistration.bind(this),verifyRegistration:this._verifyPasskeyRegistration.bind(this),startAuthentication:this._startPasskeyAuthentication.bind(this),verifyAuthentication:this._verifyPasskeyAuthentication.bind(this),list:this._listPasskeys.bind(this),update:this._updatePasskey.bind(this),delete:this._deletePasskey.bind(this)},this.persistSession?(i.storage?this.storage=i.storage:(0,a.supportsLocalStorage)()?this.storage=globalThis.localStorage:(this.memoryStorage={},this.storage=(0,o.memoryLocalStorageAdapter)(this.memoryStorage)),i.userStorage&&(this.userStorage=i.userStorage)):(this.memoryStorage={},this.storage=(0,o.memoryLocalStorageAdapter)(this.memoryStorage)),(0,a.isBrowser)()&&globalThis.BroadcastChannel&&this.persistSession&&this.storageKey){try{this.broadcastChannel=new globalThis.BroadcastChannel(this.storageKey)}catch(e){console.error(`Failed to create a new BroadcastChannel, multi-tab state changes will not be available`,e)}(r=this.broadcastChannel)==null||r.addEventListener(`message`,async e=>{this._debug(`received broadcast notification from other tab or client`,e),(e.data.event===`TOKEN_REFRESHED`||e.data.event===`SIGNED_IN`)&&(this.lastRefreshFailure=null);try{await this._notifyAllSubscribers(e.data.event,e.data.session,!1)}catch(e){this._debug(`#broadcastChannel`,`error`,e)}})}i.skipAutoInitialize||this.initialize().catch(e=>{this._debug(`#initialize()`,`error`,e)})}isThrowOnErrorEnabled(){return this.throwOnError}_returnResult(e){if(this.throwOnError&&e&&e.error)throw e.error;return e}_logPrefix(){return`GoTrueClient@${this.storageKey}:${this.instanceID} (${l.version}) ${(/* @__PURE__ */ new Date()).toISOString()}`}_debug(...e){return this.logDebugMessages&&this.logger(this._logPrefix(),...e),this}async initialize(){if(this.initializePromise)return await this.initializePromise;this._pendingInitNotifications=[],this.initializePromise=(async()=>this.lock==null?await this._initialize():await this._acquireLock(this.lockAcquireTimeout,async()=>await this._initialize()))();let e=await this.initializePromise,t=this._pendingInitNotifications??[];this._pendingInitNotifications=null;for(let e of t)await this._notifyAllSubscribers(e.event,e.session,e.broadcast);return e}async _initialize(){try{let e={},t=`none`;if((0,a.isBrowser)()&&(e=(0,a.parseParametersFromURL)(window.location.href),this._isImplicitGrantCallback(e)?t=`implicit`:await this._isPKCECallback(e)&&(t=`pkce`)),(0,a.isBrowser)()&&this.detectSessionInUrl&&t!==`none`){let{data:n,error:i}=await this._getSessionFromURL(e,t);if(i){if(this._debug(`#_initialize()`,`error detecting session from URL`,i),(0,r.isAuthImplicitGrantRedirectError)(i)){let e=i.details?.code;if(e===`identity_already_exists`||e===`identity_not_found`||e===`single_identity_not_deletable`)return{error:i}}return{error:i}}let{session:a,redirectType:o}=n;return this._debug(`#_initialize()`,`detected session in URL`,a,`redirect type`,o),await this._saveSession(a),setTimeout(async()=>{o===`recovery`?await this._notifyAllSubscribers(`PASSWORD_RECOVERY`,a):await this._notifyAllSubscribers(`SIGNED_IN`,a)},0),{error:null}}return await this._recoverAndRefresh(),{error:null}}catch(e){return(0,r.isAuthError)(e)?this._returnResult({error:e}):this._returnResult({error:new r.AuthUnknownError(`Unexpected error during initialization`,e)})}finally{await this._handleVisibilityChange(),this._debug(`#_initialize()`,`end`)}}async signInAnonymously(e){try{let{data:t,error:n}=await(0,i._request)(this.fetch,`POST`,`${this.url}/signup`,{headers:this.headers,body:{data:e?.options?.data??{},gotrue_meta_security:{captcha_token:e?.options?.captchaToken}},xform:i._sessionResponse});if(n||!t)return this._returnResult({data:{user:null,session:null},error:n});let r=t.session,a=t.user;return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers(`SIGNED_IN`,r)),this._returnResult({data:{user:a,session:r},error:null})}catch(e){if((0,r.isAuthError)(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signUp(e){let t=null;try{let n;if(`email`in e){let{email:r,password:a,options:o}=e,s=null,c=null;this.flowType===`pkce`&&([s,c,t]=await this._getCodeChallengeAndMethod()),n=await(0,i._request)(this.fetch,`POST`,`${this.url}/signup`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(o?.emailRedirectTo,t),body:{email:r,password:a,data:o?.data??{},gotrue_meta_security:{captcha_token:o?.captchaToken},code_challenge:s,code_challenge_method:c},xform:i._sessionResponse})}else if(`phone`in e){let{phone:t,password:r,options:a}=e;n=await(0,i._request)(this.fetch,`POST`,`${this.url}/signup`,{headers:this.headers,body:{phone:t,password:r,data:a?.data??{},channel:a?.channel??`sms`,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:i._sessionResponse})}else throw new r.AuthInvalidCredentialsError(`You must provide either an email or phone number and a password`);let{data:o,error:s}=n;if(s||!o)return await(0,a.removePKCEVerifier)(this.storage,this.storageKey,t),this._returnResult({data:{user:null,session:null},error:s});let c=o.session,l=o.user;return o.session&&(await this._saveSession(o.session),await this._notifyAllSubscribers(`SIGNED_IN`,c)),this._returnResult({data:{user:l,session:c},error:null})}catch(e){if(await(0,a.removePKCEVerifier)(this.storage,this.storageKey,t),(0,r.isAuthError)(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithPassword(e){try{let t;if(`email`in e){let{email:n,password:r,options:a}=e;t=await(0,i._request)(this.fetch,`POST`,`${this.url}/token?grant_type=password`,{headers:this.headers,body:{email:n,password:r,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:i._sessionResponsePassword})}else if(`phone`in e){let{phone:n,password:r,options:a}=e;t=await(0,i._request)(this.fetch,`POST`,`${this.url}/token?grant_type=password`,{headers:this.headers,body:{phone:n,password:r,gotrue_meta_security:{captcha_token:a?.captchaToken}},xform:i._sessionResponsePassword})}else throw new r.AuthInvalidCredentialsError(`You must provide either an email or phone number and a password`);let{data:n,error:a}=t;if(a)return this._returnResult({data:{user:null,session:null},error:a});if(!n||!n.session||!n.user){let e=new r.AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:e})}return n.session&&(await this._saveSession(n.session),await this._notifyAllSubscribers(`SIGNED_IN`,n.session)),this._returnResult({data:Object.assign({user:n.user,session:n.session},n.weak_password?{weakPassword:n.weak_password}:null),error:a})}catch(e){if((0,r.isAuthError)(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOAuth(e){return await this._handleProviderSignIn(e.provider,{redirectTo:e.options?.redirectTo,scopes:e.options?.scopes,queryParams:e.options?.queryParams,skipBrowserRedirect:e.options?.skipBrowserRedirect})}async exchangeCodeForSession(e,t){return await this.initializePromise,this.lock==null?this._exchangeCodeForSession(e,t):this._acquireLock(this.lockAcquireTimeout,async()=>this._exchangeCodeForSession(e,t))}async signInWithWeb3(e){let{chain:t}=e;switch(t){case`ethereum`:return await this.signInWithEthereum(e);case`solana`:return await this.signInWithSolana(e);default:throw Error(`@supabase/auth-js: Unsupported chain "${t}"`)}}async signInWithEthereum(e){let t,n;if(`message`in e)t=e.message,n=e.signature;else{let{chain:r,wallet:i,statement:o,options:s}=e,c;if(!(0,a.isBrowser)()){if(typeof i!=`object`||!s?.url)throw Error(`@supabase/auth-js: Both wallet and url must be specified in non-browser environments.`);c=i}else if(typeof i==`object`)c=i;else{let e=window;if(`ethereum`in e&&typeof e.ethereum==`object`&&`request`in e.ethereum&&typeof e.ethereum.request==`function`)c=e.ethereum;else throw Error(`@supabase/auth-js: No compatible Ethereum wallet interface on the window object (window.ethereum) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'ethereum', wallet: resolvedUserWallet }) instead.`)}let l=new URL(s?.url??window.location.href),u=await c.request({method:`eth_requestAccounts`}).then(e=>e).catch(()=>{throw Error(`@supabase/auth-js: Wallet method eth_requestAccounts is missing or invalid`)});if(!u||u.length===0)throw Error(`@supabase/auth-js: No accounts available. Please ensure the wallet is connected.`);let f=(0,d.getAddress)(u[0]),p=s?.signInWithEthereum?.chainId;if(!p){let e=await c.request({method:`eth_chainId`});p=(0,d.fromHex)(e)}let m={domain:l.host,address:f,statement:o,uri:l.href,version:`1`,chainId:p,nonce:s?.signInWithEthereum?.nonce,issuedAt:s?.signInWithEthereum?.issuedAt??/* @__PURE__ */ new Date,expirationTime:s?.signInWithEthereum?.expirationTime,notBefore:s?.signInWithEthereum?.notBefore,requestId:s?.signInWithEthereum?.requestId,resources:s?.signInWithEthereum?.resources};t=(0,d.createSiweMessage)(m),n=await c.request({method:`personal_sign`,params:[(0,d.toHex)(t),f]})}try{let{data:a,error:o}=await(0,i._request)(this.fetch,`POST`,`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:`ethereum`,message:t,signature:n},e.options?.captchaToken?{gotrue_meta_security:{captcha_token:e.options?.captchaToken}}:null),xform:i._sessionResponse});if(o)throw o;if(!a||!a.session||!a.user){let e=new r.AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:e})}return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers(`SIGNED_IN`,a.session)),this._returnResult({data:Object.assign({},a),error:o})}catch(e){if((0,r.isAuthError)(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSolana(e){let t,n;if(`message`in e)t=e.message,n=e.signature;else{let{chain:r,wallet:i,statement:o,options:s}=e,c;if(!(0,a.isBrowser)()){if(typeof i!=`object`||!s?.url)throw Error(`@supabase/auth-js: Both wallet and url must be specified in non-browser environments.`);c=i}else if(typeof i==`object`)c=i;else{let e=window;if(`solana`in e&&typeof e.solana==`object`&&(`signIn`in e.solana&&typeof e.solana.signIn==`function`||`signMessage`in e.solana&&typeof e.solana.signMessage==`function`))c=e.solana;else throw Error(`@supabase/auth-js: No compatible Solana wallet interface on the window object (window.solana) detected. Make sure the user already has a wallet installed and connected for this app. Prefer passing the wallet interface object directly to signInWithWeb3({ chain: 'solana', wallet: resolvedUserWallet }) instead.`)}let l=new URL(s?.url??window.location.href);if(`signIn`in c&&c.signIn){let e=await c.signIn(Object.assign(Object.assign(Object.assign({issuedAt:(/* @__PURE__ */ new Date()).toISOString()},s?.signInWithSolana),{version:`1`,domain:l.host,uri:l.href}),o?{statement:o}:null)),r;if(Array.isArray(e)&&e[0]&&typeof e[0]==`object`)r=e[0];else if(e&&typeof e==`object`&&`signedMessage`in e&&`signature`in e)r=e;else throw Error(`@supabase/auth-js: Wallet method signIn() returned unrecognized value`);if(`signedMessage`in r&&`signature`in r&&(typeof r.signedMessage==`string`||r.signedMessage instanceof Uint8Array)&&r.signature instanceof Uint8Array)t=typeof r.signedMessage==`string`?r.signedMessage:new TextDecoder().decode(r.signedMessage),n=r.signature;else throw Error(`@supabase/auth-js: Wallet method signIn() API returned object without signedMessage and signature fields`)}else{if(!(`signMessage`in c)||typeof c.signMessage!=`function`||!(`publicKey`in c)||typeof c!=`object`||!c.publicKey||!(`toBase58`in c.publicKey)||typeof c.publicKey.toBase58!=`function`)throw Error(`@supabase/auth-js: Wallet does not have a compatible signMessage() and publicKey.toBase58() API`);t=[`${l.host} wants you to sign in with your Solana account:`,c.publicKey.toBase58(),...o?[``,o,``]:[``],`Version: 1`,`URI: ${l.href}`,`Issued At: ${s?.signInWithSolana?.issuedAt??(/* @__PURE__ */ new Date()).toISOString()}`,...s?.signInWithSolana?.notBefore?[`Not Before: ${s.signInWithSolana.notBefore}`]:[],...s?.signInWithSolana?.expirationTime?[`Expiration Time: ${s.signInWithSolana.expirationTime}`]:[],...s?.signInWithSolana?.chainId?[`Chain ID: ${s.signInWithSolana.chainId}`]:[],...s?.signInWithSolana?.nonce?[`Nonce: ${s.signInWithSolana.nonce}`]:[],...s?.signInWithSolana?.requestId?[`Request ID: ${s.signInWithSolana.requestId}`]:[],...s?.signInWithSolana?.resources?.length?[`Resources`,...s.signInWithSolana.resources.map(e=>`- ${e}`)]:[]].join(`
14
+ `);let e=await c.signMessage(new TextEncoder().encode(t),`utf8`);if(!e||!(e instanceof Uint8Array))throw Error(`@supabase/auth-js: Wallet signMessage() API returned an recognized value`);n=e}}try{let{data:a,error:o}=await(0,i._request)(this.fetch,`POST`,`${this.url}/token?grant_type=web3`,{headers:this.headers,body:Object.assign({chain:`solana`,message:t,signature:(0,u.bytesToBase64URL)(n)},e.options?.captchaToken?{gotrue_meta_security:{captcha_token:e.options?.captchaToken}}:null),xform:i._sessionResponse});if(o)throw o;if(!a||!a.session||!a.user){let e=new r.AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:e})}return a.session&&(await this._saveSession(a.session),await this._notifyAllSubscribers(`SIGNED_IN`,a.session)),this._returnResult({data:Object.assign({},a),error:o})}catch(e){if((0,r.isAuthError)(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _exchangeCodeForSession(e,t){let o=t?.flowId!=null,s=o?(0,a.validatePKCEFlowId)(t?.flowId):(0,a.isBrowser)()?(0,a.validatePKCEFlowId)((0,a.parseParametersFromURL)(window.location.href)[n.PKCE_FLOW_ID_PARAM]):null;o&&!s&&this._debug(`#_exchangeCodeForSession()`,`provided flowId is not a valid flow id`,t?.flowId);let{verifier:c,flowId:l}=o&&!s?{verifier:null,flowId:null}:await(0,a.retrievePKCEVerifier)(this.storage,this.storageKey,s),[u,d]=(c??``).split(`/`);try{if(!u&&this.flowType===`pkce`)throw new r.AuthPKCECodeVerifierMissingError;let{data:t,error:n}=await(0,i._request)(this.fetch,`POST`,`${this.url}/token?grant_type=pkce`,{headers:this.headers,body:{auth_code:e,code_verifier:u},xform:i._sessionResponse});if(await(0,a.removePKCEVerifier)(this.storage,this.storageKey,l),n)throw n;if(!t||!t.session||!t.user){let e=new r.AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null,redirectType:null},error:e})}return t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers(d===`recovery`?`PASSWORD_RECOVERY`:`SIGNED_IN`,t.session)),this._returnResult({data:Object.assign(Object.assign({},t),{redirectType:d??null}),error:n})}catch(e){if(await(0,a.removePKCEVerifier)(this.storage,this.storageKey,l),(0,r.isAuthError)(e))return this._returnResult({data:{user:null,session:null,redirectType:null},error:e});throw e}}async signInWithIdToken(e){try{let{options:t,provider:n,token:a,access_token:o,nonce:s}=e,{data:c,error:l}=await(0,i._request)(this.fetch,`POST`,`${this.url}/token?grant_type=id_token`,{headers:this.headers,body:{provider:n,id_token:a,access_token:o,nonce:s,gotrue_meta_security:{captcha_token:t?.captchaToken}},xform:i._sessionResponse});if(l)return this._returnResult({data:{user:null,session:null},error:l});if(!c||!c.session||!c.user){let e=new r.AuthInvalidTokenResponseError;return this._returnResult({data:{user:null,session:null},error:e})}return c.session&&(await this._saveSession(c.session),await this._notifyAllSubscribers(`SIGNED_IN`,c.session)),this._returnResult({data:c,error:l})}catch(e){if((0,r.isAuthError)(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithOtp(e){let t=null;try{if(`email`in e){let{email:n,options:r}=e,a=null,o=null;this.flowType===`pkce`&&([a,o,t]=await this._getCodeChallengeAndMethod());let{error:s}=await(0,i._request)(this.fetch,`POST`,`${this.url}/otp`,{headers:this.headers,body:{email:n,data:r?.data??{},create_user:r?.shouldCreateUser??!0,gotrue_meta_security:{captcha_token:r?.captchaToken},code_challenge:a,code_challenge_method:o},redirectTo:this._maybeAppendFlowIdToRedirect(r?.emailRedirectTo,t)});return this._returnResult({data:{user:null,session:null},error:s})}if(`phone`in e){let{phone:t,options:n}=e,{data:r,error:a}=await(0,i._request)(this.fetch,`POST`,`${this.url}/otp`,{headers:this.headers,body:{phone:t,data:n?.data??{},create_user:n?.shouldCreateUser??!0,gotrue_meta_security:{captcha_token:n?.captchaToken},channel:n?.channel??`sms`}});return this._returnResult({data:{user:null,session:null,messageId:r?.message_id},error:a})}throw new r.AuthInvalidCredentialsError(`You must provide either an email or phone number.`)}catch(e){if(await(0,a.removePKCEVerifier)(this.storage,this.storageKey,t),(0,r.isAuthError)(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async verifyOtp(e){try{let t,n;`options`in e&&(t=e.options?.redirectTo,n=e.options?.captchaToken);let{data:r,error:a}=await(0,i._request)(this.fetch,`POST`,`${this.url}/verify`,{headers:this.headers,body:Object.assign(Object.assign({},e),{gotrue_meta_security:{captcha_token:n}}),redirectTo:t,xform:i._sessionResponse});if(a)throw a;if(!r)throw/* @__PURE__ */ Error(`An error occurred on token verification.`);let o=r.session,s=r.user;return o?.access_token&&(await this._saveSession(o),await this._notifyAllSubscribers(e.type==`recovery`?`PASSWORD_RECOVERY`:`SIGNED_IN`,o)),this._returnResult({data:{user:s,session:o},error:null})}catch(e){if((0,r.isAuthError)(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async signInWithSSO(e){let t=null;try{let n=null,r=null;this.flowType===`pkce`&&([n,r,t]=await this._getCodeChallengeAndMethod());let o=await(0,i._request)(this.fetch,`POST`,`${this.url}/sso`,{body:Object.assign(Object.assign(Object.assign(Object.assign(Object.assign({},`providerId`in e?{provider_id:e.providerId}:null),`domain`in e?{domain:e.domain}:null),{redirect_to:this._maybeAppendFlowIdToRedirect(e.options?.redirectTo,t)}),e?.options?.captchaToken?{gotrue_meta_security:{captcha_token:e.options.captchaToken}}:null),{skip_http_redirect:!0,code_challenge:n,code_challenge_method:r}),headers:this.headers,xform:i._ssoResponse});return o.data?.url&&(0,a.isBrowser)()&&!e.options?.skipBrowserRedirect&&window.location.assign(o.data.url),this._returnResult(o)}catch(e){if(await(0,a.removePKCEVerifier)(this.storage,this.storageKey,t),(0,r.isAuthError)(e))return this._returnResult({data:null,error:e});throw e}}async reauthenticate(){return await this.initializePromise,this.lock==null?await this._reauthenticate():await this._acquireLock(this.lockAcquireTimeout,async()=>await this._reauthenticate())}async _reauthenticate(){try{return await this._useSession(async e=>{let{data:{session:t},error:n}=e;if(n)throw n;if(!t)throw new r.AuthSessionMissingError;let{error:a}=await(0,i._request)(this.fetch,`GET`,`${this.url}/reauthenticate`,{headers:this.headers,jwt:t.access_token});return this._returnResult({data:{user:null,session:null},error:a})})}catch(e){if((0,r.isAuthError)(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async resend(e){let t=null;try{let n=`${this.url}/resend`;if(`email`in e){let{email:r,type:o,options:s}=e,c=null,l=null;this.flowType===`pkce`&&([c,l,t]=await this._getCodeChallengeAndMethod());let{error:u}=await(0,i._request)(this.fetch,`POST`,n,{headers:this.headers,body:{email:r,type:o,gotrue_meta_security:{captcha_token:s?.captchaToken},code_challenge:c,code_challenge_method:l},redirectTo:this._maybeAppendFlowIdToRedirect(s?.emailRedirectTo,t)});return u&&await(0,a.removePKCEVerifier)(this.storage,this.storageKey,t),this._returnResult({data:{user:null,session:null},error:u})}if(`phone`in e){let{phone:t,type:r,options:a}=e,{data:o,error:s}=await(0,i._request)(this.fetch,`POST`,n,{headers:this.headers,body:{phone:t,type:r,gotrue_meta_security:{captcha_token:a?.captchaToken}}});return this._returnResult({data:{user:null,session:null,messageId:o?.message_id},error:s})}throw new r.AuthInvalidCredentialsError(`You must provide either an email or phone number and a type`)}catch(e){if(await(0,a.removePKCEVerifier)(this.storage,this.storageKey,t),(0,r.isAuthError)(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async getSession(){return await this.initializePromise,this.lock==null?await this._useSession(async e=>e):await this._acquireLock(this.lockAcquireTimeout,async()=>this._useSession(async e=>e))}async _acquireLock(e,t){this._debug(`#_acquireLock`,`begin`,e);try{if(this.lockAcquired){let e=this.pendingInLock.length?this.pendingInLock[this.pendingInLock.length-1]:Promise.resolve(),n=(async()=>(await e,await t()))();return this.pendingInLock.push((async()=>{try{await n}catch{}})()),n}return await this.lock(`lock:${this.storageKey}`,e,async()=>{this._debug(`#_acquireLock`,`lock acquired for storage key`,this.storageKey);try{this.lockAcquired=!0;let e=t();for(this.pendingInLock.push((async()=>{try{await e}catch{}})()),await e;this.pendingInLock.length;){let e=[...this.pendingInLock];await Promise.all(e),this.pendingInLock.splice(0,e.length)}return await e}finally{this._debug(`#_acquireLock`,`lock released for storage key`,this.storageKey),this.lockAcquired=!1}})}finally{this._debug(`#_acquireLock`,`end`)}}async _useSession(e){this._debug(`#_useSession`,`begin`);try{return await e(await this.__loadSession())}finally{this._debug(`#_useSession`,`end`)}}async __loadSession(){this._debug(`#__loadSession()`,`begin`),this.lock!=null&&!this.lockAcquired&&this._debug(`#__loadSession()`,`used outside of an acquired lock!`,(/* @__PURE__ */ Error()).stack);try{let e=null,t=await(0,a.getItemAsync)(this.storage,this.storageKey);if(this._debug(`#getSession()`,`session from storage`,t),t!==null&&(this._isValidSession(t)?e=t:(this._debug(`#getSession()`,`session from storage is not valid`),await this._removeSession())),!e)return{data:{session:null},error:null};let r=e.expires_at?e.expires_at*1e3-Date.now()<n.EXPIRY_MARGIN_MS:!1;if(this._debug(`#__loadSession()`,`session has${r?``:` not`} expired`,`expires_at`,e.expires_at),!r)return{data:{session:await this._hydrateSessionUser(e)},error:null};let{data:i,error:o}=await this._callRefreshToken(e.refresh_token);if(o){let e=await(0,a.getItemAsync)(this.storage,this.storageKey);return e&&this._isValidSession(e)&&e.expires_at&&e.expires_at*1e3>Date.now()?this._returnResult({data:{session:await this._hydrateSessionUser(e)},error:null}):this._returnResult({data:{session:null},error:o})}return this._returnResult({data:{session:i},error:null})}finally{this._debug(`#__loadSession()`,`end`)}}async _hydrateSessionUser(e){if(this.userStorage){let t=await(0,a.getItemAsync)(this.userStorage,this.storageKey+`-user`);e.user=t?.user?t.user:(0,a.userNotAvailableProxy)()}if(this.storage.isServer&&e.user&&!e.user.__isUserNotAvailableProxy){let t={value:this.suppressGetSessionWarning};e.user=(0,a.insecureUserWarningProxy)(e.user,t),t.value&&(this.suppressGetSessionWarning=!0)}return e}async getUser(e){if(e)return await this._getUser(e);await this.initializePromise;let t;return t=this.lock==null?await this._getUser():await this._acquireLock(this.lockAcquireTimeout,async()=>await this._getUser()),t.data.user&&(this.suppressGetSessionWarning=!0),t}async _getUser(e){try{return e?await(0,i._request)(this.fetch,`GET`,`${this.url}/user`,{headers:this.headers,jwt:e,xform:i._userResponse}):await this._useSession(async e=>{let{data:t,error:n}=e;if(n)throw n;return!t.session?.access_token&&!this.hasCustomAuthorizationHeader?{data:{user:null},error:new r.AuthSessionMissingError}:await(0,i._request)(this.fetch,`GET`,`${this.url}/user`,{headers:this.headers,jwt:t.session?.access_token??void 0,xform:i._userResponse})})}catch(e){if((0,r.isAuthError)(e))return(0,r.isAuthSessionMissingError)(e)&&await this._removeSession(),this._returnResult({data:{user:null},error:e});throw e}}async updateUser(e,t={}){return await this.initializePromise,this.lock==null?await this._updateUser(e,t):await this._acquireLock(this.lockAcquireTimeout,async()=>await this._updateUser(e,t))}async _updateUser(e,t={}){let n=null;try{return await this._useSession(async a=>{let{data:o,error:s}=a;if(s)throw s;if(!o.session)throw new r.AuthSessionMissingError;let c=o.session,l=null,u=null;this.flowType===`pkce`&&e.email!=null&&([l,u,n]=await this._getCodeChallengeAndMethod());let{data:d,error:f}=await(0,i._request)(this.fetch,`PUT`,`${this.url}/user`,{headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(t?.emailRedirectTo,n),body:Object.assign(Object.assign({},e),{code_challenge:l,code_challenge_method:u}),jwt:c.access_token,xform:i._userResponse});if(f)throw f;return c.user=d.user,await this._saveSession(c),await this._notifyAllSubscribers(`USER_UPDATED`,c),this._returnResult({data:{user:c.user},error:null})})}catch(e){if(await(0,a.removePKCEVerifier)(this.storage,this.storageKey,n),(0,r.isAuthError)(e))return this._returnResult({data:{user:null},error:e});throw e}}async setSession(e){return await this.initializePromise,this.lock==null?await this._setSession(e):await this._acquireLock(this.lockAcquireTimeout,async()=>await this._setSession(e))}async _setSession(e){try{if(!e.access_token||!e.refresh_token)throw new r.AuthSessionMissingError;let t=Date.now()/1e3,n=t,i=!0,o=null,{payload:s}=(0,a.decodeJWT)(e.access_token);if(s.exp&&(n=s.exp,i=n<=t),i){let{data:t,error:n}=await this._callRefreshToken(e.refresh_token);if(n)return this._returnResult({data:{user:null,session:null},error:n});if(!t)return{data:{user:null,session:null},error:null};o=t}else{let{data:r,error:i}=await this._getUser(e.access_token);if(i)return this._returnResult({data:{user:null,session:null},error:i});o={access_token:e.access_token,refresh_token:e.refresh_token,user:r.user,token_type:`bearer`,expires_in:n-t,expires_at:n},await this._saveSession(o),await this._notifyAllSubscribers(`SIGNED_IN`,o)}return this._returnResult({data:{user:o.user,session:o},error:null})}catch(e){if((0,r.isAuthError)(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}}async refreshSession(e){return await this.initializePromise,this.lock==null?await this._refreshSession(e):await this._acquireLock(this.lockAcquireTimeout,async()=>await this._refreshSession(e))}async _refreshSession(e){try{return await this._useSession(async t=>{if(!e){let{data:n,error:r}=t;if(r)throw r;e=n.session??void 0}if(!e?.refresh_token)throw new r.AuthSessionMissingError;let{data:n,error:i}=await this._callRefreshToken(e.refresh_token);return i?this._returnResult({data:{user:null,session:null},error:i}):n?this._returnResult({data:{user:n.user,session:n},error:null}):this._returnResult({data:{user:null,session:null},error:null})})}catch(e){if((0,r.isAuthError)(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}}async _getSessionFromURL(e,t){try{if(!(0,a.isBrowser)())throw new r.AuthImplicitGrantRedirectError(`No browser detected.`);if(e.error||e.error_description||e.error_code)throw new r.AuthImplicitGrantRedirectError(e.error_description||`Error in URL with unspecified error_description`,{error:e.error||`unspecified_error`,code:e.error_code||`unspecified_code`});switch(t){case`implicit`:if(this.flowType===`pkce`)throw new r.AuthPKCEGrantCodeExchangeError(`Not a valid PKCE flow url.`);break;case`pkce`:if(this.flowType===`implicit`)throw new r.AuthImplicitGrantRedirectError(`Not a valid implicit grant flow url.`)}if(t===`pkce`){if(this._debug(`#_initialize()`,`begin`,`is PKCE flow`,!0),!e.code)throw new r.AuthPKCEGrantCodeExchangeError(`No code detected.`);let{data:t,error:i}=await this._exchangeCodeForSession(e.code,{flowId:e[n.PKCE_FLOW_ID_PARAM]});if(i)throw i;let a=new URL(window.location.href);return a.searchParams.delete(`code`),a.searchParams.delete(n.PKCE_FLOW_ID_PARAM),window.history.replaceState(window.history.state,``,a.toString()),{data:{session:t.session,redirectType:t.redirectType??null},error:null}}let{provider_token:i,provider_refresh_token:o,access_token:s,refresh_token:c,expires_in:l,expires_at:u,token_type:d}=e;if(!s||!l||!c||!d)throw new r.AuthImplicitGrantRedirectError(`No session defined in URL`);let f=Math.round(Date.now()/1e3),p=parseInt(l),m=f+p;u&&(m=parseInt(u));let h=m-f;h*1e3<=n.AUTO_REFRESH_TICK_DURATION_MS&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL expires in ${h}s, should have been closer to ${p}s`);let g=m-p;f-g>=120?console.warn(`@supabase/gotrue-js: Session as retrieved from URL was issued over 120s ago, URL could be stale`,g,m,f):f-g<0&&console.warn(`@supabase/gotrue-js: Session as retrieved from URL was issued in the future? Check the device clock for skew`,g,m,f);let{data:_,error:v}=await this._getUser(s);if(v)throw v;let y={provider_token:i,provider_refresh_token:o,access_token:s,expires_in:p,expires_at:m,refresh_token:c,token_type:d,user:_.user};return window.location.hash=``,this._debug(`#_getSessionFromURL()`,`clearing window.location.hash`),this._returnResult({data:{session:y,redirectType:e.type},error:null})}catch(e){if((0,r.isAuthError)(e))return this._returnResult({data:{session:null,redirectType:null},error:e});throw e}}_isImplicitGrantCallback(e){return typeof this.detectSessionInUrl==`function`?this.detectSessionInUrl(new URL(window.location.href),e):!!(e.access_token||e.error||e.error_description||e.error_code)}async _isPKCECallback(e){if(!e.code)return!1;let t=(0,a.validatePKCEFlowId)(e[n.PKCE_FLOW_ID_PARAM]);return t&&await(0,a.getItemAsync)(this.storage,(0,a.pkceVerifierSlotKey)(this.storageKey,t))?!0:!!await(0,a.getItemAsync)(this.storage,`${this.storageKey}-code-verifier`)}async signOut(e={scope:`global`}){return await this.initializePromise,this.lock==null?await this._signOut(e):await this._acquireLock(this.lockAcquireTimeout,async()=>await this._signOut(e))}async _signOut({scope:e}={scope:`global`}){return await this._useSession(async t=>{let n=async()=>{await this._removeSession()},{data:i,error:a}=t;if(a&&!(0,r.isAuthSessionMissingError)(a))return this._returnResult({error:a});let o=i.session?.access_token;if(o){let{error:t}=await this.admin.signOut(o,e);if(t&&!((0,r.isAuthApiError)(t)&&(t.status===404||t.status===401||t.status===403)||(0,r.isAuthSessionMissingError)(t)))return e!==`others`&&await n(),this._returnResult({error:t})}return e!==`others`&&await n(),this._returnResult({error:null})})}onAuthStateChange(e){let t=(0,a.generateCallbackId)(),n={id:t,callback:e,unsubscribe:()=>{this._debug(`#unsubscribe()`,`state change callback with id removed`,t),this.stateChangeEmitters.delete(t)}};return this._debug(`#onAuthStateChange()`,`registered callback with id`,t),this.stateChangeEmitters.set(t,n),(async()=>{await this.initializePromise,this.lock==null?await this._emitInitialSession(t):await this._acquireLock(this.lockAcquireTimeout,async()=>{this._emitInitialSession(t)})})(),{data:{subscription:n}}}async _emitInitialSession(e){return await this._useSession(async t=>{try{let{data:{session:n},error:r}=t;if(r)throw r;await this.stateChangeEmitters.get(e)?.callback(`INITIAL_SESSION`,n),this._debug(`INITIAL_SESSION`,`callback id`,e,`session`,n)}catch(t){if(await this.stateChangeEmitters.get(e)?.callback(`INITIAL_SESSION`,null),this._debug(`INITIAL_SESSION`,`callback id`,e,`error`,t),(0,r.isAuthRefreshDiscardedError)(t))return;(0,r.isAuthSessionMissingError)(t)||(0,r.isAuthRetryableFetchError)(t)||(0,r.isAuthApiError)(t)&&(t.code===`refresh_token_not_found`||t.code===`refresh_token_already_used`||t.code===`session_expired`)?console.warn(t):console.error(t)}})}async resetPasswordForEmail(e,t={}){let n=null,o=null,s=null;this.flowType===`pkce`&&([n,o,s]=await this._getCodeChallengeAndMethod(!0));try{return await(0,i._request)(this.fetch,`POST`,`${this.url}/recover`,{body:{email:e,code_challenge:n,code_challenge_method:o,gotrue_meta_security:{captcha_token:t.captchaToken}},headers:this.headers,redirectTo:this._maybeAppendFlowIdToRedirect(t.redirectTo,s)})}catch(e){if(await(0,a.removePKCEVerifier)(this.storage,this.storageKey,s),(0,r.isAuthError)(e))return this._returnResult({data:null,error:e});throw e}}async getUserIdentities(){try{let{data:e,error:t}=await this.getUser();if(t)throw t;return this._returnResult({data:{identities:e.user.identities??[]},error:null})}catch(e){if((0,r.isAuthError)(e))return this._returnResult({data:null,error:e});throw e}}async linkIdentity(e){return`token`in e?this.linkIdentityIdToken(e):this.linkIdentityOAuth(e)}async linkIdentityOAuth(e){let t=null;try{let{data:n,error:r}=await this._useSession(async n=>{let{data:r,error:a}=n;if(a)throw a;let{url:o,flowId:s}=await this._getUrlForProvider(`${this.url}/user/identities/authorize`,e.provider,{redirectTo:e.options?.redirectTo,scopes:e.options?.scopes,queryParams:e.options?.queryParams,skipBrowserRedirect:!0});return t=s,await(0,i._request)(this.fetch,`GET`,o,{headers:this.headers,jwt:r.session?.access_token??void 0})});if(r)throw r;return(0,a.isBrowser)()&&!e.options?.skipBrowserRedirect&&window.location.assign(n?.url),this._returnResult({data:{provider:e.provider,url:n?.url,flowId:t},error:null})}catch(n){if((0,r.isAuthError)(n))return this._returnResult({data:{provider:e.provider,url:null,flowId:t},error:n});throw n}}async linkIdentityIdToken(e){return await this._useSession(async t=>{try{let{error:n,data:{session:a}}=t;if(n)throw n;let{options:o,provider:s,token:c,access_token:l,nonce:u}=e,{data:d,error:f}=await(0,i._request)(this.fetch,`POST`,`${this.url}/token?grant_type=id_token`,{headers:this.headers,jwt:a?.access_token??void 0,body:{provider:s,id_token:c,access_token:l,nonce:u,link_identity:!0,gotrue_meta_security:{captcha_token:o?.captchaToken}},xform:i._sessionResponse});return f?this._returnResult({data:{user:null,session:null},error:f}):!d||!d.session||!d.user?this._returnResult({data:{user:null,session:null},error:new r.AuthInvalidTokenResponseError}):(d.session&&(await this._saveSession(d.session),await this._notifyAllSubscribers(`USER_UPDATED`,d.session)),this._returnResult({data:d,error:f}))}catch(e){if(await(0,a.removePKCEVerifier)(this.storage,this.storageKey,null),(0,r.isAuthError)(e))return this._returnResult({data:{user:null,session:null},error:e});throw e}})}async unlinkIdentity(e){try{return await this._useSession(async t=>{let{data:n,error:r}=t;if(r)throw r;return await(0,i._request)(this.fetch,`DELETE`,`${this.url}/user/identities/${e.identity_id}`,{headers:this.headers,jwt:n.session?.access_token??void 0})})}catch(e){if((0,r.isAuthError)(e))return this._returnResult({data:null,error:e});throw e}}async _refreshAccessToken(e){let t=`#_refreshAccessToken()`;this._debug(t,`begin`);try{let o=Date.now();return await(0,a.retryable)(async n=>(n>0&&await(0,a.sleep)(200*2**(n-1)),this._debug(t,`refreshing attempt`,n),await(0,i._request)(this.fetch,`POST`,`${this.url}/token?grant_type=refresh_token`,{body:{refresh_token:e},headers:this.headers,xform:i._sessionResponse})),(e,t)=>{let i=200*2**e;return t&&(0,r.isAuthRetryableFetchError)(t)&&Date.now()+i-o<n.AUTO_REFRESH_TICK_DURATION_MS})}catch(e){if(this._debug(t,`error`,e),(0,r.isAuthError)(e))return this._returnResult({data:{session:null,user:null},error:e});throw e}finally{this._debug(t,`end`)}}_isValidSession(e){return typeof e==`object`&&!!e&&`access_token`in e&&`refresh_token`in e&&`expires_at`in e}async _handleProviderSignIn(e,t){let{url:n,flowId:r}=await this._getUrlForProvider(`${this.url}/authorize`,e,{redirectTo:t.redirectTo,scopes:t.scopes,queryParams:t.queryParams});return this._debug(`#_handleProviderSignIn()`,`provider`,e,`options`,t,`url`,n),(0,a.isBrowser)()&&!t.skipBrowserRedirect&&window.location.assign(n),{data:{provider:e,url:n,flowId:r},error:null}}async _recoverAndRefresh(){let e=`#_recoverAndRefresh()`;this._debug(e,`begin`);try{let t=await(0,a.getItemAsync)(this.storage,this.storageKey);if(t&&this.userStorage){let e=await(0,a.getItemAsync)(this.userStorage,this.storageKey+`-user`);!this.storage.isServer&&Object.is(this.storage,this.userStorage)&&!e&&(e={user:t.user},await(0,a.setItemAsync)(this.userStorage,this.storageKey+`-user`,e)),t.user=e?.user??(0,a.userNotAvailableProxy)()}else if(t&&!t.user&&!t.user){let e=await(0,a.getItemAsync)(this.storage,this.storageKey+`-user`);e&&e?.user?(t.user=e.user,await(0,a.removeItemAsync)(this.storage,this.storageKey+`-user`),await(0,a.setItemAsync)(this.storage,this.storageKey,t)):t.user=(0,a.userNotAvailableProxy)()}if(this._debug(e,`session from storage`,t),!this._isValidSession(t)){this._debug(e,`session is not valid`),t!==null&&await this._removeSession();return}let i=(t.expires_at??1/0)*1e3-Date.now()<n.EXPIRY_MARGIN_MS;if(this._debug(e,`session has${i?``:` not`} expired with margin of ${n.EXPIRY_MARGIN_MS}s`),i){if(this.autoRefreshToken&&t.refresh_token){let{error:n}=await this._callRefreshToken(t.refresh_token);n&&((0,r.isAuthRefreshDiscardedError)(n)?this._debug(e,`refresh discarded by commit guard`,n):this._debug(e,`refresh failed`,n))}}else if(t.user&&t.user.__isUserNotAvailableProxy===!0)try{let{data:n,error:r}=await this._getUser(t.access_token);!r&&n?.user?(t.user=n.user,await this._saveSession(t),await this._notifyAllSubscribers(`SIGNED_IN`,t)):this._debug(e,`could not get user data, skipping SIGNED_IN notification`)}catch(t){console.error(`Error getting user data:`,t),this._debug(e,`error getting user data, skipping SIGNED_IN notification`,t)}else await this._notifyAllSubscribers(`SIGNED_IN`,t)}catch(t){this._debug(e,`error`,t),(0,r.isAuthRetryableFetchError)(t)?console.warn(t):console.error(t);return}finally{this._debug(e,`end`)}}async _callRefreshToken(e){var t,i;if(!e)throw new r.AuthSessionMissingError;if(this.refreshingDeferred)return this.refreshingDeferred.promise;if(this.lastRefreshFailure&&this.lastRefreshFailure.refreshToken===e&&Date.now()<this.lastRefreshFailure.expiresAt)return this._debug(`#_callRefreshToken()`,`returning cached failure (cooldown active)`),this.lastRefreshFailure.result;let o=`#_callRefreshToken()`;this._debug(o,`begin`);try{this.refreshingDeferred=new a.Deferred,this.refreshingDeferred.promise.then(void 0,()=>{});let t=await(0,a.getItemAsync)(this.storage,this.storageKey),{data:n,error:i}=await this._refreshAccessToken(e);if(i)throw i;if(!n.session)throw new r.AuthSessionMissingError;let s=await(0,a.getItemAsync)(this.storage,this.storageKey);if(t!==null&&(s===null||s.refresh_token!==t.refresh_token)){this._debug(o,`commit guard: storage changed since refresh started, discarding rotated tokens`,{startedWith:`present`,nowHolds:s?`replaced`:`cleared`});let e={data:null,error:new r.AuthRefreshDiscardedError};return this.refreshingDeferred.resolve(e),e}let c=this._sessionRemovalEpoch;if(await this._saveSession(n.session),this._sessionRemovalEpoch!==c){this._debug(o,`commit guard (post-save): _removeSession ran during _saveSession, undoing write`),await(0,a.removeItemAsync)(this.storage,this.storageKey),this.userStorage&&await(0,a.removeItemAsync)(this.userStorage,this.storageKey+`-user`);let e={data:null,error:new r.AuthRefreshDiscardedError};return this.refreshingDeferred.resolve(e),e}await this._notifyAllSubscribers(`TOKEN_REFRESHED`,n.session);let l={data:n.session,error:null};return this.lastRefreshFailure=null,this.refreshingDeferred.resolve(l),l}catch(s){if(this._debug(o,`error`,s),(0,r.isAuthError)(s)){let i={data:null,error:s};if(!(0,r.isAuthRetryableFetchError)(s)){let e=await(0,a.getItemAsync)(this.storage,this.storageKey);e?.expires_at&&e.expires_at*1e3>Date.now()?this._debug(o,`proactive refresh failed, access token still valid — preserving session`):await this._removeSession()}return this.lastRefreshFailure={refreshToken:e,result:i,expiresAt:Date.now()+n.REFRESH_FAILURE_COOLDOWN_MS},(t=this.refreshingDeferred)==null||t.resolve(i),i}throw(i=this.refreshingDeferred)==null||i.reject(s),s}finally{this.refreshingDeferred=null,this._debug(o,`end`)}}async _notifyAllSubscribers(e,t,n=!0){if(this._pendingInitNotifications!==null&&n){this._pendingInitNotifications.push({event:e,session:t,broadcast:n});return}let r=`#_notifyAllSubscribers(${e})`;this._debug(r,`begin`,t,`broadcast = ${n}`);try{this.broadcastChannel&&n&&this.broadcastChannel.postMessage({event:e,session:t});let r=[],i=Array.from(this.stateChangeEmitters.values()).map(async n=>{try{await n.callback(e,t)}catch(e){r.push(e)}});if(await Promise.all(i),r.length>0){for(let e=0;e<r.length;e+=1)console.error(r[e]);throw r[0]}}finally{this._debug(r,`end`)}}async _saveSession(e){this._debug(`#_saveSession()`,e),this.suppressGetSessionWarning=!0;let t=Object.assign({},e),n=t.user&&t.user.__isUserNotAvailableProxy===!0;if(this.userStorage){!n&&t.user&&await(0,a.setItemAsync)(this.userStorage,this.storageKey+`-user`,{user:t.user});let e=Object.assign({},t);delete e.user;let r=(0,a.deepClone)(e);await(0,a.setItemAsync)(this.storage,this.storageKey,r)}else{let e=(0,a.deepClone)(t);await(0,a.setItemAsync)(this.storage,this.storageKey,e)}}async _removeSession(){this._sessionRemovalEpoch+=1,this._debug(`#_removeSession()`),this.lastRefreshFailure=null,this.suppressGetSessionWarning=!1,await(0,a.removeItemAsync)(this.storage,this.storageKey),await(0,a.removeAllPKCEVerifiers)(this.storage,this.storageKey),await(0,a.removeItemAsync)(this.storage,this.storageKey+`-user`),this.userStorage&&await(0,a.removeItemAsync)(this.userStorage,this.storageKey+`-user`),await this._notifyAllSubscribers(`SIGNED_OUT`,null)}_removeVisibilityChangedCallback(){this._debug(`#_removeVisibilityChangedCallback()`);let e=this.visibilityChangedCallback;this.visibilityChangedCallback=null;try{e&&(0,a.isBrowser)()&&window!=null&&window.removeEventListener&&window.removeEventListener(`visibilitychange`,e)}catch(e){console.error(`removing visibilitychange callback failed`,e)}}async _startAutoRefresh(){await this._stopAutoRefresh(),this._debug(`#_startAutoRefresh()`);let e=setInterval(()=>this._autoRefreshTokenTick(),n.AUTO_REFRESH_TICK_DURATION_MS);this.autoRefreshTicker=e,e&&typeof e==`object`&&typeof e.unref==`function`?e.unref():typeof Deno<`u`&&typeof Deno.unrefTimer==`function`&&Deno.unrefTimer(e);let t=setTimeout(async()=>{await this.initializePromise,await this._autoRefreshTokenTick()},0);this.autoRefreshTickTimeout=t,t&&typeof t==`object`&&typeof t.unref==`function`?t.unref():typeof Deno<`u`&&typeof Deno.unrefTimer==`function`&&Deno.unrefTimer(t)}async _stopAutoRefresh(){this._debug(`#_stopAutoRefresh()`);let e=this.autoRefreshTicker;this.autoRefreshTicker=null,e&&clearInterval(e);let t=this.autoRefreshTickTimeout;this.autoRefreshTickTimeout=null,t&&clearTimeout(t)}async startAutoRefresh(){this._removeVisibilityChangedCallback(),await this._startAutoRefresh()}async stopAutoRefresh(){this._removeVisibilityChangedCallback(),await this._stopAutoRefresh()}async dispose(){var e;this._removeVisibilityChangedCallback(),await this._stopAutoRefresh(),(e=this.broadcastChannel)==null||e.close(),this.broadcastChannel=null,this.stateChangeEmitters.clear()}async _autoRefreshTokenTick(){if(this._debug(`#_autoRefreshTokenTick()`,`begin`),this.lock!=null)try{await this._acquireLock(0,async()=>{try{let e=Date.now();try{return await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug(`#_autoRefreshTokenTick()`,`no session`);return}let i=Math.floor((r.expires_at*1e3-e)/n.AUTO_REFRESH_TICK_DURATION_MS);this._debug(`#_autoRefreshTokenTick()`,`access token expires in ${i} ticks, a tick lasts ${n.AUTO_REFRESH_TICK_DURATION_MS}ms, refresh threshold is ${n.AUTO_REFRESH_TICK_THRESHOLD} ticks`),i<=n.AUTO_REFRESH_TICK_THRESHOLD&&await this._callRefreshToken(r.refresh_token)})}catch(e){console.error(`Auto refresh tick failed with error. This is likely a transient error.`,e)}}finally{this._debug(`#_autoRefreshTokenTick()`,`end`)}})}catch(e){if(e instanceof s.LockAcquireTimeoutError)this._debug(`auto refresh token tick lock not available`);else throw e}else if(this.refreshingDeferred!==null)this._debug(`#_autoRefreshTokenTick()`,`refresh already in flight, skipping`);else try{let e=Date.now();try{await this._useSession(async t=>{let{data:{session:r}}=t;if(!r||!r.refresh_token||!r.expires_at){this._debug(`#_autoRefreshTokenTick()`,`no session`);return}let i=Math.floor((r.expires_at*1e3-e)/n.AUTO_REFRESH_TICK_DURATION_MS);this._debug(`#_autoRefreshTokenTick()`,`access token expires in ${i} ticks, a tick lasts ${n.AUTO_REFRESH_TICK_DURATION_MS}ms, refresh threshold is ${n.AUTO_REFRESH_TICK_THRESHOLD} ticks`),i<=n.AUTO_REFRESH_TICK_THRESHOLD&&await this._callRefreshToken(r.refresh_token)})}catch(e){console.error(`Auto refresh tick failed with error. This is likely a transient error.`,e)}}finally{this._debug(`#_autoRefreshTokenTick()`,`end`)}}async _handleVisibilityChange(){if(this._debug(`#_handleVisibilityChange()`),!(0,a.isBrowser)()||!(window!=null&&window.addEventListener))return this.autoRefreshToken&&this.startAutoRefresh(),!1;try{this.visibilityChangedCallback=async()=>{try{await this._onVisibilityChanged(!1)}catch(e){this._debug(`#visibilityChangedCallback`,`error`,e)}},window==null||window.addEventListener(`visibilitychange`,this.visibilityChangedCallback),await this._onVisibilityChanged(!0)}catch(e){console.error(`_handleVisibilityChange`,e)}}async _onVisibilityChanged(e){let t=`#_onVisibilityChanged(${e})`;if(this._debug(t,`visibilityState`,document.visibilityState),document.visibilityState===`visible`){if(this.autoRefreshToken&&this._startAutoRefresh(),!e){if(await this.initializePromise,this.lock!=null)await this._acquireLock(this.lockAcquireTimeout,async()=>{document.visibilityState===`visible`?await this._recoverAndRefresh():this._debug(t,`acquired the lock to recover the session, but the browser visibilityState is no longer visible, aborting`)});else{if(document.visibilityState!==`visible`){this._debug(t,`visibilityState is no longer visible, skipping recovery`);return}await this._recoverAndRefresh()}}}else document.visibilityState===`hidden`&&this.autoRefreshToken&&this._stopAutoRefresh()}async _getUrlForProvider(e,t,n){let r=n?.redirectTo,i=null,a=null,o=null;this.flowType===`pkce`&&([i,a,o]=await this._getCodeChallengeAndMethod(),r=this._maybeAppendFlowIdToRedirect(r,o));let s=[`provider=${encodeURIComponent(t)}`];if(r&&s.push(`redirect_to=${encodeURIComponent(r)}`),n?.scopes&&s.push(`scopes=${encodeURIComponent(n.scopes)}`),i!=null&&a!=null){let e=new URLSearchParams({code_challenge:`${encodeURIComponent(i)}`,code_challenge_method:`${encodeURIComponent(a)}`});s.push(e.toString())}if(n?.queryParams){let e=new URLSearchParams(n.queryParams);s.push(e.toString())}return n?.skipBrowserRedirect&&s.push(`skip_http_redirect=${n.skipBrowserRedirect}`),{url:`${e}?${s.join(`&`)}`,flowId:o}}_maybeAppendFlowIdToRedirect(e,t){return!e||!t||!this.experimental.appendPkceFlowIdToRedirects?e??void 0:(0,a.appendFlowIdToRedirectTo)(e,t)}async _getCodeChallengeAndMethod(e=!1){return(0,a.getCodeChallengeAndMethod)(this.storage,this.storageKey,e,e=>this._debug(`#_getCodeChallengeAndMethod()`,`evicted oldest pending PKCE verifier slot`,e))}async _unenroll(e){try{return await this._useSession(async t=>{let{data:n,error:r}=t;return r?this._returnResult({data:null,error:r}):await(0,i._request)(this.fetch,`DELETE`,`${this.url}/factors/${e.factorId}`,{headers:this.headers,jwt:n?.session?.access_token})})}catch(e){if((0,r.isAuthError)(e))return this._returnResult({data:null,error:e});throw e}}async _enroll(e){try{return await this._useSession(async t=>{let{data:n,error:r}=t;if(r)return this._returnResult({data:null,error:r});let a=Object.assign({friendly_name:e.friendlyName,factor_type:e.factorType},e.factorType===`phone`?{phone:e.phone}:e.factorType===`totp`?{issuer:e.issuer}:{}),{data:o,error:s}=await(0,i._request)(this.fetch,`POST`,`${this.url}/factors`,{body:a,headers:this.headers,jwt:n?.session?.access_token});return s?this._returnResult({data:null,error:s}):(e.factorType===`totp`&&o.type===`totp`&&o?.totp?.qr_code&&(o.totp.qr_code=`data:image/svg+xml;utf-8,${o.totp.qr_code}`),this._returnResult({data:o,error:null}))})}catch(e){if((0,r.isAuthError)(e))return this._returnResult({data:null,error:e});throw e}}async _verify(e){let t=async()=>{try{return await this._useSession(async t=>{let{data:n,error:r}=t;if(r)return this._returnResult({data:null,error:r});let a=Object.assign({challenge_id:e.challengeId},`webauthn`in e?{webauthn:Object.assign(Object.assign({},e.webauthn),{credential_response:e.webauthn.type===`create`?(0,f.serializeCredentialCreationResponse)(e.webauthn.credential_response):(0,f.serializeCredentialRequestResponse)(e.webauthn.credential_response)})}:{code:e.code}),{data:o,error:s}=await(0,i._request)(this.fetch,`POST`,`${this.url}/factors/${e.factorId}/verify`,{body:a,headers:this.headers,jwt:n?.session?.access_token});return s?this._returnResult({data:null,error:s}):(await this._saveSession(Object.assign({expires_at:Math.round(Date.now()/1e3)+o.expires_in},o)),await this._notifyAllSubscribers(`MFA_CHALLENGE_VERIFIED`,o),this._returnResult({data:o,error:s}))})}catch(e){if((0,r.isAuthError)(e))return this._returnResult({data:null,error:e});throw e}};return this.lock==null?t():this._acquireLock(this.lockAcquireTimeout,t)}async _challenge(e){let t=async()=>{try{return await this._useSession(async t=>{let{data:n,error:r}=t;if(r)return this._returnResult({data:null,error:r});let a=await(0,i._request)(this.fetch,`POST`,`${this.url}/factors/${e.factorId}/challenge`,{body:e,headers:this.headers,jwt:n?.session?.access_token});if(a.error)return a;let{data:o}=a;if(o.type!==`webauthn`)return{data:o,error:null};switch(o.webauthn.type){case`create`:return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:(0,f.deserializeCredentialCreationOptions)(o.webauthn.credential_options.publicKey)})})}),error:null};case`request`:return{data:Object.assign(Object.assign({},o),{webauthn:Object.assign(Object.assign({},o.webauthn),{credential_options:Object.assign(Object.assign({},o.webauthn.credential_options),{publicKey:(0,f.deserializeCredentialRequestOptions)(o.webauthn.credential_options.publicKey)})})}),error:null}}})}catch(e){if((0,r.isAuthError)(e))return this._returnResult({data:null,error:e});throw e}};return this.lock==null?t():this._acquireLock(this.lockAcquireTimeout,t)}async _challengeAndVerify(e){let{data:t,error:n}=await this._challenge({factorId:e.factorId});return n?this._returnResult({data:null,error:n}):await this._verify({factorId:e.factorId,challengeId:t.id,code:e.code})}async _listFactors(){let{data:{user:e},error:t}=await this.getUser();if(t)return{data:null,error:t};let n={all:[],phone:[],totp:[],webauthn:[],recovery_code:[]};for(let t of e?.factors??[])n.all.push(t),t.status===`verified`&&t.factor_type in n&&Array.isArray(n[t.factor_type])&&n[t.factor_type].push(t);return{data:n,error:null}}async _getAuthenticatorAssuranceLevel(e){if(e)try{let{payload:t}=(0,a.decodeJWT)(e),n=null;t.aal&&(n=t.aal);let r=n,{data:{user:i},error:o}=await this.getUser(e);if(o)return this._returnResult({data:null,error:o});((i?.factors)?.filter(e=>e.status===`verified`)??[]).length>0&&(r=`aal2`);let s=t.amr||[];return{data:{currentLevel:n,nextLevel:r,currentAuthenticationMethods:s},error:null}}catch(e){if((0,r.isAuthError)(e))return this._returnResult({data:null,error:e});throw e}let{data:{session:t},error:n}=await this.getSession();if(n)return this._returnResult({data:null,error:n});if(!t)return{data:{currentLevel:null,nextLevel:null,currentAuthenticationMethods:[]},error:null};let{payload:i}=(0,a.decodeJWT)(t.access_token),o=null;i.aal&&(o=i.aal);let s=o;(t.user.factors?.filter(e=>e.status===`verified`)??[]).length>0&&(s=`aal2`);let c=i.amr||[];return{data:{currentLevel:o,nextLevel:s,currentAuthenticationMethods:c},error:null}}async _getRecoveryCodesStatus(){(0,a.assertRecoveryCodesExperimentalEnabled)(this.experimental);try{return await this._useSession(async e=>{let{data:t,error:n}=e;if(n)return this._returnResult({data:null,error:n});let{data:r,error:a}=await(0,i._request)(this.fetch,`GET`,`${this.url}/factors/recovery-codes`,{headers:this.headers,jwt:t?.session?.access_token});return a?this._returnResult({data:null,error:a}):this._returnResult({data:r,error:null})})}catch(e){if((0,r.isAuthError)(e))return this._returnResult({data:null,error:e});throw e}}async _generateRecoveryCodes(e){(0,a.assertRecoveryCodesExperimentalEnabled)(this.experimental);try{return await this._useSession(async t=>{let{data:n,error:r}=t;if(r)return this._returnResult({data:null,error:r});let{data:a,error:o}=await(0,i._request)(this.fetch,`POST`,`${this.url}/factors/recovery-codes`,{body:e?.friendlyName?{friendly_name:e.friendlyName}:void 0,headers:this.headers,jwt:n?.session?.access_token});return o?this._returnResult({data:null,error:o}):this._returnResult({data:a,error:null})})}catch(e){if((0,r.isAuthError)(e))return this._returnResult({data:null,error:e});throw e}}async _verifyRecoveryCode(e){(0,a.assertRecoveryCodesExperimentalEnabled)(this.experimental);let t=async()=>{try{return await this._useSession(async t=>{let{data:n,error:r}=t;if(r)return this._returnResult({data:null,error:r});let{data:o,error:s}=await(0,i._request)(this.fetch,`POST`,`${this.url}/factors/recovery-codes/verify`,{body:{code:e.code},headers:this.headers,jwt:n?.session?.access_token});if(s)return this._returnResult({data:null,error:s});let c=Object.assign({expires_at:(0,a.expiresAt)(o.expires_in)},o);return await this._saveSession(c),await this._notifyAllSubscribers(`MFA_CHALLENGE_VERIFIED`,c),this._returnResult({data:o,error:null})})}catch(e){if((0,r.isAuthError)(e))return this._returnResult({data:null,error:e});throw e}};return this.lock==null?t():this._acquireLock(this.lockAcquireTimeout,t)}async _regenerateRecoveryCodes(){(0,a.assertRecoveryCodesExperimentalEnabled)(this.experimental);try{return await this._useSession(async e=>{let{data:t,error:n}=e;if(n)return this._returnResult({data:null,error:n});let{data:r,error:a}=await(0,i._request)(this.fetch,`POST`,`${this.url}/factors/recovery-codes/regenerate`,{headers:this.headers,jwt:t?.session?.access_token});return a?this._returnResult({data:null,error:a}):this._returnResult({data:r,error:null})})}catch(e){if((0,r.isAuthError)(e))return this._returnResult({data:null,error:e});throw e}}async _unenrollRecoveryCodes(){(0,a.assertRecoveryCodesExperimentalEnabled)(this.experimental);try{return await this._useSession(async e=>{let{data:t,error:n}=e;if(n)return this._returnResult({data:null,error:n});let{data:r,error:a}=await(0,i._request)(this.fetch,`DELETE`,`${this.url}/factors/recovery-codes`,{headers:this.headers,jwt:t?.session?.access_token});return a?this._returnResult({data:null,error:a}):this._returnResult({data:r,error:null})})}catch(e){if((0,r.isAuthError)(e))return this._returnResult({data:null,error:e});throw e}}async _getAuthorizationDetails(e){try{return await this._useSession(async t=>{let{data:{session:n},error:a}=t;return a?this._returnResult({data:null,error:a}):n?await(0,i._request)(this.fetch,`GET`,`${this.url}/oauth/authorizations/${e}`,{headers:this.headers,jwt:n.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new r.AuthSessionMissingError})})}catch(e){if((0,r.isAuthError)(e))return this._returnResult({data:null,error:e});throw e}}async _approveAuthorization(e,t){try{return await this._useSession(async n=>{let{data:{session:o},error:s}=n;if(s)return this._returnResult({data:null,error:s});if(!o)return this._returnResult({data:null,error:new r.AuthSessionMissingError});let c=await(0,i._request)(this.fetch,`POST`,`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:o.access_token,body:{action:`approve`},xform:e=>({data:e,error:null})});return c.data&&c.data.redirect_url&&(0,a.isBrowser)()&&!t?.skipBrowserRedirect&&window.location.assign(c.data.redirect_url),c})}catch(e){if((0,r.isAuthError)(e))return this._returnResult({data:null,error:e});throw e}}async _denyAuthorization(e,t){try{return await this._useSession(async n=>{let{data:{session:o},error:s}=n;if(s)return this._returnResult({data:null,error:s});if(!o)return this._returnResult({data:null,error:new r.AuthSessionMissingError});let c=await(0,i._request)(this.fetch,`POST`,`${this.url}/oauth/authorizations/${e}/consent`,{headers:this.headers,jwt:o.access_token,body:{action:`deny`},xform:e=>({data:e,error:null})});return c.data&&c.data.redirect_url&&(0,a.isBrowser)()&&!t?.skipBrowserRedirect&&window.location.assign(c.data.redirect_url),c})}catch(e){if((0,r.isAuthError)(e))return this._returnResult({data:null,error:e});throw e}}async _listOAuthGrants(){try{return await this._useSession(async e=>{let{data:{session:t},error:n}=e;return n?this._returnResult({data:null,error:n}):t?await(0,i._request)(this.fetch,`GET`,`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:t.access_token,xform:e=>({data:e,error:null})}):this._returnResult({data:null,error:new r.AuthSessionMissingError})})}catch(e){if((0,r.isAuthError)(e))return this._returnResult({data:null,error:e});throw e}}async _revokeOAuthGrant(e){try{return await this._useSession(async t=>{let{data:{session:n},error:a}=t;return a?this._returnResult({data:null,error:a}):n?(await(0,i._request)(this.fetch,`DELETE`,`${this.url}/user/oauth/grants`,{headers:this.headers,jwt:n.access_token,query:{client_id:e.clientId},noResolveJson:!0}),{data:{},error:null}):this._returnResult({data:null,error:new r.AuthSessionMissingError})})}catch(e){if((0,r.isAuthError)(e))return this._returnResult({data:null,error:e});throw e}}async fetchJwk(e,t={keys:[]}){let r=t.keys.find(t=>t.kid===e);if(r)return r;let a=Date.now();if(r=this.jwks.keys.find(t=>t.kid===e),r&&this.jwks_cached_at+n.JWKS_TTL>a)return r;let{data:o,error:s}=await(0,i._request)(this.fetch,`GET`,`${this.url}/.well-known/jwks.json`,{headers:this.headers});if(s)throw s;return!o.keys||o.keys.length===0||(this.jwks=o,this.jwks_cached_at=a,r=o.keys.find(t=>t.kid===e),!r)?null:r}async getClaims(e,t={}){try{let n=e;if(!n){let{data:e,error:t}=await this.getSession();if(t||!e.session)return this._returnResult({data:null,error:t});n=e.session.access_token}let{header:i,payload:o,signature:s,raw:{header:c,payload:l}}=(0,a.decodeJWT)(n);if(!t?.allowExpired)try{(0,a.validateExp)(o.exp)}catch(e){throw new r.AuthInvalidJwtError(e instanceof Error?e.message:`JWT validation failed`)}let d=!i.alg||i.alg.startsWith(`HS`)||!i.kid||!(`crypto`in globalThis&&`subtle`in globalThis.crypto)?null:await this.fetchJwk(i.kid,t?.keys?{keys:t.keys}:t?.jwks);if(!d){let{error:e}=await this.getUser(n);if(e)throw e;return{data:{claims:o,header:i,signature:s},error:null}}let f=(0,a.getAlgorithm)(i.alg),p=await crypto.subtle.importKey(`jwk`,d,f,!0,[`verify`]);if(!await crypto.subtle.verify(f,p,s,(0,u.stringToUint8Array)(`${c}.${l}`)))throw new r.AuthInvalidJwtError(`Invalid JWT signature`);return{data:{claims:o,header:i,signature:s},error:null}}catch(e){if((0,r.isAuthError)(e))return this._returnResult({data:null,error:e});throw e}}async signInWithPasskey(e){try{if(!(0,f.browserSupportsWebAuthn)())return this._returnResult({data:null,error:new r.AuthUnknownError(`Browser does not support WebAuthn`,null)});let{data:t,error:n}=await this._startPasskeyAuthentication({options:{captchaToken:e?.options?.captchaToken}});if(n||!t)return this._returnResult({data:null,error:n});let i=(0,f.deserializeCredentialRequestOptions)(t.options),a=e?.options?.signal??f.webAuthnAbortService.createNewAbortSignal(),{data:o,error:s}=await(0,f.getCredential)({publicKey:i,signal:a,mediation:e?.options?.mediation});if(s||!o)return this._returnResult({data:null,error:s??new r.AuthUnknownError(`WebAuthn ceremony failed`,null)});let c=(0,f.serializeCredentialRequestResponse)(o);return this._verifyPasskeyAuthentication({challengeId:t.challenge_id,credential:c})}catch(e){if((0,r.isAuthError)(e))return this._returnResult({data:null,error:e});throw e}}async registerPasskey(e){try{if(!(0,f.browserSupportsWebAuthn)())return this._returnResult({data:null,error:new r.AuthUnknownError(`Browser does not support WebAuthn`,null)});let{data:t,error:n}=await this._startPasskeyRegistration();if(n||!t)return this._returnResult({data:null,error:n});let i=(0,f.deserializeCredentialCreationOptions)(t.options),a=e?.options?.signal??f.webAuthnAbortService.createNewAbortSignal(),{data:o,error:s}=await(0,f.createCredential)({publicKey:i,signal:a});if(s||!o)return this._returnResult({data:null,error:s??new r.AuthUnknownError(`WebAuthn ceremony failed`,null)});let c=(0,f.serializeCredentialCreationResponse)(o);return this._verifyPasskeyRegistration({challengeId:t.challenge_id,credential:c})}catch(e){if((0,r.isAuthError)(e))return this._returnResult({data:null,error:e});throw e}}async _startPasskeyRegistration(){try{return await this._useSession(async e=>{let{data:{session:t},error:n}=e;if(n)return this._returnResult({data:null,error:n});if(!t)return this._returnResult({data:null,error:new r.AuthSessionMissingError});let{data:a,error:o}=await(0,i._request)(this.fetch,`POST`,`${this.url}/passkeys/registration/options`,{headers:this.headers,jwt:t.access_token,body:{}});return o?this._returnResult({data:null,error:o}):this._returnResult({data:a,error:null})})}catch(e){if((0,r.isAuthError)(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyRegistration(e){try{return await this._useSession(async t=>{let{data:{session:n},error:a}=t;if(a)return this._returnResult({data:null,error:a});if(!n)return this._returnResult({data:null,error:new r.AuthSessionMissingError});let{data:o,error:s}=await(0,i._request)(this.fetch,`POST`,`${this.url}/passkeys/registration/verify`,{headers:this.headers,jwt:n.access_token,body:{challenge_id:e.challengeId,credential:e.credential}});return s?this._returnResult({data:null,error:s}):this._returnResult({data:o,error:null})})}catch(e){if((0,r.isAuthError)(e))return this._returnResult({data:null,error:e});throw e}}async _startPasskeyAuthentication(e){try{let{data:t,error:n}=await(0,i._request)(this.fetch,`POST`,`${this.url}/passkeys/authentication/options`,{headers:this.headers,body:{gotrue_meta_security:{captcha_token:e?.options?.captchaToken}}});return n?this._returnResult({data:null,error:n}):this._returnResult({data:t,error:null})}catch(e){if((0,r.isAuthError)(e))return this._returnResult({data:null,error:e});throw e}}async _verifyPasskeyAuthentication(e){try{let{data:t,error:n}=await(0,i._request)(this.fetch,`POST`,`${this.url}/passkeys/authentication/verify`,{headers:this.headers,body:{challenge_id:e.challengeId,credential:e.credential},xform:i._sessionResponse});return n?this._returnResult({data:null,error:n}):(t.session&&(await this._saveSession(t.session),await this._notifyAllSubscribers(`SIGNED_IN`,t.session)),this._returnResult({data:t,error:null}))}catch(e){if((0,r.isAuthError)(e))return this._returnResult({data:null,error:e});throw e}}async _listPasskeys(){try{return await this._useSession(async e=>{let{data:{session:t},error:n}=e;if(n)return this._returnResult({data:null,error:n});if(!t)return this._returnResult({data:null,error:new r.AuthSessionMissingError});let{data:a,error:o}=await(0,i._request)(this.fetch,`GET`,`${this.url}/passkeys`,{headers:this.headers,jwt:t.access_token,xform:e=>({data:e,error:null})});return o?this._returnResult({data:null,error:o}):this._returnResult({data:a,error:null})})}catch(e){if((0,r.isAuthError)(e))return this._returnResult({data:null,error:e});throw e}}async _updatePasskey(e){try{return await this._useSession(async t=>{let{data:{session:n},error:a}=t;if(a)return this._returnResult({data:null,error:a});if(!n)return this._returnResult({data:null,error:new r.AuthSessionMissingError});let{data:o,error:s}=await(0,i._request)(this.fetch,`PATCH`,`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:n.access_token,body:{friendly_name:e.friendlyName}});return s?this._returnResult({data:null,error:s}):this._returnResult({data:o,error:null})})}catch(e){if((0,r.isAuthError)(e))return this._returnResult({data:null,error:e});throw e}}async _deletePasskey(e){try{return await this._useSession(async t=>{let{data:{session:n},error:a}=t;if(a)return this._returnResult({data:null,error:a});if(!n)return this._returnResult({data:null,error:new r.AuthSessionMissingError});let{error:o}=await(0,i._request)(this.fetch,`DELETE`,`${this.url}/passkeys/${e.passkeyId}`,{headers:this.headers,jwt:n.access_token,noResolveJson:!0});return o?this._returnResult({data:null,error:o}):this._returnResult({data:null,error:null})})}catch(e){if((0,r.isAuthError)(e))return this._returnResult({data:null,error:e});throw e}}};g.nextInstanceID={},e.default=g})),tr=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=(Qe(),ue(me)).__importDefault(qn()).default})),nr=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=(Qe(),ue(me)).__importDefault(er()).default})),rr=(/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.processLock=e.lockInternals=e.NavigatorLockAcquireTimeoutError=e.navigatorLock=e.AuthClient=e.AuthAdminApi=e.GoTrueClient=e.GoTrueAdminApi=void 0;let t=(Qe(),ue(me));e.GoTrueAdminApi=t.__importDefault(qn()).default,e.GoTrueClient=t.__importDefault(er()).default,e.AuthAdminApi=t.__importDefault(tr()).default,e.AuthClient=t.__importDefault(nr()).default,t.__exportStar(Kn(),e),t.__exportStar(Hn(),e);var n=Yn();Object.defineProperty(e,"navigatorLock",{enumerable:!0,get:function(){return n.navigatorLock}}),Object.defineProperty(e,"NavigatorLockAcquireTimeoutError",{enumerable:!0,get:function(){return n.NavigatorLockAcquireTimeoutError}}),Object.defineProperty(e,"lockInternals",{enumerable:!0,get:function(){return n.internals}}),Object.defineProperty(e,"processLock",{enumerable:!0,get:function(){return n.processLock}})})))();let ir=``,ar;if(typeof Deno<`u`)ir=`deno`,ar=Deno.version?.deno;else if(typeof document<`u`)ir=`web`;else if(typeof navigator<`u`&&navigator.product===`ReactNative`)ir=`react-native`;else{var or;ir=`node`;let e=globalThis.process;ar=e==null||(or=e.version)==null?void 0:or.replace(/^v/,``)}const sr=[`runtime=${ir}`];ar&&sr.push(`runtime-version=${ar}`);const cr={headers:{"X-Client-Info":`supabase-js/2.118.0; ${sr.join(`; `)}`}},lr={schema:`public`},ur={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:`implicit`},dr={},fr={enabled:!1,respectSamplingDecision:!0};function pr(e){if(!e||typeof e!=`string`)return null;let t=e.split(`-`);if(t.length!==4)return null;let[n,r,i,a]=t;if(n.length!==2||r.length!==32||i.length!==16||a.length!==2)return null;let o=/^[0-9a-f]+$/i;return!o.test(n)||!o.test(r)||!o.test(i)||!o.test(a)||r===`00000000000000000000000000000000`||i===`0000000000000000`?null:{version:n,traceId:r,parentId:i,traceFlags:a,isSampled:(parseInt(a,16)&1)==1}}function mr(e,t){if(!e||!t||t.length===0)return!1;let n;if(e instanceof URL)n=e;else try{n=new URL(e)}catch{return!1}for(let e of t)try{if(typeof e==`string`){if(hr(n.hostname,e))return!0}else if(e instanceof RegExp){if(e.test(n.hostname))return!0}else if(typeof e==`function`&&e(n))return!0}catch{continue}return!1}function hr(e,t){if(t===e)return!0;if(t.startsWith(`*.`)){let n=t.slice(2);if(e.endsWith(n)&&(e===n||e.endsWith(`.`+n)))return!0}return!1}function gr(e){let t=[];try{let n=new URL(e);t.push(n.hostname)}catch{}return t.push(`*.supabase.co`,`*.supabase.in`),t.push(`localhost`,`127.0.0.1`,`[::1]`),t}function _r(e){"@babel/helpers - typeof";return _r=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},_r(e)}function vr(e,t){if(_r(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(_r(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function yr(e){var t=vr(e,`string`);return _r(t)==`symbol`?t:t+``}function br(e,t,n){return(t=yr(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function xr(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter(function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable})),n.push.apply(n,r)}return n}function Sr(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?xr(Object(n),!0).forEach(function(t){br(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):xr(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}const Cr=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),wr=()=>Headers,Tr=e=>e.startsWith(`sb_publishable_`)||e.startsWith(`sb_secret_`),Er=/* @__PURE__ */ new Set,Dr=e=>{if(!e.startsWith(`sb_`)||Tr(e)||e.startsWith(`sb_temp_`))return;let t=e.match(/^sb_[a-zA-Z0-9]+_/)?.[0]??`unknown`;Er.has(t)||(Er.add(t),console.warn(`@supabase/supabase-js: Unrecognized Supabase API key format. The client will proceed and send this key as-is; if you see authentication errors you may need to upgrade @supabase/supabase-js to a version that recognizes this key type.`))},Or=(e,t,n,r,i,a)=>{let o=Cr(r),s=wr(),c=i?.enabled===!0,l=i?.respectSamplingDecision!==!1,u=c?gr(t):null,d=!(a?.omitApiKeyAsBearer&&Tr(e));return async(t,r)=>{let i=await n(),a=new s(r?.headers);if(a.has(`apikey`)||a.set(`apikey`,e),!a.has(`Authorization`)){let t=i??(d?e:null);t&&a.set(`Authorization`,`Bearer ${t}`)}if(u){let e=jr(t,u,l);e&&(e.traceparent&&!a.has(`traceparent`)&&a.set(`traceparent`,e.traceparent),e.tracestate&&!a.has(`tracestate`)&&a.set(`tracestate`,e.tracestate),e.baggage&&!a.has(`baggage`)&&a.set(`baggage`,e.baggage))}return o(t,Sr(Sr({},r),{},{headers:a}))}};let kr=!1,Ar=!1;function jr(e,t,n){let r=pe();if(!r)return kr||(kr=!0,console.warn("@supabase/supabase-js: tracePropagation is enabled but the tracing runtime is not loaded, so trace headers will not be attached. Add `import '@supabase/supabase-js/tracing'` at your application entry point (requires the OpenTelemetry API package to be installed). The CDN/UMD build does not support trace propagation.")),null;if(!mr(typeof e==`string`||e instanceof URL?e:e.url,t))return null;let i=r();if(!i||!i.traceparent){var a;if(i!=null&&(a=i.carrierKeys)!=null&&a.length&&!Ar){Ar=!0;let e=i.carrierKeys.includes(`sentry-trace`)?" Sentry detected: set `propagateTraceparent: true` in Sentry.init() to emit it.":` Configure your tracing SDK to emit W3C trace context on outgoing requests.`;console.warn(`@supabase/supabase-js: tracePropagation is enabled and a tracing SDK is active, but its propagator wrote [${i.carrierKeys.join(`, `)}] and no W3C traceparent header, so trace headers will not be attached.`+e)}return null}if(n){let e=pr(i.traceparent);if(e&&!e.isSampled)return{traceparent:i.traceparent}}return i}function Mr(e){return typeof e==`boolean`?{enabled:e}:e}function Nr(e){return e.endsWith(`/`)?e:e+`/`}let Pr=!1;function Fr(e){Pr||typeof e==`object`&&e&&`schema`in e&&e.schema!==void 0&&(Pr=!0,console.warn(`@supabase/supabase-js: The "schema" option must be nested under "db", e.g. createClient(url, key, { db: { schema: 'myschema' } }). A top-level "schema" is ignored and queries go to the default schema.`))}function Ir(e,t){let{db:n,auth:r,realtime:i,global:a}=e,{db:o,auth:s,realtime:c,global:l}=t,u=Mr(e.tracePropagation),d=Mr(t.tracePropagation),f={db:Sr(Sr({},o),n),auth:Sr(Sr({},s),r),realtime:Sr(Sr({},c),i),storage:{},global:Sr(Sr(Sr({},l),a),{},{headers:Sr(Sr({},l?.headers??{}),a?.headers??{})}),tracePropagation:{enabled:u?.enabled??d?.enabled??!1,respectSamplingDecision:u?.respectSamplingDecision??d?.respectSamplingDecision??!0},accessToken:async()=>``};return e.accessToken?f.accessToken=e.accessToken:delete f.accessToken,f}function Lr(e){let t=e?.trim();if(!t)throw Error(`supabaseUrl is required.`);if(!t.match(/^https?:\/\//i))throw Error(`Invalid supabaseUrl: Must be a valid HTTP or HTTPS URL.`);try{return new URL(Nr(t))}catch{throw Error(`Invalid supabaseUrl: Provided URL is malformed.`)}}var Rr=class extends rr.AuthClient{constructor(e){super(e)}},zr=class{constructor(e,t,n){this.supabaseUrl=e,this.supabaseKey=t;let r=Lr(e);if(!t)throw Error(`supabaseKey is required.`);Dr(t),Fr(n),this.realtimeUrl=new URL(`realtime/v1`,r),this.realtimeUrl.protocol=this.realtimeUrl.protocol.replace(`http`,`ws`),this.authUrl=new URL(`auth/v1`,r),this.storageUrl=new URL(`storage/v1`,r),this.functionsUrl=new URL(`functions/v1`,r);let i=`sb-${r.hostname.split(`.`)[0]}-auth-token`,a={db:lr,realtime:dr,auth:Sr(Sr({},ur),{},{storageKey:i}),global:cr,tracePropagation:fr},o=Ir(n??{},a);this.settings=o,this.storageKey=o.auth.storageKey??``,this.headers=o.global.headers??{},o.accessToken?(this.accessToken=o.accessToken,this.auth=new Proxy({},{get:(e,t)=>{throw Error(`@supabase/supabase-js: Supabase Client is configured with the accessToken option, accessing supabase.auth.${String(t)} is not possible`)}})):this.auth=this._initSupabaseAuthClient(o.auth??{},this.headers,o.global.fetch),this.fetch=Or(t,e,this._getSessionToken.bind(this),o.global.fetch,o.tracePropagation),this.functionsFetch=Or(t,e,this._getSessionToken.bind(this),o.global.fetch,o.tracePropagation,{omitApiKeyAsBearer:!0}),this.realtime=this._initRealtimeClient(Sr({headers:this.headers,accessToken:this._getAccessToken.bind(this),fetch:this.fetch},o.realtime)),this.accessToken&&Promise.resolve(this.accessToken()).then(e=>this.realtime.setAuth(e)).catch(e=>console.warn(`Failed to set initial Realtime auth token:`,e)),this.rest=new Ct(new URL(`rest/v1`,r).href,{headers:this.headers,schema:o.db.schema,fetch:this.fetch,timeout:o.db.timeout,urlLengthLimit:o.db.urlLengthLimit,retry:o.db.retry}),this.storage=new zn(this.storageUrl.href,this.headers,this.fetch,n?.storage),o.accessToken||this._listenForAuthEvents()}get functions(){return new nt.FunctionsClient(this.functionsUrl.href,{headers:this.headers,customFetch:this.functionsFetch})}from(e){return this.rest.from(e)}schema(e){return this.rest.schema(e)}getOpenApiSpec(){return this.rest.getOpenApiSpec()}rpc(e,t={},n={head:!1,get:!1,count:void 0}){return this.rest.rpc(e,t,n)}channel(e,t={config:{}}){return this.realtime.channel(e,t)}getChannels(){return this.realtime.getChannels()}removeChannel(e){return this.realtime.removeChannel(e)}removeAllChannels(){return this.realtime.removeAllChannels()}async _getSessionToken(){var e=this;if(e.accessToken)return await e.accessToken();let{data:t}=await e.auth.getSession();return t.session?.access_token??null}async _getAccessToken(){var e=this;return await e._getSessionToken()??e.supabaseKey}_initSupabaseAuthClient({autoRefreshToken:e,persistSession:t,detectSessionInUrl:n,storage:r,userStorage:i,storageKey:a,flowType:o,lock:s,debug:c,throwOnError:l,experimental:u,lockAcquireTimeout:d,skipAutoInitialize:f},p,m){let h={Authorization:`Bearer ${this.supabaseKey}`,apikey:`${this.supabaseKey}`};return new Rr({url:this.authUrl.href,headers:Sr(Sr({},h),p),storageKey:a,autoRefreshToken:e,persistSession:t,detectSessionInUrl:n,storage:r,userStorage:i,flowType:o,lock:s,debug:c,throwOnError:l,experimental:u,fetch:m,lockAcquireTimeout:d,skipAutoInitialize:f,hasCustomAuthorizationHeader:Object.keys(this.headers).some(e=>e.toLowerCase()===`authorization`)})}_initRealtimeClient(e){return new Rt.RealtimeClient(this.realtimeUrl.href,Sr(Sr({},e),{},{params:Sr(Sr({},{apikey:this.supabaseKey}),e?.params)}))}_listenForAuthEvents(){return this.auth.onAuthStateChange((e,t)=>{this._handleTokenChanged(e,`CLIENT`,t?.access_token)})}_handleTokenChanged(e,t,n){(e===`TOKEN_REFRESHED`||e===`SIGNED_IN`||e===`INITIAL_SESSION`)&&this.changedAccessToken!==n?(this.changedAccessToken=n,this.realtime.setAuth(n)):e===`SIGNED_OUT`&&(this.realtime.setAuth(),t==`STORAGE`&&this.auth.signOut(),this.changedAccessToken=void 0)}};const Br=(e,t,n)=>new zr(e,t,n);function Vr(){if(typeof window<`u`||globalThis.Deno!==void 0)return!1;let e=globalThis.process;if(!e)return!1;let t=e.version;if(t==null)return!1;let n=t.match(/^v(\d+)\./);return n?parseInt(n[1],10)<=20:!1}Vr()&&console.warn(`⚠️ Node.js 20 and below are deprecated and will no longer be supported in future versions of @supabase/supabase-js. Please upgrade to Node.js 22 or later. For more information, visit: https://github.com/orgs/supabase/discussions/45715`);var Hr=class extends Error{},Ur=class{client;connection;constructor(e){this.connection=e,this.client=Br(e.apiUrl,e.publishableKey,{auth:{persistSession:!1,autoRefreshToken:!1}})}async call(e,t={}){if(!this.connection.key)throw new Hr("Not signed in to Quirl. Run `quirl login` in a terminal.");let{data:n,error:r}=await this.client.rpc(`api_${e}`,{p_key:this.connection.key,...t});if(r)throw new Hr(r.message);return n}whoami(){return this.call(`whoami`)}context(e){return this.call(`context`,{p_project:e})}};function Wr(e,t){let n=Br(e,t,{auth:{persistSession:!1,autoRefreshToken:!1}});return{async start(e){let{data:t,error:r}=await n.rpc(`cli_login_start`,{p_device_name:e});if(r)throw new Hr(r.message);return t},async poll(e,t){let{data:r,error:i}=await n.rpc(`cli_login_poll`,{p_request_id:e,p_poll_secret:t});if(i)throw new Hr(i.message);return r}}}var k;(function(e){e.assertEqual=e=>{};function t(e){}e.assertIs=t;function n(e){throw Error()}e.assertNever=n,e.arrayToEnum=e=>{let t={};for(let n of e)t[n]=n;return t},e.getValidEnumValues=t=>{let n=e.objectKeys(t).filter(e=>typeof t[t[e]]!=`number`),r={};for(let e of n)r[e]=t[e];return e.objectValues(r)},e.objectValues=t=>e.objectKeys(t).map(function(e){return t[e]}),e.objectKeys=typeof Object.keys==`function`?e=>Object.keys(e):e=>{let t=[];for(let n in e)Object.prototype.hasOwnProperty.call(e,n)&&t.push(n);return t},e.find=(e,t)=>{for(let n of e)if(t(n))return n},e.isInteger=typeof Number.isInteger==`function`?e=>Number.isInteger(e):e=>typeof e==`number`&&Number.isFinite(e)&&Math.floor(e)===e;function r(e,t=` | `){return e.map(e=>typeof e==`string`?`'${e}'`:e).join(t)}e.joinValues=r,e.jsonStringifyReplacer=(e,t)=>typeof t==`bigint`?t.toString():t})(k||={});var Gr;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(Gr||={});const A=k.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),Kr=e=>{switch(typeof e){case`undefined`:return A.undefined;case`string`:return A.string;case`number`:return Number.isNaN(e)?A.nan:A.number;case`boolean`:return A.boolean;case`function`:return A.function;case`bigint`:return A.bigint;case`symbol`:return A.symbol;case`object`:return Array.isArray(e)?A.array:e===null?A.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?A.promise:typeof Map<`u`&&e instanceof Map?A.map:typeof Set<`u`&&e instanceof Set?A.set:typeof Date<`u`&&e instanceof Date?A.date:A.object;default:return A.unknown}},j=k.arrayToEnum([`invalid_type`,`invalid_literal`,`custom`,`invalid_union`,`invalid_union_discriminator`,`invalid_enum_value`,`unrecognized_keys`,`invalid_arguments`,`invalid_return_type`,`invalid_date`,`invalid_string`,`too_small`,`too_big`,`invalid_intersection_types`,`not_multiple_of`,`not_finite`]);var qr=class e extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=e=>{this.issues=[...this.issues,e]},this.addIssues=(e=[])=>{this.issues=[...this.issues,...e]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name=`ZodError`,this.issues=e}format(e){let t=e||function(e){return e.message},n={_errors:[]},r=e=>{for(let i of e.issues)if(i.code===`invalid_union`)i.unionErrors.map(r);else if(i.code===`invalid_return_type`)r(i.returnTypeError);else if(i.code===`invalid_arguments`)r(i.argumentsError);else if(i.path.length===0)n._errors.push(t(i));else{let e=n,r=0;for(;r<i.path.length;){let n=i.path[r],a=r===i.path.length-1;n===`_errors`?(a&&e._errors.push(t(i)),r++):(Object.prototype.hasOwnProperty.call(e,n)||(n===`__proto__`?Object.defineProperty(e,n,{value:{_errors:[]},writable:!0,enumerable:!0,configurable:!0}):e[n]={_errors:[]}),e=e[n],a&&e._errors.push(t(i)),r++)}}};return r(this),n}static assert(t){if(!(t instanceof e))throw Error(`Not a ZodError: ${t}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,k.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=e=>e.message){let t=Object.create(null),n=[];for(let r of this.issues)if(r.path.length>0){let n=r.path[0];t[n]=t[n]||[],t[n].push(e(r))}else n.push(e(r));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};qr.create=e=>new qr(e);const Jr=(e,t)=>{let n;switch(e.code){case j.invalid_type:n=e.received===A.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case j.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,k.jsonStringifyReplacer)}`;break;case j.unrecognized_keys:n=`Unrecognized key(s) in object: ${k.joinValues(e.keys,`, `)}`;break;case j.invalid_union:n=`Invalid input`;break;case j.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${k.joinValues(e.options)}`;break;case j.invalid_enum_value:n=`Invalid enum value. Expected ${k.joinValues(e.options)}, received '${e.received}'`;break;case j.invalid_arguments:n=`Invalid function arguments`;break;case j.invalid_return_type:n=`Invalid function return type`;break;case j.invalid_date:n=`Invalid date`;break;case j.invalid_string:typeof e.validation==`object`?`includes`in e.validation?(n=`Invalid input: must include "${e.validation.includes}"`,typeof e.validation.position==`number`&&(n=`${n} at one or more positions greater than or equal to ${e.validation.position}`)):`startsWith`in e.validation?n=`Invalid input: must start with "${e.validation.startsWith}"`:`endsWith`in e.validation?n=`Invalid input: must end with "${e.validation.endsWith}"`:k.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case j.too_small:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at least`:`more than`} ${e.minimum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at least`:`over`} ${e.minimum} character(s)`:e.type===`number`||e.type===`bigint`?`Number must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${e.minimum}`:e.type===`date`?`Date must be ${e.exact?`exactly equal to `:e.inclusive?`greater than or equal to `:`greater than `}${new Date(Number(e.minimum))}`:`Invalid input`;break;case j.too_big:n=e.type===`array`?`Array must contain ${e.exact?`exactly`:e.inclusive?`at most`:`less than`} ${e.maximum} element(s)`:e.type===`string`?`String must contain ${e.exact?`exactly`:e.inclusive?`at most`:`under`} ${e.maximum} character(s)`:e.type===`number`?`Number must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`bigint`?`BigInt must be ${e.exact?`exactly`:e.inclusive?`less than or equal to`:`less than`} ${e.maximum}`:e.type===`date`?`Date must be ${e.exact?`exactly`:e.inclusive?`smaller than or equal to`:`smaller than`} ${new Date(Number(e.maximum))}`:`Invalid input`;break;case j.custom:n=`Invalid input`;break;case j.invalid_intersection_types:n=`Intersection results could not be merged`;break;case j.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case j.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,k.assertNever(e)}return{message:n}};let Yr=Jr;function Xr(){return Yr}const Zr=e=>{let{data:t,path:n,errorMaps:r,issueData:i}=e,a=[...n,...i.path||[]],o={...i,path:a};if(i.message!==void 0)return{...i,path:a,message:i.message};let s=``,c=r.filter(e=>!!e).slice().reverse();for(let e of c)s=e(o,{data:t,defaultError:s}).message;return{...i,path:a,message:s}};function M(e,t){let n=Xr(),r=Zr({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Jr?void 0:Jr].filter(e=>!!e)});e.common.issues.push(r)}var Qr=class e{constructor(){this.value=`valid`}dirty(){this.value===`valid`&&(this.value=`dirty`)}abort(){this.value!==`aborted`&&(this.value=`aborted`)}static mergeArray(e,t){let n=[];for(let r of t){if(r.status===`aborted`)return N;r.status===`dirty`&&e.dirty(),n.push(r.value)}return{status:e.value,value:n}}static async mergeObjectAsync(t,n){let r=[];for(let e of n){let t=await e.key,n=await e.value;r.push({key:t,value:n})}return e.mergeObjectSync(t,r)}static mergeObjectSync(e,t){let n={};for(let r of t){let{key:t,value:i}=r;if(t.status===`aborted`||i.status===`aborted`)return N;t.status===`dirty`&&e.dirty(),i.status===`dirty`&&e.dirty(),t.value!==`__proto__`&&(i.value!==void 0||r.alwaysSet)&&(n[t.value]=i.value)}return{status:e.value,value:n}}};const N=Object.freeze({status:`aborted`}),$r=e=>({status:`dirty`,value:e}),ei=e=>({status:`valid`,value:e}),ti=e=>e.status===`aborted`,ni=e=>e.status===`dirty`,ri=e=>e.status===`valid`,ii=e=>typeof Promise<`u`&&e instanceof Promise;var P;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(P||={});var ai=class{constructor(e,t,n,r){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=r}get path(){return this._cachedPath.length||(Array.isArray(this._key)?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}};const oi=(e,t)=>{if(ri(t))return{success:!0,data:t.value};if(!e.common.issues.length)throw Error(`Validation failed but no issues detected.`);return{success:!1,get error(){if(this._error)return this._error;let t=new qr(e.common.issues);return this._error=t,this._error}}};function F(e){if(!e)return{};let{errorMap:t,invalid_type_error:n,required_error:r,description:i}=e;if(t&&(n||r))throw Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return t?{errorMap:t,description:i}:{errorMap:(t,i)=>{let{message:a}=e;return t.code===`invalid_enum_value`?{message:a??i.defaultError}:i.data===void 0?{message:a??r??i.defaultError}:t.code===`invalid_type`?{message:a??n??i.defaultError}:{message:i.defaultError}},description:i}}var I=class{get description(){return this._def.description}_getType(e){return Kr(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Kr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Qr,ctx:{common:e.parent.common,data:e.data,parsedType:Kr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(ii(t))throw Error(`Synchronous parse encountered promise.`);return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){let n={common:{issues:[],async:t?.async??!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Kr(e)},r=this._parseSync({data:e,path:n.path,parent:n});return oi(n,r)}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Kr(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return ri(n)?{value:n.value}:{issues:t.common.issues}}catch(e){e?.message?.toLowerCase()?.includes(`encountered`)&&(this[`~standard`].async=!0),t.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:t}).then(e=>ri(e)?{value:e.value}:{issues:t.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Kr(e)},r=this._parse({data:e,path:n.path,parent:n}),i=await(ii(r)?r:Promise.resolve(r));return oi(n,i)}refine(e,t){let n=e=>typeof t==`string`||t===void 0?{message:t}:typeof t==`function`?t(e):t;return this._refinement((t,r)=>{let i=e(t),a=()=>r.addIssue({code:j.custom,...n(t)});return typeof Promise<`u`&&i instanceof Promise?i.then(e=>e?!0:(a(),!1)):i?!0:(a(),!1)})}refinement(e,t){return this._refinement((n,r)=>e(n)?!0:(r.addIssue(typeof t==`function`?t(n,r):t),!1))}_refinement(e){return new ca({schema:this,typeName:L.ZodEffects,effect:{type:`refinement`,refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this[`~standard`]={version:1,vendor:`zod`,validate:e=>this[`~validate`](e)}}optional(){return la.create(this,this._def)}nullable(){return ua.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Ui.create(this)}promise(){return sa.create(this,this._def)}or(e){return Ki.create([this,e],this._def)}and(e){return Xi.create(this,e,this._def)}transform(e){return new ca({...F(this._def),schema:this,typeName:L.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new da({...F(this._def),innerType:this,defaultValue:t,typeName:L.ZodDefault})}brand(){return new ma({typeName:L.ZodBranded,type:this,...F(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new fa({...F(this._def),innerType:this,catchValue:t,typeName:L.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return ha.create(this,e)}readonly(){return ga.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const si=/^c[^\s-]{8,}$/i,ci=/^[0-9a-z]+$/,li=/^[0-9A-HJKMNP-TV-Z]{26}$/i,ui=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,di=/^[a-z0-9_-]{21}$/i,fi=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,pi=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,mi=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let hi;const gi=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,_i=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,vi=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,yi=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,bi=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,xi=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Si=`((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))`,Ci=RegExp(`^${Si}$`);function wi(e){let t=`[0-5]\\d`;e.precision?t=`${t}\\.\\d{${e.precision}}`:e.precision??(t=`${t}(\\.\\d+)?`);let n=e.precision?`+`:`?`;return`([01]\\d|2[0-3]):[0-5]\\d(:${t})${n}`}function Ti(e){return RegExp(`^${wi(e)}$`)}function Ei(e){let t=`${Si}T${wi(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function Di(e,t){return!((t!==`v4`&&t||!gi.test(e))&&(t!==`v6`&&t||!vi.test(e)))}function Oi(e,t){if(!fi.test(e))return!1;try{let[n]=e.split(`.`);if(!n)return!1;let r=n.replace(/-/g,`+`).replace(/_/g,`/`).padEnd(n.length+(4-n.length%4)%4,`=`),i=JSON.parse(atob(r));return!(typeof i!=`object`||!i||`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&i.alg!==t)}catch{return!1}}function ki(e,t){return!((t!==`v4`&&t||!_i.test(e))&&(t!==`v6`&&t||!yi.test(e)))}var Ai=class e extends I{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==A.string){let t=this._getOrReturnCtx(e);return M(t,{code:j.invalid_type,expected:A.string,received:t.parsedType}),N}let t=new Qr,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),M(n,{code:j.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`max`)e.data.length>r.value&&(n=this._getOrReturnCtx(e,n),M(n,{code:j.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!1,message:r.message}),t.dirty());else if(r.kind===`length`){let i=e.data.length>r.value,a=e.data.length<r.value;(i||a)&&(n=this._getOrReturnCtx(e,n),i?M(n,{code:j.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&M(n,{code:j.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)mi.test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`email`,code:j.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)hi||=RegExp(`^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`,`u`),hi.test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`emoji`,code:j.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)ui.test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`uuid`,code:j.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)di.test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`nanoid`,code:j.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)si.test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`cuid`,code:j.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)ci.test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`cuid2`,code:j.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)li.test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`ulid`,code:j.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),M(n,{validation:`url`,code:j.invalid_string,message:r.message}),t.dirty()}else r.kind===`regex`?(r.regex.lastIndex=0,r.regex.test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`regex`,code:j.invalid_string,message:r.message}),t.dirty())):r.kind===`trim`?e.data=e.data.trim():r.kind===`includes`?e.data.includes(r.value,r.position)||(n=this._getOrReturnCtx(e,n),M(n,{code:j.invalid_string,validation:{includes:r.value,position:r.position},message:r.message}),t.dirty()):r.kind===`toLowerCase`?e.data=e.data.toLowerCase():r.kind===`toUpperCase`?e.data=e.data.toUpperCase():r.kind===`startsWith`?e.data.startsWith(r.value)||(n=this._getOrReturnCtx(e,n),M(n,{code:j.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),M(n,{code:j.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?Ei(r).test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{code:j.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?Ci.test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{code:j.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?Ti(r).test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{code:j.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?pi.test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`duration`,code:j.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?Di(e.data,r.version)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`ip`,code:j.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?Oi(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`jwt`,code:j.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?ki(e.data,r.version)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`cidr`,code:j.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?bi.test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`base64`,code:j.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?xi.test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`base64url`,code:j.invalid_string,message:r.message}),t.dirty()):k.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:j.invalid_string,...P.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...P.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...P.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...P.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...P.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...P.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...P.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...P.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...P.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...P.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...P.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...P.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...P.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...P.errToObj(e)})}datetime(e){return typeof e==`string`?this._addCheck({kind:`datetime`,precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:`datetime`,precision:e?.precision===void 0?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...P.errToObj(e?.message)})}date(e){return this._addCheck({kind:`date`,message:e})}time(e){return typeof e==`string`?this._addCheck({kind:`time`,precision:null,message:e}):this._addCheck({kind:`time`,precision:e?.precision===void 0?null:e?.precision,...P.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...P.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...P.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...P.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...P.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...P.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...P.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...P.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...P.errToObj(t)})}nonempty(e){return this.min(1,P.errToObj(e))}trim(){return new e({...this._def,checks:[...this._def.checks,{kind:`trim`}]})}toLowerCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toLowerCase`}]})}toUpperCase(){return new e({...this._def,checks:[...this._def.checks,{kind:`toUpperCase`}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind===`datetime`)}get isDate(){return!!this._def.checks.find(e=>e.kind===`date`)}get isTime(){return!!this._def.checks.find(e=>e.kind===`time`)}get isDuration(){return!!this._def.checks.find(e=>e.kind===`duration`)}get isEmail(){return!!this._def.checks.find(e=>e.kind===`email`)}get isURL(){return!!this._def.checks.find(e=>e.kind===`url`)}get isEmoji(){return!!this._def.checks.find(e=>e.kind===`emoji`)}get isUUID(){return!!this._def.checks.find(e=>e.kind===`uuid`)}get isNANOID(){return!!this._def.checks.find(e=>e.kind===`nanoid`)}get isCUID(){return!!this._def.checks.find(e=>e.kind===`cuid`)}get isCUID2(){return!!this._def.checks.find(e=>e.kind===`cuid2`)}get isULID(){return!!this._def.checks.find(e=>e.kind===`ulid`)}get isIP(){return!!this._def.checks.find(e=>e.kind===`ip`)}get isCIDR(){return!!this._def.checks.find(e=>e.kind===`cidr`)}get isBase64(){return!!this._def.checks.find(e=>e.kind===`base64`)}get isBase64url(){return!!this._def.checks.find(e=>e.kind===`base64url`)}get minLength(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};Ai.create=e=>new Ai({checks:[],typeName:L.ZodString,coerce:e?.coerce??!1,...F(e)});function ji(e,t){let n=(e.toString().split(`.`)[1]||``).length,r=(t.toString().split(`.`)[1]||``).length,i=n>r?n:r;return Number.parseInt(e.toFixed(i).replace(`.`,``))%Number.parseInt(t.toFixed(i).replace(`.`,``))/10**i}var Mi=class e extends I{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==A.number){let t=this._getOrReturnCtx(e);return M(t,{code:j.invalid_type,expected:A.number,received:t.parsedType}),N}let t,n=new Qr;for(let r of this._def.checks)r.kind===`int`?k.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),M(t,{code:j.invalid_type,expected:`integer`,received:`float`,message:r.message}),n.dirty()):r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),M(t,{code:j.too_small,minimum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),M(t,{code:j.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?ji(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),M(t,{code:j.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),M(t,{code:j.not_finite,message:r.message}),n.dirty()):k.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,P.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,P.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,P.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,P.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:P.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:P.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:P.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:P.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:P.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:P.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:P.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:P.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:P.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:P.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind===`int`||e.kind===`multipleOf`&&k.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks)if(n.kind===`finite`||n.kind===`int`||n.kind===`multipleOf`)return!0;else n.kind===`min`?(t===null||n.value>t)&&(t=n.value):n.kind===`max`&&(e===null||n.value<e)&&(e=n.value);return Number.isFinite(t)&&Number.isFinite(e)}};Mi.create=e=>new Mi({checks:[],typeName:L.ZodNumber,coerce:e?.coerce||!1,...F(e)});var Ni=class e extends I{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==A.bigint)return this._getInvalidInput(e);let t,n=new Qr;for(let r of this._def.checks)r.kind===`min`?(r.inclusive?e.data<r.value:e.data<=r.value)&&(t=this._getOrReturnCtx(e,t),M(t,{code:j.too_small,type:`bigint`,minimum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`max`?(r.inclusive?e.data>r.value:e.data>=r.value)&&(t=this._getOrReturnCtx(e,t),M(t,{code:j.too_big,type:`bigint`,maximum:r.value,inclusive:r.inclusive,message:r.message}),n.dirty()):r.kind===`multipleOf`?e.data%r.value!==BigInt(0)&&(t=this._getOrReturnCtx(e,t),M(t,{code:j.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):k.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return M(t,{code:j.invalid_type,expected:A.bigint,received:t.parsedType}),N}gte(e,t){return this.setLimit(`min`,e,!0,P.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,P.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,P.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,P.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:P.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}positive(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!1,message:P.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:P.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:P.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:P.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:P.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e}};Ni.create=e=>new Ni({checks:[],typeName:L.ZodBigInt,coerce:e?.coerce??!1,...F(e)});var Pi=class extends I{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==A.boolean){let t=this._getOrReturnCtx(e);return M(t,{code:j.invalid_type,expected:A.boolean,received:t.parsedType}),N}return ei(e.data)}};Pi.create=e=>new Pi({typeName:L.ZodBoolean,coerce:e?.coerce||!1,...F(e)});var Fi=class e extends I{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==A.date){let t=this._getOrReturnCtx(e);return M(t,{code:j.invalid_type,expected:A.date,received:t.parsedType}),N}if(Number.isNaN(e.data.getTime()))return M(this._getOrReturnCtx(e),{code:j.invalid_date}),N;let t=new Qr,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),M(n,{code:j.too_small,message:r.message,inclusive:!0,exact:!1,minimum:r.value,type:`date`}),t.dirty()):r.kind===`max`?e.data.getTime()>r.value&&(n=this._getOrReturnCtx(e,n),M(n,{code:j.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):k.assertNever(r);return{status:t.value,value:new Date(e.data.getTime())}}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}min(e,t){return this._addCheck({kind:`min`,value:e.getTime(),message:P.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:P.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind===`min`&&(e===null||t.value>e)&&(e=t.value);return e==null?null:new Date(e)}get maxDate(){let e=null;for(let t of this._def.checks)t.kind===`max`&&(e===null||t.value<e)&&(e=t.value);return e==null?null:new Date(e)}};Fi.create=e=>new Fi({checks:[],coerce:e?.coerce||!1,typeName:L.ZodDate,...F(e)});var Ii=class extends I{_parse(e){if(this._getType(e)!==A.symbol){let t=this._getOrReturnCtx(e);return M(t,{code:j.invalid_type,expected:A.symbol,received:t.parsedType}),N}return ei(e.data)}};Ii.create=e=>new Ii({typeName:L.ZodSymbol,...F(e)});var Li=class extends I{_parse(e){if(this._getType(e)!==A.undefined){let t=this._getOrReturnCtx(e);return M(t,{code:j.invalid_type,expected:A.undefined,received:t.parsedType}),N}return ei(e.data)}};Li.create=e=>new Li({typeName:L.ZodUndefined,...F(e)});var Ri=class extends I{_parse(e){if(this._getType(e)!==A.null){let t=this._getOrReturnCtx(e);return M(t,{code:j.invalid_type,expected:A.null,received:t.parsedType}),N}return ei(e.data)}};Ri.create=e=>new Ri({typeName:L.ZodNull,...F(e)});var zi=class extends I{constructor(){super(...arguments),this._any=!0}_parse(e){return ei(e.data)}};zi.create=e=>new zi({typeName:L.ZodAny,...F(e)});var Bi=class extends I{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ei(e.data)}};Bi.create=e=>new Bi({typeName:L.ZodUnknown,...F(e)});var Vi=class extends I{_parse(e){let t=this._getOrReturnCtx(e);return M(t,{code:j.invalid_type,expected:A.never,received:t.parsedType}),N}};Vi.create=e=>new Vi({typeName:L.ZodNever,...F(e)});var Hi=class extends I{_parse(e){if(this._getType(e)!==A.undefined){let t=this._getOrReturnCtx(e);return M(t,{code:j.invalid_type,expected:A.void,received:t.parsedType}),N}return ei(e.data)}};Hi.create=e=>new Hi({typeName:L.ZodVoid,...F(e)});var Ui=class e extends I{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==A.array)return M(t,{code:j.invalid_type,expected:A.array,received:t.parsedType}),N;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(M(t,{code:e?j.too_big:j.too_small,minimum:i?r.exactLength.value:void 0,maximum:e?r.exactLength.value:void 0,type:`array`,inclusive:!0,exact:!0,message:r.exactLength.message}),n.dirty())}if(r.minLength!==null&&t.data.length<r.minLength.value&&(M(t,{code:j.too_small,minimum:r.minLength.value,type:`array`,inclusive:!0,exact:!1,message:r.minLength.message}),n.dirty()),r.maxLength!==null&&t.data.length>r.maxLength.value&&(M(t,{code:j.too_big,maximum:r.maxLength.value,type:`array`,inclusive:!0,exact:!1,message:r.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((e,n)=>r.type._parseAsync(new ai(t,e,t.path,n)))).then(e=>Qr.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new ai(t,e,t.path,n)));return Qr.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:P.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:P.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:P.toString(n)}})}nonempty(e){return this.min(1,e)}};Ui.create=(e,t)=>new Ui({type:e,minLength:null,maxLength:null,exactLength:null,typeName:L.ZodArray,...F(t)});function Wi(e){if(e instanceof Gi){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=la.create(Wi(r))}return new Gi({...e._def,shape:()=>t})}return e instanceof Ui?new Ui({...e._def,type:Wi(e.element)}):e instanceof la?la.create(Wi(e.unwrap())):e instanceof ua?ua.create(Wi(e.unwrap())):e instanceof Zi?Zi.create(e.items.map(e=>Wi(e))):e}var Gi=class e extends I{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=k.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==A.object){let t=this._getOrReturnCtx(e);return M(t,{code:j.invalid_type,expected:A.object,received:t.parsedType}),N}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Vi&&this._def.unknownKeys===`strip`))for(let e in n.data)i.includes(e)||a.push(e);let o=[];for(let e of i){let t=r[e],i=n.data[e];o.push({key:{status:`valid`,value:e},value:t._parse(new ai(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof Vi){let e=this._def.unknownKeys;if(e===`passthrough`)for(let e of a)o.push({key:{status:`valid`,value:e},value:{status:`valid`,value:n.data[e]}});else if(e===`strict`)a.length>0&&(M(n,{code:j.unrecognized_keys,keys:a}),t.dirty());else if(e!==`strip`)throw Error(`Internal ZodObject error: invalid unknownKeys value.`)}else{let e=this._def.catchall;for(let t of a){let r=n.data[t];o.push({key:{status:`valid`,value:t},value:e._parse(new ai(n,r,n.path,t)),alwaysSet:t in n.data})}}return n.common.async?Promise.resolve().then(async()=>{let e=[];for(let t of o){let n=await t.key,r=await t.value;e.push({key:n,value:r,alwaysSet:t.alwaysSet})}return e}).then(e=>Qr.mergeObjectSync(t,e)):Qr.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return P.errToObj,new e({...this._def,unknownKeys:`strict`,...t===void 0?{}:{errorMap:(e,n)=>{let r=this._def.errorMap?.(e,n).message??n.defaultError;return e.code===`unrecognized_keys`?{message:P.errToObj(t).message??r}:{message:r}}}})}strip(){return new e({...this._def,unknownKeys:`strip`})}passthrough(){return new e({...this._def,unknownKeys:`passthrough`})}extend(t){return new e({...this._def,shape:()=>({...this._def.shape(),...t})})}merge(t){return new e({unknownKeys:t._def.unknownKeys,catchall:t._def.catchall,shape:()=>({...this._def.shape(),...t._def.shape()}),typeName:L.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(t){return new e({...this._def,catchall:t})}pick(t){let n={};for(let e of k.objectKeys(t))t[e]&&this.shape[e]&&(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}omit(t){let n={};for(let e of k.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return Wi(this)}partial(t){let n={};for(let e of k.objectKeys(this.shape)){let r=this.shape[e];n[e]=t&&!t[e]?r:r.optional()}return new e({...this._def,shape:()=>n})}required(t){let n={};for(let e of k.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof la;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return ia(k.objectKeys(this.shape))}};Gi.create=(e,t)=>new Gi({shape:()=>e,unknownKeys:`strip`,catchall:Vi.create(),typeName:L.ZodObject,...F(t)}),Gi.strictCreate=(e,t)=>new Gi({shape:()=>e,unknownKeys:`strict`,catchall:Vi.create(),typeName:L.ZodObject,...F(t)}),Gi.lazycreate=(e,t)=>new Gi({shape:e,unknownKeys:`strip`,catchall:Vi.create(),typeName:L.ZodObject,...F(t)});var Ki=class extends I{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function r(e){for(let t of e)if(t.result.status===`valid`)return t.result;for(let n of e)if(n.result.status===`dirty`)return t.common.issues.push(...n.ctx.common.issues),n.result;let n=e.map(e=>new qr(e.ctx.common.issues));return M(t,{code:j.invalid_union,unionErrors:n}),N}if(t.common.async)return Promise.all(n.map(async e=>{let n={...t,common:{...t.common,issues:[]},parent:null};return{result:await e._parseAsync({data:t.data,path:t.path,parent:n}),ctx:n}})).then(r);{let e,r=[];for(let i of n){let n={...t,common:{...t.common,issues:[]},parent:null},a=i._parseSync({data:t.data,path:t.path,parent:n});if(a.status===`valid`)return a;a.status===`dirty`&&!e&&(e={result:a,ctx:n}),n.common.issues.length&&r.push(n.common.issues)}if(e)return t.common.issues.push(...e.ctx.common.issues),e.result;let i=r.map(e=>new qr(e));return M(t,{code:j.invalid_union,unionErrors:i}),N}}get options(){return this._def.options}};Ki.create=(e,t)=>new Ki({options:e,typeName:L.ZodUnion,...F(t)});const qi=e=>e instanceof na?qi(e.schema):e instanceof ca?qi(e.innerType()):e instanceof ra?[e.value]:e instanceof aa?e.options:e instanceof oa?k.objectValues(e.enum):e instanceof da?qi(e._def.innerType):e instanceof Li?[void 0]:e instanceof Ri?[null]:e instanceof la?[void 0,...qi(e.unwrap())]:e instanceof ua?[null,...qi(e.unwrap())]:e instanceof ma||e instanceof ga?qi(e.unwrap()):e instanceof fa?qi(e._def.innerType):[];var Ji=class e extends I{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==A.object)return M(t,{code:j.invalid_type,expected:A.object,received:t.parsedType}),N;let n=this.discriminator,r=t.data[n],i=this.optionsMap.get(r);return i?t.common.async?i._parseAsync({data:t.data,path:t.path,parent:t}):i._parseSync({data:t.data,path:t.path,parent:t}):(M(t,{code:j.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),N)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(t,n,r){let i=/* @__PURE__ */ new Map;for(let e of n){let n=qi(e.shape[t]);if(!n.length)throw Error(`A discriminator value for key \`${t}\` could not be extracted from all schema options`);for(let r of n){if(i.has(r))throw Error(`Discriminator property ${String(t)} has duplicate value ${String(r)}`);i.set(r,e)}}return new e({typeName:L.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...F(r)})}};function Yi(e,t){let n=Kr(e),r=Kr(t);if(e===t)return{valid:!0,data:e};if(n===A.object&&r===A.object){let n=k.objectKeys(t),r=k.objectKeys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};Object.prototype.hasOwnProperty.call(i,`__proto__`)&&delete i.__proto__;for(let n of r){if(n===`__proto__`)continue;let r=Yi(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}if(n===A.array&&r===A.array){if(e.length!==t.length)return{valid:!1};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=Yi(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}return n===A.date&&r===A.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var Xi=class extends I{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(ti(e)||ti(r))return N;let i=Yi(e.value,r.value);return i.valid?((ni(e)||ni(r))&&t.dirty(),{status:t.value,value:i.data}):(M(n,{code:j.invalid_intersection_types}),N)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([e,t])=>r(e,t)):r(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Xi.create=(e,t,n)=>new Xi({left:e,right:t,typeName:L.ZodIntersection,...F(n)});var Zi=class e extends I{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==A.array)return M(n,{code:j.invalid_type,expected:A.array,received:n.parsedType}),N;if(n.data.length<this._def.items.length)return M(n,{code:j.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),N;!this._def.rest&&n.data.length>this._def.items.length&&(M(n,{code:j.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),t.dirty());let r=[...n.data].map((e,t)=>{let r=this._def.items[t]||this._def.rest;return r?r._parse(new ai(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>Qr.mergeArray(t,e)):Qr.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Zi.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new Zi({items:e,typeName:L.ZodTuple,rest:null,...F(t)})};var Qi=class e extends I{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==A.object)return M(n,{code:j.invalid_type,expected:A.object,received:n.parsedType}),N;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new ai(n,e,n.path,e)),value:a._parse(new ai(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?Qr.mergeObjectAsync(t,r):Qr.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof I?new e({keyType:t,valueType:n,typeName:L.ZodRecord,...F(r)}):new e({keyType:Ai.create(),valueType:t,typeName:L.ZodRecord,...F(n)})}},$i=class extends I{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==A.map)return M(n,{code:j.invalid_type,expected:A.map,received:n.parsedType}),N;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new ai(n,e,n.path,[a,`key`])),value:i._parse(new ai(n,t,n.path,[a,`value`]))}));if(n.common.async){let e=/* @__PURE__ */ new Map;return Promise.resolve().then(async()=>{for(let n of a){let r=await n.key,i=await n.value;if(r.status===`aborted`||i.status===`aborted`)return N;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}})}{let e=/* @__PURE__ */ new Map;for(let n of a){let r=n.key,i=n.value;if(r.status===`aborted`||i.status===`aborted`)return N;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};$i.create=(e,t,n)=>new $i({valueType:t,keyType:e,typeName:L.ZodMap,...F(n)});var ea=class e extends I{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==A.set)return M(n,{code:j.invalid_type,expected:A.set,received:n.parsedType}),N;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(M(n,{code:j.too_small,minimum:r.minSize.value,type:`set`,inclusive:!0,exact:!1,message:r.minSize.message}),t.dirty()),r.maxSize!==null&&n.data.size>r.maxSize.value&&(M(n,{code:j.too_big,maximum:r.maxSize.value,type:`set`,inclusive:!0,exact:!1,message:r.maxSize.message}),t.dirty());let i=this._def.valueType;function a(e){let n=/* @__PURE__ */ new Set;for(let r of e){if(r.status===`aborted`)return N;r.status===`dirty`&&t.dirty(),n.add(r.value)}return{status:t.value,value:n}}let o=[...n.data.values()].map((e,t)=>i._parse(new ai(n,e,n.path,t)));return n.common.async?Promise.all(o).then(e=>a(e)):a(o)}min(t,n){return new e({...this._def,minSize:{value:t,message:P.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:P.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};ea.create=(e,t)=>new ea({valueType:e,minSize:null,maxSize:null,typeName:L.ZodSet,...F(t)});var ta=class e extends I{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==A.function)return M(t,{code:j.invalid_type,expected:A.function,received:t.parsedType}),N;function n(e,n){return Zr({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Xr(),Jr].filter(e=>!!e),issueData:{code:j.invalid_arguments,argumentsError:n}})}function r(e,n){return Zr({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Xr(),Jr].filter(e=>!!e),issueData:{code:j.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof sa){let e=this;return ei(async function(...t){let o=new qr([]),s=await e._def.args.parseAsync(t,i).catch(e=>{throw o.addIssue(n(t,e)),o}),c=await Reflect.apply(a,this,s);return await e._def.returns._def.type.parseAsync(c,i).catch(e=>{throw o.addIssue(r(c,e)),o})})}{let e=this;return ei(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new qr([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new qr([r(s,c.error)]);return c.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...t){return new e({...this._def,args:Zi.create(t).rest(Bi.create())})}returns(t){return new e({...this._def,returns:t})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(t,n,r){return new e({args:t||Zi.create([]).rest(Bi.create()),returns:n||Bi.create(),typeName:L.ZodFunction,...F(r)})}},na=class extends I{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};na.create=(e,t)=>new na({getter:e,typeName:L.ZodLazy,...F(t)});var ra=class extends I{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return M(t,{received:t.data,code:j.invalid_literal,expected:this._def.value}),N}return{status:`valid`,value:e.data}}get value(){return this._def.value}};ra.create=(e,t)=>new ra({value:e,typeName:L.ZodLiteral,...F(t)});function ia(e,t){return new aa({values:e,typeName:L.ZodEnum,...F(t)})}var aa=class e extends I{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return M(t,{expected:k.joinValues(n),received:t.parsedType,code:j.invalid_type}),N}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return M(t,{received:t.data,code:j.invalid_enum_value,options:n}),N}return ei(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(t,n=this._def){return e.create(t,{...this._def,...n})}exclude(t,n=this._def){return e.create(this.options.filter(e=>!t.includes(e)),{...this._def,...n})}};aa.create=ia;var oa=class extends I{_parse(e){let t=k.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==A.string&&n.parsedType!==A.number){let e=k.objectValues(t);return M(n,{expected:k.joinValues(e),received:n.parsedType,code:j.invalid_type}),N}if(this._cache||=new Set(k.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=k.objectValues(t);return M(n,{received:n.data,code:j.invalid_enum_value,options:e}),N}return ei(e.data)}get enum(){return this._def.values}};oa.create=(e,t)=>new oa({values:e,typeName:L.ZodNativeEnum,...F(t)});var sa=class extends I{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==A.promise&&t.common.async===!1)return M(t,{code:j.invalid_type,expected:A.promise,received:t.parsedType}),N;let n=t.parsedType===A.promise?t.data:Promise.resolve(t.data);return ei(n.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};sa.create=(e,t)=>new sa({type:e,typeName:L.ZodPromise,...F(t)});var ca=class extends I{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===L.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=this._def.effect||null,i={addIssue:e=>{M(n,e),e.fatal?t.abort():t.dirty()},get path(){return n.path}};if(i.addIssue=i.addIssue.bind(i),r.type===`preprocess`){let e=r.transform(n.data,i);if(n.common.async)return Promise.resolve(e).then(async e=>{if(t.value===`aborted`)return N;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?N:r.status===`dirty`||t.value===`dirty`?$r(r.value):r});{if(t.value===`aborted`)return N;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?N:r.status===`dirty`||t.value===`dirty`?$r(r.value):r}}if(r.type===`refinement`){let e=e=>{let t=r.refinement(e,i);if(n.common.async)return Promise.resolve(t);if(t instanceof Promise)throw Error(`Async refinement encountered during synchronous parse operation. Use .parseAsync instead.`);return e};if(n.common.async===!1){let r=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return r.status===`aborted`?N:(r.status===`dirty`&&t.dirty(),e(r.value),{status:t.value,value:r.value})}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(n=>n.status===`aborted`?N:(n.status===`dirty`&&t.dirty(),e(n.value).then(()=>({status:t.value,value:n.value}))))}if(r.type===`transform`){if(n.common.async===!1){let e=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!ri(e))return N;let a=r.transform(e.value,i);if(a instanceof Promise)throw Error(`Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.`);return{status:t.value,value:a}}return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(e=>ri(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):N)}k.assertNever(r)}};ca.create=(e,t,n)=>new ca({schema:e,typeName:L.ZodEffects,effect:t,...F(n)}),ca.createWithPreprocess=(e,t,n)=>new ca({schema:t,effect:{type:`preprocess`,transform:e},typeName:L.ZodEffects,...F(n)});var la=class extends I{_parse(e){return this._getType(e)===A.undefined?ei(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};la.create=(e,t)=>new la({innerType:e,typeName:L.ZodOptional,...F(t)});var ua=class extends I{_parse(e){return this._getType(e)===A.null?ei(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ua.create=(e,t)=>new ua({innerType:e,typeName:L.ZodNullable,...F(t)});var da=class extends I{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===A.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};da.create=(e,t)=>new da({innerType:e,typeName:L.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...F(t)});var fa=class extends I{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},r=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return ii(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new qr(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new qr(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};fa.create=(e,t)=>new fa({innerType:e,typeName:L.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...F(t)});var pa=class extends I{_parse(e){if(this._getType(e)!==A.nan){let t=this._getOrReturnCtx(e);return M(t,{code:j.invalid_type,expected:A.nan,received:t.parsedType}),N}return{status:`valid`,value:e.data}}};pa.create=e=>new pa({typeName:L.ZodNaN,...F(e)});var ma=class extends I{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},ha=class e extends I{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let e=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?N:e.status===`dirty`?(t.dirty(),$r(e.value)):this._def.out._parseAsync({data:e.value,path:n.path,parent:n})})();{let e=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return e.status===`aborted`?N:e.status===`dirty`?(t.dirty(),{status:`dirty`,value:e.value}):this._def.out._parseSync({data:e.value,path:n.path,parent:n})}}static create(t,n){return new e({in:t,out:n,typeName:L.ZodPipeline})}},ga=class extends I{_parse(e){let t=this._def.innerType._parse(e),n=e=>(ri(e)&&(e.value=Object.freeze(e.value)),e);return ii(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};ga.create=(e,t)=>new ga({innerType:e,typeName:L.ZodReadonly,...F(t)}),Gi.lazycreate;var L;(function(e){e.ZodString=`ZodString`,e.ZodNumber=`ZodNumber`,e.ZodNaN=`ZodNaN`,e.ZodBigInt=`ZodBigInt`,e.ZodBoolean=`ZodBoolean`,e.ZodDate=`ZodDate`,e.ZodSymbol=`ZodSymbol`,e.ZodUndefined=`ZodUndefined`,e.ZodNull=`ZodNull`,e.ZodAny=`ZodAny`,e.ZodUnknown=`ZodUnknown`,e.ZodNever=`ZodNever`,e.ZodVoid=`ZodVoid`,e.ZodArray=`ZodArray`,e.ZodObject=`ZodObject`,e.ZodUnion=`ZodUnion`,e.ZodDiscriminatedUnion=`ZodDiscriminatedUnion`,e.ZodIntersection=`ZodIntersection`,e.ZodTuple=`ZodTuple`,e.ZodRecord=`ZodRecord`,e.ZodMap=`ZodMap`,e.ZodSet=`ZodSet`,e.ZodFunction=`ZodFunction`,e.ZodLazy=`ZodLazy`,e.ZodLiteral=`ZodLiteral`,e.ZodEnum=`ZodEnum`,e.ZodEffects=`ZodEffects`,e.ZodNativeEnum=`ZodNativeEnum`,e.ZodOptional=`ZodOptional`,e.ZodNullable=`ZodNullable`,e.ZodDefault=`ZodDefault`,e.ZodCatch=`ZodCatch`,e.ZodPromise=`ZodPromise`,e.ZodBranded=`ZodBranded`,e.ZodPipeline=`ZodPipeline`,e.ZodReadonly=`ZodReadonly`})(L||={}),Ai.create,Mi.create,pa.create,Ni.create,Pi.create,Fi.create,Ii.create,Li.create,Ri.create,zi.create,Bi.create,Vi.create,Hi.create,Ui.create;const _a=Gi.create;Gi.strictCreate,Ki.create,Ji.create,Xi.create,Zi.create,Qi.create,$i.create,ea.create,ta.create,na.create,ra.create,aa.create,oa.create,sa.create,ca.create,la.create,ua.create,ca.createWithPreprocess,ha.create;function va(e){let t=Object.values(e).filter(e=>typeof e==`number`);return Object.entries(e).filter(([e,n])=>t.indexOf(+e)===-1).map(([e,t])=>t)}function ya(e,t=`|`){return e.map(e=>Wa(e)).join(t)}function ba(e,t){return typeof t==`bigint`?t.toString():t}var xa=class{constructor(e){this._getter=e,this._value=void 0}get value(){let e=this._getter;return e!==void 0&&(this._value=e(),this._getter=void 0),this._value}};function Sa(e){return new xa(e)}function Ca(e){return e==null}function wa(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function Ta(e,t){let n=e/t,r=Math.round(n),i=4*2**-52*Math.max(Math.abs(n),1);return Math.abs(n-r)<i?0:n-r}function Ea(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Da(e){let t=Object.getOwnPropertyDescriptor(e,`shape`);return t?.get?t.get.raw:t?.value}function Oa(e){return Da(e._zod.def)??e._zod.def.shape}function ka(e,t,n){Object.defineProperty(e,t,{get(){let e=n();return Ea(this,t,e),e},enumerable:!0,configurable:!0})}function Aa(e,t,n){t in e?Ea(e,t,n):e[t]=n}function ja(e,t,n,r){let i=Oa(t);for(let a of n){let n=Object.getOwnPropertyDescriptor(i,a);n.enumerable&&(n.get?ka(e,a,()=>{let e=t._zod.def.shape[a];return r?r(e,a):e}):Aa(e,a,r?r(n.value,a):n.value))}}function Ma(e,t){for(let n of Reflect.ownKeys(t)){let r=Object.getOwnPropertyDescriptor(t,n);r.enumerable&&(r.get?ka(e,n,()=>t[n]):Aa(e,n,r.value))}}function Na(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function Pa(e){return JSON.stringify(e)}function Fa(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}const Ia=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function La(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Ra=/* @__PURE__*/ Sa(()=>{if(No.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function za(e){if(La(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return La(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}function Ba(e){return za(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const Va=/* @__PURE__*/ new Set([`string`,`number`,`symbol`]);function Ha(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Ua(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function R(e){let t=e;if(!t)return{};if(typeof t==`string`)return{error:()=>t};if(t?.message!==void 0){if(t?.error!==void 0)throw Error("Cannot specify both `message` and `error` params");t.error=t.message}return delete t.message,typeof t.error==`string`?{...t,error:()=>t.error}:t}function Wa(e){return typeof e==`bigint`?e.toString()+`n`:typeof e==`string`?`"${e}"`:`${e}`}function Ga(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout===`optional`)}const Ka={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},qa={int64:[/* @__PURE__*/ BigInt(`-9223372036854775808`),/* @__PURE__*/ BigInt(`9223372036854775807`)],uint64:[/* @__PURE__*/ BigInt(0),/* @__PURE__*/ BigInt(`18446744073709551615`)]};function Ja(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.pick() cannot be used on object schemas containing refinements`);let i={};return ja(i,e,Ya(e,t)),Ua(e,Na(n,{shape:i,checks:[]}))}function Ya(e,t){let n=Oa(e),r=[];for(let e of Reflect.ownKeys(t)){if(!Object.getOwnPropertyDescriptor(n,e)?.enumerable)throw Error(`Unrecognized key: "${String(e)}"`);t[e]&&r.push(e)}return r}function Xa(e,t){let n=e._zod.def,r=n.checks;if(r&&r.length>0)throw Error(`.omit() cannot be used on object schemas containing refinements`);let i=new Set(Ya(e,t)),a={};return ja(a,e,Reflect.ownKeys(Oa(e)).filter(e=>!i.has(e))),Ua(e,Na(n,{shape:a,checks:[]}))}function Za(e,t){if(!za(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=Oa(e);for(let e of Reflect.ownKeys(t))if(Object.getOwnPropertyDescriptor(n,e)!==void 0)throw Error("Cannot overwrite keys on object schemas containing refinements. Use `.safeExtend()` instead.")}return Ua(e,Na(e._zod.def,{shape:Qa(e,t)}))}function Qa(e,t){let n={};return ja(n,e,Reflect.ownKeys(Oa(e))),Ma(n,t),n}function $a(e,t){if(!za(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return Ua(e,Na(e._zod.def,{shape:Qa(e,t)}))}function eo(e,t){if(!t?._zod?.def)throw Error("Invalid input to merge: expected an object schema. To merge a plain shape, use `.extend()`.");if(e._zod.def.checks?.length)throw Error(`.merge() cannot be used on object schemas containing refinements. Use .safeExtend() instead.`);let n={};return ja(n,e,Reflect.ownKeys(Oa(e))),ja(n,t,Reflect.ownKeys(Oa(t))),Ua(e,Na(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function to(e,t,n,r=`partial`){let i=t._zod.def.checks;if(i&&i.length>0)throw Error(`.${r}() cannot be used on object schemas containing refinements`);let a=n?new Set(Ya(t,n)):void 0,o={};return ja(o,t,Reflect.ownKeys(Oa(t)),e&&((t,n)=>a&&!a.has(n)?t:new e({type:`optional`,innerType:t}))),Ua(t,Na(t._zod.def,{shape:o,checks:[]}))}function no(e,t,n){let r=n?new Set(Ya(t,n)):void 0,i={};return ja(i,t,Reflect.ownKeys(Oa(t)),(t,n)=>r&&!r.has(n)?t:new e({type:`nonoptional`,innerType:t})),Ua(t,Na(t._zod.def,{shape:i}))}function ro(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue!==!0)return!0;return!1}function io(e,t=0){if(e.aborted===!0)return!0;for(let n=t;n<e.issues.length;n++)if(e.issues[n]?.continue===!1)return!0;return!1}function ao(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function oo(e){return typeof e==`string`?e:e?.message}function so(e){let t=[];for(let n of e??[]){let e=n._zod.def;if(!/_(length|size)$|_equals$/.test(e.check))break;let r=e.maximum??e.length??e.size;r>=0&&t.push([r,n])}return t}function co(e,t,n){var r;for(let i=t;i<e.length;i++)(r=e[i]).schema??(r.schema=n)}function lo(e,t,n){var r;let i=e.inst?._zod?.traits;i?.has(`$ZodType`)&&(i.has(`$ZodCheck`)?(r=e).schema??(r.schema=e.inst):e.schema=e.inst);let a=e.schema===e.inst?void 0:e.schema?._zod.def?.error,o=e.message?e.message:oo(e.inst?._zod.def?.error?.(e))??oo(a?.(e))??oo(t?.error?.(e))??oo(n.customError?.(e))??oo(n.localeError?.(e))??`Invalid input`,s={};for(let t of Object.keys(e))t!==`inst`&&t!==`schema`&&t!==`continue`&&t!==`input`&&t!==`__proto__`&&(s[t]=e[t]);return s.path??=[],s.message=o,t?.reportInput&&(s.input=e.input),s}const uo=/[\uD800-\uDBFF]/;function fo(e){let t=e.length;if(!uo.test(e))return t;let n=t;for(let r=0;r<t-1;r++)(e.charCodeAt(r)&64512)==55296&&(e.charCodeAt(r+1)&64512)==56320&&(n--,r++);return n}function po(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function mo(e){let t=typeof e;switch(t){case`number`:return Number.isNaN(e)?`nan`:`number`;case`object`:{if(e===null)return`null`;if(Array.isArray(e))return`array`;let t=e;if(t&&Object.getPrototypeOf(t)!==Object.prototype&&`constructor`in t&&t.constructor)return t.constructor.name}}return t}function ho(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}function go(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);r.get?Object.defineProperty(e,n,{...r,enumerable:!1}):bo(e,n,r.value)}}function _o(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function vo(e,t,n){return _o(e,t,n,!1)}/* @__NO_SIDE_EFFECTS__ */
15
+ function yo(e,t){for(let n in e){let r=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return _o(this,n,r(this))},set(e){_o(this,n,e)}})}return t}function bo(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:_o(this,t,n.bind(this))},set(e){_o(this,t,e)}})}function xo(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}let So,Co=!1;const wo={configurable:!0,get(){Co=!0}};function z(e,t,n){let r=Object.getPrototypeOf(e._zod);t in r&&So!==e._zod?So=void 0:(So=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,wo);let e=Co;Co=!1;try{let r=n(this);return Co?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:r}),Co||=e,r}catch(n){throw delete this[t],Co||=e,n}},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}}))}function To(e,t,n,r){let i=xo(e,t);i&&Object.defineProperty(i,t,{configurable:!0,get(){let e={configurable:!0,writable:!0,enumerable:r,value:void 0};return Object.defineProperty(this,t,e),e.value=n(this),Object.defineProperty(this,t,e),e.value},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,enumerable:r,value:e})}})}function Eo(e){let t=()=>e;return t[`~constantCatch`]=!0,t}var Do;const Oo={value:void 0,enumerable:!1};let ko=`captureStackTrace`in Error?Error:null;function Ao(e){let t=ko;if(t){let n=t.stackTraceLimit;if(typeof n==`number`){try{t.stackTraceLimit=0}catch{return ko=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}/* @__NO_SIDE_EFFECTS__ */
16
+ function B(e,t,n,r){let i={};function a(e){this.def=e,this.constr=d,this.traits=/* @__PURE__ */ new Set}a.prototype=i;let o=n,s=o&&/* @__PURE__ */ new WeakSet;function c(n,r){if(!n._zod){Oo.value=new a(r);try{Object.defineProperty(n,"_zod",Oo)}finally{Oo.value=void 0}}else if(n._zod.traits.has(e))return;if(n._zod.traits.add(e),t(n,r),s){let e=Object.getPrototypeOf(n),t=n._zod.constr.prototype,r=e;for(;r&&r!==t;)r=Object.getPrototypeOf(r);let i=r??e;s.has(i)||(s.add(i),go(i,o))}let i=d.prototype;for(let e in i)Object.prototype.hasOwnProperty.call(i,e)&&(e in n||(n[e]=i[e].bind(n)))}let l=r?.Parent??Object;class u extends l{}Object.defineProperty(u,"name",{value:e});function d(e){let t=r?.Parent?Ao(u):this;c(t,e);let n=t._zod.deferred;if(n){for(let e of n)e();t._zod.deferred=void 0}let i=globalThis.__zod_globalConfig?.postProcessor;return i&&i(t),t}return Object.defineProperty(d,"init",{value:c}),Object.defineProperty(d,Symbol.hasInstance,{value:t=>r?.Parent&&t instanceof r.Parent?!0:t?._zod?.traits?.has(e)}),Object.defineProperty(d,"name",{value:e}),d}var jo=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},Mo=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(Do=globalThis).__zod_globalConfig??(Do.__zod_globalConfig={});const No=globalThis.__zod_globalConfig;function Po(e){return e&&Object.assign(No,e),No}function Fo(){let e=this._zod;return e.message??=JSON.stringify(e.def,ba,2),e.message}function Io(e){this._zod.message=e}const Lo={get:Fo,set:Io,enumerable:!0,configurable:!0},Ro={value:void 0,enumerable:!1},zo=/* @__PURE__ */ new WeakSet([Object.prototype,Error.prototype]),Bo=(e,t)=>{e.name=`$ZodError`,Ro.value=t,Object.defineProperty(e,"issues",Ro),Ro.value=void 0,Object.defineProperty(e,"message",Lo);let n=Object.getPrototypeOf(e);zo.has(n)||(zo.add(n),Object.defineProperty(n,"toString",{configurable:!0,enumerable:!1,get(){let e=()=>this.message;return Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,"toString",{value:e,configurable:!0,writable:!0})}}))},Vo=/* @__PURE__ */ B(`$ZodError`,Bo),Ho=/* @__PURE__ */ B(`$ZodError`,Bo,void 0,{Parent:Error});function Uo(e,t,n){return Object.prototype.hasOwnProperty.call(e,t)||(t===`__proto__`?Object.defineProperty(e,t,{value:n(),writable:!0,enumerable:!0,configurable:!0}):e[t]=n()),e[t]}function Wo(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?Uo(n,i.path[0],()=>[]).push(t(i)):r.push(t(i));return{formErrors:r,fieldErrors:n}}function Go(e,t=e=>e.message){let n={_errors:[]},r=(e,i=[])=>{for(let a of e.issues)if(a.code===`invalid_union`&&a.errors.length)a.errors.map(e=>r({issues:e},[...i,...a.path]));else if(a.code===`invalid_key`)r({issues:a.issues},[...i,...a.path]);else if(a.code===`invalid_element`)r({issues:a.issues},[...i,...a.path]);else{let e=[...i,...a.path];if(e.length===0)n._errors.push(t(a));else{let r=n,i=0;for(;i<e.length;){let n=e[i],o=i===e.length-1;if(n===`_errors`){o&&r._errors.push(t(a)),i++;continue}Object.prototype.hasOwnProperty.call(r,n)||Object.defineProperty(r,n,{value:{_errors:[]},enumerable:!0,writable:!0,configurable:!0});let s=r[n];o&&s._errors.push(t(a)),r=s,i++}}}};return r(e),n}function Ko(e,t){return{callee:t?.callee??e,Err:t?.Err}}const qo=e=>{let t=(n,r,i,a)=>{let o=i?{...i,async:!1}:{async:!1},s=n._zod.run({value:r,issues:[]},o);if(s instanceof Promise)throw new jo;if(s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>lo(e,o,Po())));throw Ia(n,a?.callee??t),n}return s.value};return t},Jo=/* @__PURE__*/ qo(Ho),Yo=e=>{let t=async(n,r,i,a)=>{let o=i?{...i,async:!0}:{async:!0},s=n._zod.run({value:r,issues:[]},o);if(s instanceof Promise&&(s=await s),s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>lo(e,o,Po())));throw Ia(n,a?.callee??t),n}return s.value};return t},Xo=/* @__PURE__*/ Yo(Ho),Zo=e=>(t,n,r)=>{let i=r?{...r,async:!1}:{async:!1},a=t._zod.run({value:n,issues:[]},i);if(a instanceof Promise)throw new jo;return a.issues.length?$o(e,a.issues,i):{success:!0,data:a.value}},Qo=/* @__PURE__*/ Zo(Ho);function $o(e,t,n){let r;return{success:!1,get error(){return r||(r=new e(t.map(e=>lo(e,n,Po()))),t=void 0,n=void 0),r},set error(e){r=e,t=void 0,n=void 0}}}const es=e=>async(t,n,r)=>{let i=r?{...r,async:!0}:{async:!0},a=t._zod.run({value:n,issues:[]},i);return a instanceof Promise&&(a=await a),a.issues.length?$o(e,a.issues,i):{success:!0,data:a.value}},ts=/* @__PURE__*/ es(Ho),ns=/* @__PURE__ */ Symbol.for(`zod.compile.invalid`),rs=/* @__PURE__ */ Symbol.for(`zod.compile.fallback`),is=((e,t,n)=>{let r=e._zod.bag.validator;if(r!==void 0){if(r(t)!==ns)return!0;if(r.definite===!0&&n===void 0)return!1}return as(e,t,n)});function as(e,t,n){let r=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},i=e._zod.bag.fallbackRun,a;if(i?(r[rs]=!0,a=i({value:t,issues:[]},r)):a=e._zod.run({value:t,issues:[]},r),a instanceof Promise)throw new jo;return a.issues.length===0}const os=async(e,t,n)=>{let r=n?{...n,async:!0,abortEarly:!0}:{async:!0,abortEarly:!0},i=e._zod.run({value:t,issues:[]},r);return i instanceof Promise&&(i=await i),i.issues.length===0},ss=e=>{let t=qo(e),n=(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return t(e,r,o,Ko(n,a))};return n},cs=e=>{let t=qo(e),n=(e,r,i,a)=>t(e,r,i,Ko(n,a));return n},ls=e=>{let t=Yo(e),n=async(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return await t(e,r,o,Ko(n,a))};return n},us=e=>{let t=Yo(e),n=async(e,r,i,a)=>await t(e,r,i,Ko(n,a));return n},ds=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Zo(e)(t,n,i)},fs=e=>(t,n,r)=>Zo(e)(t,n,r),ps=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return es(e)(t,n,i)},ms=e=>async(t,n,r)=>es(e)(t,n,r),hs=/^[cC][0-9a-z]{6,}$/,gs=/^[0-9a-z]+$/,_s=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,vs=/^[0-9a-vA-V]{20}$/,ys=/^[A-Za-z0-9]{27}$/,bs=/^[a-zA-Z0-9_-]{21}$/;function xs(e){return RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}const Ss=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Cs=/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})$/,ws=e=>e?RegExp(`^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-${e}[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12})$`):/^([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[1-8][0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/,Ts=/^(?:[A-Za-z0-9_'+\-]+\.)*[A-Za-z0-9_'+\-]*[A-Za-z0-9_+-]@(?:[A-Za-z0-9][A-Za-z0-9\-]*\.)+[A-Za-z]{2,}$/;function Es(){return RegExp(`^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`,`u`)}const Ds=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Os=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))$/,ks=/^((25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/([0-9]|[1-2][0-9]|3[0-2])$/,As=/^(([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,js=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ms=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,Ns=/^https?$/,Ps=/^\+[1-9]\d{6,14}$/,Fs=`(?:(?:\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-(?:(?:0[13578]|1[02])-(?:0[1-9]|[12]\\d|3[01])|(?:0[469]|11)-(?:0[1-9]|[12]\\d|30)|(?:02)-(?:0[1-9]|1\\d|2[0-8])))`;function Is(e){return RegExp(`^${e}$`)}const Ls=/*@__PURE__*/ Is(Fs);function Rs(e){let t=`(?:[01]\\d|2[0-3]):[0-5]\\d`;return typeof e.precision==`number`?e.precision===-1?`${t}`:e.precision===0?`${t}:[0-5]\\d`:`${t}:[0-5]\\d\\.\\d{${e.precision}}`:e.seconds?`${t}:[0-5]\\d(?:\\.\\d+)?`:`${t}(?::[0-5]\\d(?:\\.\\d+)?)?`}function zs(e){return RegExp(`^${Rs(e)}$`)}function Bs(e){let t=[`Z`];e.offset&&t.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let n=`${Rs({precision:e.precision,seconds:!0})}(?:${t.join(`|`)})`,r=e.local?`${n}|${Rs({precision:e.precision})}`:n;return RegExp(`^${Fs}T(?:${r})$`)}const Vs=/^[\s\S]{0,}$/,Hs=/^-?\d+$/,Us=/^-?\d+(?:\.\d+)?$/,Ws=/^(?:true|false)$/i,Gs=/^null$/i,Ks=/^[^A-Z]*$/,qs=/^[^a-z]*$/,Js=/*@__PURE__*/ B(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Ys=e=>{let t=e.value;return!Ca(t)&&t.length!==void 0},Xs={number:`number`,bigint:`bigint`,object:`date`},Zs=/*@__PURE__*/ B(`$ZodCheckLessThan`,(e,t)=>{Js.init(e,t);let n=Xs[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:Xs[typeof r.value]??n,code:`too_big`,maximum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),Qs=/*@__PURE__*/ B(`$ZodCheckGreaterThan`,(e,t)=>{Js.init(e,t);let n=Xs[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:Xs[typeof r.value]??n,code:`too_small`,minimum:typeof t.value==`object`?t.value.getTime():t.value,input:r.value,inclusive:t.inclusive,inst:e,continue:!t.abort})}}),$s=/*@__PURE__*/ B(`$ZodCheckMultipleOf`,(e,t)=>{Js.init(e,t),e._zod.check=n=>{if(typeof n.value!=typeof t.value)throw Error(`Cannot mix number and bigint in multiple_of check.`);(typeof n.value==`bigint`?t.value!==BigInt(0)&&n.value%t.value===BigInt(0):Ta(n.value,t.value)===0)||n.issues.push({origin:typeof n.value,code:`not_multiple_of`,divisor:t.value,input:n.value,inst:e,continue:!t.abort})}}),ec=/*@__PURE__*/ B(`$ZodCheckNumberFormat`,(e,t)=>{Js.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=Ka[t.format];e._zod.check=o=>{let s=o.value;if(n){if(!Number.isInteger(s)){o.issues.push({expected:r,format:t.format,code:`invalid_type`,continue:!1,input:s,inst:e});return}if(!Number.isSafeInteger(s)){s>0?o.issues.push({input:s,code:`too_big`,maximum:2**53-1,note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort}):o.issues.push({input:s,code:`too_small`,minimum:-(2**53-1),note:`Integers must be within the safe integer range.`,inst:e,origin:r,inclusive:!0,continue:!t.abort});return}}s<i&&o.issues.push({origin:`number`,input:s,code:`too_small`,minimum:i,inclusive:!0,inst:e,continue:!t.abort}),s>a&&o.issues.push({origin:`number`,input:s,code:`too_big`,maximum:a,inclusive:!0,inst:e,continue:!t.abort})}}),tc=/*@__PURE__*/ B(`$ZodCheckMaxLength`,(e,t)=>{var n;Js.init(e,t),(n=e._zod.def).when??(n.when=Ys),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>t.maximum?fo(r):i)<=t.maximum)return;let a=po(r);n.issues.push({origin:a,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),nc=/*@__PURE__*/ B(`$ZodCheckMinLength`,(e,t)=>{var n;Js.init(e,t),(n=e._zod.def).when??(n.when=Ys),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>=t.minimum&&i<t.minimum*2?fo(r):i)>=t.minimum)return;let a=po(r);n.issues.push({origin:a,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),rc=/*@__PURE__*/ B(`$ZodCheckLengthEquals`,(e,t)=>{var n;Js.init(e,t),(n=e._zod.def).when??(n.when=Ys),e._zod.check=n=>{let r=n.value,i=r.length,a=typeof r==`string`&&i>=t.length&&i<=t.length*2?fo(r):i;if(a===t.length)return;let o=po(r),s=a>t.length;n.issues.push({origin:o,...s?{code:`too_big`,maximum:t.length}:{code:`too_small`,minimum:t.length},inclusive:!0,exact:!0,input:n.value,inst:e,continue:!t.abort})}}),ic=/*@__PURE__*/ B(`$ZodCheckStringFormat`,(e,t)=>{var n,r;Js.init(e,t),t.pattern?(n=e._zod).check??(n.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:t.format,input:n.value,...t.pattern?{pattern:t.pattern.toString()}:{},inst:e,continue:!t.abort})}):(r=e._zod).check??(r.check=()=>{})}),ac=/*@__PURE__*/ B(`$ZodCheckRegex`,(e,t)=>{ic.init(e,t),e._zod.check=n=>{t.pattern.lastIndex=0,!t.pattern.test(n.value)&&n.issues.push({origin:`string`,code:`invalid_format`,format:`regex`,input:n.value,pattern:t.pattern.toString(),inst:e,continue:!t.abort})}}),oc=/*@__PURE__*/ B(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=Ks,ic.init(e,t)}),sc=/*@__PURE__*/ B(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=qs,ic.init(e,t)}),cc=/*@__PURE__*/ B(`$ZodCheckIncludes`,(e,t)=>{Js.init(e,t);let n=Ha(t.includes);t.pattern=new RegExp(typeof t.position==`number`?`^.{${t.position},}${n}`:n),e._zod.check=n=>{n.value.includes(t.includes,t.position)||n.issues.push({origin:`string`,code:`invalid_format`,format:`includes`,includes:t.includes,input:n.value,inst:e,continue:!t.abort})}}),lc=/*@__PURE__*/ B(`$ZodCheckStartsWith`,(e,t)=>{Js.init(e,t);let n=RegExp(`^${Ha(t.prefix)}.*`);t.pattern??=n,e._zod.check=n=>{n.value.startsWith(t.prefix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`starts_with`,prefix:t.prefix,input:n.value,inst:e,continue:!t.abort})}}),uc=/*@__PURE__*/ B(`$ZodCheckEndsWith`,(e,t)=>{Js.init(e,t);let n=RegExp(`.*${Ha(t.suffix)}$`);t.pattern??=n,e._zod.check=n=>{n.value.endsWith(t.suffix)||n.issues.push({origin:`string`,code:`invalid_format`,format:`ends_with`,suffix:t.suffix,input:n.value,inst:e,continue:!t.abort})}}),dc=/*@__PURE__*/ B(`$ZodCheckOverwrite`,(e,t)=>{Js.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var fc=class{constructor(e=[],t={}){this.content=[],this.indent=0,this.args=e,this.closed=t}indented(e){this.indent+=1;try{e(this)}finally{--this.indent}}write(e){if(typeof e==`function`){e(this,{execution:`sync`}),e(this,{execution:`async`});return}let t=e.split(`
17
+ `).filter(e=>e),n=Math.min(...t.map(e=>e.length-e.trimStart().length)),r=t.map(e=>e.slice(n)).map(e=>` `.repeat(this.indent*2)+e);for(let e of r)this.content.push(e)}compile(){let e=Function,t=this?.content??[``];return new e(...Object.keys(this.closed),`return function (${this.args.join(`, `)}) {\n${t.join(`
18
+ `)}\n};`)(...Object.values(this.closed))}};const pc={major:4,minor:6,patch:7},mc=/*@__PURE__*/ B(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=pc;let r=e._zod.def.checks,i=e._zod.traits.has(`$ZodCheck`)?[e,...r??[]]:r?.length?[...r]:[];for(let t of i)for(let n of t._zod.onattach)n(e);if(i.length===0)(n=e._zod).deferred??(n.deferred=[]),e._zod.deferred?.push(()=>{e._zod.run=e._zod.parse});else{let t=(t,n,r)=>{if(t.memo)return t;let i=ro(t),a;for(let o of n){if(o._zod.def.when){if(io(t)||!o._zod.def.when(t))continue}else if(i)continue;let n=t.issues.length,s=o._zod.check(t);if(s instanceof Promise&&r?.async===!1)throw new jo;if(a||s instanceof Promise)a=(a??Promise.resolve()).then(async()=>{await s,t.issues.length!==n&&(co(t.issues,n,e),i||=ro(t,n))});else{if(t.issues.length===n)continue;co(t.issues,n,e),i||=ro(t,n)}}return a?a.then(()=>t):t},n=(n,r,a)=>{if(ro(n))return n.aborted=!0,n;let o=t(r,i,a);if(o instanceof Promise){if(a.async===!1)throw new jo;return o.then(t=>e._zod.parse(t,a))}return e._zod.parse(o,a)};e._zod.run=(r,a)=>{if(a.skipChecks)return e._zod.parse(r,a);if(a.direction===`backward`){let t=e._zod.parse({value:r.value,issues:[]},{...a,skipChecks:!0});return t instanceof Promise?t.then(e=>n(e,r,a)):n(t,r,a)}let o=e._zod.parse(r,a);if(o instanceof Promise){if(a.async===!1)throw new jo;return o.then(e=>t(e,i,a))}return t(o,i,a)}}},{get"~standard"(){return vo(this,`~standard`,_c(this))},set"~standard"(e){_o(this,`~standard`,e)}}),hc=(e,t)=>e.issues.length?{issues:e.issues.map(e=>lo(e,t,Po()))}:{value:e.value};async function gc(e,t){let n={async:!0};return hc(await e._zod.run({value:t,issues:[]},n),n)}function _c(e){return{validate:t=>{let n={async:!1};try{let r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return hc(r,n)}catch{}return gc(e,t)},vendor:`zod`,version:1}}const vc=/*@__PURE__*/ B(`$ZodString`,(e,t)=>{mc.init(e,t),e._zod.pattern=t.pattern??Vs,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=String(n.value)}catch{}return typeof n.value==`string`||n.issues.push({expected:`string`,code:`invalid_type`,input:n.value,inst:e}),n}}),yc=/*@__PURE__*/ B(`$ZodStringFormat`,(e,t)=>{ic.init(e,t),vc.init(e,t)}),bc=/*@__PURE__*/ B(`$ZodGUID`,(e,t)=>{t.pattern??=Cs,yc.init(e,t)}),xc=/*@__PURE__*/ B(`$ZodUUID`,(e,t)=>{if(t.version){let e={v1:1,v2:2,v3:3,v4:4,v5:5,v6:6,v7:7,v8:8}[t.version];if(e===void 0)throw Error(`Invalid UUID version: "${t.version}"`);t.pattern??=ws(e)}else t.pattern??=ws();yc.init(e,t)}),Sc=/*@__PURE__*/ B(`$ZodEmail`,(e,t)=>{t.pattern??=Ts,yc.init(e,t)});function Cc(e){try{return typeof URL<`u`&&typeof URL.canParse==`function`?URL.canParse(e):(new URL(e),!0)}catch{return!1}}function wc(e,t){return!(`normalize`in t)&&!(`hostname`in t)&&!(`protocol`in t)?Cc(e)||2:Tc(e,t)}function Tc(e,t){if(!t.normalize&&t.protocol?.source===Ns.source&&!/^https?:\/\//i.test(e))return 1;try{if(typeof URL<`u`){let t=URL;if(typeof t.parse==`function`)return t.parse(e)??2}return new URL(e)}catch{return 2}}const Ec=/[\t\n\r]/g;function Dc(e){return e.replace(Ec,``)}function Oc(e,t){return t.lastIndex=0,t.test(e.hostname)}function kc(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(`:`)?e.protocol.slice(0,-1):e.protocol)}const Ac=/*@__PURE__*/ B(`$ZodURL`,(e,t)=>{yc.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),i=wc(r,t);if(i===1){n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid URL format`,input:n.value,inst:e,continue:!t.abort});return}if(i===2){n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort});return}if(i===!0){n.value=Dc(r);return}t.hostname&&!Oc(i,t.hostname)&&n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid hostname`,pattern:t.hostname.source,input:n.value,inst:e,continue:!t.abort}),t.protocol&&!kc(i,t.protocol)&&n.issues.push({code:`invalid_format`,format:`url`,note:`Invalid protocol`,pattern:t.protocol.source,input:n.value,inst:e,continue:!t.abort}),n.value=t.normalize?i.href:Dc(r);return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),jc=/*@__PURE__*/ B(`$ZodEmoji`,(e,t)=>{t.pattern??=Es(),yc.init(e,t)}),Mc=/*@__PURE__*/ B(`$ZodNanoID`,(e,t)=>{if(t.length!==void 0&&(!Number.isInteger(t.length)||t.length<1))throw Error(`Invalid nanoid length: ${t.length}`);t.pattern??=t.length===void 0?bs:xs(t.length),yc.init(e,t)}),Nc=/*@__PURE__*/ B(`$ZodCUID`,(e,t)=>{t.pattern??=hs,yc.init(e,t)}),Pc=/*@__PURE__*/ B(`$ZodCUID2`,(e,t)=>{t.pattern??=gs,yc.init(e,t)}),Fc=/*@__PURE__*/ B(`$ZodULID`,(e,t)=>{t.pattern??=_s,yc.init(e,t)}),Ic=/*@__PURE__*/ B(`$ZodXID`,(e,t)=>{t.pattern??=vs,yc.init(e,t)}),Lc=/*@__PURE__*/ B(`$ZodKSUID`,(e,t)=>{t.pattern??=ys,yc.init(e,t)}),Rc=/*@__PURE__*/ B(`$ZodISODateTime`,(e,t)=>{t.pattern??=Bs(t),yc.init(e,t)}),zc=/*@__PURE__*/ B(`$ZodISODate`,(e,t)=>{t.pattern??=Ls,yc.init(e,t)}),Bc=/*@__PURE__*/ B(`$ZodISOTime`,(e,t)=>{t.pattern??=zs(t),yc.init(e,t)}),Vc=/*@__PURE__*/ B(`$ZodISODuration`,(e,t)=>{t.pattern??=Ss,yc.init(e,t)}),Hc=/*@__PURE__*/ B(`$ZodIPv4`,(e,t)=>{t.pattern??=Ds,yc.init(e,t)}),Uc=/^[0-9a-fA-F:.]+$/;function Wc(e){return Uc.test(e)?Cc(`http://[${e}]`):!1}const Gc=/*@__PURE__*/ B(`$ZodIPv6`,(e,t)=>{t.pattern??=Os,yc.init(e,t),e._zod.check=n=>{Wc(n.value)||n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}),Kc=/*@__PURE__*/ B(`$ZodCIDRv4`,(e,t)=>{t.pattern??=ks,yc.init(e,t)});function qc(e){let t=e.split(`/`);if(t.length!==2)return!1;let[n,r]=t;if(!r)return!1;let i=Number(r);return`${i}`!==r||i<0||i>128?!1:Wc(n)}const Jc=/*@__PURE__*/ B(`$ZodCIDRv6`,(e,t)=>{t.pattern??=As,yc.init(e,t),e._zod.check=n=>{qc(n.value)||n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}});function Yc(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const Xc=/^[0-9a-zA-Z+/]*={0,2}$/,Zc=/*@__PURE__*/ B(`$ZodBase64`,(e,t)=>{t.pattern??=Xc,yc.init(e,t),e._zod.check=n=>{Yc(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}}),Qc=/^[A-Za-z0-9_-]*$/;function $c(e){if(!Qc.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return Yc(t.padEnd(Math.ceil(t.length/4)*4,`=`))}const el=/*@__PURE__*/ B(`$ZodBase64URL`,(e,t)=>{t.pattern??=Qc,yc.init(e,t),e._zod.check=n=>{$c(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),tl=/*@__PURE__*/ B(`$ZodE164`,(e,t)=>{t.pattern??=Ps,yc.init(e,t)});function nl(e,t=null){try{let n=e.split(`.`);if(n.length!==3)return!1;let[r]=n;if(!r)return!1;let i=JSON.parse(atob(r));return!(`typ`in i&&i?.typ!==`JWT`||!i.alg||t&&(!(`alg`in i)||i.alg!==t))}catch{return!1}}const rl=/*@__PURE__*/ B(`$ZodJWT`,(e,t)=>{yc.init(e,t),e._zod.check=n=>{nl(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),il=/*@__PURE__*/ B(`$ZodNumber`,(e,t)=>{mc.init(e,t),e._zod.pattern=Us,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=Number(n.value)}catch{}let i=n.value;if(typeof i==`number`&&!Number.isNaN(i)&&Number.isFinite(i))return n;let a=typeof i==`number`?Number.isNaN(i)?`NaN`:Number.isFinite(i)?void 0:String(i):void 0;return n.issues.push({expected:`number`,code:`invalid_type`,input:i,inst:e,...a?{received:a}:{}}),n}}),al=/*@__PURE__*/ B(`$ZodNumberFormat`,(e,t)=>{ec.init(e,t),il.init(e,t)}),ol=/*@__PURE__*/ B(`$ZodBoolean`,(e,t)=>{mc.init(e,t),e._zod.pattern=Ws,e._zod.parse=(n,r)=>{if(t.coerce)try{n.value=!!n.value}catch{}let i=n.value;return typeof i==`boolean`||n.issues.push({expected:`boolean`,code:`invalid_type`,input:i,inst:e}),n}}),sl=/*@__PURE__*/ B(`$ZodNull`,(e,t)=>{mc.init(e,t),e._zod.pattern=Gs,e._zod.values=/* @__PURE__ */ new Set([null]),e._zod.parse=(t,n)=>{let r=t.value;return r===null||t.issues.push({expected:`null`,code:`invalid_type`,input:r,inst:e}),t}}),cl=/*@__PURE__*/ B(`$ZodUnknown`,(e,t)=>{mc.init(e,t),e._zod.parse=e=>e}),ll=/*@__PURE__*/ B(`$ZodNever`,(e,t)=>{mc.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function ul(e,t){let n=so(e._zod.def.checks);if(!n.length)return;let r=Math.min(...n.map(e=>e[0])),i=e._zod.parse;e._zod.parse=(n,a)=>{let o=t(n.value);if(o>r&&!a?.skipChecks&&a?.direction!==`backward`){for(let[t,r]of so(e._zod.def.checks))if(o>t&&r._zod.def.when(n)){let t=n.issues.length;return r._zod.check(n),n.issues[t].continue=!1,co(n.issues,t,e),n}}return i(n,a)}}const dl=e=>Array.isArray(e)?e.length:-1;function fl(e,t,n){e.issues.length&&t.issues.push(...ao(n,e.issues)),t.value[n]=e.value}const pl=/*@__PURE__*/ B(`$ZodArray`,(e,t)=>{mc.init(e,t);let n=No.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!Array.isArray(a))return r.issues.push({expected:`array`,code:`invalid_type`,input:a,inst:e}),r;r.value=n?n.alloc(e,r,Array(a.length),i):Array(a.length);let o=[],s=i?.abortEarly;for(let e=0;e<a.length;e++){let n=a[e],c=t.element._zod.run({value:n,issues:[]},i);if(c instanceof Promise)o.push(c.then(t=>fl(t,r,e)));else if(fl(c,r,e),s&&c.issues.length!==0&&ro(c))break}return o.length?Promise.all(o).then(()=>r):r},ul(e,dl)});function ml(e,t,n,r,i,a){let o=n in r,s=a===`optional`;if(o||!s||i!==`optional`){if(e.issues.length){if(i!==void 0&&s&&!o)return;t.issues.push(...ao(n,e.issues))}!o&&i===void 0?e.issues.length||t.issues.push({code:`invalid_type`,expected:`nonoptional`,input:void 0,path:[n]}):e.value===void 0?(o||i===`defaulted`&&!s)&&(t.value[n]=void 0):t.value[n]=e.value}}const hl=[];function gl(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:hl,i=r.length?[...t,...r]:t;for(let t of i)if(!e.shape?.[t]?._zod?.traits?.has(`$ZodType`))throw Error(`Invalid element at key "${String(t)}": expected a Zod schema`);let a=Ga(e.shape);return{...e,allKeys:i,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(a)}}function _l(e,t,n,r,i,a,o){let s=[],c=i.keySet,l=i.catchall._zod,u=l.def.type,d=l.optin,f=l.optout,p=0;for(let i in t){if(o&&n.issues.length!==p){if(ro(n,p))break;p=n.issues.length}if(c.has(i))continue;if(i===`__proto__`){u===`never`&&s.push(i);continue}if(u===`never`){s.push(i);continue}let a=l.run({value:t[i],issues:[]},r);a instanceof Promise?e.push(a.then(e=>ml(e,n,i,t,d,f))):ml(a,n,i,t,d,f)}return s.length&&n.issues.push({code:`unrecognized_keys`,keys:s,input:t,inst:a,continue:!0}),e.length?Promise.all(e).then(()=>n):n}const vl=/*@__PURE__*/ B(`$ZodObject`,(e,t)=>{mc.init(e,t);let n=Object.getOwnPropertyDescriptor(t,`shape`),r=n?.get?n.get.raw:t.shape??{};if(r){let e=()=>{let n={...r};return Object.defineProperty(t,"shape",{value:n}),e.raw=n,n};e.raw=r,Object.defineProperty(t,"shape",{get:e})}let i=Sa(()=>gl(t));z(e,`propValues`,e=>{let t=e.def.shape,n={};for(let e in t){let r=t[e]._zod;if(r.values){Object.prototype.hasOwnProperty.call(n,e)||Ea(n,e,/* @__PURE__ */ new Set);for(let t of r.values)n[e].add(t);r.optin!==void 0&&n[e].add(void 0)}}return n});let a=La,o=t.catchall,s,c=No.memoizer;c?.attach(e),e._zod.parse=(t,n)=>{s??=i.value;let r=t.value;if(!a(r))return t.issues.push({expected:`object`,code:`invalid_type`,input:r,inst:e}),t;t.value=c?c.alloc(e,t,{},n):{};let l=[],u=s.shape,d=n?.abortEarly,f=t.issues.length;for(let e of s.allKeys){if(d&&t.issues.length!==f){if(ro(t,f))break;f=t.issues.length}if(e===`__proto__`)continue;let i=u[e],a=i._zod.optin,o=i._zod.optout,s=i._zod.run({value:r[e],issues:[]},n);s instanceof Promise?l.push(s.then(n=>ml(n,t,e,r,a,o))):ml(s,t,e,r,a,o)}return o?_l(l,r,t,n,i.value,e,d===!0):l.length?Promise.all(l).then(()=>t):t}}),yl=/*@__PURE__*/ B(`$ZodObjectJIT`,(e,t)=>{vl.init(e,t);let n=e._zod.parse,r=Sa(()=>gl(t)),i=No.memoizer,a=t=>{let n=r.value,a=n.symbolKeys,o=new fc([`payload`,`ctx`],{shape:t,inst:e,memo:i,syms:a}),s=e=>`shape[${e}]._zod.run({ value: input[${e}], issues: [] }, ctx)`,c=(e,t)=>`
19
+ let ${e}_ab = false;
20
+ for (let i = 0; i < ${e}.issues.length; i++) {
21
+ const iss = ${e}.issues[i];
22
+ iss.path = iss.path ? [${t}, ...iss.path] : [${t}];
23
+ payload.issues.push(iss);
24
+ if (iss.continue !== true) ${e}_ab = true;
25
+ }
26
+ if (${e}_ab && ctx && ctx.abortEarly) {
27
+ payload.value = newResult;
28
+ return payload;
29
+ }`;o.write(`const input = payload.value;`);let l=Object.create(null),u=0;for(let e of n.allKeys)l[e]=`key_${u++}`;o.write(i?`const newResult = memo.alloc(inst, payload, {}, ctx);`:`const newResult = {};`);for(let e of n.allKeys){if(e===`__proto__`)continue;let n=l[e],r=typeof e==`symbol`?`syms[${a.indexOf(e)}]`:Pa(e),i=`${r} in input`,u=t[e],d=u?._zod?.optin,f=d!==void 0,p=u?._zod?.optout===`optional`;if(o.write(`const ${n} = ${s(r)};`),f&&p){let e=d===`optional`?`${n}_present`:`${n}.value !== undefined || ${n}_present`;o.write(`
30
+ const ${n}_present = ${i};
31
+ if (!${n}.issues.length || ${n}_present) {
32
+ if (${n}.issues.length) {${c(n,r)}
33
+ }
34
+
35
+ if (${e}) {
36
+ newResult[${r}] = ${n}.value;
37
+ }
38
+ }
39
+
40
+ `)}else f?(o.write(`
41
+ if (${n}.issues.length) {${c(n,r)}
42
+ }
43
+ `),d===`defaulted`?o.write(`newResult[${r}] = ${n}.value;`):o.write(`
44
+ if (${n}.value !== undefined || ${i}) {
45
+ newResult[${r}] = ${n}.value;
46
+ }
47
+ `)):o.write(`
48
+ const ${n}_present = ${i};
49
+ if (${n}.issues.length) {${c(n,r)}
50
+ }
51
+ if (!${n}_present && !${n}.issues.length) {
52
+ payload.issues.push({
53
+ code: "invalid_type",
54
+ expected: "nonoptional",
55
+ input: undefined,
56
+ path: [${r}]
57
+ });
58
+ if (ctx && ctx.abortEarly) {
59
+ payload.value = newResult;
60
+ return payload;
61
+ }
62
+ }
63
+
64
+ if (${n}_present) {
65
+ newResult[${r}] = ${n}.value;
66
+ }
67
+
68
+ `)}return o.write(`payload.value = newResult;`),o.write(`return payload;`),o.compile()},o,s=La,c=!No.jitless,l=c&&Ra.value,u=t.catchall,d;e._zod.parse=(i,f)=>{d??=r.value;let p=i.value;return s(p)?c&&l&&f?.async===!1&&f.jitless!==!0?(o||=a(t.shape),i=o(i,f),u?_l([],p,i,f,d,e,f?.abortEarly===!0):i):n(i,f):(i.issues.push({expected:`object`,code:`invalid_type`,input:p,inst:e}),i)}});function bl(e,t,n,r){for(let n of e)if(n.issues.length===0)return t.value=n.value,t;let i=e.filter(e=>!ro(e));return i.length===1?(t.value=i[0].value,i[0]):(t.issues.push({code:`invalid_union`,input:t.value,inst:n,errors:e.map(e=>e.issues.map(e=>lo(e,r,Po())))}),t)}const xl=/*@__PURE__*/ B(`$ZodUnion`,(e,t)=>{mc.init(e,t),z(e,`optin`,e=>e.def.options.some(e=>e._zod.optin===`defaulted`)?`defaulted`:e.def.options.some(e=>e._zod.optin!==void 0)?`optional`:void 0),z(e,`optout`,e=>e.def.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),z(e,`values`,e=>{if(e.def.options.every(e=>e._zod.values))return new Set(e.def.options.flatMap(e=>Array.from(e._zod.values)))}),z(e,`pattern`,e=>{if(e.def.options.every(e=>e._zod.pattern)){let t=e.def.options.map(e=>e._zod.pattern);return RegExp(`^(${t.map(e=>wa(e.source)).join(`|`)})$`)}});let n=t.options.length===1?t.options[0]._zod.run:null;e._zod.parse=(r,i)=>{if(n)return n(r,i);let a=!1,o=[];for(let e of t.options){let t=e._zod.run({value:r.value,issues:[]},i);if(t instanceof Promise)o.push(t),a=!0;else{if(t.issues.length===0)return t;o.push(t)}}return a?Promise.all(o).then(t=>bl(t,r,e,i)):bl(o,r,e,i)}});function Sl(e){let t=/* @__PURE__ */ new Map;for(let n of e.options){let r=n._zod.propValues?.[e.discriminator];if(!r||r.size===0)throw Error(`Invalid discriminated union option at index "${e.options.indexOf(n)}"`);for(let e of r)if(t.has(e)){if(e!==void 0)throw Error(`Duplicate discriminator value "${String(e)}"`);t.set(e,null)}else t.set(e,n)}return t}const Cl=/*@__PURE__*/ B(`$ZodDiscriminatedUnion`,(e,t)=>{t.inclusive=!1,xl.init(e,t);let n=e._zod.parse;z(e,`propValues`,e=>{let t={},n=0;for(let r of e.def.options){let i=r._zod.propValues;if(!i||Object.keys(i).length===0)throw Error(`Invalid discriminated union option at index "${e.def.options.indexOf(r)}"`);i[e.def.discriminator]?.has(void 0)&&n++;for(let[e,n]of Object.entries(i)){Object.prototype.hasOwnProperty.call(t,e)||Ea(t,e,/* @__PURE__ */ new Set);for(let r of n)t[e].add(r)}}return!e.def.unionFallback&&n>1&&t[e.def.discriminator]?.delete(void 0),t}),t.options.forEach((e,n)=>{let r=Da(e._zod.def);if(r&&!Object.prototype.hasOwnProperty.call(r,t.discriminator))throw Error(`Invalid discriminated union option at index "${n}"`)});let r=Sa(()=>Sl(t));e._zod.parse=(i,a)=>{let o=i.value;if(!La(o))return i.issues.push({code:`invalid_type`,expected:`object`,input:o,inst:e}),i;let s=o?.[t.discriminator],c=r.value.get(s);return c&&(s!==void 0||a.direction!==`backward`)?c._zod.run(i,a):t.unionFallback||a.direction===`backward`?n(i,a):(i.issues.push({code:`invalid_union`,errors:[],note:`No matching discriminator`,discriminator:t.discriminator,options:Array.from(r.value.keys()).filter(e=>r.value.get(e)!==null),input:o,path:[t.discriminator],inst:e}),i)}}),wl=/*@__PURE__*/ B(`$ZodIntersection`,(e,t)=>{mc.init(e,t),e._zod.parse=(e,n)=>{let r=e.value,i=t.left._zod.run({value:r,issues:[]},n),a=t.right._zod.run({value:r,issues:[]},n);return i instanceof Promise||a instanceof Promise?Promise.all([i,a]).then(([t,n])=>El(e,t,n)):El(e,i,a)}});function Tl(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(za(e)&&za(t)){let n=Object.keys(t),r=Object.keys(e).filter(e=>n.indexOf(e)!==-1),i={...e,...t};Object.prototype.hasOwnProperty.call(i,`__proto__`)&&delete i.__proto__;for(let n of r){if(n===`__proto__`)continue;let r=Tl(e[n],t[n]);if(!r.valid)return{valid:!1,mergeErrorPath:[n,...r.mergeErrorPath]};i[n]=r.data}return{valid:!0,data:i}}if(Array.isArray(e)&&Array.isArray(t)){if(e.length!==t.length)return{valid:!1,mergeErrorPath:[]};let n=[];for(let r=0;r<e.length;r++){let i=e[r],a=t[r],o=Tl(i,a);if(!o.valid)return{valid:!1,mergeErrorPath:[r,...o.mergeErrorPath]};n.push(o.data)}return{valid:!0,data:n}}return{valid:!1,mergeErrorPath:[]}}function El(e,t,n){let r=/* @__PURE__ */ new Map,i,a=/* @__PURE__ */ new Map,o=(e,t)=>{let n;if(e.code===`unrecognized_keys`&&!e.path?.length)i??=e,n=e.keys;else if(e.code===`invalid_key`&&e.origin===`record`&&e.path?.length===1){let t=String(e.path[0]);a.has(t)||a.set(t,e),n=[t]}else return!1;for(let e of n)r.has(e)||r.set(e,{}),r.get(e)[t]=!0;return!0};for(let n of t.issues)o(n,`l`)||e.issues.push(n);for(let t of n.issues)o(t,`r`)||e.issues.push(t);let s=[...r].filter(([,e])=>e.l&&e.r).map(([e])=>e);if(s.length){let t=i?s.filter(e=>i.keys.includes(e)):[];t.length&&e.issues.push({...i,keys:t});for(let n of s)!t.includes(n)&&a.has(n)&&e.issues.push(a.get(n))}let c=Tl(t.value,n.value);if(!c.valid){if(ro(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}const Dl=/*@__PURE__*/ B(`$ZodRecord`,(e,t)=>{mc.init(e,t);let n=No.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!za(a))return r.issues.push({expected:`record`,code:`invalid_type`,input:a,inst:e}),r;let o=[],s=t.keyType._zod.values;if(s&&!t.partial){r.value=n?n.alloc(e,r,{},i):{};let c=/* @__PURE__ */ new Set;for(let n of s)if(typeof n==`string`||typeof n==`number`||typeof n==`symbol`){if(c.add(typeof n==`number`?n.toString():n),n===`__proto__`)continue;let s=t.keyType._zod.run({value:n,issues:[]},i);if(s instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(s.issues.length){r.issues.push({code:`invalid_key`,origin:`record`,issues:s.issues.map(e=>lo(e,i,Po())),input:n,path:[n],inst:e});continue}let l=s.value;if(l===`__proto__`)continue;let u=t.valueType._zod.run({value:a[n],issues:[]},i);u instanceof Promise?o.push(u.then(e=>{e.issues.length&&r.issues.push(...ao(n,e.issues)),r.value[l]=e.value})):(u.issues.length&&r.issues.push(...ao(n,u.issues)),r.value[l]=u.value)}let l;for(let e in a)if(!c.has(e)){if(t.mode===`loose`){if(e===`__proto__`)continue;r.value[e]=a[e]}else l??=[],l.push(e)}l&&l.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:l,continue:!0})}else{r.value=n?n.alloc(e,r,{},i):{};let c;for(let n of Reflect.ownKeys(a)){if(n===`__proto__`||!Object.prototype.propertyIsEnumerable.call(a,n))continue;let l=t.keyType._zod.run({value:n,issues:[]},i);if(l instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);if(typeof n==`string`&&Us.test(n)&&l.issues.length){let e=t.keyType._zod.run({value:Number(n),issues:[]},i);if(e instanceof Promise)throw Error(`Async schemas not supported in object keys currently`);e.issues.length===0&&(l=e)}if(l.issues.length){t.mode===`loose`?r.value[n]=a[n]:s?(c??=[],c.push(n)):r.issues.push({code:`invalid_key`,origin:`record`,issues:l.issues.map(e=>lo(e,i,Po())),input:n,path:[n],inst:e});continue}let u=l.value;if(u===`__proto__`)continue;let d=t.valueType._zod.run({value:a[n],issues:[]},i);d instanceof Promise?o.push(d.then(e=>{e.issues.length&&r.issues.push(...ao(n,e.issues)),r.value[u]=e.value})):(d.issues.length&&r.issues.push(...ao(n,d.issues)),r.value[u]=d.value)}c&&c.length>0&&r.issues.push({code:`unrecognized_keys`,input:a,inst:e,keys:c,continue:!0})}return o.length?Promise.all(o).then(()=>r):r}}),Ol=/*@__PURE__*/ B(`$ZodEnum`,(e,t)=>{mc.init(e,t);let n=va(t.entries),r=new Set(n);e._zod.values=r,z(e,`pattern`,e=>{let t=va(e.def.entries).filter(e=>Va.has(typeof e));return RegExp(t.length?`^(${t.map(e=>Ha(e.toString())).join(`|`)})$`:`^[^\\s\\S]$`)}),e._zod.parse=(t,i)=>{let a=t.value;return r.has(a)||t.issues.push({code:`invalid_value`,values:n,input:a,inst:e}),t}}),kl=/*@__PURE__*/ B(`$ZodLiteral`,(e,t)=>{mc.init(e,t);let n=new Set(t.values);e._zod.values=n,z(e,`pattern`,e=>{let t=e.def.values;return RegExp(t.length?`^(${t.map(e=>typeof e==`string`?Ha(e):e?Ha(e.toString()):String(e)).join(`|`)})$`:`^[^\\s\\S]$`)}),e._zod.parse=(r,i)=>{let a=r.value;return n.has(a)||r.issues.push({code:`invalid_value`,values:t.values,input:a,inst:e}),r}}),Al=/*@__PURE__*/ B(`$ZodTransform`,(e,t)=>{mc.init(e,t),e._zod.optin=`optional`,No.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Mo(e.constructor.name);let i=t.transform(n.value,n);if(r.async)return(i instanceof Promise?i:Promise.resolve(i)).then(e=>(n.value=e,n));if(i instanceof Promise)throw new jo;return n.value=i,n}});function jl(e,t){return e.value=t.issues.length?void 0:t.value,e}const Ml=/*@__PURE__*/ B(`$ZodOptional`,(e,t)=>{mc.init(e,t),z(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),e._zod.optout=`optional`,z(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?/* @__PURE__ */ new Set([...t,void 0]):void 0}),z(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${wa(t.source)})?$`):void 0}),e._zod.parse=(e,n)=>{if(e.value===void 0){if(t.innerType._zod.optin!==`defaulted`)return e;let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(t=>jl(e,t)):jl(e,r)}return t.innerType._zod.run(e,n)}}),Nl=/*@__PURE__*/ B(`$ZodExactOptional`,(e,t)=>{Ml.init(e,t),z(e,`values`,e=>e.def.innerType._zod.values),z(e,`pattern`,e=>e.def.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Pl=/*@__PURE__*/ B(`$ZodNullable`,(e,t)=>{mc.init(e,t),z(e,`optin`,e=>e.def.innerType._zod.optin),z(e,`optout`,e=>e.def.innerType._zod.optout),z(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${wa(t.source)}|null)$`):void 0}),z(e,`values`,e=>e.def.innerType._zod.values?/* @__PURE__ */ new Set([...e.def.innerType._zod.values,null]):void 0),e._zod.parse=(e,n)=>e.value===null?e:t.innerType._zod.run(e,n)}),Fl=/*@__PURE__*/ B(`$ZodDefault`,(e,t)=>{mc.init(e,t),e._zod.optin=`defaulted`,z(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);if(e.value===void 0)return e.value=t.defaultValue,e;let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(e=>Il(e,t)):Il(r,t)}});function Il(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const Ll=/*@__PURE__*/ B(`$ZodPrefault`,(e,t)=>{mc.init(e,t),e._zod.optin=`defaulted`,z(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>(n.direction===`backward`||e.value===void 0&&(e.value=t.defaultValue),t.innerType._zod.run(e,n))}),Rl=/*@__PURE__*/ B(`$ZodNonOptional`,(e,t)=>{mc.init(e,t),z(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?new Set([...t].filter(e=>e!==void 0)):void 0}),e._zod.parse=(n,r)=>{let i=t.innerType._zod.run(n,r);return i instanceof Promise?i.then(t=>zl(t,e)):zl(i,e)}});function zl(e,t){return!e.issues.length&&e.value===void 0&&e.issues.push({code:`invalid_type`,expected:`nonoptional`,input:e.value,inst:t}),e}function Bl(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(e=>lo(e,r,Po()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}const Vl=/*@__PURE__*/ B(`$ZodCatch`,(e,t)=>{mc.init(e,t),z(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),z(e,`optout`,e=>e.def.innerType._zod.optout),z(e,`values`,e=>e.def.innerType._zod.values),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run({value:e.value,issues:[]},n);return r instanceof Promise?r.then(r=>Bl(e,r,t,n)):Bl(e,r,t,n)}}),Hl=/*@__PURE__*/ B(`$ZodPipe`,(e,t)=>{mc.init(e,t),z(e,`values`,e=>e.def.in._zod.values),z(e,`optin`,e=>e.def.in._zod.optin),z(e,`optout`,e=>e.def.out._zod.optout),z(e,`propValues`,e=>e.def.in._zod.propValues),e._zod.parse=(e,n)=>{if(n.direction===`backward`){let r=t.out._zod.run(e,n);return r instanceof Promise?r.then(e=>Ul(e,t.in,n)):Ul(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Ul(e,t.out,n)):Ul(r,t.out,n)}});function Ul(e,t,n){return e.issues.some(e=>e.code!==`unrecognized_keys`)?(e.aborted=!0,e):t._zod.run({value:e.value,issues:e.issues},n)}const Wl=/*@__PURE__*/ B(`$ZodPreprocess`,(e,t)=>{Hl.init(e,t)}),Gl=/*@__PURE__*/ B(`$ZodReadonly`,(e,t)=>{mc.init(e,t),z(e,`propValues`,e=>e.def.innerType._zod.propValues),z(e,`values`,e=>e.def.innerType._zod.values),z(e,`optin`,e=>e.def.innerType?._zod?.optin),z(e,`optout`,e=>e.def.innerType?._zod?.optout),e._zod.parse=(e,n)=>{if(n.direction===`backward`)return t.innerType._zod.run(e,n);let r=t.innerType._zod.run(e,n);return r instanceof Promise?r.then(Kl):Kl(r)}});function Kl(e){return e.memo||(e.value=Object.freeze(e.value)),e}const ql=/*@__PURE__*/ B(`$ZodCustom`,(e,t)=>{Js.init(e,t),mc.init(e,t),e._zod.parse=(e,t)=>e,e._zod.check=n=>{let r=n.value,i=t.fn(r);if(i instanceof Promise)return i.then(t=>Jl(t,n,r,e));Jl(i,n,r,e)}});function Jl(e,t,n,r){if(!e){let e={code:`custom`,input:n,inst:r,path:[...r._zod.def.path??[]],continue:!r._zod.def.abort};r._zod.def.params&&(e.params=r._zod.def.params),t.issues.push(ho(e))}}var Yl=class extends Error{constructor(){super(`Cannot parse a reference cycle that closes through a transform`),this.name=`ZodCyclicError`}};const Xl=`~memo`,Zl=[];function Ql(e){return typeof e==`object`&&!!e}function $l(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}const eu=/*@__PURE__*/ new WeakMap;function tu(e,t,n){let r=eu.get(e);if(r!==void 0)return r?2:0;if(t.has(e))return 2;t.add(e);let i=0,a=e=>{if(i!==2&&e?._zod){let r=tu(e,t,n);r>i&&(i=r)}},o=(e,r)=>{let i=0;for(let a of Reflect.ownKeys(e)){let o=Object.getOwnPropertyDescriptor(e,a);if(r&&!o.enumerable)continue;let s=o.get?1:o.value?._zod?tu(o.value,t,n):0;s>i&&(i=s)}return i},s=e=>{e>i&&(i=e)},c=e._zod.def;switch(c.type){case`object`:{let e=Da(c);s(e?o(e,!0):1),a(c.catchall);break}case`array`:a(c.element);break;case`tuple`:for(let e of c.items)a(e);a(c.rest);break;case`record`:case`map`:a(c.keyType),a(c.valueType);break;case`set`:a(c.valueType);break;case`union`:for(let e of c.options)a(e);break;case`intersection`:a(c.left),a(c.right);break;case`optional`:case`nullable`:case`default`:case`prefault`:case`catch`:case`readonly`:case`nonoptional`:case`promise`:case`success`:a(c.innerType);break;case`pipe`:a(c.in),a(c.out);break;case`function`:a(c.input),a(c.output);break;case`lazy`:{let r=c._cachedInner??(n?e._zod.innerType:void 0);s(r?tu(r,t,!1):1);break}case`template_literal`:case`string`:case`number`:case`int`:case`boolean`:case`bigint`:case`symbol`:case`undefined`:case`null`:case`void`:case`never`:case`any`:case`unknown`:case`date`:case`nan`:case`enum`:case`literal`:case`file`:case`transform`:case`custom`:break;default:for(let e in c){let t=Object.getOwnPropertyDescriptor(c,e);if(!t||t.get)continue;let n=t.value;if(n&&typeof n==`object`){if(n._zod)a(n);else if(Array.isArray(n))for(let e of n)a(e)}}}return t.delete(e),nu(e,i)}function nu(e,t){return t!==1&&eu.set(e,t===2),t}function ru(e,t){let n=e.buckets.get(t);return n||(n=/* @__PURE__ */ new WeakMap,e.buckets.set(t,n)),n}let iu;const au=[],ou={alloc(e,t,n){let r=iu;if(!r)return n;iu=void 0;let i={value:n,issues:null};return r.set(t.value,i),au.push(i),n},guard(e){var t;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,n=(e,n)=>{if(n.direction!==`backward`&&cu(n,e.value))throw new Yl;return t(e,n)};e._zod.parse=n,e._zod.run===t&&(e._zod.run=n)})},attach(e){var t;let n,r=!1,i,a;(t=e._zod).deferred??(t.deferred=[]),e._zod.deferred.push(()=>{let t=e._zod.parse,o=(s,c)=>{if(n===void 0){let i=tu(e,/* @__PURE__ */ new Set,!1);if(i===0)return e._zod.parse=t,e._zod.run===o&&(e._zod.run=t),t(s,c);i===2||r?n=!0:r=!0}let l=s.value;if(!Ql(l))return t(s,c);let u=c[Xl];u||(u={buckets:/* @__PURE__ */ new WeakMap,backEdges:void 0},c[Xl]=u);let d;i===c?d=a:(d=ru(u,e),i=c,a=d);let f=d.get(l);if(f)return s.value=f.value,f.issues?f.issues.length&&s.issues.push(...$l(f.issues)):(s.memo=!0,u.backEdges??(u.backEdges=/* @__PURE__ */ new WeakSet),u.backEdges.add(f.value)),s;iu=d;let p=au.length,m=t(s,c);iu=void 0;let h=au.length>p?au.pop():void 0;return m instanceof Promise?m.then(e=>(h&&(h.issues=e.issues.length?$l(e.issues):Zl),e)):(h&&(h.issues=m.issues.length?$l(m.issues):Zl),m)};e._zod.parse=o,e._zod.run===t&&(e._zod.run=o)})}};function su(){return ou}function cu(e,t){let n=e[Xl]?.backEdges;return n!==void 0&&Ql(t)&&n.has(t)}const lu=()=>{let e={string:{unit:`characters`,verb:`to have`},file:{unit:`bytes`,verb:`to have`},array:{unit:`items`,verb:`to have`},set:{unit:`items`,verb:`to have`},map:{unit:`entries`,verb:`to have`}};function t(t){return e[t]??null}let n={regex:`input`,email:`email address`,url:`URL`,emoji:`emoji`,uuid:`UUID`,uuidv4:`UUIDv4`,uuidv6:`UUIDv6`,nanoid:`nanoid`,guid:`GUID`,cuid:`cuid`,cuid2:`cuid2`,ulid:`ULID`,xid:`XID`,ksuid:`KSUID`,datetime:`ISO datetime`,date:`ISO date`,time:`ISO time`,duration:`ISO duration`,ipv4:`IPv4 address`,ipv6:`IPv6 address`,mac:`MAC address`,cidrv4:`IPv4 range`,cidrv6:`IPv6 range`,base64:`base64-encoded string`,base64url:`base64url-encoded string`,json_string:`JSON string`,e164:`E.164 number`,currency_code:`currency code`,credit_card:`credit card number`,iban:`IBAN`,jwt:`JWT`,template_literal:`input`},r={nan:`NaN`};function i(e,t){return e===`number`&&typeof t==`number`&&!Number.isFinite(t)?String(t):r[e]??e}return e=>{switch(e.code){case`invalid_type`:return`Invalid input: expected ${i(e.expected)}, received ${i(mo(e.input),e.input)}`;case`invalid_value`:return e.values.length===1?`Invalid input: expected ${Wa(e.values[0])}`:`Invalid option: expected one of ${ya(e.values,`|`)}`;case`too_big`:{let n=e.exact?`exactly `:e.inclusive?`<=`:`<`,r=t(e.origin);return r?`Too big: expected ${e.origin??`value`} to have ${n}${e.maximum.toString()} ${r.unit??`elements`}`:`Too big: expected ${e.origin??`value`} to be ${n}${e.maximum.toString()}`}case`too_small`:{let n=e.exact?`exactly `:e.inclusive?`>=`:`>`,r=t(e.origin);return r?`Too small: expected ${e.origin} to have ${n}${e.minimum.toString()} ${r.unit}`:`Too small: expected ${e.origin} to be ${n}${e.minimum.toString()}`}case`invalid_format`:{let t=e;return t.format===`starts_with`?`Invalid string: must start with "${t.prefix}"`:t.format===`ends_with`?`Invalid string: must end with "${t.suffix}"`:t.format===`includes`?`Invalid string: must include "${t.includes}"`:t.format===`regex`?`Invalid string: must match pattern ${t.pattern}`:`Invalid ${n[t.format]??e.format}`}case`not_multiple_of`:return`Invalid number: must be a multiple of ${e.divisor}`;case`unrecognized_keys`:return`Unrecognized key${e.keys.length>1?`s`:``}: ${ya(e.keys,`, `)}`;case`invalid_key`:return`Invalid key in ${e.origin}`;case`invalid_union`:return e.options&&Array.isArray(e.options)&&e.options.length>0?`Invalid discriminator value. Expected ${e.options.map(e=>`'${e}'`).join(` | `)}`:e.inclusive===!1?`Invalid input: more than one option matched`:`Invalid input`;case`invalid_element`:return`Invalid value in ${e.origin}`;default:return`Invalid input`}}};function uu(){return{localeError:lu()}}var du,fu=class{constructor(){this._map=/* @__PURE__ */ new WeakMap,this._idmap=/* @__PURE__ */ new Map}add(e,...t){let n=t[0];return this._map.set(e,n),n&&typeof n==`object`&&`id`in n&&this._idmap.set(n.id,e),this}clear(){return this._map=/* @__PURE__ */ new WeakMap,this._idmap=/* @__PURE__ */ new Map,this}remove(e){let t=this._map.get(e);return t&&typeof t==`object`&&`id`in t&&this._idmap.delete(t.id),this._map.delete(e),this}get(e){let t=e._zod.parent;if(t){let n={...this.get(t)??{}};delete n.id;let r={...n,...this._map.get(e)};return Object.keys(r).length?r:void 0}return this._map.get(e)}has(e){return this._map.has(e)}};function pu(){return new fu}(du=globalThis).__zod_globalRegistry??(du.__zod_globalRegistry=pu());const mu=globalThis.__zod_globalRegistry;function hu(e){return e.checks&&=[...e.checks],e}// @__NO_SIDE_EFFECTS__
69
+ function gu(e,t){return new e(hu({type:`string`,...R(t)}))}// @__NO_SIDE_EFFECTS__
70
+ function _u(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...R(t)})}// @__NO_SIDE_EFFECTS__
71
+ function vu(e,t){return new e({type:`string`,format:`guid`,check:`string_format`,abort:!1,...R(t)})}// @__NO_SIDE_EFFECTS__
72
+ function yu(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,...R(t)})}// @__NO_SIDE_EFFECTS__
73
+ function bu(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...R(t)})}// @__NO_SIDE_EFFECTS__
74
+ function xu(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...R(t)})}// @__NO_SIDE_EFFECTS__
75
+ function Su(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...R(t)})}// @__NO_SIDE_EFFECTS__
76
+ function Cu(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...R(t)})}// @__NO_SIDE_EFFECTS__
77
+ function wu(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...R(t)})}// @__NO_SIDE_EFFECTS__
78
+ function Tu(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...R(t)})}// @__NO_SIDE_EFFECTS__
79
+ function Eu(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...R(t)})}// @__NO_SIDE_EFFECTS__
80
+ function Du(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...R(t)})}// @__NO_SIDE_EFFECTS__
81
+ function Ou(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...R(t)})}// @__NO_SIDE_EFFECTS__
82
+ function ku(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...R(t)})}// @__NO_SIDE_EFFECTS__
83
+ function Au(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...R(t)})}// @__NO_SIDE_EFFECTS__
84
+ function ju(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...R(t)})}// @__NO_SIDE_EFFECTS__
85
+ function Mu(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...R(t)})}// @__NO_SIDE_EFFECTS__
86
+ function Nu(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...R(t)})}// @__NO_SIDE_EFFECTS__
87
+ function Pu(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...R(t)})}// @__NO_SIDE_EFFECTS__
88
+ function Fu(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...R(t)})}// @__NO_SIDE_EFFECTS__
89
+ function Iu(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...R(t)})}// @__NO_SIDE_EFFECTS__
90
+ function Lu(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...R(t)})}// @__NO_SIDE_EFFECTS__
91
+ function Ru(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...R(t)})}// @__NO_SIDE_EFFECTS__
92
+ function zu(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...R(t)})}// @__NO_SIDE_EFFECTS__
93
+ function Bu(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...R(t)})}// @__NO_SIDE_EFFECTS__
94
+ function Vu(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...R(t)})}// @__NO_SIDE_EFFECTS__
95
+ function Hu(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...R(t)})}// @__NO_SIDE_EFFECTS__
96
+ function Uu(e,t){return new e(hu({type:`number`,checks:[],...R(t)}))}// @__NO_SIDE_EFFECTS__
97
+ function Wu(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...R(t)})}// @__NO_SIDE_EFFECTS__
98
+ function Gu(e,t){return new e({type:`boolean`,...R(t)})}// @__NO_SIDE_EFFECTS__
99
+ function Ku(e,t){return new e({type:`null`,...R(t)})}// @__NO_SIDE_EFFECTS__
100
+ function qu(e){return new e({type:`unknown`})}// @__NO_SIDE_EFFECTS__
101
+ function Ju(e,t){return new e({type:`never`,...R(t)})}// @__NO_SIDE_EFFECTS__
102
+ function Yu(e,t){return new Zs({check:`less_than`,...R(t),value:e,inclusive:!1})}// @__NO_SIDE_EFFECTS__
103
+ function Xu(e,t){return new Zs({check:`less_than`,...R(t),value:e,inclusive:!0})}// @__NO_SIDE_EFFECTS__
104
+ function Zu(e,t){return new Qs({check:`greater_than`,...R(t),value:e,inclusive:!1})}// @__NO_SIDE_EFFECTS__
105
+ function Qu(e,t){return new Qs({check:`greater_than`,...R(t),value:e,inclusive:!0})}// @__NO_SIDE_EFFECTS__
106
+ function $u(e,t){return new $s({check:`multiple_of`,...R(t),value:e})}// @__NO_SIDE_EFFECTS__
107
+ function ed(e,t){return new tc({check:`max_length`,...R(t),maximum:e})}// @__NO_SIDE_EFFECTS__
108
+ function td(e,t){return new nc({check:`min_length`,...R(t),minimum:e})}// @__NO_SIDE_EFFECTS__
109
+ function nd(e,t){return new rc({check:`length_equals`,...R(t),length:e})}// @__NO_SIDE_EFFECTS__
110
+ function rd(e,t){return new ac({check:`string_format`,format:`regex`,...R(t),pattern:e})}// @__NO_SIDE_EFFECTS__
111
+ function id(e){return new oc({check:`string_format`,format:`lowercase`,...R(e)})}// @__NO_SIDE_EFFECTS__
112
+ function ad(e){return new sc({check:`string_format`,format:`uppercase`,...R(e)})}// @__NO_SIDE_EFFECTS__
113
+ function od(e,t){return new cc({check:`string_format`,format:`includes`,...R(t),includes:e})}// @__NO_SIDE_EFFECTS__
114
+ function sd(e,t){return new lc({check:`string_format`,format:`starts_with`,...R(t),prefix:e})}// @__NO_SIDE_EFFECTS__
115
+ function cd(e,t){return new uc({check:`string_format`,format:`ends_with`,...R(t),suffix:e})}// @__NO_SIDE_EFFECTS__
116
+ function ld(e){return new dc({check:`overwrite`,tx:e})}// @__NO_SIDE_EFFECTS__
117
+ function ud(e){return/* @__PURE__ */ ld(t=>t.normalize(e))}// @__NO_SIDE_EFFECTS__
118
+ function dd(){return/* @__PURE__ */ ld(e=>e.trim())}// @__NO_SIDE_EFFECTS__
119
+ function fd(){return/* @__PURE__ */ ld(e=>e.toLowerCase())}// @__NO_SIDE_EFFECTS__
120
+ function pd(){return/* @__PURE__ */ ld(e=>e.toUpperCase())}// @__NO_SIDE_EFFECTS__
121
+ function md(){return/* @__PURE__ */ ld(e=>Fa(e))}// @__NO_SIDE_EFFECTS__
122
+ function hd(e,t,n){return new e({type:`array`,element:t,...R(n)})}// @__NO_SIDE_EFFECTS__
123
+ function gd(e,t,n){let r=R(n);return r.abort??=!0,new e({type:`custom`,check:`custom`,fn:t,...r})}// @__NO_SIDE_EFFECTS__
124
+ function _d(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...R(n)})}// @__NO_SIDE_EFFECTS__
125
+ function vd(e,t){let n=/* @__PURE__ */ yd(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(ho(e,t.value,n._zod.def));else{let r=e;r.fatal&&(r.continue=!1),r.code??=`custom`,`input`in r||(r.input=t.value),r.inst??=n,r.continue??=!n._zod.def.abort,t.issues.push(ho(r))}},e(t.value,t)),t);return n}// @__NO_SIDE_EFFECTS__
126
+ function yd(e,t){let n=new Js({check:`custom`,...R(t)});return n._zod.check=e,n}function bd(e,...t){for(let n of t)for(let t of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,t)&&Ea(e,t,n[t]);return e}function xd(e){let t=e?.target??`draft-2020-12`;return t===`draft-4`&&(t=`draft-04`),t===`draft-7`&&(t=`draft-07`),{processors:e.processors??{},metadataRegistry:e?.metadata??mu,target:t,unrepresentable:e?.unrepresentable??`throw`,override:e?.override??(()=>{}),io:e?.io??`output`,counter:0,seen:/* @__PURE__ */ new Map,sharedDefsExtractedFor:void 0,sharedEmitDoneFor:void 0,cycles:e?.cycles??`ref`,reused:e?.reused??`inline`,intersections:[],deferred:[],external:e?.external??void 0}}function Sd(e,t,n,r,i){let a=typeof t.unrepresentable==`function`?t.unrepresentable({zodSchema:e,path:r.path,message:i}):t.unrepresentable;if(a===`any`)return!1;if(a===void 0||a===`throw`)throw Error(i);return Object.assign(n,a),!0}function Cd(e,t,n={path:[],schemaPath:[]}){var r;let i=e._zod.def,a=t.seen.get(e);if(a)return a.count++,n.schemaPath.includes(e)&&(a.cycle=n.path),a.schema;let o={schema:{},count:1,cycle:void 0,path:n.path};t.seen.set(e,o),t.sharedDefsExtractedFor=void 0,t.sharedEmitDoneFor=void 0;let s=e._zod.toJSONSchema?.();if(s)o.schema=s;else{let r={...n,schemaPath:[...n.schemaPath,e],path:n.path};if(e._zod.processJSONSchema)e._zod.processJSONSchema(t,o.schema,r);else{let n=o.schema,a=t.processors[i.type];if(!a)throw Error(`[toJSONSchema]: Non-representable type encountered: ${i.type}`);a(e,t,n,r)}let a=e._zod.parent;a&&(o.ref||=a,Cd(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&bd(o.schema,c),t.io===`input`&&Nd(e)&&(delete o.schema.examples,delete o.schema.default),t.io===`input`&&`_prefault`in o.schema&&((r=o.schema).default??(r.default=o.schema._prefault)),delete o.schema._prefault,t.seen.get(e).schema}function wd(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function Td(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);if(e.external&&e.sharedDefsExtractedFor===e.external)return;let r=/* @__PURE__ */ new Map;for(let t of e.seen.entries()){let n=e.metadataRegistry.get(t[0])?.id;if(n){let e=r.get(n);if(e&&e!==t[0])throw Error(`Duplicate schema id "${n}" detected during JSON Schema conversion. Two different schemas cannot share the same id when converted together.`);r.set(n,t[0])}}let i=t=>{let r=e.target===`draft-2020-12`?`$defs`:`definitions`;if(e.external){let n=e.external.registry.get(t[0])?.id,i=e.external.uri??(e=>e);if(n)return{ref:i(n)};let a=t[1].defId??t[1].schema.id??`schema${e.counter++}`;return t[1].defId=a,{defId:a,ref:`${i(`__shared`)}#/${r}/${wd(a)}`}}let i=`#/${r}/`;if(t[1]===n&&!t[1].schema.id)return{ref:`#`};let a=t[1].schema.id??`__schema${e.counter++}`;return{defId:a,ref:i+wd(a)}},a=e=>{if(e[1].schema.$ref)return;let t=e[1],{ref:n,defId:r}=i(e);t.def={...t.schema},r&&(t.defId=r);let a=t.schema;for(let e in a)delete a[e];a.$ref=n};if(e.cycles===`throw`)for(let t of e.seen.entries()){let e=t[1];if(e.cycle)throw Error(`Cycle detected: #/${e.cycle?.join(`/`)}/<root>
127
+
128
+ Set the \`cycles\` parameter to \`"ref"\` to resolve cyclical schemas with defs.`)}for(let n of e.seen.entries()){let r=n[1];if(t===n[0])a(n);else{if(e.external){let r=e.external.registry.get(n[0])?.id;if(t!==n[0]&&r){a(n);continue}}(e.metadataRegistry.get(n[0])?.id||r.cycle||r.count>1&&e.reused===`ref`)&&a(n)}}e.external&&(e.sharedDefsExtractedFor=e.external)}function Ed(e){let t=e.anyOf;if(!Array.isArray(t)||t.length===0||e.type!==void 0)return;let n=[];for(let e of t){if(!e||typeof e!=`object`)return;Ed(e);let t=Object.keys(e);if(t.length!==1||t[0]!==`type`)return;let r=e.type;for(let e of Array.isArray(r)?r:[r]){if(typeof e!=`string`)return;n.includes(e)||n.push(e)}}delete e.anyOf,e.type=n.length===1?n[0]:n}const Dd=/* @__PURE__ */ new Set([`type`,`properties`,`required`,`additionalProperties`]),Od=[`oneOf`,`anyOf`];function kd(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function Ad(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!Dd.has(e))return null;t.push(n)}let n={},r=/* @__PURE__ */ new Set;for(let e of t){for(let r in e.properties){if(Object.prototype.hasOwnProperty.call(n,r))continue;let e=[];for(let n of t){let t=n.properties?.[r]??kd(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}Ea(n,r,e.length===1?e[0]:Ad(e)??{allOf:e})}for(let t of e.required??[])r.add(t)}let i={type:`object`,properties:n};if(r.size&&(i.required=[...r]),t.every(e=>e.additionalProperties===!1))i.additionalProperties=!1;else{let e=[];for(let n of t){let t=kd(n);t&&!e.some(e=>JSON.stringify(e)===JSON.stringify(t))&&e.push(t)}e.length===1?i.additionalProperties=e[0]:e.length>1&&(i.additionalProperties={allOf:e})}return i}function jd(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of Dd)if(t in e)return;let n=t.filter(e=>Od.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=Ad(t);else{let e=n[0],i=Od.find(t=>Array.isArray(e[t]));if(Object.keys(e).length!==1)return;let a=t.filter(t=>t!==e),o=e[i].map(e=>Ad([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,bd(e,r))}function Md(e,t){let n=e.seen.get(t);if(!n)throw Error(`Unprocessed schema. This is a bug in Zod.`);let r=t=>{let n=e.seen.get(t);if(n.ref===null)return;let i=n.def??n.schema,a={...i},o=n.ref;if(n.ref=null,o){r(o);let n=e.seen.get(o),s=n.schema;if(s.$ref&&(e.target===`draft-07`||e.target===`draft-04`||e.target===`openapi-3.0`)?(i.allOf=i.allOf??[],i.allOf.push(s)):bd(i,s),bd(i,a),t._zod.parent===o)for(let e in i)e!==`$ref`&&e!==`allOf`&&(e in a||delete i[e]);if(s.$ref&&n.def)for(let e in i)e!==`$ref`&&e!==`allOf`&&e in n.def&&JSON.stringify(i[e])===JSON.stringify(n.def[e])&&delete i[e]}let s=t._zod.parent;if(s&&s!==o){r(s);let t=e.seen.get(s);if(t?.schema.$ref&&(i.$ref=t.schema.$ref,t.def))for(let e in i)e!==`$ref`&&e!==`allOf`&&e in t.def&&JSON.stringify(i[e])===JSON.stringify(t.def[e])&&delete i[e]}e.override({zodSchema:t,jsonSchema:i,path:n.path??[]})};if(!e.external||e.sharedEmitDoneFor!==e.external){for(let t of[...e.seen.entries()].reverse())r(t[0]);if(e.target!==`openapi-3.0`)for(let t of e.seen.entries())Ed(t[1].def??t[1].schema);for(let t of e.deferred)t();if(e.intersections.length){let t=/* @__PURE__ */ new Map;for(let n of e.seen.values())for(let e of[n.schema,n.def]){let n=e?.allOf;if(!Array.isArray(n))continue;let r=t.get(n);r?r.push(e):t.set(n,[e])}for(let n of e.intersections)for(let e of t.get(n)??[])jd(e)}}let i={};if(e.target===`draft-2020-12`?i.$schema=`https://json-schema.org/draft/2020-12/schema`:e.target===`draft-07`?i.$schema=`http://json-schema.org/draft-07/schema#`:e.target===`draft-04`?i.$schema=`http://json-schema.org/draft-04/schema#`:e.target,e.external?.uri){let n=e.external.registry.get(t)?.id;if(!n)throw Error("Schema is missing an `id` property");i.$id=e.external.uri(n)}bd(i,n.defId?n.schema:n.def??n.schema);let a=e.metadataRegistry.get(t)?.id;a!==void 0&&i.id===a&&delete i.id;let o=e.external?.defs??{};if(!e.external||e.sharedEmitDoneFor!==e.external)for(let t of e.seen.entries()){let e=t[1];e.def&&e.defId&&(e.def.id===e.defId&&delete e.def.id,Ea(o,e.defId,e.def))}e.external&&(e.sharedEmitDoneFor=e.external),e.external||Object.keys(o).length>0&&(e.target===`draft-2020-12`?i.$defs=o:i.definitions=o);try{let n=JSON.parse(JSON.stringify(i));return Object.defineProperty(n,"~standard",{value:{...t[`~standard`],jsonSchema:{input:Fd(t,`input`,e.processors),output:Fd(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function Nd(e,t){let n=t??{seen:/* @__PURE__ */ new Set};if(n.seen.has(e))return!1;n.seen.add(e);let r=e._zod.def;if(r.type===`transform`)return!0;if(r.type===`array`)return Nd(r.element,n);if(r.type===`set`)return Nd(r.valueType,n);if(r.type===`lazy`)return Nd(r.getter(),n);if(r.type===`promise`||r.type===`optional`||r.type===`nonoptional`||r.type===`nullable`||r.type===`readonly`||r.type==="default"||r.type===`prefault`||r.type===`catch`)return Nd(r.innerType,n);if(r.type===`intersection`)return Nd(r.left,n)||Nd(r.right,n);if(r.type===`record`||r.type===`map`)return Nd(r.keyType,n)||Nd(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:Nd(r.in,n)||Nd(r.out,n);if(r.type===`object`){for(let e in r.shape)if(Nd(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(Nd(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(Nd(e,n))return!0;return!!(r.rest&&Nd(r.rest,n))}return!1}const Pd=(e,t={})=>n=>{let r=xd({...n,processors:t});return Cd(e,r),Td(r,e),Md(r,e)},Fd=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=xd({...i??{},target:a,io:t,processors:n});return Cd(e,o),Td(o,e),Md(o,e)},Id=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},Ld=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},Rd=(e,t)=>{Id(e,`minimum`,t),Ld(e,`maximum`,t)},zd=(e,t)=>{e.multipleOf??=[],e.multipleOf.includes(t)||e.multipleOf.push(t)},Bd=(e,t)=>{e.patterns??=/* @__PURE__ */ new Set,e.patterns.add(t)},Vd=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},Hd=(e,t)=>{e.format=t,t.includes(`int`)&&(e.isInt=!0)},Ud=(e,t)=>Id(e,`minimum`,t.minimum),Wd=(e,t)=>Ld(e,`maximum`,t.maximum),Gd=e=>(t,n)=>{Hd(t,n.format);let[r,i]=e[n.format];Id(t,`minimum`,r),Ld(t,`maximum`,i)},Kd={greater_than:(e,t)=>Id(e,t.inclusive?`minimum`:`exclusiveMinimum`,t.value),less_than:(e,t)=>Ld(e,t.inclusive?`maximum`:`exclusiveMaximum`,t.value),multiple_of:(e,t)=>zd(e,t.value),number_format:Gd(Ka),bigint_format:Gd(qa),min_length:Ud,max_length:Wd,length_equals:(e,t)=>Rd(e,t.length),min_size:Ud,max_size:Wd,size_equals:(e,t)=>Rd(e,t.size),string_format:(e,t)=>{Hd(e,t.format),t.pattern&&Bd(e,t.pattern),(t.format===`base64`||t.format===`base64url`)&&(e.contentEncoding=t.format),(t.local||t.precision===-1)&&(e.laxFormat=!0)},mime_type:(e,t)=>Vd(e,t.mime)};function qd(e){let t={},n=e._zod.def,r=e._zod.traits.has(`$ZodCheck`)?[e,...n.checks??[]]:n.checks??[];for(let e of r)Kd[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;i.minimum!==void 0&&Id(t,`minimum`,i.minimum),i.exclusiveMinimum!==void 0&&Id(t,`exclusiveMinimum`,i.exclusiveMinimum),i.maximum!==void 0&&Ld(t,`maximum`,i.maximum),i.exclusiveMaximum!==void 0&&Ld(t,`exclusiveMaximum`,i.exclusiveMaximum),i.multipleOf!==void 0&&zd(t,i.multipleOf),i.format!==void 0&&(t.format??=i.format,i.format.includes(`int`)&&(t.isInt=!0)),i.mime&&Vd(t,i.mime);for(let e of i.patterns??[])Bd(t,e);return t}const Jd={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Yd=/* @__PURE__ */ new Map([[Xc,js],[Qc,Ms]]),Xd=e=>Yd.get(e)??e,Zd=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=qd(e);if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Jd[s]??s,i.format===``&&delete i.format,(s===`time`||u)&&delete i.format),l&&(i.contentEncoding=l),c&&c.size>0){let e=[...c].map(Xd);e.length===1?i.pattern=e[0].source:e.length>1&&(i.allOf=[...e.map(e=>({...t.target===`draft-07`||t.target===`draft-04`||t.target===`openapi-3.0`?{type:`string`}:{},pattern:e.source}))])}},Qd=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=qd(e);i.type=u?`integer`:`number`;let d=typeof l==`number`&&l>=(a??-1/0),f=typeof c==`number`&&c<=(o??1/0),p=t.target===`draft-04`||t.target===`openapi-3.0`;if(d?p?(i.minimum=l,i.exclusiveMinimum=!0):i.exclusiveMinimum=l:typeof a==`number`&&(i.minimum=a),f?p?(i.maximum=c,i.exclusiveMaximum=!0):i.exclusiveMaximum=c:typeof o==`number`&&(i.maximum=o),s){let n=/* @__PURE__ */ new Set;for(let a of s)Number.isFinite(a)&&a!==0?n.add(Math.abs(a)):Sd(e,t,i,r,`A multipleOf divisor of ${a} cannot be represented in JSON Schema`);let[a,...o]=n;a!==void 0&&(i.multipleOf=a),o.length&&(i.allOf=[...i.allOf??[],...o.map(e=>({multipleOf:e}))])}},$d=(e,t,n,r)=>{n.type=`boolean`},ef=(e,t,n,r)=>{Sd(e,t,n,r,`BigInt cannot be represented in JSON Schema`)},tf=(e,t,n,r)=>{Sd(e,t,n,r,`Symbols cannot be represented in JSON Schema`)},nf=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},rf=(e,t,n,r)=>{Sd(e,t,n,r,`Undefined cannot be represented in JSON Schema`)},af=(e,t,n,r)=>{Sd(e,t,n,r,`Void cannot be represented in JSON Schema`)},of=(e,t,n,r)=>{n.not={}},sf=(e,t,n,r)=>{},cf=(e,t,n,r)=>{},lf=(e,t,n,r)=>{Sd(e,t,n,r,`Date cannot be represented in JSON Schema`)},uf=(e,t,n,r)=>{let i=e._zod.def,a=va(i.entries);a.length===0?n.not={}:(a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),n.enum=a)},df=(e,t,n,r)=>{let i=e._zod.def;if(i.values.length===0){n.not={};return}let a=[];for(let o of i.values)if(o===void 0){if(Sd(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof o==`bigint`){if(Sd(e,t,n,r,`BigInt literals cannot be represented in JSON Schema`))return;a.push(Number(o))}else a.push(o);if(a.length!==0){if(a.length===1){let e=a[0];n.type=e===null?`null`:typeof e,t.target===`draft-04`||t.target===`openapi-3.0`?n.enum=[e]:n.const=e}else a.every(e=>typeof e==`number`)&&(n.type=`number`),a.every(e=>typeof e==`string`)&&(n.type=`string`),a.every(e=>typeof e==`boolean`)&&(n.type=`boolean`),a.every(e=>e===null)&&(n.type=`null`),n.enum=a}},ff=(e,t,n,r)=>{Sd(e,t,n,r,`NaN cannot be represented in JSON Schema`)},pf=(e,t,n,r)=>{let i=n,a=e._zod.pattern;if(!a)throw Error(`Pattern not found in template literal`);i.type=`string`,i.pattern=a.source},mf=(e,t,n,r)=>{let i=n;i.type=`string`,i.format=`binary`,i.contentEncoding=`binary`;let{minimum:a,maximum:o,mime:s}=qd(e);a!==void 0&&(i.minLength=a),o!==void 0&&(i.maxLength=o),s&&(s.length===0?i.not={}:s.length===1?i.contentMediaType=s[0]:i.anyOf=s.map(e=>({contentMediaType:e})))},hf=(e,t,n,r)=>{n.type=`boolean`},gf=(e,t,n,r)=>{Sd(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},_f=(e,t,n,r)=>{Sd(e,t,n,r,`Function types cannot be represented in JSON Schema`)},vf=(e,t,n,r)=>{Sd(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},yf=(e,t,n,r)=>{Sd(e,t,n,r,`Map cannot be represented in JSON Schema`)},bf=(e,t,n,r)=>{Sd(e,t,n,r,`Set cannot be represented in JSON Schema`)},xf=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=qd(e);typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=Cd(a.element,t,{...r,path:[...r.path,`items`]})};function Sf(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?Sf(t.out):t.type===`catch`?Sf(t.innerType):e._zod.optin}const Cf=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&Sd(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in o)Ea(i.properties,e,Cd(o[e],t,{...r,path:[...r.path,`properties`,e]}));let s=[];for(let e of Object.keys(o)){let n=a.shape[e];(t.io===`input`?Sf(n)===void 0:n._zod.optout===void 0)&&s.push(e)}s.length>0&&(i.required=s),a.catchall?._zod.def.type===`never`?i.additionalProperties=!1:a.catchall?a.catchall&&(i.additionalProperties=Cd(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},wf=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>Cd(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Tf=(e,t,n,r)=>{let i=e._zod.def,a=Cd(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=Cd(i.right,t,{...r,path:[...r.path,`allOf`,1]}),s=e=>`allOf`in e&&Object.keys(e).length===1,c=[...s(a)?a.allOf:[a],...s(o)?o.allOf:[o]];n.allOf=c,t.intersections.push(c)},Ef=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`array`;let o=t.target===`draft-2020-12`?`prefixItems`:`items`,s=t.target===`draft-2020-12`||t.target===`openapi-3.0`?`items`:`additionalItems`,c=a.items.map((e,n)=>Cd(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?Cd(a.rest,t,{...r,path:[...r.path,s,...t.target===`openapi-3.0`?[a.items.length]:[]]}):null,u=a.items.length;for(;u>0;){let e=a.items[u-1];if(!(t.io===`input`?Sf(e)!==void 0:e._zod.optout===`optional`))break;u--}let d=a.items.length,f=!a.rest;t.target===`draft-2020-12`?(i.prefixItems=c,f?i.items=!1:l&&(i.items=l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):t.target===`openapi-3.0`?(i.items={anyOf:c},l&&i.items.anyOf.push(l),u>0&&(i.minItems=u),f&&(i.maxItems=d)):(i.items=c,f?i.additionalItems=!1:l&&(i.additionalItems=l),u>0&&(i.minItems=u),f&&(i.maxItems=d));let{minimum:p,maximum:m}=qd(e);typeof p==`number`&&(i.minItems=p),typeof m==`number`&&(i.maxItems=m)};function Df(e,t,n){if(t.$ref){if(n.has(t))return t;n.add(t);let r=e.get(t)?.def;if(!r)return t;let i=Df(e,r,n);return i===r?t:i}for(let r of[`anyOf`,`oneOf`]){let i=t[r];if(!Array.isArray(i))continue;let a=i.map(t=>Df(e,t,n));a.some((e,t)=>e!==i[t])&&(t={...t,[r]:a})}let r=Array.isArray(t.type)?t.type:[t.type],i=!r.includes(`string`)&&r.some(e=>e===`number`||e===`integer`),a=t.enum??(t.const===void 0?void 0:[t.const]);if(!i&&!a?.some(e=>typeof e==`number`))return t;let{minimum:o,maximum:s,exclusiveMinimum:c,exclusiveMaximum:l,multipleOf:u,format:d,id:f,...p}=t;return p.enum?p.enum=p.enum.map(e=>typeof e==`number`?String(e):e):typeof p.const==`number`&&(p.const=String(p.const)),i&&(p.type=`string`,a||(p.pattern=(r.includes(`number`)?Us:Hs).source)),p}const Of=/* @__PURE__ */ new WeakMap;function kf(e){let t=/* @__PURE__ */ new Map;for(let n of e.seen.values())n.def&&!t.has(n.schema)&&t.set(n.schema,n);let n=/* @__PURE__ */ new Map;for(let r of Of.get(e)??[]){let i=e.seen.get(r),a=(i?.def??i?.schema)?.propertyNames;if(!a||a===!0||n.has(a))continue;let o=Df(t,a,/* @__PURE__ */ new Set);o!==a&&n.set(a,o)}if(n.size)for(let t of e.seen.values())for(let e of[t.schema,t.def]){let t=e&&n.get(e.propertyNames);t&&(e.propertyNames=t)}}const Af=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=qd(o).patterns;if(a.mode===`loose`&&s&&s.size>0){let e=Cd(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)Ea(i.patternProperties,Xd(t).source,e)}else{if(t.target===`draft-07`||t.target===`draft-2020-12`){i.propertyNames=Cd(a.keyType,t,{...r,path:[...r.path,`propertyNames`]});let n=Of.get(t);n||(n=[],Of.set(t,n),t.deferred.push(()=>kf(t))),n.push(e)}i.additionalProperties=Cd(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]})}let c=o._zod.values,l=t.io===`input`&&Sf(a.valueType)!==void 0;if(c&&!a.partial&&!l){let e=[...c].filter(e=>typeof e==`string`||typeof e==`number`);e.length>0&&(i.required=e.map(String))}},jf=(e,t,n,r)=>{let i=e._zod.def,a=Cd(i.innerType,t,r),o=t.seen.get(e);t.target===`openapi-3.0`?(o.ref=i.innerType,n.nullable=!0):n.anyOf=[a,{type:`null`}]},Mf=(e,t,n,r)=>{let i=e._zod.def;Cd(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Nf=Symbol();function Pf(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(Sd(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),Nf):JSON.parse(o)}const Ff=(e,t,n,r)=>{let i=e._zod.def;Cd(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=Pf(i.defaultValue,e,t,n,r);o!==Nf&&(n.default=o)},If=(e,t,n,r)=>{let i=e._zod.def;Cd(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=Pf(i.defaultValue,e,t,n,r);o!==Nf&&(n._prefault=o)},Lf=(e,t,n,r)=>{let i=e._zod.def;Cd(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{Sd(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},Rf=(e,t,n,r)=>{let i=e._zod.def,a=i.in._zod.traits.has(`$ZodTransform`),o=t.io===`input`?a?i.out:i.in:i.out;Cd(o,t,r);let s=t.seen.get(e);s.ref=o},zf=(e,t,n,r)=>{let i=e._zod.def;Cd(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},Bf=(e,t,n,r)=>{let i=e._zod.def;Cd(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Vf=(e,t,n,r)=>{let i=e._zod.def;Cd(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Hf={string:Zd,number:Qd,boolean:$d,bigint:ef,symbol:tf,null:nf,undefined:rf,void:af,never:of,any:sf,unknown:cf,date:lf,enum:uf,literal:df,nan:ff,template_literal:pf,file:mf,success:hf,custom:gf,function:_f,transform:vf,map:yf,set:bf,array:xf,object:Cf,union:wf,intersection:Tf,tuple:Ef,record:Af,nullable:jf,nonoptional:Mf,default:Ff,prefault:If,catch:Lf,pipe:Rf,readonly:zf,promise:Bf,optional:Vf,lazy:(e,t,n,r)=>{let i=e._zod.innerType;Cd(i,t,r);let a=t.seen.get(e);a.ref=i}};function Uf(e,t){if(`_idmap`in e){let n=e,r=xd({...t,processors:Hf}),i={};for(let e of n._idmap.entries()){let[t,n]=e;Cd(n,r)}let a={};r.external={registry:n,uri:t?.uri,defs:i};for(let e of n._idmap.entries()){let[t,n]=e;Td(r,n),Ea(a,t,Md(r,n))}return Object.keys(i).length>0&&(a.__shared={[r.target===`draft-2020-12`?`$defs`:`definitions`]:i}),{schemas:a}}let n=xd({...t,processors:Hf});return Cd(e,n),Td(n,e),Md(n,e)}const Wf=/*@__PURE__*/ B(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);mc.init(e,t),e.def=t,e.type=t.type},{get with(){return this.check},set with(e){_o(this,`with`,e)},parse(e,t){return Jo(this,e,t,{callee:this.parse})},parseAsync(e,t){return Xo(this,e,t,{callee:this.parseAsync})},safeParse(e,t){return Qo(this,e,t)},safeParseAsync(e,t){return ts(this,e,t)},check(...e){let t=this.def;return this.clone({...t,checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]},{parent:!0})},clone(e,t){return Ua(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},apply(e,...t){return t.length===0?e(this):e(this,...t)}}),Gf=/*@__PURE__*/ B(`ZodMiniObject`,(e,t)=>{vl.init(e,t),Wf.init(e,t),To(e,`shape`,e=>e._zod.def.shape,!1)});// @__NO_SIDE_EFFECTS__
129
+ function Kf(e,t){let n={type:`object`,shape:e??{},...R(t)};return new Gf(n)}function qf(e){return!!e._zod}function Jf(e){let t=Object.values(e);if(t.length===0)return/* @__PURE__ */ Kf({});let n=t.every(qf),r=t.every(e=>!qf(e));if(n)return/* @__PURE__ */ Kf(e);if(r)return _a(e);throw Error(`Mixed Zod versions detected in object shape.`)}function Yf(e,t){return qf(e)?Qo(e,t):e.safeParse(t)}async function Xf(e,t){return qf(e)?await ts(e,t):await e.safeParseAsync(t)}function Zf(e){if(!e)return;let t;if(t=qf(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function Qf(e){if(e){if(typeof e==`object`){let t=e,n=e;if(!t._def&&!n._zod){let t=Object.values(e);if(t.length>0&&t.every(e=>typeof e==`object`&&!!e&&(e._def!==void 0||e._zod!==void 0||typeof e.parse==`function`)))return Jf(e)}}if(qf(e)){let t=e._zod?.def;if(t&&(t.type===`object`||t.shape!==void 0))return e}else if(e.shape!==void 0)return e}}function $f(e){return e.length===0?`object root`:e.reduce((e,t,n)=>n===0?String(t):typeof t==`number`?`${e}[${t}]`:`${e}.${t}`,``)}function ep(e){if(e&&typeof e==`object`){if(`issues`in e&&Array.isArray(e.issues)&&e.issues.length>0)return e.issues.map(e=>e.path?.length?`${e.message} at ${$f(e.path)}`:e.message).join(`
130
+ `);if(`message`in e&&typeof e.message==`string`)return e.message;try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function tp(e){return e.description}function np(e){if(qf(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function rp(e){if(qf(e)){let t=e._zod?.def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}}let t=e._def;if(t){if(t.value!==void 0)return t.value;if(Array.isArray(t.values)&&t.values.length>0)return t.values[0]}let n=e.value;if(n!==void 0)return n}const ip=/* @__PURE__ */ new WeakSet([Object.prototype,Error.prototype]);function ap(e,t,n){Object.defineProperty(e,t,{configurable:!0,enumerable:!1,get(){let e=n(this);return Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0}),e},set(e){Object.defineProperty(this,t,{value:e,configurable:!0,writable:!0})}})}const op=/*@__PURE__*/ B(`ZodError`,(e,t)=>{Vo.init(e,t),e.name=`ZodError`;let n=Object.getPrototypeOf(e);ip.has(n)||(ip.add(n),ap(n,`format`,e=>t=>Go(e,t)),ap(n,`flatten`,e=>t=>Wo(e,t)),ap(n,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,ba,2)}),ap(n,`addIssues`,e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,ba,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},void 0,{Parent:Error}),sp=/* @__PURE__ */ qo(op),cp=/* @__PURE__ */ Yo(op),lp=/* @__PURE__ */ Zo(op),up=/* @__PURE__ */ es(op),dp=/* @__PURE__ */ ss(op),fp=/* @__PURE__ */ cs(op),pp=/* @__PURE__ */ ls(op),mp=/* @__PURE__ */ us(op),hp=/* @__PURE__ */ ds(op),gp=/* @__PURE__ */ fs(op),_p=/* @__PURE__ */ ps(op),vp=/* @__PURE__ */ ms(op);function yp(){No.localeError||Po(uu())}function bp(){No.memoizer||Po({memoizer:su()})}const xp=/*@__PURE__*/ B(`ZodType`,(e,t)=>(yp(),mc.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(Na(t,{checks:[...t.checks??[],...e.map(e=>typeof e==`function`?{_zod:{check:e,def:{check:`custom`},onattach:[]}}:e)]}),{parent:!0})},with(...e){return this.check(...e)},clone(e,t){return Ua(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Hm(e,t))},superRefine(e,t){return this.check(Um(e,t))},overwrite(e){return this.check(/* @__PURE__ */ ld(e))},optional(){return Sm(this)},exactOptional(){return wm(this)},nullable(){return Em(this)},nullish(){return Sm(Em(this))},nonoptional(e){return Mm(this,e)},array(){return U(this)},or(e){return lm([this,e])},and(e){return pm(this,e)},transform(e){return Im(this,bm(e))},default(e){return Om(this,e)},prefault(e){return Am(this,e)},catch(e){return Pm(this,e)},pipe(e){return Im(this,e)},readonly(){return zm(this)},describe(e){let t=this.clone();return mu.add(t,{description:e}),t},meta(...e){if(e.length===0)return mu.get(this);let t=this.clone();return mu.add(t,e[0]),t},isOptional(){return this.safeParse(void 0).success},isNullable(){return this.safeParse(null).success},apply(e,...t){return t.length===0?e(this):e(this,...t)},get"~standard"(){return vo(this,`~standard`,{..._c(this),jsonSchema:{input:Fd(this,`input`),output:Fd(this,`output`)}})},set"~standard"(e){_o(this,`~standard`,e)},parse:function e(t,n){return sp(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await cp(this,t,n,{callee:e})},safeParse(e,t){return lp(this,e,t)},async safeParseAsync(e,t){return up(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){_o(this,`spa`,e)},validate(e,t){return is(this,e,t)},validateAsync(e,t){return os(this,e,t)},encode:function e(t,n){return dp(this,t,n,{callee:e})},decode:function e(t,n){return fp(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await pp(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await mp(this,t,n,{callee:e})},safeEncode(e,t){return hp(this,e,t)},safeDecode(e,t){return gp(this,e,t)},async safeEncodeAsync(e,t){return _p(this,e,t)},async safeDecodeAsync(e,t){return vp(this,e,t)},toJSONSchema(e){return Pd(this,{})(e)},get description(){return mu.get(this)?.description},get _def(){return this._zod.def}}),Sp=/*@__PURE__*/ B(`_ZodString`,(e,t)=>{vc.init(e,t),xp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Zd(e,t,n,r)},/*@__PURE__*/ yo({format:e=>qd(e).format??null,minLength:e=>qd(e).minimum??null,maxLength:e=>qd(e).maximum??null},{regex(...e){return this.check(/* @__PURE__ */ rd(...e))},includes(...e){return this.check(/* @__PURE__ */ od(...e))},startsWith(...e){return this.check(/* @__PURE__ */ sd(...e))},endsWith(...e){return this.check(/* @__PURE__ */ cd(...e))},min(...e){return this.check(/* @__PURE__ */ td(...e))},max(...e){return this.check(/* @__PURE__ */ ed(...e))},length(...e){return this.check(/* @__PURE__ */ nd(...e))},nonempty(...e){return this.check(/* @__PURE__ */ td(1,...e))},lowercase(e){return this.check(/* @__PURE__ */ id(e))},uppercase(e){return this.check(/* @__PURE__ */ ad(e))},trim(){return this.check(/* @__PURE__ */ dd())},normalize(...e){return this.check(/* @__PURE__ */ ud(...e))},toLowerCase(){return this.check(/* @__PURE__ */ fd())},toUpperCase(){return this.check(/* @__PURE__ */ pd())},slugify(){return this.check(/* @__PURE__ */ md())}})),Cp=/*@__PURE__*/ B(`ZodString`,(e,t)=>{vc.init(e,t),Sp.init(e,t)},{email(e){return this.check(/* @__PURE__ */ _u(kp,e))},url(e){return this.check(/* @__PURE__ */ Cu(Mp,e))},jwt(e){return this.check(/* @__PURE__ */ Ru(qp,e))},emoji(e){return this.check(/* @__PURE__ */ wu(Np,e))},guid(e){return this.check(/* @__PURE__ */ vu(Ap,e))},uuid(e){return this.check(/* @__PURE__ */ yu(jp,e))},uuidv4(e){return this.check(/* @__PURE__ */ bu(jp,e))},uuidv6(e){return this.check(/* @__PURE__ */ xu(jp,e))},uuidv7(e){return this.check(/* @__PURE__ */ Su(jp,e))},nanoid(e){return this.check(/* @__PURE__ */ Tu(Pp,e))},cuid(e){return this.check(/* @__PURE__ */ Eu(Fp,e))},cuid2(e){return this.check(/* @__PURE__ */ Du(Ip,e))},ulid(e){return this.check(/* @__PURE__ */ Ou(Lp,e))},base64(e){return this.check(/* @__PURE__ */ Fu(Wp,e))},base64url(e){return this.check(/* @__PURE__ */ Iu(Gp,e))},xid(e){return this.check(/* @__PURE__ */ ku(Rp,e))},ksuid(e){return this.check(/* @__PURE__ */ Au(zp,e))},ipv4(e){return this.check(/* @__PURE__ */ ju(Bp,e))},ipv6(e){return this.check(/* @__PURE__ */ Mu(Vp,e))},cidrv4(e){return this.check(/* @__PURE__ */ Nu(Hp,e))},cidrv6(e){return this.check(/* @__PURE__ */ Pu(Up,e))},e164(e){return this.check(/* @__PURE__ */ Lu(Kp,e))},datetime(e){return this.check(/* @__PURE__ */ zu(Tp,e))},date(e){return this.check(/* @__PURE__ */ Bu(Ep,e))},time(e){return this.check(/* @__PURE__ */ Vu(Dp,e))},duration(e){return this.check(/* @__PURE__ */ Hu(Op,e))}});function V(e){return/* @__PURE__ */ gu(Cp,e)}const wp=/*@__PURE__*/ B(`ZodStringFormat`,(e,t)=>{yc.init(e,t),Sp.init(e,t)}),Tp=/*@__PURE__*/ B(`ZodISODateTime`,(e,t)=>{Rc.init(e,t),wp.init(e,t)}),Ep=/*@__PURE__*/ B(`ZodISODate`,(e,t)=>{zc.init(e,t),wp.init(e,t)}),Dp=/*@__PURE__*/ B(`ZodISOTime`,(e,t)=>{Bc.init(e,t),wp.init(e,t)}),Op=/*@__PURE__*/ B(`ZodISODuration`,(e,t)=>{Vc.init(e,t),wp.init(e,t)}),kp=/*@__PURE__*/ B(`ZodEmail`,(e,t)=>{Sc.init(e,t),wp.init(e,t)}),Ap=/*@__PURE__*/ B(`ZodGUID`,(e,t)=>{bc.init(e,t),wp.init(e,t)}),jp=/*@__PURE__*/ B(`ZodUUID`,(e,t)=>{xc.init(e,t),wp.init(e,t)}),Mp=/*@__PURE__*/ B(`ZodURL`,(e,t)=>{Ac.init(e,t),wp.init(e,t)}),Np=/*@__PURE__*/ B(`ZodEmoji`,(e,t)=>{jc.init(e,t),wp.init(e,t)}),Pp=/*@__PURE__*/ B(`ZodNanoID`,(e,t)=>{Mc.init(e,t),wp.init(e,t)}),Fp=/*@__PURE__*/ B(`ZodCUID`,(e,t)=>{Nc.init(e,t),wp.init(e,t)}),Ip=/*@__PURE__*/ B(`ZodCUID2`,(e,t)=>{Pc.init(e,t),wp.init(e,t)}),Lp=/*@__PURE__*/ B(`ZodULID`,(e,t)=>{Fc.init(e,t),wp.init(e,t)}),Rp=/*@__PURE__*/ B(`ZodXID`,(e,t)=>{Ic.init(e,t),wp.init(e,t)}),zp=/*@__PURE__*/ B(`ZodKSUID`,(e,t)=>{Lc.init(e,t),wp.init(e,t)}),Bp=/*@__PURE__*/ B(`ZodIPv4`,(e,t)=>{Hc.init(e,t),wp.init(e,t)}),Vp=/*@__PURE__*/ B(`ZodIPv6`,(e,t)=>{Gc.init(e,t),wp.init(e,t)}),Hp=/*@__PURE__*/ B(`ZodCIDRv4`,(e,t)=>{Kc.init(e,t),wp.init(e,t)}),Up=/*@__PURE__*/ B(`ZodCIDRv6`,(e,t)=>{Jc.init(e,t),wp.init(e,t)}),Wp=/*@__PURE__*/ B(`ZodBase64`,(e,t)=>{Zc.init(e,t),wp.init(e,t)}),Gp=/*@__PURE__*/ B(`ZodBase64URL`,(e,t)=>{el.init(e,t),wp.init(e,t)}),Kp=/*@__PURE__*/ B(`ZodE164`,(e,t)=>{tl.init(e,t),wp.init(e,t)}),qp=/*@__PURE__*/ B(`ZodJWT`,(e,t)=>{rl.init(e,t),wp.init(e,t)}),Jp=/*@__PURE__*/ B(`ZodNumber`,(e,t)=>{il.init(e,t),xp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Qd(e,t,n,r),e.isFinite=!0},/*@__PURE__*/ yo({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=qd(e);return Math.max(t??-1/0,n??-1/0)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=qd(e);return Math.min(t??1/0,n??1/0)},isInt:e=>{let{isInt:t,multipleOf:n}=qd(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>qd(e).format??null},{gt(e,t){return this.check(/* @__PURE__ */ Zu(e,t))},gte(e,t){return this.check(/* @__PURE__ */ Qu(e,t))},min(e,t){return this.check(/* @__PURE__ */ Qu(e,t))},lt(e,t){return this.check(/* @__PURE__ */ Yu(e,t))},lte(e,t){return this.check(/* @__PURE__ */ Xu(e,t))},max(e,t){return this.check(/* @__PURE__ */ Xu(e,t))},int(e){return this.check(Xp(e))},safe(e){return this.check(Xp(e))},positive(e){return this.check(/* @__PURE__ */ Zu(0,e))},nonnegative(e){return this.check(/* @__PURE__ */ Qu(0,e))},negative(e){return this.check(/* @__PURE__ */ Yu(0,e))},nonpositive(e){return this.check(/* @__PURE__ */ Xu(0,e))},multipleOf(e,t){return this.check(/* @__PURE__ */ $u(e,t))},step(e,t){return this.check(/* @__PURE__ */ $u(e,t))},finite(){return this}}));function H(e){return/* @__PURE__ */ Uu(Jp,e)}const Yp=/*@__PURE__*/ B(`ZodNumberFormat`,(e,t)=>{al.init(e,t),Jp.init(e,t)});function Xp(e){return/* @__PURE__ */ Wu(Yp,e)}const Zp=/*@__PURE__*/ B(`ZodBoolean`,(e,t)=>{ol.init(e,t),xp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$d(e,t,n,r)});function Qp(e){return/* @__PURE__ */ Gu(Zp,e)}const $p=/*@__PURE__*/ B(`ZodNull`,(e,t)=>{sl.init(e,t),xp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>nf(e,t,n,r)});function em(e){return/* @__PURE__ */ Ku($p,e)}const tm=/*@__PURE__*/ B(`ZodUnknown`,(e,t)=>{cl.init(e,t),xp.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function nm(){return/* @__PURE__ */ qu(tm)}const rm=/*@__PURE__*/ B(`ZodNever`,(e,t)=>{ll.init(e,t),xp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>of(e,t,n,r)});function im(e){return/* @__PURE__ */ Ju(rm,e)}const am=/*@__PURE__*/ B(`ZodArray`,(e,t)=>{bp(),pl.init(e,t),xp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>xf(e,t,n,r),e.element=t.element},{min(e,t){return this.check(/* @__PURE__ */ td(e,t))},nonempty(e){return this.check(/* @__PURE__ */ td(1,e))},max(e,t){return this.check(/* @__PURE__ */ ed(e,t))},length(e,t){return this.check(/* @__PURE__ */ nd(e,t))},unwrap(){return this.element}});function U(e,t){return/* @__PURE__ */ hd(am,e,t)}const om=/*@__PURE__*/ B(`ZodObject`,(e,t)=>{bp(),yl.init(e,t),xp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Cf(e,t,n,r),To(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return _m(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(Na(this._zod.def,{catchall:e}))},passthrough(){return this.clone(Na(this._zod.def,{catchall:nm()}))},loose(){return this.clone(Na(this._zod.def,{catchall:nm()}))},strict(){return this.clone(Na(this._zod.def,{catchall:im()}))},strip(){return this.clone(Na(this._zod.def,{catchall:void 0}))},extend(e){return Za(this,e)},safeExtend(e){return $a(this,e)},merge(e){return eo(this,e)},pick(e){return Ja(this,e)},omit(e){return Xa(this,e)},partial(...e){return to(xm,this,e[0])},exactPartial(...e){return to(Cm,this,e[0],`exactPartial`)},required(...e){return no(jm,this,e[0])}});function W(e,t){let n={type:`object`,shape:e??{},...R(t)};return new om(n)}function sm(e,t){return new om({type:`object`,shape:e,catchall:nm(),...R(t)})}const cm=/*@__PURE__*/ B(`ZodUnion`,(e,t)=>{xl.init(e,t),xp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>wf(e,t,n,r),e.options=t.options});function lm(e,t){return new cm({type:`union`,options:e,...R(t)})}const um=/*@__PURE__*/ B(`ZodDiscriminatedUnion`,(e,t)=>{cm.init(e,t),Cl.init(e,t)});function dm(e,t,n){return new um({type:`union`,options:t,discriminator:e,...R(n)})}const fm=/*@__PURE__*/ B(`ZodIntersection`,(e,t)=>{wl.init(e,t),xp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Tf(e,t,n,r)});function pm(e,t){return new fm({type:`intersection`,left:e,right:t})}const mm=/*@__PURE__*/ B(`ZodRecord`,(e,t)=>{bp(),Dl.init(e,t),xp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Af(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function hm(e,t,n){return!t||!t._zod?new mm({type:`record`,keyType:V(),valueType:e,...R(t)}):new mm({type:`record`,keyType:e,valueType:t,...R(n)})}const gm=/*@__PURE__*/ B(`ZodEnum`,(e,t)=>{Ol.init(e,t),xp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>uf(e,t,n,r),e.enum=t.entries,e.options=[...e._zod.values];let n=new Set(Object.keys(t.entries));e.extract=(e,r)=>{let i={};for(let r of e)if(n.has(r))i[r]=t.entries[r];else throw Error(`Key ${r} not found in enum`);return new gm({...t,checks:[],...R(r),entries:i})},e.exclude=(e,r)=>{let i={...t.entries};for(let t of e)if(n.has(t))delete i[t];else throw Error(`Key ${t} not found in enum`);return new gm({...t,checks:[],...R(r),entries:i})}});function _m(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new gm({type:`enum`,entries:n,...R(t)})}const vm=/*@__PURE__*/ B(`ZodLiteral`,(e,t)=>{kl.init(e,t),xp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>df(e,t,n,r),e.values=new Set(t.values),Object.defineProperty(e,"value",{get(){if(t.values.length>1)throw Error("This schema contains multiple valid literal values. Use `.values` instead.");return t.values[0]}})});function G(e,t){return new vm({type:`literal`,values:Array.isArray(e)?e:[e],...R(t)})}const ym=/*@__PURE__*/ B(`ZodTransform`,(e,t)=>{bp(),Al.init(e,t),xp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vf(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Mo(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(ho(r,n.value,t));else{let t=r;t.fatal&&(t.continue=!1),t.code??=`custom`,`input`in t||(t.input=n.value),t.inst??=e,n.issues.push(ho(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function bm(e){return new ym({type:`transform`,transform:e})}const xm=/*@__PURE__*/ B(`ZodOptional`,(e,t)=>{Ml.init(e,t),xp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Vf(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Sm(e){return new xm({type:`optional`,innerType:e})}const Cm=/*@__PURE__*/ B(`ZodExactOptional`,(e,t)=>{Nl.init(e,t),xp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Vf(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function wm(e){return new Cm({type:`optional`,innerType:e})}const Tm=/*@__PURE__*/ B(`ZodNullable`,(e,t)=>{Pl.init(e,t),xp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>jf(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Em(e){return new Tm({type:`nullable`,innerType:e})}const Dm=/*@__PURE__*/ B(`ZodDefault`,(e,t)=>{Fl.init(e,t),xp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ff(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Om(e,t){return new Dm({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():Ba(t)}})}const km=/*@__PURE__*/ B(`ZodPrefault`,(e,t)=>{Ll.init(e,t),xp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>If(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Am(e,t){return new km({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():Ba(t)}})}const jm=/*@__PURE__*/ B(`ZodNonOptional`,(e,t)=>{Rl.init(e,t),xp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Mf(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Mm(e,t){return new jm({type:`nonoptional`,innerType:e,...R(t)})}const Nm=/*@__PURE__*/ B(`ZodCatch`,(e,t)=>{Vl.init(e,t),xp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Lf(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Pm(e,t){return new Nm({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:Eo(t)})}const Fm=/*@__PURE__*/ B(`ZodPipe`,(e,t)=>{Hl.init(e,t),xp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Rf(e,t,n,r),e.in=t.in,e.out=t.out});function Im(e,t){return new Fm({type:`pipe`,in:e,out:t})}const Lm=/*@__PURE__*/ B(`ZodPreprocess`,(e,t)=>{Fm.init(e,t),Wl.init(e,t)}),Rm=/*@__PURE__*/ B(`ZodReadonly`,(e,t)=>{Gl.init(e,t),xp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zf(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function zm(e){return new Rm({type:`readonly`,innerType:e})}const Bm=/*@__PURE__*/ B(`ZodCustom`,(e,t)=>{ql.init(e,t),xp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>gf(e,t,n,r)});function Vm(e,t){return/* @__PURE__ */ gd(Bm,e??(()=>!0),t)}function Hm(e,t={}){return/* @__PURE__ */ _d(Bm,e,t)}function Um(e,t){return/* @__PURE__ */ vd(e,t)}function Wm(e,t){return new Lm({type:`pipe`,in:bm(e),out:t})}function Gm(e){return/* @__PURE__ */ zu(Tp,e)}const Km=`2025-11-25`,qm=[Km,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],Jm=`io.modelcontextprotocol/related-task`,Ym=Vm(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),Xm=lm([V(),H().int()]),Zm=V();sm({ttl:H().optional(),pollInterval:H().optional()});const Qm=W({ttl:H().optional()}),$m=W({taskId:V()}),eh=sm({progressToken:Xm.optional(),[Jm]:$m.optional()}),th=W({_meta:eh.optional()}),nh=th.extend({task:Qm.optional()}),rh=e=>nh.safeParse(e).success,ih=W({method:V(),params:th.loose().optional()}),ah=W({_meta:eh.optional()}),oh=W({method:V(),params:ah.loose().optional()}),sh=sm({_meta:eh.optional()}),ch=lm([V(),H().int()]),lh=W({jsonrpc:G(`2.0`),id:ch,...ih.shape}).strict(),uh=e=>lh.safeParse(e).success,dh=W({jsonrpc:G(`2.0`),...oh.shape}).strict(),fh=e=>dh.safeParse(e).success,ph=W({jsonrpc:G(`2.0`),id:ch,result:sh}).strict(),mh=e=>ph.safeParse(e).success;var K;(function(e){e[e.ConnectionClosed=-32e3]=`ConnectionClosed`,e[e.RequestTimeout=-32001]=`RequestTimeout`,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.UrlElicitationRequired=-32042]=`UrlElicitationRequired`})(K||={});const hh=W({jsonrpc:G(`2.0`),id:ch.optional(),error:W({code:H().int(),message:V(),data:nm().optional()})}).strict(),gh=e=>hh.safeParse(e).success,_h=lm([lh,dh,ph,hh]);lm([ph,hh]);const vh=sh.strict(),yh=ah.extend({requestId:ch.optional(),reason:V().optional()}),bh=oh.extend({method:G(`notifications/cancelled`),params:yh}),xh=W({icons:U(W({src:V(),mimeType:V().optional(),sizes:U(V()).optional(),theme:_m([`light`,`dark`]).optional()})).optional()}),Sh=W({name:V(),title:V().optional()}),Ch=Sh.extend({...Sh.shape,...xh.shape,version:V(),websiteUrl:V().optional(),description:V().optional()}),wh=Wm(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,pm(W({form:pm(W({applyDefaults:Qp().optional()}),hm(V(),nm())).optional(),url:Ym.optional()}),hm(V(),nm()).optional())),Th=sm({list:Ym.optional(),cancel:Ym.optional(),requests:sm({sampling:sm({createMessage:Ym.optional()}).optional(),elicitation:sm({create:Ym.optional()}).optional()}).optional()}),Eh=sm({list:Ym.optional(),cancel:Ym.optional(),requests:sm({tools:sm({call:Ym.optional()}).optional()}).optional()}),Dh=W({experimental:hm(V(),Ym).optional(),sampling:W({context:Ym.optional(),tools:Ym.optional()}).optional(),elicitation:wh.optional(),roots:W({listChanged:Qp().optional()}).optional(),tasks:Th.optional(),extensions:hm(V(),Ym).optional()}),Oh=th.extend({protocolVersion:V(),capabilities:Dh,clientInfo:Ch}),kh=ih.extend({method:G(`initialize`),params:Oh}),Ah=W({experimental:hm(V(),Ym).optional(),logging:Ym.optional(),completions:Ym.optional(),prompts:W({listChanged:Qp().optional()}).optional(),resources:W({subscribe:Qp().optional(),listChanged:Qp().optional()}).optional(),tools:W({listChanged:Qp().optional()}).optional(),tasks:Eh.optional(),extensions:hm(V(),Ym).optional()}),jh=sh.extend({protocolVersion:V(),capabilities:Ah,serverInfo:Ch,instructions:V().optional()}),Mh=oh.extend({method:G(`notifications/initialized`),params:ah.optional()}),Nh=ih.extend({method:G(`ping`),params:th.optional()}),Ph=W({progress:H(),total:Sm(H()),message:Sm(V())}),Fh=W({...ah.shape,...Ph.shape,progressToken:Xm}),Ih=oh.extend({method:G(`notifications/progress`),params:Fh}),Lh=th.extend({cursor:Zm.optional()}),Rh=ih.extend({params:Lh.optional()}),zh=sh.extend({nextCursor:Zm.optional()}),Bh=_m([`working`,`input_required`,`completed`,`failed`,`cancelled`]),Vh=W({taskId:V(),status:Bh,ttl:lm([H(),em()]),createdAt:V(),lastUpdatedAt:V(),pollInterval:Sm(H()),statusMessage:Sm(V())}),Hh=sh.extend({task:Vh}),Uh=ah.merge(Vh),Wh=oh.extend({method:G(`notifications/tasks/status`),params:Uh}),Gh=ih.extend({method:G(`tasks/get`),params:th.extend({taskId:V()})}),Kh=sh.merge(Vh),qh=ih.extend({method:G(`tasks/result`),params:th.extend({taskId:V()})});sh.loose();const Jh=Rh.extend({method:G(`tasks/list`)}),Yh=zh.extend({tasks:U(Vh)}),Xh=ih.extend({method:G(`tasks/cancel`),params:th.extend({taskId:V()})}),Zh=sh.merge(Vh),Qh=W({uri:V(),mimeType:Sm(V()),_meta:hm(V(),nm()).optional()}),$h=Qh.extend({text:V()}),eg=V().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),tg=Qh.extend({blob:eg}),ng=_m([`user`,`assistant`]),rg=W({audience:U(ng).optional(),priority:H().min(0).max(1).optional(),lastModified:Gm({offset:!0}).optional()}),ig=W({...Sh.shape,...xh.shape,uri:V(),description:Sm(V()),mimeType:Sm(V()),size:Sm(H()),annotations:rg.optional(),_meta:Sm(sm({}))}),ag=W({...Sh.shape,...xh.shape,uriTemplate:V(),description:Sm(V()),mimeType:Sm(V()),annotations:rg.optional(),_meta:Sm(sm({}))}),og=Rh.extend({method:G(`resources/list`)}),sg=zh.extend({resources:U(ig)}),cg=Rh.extend({method:G(`resources/templates/list`)}),lg=zh.extend({resourceTemplates:U(ag)}),ug=th.extend({uri:V()}),dg=ug,fg=ih.extend({method:G(`resources/read`),params:dg}),pg=sh.extend({contents:U(lm([$h,tg]))}),mg=oh.extend({method:G(`notifications/resources/list_changed`),params:ah.optional()}),hg=ug,gg=ih.extend({method:G(`resources/subscribe`),params:hg}),_g=ug,vg=ih.extend({method:G(`resources/unsubscribe`),params:_g}),yg=ah.extend({uri:V()}),bg=oh.extend({method:G(`notifications/resources/updated`),params:yg}),xg=W({name:V(),description:Sm(V()),required:Sm(Qp())}),Sg=W({...Sh.shape,...xh.shape,description:Sm(V()),arguments:Sm(U(xg)),_meta:Sm(sm({}))}),Cg=Rh.extend({method:G(`prompts/list`)}),wg=zh.extend({prompts:U(Sg)}),Tg=th.extend({name:V(),arguments:hm(V(),V()).optional()}),Eg=ih.extend({method:G(`prompts/get`),params:Tg}),Dg=W({type:G(`text`),text:V(),annotations:rg.optional(),_meta:hm(V(),nm()).optional()}),Og=W({type:G(`image`),data:eg,mimeType:V(),annotations:rg.optional(),_meta:hm(V(),nm()).optional()}),kg=W({type:G(`audio`),data:eg,mimeType:V(),annotations:rg.optional(),_meta:hm(V(),nm()).optional()}),Ag=W({type:G(`tool_use`),name:V(),id:V(),input:hm(V(),nm()),_meta:hm(V(),nm()).optional()}),jg=W({type:G(`resource`),resource:lm([$h,tg]),annotations:rg.optional(),_meta:hm(V(),nm()).optional()}),Mg=lm([Dg,Og,kg,ig.extend({type:G(`resource_link`)}),jg]),Ng=W({role:ng,content:Mg}),Pg=sh.extend({description:V().optional(),messages:U(Ng)}),Fg=oh.extend({method:G(`notifications/prompts/list_changed`),params:ah.optional()}),Ig=W({title:V().optional(),readOnlyHint:Qp().optional(),destructiveHint:Qp().optional(),idempotentHint:Qp().optional(),openWorldHint:Qp().optional()}),Lg=W({taskSupport:_m([`required`,`optional`,`forbidden`]).optional()}),Rg=W({...Sh.shape,...xh.shape,description:V().optional(),inputSchema:W({type:G(`object`),properties:hm(V(),Ym).optional(),required:U(V()).optional()}).catchall(nm()),outputSchema:W({type:G(`object`),properties:hm(V(),Ym).optional(),required:U(V()).optional()}).catchall(nm()).optional(),annotations:Ig.optional(),execution:Lg.optional(),_meta:hm(V(),nm()).optional()}),zg=Rh.extend({method:G(`tools/list`)}),Bg=zh.extend({tools:U(Rg)}),Vg=sh.extend({content:U(Mg).default([]),structuredContent:hm(V(),nm()).optional(),isError:Qp().optional()});Vg.or(sh.extend({toolResult:nm()}));const Hg=nh.extend({name:V(),arguments:hm(V(),nm()).optional()}),Ug=ih.extend({method:G(`tools/call`),params:Hg}),Wg=oh.extend({method:G(`notifications/tools/list_changed`),params:ah.optional()});W({autoRefresh:Qp().default(!0),debounceMs:H().int().nonnegative().default(300)});const Gg=_m([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Kg=th.extend({level:Gg}),qg=ih.extend({method:G(`logging/setLevel`),params:Kg}),Jg=ah.extend({level:Gg,logger:V().optional(),data:nm()}),Yg=oh.extend({method:G(`notifications/message`),params:Jg}),Xg=W({hints:U(W({name:V().optional()})).optional(),costPriority:H().min(0).max(1).optional(),speedPriority:H().min(0).max(1).optional(),intelligencePriority:H().min(0).max(1).optional()}),Zg=W({mode:_m([`auto`,`required`,`none`]).optional()}),Qg=W({type:G(`tool_result`),toolUseId:V().describe(`The unique identifier for the corresponding tool call.`),content:U(Mg).default([]),structuredContent:W({}).loose().optional(),isError:Qp().optional(),_meta:hm(V(),nm()).optional()}),$g=dm(`type`,[Dg,Og,kg]),e_=dm(`type`,[Dg,Og,kg,Ag,Qg]),t_=W({role:ng,content:lm([e_,U(e_)]),_meta:hm(V(),nm()).optional()}),n_=nh.extend({messages:U(t_),modelPreferences:Xg.optional(),systemPrompt:V().optional(),includeContext:_m([`none`,`thisServer`,`allServers`]).optional(),temperature:H().optional(),maxTokens:H().int(),stopSequences:U(V()).optional(),metadata:Ym.optional(),tools:U(Rg).optional(),toolChoice:Zg.optional()}),r_=ih.extend({method:G(`sampling/createMessage`),params:n_}),i_=sh.extend({model:V(),stopReason:Sm(_m([`endTurn`,`stopSequence`,`maxTokens`]).or(V())),role:ng,content:$g}),a_=sh.extend({model:V(),stopReason:Sm(_m([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(V())),role:ng,content:lm([e_,U(e_)])}),o_=W({type:G(`boolean`),title:V().optional(),description:V().optional(),default:Qp().optional()}),s_=W({type:G(`string`),title:V().optional(),description:V().optional(),minLength:H().optional(),maxLength:H().optional(),format:_m([`email`,`uri`,`date`,`date-time`]).optional(),default:V().optional()}),c_=W({type:_m([`number`,`integer`]),title:V().optional(),description:V().optional(),minimum:H().optional(),maximum:H().optional(),default:H().optional()}),l_=W({type:G(`string`),title:V().optional(),description:V().optional(),enum:U(V()),default:V().optional()}),u_=W({type:G(`string`),title:V().optional(),description:V().optional(),oneOf:U(W({const:V(),title:V()})),default:V().optional()}),d_=lm([lm([W({type:G(`string`),title:V().optional(),description:V().optional(),enum:U(V()),enumNames:U(V()).optional(),default:V().optional()}),lm([l_,u_]),lm([W({type:G(`array`),title:V().optional(),description:V().optional(),minItems:H().optional(),maxItems:H().optional(),items:W({type:G(`string`),enum:U(V())}),default:U(V()).optional()}),W({type:G(`array`),title:V().optional(),description:V().optional(),minItems:H().optional(),maxItems:H().optional(),items:W({anyOf:U(W({const:V(),title:V()}))}),default:U(V()).optional()})])]),o_,s_,c_]),f_=lm([nh.extend({mode:G(`form`).optional(),message:V(),requestedSchema:W({type:G(`object`),properties:hm(V(),d_),required:U(V()).optional()})}),nh.extend({mode:G(`url`),message:V(),elicitationId:V(),url:V().url()})]),p_=ih.extend({method:G(`elicitation/create`),params:f_}),m_=ah.extend({elicitationId:V()}),h_=oh.extend({method:G(`notifications/elicitation/complete`),params:m_}),g_=sh.extend({action:_m([`accept`,`decline`,`cancel`]),content:Wm(e=>e===null?void 0:e,hm(V(),lm([V(),H(),Qp(),U(V())])).optional())}),__=W({type:G(`ref/resource`),uri:V()}),v_=W({type:G(`ref/prompt`),name:V()}),y_=th.extend({ref:lm([v_,__]),argument:W({name:V(),value:V()}),context:W({arguments:hm(V(),V()).optional()}).optional()}),b_=ih.extend({method:G(`completion/complete`),params:y_});function x_(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function S_(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const C_=sh.extend({completion:sm({values:U(V()).max(100),total:Sm(H().int()),hasMore:Sm(Qp())})}),w_=W({uri:V().startsWith(`file://`),name:V().optional(),_meta:hm(V(),nm()).optional()}),T_=ih.extend({method:G(`roots/list`),params:th.optional()}),E_=sh.extend({roots:U(w_)}),D_=oh.extend({method:G(`notifications/roots/list_changed`),params:ah.optional()});lm([Nh,kh,b_,qg,Eg,Cg,og,cg,fg,gg,vg,Ug,zg,Gh,qh,Jh,Xh]),lm([bh,Ih,Mh,D_,Wh]),lm([vh,i_,a_,g_,E_,Kh,Yh,Hh]),lm([Nh,r_,p_,T_,Gh,qh,Jh,Xh]),lm([bh,Ih,Yg,bg,mg,Wg,Fg,Wh,h_]),lm([vh,jh,C_,Pg,wg,sg,lg,pg,Vg,Bg,Kh,Yh,Hh]);var q=class e extends Error{constructor(e,t,n){super(`MCP error ${e}: ${t}`),this.code=e,this.data=n,this.name=`McpError`}static fromError(t,n,r){if(t===K.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new O_(e.elicitations,n)}return new e(t,n,r)}},O_=class extends q{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(K.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function k_(e){return e===`completed`||e===`failed`||e===`cancelled`}const A_=Symbol(`Let zodToJsonSchema decide on which parser to use`),j_={name:void 0,$refStrategy:`root`,basePath:[`#`],effectStrategy:`input`,pipeStrategy:`all`,dateStrategy:`format:date-time`,mapStrategy:`entries`,removeAdditionalStrategy:`passthrough`,allowedAdditionalProperties:!0,rejectedAdditionalProperties:!1,definitionPath:`definitions`,target:`jsonSchema7`,strictUnions:!1,definitions:{},errorMessages:!1,markdownDescription:!1,patternStrategy:`escape`,applyRegexFlags:!1,emailStrategy:`format:email`,base64Strategy:`contentEncoding:base64`,nameStrategy:`ref`,openAiAnyTypeName:`OpenAiAnyType`},M_=e=>typeof e==`string`?{...j_,name:e}:{...j_,...e},N_=e=>{let t=M_(e),n=t.name===void 0?t.basePath:[...t.basePath,t.definitionPath,t.name];return{...t,flags:{hasReferencedOpenAiAnyType:!1},currentPath:n,propertyPath:void 0,seen:new Map(Object.entries(t.definitions).map(([e,n])=>[n._def,{def:n._def,path:[...t.basePath,t.definitionPath,e],jsonSchema:void 0}]))}};function P_(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function J(e,t,n,r,i){e[t]=n,P_(e,t,r,i)}const F_=(e,t)=>{let n=0;for(;n<e.length&&n<t.length&&e[n]===t[n];n++);return[(e.length-n).toString(),...t.slice(n)].join(`/`)};function I_(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?F_(t,e.currentPath):t.join(`/`)}}function L_(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==L.ZodAny&&(n.items=Y(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&J(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&J(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(J(n,`minItems`,e.exactLength.value,e.exactLength.message,t),J(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function R_(e,t){let n={type:`integer`,format:`int64`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`min`:t.target===`jsonSchema7`?r.inclusive?J(n,`minimum`,r.value,r.message,t):J(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),J(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?J(n,`maximum`,r.value,r.message,t):J(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),J(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:J(n,`multipleOf`,r.value,r.message,t)}return n}function z_(){return{type:`boolean`}}function B_(e,t){return Y(e.type._def,t)}const V_=(e,t)=>Y(e.innerType._def,t);function H_(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>H_(e,t,n))};switch(r){case`string`:case`format:date-time`:return{type:`string`,format:`date-time`};case`format:date`:return{type:`string`,format:`date`};case`integer`:return U_(e,t)}}const U_=(e,t)=>{let n={type:`integer`,format:`unix-time`};if(t.target===`openApi3`)return n;for(let r of e.checks)switch(r.kind){case`min`:J(n,`minimum`,r.value,r.message,t);break;case`max`:J(n,`maximum`,r.value,r.message,t)}return n};function W_(e,t){return{...Y(e.innerType._def,t),default:e.defaultValue()}}function G_(e,t){return t.effectStrategy===`input`?Y(e.schema._def,t):I_(t)}function K_(e){return{type:`string`,enum:Array.from(e.values)}}const q_=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function J_(e,t){let n=[Y(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),Y(e.right._def,{...t,currentPath:[...t.currentPath,`allOf`,`1`]})].filter(e=>!!e),r=t.target===`jsonSchema2019-09`?{unevaluatedProperties:!1}:void 0,i=[];return n.forEach(e=>{if(q_(e))i.push(...e.allOf),e.unevaluatedProperties===void 0&&(r=void 0);else{let t=e;if(`additionalProperties`in e&&e.additionalProperties===!1){let{additionalProperties:n,...r}=e;t=r}else r=void 0;i.push(t)}}),i.length?{allOf:i,...r}:void 0}function Y_(e,t){let n=typeof e.value;return n!==`bigint`&&n!==`number`&&n!==`boolean`&&n!==`string`?{type:Array.isArray(e.value)?`array`:`object`}:t.target===`openApi3`?{type:n===`bigint`?`integer`:n,enum:[e.value]}:{type:n===`bigint`?`integer`:n,const:e.value}}let X_;const Z_={cuid:/^[cC][^\s-]{8,}$/,cuid2:/^[0-9a-z]+$/,ulid:/^[0-9A-HJKMNP-TV-Z]{26}$/,email:/^(?!\.)(?!.*\.\.)([a-zA-Z0-9_'+\-\.]*)[a-zA-Z0-9_+-]@([a-zA-Z0-9][a-zA-Z0-9\-]*\.)+[a-zA-Z]{2,}$/,emoji:()=>(X_===void 0&&(X_=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),X_),uuid:/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/,ipv4:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,ipv4Cidr:/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,ipv6:/^(([a-f0-9]{1,4}:){7}|::([a-f0-9]{1,4}:){0,6}|([a-f0-9]{1,4}:){1}:([a-f0-9]{1,4}:){0,5}|([a-f0-9]{1,4}:){2}:([a-f0-9]{1,4}:){0,4}|([a-f0-9]{1,4}:){3}:([a-f0-9]{1,4}:){0,3}|([a-f0-9]{1,4}:){4}:([a-f0-9]{1,4}:){0,2}|([a-f0-9]{1,4}:){5}:([a-f0-9]{1,4}:){0,1})([a-f0-9]{1,4}|(((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2}))\.){3}((25[0-5])|(2[0-4][0-9])|(1[0-9]{2})|([0-9]{1,2})))$/,ipv6Cidr:/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,base64:/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,base64url:/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,nanoid:/^[a-zA-Z0-9_-]{21}$/,jwt:/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/};function Q_(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:J(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:J(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`email`:switch(t.emailStrategy){case`format:email`:nv(n,`email`,r.message,t);break;case`format:idn-email`:nv(n,`idn-email`,r.message,t);break;case`pattern:zod`:rv(n,Z_.email,r.message,t)}break;case`url`:nv(n,`uri`,r.message,t);break;case`uuid`:nv(n,`uuid`,r.message,t);break;case`regex`:rv(n,r.regex,r.message,t);break;case`cuid`:rv(n,Z_.cuid,r.message,t);break;case`cuid2`:rv(n,Z_.cuid2,r.message,t);break;case`startsWith`:rv(n,RegExp(`^${$_(r.value,t)}`),r.message,t);break;case`endsWith`:rv(n,RegExp(`${$_(r.value,t)}$`),r.message,t);break;case`datetime`:nv(n,`date-time`,r.message,t);break;case`date`:nv(n,`date`,r.message,t);break;case`time`:nv(n,`time`,r.message,t);break;case`duration`:nv(n,`duration`,r.message,t);break;case`length`:J(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),J(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:rv(n,RegExp($_(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&nv(n,`ipv4`,r.message,t),r.version!==`v4`&&nv(n,`ipv6`,r.message,t);break;case`base64url`:rv(n,Z_.base64url,r.message,t);break;case`jwt`:rv(n,Z_.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&rv(n,Z_.ipv4Cidr,r.message,t),r.version!==`v4`&&rv(n,Z_.ipv6Cidr,r.message,t);break;case`emoji`:rv(n,Z_.emoji(),r.message,t);break;case`ulid`:rv(n,Z_.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:nv(n,`binary`,r.message,t);break;case`contentEncoding:base64`:J(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:rv(n,Z_.base64,r.message,t)}break;case`nanoid`:rv(n,Z_.nanoid,r.message,t)}return n}function $_(e,t){return t.patternStrategy===`escape`?tv(e):e}const ev=/* @__PURE__ */ new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function tv(e){let t=``;for(let n=0;n<e.length;n++)ev.has(e[n])||(t+=`\\`),t+=e[n];return t}function nv(e,t,n,r){e.format||e.anyOf?.some(e=>e.format)?(e.anyOf||=[],e.format&&(e.anyOf.push({format:e.format,...e.errorMessage&&r.errorMessages&&{errorMessage:{format:e.errorMessage.format}}}),delete e.format,e.errorMessage&&(delete e.errorMessage.format,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.anyOf.push({format:t,...n&&r.errorMessages&&{errorMessage:{format:n}}})):J(e,`format`,t,n,r)}function rv(e,t,n,r){e.pattern||e.allOf?.some(e=>e.pattern)?(e.allOf||=[],e.pattern&&(e.allOf.push({pattern:e.pattern,...e.errorMessage&&r.errorMessages&&{errorMessage:{pattern:e.errorMessage.pattern}}}),delete e.pattern,e.errorMessage&&(delete e.errorMessage.pattern,Object.keys(e.errorMessage).length===0&&delete e.errorMessage)),e.allOf.push({pattern:iv(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):J(e,`pattern`,iv(t,r),n,r)}function iv(e,t){if(!t.applyRegexFlags||!e.flags)return e.source;let n={i:e.flags.includes(`i`),m:e.flags.includes(`m`),s:e.flags.includes(`s`)},r=n.i?e.source.toLowerCase():e.source,i=``,a=!1,o=!1,s=!1;for(let e=0;e<r.length;e++)if(a)i+=r[e],a=!1;else{if(n.i){if(o){if(r[e].match(/[a-z]/)){s?(i+=r[e],i+=`${r[e-2]}-${r[e]}`.toUpperCase(),s=!1):r[e+1]===`-`&&r[e+2]?.match(/[a-z]/)?(i+=r[e],s=!0):i+=`${r[e]}${r[e].toUpperCase()}`;continue}}else if(r[e].match(/[a-z]/)){i+=`[${r[e]}${r[e].toUpperCase()}]`;continue}}if(n.m){if(r[e]===`^`){i+=`(^|(?<=[\r
131
+ ]))`;continue}if(r[e]===`$`){i+=`($|(?=[\r
132
+ ]))`;continue}}n.s&&r[e]===`.`?i+=o?`${r[e]}\r\n`:`[${r[e]}\r\n]`:(i+=r[e],r[e]===`\\`?a=!0:o&&r[e]===`]`?o=!1:!o&&r[e]===`[`&&(o=!0))}try{new RegExp(i)}catch{return console.warn(`Could not convert regex pattern at ${t.currentPath.join(`/`)} to a flag-independent form! Falling back to the flag-ignorant source`),e.source}return i}function av(e,t){if(t.target===`openAi`&&console.warn(`Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead.`),t.target===`openApi3`&&e.keyType?._def.typeName===L.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:Y(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??I_(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:Y(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===L.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=Q_(e.keyType._def,t);return{...n,propertyNames:i}}if(e.keyType?._def.typeName===L.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===L.ZodBranded&&e.keyType._def.type._def.typeName===L.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=B_(e.keyType._def,t);return{...n,propertyNames:i}}return n}function ov(e,t){return t.mapStrategy===`record`?av(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[Y(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||I_(t),Y(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||I_(t)],minItems:2,maxItems:2}}}function sv(e){let t=e.values,n=Object.keys(e.values).filter(e=>typeof t[t[e]]!=`number`).map(e=>t[e]),r=Array.from(new Set(n.map(e=>typeof e)));return{type:r.length===1?r[0]===`string`?`string`:`number`:[`string`,`number`],enum:n}}function cv(e){return e.target===`openAi`?void 0:{not:I_({...e,currentPath:[...e.currentPath,`not`]})}}function lv(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}const uv={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function dv(e,t){if(t.target===`openApi3`)return fv(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in uv&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=uv[t._def.typeName];return n&&!e.includes(n)?[...e,n]:e},[]);return{type:e.length>1?e:e[0]}}if(n.every(e=>e._def.typeName===`ZodLiteral`&&!e.description)){let e=n.reduce((e,t)=>{let n=typeof t._def.value;switch(n){case`string`:case`number`:case`boolean`:return[...e,n];case`bigint`:return[...e,`integer`];case`object`:if(t._def.value===null)return[...e,`null`];default:return e}},[]);if(e.length===n.length){let t=e.filter((e,t,n)=>n.indexOf(e)===t);return{type:t.length>1?t:t[0],enum:n.reduce((e,t)=>e.includes(t._def.value)?e:[...e,t._def.value],[])}}}else if(n.every(e=>e._def.typeName===`ZodEnum`))return{type:`string`,enum:n.reduce((e,t)=>[...e,...t._def.values.filter(t=>!e.includes(t))],[])};return fv(e,t)}const fv=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>Y(e._def,{...t,currentPath:[...t.currentPath,`anyOf`,`${n}`]})).filter(e=>!!e&&(!t.strictUnions||typeof e==`object`&&Object.keys(e).length>0));return n.length?{anyOf:n}:void 0};function pv(e,t){if([`ZodString`,`ZodNumber`,`ZodBigInt`,`ZodBoolean`,`ZodNull`].includes(e.innerType._def.typeName)&&(!e.innerType._def.checks||!e.innerType._def.checks.length))return t.target===`openApi3`?{type:uv[e.innerType._def.typeName],nullable:!0}:{type:[uv[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=Y(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=Y(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function mv(e,t){let n={type:`number`};if(!e.checks)return n;for(let r of e.checks)switch(r.kind){case`int`:n.type=`integer`,P_(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?J(n,`minimum`,r.value,r.message,t):J(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),J(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?J(n,`maximum`,r.value,r.message,t):J(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),J(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:J(n,`multipleOf`,r.value,r.message,t)}return n}function hv(e,t){let n=t.target===`openAi`,r={type:`object`,properties:{}},i=[],a=e.shape();for(let e in a){let o=a[e];if(o===void 0||o._def===void 0)continue;let s=_v(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=Y(o._def,{...t,currentPath:[...t.currentPath,`properties`,e],propertyPath:[...t.currentPath,`properties`,e]});c!==void 0&&(r.properties[e]=c,s||i.push(e))}i.length&&(r.required=i);let o=gv(e,t);return o!==void 0&&(r.additionalProperties=o),r}function gv(e,t){if(e.catchall._def.typeName!==`ZodNever`)return Y(e.catchall._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]});switch(e.unknownKeys){case`passthrough`:return t.allowedAdditionalProperties;case`strict`:return t.rejectedAdditionalProperties;case`strip`:return t.removeAdditionalStrategy===`strict`?t.allowedAdditionalProperties:t.rejectedAdditionalProperties}}function _v(e){try{return e.isOptional()}catch{return!0}}const vv=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return Y(e.innerType._def,t);let n=Y(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:I_(t)},n]}:I_(t)},yv=(e,t)=>{if(t.pipeStrategy===`input`)return Y(e.in._def,t);if(t.pipeStrategy===`output`)return Y(e.out._def,t);let n=Y(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,Y(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function bv(e,t){return Y(e.type._def,t)}function xv(e,t){let n={type:`array`,uniqueItems:!0,items:Y(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&J(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&J(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function Sv(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>Y(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:Y(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>Y(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function Cv(e){return{not:I_(e)}}function wv(e){return I_(e)}const Tv=(e,t)=>Y(e.innerType._def,t),Ev=(e,t,n)=>{switch(t){case L.ZodString:return Q_(e,n);case L.ZodNumber:return mv(e,n);case L.ZodObject:return hv(e,n);case L.ZodBigInt:return R_(e,n);case L.ZodBoolean:return z_();case L.ZodDate:return H_(e,n);case L.ZodUndefined:return Cv(n);case L.ZodNull:return lv(n);case L.ZodArray:return L_(e,n);case L.ZodUnion:case L.ZodDiscriminatedUnion:return dv(e,n);case L.ZodIntersection:return J_(e,n);case L.ZodTuple:return Sv(e,n);case L.ZodRecord:return av(e,n);case L.ZodLiteral:return Y_(e,n);case L.ZodEnum:return K_(e);case L.ZodNativeEnum:return sv(e);case L.ZodNullable:return pv(e,n);case L.ZodOptional:return vv(e,n);case L.ZodMap:return ov(e,n);case L.ZodSet:return xv(e,n);case L.ZodLazy:return()=>e.getter()._def;case L.ZodPromise:return bv(e,n);case L.ZodNaN:case L.ZodNever:return cv(n);case L.ZodEffects:return G_(e,n);case L.ZodAny:return I_(n);case L.ZodUnknown:return wv(n);case L.ZodDefault:return W_(e,n);case L.ZodBranded:return B_(e,n);case L.ZodReadonly:return Tv(e,n);case L.ZodCatch:return V_(e,n);case L.ZodPipeline:return yv(e,n);case L.ZodFunction:case L.ZodVoid:case L.ZodSymbol:return;default:return(e=>void 0)(t)}};function Y(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==A_)return i}if(r&&!n){let e=Dv(r,t);if(e!==void 0)return e}let i={def:e,path:t.currentPath,jsonSchema:void 0};t.seen.set(e,i);let a=Ev(e,e.typeName,t),o=typeof a==`function`?Y(a(),t):a;if(o&&Ov(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}const Dv=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:F_(t.currentPath,e.path)};case`none`:case`seen`:return e.path.length<t.currentPath.length&&e.path.every((e,n)=>t.currentPath[n]===e)?(console.warn(`Recursive reference detected at ${t.currentPath.join(`/`)}! Defaulting to any`),I_(t)):t.$refStrategy===`seen`?I_(t):void 0}},Ov=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),kv=(e,t)=>{let n=N_(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:Y(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??I_(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=Y(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??I_(n),o=typeof t==`object`&&t.name!==void 0&&t.nameStrategy===`title`?t.name:void 0;o!==void 0&&(a.title=o),n.flags.hasReferencedOpenAiAnyType&&(r||={},r[n.openAiAnyTypeName]||(r[n.openAiAnyTypeName]={type:[`string`,`number`,`integer`,`boolean`,`array`,`null`],items:{$ref:n.$refStrategy===`relative`?`1`:[...n.basePath,n.definitionPath,n.openAiAnyTypeName].join(`/`)}}));let s=i===void 0?r?{...a,[n.definitionPath]:r}:a:{$ref:[...n.$refStrategy===`relative`?[]:n.basePath,n.definitionPath,i].join(`/`),[n.definitionPath]:{...r,[i]:a}};return n.target===`jsonSchema7`?s.$schema=`http://json-schema.org/draft-07/schema#`:(n.target===`jsonSchema2019-09`||n.target===`openAi`)&&(s.$schema=`https://json-schema.org/draft/2019-09/schema#`),n.target===`openAi`&&(`anyOf`in s||`oneOf`in s||`allOf`in s||`type`in s&&Array.isArray(s.type))&&console.warn(`Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property.`),s};function Av(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function jv(e,t){return qf(e)?Uf(e,{target:Av(t?.target),io:t?.pipeStrategy??`input`}):kv(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function Mv(e){let t=Zf(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=rp(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function Nv(e,t){let n=Yf(e,t);if(!n.success)throw n.error;return n.data}var Pv=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=/* @__PURE__ */ new Map,this._requestHandlerAbortControllers=/* @__PURE__ */ new Map,this._notificationHandlers=/* @__PURE__ */ new Map,this._responseHandlers=/* @__PURE__ */ new Map,this._progressHandlers=/* @__PURE__ */ new Map,this._timeoutInfo=/* @__PURE__ */ new Map,this._pendingDebouncedNotifications=/* @__PURE__ */ new Set,this._taskProgressTokens=/* @__PURE__ */ new Map,this._requestResolvers=/* @__PURE__ */ new Map,this.setNotificationHandler(bh,e=>{this._oncancel(e)}),this.setNotificationHandler(Ih,e=>{this._onprogress(e)}),this.setRequestHandler(Nh,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Gh,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new q(K.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(qh,async(e,t)=>{let n=async()=>{let r=e.params.taskId;if(!await this._taskStore.getTask(r,t.sessionId))throw new q(K.InvalidParams,`Task not found: ${r}`);if(this._taskMessageQueue){let e;for(;e=await this._taskMessageQueue.dequeue(r,t.sessionId);)if(e.type===`response`||e.type===`error`){let t=e.message,n=t.id,r=this._requestResolvers.get(n);if(r){if(this._requestResolvers.delete(n),e.type===`response`)r(t);else{let e=t;r(new q(e.error.code,e.error.message,e.error.data))}}else{let t=e.type===`response`?`Response`:`Error`;this._onerror(/* @__PURE__ */ Error(`${t} handler missing for request ${n}`))}}else await this._transport?.send(e.message,{relatedRequestId:t.requestId})}let i=await this._taskStore.getTask(r,t.sessionId);if(!i)throw new q(K.InvalidParams,`Task not found: ${r}`);if(!k_(i.status))return await this._waitForTaskUpdate(r,t.signal,t.sessionId),await n();if(k_(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r,t.sessionId),{...e,_meta:{...e._meta,[Jm]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(Jh,async(e,t)=>{try{let{tasks:n,nextCursor:r}=await this._taskStore.listTasks(e.params?.cursor,t.sessionId);return{tasks:n,nextCursor:r,_meta:{}}}catch(e){throw new q(K.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(Xh,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new q(K.InvalidParams,`Task not found: ${e.params.taskId}`);if(k_(n.status))throw new q(K.InvalidParams,`Cannot cancel task in terminal status: ${n.status}`);await this._taskStore.updateTaskStatus(e.params.taskId,`cancelled`,`Client cancelled task execution.`,t.sessionId),this._clearTaskQueue(e.params.taskId,t.sessionId);let r=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!r)throw new q(K.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof q?e:new q(K.InvalidRequest,`Failed to cancel task: ${e instanceof Error?e.message:String(e)}`)}}))}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),q.fromError(K.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){if(this._transport)throw Error(`Already connected to a transport. Call close() before connecting to a new transport, or use a separate Protocol instance per connection.`);this._transport=e;let t=this.transport?.onclose;this._transport.onclose=()=>{t?.(),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),mh(e)||gh(e)?this._onresponse(e):uh(e)?this._onrequest(e,t):fh(e)?this._onnotification(e):this._onerror(/* @__PURE__ */ Error(`Unknown message type: ${JSON.stringify(e)}`))},await this._transport.start()}_onclose(){let e=this._responseHandlers;this._responseHandlers=/* @__PURE__ */ new Map,this._progressHandlers.clear(),this._taskProgressTokens.clear(),this._pendingDebouncedNotifications.clear();for(let e of this._timeoutInfo.values())clearTimeout(e.timeoutId);this._timeoutInfo.clear();for(let e of this._requestHandlerAbortControllers.values())e.abort();this._requestHandlerAbortControllers.clear();let t=q.fromError(K.ConnectionClosed,`Connection closed`);this._transport=void 0,this.onclose?.();for(let n of e.values())n(t)}_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(/* @__PURE__ */ Error(`Uncaught error in notification handler: ${e}`)))}_onrequest(e,t){let n=this._requestHandlers.get(e.method)??this.fallbackRequestHandler,r=this._transport,i=e.params?._meta?.[Jm]?.taskId,a=r?.sessionId,o=this._taskStore,s=!0,c;if(i&&o&&this._taskMessageQueue&&a!==void 0&&(s=!1,c=(async()=>{if(!await o.getTask(i,a))throw new q(K.InvalidParams,`Task not found: ${i}`);s=!0})()),n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:K.MethodNotFound,message:`Method not found`}};if(i&&c){let e={type:`error`,message:t,timestamp:Date.now()};c.then(()=>this._enqueueTaskMessage(i,e,a),()=>r?.send(t)).catch(e=>this._onerror(/* @__PURE__ */ Error(`Failed to send an error response: ${e}`)))}else i&&this._taskMessageQueue?this._enqueueTaskMessage(i,{type:`error`,message:t,timestamp:Date.now()},r?.sessionId).catch(e=>this._onerror(/* @__PURE__ */ Error(`Failed to enqueue error response: ${e}`))):r?.send(t).catch(e=>this._onerror(/* @__PURE__ */ Error(`Failed to send an error response: ${e}`)));return}let l=new AbortController;this._requestHandlerAbortControllers.set(e.id,l);let u=rh(e.params)?e.params.task:void 0,d=this._taskStore?this.requestTaskStore(e,r?.sessionId):void 0,f={signal:l.signal,sessionId:r?.sessionId,_meta:e.params?._meta,sendNotification:async t=>{if(l.signal.aborted)return;let n={relatedRequestId:e.id};i&&(n.relatedTask={taskId:i}),await this.notification(t,n)},sendRequest:async(t,n,r)=>{if(l.signal.aborted)throw new q(K.ConnectionClosed,`Request was cancelled`);let a={...r,relatedRequestId:e.id};i&&!a.relatedTask&&(a.relatedTask={taskId:i});let o=a.relatedTask?.taskId??i;return o&&d&&await d.updateTaskStatus(o,`input_required`),await this.request(t,n,a)},authInfo:t?.authInfo,requestId:e.id,requestInfo:t?.requestInfo,taskId:i,taskStore:d,taskRequestedTtl:u?.ttl,closeSSEStream:t?.closeSSEStream,closeStandaloneSSEStream:t?.closeStandaloneSSEStream};(c??Promise.resolve()).then(()=>{if(c&&l.signal.aborted)throw new q(K.ConnectionClosed,`Request was cancelled`);u&&this.assertTaskHandlerCapability(e.method)}).then(()=>n(e,f)).then(async t=>{if(l.signal.aborted)return;let n={result:t,jsonrpc:`2.0`,id:e.id};i&&this._taskMessageQueue?await this._enqueueTaskMessage(i,{type:`response`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)},async t=>{if(l.signal.aborted)return;let n={jsonrpc:`2.0`,id:e.id,error:{code:Number.isSafeInteger(t.code)?t.code:K.InternalError,message:t.message??`Internal error`,...t.data!==void 0&&{data:t.data}}};i&&this._taskMessageQueue&&s?await this._enqueueTaskMessage(i,{type:`error`,message:n,timestamp:Date.now()},r?.sessionId):await r?.send(n)}).catch(e=>this._onerror(/* @__PURE__ */ Error(`Failed to send response: ${e}`))).finally(()=>{this._requestHandlerAbortControllers.get(e.id)===l&&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(/* @__PURE__ */ 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._requestResolvers.get(t);if(n){this._requestResolvers.delete(t),mh(e)?n(e):n(new q(e.error.code,e.error.message,e.error.data));return}let r=this._responseHandlers.get(t);if(r===void 0){this._onerror(/* @__PURE__ */ Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}this._responseHandlers.delete(t),this._cleanupTimeout(t);let i=!1;if(mh(e)&&e.result&&typeof e.result==`object`){let n=e.result;if(n.task&&typeof n.task==`object`){let e=n.task;typeof e.taskId==`string`&&(i=!0,this._taskProgressTokens.set(e.taskId,t))}}i||this._progressHandlers.delete(t),mh(e)?r(e):r(q.fromError(e.error.code,e.error.message,e.error.data))}get transport(){return this._transport}async close(){await this._transport?.close()}async*requestStream(e,t,n){let{task:r}=n??{};if(!r){try{yield{type:`result`,result:await this.request(e,t,n)}}catch(e){yield{type:`error`,error:e instanceof q?e:new q(K.InternalError,String(e))}}return}let i;try{let r=await this.request(e,Hh,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new q(K.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},k_(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new q(K.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new q(K.InternalError,`Task ${i} was cancelled`)});return}if(e.status===`input_required`){yield{type:`result`,result:await this.getTaskResult({taskId:i},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 q?e:new q(K.InternalError,String(e))}}}request(e,t,n){let{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a,task:o,relatedTask:s}=n??{};return new Promise((c,l)=>{let u=e=>{l(e)};if(!this._transport){u(/* @__PURE__ */ Error(`Not connected`));return}if(this._options?.enforceStrictCapabilities===!0)try{this.assertCapabilityForMethod(e.method),o&&this.assertTaskCapability(e.method)}catch(e){u(e);return}n?.signal?.throwIfAborted();let d=this._requestMessageId++,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}}),o&&(f.params={...f.params,task:o}),s&&(f.params={...f.params,_meta:{...f.params?._meta||{},[Jm]:s}});let p=e=>{this._responseHandlers.delete(d),this._progressHandlers.delete(d),this._cleanupTimeout(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(/* @__PURE__ */ Error(`Failed to send cancellation: ${e}`))),l(e instanceof q?e:new q(K.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=Yf(t,e.result);n.success?c(n.data):l(n.error)}catch(e){l(e)}}}),n?.signal?.addEventListener(`abort`,()=>{p(n?.signal?.reason)});let m=n?.timeout??6e4;this._setupTimeout(d,m,n?.maxTotalTimeout,()=>p(q.fromError(K.RequestTimeout,`Request timed out`,{timeout:m})),n?.resetTimeoutOnProgress??!1);let h=s?.taskId;h?(this._requestResolvers.set(d,e=>{let t=this._responseHandlers.get(d);t?t(e):this._onerror(/* @__PURE__ */ Error(`Response handler missing for side-channeled request ${d}`))}),this._enqueueTaskMessage(h,{type:`request`,message:f,timestamp:Date.now()}).catch(e=>{this._cleanupTimeout(d),l(e)})):this._transport.send(f,{relatedRequestId:r,resumptionToken:i,onresumptiontoken:a}).catch(e=>{this._cleanupTimeout(d),l(e)})})}async getTask(e,t){return this.request({method:`tasks/get`,params:e},Kh,t)}async getTaskResult(e,t,n){return this.request({method:`tasks/result`,params:e},t,n)}async listTasks(e,t){return this.request({method:`tasks/list`,params:e},Yh,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},Zh,t)}async notification(e,t){if(!this._transport)throw Error(`Not connected`);this.assertNotificationCapability(e.method);let n=t?.relatedTask?.taskId;if(n){let r={...e,jsonrpc:`2.0`,params:{...e.params,_meta:{...e.params?._meta||{},[Jm]:t.relatedTask}}};await this._enqueueTaskMessage(n,{type:`notification`,message:r,timestamp:Date.now()});return}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(()=>{if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let n={...e,jsonrpc:`2.0`};t?.relatedTask&&(n={...n,params:{...n.params,_meta:{...n.params?._meta||{},[Jm]:t.relatedTask}}}),this._transport?.send(n,t).catch(e=>this._onerror(e))});return}let r={...e,jsonrpc:`2.0`};t?.relatedTask&&(r={...r,params:{...r.params,_meta:{...r.params?._meta||{},[Jm]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=Mv(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=Nv(e,n);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=Mv(e);this._notificationHandlers.set(n,n=>{let r=Nv(e,n);return Promise.resolve(t(r))})}removeNotificationHandler(e){this._notificationHandlers.delete(e)}_cleanupTaskProgressHandler(e){let t=this._taskProgressTokens.get(e);t!==void 0&&(this._progressHandlers.delete(t),this._taskProgressTokens.delete(e))}async _enqueueTaskMessage(e,t,n){if(!this._taskStore||!this._taskMessageQueue)throw Error(`Cannot enqueue task message: taskStore and taskMessageQueue are not configured`);let r=this._options?.maxTaskQueueSize;await this._taskMessageQueue.enqueue(e,t,n??this._transport?.sessionId,r)}async _clearTaskQueue(e,t){if(this._taskMessageQueue){let n=await this._taskMessageQueue.dequeueAll(e,t);for(let t of n)if(t.type===`request`&&uh(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new q(K.InternalError,`Task cancelled or completed`)),this._requestResolvers.delete(n)):this._onerror(/* @__PURE__ */ Error(`Resolver missing for request ${n} during task ${e} cleanup`))}}}async _waitForTaskUpdate(e,t,n){let r=this._options?.defaultTaskPollInterval??1e3;try{let t=await this._taskStore?.getTask(e,n);t?.pollInterval&&(r=t.pollInterval)}catch{}return new Promise((e,n)=>{if(t.aborted){n(new q(K.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,r);t.addEventListener(`abort`,()=>{clearTimeout(i),n(new q(K.InvalidRequest,`Request cancelled`))},{once:!0})})}requestTaskStore(e,t){let n=this._taskStore;if(!n)throw Error(`No task store configured`);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 q(K.InvalidParams,`Failed to retrieve task: Task not found`);return r},storeTaskResult:async(e,r,i)=>{await n.storeTaskResult(e,r,i,t);let a=await n.getTask(e,t);if(a){let t=Wh.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),k_(a.status)&&this._cleanupTaskProgressHandler(e)}},getTaskResult:e=>n.getTaskResult(e,t),updateTaskStatus:async(e,r,i)=>{let a=await n.getTask(e,t);if(!a)throw new q(K.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(k_(a.status))throw new q(K.InvalidParams,`Cannot update task "${e}" from terminal status "${a.status}" to "${r}". Terminal states (completed, failed, cancelled) cannot transition to other states.`);await n.updateTaskStatus(e,r,i,t);let o=await n.getTask(e,t);if(o){let t=Wh.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),k_(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function Fv(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Iv(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]=Fv(a)&&Fv(i)?{...a,...i}:i}return n}var Lv=/* @__PURE__ */ D((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})),Rv=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=Lv();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]=/* @__PURE__ */ 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]||/* @__PURE__ */ 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}}})),X=/* @__PURE__ */ D((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=Lv(),n=Rv();var r=Lv();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=Rv();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&&=ne(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=ne(this.rhs,e,n),this}get names(){return te(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=ne(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)||(re(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>ee(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(ie(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=ne(this.condition,e,t),this}get names(){let e=super.names;return te(e,this.condition),this.else&&ee(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=ne(this.iteration,e,t),this}get names(){return ee(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 te(te(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=ne(this.iterable,e,t),this}get names(){return ee(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&&ee(e,this.catch.names),this.finally&&ee(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 E=class extends m{render(e){return`finally`+super.render(e)}};E.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
133
+ `:``},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]=/* @__PURE__ */ 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 E,this.code(n)),this._endBlockNode(T,E)}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 ee(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function te(e,n){return n instanceof t._CodeOrName?ee(e,n.names):e}function ne(e,n,r){return e instanceof t.Name?i(e):a(e)?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),[])):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 re(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function ie(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${le(e)}`}e.not=ie;let ae=ce(e.operators.AND);function oe(...e){return e.reduce(ae)}e.and=oe;let D=ce(e.operators.OR);function se(...e){return e.reduce(D)}e.or=se;function ce(e){return(n,r)=>n===t.nil?r:r===t.nil?n:(0,t._)`${le(n)} ${e} ${le(r)}`}function le(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),Z=/* @__PURE__ */ D((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=X(),n=Lv();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})),zv=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=X();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`)}})),Bv=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;let t=X(),n=Z(),r=zv();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}){
134
+ /* istanbul ignore if */
135
+ 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])}})),Vv=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=Bv(),n=X(),r=zv(),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)}})),Hv=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getRules=e.isJSONType=void 0;let t=/* @__PURE__ */ 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})),Uv=/* @__PURE__ */ D((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})),Wv=/* @__PURE__ */ D((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=Hv(),n=Uv(),r=Bv(),i=X(),a=Z();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=/* @__PURE__ */ 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
136
+ || (${s} == "string" && ${a} && ${a} == +${a})`).assign(c,(0,i._)`+${a}`);return;case`integer`:r.elseIf((0,i._)`${s} === "boolean" || ${a} === null
137
+ || (${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"
138
+ || ${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}}})),Gv=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.assignDefaults=void 0;let t=X(),n=Z();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)}`)}})),Kv=/* @__PURE__ */ D((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=X(),n=Z(),r=zv(),i=Z();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;
139
+ /* istanbul ignore if */
140
+ 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})),qv=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;let t=X(),n=zv(),r=Kv(),i=Bv();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){
141
+ /* istanbul ignore if */
142
+ 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})),Jv=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;let t=X(),n=Z();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=/* @__PURE__ */ 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})),Yv=/* @__PURE__ */ D(((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}})),Xv=/* @__PURE__ */ D(((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`)}})),Zv=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;let t=Z(),n=Yv(),r=Xv(),i=/* @__PURE__ */ 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=/* @__PURE__ */ 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=/* @__PURE__ */ 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/* @__PURE__ */ Error(`reference "${e}" resolves to more than one schema`)}}e.getSchemaRefs=h})),Qv=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=Vv(),n=Wv(),r=Uv(),i=Wv(),a=Gv(),o=qv(),s=Jv(),c=X(),l=zv(),u=Zv(),d=Z(),f=Bv();function p(e){S(e)&&(w(e),x(e))?_(e):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&&re(e),ee(e),r.let(l.default.vErrors,null),r.let(l.default.errors,0),n.unevaluated&&v(e),T(e),ie(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){S(e)&&(w(e),x(e))?C(e,n):(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&&re(e),te(e),ne(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),E(e)}function T(e,t){if(e.opts.jtd)return oe(e,[],!1,t);let r=(0,n.getSchemaTypes)(e.schema);oe(e,r,!(0,n.coerceAndCheckDataType)(e,r),t)}function E(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 ee(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 te(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function ne(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error(`async schema in sync schema`)}function re({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 ie(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&&ae(e),t.return((0,c._)`${l.default.errors} === 0`))}function ae({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 oe(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(()=>ge(e,`$ref`,h.all.$ref.definition));return}p.jtd||se(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)),D(e,d),t.length===1&&t[0]===d.type&&n&&(o.else(),(0,i.reportTypeError)(e)),o.endIf()):D(e,d),f||o.if((0,c._)`${l.default.errors} === ${a||0}`))}}function D(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)&&ge(e,n.keyword,n.definition,t.type)})}function se(e,t){!e.schemaEnv.meta&&e.opts.strictTypes&&(ce(e,t),e.opts.allowUnionTypes||le(e,t),ue(e,e.dataTypes))}function ce(e,t){t.length&&(e.dataTypes.length?(t.forEach(t=>{fe(e.dataTypes,t)||me(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),pe(e,t)):e.dataTypes=t)}function le(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&me(e,`use allowUnionTypes to allow union type keyword`)}function ue(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=>de(t,e))&&me(e,`missing type "${n.join(`,`)}" for keyword "${i}"`)}}}function de(e,t){return e.includes(t)||t===`number`&&e.includes(`integer`)}function fe(e,t){return e.includes(t)||t===`integer`&&e.includes(`number`)}function pe(e,t){let n=[];for(let r of e.dataTypes)fe(t,r)?n.push(r):t.includes(`integer`)&&r===`number`&&n.push(`integer`);e.dataTypes=n}function me(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}var he=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`,ye(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){e===void 0?(this.error(),this.allErrors||this.gen.if(!1)):(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){t?(this.setParams(t),this._error(e,n),this.setParams({})):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){
143
+ /* istanbul ignore if */
144
+ 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=he;function ge(e,t,n,r){let i=new he(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 _e=/^\/(?:[^~]|~0|~1)*$/,ve=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function ye(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let i,a;if(e===``)return l.default.rootData;if(e[0]===`/`){if(!_e.test(e))throw Error(`Invalid JSON-pointer: ${e}`);i=e,a=l.default.rootData}else{let o=ve.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=ye})),$v=/* @__PURE__ */ D((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}}})),ey=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Zv();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))}}})),ty=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=X(),n=$v(),r=zv(),i=Zv(),a=Z(),o=Qv();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:/* @__PURE__ */ 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=/* @__PURE__ */ 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}})),ny=/* @__PURE__ */ D(((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}})),ry=/* @__PURE__ */ D(((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),i=RegExp.prototype.test.bind(/^\d*$/u),a=RegExp.prototype.test.bind(/^[\da-f]{2}$/iu),o=RegExp.prototype.test.bind(/^[\da-z\-._~]$/iu),s=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/]$/u),c=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:@/?]$/u),l=RegExp.prototype.test.bind(/^[A-Za-z0-9\-._~!$&'()*+,;=:]$/u),u=Array(256);{let e=`0123456789ABCDEF`;for(let t=0;t<256;t++)u[t]=`%`+e[t>>4]+e[t&15]}function d(e){return e<2048?u[192|e>>6]+u[128|e&63]:e<65536?u[224|e>>12]+u[128|e>>6&63]+u[128|e&63]:u[240|e>>18]+u[128|e>>12&63]+u[128|e>>6&63]+u[128|e&63]}function f(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 p=RegExp.prototype.test.bind(/^[\dA-Fa-f]{1,4}$/),m=RegExp.prototype.test.bind(/^[vV][\dA-Fa-f]+\.[A-Za-z\d\-._~!$&'()*+,;=:]+$/),h=RegExp.prototype.test.bind(/^[A-Za-z\d\-._~]$/),g=RegExp.prototype.test.bind(/[^!"$&'()*+,\-.;=_`a-z{}~]/u);function _(e){if(e.length===0)return!1;for(let t=0;t<e.length;t++)if(!h(e[t])){if(e[t]===`%`&&t+2<e.length&&a(e.slice(t+1,t+3)))t+=2;else return!1}return!0}function v(e){let t=-1,n=0,r=-1,i=0;for(let a=0;a<e.length;a++)e[a]===`0`?(r===-1&&(r=a),i++,i>n&&(n=i,t=r)):(r=-1,i=0);if(n<2)return e.join(`:`);let a=e.slice(0,t).join(`:`),o=e.slice(t+n).join(`:`);return a+`::`+o}function y(e){let t=e.indexOf(`::`);if(t!==-1&&e.indexOf(`::`,t+1)!==-1)return;let n=t===-1?e.split(`:`):e.slice(0,t).split(`:`),i=t===-1?[]:e.slice(t+2).split(`:`);t!==-1&&(n.length===1&&n[0]===``&&(n.length=0),i.length===1&&i[0]===``&&(i.length=0));let a=n.concat(i),o=0;for(let e=0;e<a.length;e++){let n=a[e];if(n===``)return;if(n.indexOf(`.`)!==-1){if(e!==a.length-1||t!==-1&&i.length===0||!r(n))return;o+=2}else{if(!p(n))return;a[e]=parseInt(n,16).toString(16),o++}}if(t===-1)return o===8?v(a):void 0;if(o>=8)return;let s=a.slice(0,n.length);for(let e=o;e<8;e++)s.push(`0`);for(let e=n.length;e<a.length;e++)s.push(a[e]);return v(s)}function b(e){let t=e[0]===`[`&&e[e.length-1]===`]`;if((e[0]===`[`||e[e.length-1]===`]`)&&!t)return{host:e,isIPV6:!1,error:!0};let n=t?e.slice(1,-1):e;if(t&&m(n))return n=n.toLowerCase(),{host:`[${n}]`,escapedHost:n,isIPV6:!1,isIPVFuture:!0};if(x(n,`:`)<2)return{host:e,isIPV6:!1,error:t};let r=``,i=n.indexOf(`%`);if(i!==-1){let t=n.slice(i,i+3).toLowerCase()===`%25`?3:1;if(r=n.slice(i+t),!_(r))return{host:e,isIPV6:!1,error:!0};n=n.slice(0,i)}let a=y(n);return a===void 0?{host:e,isIPV6:!1,error:!0}:{host:a+(r?`%`+r:``),escapedHost:a+(r?`%25`+r:``),isIPV6:!0}}function x(e,t){let n=0;for(let r=0;r<e.length;r++)e[r]===t&&n++;return n}function S(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 C(e){if(e===``||e[0]===`/`)return S(e);let t=e.split(`/`),n=t.length-1,r=[],i=!1;for(let e=0;e<=n;e++){let a=t[e];a===`.`||a===`..`?(a===`..`&&(r.length!==0&&r[r.length-1]!==`..`?r.pop():r.push(`..`)),i=e===n):r.push(a)}return i&&r[r.length-1]!==`..`&&r.push(``),(r.length===0||r[0]===``||r[0].includes(`:`))&&r.unshift(`.`),r.join(`/`)}let w={"@":`%40`,"/":`%2F`,"?":`%3F`,"#":`%23`,":":`%3A`},T=/[@/?#:]/g,E=/[@/?#]/g;function ee(e,t){let n=t?E:T;return n.lastIndex=0,e.replace(n,e=>w[e])}function te(e,t=!1){if(e.indexOf(`%`)===-1)return e;let n=``;for(let r=0;r<e.length;r++){if(e[r]===`%`&&r+2<e.length){let i=e.slice(r+1,r+3);if(a(i)){let e=i.toUpperCase(),a=String.fromCharCode(parseInt(e,16));t&&o(a)?n+=a:n+=`%`+e,r+=2;continue}}n+=e[r]}return n}function ne(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(r===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(a(r)){let e=r.toUpperCase(),i=String.fromCharCode(parseInt(e,16));i!==`.`&&o(i)?t+=i:t+=`%`+e,n+=2;continue}}if(s(r))t+=r;else{let i=e.charCodeAt(n);if(i<128)t+=se(i)?r:u[i];else if(i<55296||i>57343)t+=d(i);else if(i<=56319&&n+1<e.length){let r=e.charCodeAt(n+1);r>=56320&&r<=57343?(t+=d(65536+(i-55296<<10)+(r-56320)),n++):t+=d(65533)}else t+=d(65533)}}return t}function re(e,t=!1){let n=``,r=t&&e[0]!==`/`;for(let t=0;t<e.length;t++){let i=e[t];if(i===`%`&&t+2<e.length){let r=e.slice(t+1,t+3);if(a(r)){n+=`%`+r.toUpperCase(),t+=2;continue}}if(i===`/`&&(r=!1),s(i)&&(i!==`:`||!r))n+=i;else{let r=e.charCodeAt(t);if(r<128)n+=u[r];else if(r<55296||r>57343)n+=d(r);else if(r<=56319&&t+1<e.length){let i=e.charCodeAt(t+1);i>=56320&&i<=57343?(n+=d(65536+(r-55296<<10)+(i-56320)),t++):n+=d(65533)}else n+=d(65533)}}return n}function ie(e,t){let n=``;for(let r=0;r<e.length;r++){let i=e[r];if(i===`%`&&r+2<e.length){let t=e.slice(r+1,r+3);if(a(t)){n+=`%`+t.toUpperCase(),r+=2;continue}}if(t(i))n+=i;else{let t=e.charCodeAt(r);if(t<128)n+=u[t];else if(t<55296||t>57343)n+=d(t);else if(t<=56319&&r+1<e.length){let i=e.charCodeAt(r+1);i>=56320&&i<=57343?(n+=d(65536+(t-55296<<10)+(i-56320)),r++):n+=d(65533)}else n+=d(65533)}}return n}function ae(e){return ie(e,l)}function oe(e){return ie(e,c)}function D(e){return ie(e,c)}function se(e){return e>=48&&e<=57||e>=65&&e<=90||e>=97&&e<=122||e===42||e===43||e===45||e===46||e===47||e===64||e===95}function ce(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];if(r===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(a(r)){let e=r.toUpperCase(),i=String.fromCharCode(parseInt(e,16));o(i)?t+=i:t+=`%`+e,n+=2;continue}}if(c(r))t+=r;else{let i=e.charCodeAt(n);if(i<128)t+=se(i)?r:u[i];else if(i<55296||i>57343)t+=d(i);else if(i<=56319&&n+1<e.length){let r=e.charCodeAt(n+1);r>=56320&&r<=57343?(t+=d(65536+(i-55296<<10)+(r-56320)),n++):t+=d(65533)}else t+=d(65533)}}return t}function le(e){let t=``;for(let n=0;n<e.length;n++){if(e[n]===`%`&&n+2<e.length){let r=e.slice(n+1,n+3);if(a(r)){t+=`%`+r.toUpperCase(),n+=2;continue}}t+=escape(e[n])}return t}function ue(e){let t=[];if(e.userinfo!==void 0&&(t.push(ae(e.userinfo)),t.push(`@`)),e.host!==void 0){let n=e.host;if(!r(n)){let e=b(n);e.isIPV6!==!0&&e.isIPVFuture!==!0&&(n=te(n,!0),e=b(n)),n=e.isIPV6===!0||e.isIPVFuture===!0?`[${e.escapedHost}]`:ee(n,!1)}t.push(n)}if(typeof e.port==`number`||typeof e.port==`string`){let n=String(e.port);if(!i(n))throw TypeError(`URI port is malformed.`);t.push(`:`),t.push(n)}return t.length?t.join(``):void 0}t.exports={nonSimpleDomain:g,recomposeAuthority:ue,reescapeHostDelimiters:ee,normalizePercentEncoding:te,normalizePathEncoding:ne,serializePathEncoding:re,normalizeQueryFragmentEncoding:ce,encodeUserinfo:ae,encodeQuery:oe,encodeFragment:D,escapePreservingEscapes:le,removeDotSegments:S,removeDotSegmentsRelative:C,isIPv4:r,isUUID:n,normalizeIPv6:b,stringArrayToHexStripped:f}})),iy=/* @__PURE__ */ D(((e,t)=>{let{isUUID:n}=ry(),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=e.resourceName.indexOf(`?`),n=t===-1?e.resourceName:e.resourceName.slice(0,t);e.path=n&&n!==`/`?n:void 0,e.query=t===-1?void 0:e.resourceName.slice(t+1),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&&n[0]===e.path){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}})),ay=/* @__PURE__ */ D(((e,t)=>{let{normalizeIPv6:n,removeDotSegments:r,removeDotSegmentsRelative:i,recomposeAuthority:a,normalizePercentEncoding:o,normalizePathEncoding:s,serializePathEncoding:c,normalizeQueryFragmentEncoding:l,encodeQuery:u,encodeFragment:d,reescapeHostDelimiters:f,isIPv4:p,nonSimpleDomain:m}=ry(),{SCHEMES:h,getSchemeHandler:g}=iy(),_=/^[A-Za-z][A-Za-z0-9+.-]*$/u,v=`URI scheme is malformed.`,y=`URI host is malformed.`,b=/[\0-\x20"#/:<>?@[\\\]^`{|}\x7F]/u;function x(e){let t=String(e);if(!_.test(t))throw TypeError(v);return t}function S(e,t){return typeof e==`string`?e=de(e,t):typeof e==`object`&&(e=ue(E(e,t),t)),e}function C(e,t,r){let i=r?Object.assign({scheme:`null`},r):{scheme:`null`},{parsed:a,malformedAuthorityOrPort:o,malformedPercentEncoding:s,malformedSchemeSpecific:c,malformedHost:l,malformedScheme:u}=le(e,i),{parsed:d,malformedAuthorityOrPort:f,malformedPercentEncoding:m,malformedSchemeSpecific:h,malformedHost:_,malformedScheme:v}=le(t,i);if(o||f||s||m||c||h||l||_||u||v)throw Error(a.error||d.error||`URI is malformed.`);let b=w(a,d,i,!0),x=g(r&&r.scheme||b.scheme),S=b.host,C=S!==void 0&&S!==``&&(p(S)||n(S).isIPV6);if(se(b,r||{},x,C))throw Error(y);D(b,r||{},x,C);let T=S&&S.indexOf(`%`)!==-1&&!/\P{ASCII}/u.test(S);if(b.error&&!T)throw Error(b.error);return i.skipEscape=!0,E(b,i)}function w(e,t,n,a){let o={};if(a||(e=ue(E(e,n),n),t=ue(E(t,n),n)),n||={},!n.tolerant&&t.scheme)o.scheme=t.scheme,o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=r(t.path||``),o.query=t.query;else{if(t.userinfo!==void 0||t.host!==void 0||t.port!==void 0)o.userinfo=t.userinfo,o.host=t.host,o.port=t.port,o.path=r(t.path||``),o.query=t.query;else{if(!t.path)o.path=e.path,o.query=t.query===void 0?e.query:t.query;else{if(t.path[0]===`/`)o.path=r(t.path);else{let n=e.userinfo!==void 0||e.host!==void 0||e.port!==void 0;o.path=n&&!e.path?`/`+t.path:e.path?e.path.slice(0,e.path.lastIndexOf(`/`)+1)+t.path:t.path,o.path=e.scheme===void 0&&!n&&o.path[0]!==`/`?i(o.path):r(o.path)}o.query=t.query}o.userinfo=e.userinfo,o.host=e.host,o.port=e.port}o.scheme=e.scheme}return o.fragment=t.fragment,o}function T(e,t,n){let r=pe(e,n),i=pe(t,n);return r!==void 0&&i!==void 0&&r===i}function E(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:``},s=Object.assign({},t),l=[];n.scheme&&=x(n.scheme);let f=g(s.scheme||n.scheme);f&&f.serialize&&f.serialize(n,s);let p=n.userinfo!==void 0||n.host!==void 0||n.port!==void 0,m=(n.scheme===void 0||s.reference===`suffix`)&&!p,h=!s.skipEscape&&m;n.path!==void 0&&(n.path=s.skipEscape?o(n.path):c(n.path,h)),s.reference!==`suffix`&&n.scheme&&(n.scheme=x(n.scheme),l.push(n.scheme,`:`));let _=a(n);if(_!==void 0&&(s.reference!==`suffix`&&l.push(`//`),l.push(_),n.path&&n.path[0]!==`/`&&l.push(`/`)),n.path!==void 0){let e=n.path;s.absolutePath||f&&f.absolutePath||(e=m&&e[0]!==`/`?i(e):r(e)),m&&(e=c(e,!0)),_===void 0&&e[0]===`/`&&e[1]===`/`&&(e=`/%2F`+e.slice(2)),l.push(e)}return n.query!==void 0&&l.push(`?`,u(n.query)),n.fragment!==void 0&&l.push(`#`,d(n.fragment)),l.join(``)}let ee=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,te=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,ne=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function re(e,t){if(t[2]!==void 0&&e.path&&e.path[0]!==`/`)return`URI path must start with "/" when authority is present.`;if(typeof e.port==`number`&&(e.port<0||e.port>65535))return`URI port is malformed.`}function ie(e){if(e===void 0)return!1;let t=e.indexOf(`%`);for(;t!==-1;){if(t+2>=e.length||!/^[\da-f]{2}$/iu.test(e.slice(t+1,t+3)))return!0;t=e.indexOf(`%`,t+3)}return!1}function ae(e){return e[0]===`[`&&e[e.length-1]===`]`}function oe(e){let t=e[4];return ie(e[3])||t!==void 0&&!ae(t)&&ie(t)||ie(e[6])||ie(e[7])||ie(e[8])}function D(e,t,n,r){if(se(e,t,n,r))return e.error=e.error||y,!0;if(!t.unicodeSupport&&(!n||!n.unicodeSupport)&&e.host&&!ae(e.host)&&(t.domainHost||n&&n.domainHost)&&r===!1&&m(e.host)){let t;try{t=new URL(`http://`+e.host)}catch(t){return e.error=e.error||`Host's domain name can not be converted to ASCII: `+t,!0}if(!ce(t))return e.error=e.error||y,!0;e.host=t.hostname}return!1}function se(e,t,n,r){return!!(e.host&&r===!1&&!ae(e.host)&&(t.domainHost||n&&n.domainHost)&&b.test(e.host))}function ce(e){return e.username===``&&e.password===``&&e.port===``&&e.pathname===`/`&&e.search===``&&e.hash===``&&e.hostname!==``}function le(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,c=!1,u=!1,d=!1,m=!1,b=!1,x=!1;r.reference===`suffix`&&(e=r.scheme?r.scheme+`:`+e:`//`+e);let S=e.match(te);S!==null&&S[1].indexOf(`\\`)!==-1&&(i.error=`URI authority must not contain a literal backslash.`,a=!0);let C=e.match(ne);if(C!==null){let e=C[1],t=e.replace(/[\t\n\r]/g,``);t.length>=2&&(t.slice(0,2)===`//`?e.length!==t.length&&(i.error=i.error||`URI authority introducer must not contain whitespace.`,a=!0):(i.error=i.error||`URI authority must not contain a literal backslash.`,a=!0))}let w=e.match(ee);if(w){i.scheme=w[1],i.userinfo=w[3],i.host=w[4],i.port=parseInt(w[5],10),i.path=w[6]||``,i.query=w[7],i.fragment=w[8],i.scheme!==void 0&&(_.test(i.scheme)?i.scheme=i.scheme.toLowerCase():(i.error=i.error||v,b=!0)),c=oe(w),c&&(i.error=i.error||`URI contains malformed percent-encoding.`),isNaN(i.port)&&(i.port=w[5]);let t=re(i,w);if(t!==void 0&&(i.error=i.error||t,a=!0),i.host){if(p(i.host)===!1){let e=ae(i.host),t=i.host.indexOf(`[`)!==-1||i.host.indexOf(`]`)!==-1,r=n(i.host);x=r.isIPV6||r.isIPVFuture===!0,m=t&&(!e||r.error===!0),i.host=x?r.host:r.host.toLowerCase(),m&&(i.error=i.error||y,a=!0)}else x=!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 S=g(r.scheme||i.scheme);if(m||(d=D(i,r,S,x)),e.indexOf(`%`)!==-1&&i.host!==void 0&&!m){let e=x?i.host:o(i.host,!0);x||(e=o(e.toLowerCase())),i.host=x||r.scheme!==`null`?f(e,x):e}(!S||S&&!S.skipNormalize)&&(i.path&&=s(i.path),i.query&&=l(i.query),i.fragment&&=l(i.fragment)),S&&S.parse&&(S.parse(i,r),S===h.urn&&i.nid===void 0&&(u=!0))}else i.error=i.error||`URI can not be parsed.`;return{parsed:i,malformedAuthorityOrPort:a,malformedPercentEncoding:c,malformedSchemeSpecific:u,malformedHost:d,malformedScheme:b}}function ue(e,t){return le(e,t).parsed}function de(e,t){return fe(e,t).normalized}function fe(e,t){let{parsed:n,malformedAuthorityOrPort:r,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:o,malformedScheme:s}=le(e,t);return{normalized:r||i||a||o||s?e:E(n,t),malformedAuthorityOrPort:r,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:o,malformedScheme:s}}function pe(e,t){if(typeof e!=`string`&&typeof e!=`object`)return;let n;try{n=typeof e==`string`?e:E(e,t)}catch{return}let{normalized:r,malformedAuthorityOrPort:i,malformedPercentEncoding:a,malformedSchemeSpecific:o,malformedHost:s,malformedScheme:c}=fe(n,t);return i||a||o||s||c?void 0:r}let me={SCHEMES:h,normalize:S,resolve:C,resolveComponent:w,equal:T,serialize:E,parse:ue};t.exports=me,t.exports.default=me,t.exports.fastUri=me})),oy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ay();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),sy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=Qv();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var n=X();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=$v(),i=ey(),a=Hv(),o=ty(),s=X(),c=Zv(),l=Wv(),u=Z(),d=ny(),f=oy(),p=(e,t)=>new RegExp(e,t);p.code=`new RegExp`;let m=[`removeAdditional`,`useDefaults`,`coerceTypes`],h=/* @__PURE__ */ 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=Object.create(null),this._compilations=/* @__PURE__ */ new Set,this._loading={},this._cache=/* @__PURE__ */ 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=ee(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(ne.call(this,n,t),!t)return(0,u.eachItem)(n,e=>re.call(this,e)),this;ae.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=>re.call(this,e,r):e=>r.type.forEach(t=>re.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]=D(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){
145
+ /* istanbul ignore if */
146
+ 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);else{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 E={log(){},warn(){},error(){}};function ee(e){if(e===!1)return E;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 te=/^[a-z_$][a-z0-9_$:-]*$/i;function ne(e,t){let{RULES:n}=this;if((0,u.eachItem)(e,e=>{if(n.keywords[e])throw Error(`Keyword ${e} is already defined`);if(!te.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 re(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?ie.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 ie(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 ae(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=D(t)),e.validateSchema=this.compile(t,!0))}let oe={$ref:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`};function D(e){return{anyOf:[e,oe]}}})),cy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),ly=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.callRef=e.getValidate=void 0;let t=ey(),n=Kv(),r=X(),i=zv(),a=ty(),o=Z(),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);return h instanceof a.SchemaEnv?_(h):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})),uy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=cy(),n=ly();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),dy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=X(),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})`)}}})),fy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=X();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}))`)}}})),py=/* @__PURE__ */ D((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`})),my=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=X(),n=Z(),r=py();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}`)}}})),hy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Kv(),n=Z(),r=X();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})`)}}}})),gy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=X();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}`)}}})),_y=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Kv(),n=X(),r=Z();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)}}}})),vy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=X();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}`)}}})),yy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Yv();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),by=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Wv(),n=X(),r=Z(),i=yy();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)})))}}}})),xy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=X(),n=Z(),r=yy();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}`)}}})),Sy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=X(),n=Z(),r=yy();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{
147
+ /* istanbul ignore if */
148
+ 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}`}}}})),Cy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=dy(),n=fy(),r=my(),i=hy(),a=gy(),o=_y(),s=vy(),c=by(),l=xy(),u=Sy();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]})),wy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateAdditionalItems=void 0;let t=X(),n=Z(),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;Array.isArray(a)?i(e,a):(0,n.checkStrictMode)(r,`"additionalItems" is ignored when "items" is not an array of schemas`)}};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})),Ty=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateTuple=void 0;let t=X(),n=Z(),r=Kv(),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})),Ey=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Ty();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),Dy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=X(),n=Z(),r=Kv(),i=wy();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)))}}})),Oy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=X(),n=Z();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)))}}}})),ky=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;let t=X(),n=Z(),r=Kv();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},
149
+ missingProperty: ${i},
150
+ depsCount: ${n},
151
+ 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})),Ay=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=X(),n=Z();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)}}})),jy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Kv(),n=X(),r=zv(),i=Z();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;
152
+ /* istanbul ignore if */
153
+ 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);else if(o===!1)e.setParams({additionalProperty:t}),e.error(),d||a.break();else 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)}}}})),My=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Qv(),n=Kv(),r=Z(),i=jy();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)}}}})),Ny=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Kv(),n=X(),r=Z(),i=Z();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())})})}}}})),Py=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Z();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`}}})),Fy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:Kv().validateUnion,error:{message:`must match a schema in anyOf`}}})),Iy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=X(),n=Z();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;
154
+ /* istanbul ignore if */
155
+ 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)})})}}}})),Ly=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Z();e.default={keyword:`allOf`,schemaType:`array`,code(e){let{gen:n,schema:r,it:i}=e;
156
+ /* istanbul ignore if */
157
+ 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)})}}})),Ry=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=X(),n=Z(),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})),zy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Z();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`)}}})),By=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=wy(),n=Ey(),r=Ty(),i=Dy(),a=Oy(),o=ky(),s=Ay(),c=jy(),l=My(),u=Ny(),d=Py(),f=Fy(),p=Iy(),m=Ly(),h=Ry(),g=zy();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=_})),Vy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=X();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})`}}}}})),Hy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=[Vy().default]})),Uy=/* @__PURE__ */ D((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`]})),Wy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=uy(),n=Cy(),r=By(),i=Hy(),a=Uy();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),Gy=/* @__PURE__ */ D((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={}))})),Ky=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=X(),n=Gy(),r=ty(),i=ey(),a=Z();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}}}}})),qy=/* @__PURE__ */ D(((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}})),Jy=/* @__PURE__ */ D(((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=sy(),r=Wy(),i=Ky(),a=qy(),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=Qv();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return l.KeywordCxt}});var u=X();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=$v();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return d.default}});var f=ey();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return f.default}})})),Yy=/* @__PURE__ */ D((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:E,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=(/* @__PURE__ */ new Date(`2020-01-01T`+e)).valueOf(),r=(/* @__PURE__ */ 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 E(e){if(T.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),Xy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;let t=Jy(),n=X(),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)})),Zy=/* @__PURE__ */ D(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});let n=Yy(),r=Xy(),i=X(),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})),Qy=/* @__PURE__ */ le(Jy(),1),$y=/* @__PURE__ */ le(Zy(),1);function eb(){let e=new Qy.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,$y.default)(e),e}var tb=class{constructor(e){this._ajv=e??eb()}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)}}},nb=class{constructor(e){this._server=e}requestStream(e,t,n){return this._server.requestStream(e,t,n)}createMessageStream(e,t){let n=this._server.getClientCapabilities();if((e.tools||e.toolChoice)&&!n?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-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[e.messages.length-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},i_,t)}elicitInputStream(e,t){let n=this._server.getClientCapabilities(),r=e.mode??`form`;switch(r){case`url`:if(!n?.elicitation?.url)throw Error(`Client does not support url elicitation.`);break;case`form`:if(!n?.elicitation?.form)throw Error(`Client does not support form elicitation.`)}let i=r===`form`&&e.mode===void 0?{...e,mode:`form`}:e;return this.requestStream({method:`elicitation/create`,params:i},g_,t)}async getTask(e,t){return this._server.getTask({taskId:e},t)}async getTaskResult(e,t,n){return this._server.getTaskResult({taskId:e},t,n)}async listTasks(e,t){return this._server.listTasks(e?{cursor:e}:void 0,t)}async cancelTask(e,t){return this._server.cancelTask({taskId:e},t)}};function rb(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);if(t===`tools/call`&&!e.tools?.call)throw Error(`${n} does not support task creation for tools/call (required for ${t})`)}function ib(e,t,n){if(!e)throw Error(`${n} does not support task creation (required for ${t})`);switch(t){case`sampling/createMessage`:if(!e.sampling?.createMessage)throw Error(`${n} does not support task creation for sampling/createMessage (required for ${t})`);break;case`elicitation/create`:if(!e.elicitation?.create)throw Error(`${n} does not support task creation for elicitation/create (required for ${t})`)}}var ab=class extends Pv{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=/* @__PURE__ */ new Map,this.LOG_LEVEL_SEVERITY=new Map(Gg.options.map((e,t)=>[e,t])),this.isMessageIgnored=(e,t)=>{let n=this._loggingLevels.get(t);return n?this.LOG_LEVEL_SEVERITY.get(e)<this.LOG_LEVEL_SEVERITY.get(n):!1},this._capabilities=t?.capabilities??{},this._instructions=t?.instructions,this._jsonSchemaValidator=t?.jsonSchemaValidator??new tb,this.setRequestHandler(kh,e=>this._oninitialize(e)),this.setNotificationHandler(Mh,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(qg,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=Gg.safeParse(r);return i.success&&this._loggingLevels.set(n,i.data),{}})}get experimental(){return this._experimental||={tasks:new nb(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=Iv(this._capabilities,e)}setRequestHandler(e,t){let n=Zf(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r=rp(n);if(typeof r!=`string`)throw Error(`Schema method literal must be a string`);return r===`tools/call`?super.setRequestHandler(e,async(e,n)=>{let r=Yf(Ug,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new q(K.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=Yf(Hh,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new q(K.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=Yf(Vg,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new q(K.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 Error(`Client does not support sampling (required for ${e})`);break;case`elicitation/create`:if(!this._clientCapabilities?.elicitation)throw Error(`Client does not support elicitation (required for ${e})`);break;case`roots/list`:if(!this._clientCapabilities?.roots)throw Error(`Client does not support listing roots (required for ${e})`)}}assertNotificationCapability(e){switch(e){case`notifications/message`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`notifications/resources/updated`:case`notifications/resources/list_changed`:if(!this._capabilities.resources)throw Error(`Server does not support notifying about resources (required for ${e})`);break;case`notifications/tools/list_changed`:if(!this._capabilities.tools)throw Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case`notifications/prompts/list_changed`:if(!this._capabilities.prompts)throw Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case`notifications/elicitation/complete`:if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support URL elicitation (required for ${e})`)}}assertRequestHandlerCapability(e){if(this._capabilities)switch(e){case`completion/complete`:if(!this._capabilities.completions)throw Error(`Server does not support completions (required for ${e})`);break;case`logging/setLevel`:if(!this._capabilities.logging)throw Error(`Server does not support logging (required for ${e})`);break;case`prompts/get`:case`prompts/list`:if(!this._capabilities.prompts)throw Error(`Server does not support prompts (required for ${e})`);break;case`resources/list`:case`resources/templates/list`:case`resources/read`:if(!this._capabilities.resources)throw Error(`Server does not support resources (required for ${e})`);break;case`tools/call`:case`tools/list`:if(!this._capabilities.tools)throw Error(`Server does not support tools (required for ${e})`);break;case`tasks/get`:case`tasks/list`:case`tasks/result`:case`tasks/cancel`:if(!this._capabilities.tasks)throw Error(`Server does not support tasks capability (required for ${e})`)}}assertTaskCapability(e){ib(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&rb(this._capabilities.tasks?.requests,e,`Server`)}async _oninitialize(e){let t=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:qm.includes(t)?t:Km,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.request({method:`ping`},vh)}async createMessage(e,t){if((e.tools||e.toolChoice)&&!this._clientCapabilities?.sampling?.tools)throw Error(`Client does not support sampling tools capability.`);if(e.messages.length>0){let t=e.messages[e.messages.length-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[e.messages.length-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 e.tools?this.request({method:`sampling/createMessage`,params:e},a_,t):this.request({method:`sampling/createMessage`,params:e},i_,t)}async elicitInput(e,t){switch(e.mode??`form`){case`url`:{if(!this._clientCapabilities?.elicitation?.url)throw Error(`Client does not support url elicitation.`);let n=e;return this.request({method:`elicitation/create`,params:n},g_,t)}case`form`:{if(!this._clientCapabilities?.elicitation?.form)throw Error(`Client does not support form elicitation.`);let n=e.mode===`form`?e:{...e,mode:`form`},r=await this.request({method:`elicitation/create`,params:n},g_,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new q(K.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof q?e:new q(K.InternalError,`Error validating elicitation response: ${e instanceof Error?e.message:String(e)}`)}return r}}}createElicitationCompletionNotifier(e,t){if(!this._clientCapabilities?.elicitation?.url)throw Error(`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.request({method:`roots/list`,params:e},E_,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`})}};const ob=Symbol.for(`mcp.completable`);function sb(e){return!!e&&typeof e==`object`&&ob in e}function cb(e){return e[ob]?.complete}var lb;(function(e){e.Completable=`McpCompletable`})(lb||={});const ub=/^[A-Za-z0-9._-]{1,128}$/;function db(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`),!ub.test(e)){let n=e.split(``).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 fb(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 pb(e){let t=db(e);return fb(e,t.warnings),t.isValid}var mb=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)}};function hb(e,t){let n=0,r=[e];for(;r.length>0;){let e=r.pop();if(typeof e==`object`&&e){if(Array.isArray(e))for(let i of e){if(++n>t)return n;typeof i==`object`&&i&&r.push(i)}else for(let i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;if(++n>t)return n;let a=e[i];typeof a==`object`&&a&&r.push(a)}}}return n}function gb(e){if(e!==void 0&&e!==1/0){if(typeof e!=`number`||Number.isNaN(e)||e<1)throw RangeError(`maxToolInputElements must be a number of at least 1, or Infinity, got ${String(e)}`);return e}}var _b=class{constructor(e,t){this._registeredResources={},this._registeredResourceTemplates={},this._registeredTools={},this._registeredPrompts={},this._toolHandlersInitialized=!1,this._completionHandlerInitialized=!1,this._resourceHandlersInitialized=!1,this._promptHandlersInitialized=!1,this.server=new ab(e,t),this._maxToolInputElements=gb(t?.maxToolInputElements),t?.capabilities?.tools&&this.setToolRequestHandlers(),t?.capabilities?.resources&&this.setResourceRequestHandlers(),t?.capabilities?.prompts&&this.setPromptRequestHandlers()}get experimental(){return this._experimental||={tasks:new mb(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(wb(zg)),this.server.assertCanSetRequestHandler(wb(Ug)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(zg,()=>({tools:Object.entries(this._registeredTools).filter(([,e])=>e.enabled).map(([e,t])=>{let n={name:e,title:t.title,description:t.description,inputSchema:(()=>{let e=Qf(t.inputSchema);return e?jv(e,{strictUnions:!0,pipeStrategy:`input`}):vb})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=Qf(t.outputSchema);e&&(n.outputSchema=jv(e,{strictUnions:!0,pipeStrategy:`output`}))}return n})})),this.server.setRequestHandler(Ug,async(e,t)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new q(K.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new q(K.InvalidParams,`Tool ${e.params.name} disabled`);let r=!!e.params.task,i=n.execution?.taskSupport,a=`createTask`in n.handler;if((i===`required`||i===`optional`)&&!a)throw new q(K.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new q(K.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 q&&e.code===K.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(this._maxToolInputElements!==void 0&&hb(t,this._maxToolInputElements)>this._maxToolInputElements)throw new q(K.InvalidParams,`Invalid arguments for tool ${n}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);if(!e.inputSchema)return;let r=await Xf(Qf(e.inputSchema)??e.inputSchema,t??{});if(!r.success){let e=ep(`error`in r?r.error:`Unknown error`);throw new q(K.InvalidParams,`Input validation error: Invalid arguments for tool ${n}: ${e}`)}return r.data}async validateToolOutput(e,t,n){if(!e.outputSchema||!(`content`in t)||t.isError)return;if(!t.structuredContent)throw new q(K.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await Xf(Qf(e.outputSchema),t.structuredContent);if(!r.success){let e=ep(`error`in r?r.error:`Unknown error`);throw new q(K.InvalidParams,`Output validation error: Invalid structured content for tool ${n}: ${e}`)}}async executeToolHandler(e,t,n){let r=e.handler;if(`createTask`in r){if(!n.taskStore)throw Error(`No task store provided.`);let i={...n,taskStore:n.taskStore};if(e.inputSchema){let e=r;return await Promise.resolve(e.createTask(t,i))}{let e=r;return await Promise.resolve(e.createTask(i))}}if(e.inputSchema){let e=r;return await Promise.resolve(e(t,n))}{let e=r;return await Promise.resolve(e(n))}}async handleAutomaticTaskPolling(e,t,n){if(!n.taskStore)throw Error(`No task store provided for task-capable tool.`);let r=await this.validateToolInput(e,t.params.arguments,t.params.name),i=e.handler,a={...n,taskStore:n.taskStore},o=r?await Promise.resolve(i.createTask(r,a)):await Promise.resolve(i.createTask(a)),s=o.task.taskId,c=o.task,l=c.pollInterval??5e3;for(;c.status!==`completed`&&c.status!==`failed`&&c.status!==`cancelled`;){await new Promise(e=>setTimeout(e,l));let e=await n.taskStore.getTask(s);if(!e)throw new q(K.InternalError,`Task ${s} not found during polling`);c=e}return await n.taskStore.getTaskResult(s)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(wb(b_)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(b_,async e=>{switch(e.params.ref.type){case`ref/prompt`:return x_(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return S_(e),this.handleResourceCompletion(e,e.params.ref);default:throw new q(K.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new q(K.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new q(K.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return Eb;let r=Zf(n.argsSchema)?.[e.params.argument.name];if(!sb(r))return Eb;let i=cb(r);return i?Tb(await i(e.params.argument.value,e.params.context)):Eb}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 Eb;throw new q(K.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?Tb(await r(e.params.argument.value,e.params.context)):Eb}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(wb(og)),this.server.assertCanSetRequestHandler(wb(cg)),this.server.assertCanSetRequestHandler(wb(fg)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(og,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(cg,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(fg,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new q(K.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 q(K.InvalidParams,`Resource ${n} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(wb(Cg)),this.server.assertCanSetRequestHandler(wb(Eg)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Cg,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?Cb(t.argsSchema):void 0}))})),this.server.setRequestHandler(Eg,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new q(K.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new q(K.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let r=await Xf(Qf(n.argsSchema),e.params.arguments??{});if(!r.success){let t=ep(`error`in r?r.error:`Unknown error`);throw new q(K.InvalidParams,`Invalid arguments for prompt ${e.params.name}: ${t}`)}let i=r.data,a=n.callback;return await Promise.resolve(a(i,t))}{let e=n.callback;return await Promise.resolve(e(t))}}),!0)}resource(e,t,...n){let r;typeof n[0]==`object`&&(r=n.shift());let i=n[0];if(typeof t==`string`){if(this._registeredResources[t])throw Error(`Resource ${t} is already registered`);let n=this._createRegisteredResource(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}{if(this._registeredResourceTemplates[e])throw Error(`Resource template ${e} is already registered`);let n=this._createRegisteredResourceTemplate(e,void 0,t,r,i);return this.setResourceRequestHandlers(),this.sendResourceListChanged(),n}}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){let a={title:t,description:n,argsSchema:r===void 0?void 0:Jf(r),callback: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._registeredPrompts[e],t.name&&(this._registeredPrompts[t.name]=a)),t.title!==void 0&&(a.title=t.title),t.description!==void 0&&(a.description=t.description),t.argsSchema!==void 0&&(a.argsSchema=Jf(t.argsSchema)),t.callback!==void 0&&(a.callback=t.callback),t.enabled!==void 0&&(a.enabled=t.enabled),this.sendPromptListChanged()}};return this._registeredPrompts[e]=a,r&&Object.values(r).some(e=>sb(e instanceof xm?e._def?.innerType:e))&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,t,n,r,i,a,o,s,c){pb(e);let l={title:t,description:n,inputSchema:Sb(r),outputSchema:Sb(i),annotations:a,execution:o,_meta:s,handler:c,enabled:!0,disable:()=>l.update({enabled:!1}),enable:()=>l.update({enabled:!0}),remove:()=>l.update({name:null}),update:t=>{t.name!==void 0&&t.name!==e&&(typeof t.name==`string`&&pb(t.name),delete this._registeredTools[e],t.name&&(this._registeredTools[t.name]=l)),t.title!==void 0&&(l.title=t.title),t.description!==void 0&&(l.description=t.description),t.paramsSchema!==void 0&&(l.inputSchema=Jf(t.paramsSchema)),t.outputSchema!==void 0&&(l.outputSchema=Jf(t.outputSchema)),t.callback!==void 0&&(l.handler=t.callback),t.annotations!==void 0&&(l.annotations=t.annotations),t._meta!==void 0&&(l._meta=t._meta),t.enabled!==void 0&&(l.enabled=t.enabled),this.sendToolListChanged()}};return this._registeredTools[e]=l,this.setToolRequestHandlers(),this.sendToolListChanged(),l}tool(e,...t){if(this._registeredTools[e])throw Error(`Tool ${e} is already registered`);let n,r,i,a;if(typeof t[0]==`string`&&(n=t.shift()),t.length>1){let n=t[0];if(xb(n))r=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!xb(t[0])&&(a=t.shift());else if(typeof n==`object`&&n){if(Object.values(n).some(e=>typeof e==`object`&&!!e))throw Error(`Tool ${e} expected a Zod schema or ToolAnnotations, but received an unrecognized object`);a=t.shift()}}let o=t[0];return this._createRegisteredTool(e,void 0,n,r,i,a,{taskSupport:`forbidden`},void 0,o)}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)}prompt(e,...t){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let n;typeof t[0]==`string`&&(n=t.shift());let r;t.length>1&&(r=t.shift());let i=t[0],a=this._createRegisteredPrompt(e,void 0,n,r,i);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),a}registerPrompt(e,t,n){if(this._registeredPrompts[e])throw Error(`Prompt ${e} is already registered`);let{title:r,description:i,argsSchema:a}=t,o=this._createRegisteredPrompt(e,r,i,a,n);return this.setPromptRequestHandlers(),this.sendPromptListChanged(),o}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()}};const vb={type:`object`,properties:{}};function yb(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function bb(e){return`_def`in e||`_zod`in e||yb(e)}function xb(e){return typeof e!=`object`||!e||bb(e)?!1:Object.keys(e).length===0||Object.values(e).some(yb)}function Sb(e){if(e){if(xb(e))return Jf(e);if(!bb(e))throw Error(`inputSchema must be a Zod schema or raw shape, received an unrecognized object`);return e}}function Cb(e){let t=Zf(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:tp(t),required:!np(t)})):[]}function wb(e){let t=Zf(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=rp(t);if(typeof n==`string`)return n;throw Error(`Schema method literal must be a string`)}function Tb(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const Eb={completion:{values:[],hasMore:!1}};var Db=class{constructor(e){this._maxBufferSize=e?.maxBufferSize??10485760}append(e){if((this._buffer?.length??0)+e.length>this._maxBufferSize)throw this.clear(),Error(`ReadBuffer exceeded maximum size of ${this._maxBufferSize} bytes`);this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
158
+ `);if(e===-1)return null;let t=this._buffer.toString(`utf8`,0,e).replace(/\r$/,``);return this._buffer=this._buffer.subarray(e+1),Ob(t)}clear(){this._buffer=void 0}};function Ob(e){return _h.parse(JSON.parse(e))}function kb(e){return JSON.stringify(e)+`
159
+ `}var Ab=class{constructor(e=r.stdin,t=r.stdout,n){this._stdin=e,this._stdout=t,this._started=!1,this._ondata=e=>{try{this._readBuffer.append(e),this.processReadBuffer()}catch(e){this.onerror?.(e),this.close().catch(()=>{})}},this._onerror=e=>{this.onerror?.(e)},this._readBuffer=new Db({maxBufferSize:n?.maxBufferSize})}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)}processReadBuffer(){for(;;)try{let e=this._readBuffer.readMessage();if(e===null)break;this.onmessage?.(e)}catch(e){this.onerror?.(e)}}async close(){this._stdin.off(`data`,this._ondata),this._stdin.off(`error`,this._onerror),this._stdin.listenerCount(`data`)===0&&this._stdin.pause(),this._readBuffer.clear(),this.onclose?.()}send(e){return new Promise(t=>{let n=kb(e);this._stdout.write(n)?t():this._stdout.once(`drain`,t)})}};const jb=/* @__PURE__ */ `bell.calendar.calendar-check.calendar-x.chat-text.chat-circle.credit-card.receipt.repeat.queue.list-checks.users.user-circle.lock.key.shield-check.magnifying-glass.chart-bar.file-text.files.image.envelope.globe.map-pin.clock.timer.lightning.robot.sparkle.gear.plug.database.cloud.upload-simple.download-simple.link.tag.folder.house.shopping-cart.money.bank.wallet.translate.paint-brush.device-mobile.star.arrows-clockwise.warning.check-circle.book-open.package.truck.heartbeat.stethoscope.camera.microphone.video-camera.puzzle-piece`.split(`.`),Mb=(e,t)=>{let n=/^\s*#\s+(.+?)\s*#*\s*(\n|$)/.exec(e);return(n&&n[1]?.trim().toLowerCase()===t.trim().toLowerCase()?e.slice(n[0].length):e).trim().replace(/^(#{1,5}) /gm,`$1# `)};function Nb(e,t=1/0){let n=[`# Quirl: ${e.project.name}`,`You are working in the Quirl project "${e.project.slug}" as ${e.role}. Quirl is the team's source of truth for what this software does. Use the quirl MCP tools (search_docs, lookup, update_task…) to look things up and keep tasks current.`,e.project.description].filter(Boolean).join(`
160
+
161
+ `),r=[];e.flags?.length&&r.push(`## Flags from the team (act on these, then mark each done with resolve_flag)\n\n${e.flags.map(e=>{let t=[e.section.ref,e.section.name].filter(Boolean).join(` `);return`- ${e.section.type} ${t||`(removed)`}: ${e.message}${e.flaggedBy?` (from ${e.flaggedBy})`:``} [flag ${e.id}]`}).join(`
162
+ `)}`);for(let t of e.alwaysLoadedDocs)r.push(`## ${t.title}${t.stale?` (may be out of date)`:``}\n\n${Mb(t.body,t.title)}`);e.myCards.length&&r.push(`## Your open tasks\n\n${e.myCards.map(e=>`- ${e.number} ${e.title} [${e.status}]${e.blocked?` BLOCKED: ${e.blockedReason}`:``}`).join(`
163
+ `)}`),e.tagSets?.length&&r.push(`## Tags (only these; each kind of item has its own sets)\n\n${e.tagSets.map(e=>`- ${e.for}, ${e.label} (${e.key}): ${e.values.join(`, `)}`).join(`
164
+ `)}`);let i=e.glossary.filter(e=>!e.tagSet);if(i.length||e.deprecatedTerms.length){let t=i.map(e=>`- **${e.term}**${e.aliases.length?` (also: ${e.aliases.join(`, `)})`:``}: ${e.plain}`);e.deprecatedTerms.length&&t.push(`\nDon't say: ${e.deprecatedTerms.map(e=>e.useInstead?`"${e.term}" (say "${e.useInstead}")`:`"${e.term}"`).join(`, `)}.`),r.push(`## Glossary (use these words)\n\n${t.join(`
165
+ `)}`)}e.capabilities.length&&r.push(`## What the product does\n\n${e.capabilities.map(e=>`- ${e.ref?`${e.ref} `:``}**${e.name}** [${e.status}]: ${e.whatItDoes}`).join(`
166
+ `)}`),e.otherDocs.length&&r.push(`## Other docs (fetch with search_docs or read_doc when relevant)\n\n${e.otherDocs.map(e=>`- ${e.title} (${e.type})${e.summary?`: ${e.summary}`:``}`).join(`
167
+ `)}`);let a=n;for(let e of r){let n=`${a}\n\n${e}`;if(n.length<=t){a=n;continue}let r=t-a.length-71-2;return r>200&&(a=`${a}\n\n${e.slice(0,r)}`),a+`
168
+
169
+ … (cut for length: call the quirl_context tool for the full briefing)`}return a}const Pb=e=>({content:[{type:`text`,text:typeof e==`string`?e:JSON.stringify(e,null,2)}]});function Fb(e){let t=new Ur(e),n=new _b({name:`quirl`,version:e.version},{instructions:`Quirl is this team's single source of truth for the project: what the product does (capabilities), the words the team uses (glossary), docs, tasks, repos and resources.
170
+ - Before answering questions about how the product works or what a term means, check Quirl (lookup, search_docs) rather than guessing. list_features and get_feature show what's being built.
171
+ - Use the glossary's words in code, commits and replies. Refer to items by their ids: capabilities C-12, features F-4, tasks by their number (e.g. Q-1). Don't use deprecated terms.
172
+ - When you start, finish or get blocked on work, update the task (update_task), and attach branches, commits and pull requests as evidence.
173
+ - Capabilities describe only what the product does today; everything coming is a feature. A feature either changes a capability, or has none and creates one. Never draft a capability for something not built yet.
174
+ - When a feature ships, propose the capability change: propose_capability_update for the capability it changed, or propose_capability with features=[the feature] for a new one.
175
+ - Features are what stakeholders follow on the Features page; tasks are the work under them. Put each task under the feature it serves (create_task or update_task with feature). If no feature fits, request one (request_feature) rather than leaving the task loose. A feature moves to in progress and shipped on its own as its tasks move.
176
+ - If you notice a capability description is wrong, or a capability or term is missing, propose it (propose_capability_update, propose_capability, propose_capability_details, propose_capability_archive, propose_term, propose_term_retire). A person approves it.
177
+ - Tag items only from their tag sets (listed under Tags in the briefing): capabilities by who they're for and their kind, features by kind of change, tasks by kind of work. Product areas aren't tags; group capabilities under a parent capability instead.
178
+ - Flags are messages people send about a section (a capability, feature, task, doc or term). Approved ones are listed first in the briefing: act on them, then mark each done with resolve_flag. Only admins approve or remove flags (decide_flag); list_flags shows them.
179
+ - Home shows everyone the product as a map built from Quirl: each top-level capability with its icon, arrows from what it relies on, and its parts listed under it. Give features and capabilities an icon (request_feature's icon, set_feature_icon, set_capability_icon), and propose what each capability relies on and which capability it's part of (propose_capability_details) once it's approved.
180
+ - If the project has no capabilities yet, offer to read the codebase and draft them with propose_capability.
181
+ - If the project briefing isn't already in your context, call quirl_context first.`}),r={p_project:e.project},i=()=>({tool:n.server.getClientVersion()?.name??`mcp`,model:process.env.QUIRL_AGENT_MODEL}),a=e=>async t=>{try{return Pb(await e(t))}catch(e){if(e instanceof Hr)return{...Pb(e.message),isError:!0};throw e}};n.registerTool(`quirl_context`,{title:`Project briefing`,description:`The project briefing: always-loaded docs in full, glossary, capabilities, your open tasks and the list of other docs. Usually already loaded at session start.`,inputSchema:{}},a(async()=>Nb(await t.context(e.project)))),n.registerTool(`search_docs`,{title:`Search docs`,description:`Full-text search across the project's docs (README, ADRs, guides, runbooks). Returns matching sections with their content. Use for anything not in the briefing.`,inputSchema:{query:V().describe(`Words to search for, e.g. 'refund approval limits'`),limit:H().int().min(1).max(20).optional()}},a(({query:e,limit:n})=>t.call(`search_docs`,{...r,p_query:e,p_limit:n??6}))),n.registerTool(`read_doc`,{title:`Read a doc`,description:`Read one doc in full, by id, title or source path.`,inputSchema:{doc:V().describe(`Doc id, title or path, e.g. 'docs/adr/004-queues.md'`)}},a(({doc:e})=>t.call(`read_doc`,{...r,p_doc:e}))),n.registerTool(`lookup`,{title:`Look up a term, capability or contract`,description:`Find glossary terms, capabilities, features and API/table contracts matching a name. Use it to check what a word means here, or the request/response shape of an endpoint or table.`,inputSchema:{query:V().describe(`A term, capability, endpoint or table name, e.g. 'Visit' or 'POST /login'`)}},a(({query:e})=>t.call(`lookup`,{...r,p_query:e})));let o=(e,t,r,i)=>{n.registerTool(e,r,i),n.registerTool(t,{...r,description:`Old name for ${e}; use ${e}. ${r.description}`},i)};o(`list_tasks`,`list_cards`,{title:`List tasks`,description:`List tasks on the board. Defaults to your own tasks that aren't done.`,inputSchema:{onlyMine:Qp().optional(),includeDone:Qp().optional()}},a(({onlyMine:e,includeDone:n})=>t.call(`list_cards`,{...r,p_only_mine:e??!0,p_include_done:n??!1})));let s=`Markdown: short paragraphs, and lists for steps or parts, not one long block.`,c=`Kind of work: e.g. Frontend, Backend, Database, Design, DevOps, Testing, Docs, Research. Only tags from the task set are accepted (see tagSets in quirl_context); propose a new value with propose_term (kind tag, tagSet task_work).`,l=V().describe(`Task number, e.g. 'K-104' or '104'`);return o(`get_task`,`get_card`,{title:`Get a task`,description:`A task with its feature, docs, dependencies and evidence.`,inputSchema:{task:l.optional(),card:l.optional()}},a(({task:e,card:n})=>t.call(`get_card`,{...r,p_card:e??n}))),o(`create_task`,`create_card`,{title:`Create a task`,description:`Add a task to the board (status: todo). Use it for work you discover that should be tracked. Put it under the feature it serves.`,inputSchema:{title:V(),description:V().optional().describe(`What to do and why. ${s}`),type:_m([`feature_work`,`bug`,`chore`,`research`]).optional(),feature:V().optional().describe(`Feature name or id (e.g. F-4) this task belongs to`),tags:U(V()).optional().describe(c)}},a(async({title:e,description:n,type:a,feature:o,tags:s})=>{let c=await t.call(`create_card`,{...r,p_title:e,p_description:n??``,p_type:a??`feature_work`,p_feature:o??null,p_agent:i()});return s?.length&&await t.call(`update_card`,{...r,p_card:c,p_patch:{tags:s},p_agent:i()}),c})),o(`update_task`,`update_card`,{title:`Update a task`,description:`Move a task, mark it blocked (with a reason) or unblocked, put it under a feature, set its tags, rewrite its title or description, and attach evidence: a branch, commit or pull request. Repos are referenced by name.`,inputSchema:{task:l.optional(),card:l.optional(),status:_m([`backlog`,`todo`,`in_progress`,`review`,`done`]).optional(),feature:V().optional().describe(`Feature name or id (e.g. F-4) to put the task under; an empty string takes it off its feature`),title:V().optional(),description:V().optional().describe(`Replaces the description. ${s}`),tags:U(V()).optional().describe(`${c} Replaces the current tags.`),blocked:Qp().optional(),blockedReason:V().optional(),addBranch:W({repo:V(),name:V()}).optional(),addCommit:W({repo:V(),sha:V(),message:V().optional()}).optional(),addPullRequest:W({repo:V(),number:H().int(),url:V(),state:_m([`open`,`merged`,`closed`]).optional()}).optional()}},a(({task:e,card:n,...a})=>t.call(`update_card`,{...r,p_card:e??n,p_patch:a,p_agent:i()}))),n.registerTool(`propose_term`,{title:`Propose a glossary term`,description:`Suggest a new glossary term. It shows up for approval; it isn't used until a person approves it.`,inputSchema:{term:V(),plain:V().describe(`What it means, for someone non-technical`),technical:V().describe(`What it means in the code`),kind:_m([`concept`,`tag`,`name`]).optional(),tagSet:V().optional().describe(`Required for kind 'tag': the set the value belongs to, e.g. feature_change, task_work, capability_audience, capability_kind (see tagSets in quirl_context)`),reason:V().optional()}},a(({term:e,plain:n,technical:a,kind:o,tagSet:s,reason:c})=>t.call(`propose_term`,{...r,p_term:e,p_plain:n,p_technical:a,p_kind:o??`concept`,p_tag_set:s??null,p_reason:c??null,p_agent:i()}))),n.registerTool(`propose_term_retire`,{title:`Retire a glossary term`,description:`Propose retiring a glossary term or tag that's no longer used or was a mistake. With replaceWith, the term stays as one not to say (agents are told the replacement); without it, it's removed. Either way it comes off every capability, task and feature that used it. A person approves it. Built-in tag values can't be retired.`,inputSchema:{term:V().describe(`The term or tag to retire`),replaceWith:V().optional().describe(`An approved term to say instead, if there is one`),reason:V().optional()}},a(({term:e,replaceWith:n,reason:a})=>t.call(`propose_term_retire`,{...r,p_term:e,p_replace_with:n??null,p_reason:a??null,p_agent:i()}))),n.registerTool(`list_flags`,{title:`List flags`,description:`Flags are messages people send about a section of the project: a capability, feature, task, doc or glossary term. Lists open (waiting for an admin) and approved (to act on) flags, or only those with the given status.`,inputSchema:{status:_m([`open`,`approved`,`removed`,`done`]).optional()}},a(({status:e})=>t.call(`list_flags`,{...r,p_status:e??null}))),n.registerTool(`decide_flag`,{title:`Approve or remove a flag`,description:`Admins only. Approve a flag so agents act on it at the start of their sessions, or remove it. An approved flag can still be removed. Only do this when the person you work for asks you to.`,inputSchema:{flag:V().describe(`The flag's id, from the briefing or list_flags`),decision:_m([`approve`,`remove`])}},a(({flag:e,decision:n})=>t.call(`decide_flag`,{...r,p_flag:e,p_approve:n===`approve`,p_agent:i()}))),n.registerTool(`resolve_flag`,{title:`Mark a flag done`,description:`Mark an approved flag done once you've handled it, so it leaves the briefing. Say briefly what you did.`,inputSchema:{flag:V().describe(`The flag's id, from the briefing or list_flags`),note:V().optional().describe(`What was done, e.g. 'Updated C-12 to mention SMS'`)}},a(({flag:e,note:n})=>t.call(`resolve_flag`,{...r,p_flag:e,p_note:n??null,p_agent:i()}))),n.registerTool(`set_capability_icon`,{title:`Set a capability's icon`,description:`Give a capability an icon that fits what it does; it's shown on the capability's card. Use the same icon a related feature has when one fits both.`,inputSchema:{capability:V().describe(`Capability name or id (e.g. C-12)`),icon:_m(jb)}},a(({capability:e,icon:n})=>t.call(`set_capability_icon`,{...r,p_capability:e,p_icon:n,p_agent:i()}))),n.registerTool(`list_features`,{title:`List features`,description:`List the project's features with their status, the capability each changes (or createsCapability when it has none), and task counts. Shipped ones are left out unless includeShipped. Check here before requesting a feature.`,inputSchema:{includeShipped:Qp().optional()}},a(({includeShipped:e})=>t.call(`list_features`,{...r,p_include_shipped:e??!1}))),n.registerTool(`get_feature`,{title:`Get a feature`,description:`A feature with its description, status, the capability it changes (and what that capability does) and its tasks.`,inputSchema:{feature:V().describe(`Feature name or id (e.g. F-4)`)}},a(({feature:e})=>t.call(`get_feature`,{...r,p_feature:e}))),n.registerTool(`request_feature`,{title:`Request a feature`,description:`Request a feature: a change to the product that stakeholders follow on the Features page, usually made of several tasks. Check list_features first so you don't request one twice. It shows as requested straight away and a person accepts or declines it. Put tasks under it with create_task or update_task.`,inputSchema:{name:V().describe(`Short name, e.g. 'Repeat appointments'`),description:V().describe(`What changes for the user, in plain words. Markdown: short paragraphs, and lists for parts`),capability:V().optional().describe(`Capability name or id (e.g. C-12) it changes. Leave it out when the feature creates a new capability`),tags:U(V()).optional().describe(`Kind of change: e.g. New, Improvement, Visual, Fix, Performance, Security, Removal, Internal (the feature_change set in quirl_context)`),reason:V().optional().describe(`Why it's worth doing`),icon:_m(jb).optional().describe(`An icon that fits the feature, shown on its card`)}},a(async({name:e,description:n,capability:a,tags:o,reason:s,icon:c})=>{let l=await t.call(`request_feature`,{...r,p_name:e,p_description:n,p_capability:a??null,p_tags:o??null,p_reason:s??null,p_agent:i()});return c&&l===`requested`&&await t.call(`set_feature_icon`,{...r,p_feature:e,p_icon:c,p_agent:i()}),l})),n.registerTool(`set_feature_icon`,{title:`Set a feature's icon`,description:`Give a feature an icon that fits what it does; it's shown on the feature's card. list_features shows which features have none.`,inputSchema:{feature:V().describe(`Feature name or id (e.g. F-4)`),icon:_m(jb)}},a(({feature:e,icon:n})=>t.call(`set_feature_icon`,{...r,p_feature:e,p_icon:n,p_agent:i()}))),n.registerTool(`tag_feature`,{title:`Tag a feature`,description:`Set a feature's kind-of-change tags (replaces the current ones). Only values from the feature_change tag set are accepted.`,inputSchema:{feature:V().describe(`Feature name or id (e.g. F-4)`),tags:U(V()).describe(`Kind of change: e.g. New, Improvement, Visual, Fix, Performance, Security, Removal, Internal`)}},a(({feature:e,tags:n})=>t.call(`tag_feature`,{...r,p_feature:e,p_tags:n,p_agent:i()}))),n.registerTool(`propose_capability`,{title:`Propose a capability`,description:"Draft a capability: one thing the product does today, described for a non-technical reader. Use it when the project has none yet (for example right after `quirl init`), when you find one that's missing, or when a feature that creates a new capability ships (pass it in features). Never for something not built yet: request a feature instead. A person approves it before it shows up.",inputSchema:{name:V().describe(`Short name, e.g. 'Online booking'`),whatItDoes:V().describe(`One or two plain sentences, no jargon`),technical:V().optional().describe(`Where it lives in the code and how it works. Markdown: short paragraphs, and lists for parts, not one long block`),features:U(V()).optional().describe(`Feature names or ids (e.g. F-4) that create or change this capability; they're linked to it once it's approved`),reason:V().optional()}},a(({name:e,whatItDoes:n,technical:a,features:o,reason:s})=>t.call(`propose_capability`,{...r,p_name:e,p_what_it_does:n,p_technical:a??``,p_features:o??null,p_reason:s??null,p_agent:i()}))),n.registerTool(`propose_capability_archive`,{title:`Propose archiving a capability`,description:`Suggest retiring a capability that no longer describes what the product does, or that was drafted for something not built yet. Unshipped features linked to it will create a new capability when they ship. A person approves it.`,inputSchema:{capability:V().describe(`Capability name or id (e.g. C-12)`),reason:V().describe(`Why it should go`)}},a(({capability:e,reason:n})=>t.call(`propose_capability_archive`,{...r,p_capability:e,p_reason:n,p_agent:i()}))),n.registerTool(`propose_capability_update`,{title:`Propose a capability correction`,description:`Suggest a corrected description for a capability when the code no longer matches it. A person approves it.`,inputSchema:{capability:V().describe(`Capability name or id (e.g. C-12)`),field:_m([`what_it_does`,`technical_description`]),after:V().describe(`The corrected text. Markdown: short paragraphs, and lists for parts, not one long block`),reason:V().optional()}},a(({capability:e,field:n,after:a,reason:o})=>t.call(`propose_capability_update`,{...r,p_capability:e,p_field:n,p_after:a,p_reason:o??null,p_agent:i()}))),n.registerTool(`propose_capability_details`,{title:`Propose how a capability works and its connections`,description:`Suggest a capability's 'How it works' steps, its tags (glossary terms of kind 'tag'), the capability it's part of, and its connections: capabilities it relies on, repos, resources it runs on, glossary terms and docs. Each part you pass replaces that part when a person approves it; parts you leave out are kept. Names are matched to existing, approved items. What it relies on draws the arrows on the Home map, so link the steps a user goes through (e.g. invoicing relies on booking).`,inputSchema:{capability:V().describe(`Capability name or id (e.g. C-12)`),howItWorks:U(V()).optional().describe(`3 to 5 plain-language steps, as the user experiences it`),reliesOn:U(W({capability:V().describe(`Capability name or id (e.g. C-12)`),label:V().describe(`How it relies on it, read before the name, e.g. 'extends'`)})).optional(),parent:V().optional().describe(`The capability this one is part of (name or id, e.g. C-2), or 'none' to make it top-level. Parts are listed under their parent instead of on their own`),repos:U(V()).optional().describe(`Repo names`),resources:U(V()).optional().describe(`Resource names it runs on`),terms:U(V()).optional().describe(`Glossary terms`),docs:U(V()).optional().describe(`Doc titles, or <repo>/<path> (e.g. quirl/AGENTS.md) when titles repeat`),tags:U(V()).optional().describe(`Who it's for (Customer, Admin, Developer, Agent) and its kind (Interface, Integration, Data, Automation, Infrastructure, Access and security, AI): the capability tag sets in quirl_context`),reason:V().optional()}},a(({capability:e,howItWorks:n,reliesOn:a,parent:o,repos:s,resources:c,terms:l,docs:u,tags:d,reason:f})=>t.call(`propose_capability_details`,{...r,p_capability:e,p_how_it_works:n??null,p_relies_on:a??null,p_parent:o??null,p_repos:s??null,p_resources:c??null,p_terms:l??null,p_docs:u??null,p_tags:d??null,p_reason:f??null,p_agent:i()}))),n}async function Ib(e){await Fb(e).connect(new Ab)}const Lb=`0.1.0`,Rb=process.env.QUIRL_SERVER===`local`?{apiUrl:`http://127.0.0.1:54321`,publishableKey:`sb_publishable_ACJWlzQHlZjBrEguHvfOxg_3BJgxAaH`,appUrl:`http://localhost:5173`}:{apiUrl:`https://dugevhzlzrdtasuibdzr.supabase.co`,publishableKey:`sb_publishable_45P7GyyZoJsN0AO3wfmqNA_CXbx1iCW`,appUrl:`https://app.quirl.io`};function zb(){return{apiUrl:process.env.QUIRL_API_URL??Rb.apiUrl,publishableKey:process.env.QUIRL_PUBLISHABLE_KEY??Rb.publishableKey,appUrl:process.env.QUIRL_APP_URL??Rb.appUrl}}const Bb=()=>x(process.env.XDG_CONFIG_HOME??x(h(),`.config`),`quirl`),Vb=()=>x(Bb(),`credentials.json`);async function Hb(){try{return JSON.parse(await u(Vb(),`utf8`))}catch{return{}}}async function Ub(){return process.env.QUIRL_KEY?{apiUrl:zb().apiUrl,key:process.env.QUIRL_KEY,email:``}:(await Hb())[zb().apiUrl]??null}async function Wb(e){let t=await Hb();t[e.apiUrl]=e,await l(Bb(),{recursive:!0,mode:448}),await m(Vb(),`${JSON.stringify(t,null,` `)}\n`,{mode:384}),await s(Vb(),384)}async function Gb(){let e=await Hb();delete e[zb().apiUrl],Object.keys(e).length?await m(Vb(),`${JSON.stringify(e,null,` `)}\n`,{mode:384}):await f(Vb(),{force:!0})}async function Kb(){let e=zb();return{apiUrl:e.apiUrl,publishableKey:e.publishableKey,key:(await Ub())?.key??``}}function qb(e=process.cwd()){try{return a(`git`,[`rev-parse`,`--show-toplevel`],{cwd:e,stdio:[`ignore`,`pipe`,`ignore`]}).toString().trim()}catch{return e}}const Jb=e=>x(e,`.quirl`,`project.json`);async function Yb(e=process.cwd()){let t=e;for(;;)try{return{root:t,link:JSON.parse(await u(Jb(t),`utf8`))}}catch{let e=y(t);if(e===t)return null;t=e}}async function Xb(e,t){await l(x(e,`.quirl`),{recursive:!0}),await m(Jb(e),`${JSON.stringify(t,null,` `)}\n`)}async function Zb({hook:e=!1}={}){let t=await Yb();if(!t){if(e)return;throw Error("This folder isn't linked to a Quirl project. Run `quirl init`.")}try{let n=await new Ur(await Kb()).context(t.link.projectId);process.stdout.write(`${Nb(n,e?9500:void 0)}\n`)}catch(n){if(!e)throw n;process.stdout.write(`Quirl project "${t.link.name}": couldn't load the briefing (${n.message}). The quirl MCP tools may still work.\n`)}}const Qb=/* @__PURE__ */ new Set([`.git`,`node_modules`,`dist`,`build`,`.next`,`vendor`,`.venv`,`venv`,`__pycache__`,`coverage`,`.turbo`,`.svelte-kit`,`.nuxt`,`.output`,`.cache`,`.vercel`,`.pnpm-store`,`fixtures`,`test-fixtures`,`__fixtures__`,`testdata`]),$b=2e5;async function ex(e){let t=[],n=await tx(e,t),r=new Map(n.map(e=>[e.path,e]));return{root:e,files:n,warnings:t,file:e=>r.get(e),async readText(e,n=1048576){if(e.size>n)return t.push(`${e.path}: skipped, ${cx(e.size)} is over the ${cx(n)} limit`),null;try{return await u(e.absolutePath,`utf8`)}catch(n){return t.push(`${e.path}: could not be read (${ox(n)})`),null}}}}async function tx(e,t){let n=[],r=[``];for(;r.length>0;){let i=r.pop(),a;try{a=await d(_.join(e,i),{withFileTypes:!0})}catch(e){t.push(`${i||`.`}: folder could not be read (${ox(e)})`);continue}for(let o of a){let a=i?`${i}/${o.name}`:o.name;if(o.isSymbolicLink())continue;if(o.isDirectory()){!Qb.has(o.name)&&!T(_.join(e,a,`.git`))&&r.push(a);continue}if(!o.isFile())continue;if(n.length>=$b)return t.push(`Stopped after ${$b} files; the rest of the tree was not scanned`),nx(n);let s=_.join(e,a);try{let e=await c(s);n.push({path:a,absolutePath:s,size:e.size})}catch(e){t.push(`${a}: could not be read (${ox(e)})`)}}}return nx(n)}function nx(e){return e.sort((e,t)=>e.path<t.path?-1:+(e.path>t.path))}function rx(e){let t=e.lastIndexOf(`/`);return t===-1?e:e.slice(t+1)}function ix(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}function ax(e,t){return e?`${e}/${t}`:t}function ox(e){return e instanceof Error?e.message:String(e)}function Q(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function sx(e){return typeof e==`string`?e:void 0}function cx(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:`${Math.ceil(e/1024)} KB`}async function lx(e,t=3){let n=[],r=async(e,i)=>{if(T(_.join(e,`.git`))&&n.push(e),i>=t)return;let a;try{a=await d(e,{withFileTypes:!0})}catch{return}for(let t of a)!t.isDirectory()||t.name.startsWith(`.`)||Qb.has(t.name)||await r(_.join(e,t.name),i+1)};return await r(_.resolve(e),0),n.sort((e,t)=>e.localeCompare(t))}const ux=process.stdout.isTTY&&!process.env.NO_COLOR,dx=e=>t=>ux?`\x1b[${e}m${t}\x1b[0m`:t,fx=dx(1),px=dx(2),mx=dx(32),hx=dx(31),gx=dx(36),_x=e=>console.log(`${mx(`✓`)} ${e}`),vx=e=>console.log(` ${e}`),yx=(e,t)=>console.log(`\n${e} ${t}`),bx=e=>console.log(` ${e}`);function xx(e){if(!ux)return bx(px(e)),{stop:()=>{}};let t=0,n=setInterval(()=>{process.stdout.write(`\r ${gx(`⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏`[t++%10]??``)} ${px(e)}`)},80);return{stop:()=>{clearInterval(n),process.stdout.write(`\r\x1B[2K`)}}}var Sx=class extends Error{};async function Cx(e,t=``){if(!process.stdin.isTTY)return t;let n=E({input:process.stdin,output:process.stdout});try{return(await n.question(e)).trim()||t}finally{n.close()}}async function wx(e,t){let n=await Cx(`${e} ${px(t?`[Y/n]`:`[y/N]`)} `,t?`y`:`n`);return/^y/i.test(n)}function Tx(e){if(process.env.QUIRL_NO_BROWSER)return;let t=process.platform===`darwin`?`open`:process.platform===`win32`?`cmd`:`xdg-open`,n=process.platform===`win32`?[`/c`,`start`,``,e]:[e];try{o(t,n,{stdio:`ignore`,detached:!0}).on(`error`,()=>{}).unref()}catch{}}const Ex=`<!-- quirl:start -->`,Dx=`<!-- quirl:end -->`,Ox=`# quirl: keep the project in sync`;function kx(){try{let e=a(process.platform===`win32`?`where`:`which`,[`quirl`],{stdio:[`ignore`,`pipe`,`ignore`]}).toString();if(!/[\\/]_npx[\\/]/.test(e))return{command:`quirl`,args:[],shell:`quirl`,portable:!0}}catch{}return{command:`npx`,args:[`-y`,`quirl-cli`],shell:`npx -y quirl-cli`,portable:!0}}const Ax=[`QUIRL_SERVER`,`QUIRL_API_URL`,`QUIRL_PUBLISHABLE_KEY`,`QUIRL_APP_URL`];function jx(){return Object.fromEntries(Ax.flatMap(e=>process.env[e]?[[e,process.env[e]]]:[]))}function Mx(){return`${Object.entries(jx()).map(([e,t])=>`${e}="${t}" `).join(``)}${kx().shell}`}async function Nx(e){try{return JSON.parse(await u(e,`utf8`))}catch(t){if(t.code===`ENOENT`)return{};throw Error(`${e} isn't valid JSON; fix it and run \`quirl init\` again.`)}}const Px=async(e,t)=>{await l(y(e),{recursive:!0}),await m(e,`${JSON.stringify(t,null,2)}\n`)};async function Fx(e){let t=x(e,`.mcp.json`),n=await Nx(t),r=kx();n.mcpServers={...n.mcpServers,quirl:{command:r.command,args:[...r.args,`mcp`],...Object.keys(jx()).length?{env:jx()}:{}}},await Px(t,n)}async function Ix(e){let t=x(e,`.claude`,`settings.json`),n=await Nx(t),r=n.hooks??{},i=`${Mx()} context --hook`;r.SessionStart=[...(r.SessionStart??[]).map(e=>({...e,hooks:e.hooks.filter(e=>!/\bcontext --hook$/.test(e.command))})).filter(e=>e.hooks.length),{hooks:[{type:`command`,command:i,timeout:15}]}],n.hooks=r,await Px(t,n)}async function Lx(e,t,n=[]){let r=x(e,`CLAUDE.md`),i=``;try{i=await u(r,`utf8`)}catch{}let a=`${Ex}
182
+ ## Quirl
183
+
184
+ ${n.length?`This folder holds the repos of the Quirl project **${t}** (${n.join(`, `)}). Quirl is`:`This repo is part of the Quirl project **${t}**,`} the team's source of truth for what the product does. The project briefing (always-loaded docs, glossary, capabilities, your tasks) is loaded at the start of each session. Use the \`quirl\` MCP tools:
185
+
186
+ - Before explaining or changing how something works, check Quirl: \`lookup\` for terms, capabilities and API/table contracts, \`search_docs\` / \`read_doc\` for anything else.
187
+ - Use the glossary's words in code, commits and replies. Refer to items by their ids: capabilities \`C-12\`, features \`F-4\`, tasks by their number (e.g. \`Q-1\`).
188
+ - Keep tasks current with \`update_task\`: move them as work starts and ends, say why when blocked, and attach branches, commits and pull requests.
189
+ - Put each task under the feature it serves (\`feature\` on \`create_task\` / \`update_task\`). If none fits, request one with \`request_feature\`.
190
+ - Tag items only from their tag sets (listed under Tags in the briefing): tasks by kind of work, features by kind of change (\`tag_feature\`), capabilities by who they're for and their kind. Product areas aren't tags; group capabilities under a parent capability.
191
+ - Capabilities describe only what exists; anything not built yet is a feature. When a feature ships, propose the capability change (\`propose_capability_update\`, or \`propose_capability\` with \`features\` for a new one).
192
+ - If a capability description or term is wrong or missing, propose a fix (\`propose_capability_update\`, \`propose_term\`) instead of working around it. Retire a term that's no longer used with \`propose_term_retire\`.
193
+ - After changing docs, dependencies or schemas, run \`quirl sync\` (the pre-push hook does it on push).
194
+ ${Dx}`,o=RegExp(`${Ex}[\\s\\S]*?${Dx}`);i=o.test(i)?i.replace(o,a):`${i.trimEnd()}${i.trim()?`
195
+
196
+ `:``}${a}\n`,await m(r,i)}async function Rx(e){let t;try{t=a(`git`,[`rev-parse`,`--git-path`,`hooks`],{cwd:e}).toString().trim()}catch{return null}b(t)||(t=x(e,t));let n=x(t,`pre-push`),r=``;try{r=await u(n,`utf8`)}catch{}let i=`${Ox}\n${Mx()} sync --quiet --source=git_hook || echo "quirl: sync skipped"\n`,o=r.indexOf(Ox);if(o>=0){let e=r.indexOf(`
197
+ `,r.indexOf(`
198
+ `,o)+1);r=`${r.slice(0,o)}${i}${e>=0?r.slice(e+1):``}`}else r=r?`${r.trimEnd()}\n\n${i}`:`#!/bin/sh\n${i}`;return await l(t,{recursive:!0}),await m(n,r),await s(n,493),n}async function zx({quiet:e=!1}={}){let t=zb(),n=await Ub();yx(`🔑`,fx(`Sign in to Quirl`)),n&&!e&&bx(px(`Already signed in as ${n.email}. Signing in again replaces this machine's key.`));let r=Wr(t.apiUrl,t.publishableKey),i=await r.start(`quirl CLI on ${g()}`),a=`${t.appUrl}/cli/authorize?code=${i.user_code}`;bx(`Approve this computer in your browser:`),bx(gx(a)),bx(`Check the code matches ${fx(Bx(i.user_code))}`),Tx(a);let o=xx(`Waiting for you to approve…`),s=Date.now()+6e5;for(;Date.now()<s;){await new Promise(e=>setTimeout(e,2e3));let e=await r.poll(i.request_id,i.poll_secret);if(e.status===`approved`&&e.key){let n=await new Ur({...t,key:e.key}).whoami();return o.stop(),await Wb({apiUrl:t.apiUrl,key:e.key,email:n.email}),bx(`${mx(`✓`)} Signed in as ${fx(n.email)}`),n}if(e.status!==`pending`)throw o.stop(),new Sx(`Sign-in ${e.status}. Run \`quirl login\` again.`)}throw o.stop(),new Sx("Sign-in timed out. Run `quirl login` again.")}const Bx=e=>`${e.slice(0,4)}-${e.slice(4)}`,Vx=/* @__PURE__ */ new Set([`docs`,`doc`,`adr`,`adrs`,`architecture`]),Hx=/* @__PURE__ */ new Set([`readme.md`,`contributing.md`,`architecture.md`]),Ux=/^(changelog|changes|history|license|licence|copying|notice|code_of_conduct|claude|agents)(\.|$)/i,Wx=/\.(md|mdx|markdown)$/i;async function Gx(e){let t=[];for(let n of e.files){if(!Kx(n.path))continue;let r=await e.readText(n);if(r===null)continue;let i=qx(r)??rx(n.path).replace(Wx,``),a=Yx(n.path,i);t.push({path:n.path,title:i,type:a,body:r,alwaysLoadCandidate:Xx(n.path,a),contentHash:C(`sha256`).update(r).digest(`hex`)})}return t}function Kx(e){let t=rx(e);if(!Wx.test(t)||Ux.test(t))return!1;let n=e.toLowerCase().split(`/`);return n.length===1?Hx.has(n[0]??``):e.toLowerCase()===`.github/contributing.md`||n.slice(0,-1).some(e=>Vx.has(e))}function qx(e){let t=e.replace(/\r\n/g,`
199
+ `),n=/^---\n([\s\S]*?)\n---\n/.exec(t),r=n?.[1]?/^title:\s*["']?(.+?)["']?\s*$/m.exec(n[1]):null;if(r?.[1])return r[1];let i=t.replace(/^(```|~~~)[\s\S]*?^\1.*$/gm,``),a=/^#\s+(.+?)\s*#*\s*$/m.exec(i),o=/^(?!\s*$)([^\n#>].*)\n=+\s*$/m.exec(i),s=a&&o?a.index<o.index?a[1]:o[1]:a?.[1]??o?.[1];return s?Jx(s):null}function Jx(e){return e.replace(/!\[[^\]]*\]\([^)]*\)/g,``).replace(/\[([^\]]*)\]\([^)]*\)/g,`$1`).replace(/[`*_]/g,``).trim()}function Yx(e,t){let n=`${e} ${t}`.toLowerCase();return/(^|\/)adrs?\//.test(n)||/\bdecision|\badr[-_ ]?\d/.test(n)?`decision`:/guideline|convention|contributing|style ?guide|styleguide|code[-_ ]?style|coding[-_ ]standard/.test(n)?`guideline`:/guide|how[-_ ]?to|setup|set[-_ ]up|getting[-_ ]started|install|tutorial|runbook|playbook/.test(n)?`how_to`:/architecture|design|overview/.test(n)?`architecture`:`reference`}function Xx(e,t){if(t===`guideline`)return!0;let n=rx(e).toLowerCase();return/architecture|conventions?|guidelines?|contributing|style-?guide/.test(n)||t===`architecture`&&/overview/.test(n)}const Zx=/* @__PURE__ */ new Set([`claude.md`,`agents.md`,`.cursorrules`]);async function Qx(e){let t=[];for(let n of e.files){if(!(Zx.has(rx(n.path).toLowerCase())||n.path===`.github/copilot-instructions.md`))continue;let r=(await e.readText(n))?.replace(/<!-- quirl:start -->[\s\S]*?<!-- quirl:end -->\n?/,``).trim();r&&t.push({path:n.path,body:r})}return t}const $x=/\.(md|mdx|markdown|txt)$/i,eS=/\.(pdf|docx?|odt|rtf|pages|pptx?|key|xlsx?|numbers)$/i;async function tS(e){let t=[],n=[];for(let r of e.files){if(r.path.split(`/`).some(e=>e.startsWith(`.`)))continue;let i=rx(r.path);if(eS.test(i)){n.push(r.path);continue}if(!$x.test(i)||/^(claude|agents)\.md$/i.test(i))continue;let a=await e.readText(r);if(!a?.trim())continue;let o=i.replace($x,``),s=(Wx.test(i)?qx(a):null)??o,c=Yx(r.path,s);t.push({path:r.path,title:s,type:c,body:a,alwaysLoadCandidate:!1,contentHash:C(`sha256`).update(a).digest(`hex`)})}return{docs:t,unsupported:n}}var nS=class{#e=/* @__PURE__ */ new Map;#t;#n;constructor(e,t){this.#t=e,this.#n=t}add(e,t,n){if(!e||!t)return;let r=this.#e.get(e);r&&(r.direct&&!n||r.direct===n&&rS(r.version,t)>=0)||this.#e.set(e,{ecosystem:this.#t,package:e,version:t,direct:n,sourceLockfile:this.#n})}has(e){return this.#e.has(e)}rows(){return[...this.#e.values()].sort((e,t)=>e.package.localeCompare(t.package))}};function rS(e,t){let n=e=>e.replace(/^v/,``).split(/[.+-]/),r=n(e),i=n(t);for(let e=0;e<Math.max(r.length,i.length);e++){let t=r[e]??``,n=i[e]??``,a=Number(t),o=Number(n),s=t!==``&&n!==``&&!Number.isNaN(a)&&!Number.isNaN(o)?a-o:t.localeCompare(n);if(s!==0)return s}return 0}function iS(e){let t=/* @__PURE__ */ new Set;if(!Q(e))return t;for(let n of[`dependencies`,`devDependencies`,`optionalDependencies`,`peerDependencies`]){let r=e[n];if(Q(r))for(let e of Object.keys(r))t.add(e)}return t}function aS(e){return JSON.parse(e)}function oS(e,t,n){let r=aS(e);if(!Q(r))throw Error(`not a JSON object`);let i=/* @__PURE__ */ new Set;if(n!==null){let e=aS(n);if(Q(e))for(let t of[`require`,`require-dev`]){let n=e[t];if(Q(n))for(let e of Object.keys(n))i.add(e.toLowerCase())}}let a=new nS(`composer`,t);for(let e of[`packages`,`packages-dev`]){let t=r[e];if(Array.isArray(t))for(let e of t){if(!Q(e))continue;let{name:t,version:n}=e;typeof t==`string`&&typeof n==`string`&&a.add(t,n,i.has(t.toLowerCase()))}}return a.rows()}function sS(e,t,n){let r=new nS(`other`,n),i=/* @__PURE__ */ new Set;if(e!==null){let t=!1;for(let n of e.split(/\r?\n/)){let e=n.trim();if(t){if(e.startsWith(`)`)){t=!1;continue}a(e);continue}if(/^require\s*\($/.test(e)){t=!0;continue}let r=/^require\s+(.+)$/.exec(e);r?.[1]&&a(r[1])}}function a(e){let t=/^(\S+)\s+(\S+)(.*)$/.exec(e);if(!t?.[1]||!t[2]||t[1].startsWith(`//`))return;let n=/\/\/\s*indirect\b/.test(t[3]??``);r.add(t[1],t[2],!n),i.add(t[1])}if(t!==null)for(let e of t.split(/\r?\n/)){let[t,n]=e.trim().split(/\s+/);if(!t||!n)continue;let a=n.replace(/\/go\.mod$/,``);i.has(t)||r.add(t,a,!1)}return r.rows()}var $=/* @__PURE__ */ D((e=>{let t=Symbol.for(`yaml.alias`),n=Symbol.for(`yaml.document`),r=Symbol.for(`yaml.map`),i=Symbol.for(`yaml.pair`),a=Symbol.for(`yaml.scalar`),o=Symbol.for(`yaml.seq`),s=Symbol.for(`yaml.node.type`),c=e=>!!e&&typeof e==`object`&&e[s]===t,l=e=>!!e&&typeof e==`object`&&e[s]===n,u=e=>!!e&&typeof e==`object`&&e[s]===r,d=e=>!!e&&typeof e==`object`&&e[s]===i,f=e=>!!e&&typeof e==`object`&&e[s]===a,p=e=>!!e&&typeof e==`object`&&e[s]===o;function m(e){if(e&&typeof e==`object`)switch(e[s]){case r:case o:return!0}return!1}function h(e){if(e&&typeof e==`object`)switch(e[s]){case t:case r:case a:case o:return!0}return!1}e.ALIAS=t,e.DOC=n,e.MAP=r,e.NODE_TYPE=s,e.PAIR=i,e.SCALAR=a,e.SEQ=o,e.hasAnchor=e=>(f(e)||m(e))&&!!e.anchor,e.isAlias=c,e.isCollection=m,e.isDocument=l,e.isMap=u,e.isNode=h,e.isPair=d,e.isScalar=f,e.isSeq=p})),cS=/* @__PURE__ */ D((e=>{var t=$();let n=Symbol(`break visit`),r=Symbol(`skip children`),i=Symbol(`remove node`);function a(e,n){let r=l(n);t.isDocument(e)?o(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):o(null,e,r,Object.freeze([]))}a.BREAK=n,a.SKIP=r,a.REMOVE=i;function o(e,r,a,s){let c=u(e,r,a,s);if(t.isNode(c)||t.isPair(c))return d(e,s,c),o(e,c,a,s);if(typeof c!=`symbol`){if(t.isCollection(r)){s=Object.freeze(s.concat(r));for(let e=0;e<r.items.length;++e){let t=o(e,r.items[e],a,s);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){s=Object.freeze(s.concat(r));let e=o(`key`,r.key,a,s);if(e===n)return n;e===i&&(r.key=null);let t=o(`value`,r.value,a,s);if(t===n)return n;t===i&&(r.value=null)}}return c}async function s(e,n){let r=l(n);t.isDocument(e)?await c(null,e.contents,r,Object.freeze([e]))===i&&(e.contents=null):await c(null,e,r,Object.freeze([]))}s.BREAK=n,s.SKIP=r,s.REMOVE=i;async function c(e,r,a,o){let s=await u(e,r,a,o);if(t.isNode(s)||t.isPair(s))return d(e,o,s),c(e,s,a,o);if(typeof s!=`symbol`){if(t.isCollection(r)){o=Object.freeze(o.concat(r));for(let e=0;e<r.items.length;++e){let t=await c(e,r.items[e],a,o);if(typeof t==`number`)e=t-1;else if(t===n)return n;else t===i&&(r.items.splice(e,1),--e)}}else if(t.isPair(r)){o=Object.freeze(o.concat(r));let e=await c(`key`,r.key,a,o);if(e===n)return n;e===i&&(r.key=null);let t=await c(`value`,r.value,a,o);if(t===n)return n;t===i&&(r.value=null)}}return s}function l(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 u(e,n,r,i){if(typeof r==`function`)return r(e,n,i);if(t.isMap(n))return r.Map?.(e,n,i);if(t.isSeq(n))return r.Seq?.(e,n,i);if(t.isPair(n))return r.Pair?.(e,n,i);if(t.isScalar(n))return r.Scalar?.(e,n,i);if(t.isAlias(n))return r.Alias?.(e,n,i)}function d(e,n,r){let i=n[n.length-1];if(t.isCollection(i))i.items[e]=r;else if(t.isPair(i))e===`key`?i.key=r:i.value=r;else if(t.isDocument(i))i.contents=r;else{let e=t.isAlias(i)?`alias`:`scalar`;throw Error(`Cannot replace node with ${e} parent`)}}e.visit=a,e.visitAsync=s})),lS=/* @__PURE__ */ D((e=>{var t=$(),n=cS();let r={"!":`%21`,",":`%2C`,"[":`%5B`,"]":`%5D`,"{":`%7B`,"}":`%7D`},i=e=>e.replace(/[!,[\]{}]/g,e=>r[e]);var a=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+i(e.substring(n.length));return e[0]===`!`?e:`!<${e}>`}toString(e){let r=this.yaml.explicit?[`%YAML ${this.yaml.version||`1.2`}`]:[],i=Object.entries(this.tags),a;if(e&&i.length>0&&t.isNode(e.contents)){let r={};n.visit(e.contents,(e,n)=>{t.isNode(n)&&n.tag&&(r[n.tag]=!0)}),a=Object.keys(r)}else a=[];for(let[t,n]of i)t===`!!`&&n===`tag:yaml.org,2002:`||e&&!a.some(e=>e.startsWith(n))||r.push(`%TAG ${t} ${n}`);return r.join(`
200
+ `)}};a.defaultYaml={explicit:!1,version:`1.2`},a.defaultTags={"!!":`tag:yaml.org,2002:`},e.Directives=a})),uS=/* @__PURE__ */ D((e=>{var t=$(),n=cS();function r(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 i(e){let t=/* @__PURE__ */ new Set;return n.visit(e,{Value(e,n){n.anchor&&t.add(n.anchor)}}),t}function a(e,t){for(let n=1;;++n){let r=`${e}${n}`;if(!t.has(r))return r}}function o(e,n){let r=[],o=/* @__PURE__ */ new Map,s=null;return{onAnchor:t=>{r.push(t),s??=i(e);let o=a(n,s);return s.add(o),o},setAnchors:()=>{for(let e of r){let n=o.get(e);if(typeof n==`object`&&n.anchor&&(t.isScalar(n.node)||t.isCollection(n.node)))n.node.anchor=n.anchor;else{let t=/* @__PURE__ */ Error(`Failed to resolve repeated object (this should not happen)`);throw t.source=e,t}}},sourceObjects:o}}e.anchorIsValid=r,e.anchorNames=i,e.createNodeAnchors=o,e.findNewAnchor=a})),dS=/* @__PURE__ */ D((e=>{function t(e,n,r,i){if(i&&typeof i==`object`){if(Array.isArray(i))for(let n=0,r=i.length;n<r;++n){let r=i[n],a=t(e,i,String(n),r);a===void 0?delete i[n]:a!==r&&(i[n]=a)}else if(i instanceof Map)for(let n of Array.from(i.keys())){let r=i.get(n),a=t(e,i,n,r);a===void 0?i.delete(n):a!==r&&i.set(n,a)}else if(i instanceof Set)for(let n of Array.from(i)){let r=t(e,i,n,n);r===void 0?i.delete(n):r!==n&&(i.delete(n),i.add(r))}else for(let[n,r]of Object.entries(i)){let a=t(e,i,n,r);a===void 0?delete i[n]:a!==r&&(i[n]=a)}}return e.call(n,r,i)}e.applyReviver=t})),fS=/* @__PURE__ */ D((e=>{var t=$();function n(e,r,i){if(Array.isArray(e))return e.map((e,t)=>n(e,String(t),i));if(e&&typeof e.toJSON==`function`){if(!i||!t.hasAnchor(e))return e.toJSON(r,i);let n={aliasCount:0,count:1,res:void 0};i.anchors.set(e,n),i.onCreate=e=>{n.res=e,delete i.onCreate};let a=e.toJSON(r,i);return i.onCreate&&i.onCreate(a),a}return typeof e==`bigint`&&!i?.keep?Number(e):e}e.toJS=n})),pS=/* @__PURE__ */ D((e=>{var t=dS(),n=$(),r=fS();e.NodeBase=class{constructor(e){Object.defineProperty(this,n.NODE_TYPE,{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:i,maxAliasCount:a,onAnchor:o,reviver:s}={}){if(!n.isDocument(e))throw TypeError(`A document argument is required`);let c={anchors:/* @__PURE__ */ new Map,doc:e,keep:!0,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof a==`number`?a:100},l=r.toJS(this,``,c);if(typeof o==`function`)for(let{count:e,res:t}of c.anchors.values())o(t,e);return typeof s==`function`?t.applyReviver(s,{"":l},``,l):l}}})),mS=/* @__PURE__ */ D((e=>{var t=uS(),n=cS(),r=$(),i=pS(),a=fS(),o=class extends i.NodeBase{constructor(e){super(r.ALIAS),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 i;t?.aliasResolveCache?i=t.aliasResolveCache:(i=[],n.visit(e,{Node:(e,t)=>{(r.isAlias(t)||r.hasAnchor(t))&&i.push(t)}}),t&&(t.aliasResolveCache=i));let o;for(let e of i){if(e===this)break;e.anchor===this.source&&(o=e)}if(o&&t){let{anchors:e,doc:n,maxAliasCount:r}=t,i=e.get(o);
201
+ /* istanbul ignore if */
202
+ if(i||=(a.toJS(o,null,t),e.get(o)),i?.res===void 0)throw ReferenceError(`This should not happen: Alias anchor was not resolved?`);if(r>=0&&(i.count+=1,i.aliasCount===0&&(i.aliasCount=s(n,o,e)),i.count*i.aliasCount>r))throw ReferenceError(`Excessive alias count indicates a resource exhaustion attack`)}return o}toJSON(e,t){if(!t)return{source:this.source};let n=this.resolve(t.doc,t);if(!n){let e=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw ReferenceError(e)}return t.anchors.get(n).res}toString(e,n,r){let i=`*${this.source}`;if(e){if(t.anchorIsValid(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`${i} `}return i}};function s(e,t,n){if(r.isAlias(t)){let r=t.resolve(e),i=n&&r&&n.get(r);return i?i.count*i.aliasCount:0}if(r.isCollection(t)){let r=0;for(let i of t.items){let t=s(e,i,n);t>r&&(r=t)}return r}if(r.isPair(t)){let r=s(e,t.key,n),i=s(e,t.value,n);return Math.max(r,i)}return 1}e.Alias=o})),hS=/* @__PURE__ */ D((e=>{var t=$(),n=pS(),r=fS();let i=e=>!e||typeof e!=`function`&&typeof e!=`object`;var a=class extends n.NodeBase{constructor(e){super(t.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:r.toJS(this.value,e,t)}toString(){return String(this.value)}};a.BLOCK_FOLDED=`BLOCK_FOLDED`,a.BLOCK_LITERAL=`BLOCK_LITERAL`,a.PLAIN=`PLAIN`,a.QUOTE_DOUBLE=`QUOTE_DOUBLE`,a.QUOTE_SINGLE=`QUOTE_SINGLE`,e.Scalar=a,e.isScalarValue=i})),gS=/* @__PURE__ */ D((e=>{var t=mS(),n=$(),r=hS();function i(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 a(e,a,o){if(n.isDocument(e)&&(e=e.contents),n.isNode(e))return e;if(n.isPair(e)){let t=o.schema[n.MAP].createNode?.(o.schema,null,o);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:s,onAnchor:c,onTagObj:l,schema:u,sourceObjects:d}=o,f;if(s&&e&&typeof e==`object`){if(f=d.get(e),f)return f.anchor??(f.anchor=c(e)),new t.Alias(f.anchor);f={anchor:null,node:null},d.set(e,f)}a?.startsWith(`!!`)&&(a=`tag:yaml.org,2002:`+a.slice(2));let p=i(e,a,u.tags);if(!p){if(e&&typeof e.toJSON==`function`&&(e=e.toJSON()),!e||typeof e!=`object`){let t=new r.Scalar(e);return f&&(f.node=t),t}p=e instanceof Map?u[n.MAP]:Symbol.iterator in Object(e)?u[n.SEQ]:u[n.MAP]}l&&(l(p),delete o.onTagObj);let m=p?.createNode?p.createNode(o.schema,e,o):typeof p?.nodeClass?.from==`function`?p.nodeClass.from(o.schema,e,o):new r.Scalar(e);return a?m.tag=a:p.default||(m.tag=p.tag),f&&(f.node=m),m}e.createNode=a})),_S=/* @__PURE__ */ D((e=>{var t=gS(),n=$(),r=pS();function i(e,n,r){let i=r;for(let e=n.length-1;e>=0;--e){let t=n[e];if(typeof t==`number`&&Number.isInteger(t)&&t>=0){let e=[];e[t]=i,i=e}else i=/* @__PURE__ */ new Map([[t,i]])}return t.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw Error(`This should not happen, please report a bug.`)},schema:e,sourceObjects:/* @__PURE__ */ new Map})}let a=e=>e==null||typeof e==`object`&&!!e[Symbol.iterator]().next().done;e.Collection=class extends r.NodeBase{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=>n.isNode(t)||n.isPair(t)?t.clone(e):t),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(a(e))this.add(t);else{let[r,...a]=e,o=this.get(r,!0);if(n.isCollection(o))o.addIn(a,t);else if(o===void 0&&this.schema)this.set(r,i(this.schema,a,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${a}`)}}deleteIn(e){let[t,...r]=e;if(r.length===0)return this.delete(t);let i=this.get(t,!0);if(n.isCollection(i))return i.deleteIn(r);throw Error(`Expected YAML collection at ${t}. Remaining path: ${r}`)}getIn(e,t){let[r,...i]=e,a=this.get(r,!0);return i.length===0?!t&&n.isScalar(a)?a.value:a:n.isCollection(a)?a.getIn(i,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!n.isPair(t))return!1;let r=t.value;return r==null||e&&n.isScalar(r)&&r.value==null&&!r.commentBefore&&!r.comment&&!r.tag})}hasIn(e){let[t,...r]=e;if(r.length===0)return this.has(t);let i=this.get(t,!0);return n.isCollection(i)?i.hasIn(r):!1}setIn(e,t){let[r,...a]=e;if(a.length===0)this.set(r,t);else{let e=this.get(r,!0);if(n.isCollection(e))e.setIn(a,t);else if(e===void 0&&this.schema)this.set(r,i(this.schema,a,t));else throw Error(`Expected YAML collection at ${r}. Remaining path: ${a}`)}}},e.collectionFromPath=i,e.isEmptyPath=a})),vS=/* @__PURE__ */ D((e=>{let t=e=>e.replace(/^(?!$)(?: $)?/gm,`#`);function n(e,t){return/^\n+$/.test(e)?e.substring(1):t?e.replace(/^(?! *$)/gm,t):e}e.indentComment=n,e.lineComment=(e,t,r)=>e.endsWith(`
203
+ `)?n(r,t):r.includes(`
204
+ `)?`
205
+ `+n(r,t):(e.endsWith(` `)?``:` `)+r,e.stringifyComment=t})),yS=/* @__PURE__ */ D((e=>{let t=`block`,n=`quoted`;function r(e,r,a=`flow`,{indentAtStart:o,lineWidth:s=80,minContentWidth:c=20,onFold:l,onOverflow:u}={}){if(!s||s<0)return e;s<c&&(c=0);let d=Math.max(1+c,1+s-r.length);if(e.length<=d)return e;let f=[],p={},m=s-r.length;typeof o==`number`&&(o>s-Math.max(2,c)?f.push(0):m=s-o);let h,g,_=!1,v=-1,y=-1,b=-1;a===t&&(v=i(e,v,r.length),v!==-1&&(m=v+d));for(let o;o=e[v+=1];){if(a===n&&o===`\\`){switch(y=v,e[v+1]){case`x`:v+=3;break;case`u`:v+=5;break;case`U`:v+=9;break;default:v+=1}b=v}if(o===`
206
+ `)a===t&&(v=i(e,v,r.length)),m=v+r.length+d,h=void 0;else{if(o===` `&&g&&g!==` `&&g!==`
207
+ `&&g!==` `){let t=e[v+1];t&&t!==` `&&t!==`
208
+ `&&t!==` `&&(h=v)}if(v>=m){if(h)f.push(h),m=h+d,h=void 0;else if(a===n){for(;g===` `||g===` `;)g=o,o=e[v+=1],_=!0;let t=v>b+1?v-2:y-1;if(p[t])return e;f.push(t),p[t]=!0,m=t+d,h=void 0}else _=!0}}g=o}if(_&&u&&u(),f.length===0)return e;l&&l();let x=e.slice(0,f[0]);for(let t=0;t<f.length;++t){let i=f[t],o=f[t+1]||e.length;i===0?x=`\n${r}${e.slice(0,o)}`:(a===n&&p[i]&&(x+=`${e[i]}\\`),x+=`\n${r}${e.slice(i+1,o)}`)}return x}function i(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!==`
209
+ `);r=t,i=t+1,a=e[i]}return r}e.FOLD_BLOCK=t,e.FOLD_FLOW=`flow`,e.FOLD_QUOTED=n,e.foldFlowLines=r})),bS=/* @__PURE__ */ D((e=>{var t=hS(),n=yS();let r=(e,t)=>({indentAtStart:t?e.indent.length:e.indentAtStart,lineWidth:e.options.lineWidth,minContentWidth:e.options.minContentWidth}),i=e=>/^(%|---|\.\.\.)/m.test(e);function a(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]===`
210
+ `){if(t-n>r)return!0;if(n=t+1,i-n<=r)return!1}return!0}function o(e,t){let a=JSON.stringify(e);if(t.options.doubleQuotedAsJSON)return a;let{implicitKey:o}=t,s=t.options.doubleQuotedMinMultiLineLength,c=t.indent||(i(e)?` `:``),l=``,u=0;for(let e=0,t=a[e];t;t=a[++e])if(t===` `&&a[e+1]===`\\`&&a[e+2]===`n`&&(l+=a.slice(u,e)+`\\ `,e+=1,u=e,t=`\\`),t===`\\`)switch(a[e+1]){case`u`:{l+=a.slice(u,e);let t=a.substr(e+2,4);switch(t){case`0000`:l+=`\\0`;break;case`0007`:l+=`\\a`;break;case`000b`:l+=`\\v`;break;case`001b`:l+=`\\e`;break;case`0085`:l+=`\\N`;break;case`00a0`:l+=`\\_`;break;case`2028`:l+=`\\L`;break;case`2029`:l+=`\\P`;break;default:t.substr(0,2)===`00`?l+=`\\x`+t.substr(2):l+=a.substr(e,6)}e+=5,u=e+1}break;case`n`:if(o||a[e+2]===`"`||a.length<s)e+=1;else{for(l+=a.slice(u,e)+`
211
+
212
+ `;a[e+2]===`\\`&&a[e+3]===`n`&&a[e+4]!==`"`;)l+=`
213
+ `,e+=2;l+=c,a[e+2]===` `&&(l+=`\\`),e+=1,u=e+1}break;default:e+=1}return l=u?l+a.slice(u):a,o?l:n.foldFlowLines(l,c,n.FOLD_QUOTED,r(t,!1))}function s(e,t){if(t.options.singleQuote===!1||t.implicitKey&&e.includes(`
214
+ `)||/[ \t]\n|\n[ \t]/.test(e))return o(e,t);let a=t.indent||(i(e)?` `:``),s=`'`+e.replace(/'/g,`''`).replace(/\n+/g,`$&\n${a}`)+`'`;return t.implicitKey?s:n.foldFlowLines(s,a,n.FOLD_FLOW,r(t,!1))}function c(e,t){let{singleQuote:n}=t.options,r;if(n===!1)r=o;else{let t=e.includes(`"`),i=e.includes(`'`);r=t&&!i?s:i&&!t?o:n?s:o}return r(e,t)}let l;try{l=RegExp(`(^|(?<!
215
+ ))
216
+ +(?!
217
+ |$)`,`g`)}catch{l=/\n+(?!\n|$)/g}function u({comment:e,type:o,value:s},u,d,f){let{blockQuote:p,commentString:m,lineWidth:h}=u.options;if(!p||/\n[\t ]+$/.test(s))return c(s,u);let g=u.indent||(u.forceBlockIndent||i(s)?` `:``),_=p===`literal`?!0:p===`folded`||o===t.Scalar.BLOCK_FOLDED?!1:o===t.Scalar.BLOCK_LITERAL||!a(s,h,g.length);if(!s)return _?`|
218
+ `:`>
219
+ `;let v,y;for(y=s.length;y>0;--y){let e=s[y-1];if(e!==`
220
+ `&&e!==` `&&e!==` `)break}let b=s.substring(y),x=b.indexOf(`
221
+ `);x===-1?v=`-`:s===b||x!==b.length-1?(v=`+`,f&&f()):v=``,b&&=(s=s.slice(0,-b.length),b[b.length-1]===`
222
+ `&&(b=b.slice(0,-1)),b.replace(l,`$&${g}`));let S=!1,C,w=-1;for(C=0;C<s.length;++C){let e=s[C];if(e===` `)S=!0;else if(e===`
223
+ `)w=C;else break}let T=s.substring(0,w<C?w+1:C);T&&=(s=s.substring(T.length),T.replace(/\n+/g,`$&${g}`));let E=(S?g?`2`:`1`:``)+v;if(e&&(E+=` `+m(e.replace(/ ?[\r\n]+/g,` `)),d&&d()),!_){let e=s.replace(/\n+/g,`
224
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,`$1$2`).replace(/\n+/g,`$&${g}`),i=!1,a=r(u,!0);p!==`folded`&&o!==t.Scalar.BLOCK_FOLDED&&(a.onOverflow=()=>{i=!0});let c=n.foldFlowLines(`${T}${e}${b}`,g,n.FOLD_BLOCK,a);if(!i)return`>${E}\n${g}${c}`}return s=s.replace(/\n+/g,`$&${g}`),`|${E}\n${g}${T}${s}${b}`}function d(e,a,o,s){let{type:l,value:d}=e,{actualString:f,implicitKey:p,indent:m,indentStep:h,inFlow:g}=a;if(p&&d.includes(`
225
+ `)||g&&/[[\]{},]/.test(d))return c(d,a);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(d))return p||g||!d.includes(`
226
+ `)?c(d,a):u(e,a,o,s);if(!p&&!g&&l!==t.Scalar.PLAIN&&d.includes(`
227
+ `))return u(e,a,o,s);if(i(d)){if(m===``)return a.forceBlockIndent=!0,u(e,a,o,s);if(p&&m===h)return c(d,a)}let _=d.replace(/\n+/g,`$&\n${m}`);if(f){let e=e=>e.default&&e.tag!==`tag:yaml.org,2002:str`&&e.test?.test(_),{compat:t,tags:n}=a.doc.schema;if(n.some(e)||t?.some(e))return c(d,a)}return p?_:n.foldFlowLines(_,m,n.FOLD_FLOW,r(a,!1))}function f(e,n,r,i){let{implicitKey:a,inFlow:l}=n,f=typeof e.value==`string`?e:Object.assign({},e,{value:String(e.value)}),{type:p}=e;p!==t.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(f.value)&&(p=t.Scalar.QUOTE_DOUBLE);let m=e=>{switch(e){case t.Scalar.BLOCK_FOLDED:case t.Scalar.BLOCK_LITERAL:return a||l?c(f.value,n):u(f,n,r,i);case t.Scalar.QUOTE_DOUBLE:return o(f.value,n);case t.Scalar.QUOTE_SINGLE:return s(f.value,n);case t.Scalar.PLAIN:return d(f,n,r,i);default:return null}},h=m(p);if(h===null){let{defaultKeyType:e,defaultStringType:t}=n.options,r=a&&e||t;if(h=m(r),h===null)throw Error(`Unsupported default string type ${r}`)}return h}e.stringifyString=f})),xS=/* @__PURE__ */ D((e=>{var t=uS(),n=$(),r=vS(),i=bS();function a(e,t){let n=Object.assign({blockQuote:!0,commentString:r.stringifyComment,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),i;switch(n.collectionStyle){case`block`:i=!1;break;case`flow`:i=!0;break;default:i=null}return{anchors:/* @__PURE__ */ new Set,doc:e,flowCollectionPadding:n.flowCollectionPadding?` `:``,indent:``,indentStep:typeof n.indent==`number`?` `.repeat(n.indent):` `,inFlow:i,options:n}}function o(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 r,i;if(n.isScalar(t)){i=t.value;let n=e.filter(e=>e.identify?.(i));if(n.length>1){let e=n.filter(e=>e.test);e.length>0&&(n=e)}r=n.find(e=>e.format===t.format)??n.find(e=>!e.format)}else i=t,r=e.find(e=>e.nodeClass&&i instanceof e.nodeClass);if(!r){let e=i?.constructor?.name??(i===null?`null`:typeof i);throw Error(`Tag not resolved for ${e} value`)}return r}function s(e,r,{anchors:i,doc:a}){if(!a.directives)return``;let o=[],s=(n.isScalar(e)||n.isCollection(e))&&e.anchor;s&&t.anchorIsValid(s)&&(i.add(s),o.push(`&${s}`));let c=e.tag??(r.default?null:r.tag);return c&&o.push(a.directives.tagString(c)),o.join(` `)}function c(e,t,r,a){if(n.isPair(e))return e.toString(t,r,a);if(n.isAlias(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=/* @__PURE__ */ new Set([e]),e=e.resolve(t.doc)}let c,l=n.isNode(e)?e:t.doc.createNode(e,{onTagObj:e=>c=e});c??=o(t.doc.schema.tags,l);let u=s(l,c,t);u.length>0&&(t.indentAtStart=(t.indentAtStart??0)+u.length+1);let d=typeof c.stringify==`function`?c.stringify(l,t,r,a):n.isScalar(l)?i.stringifyString(l,t,r,a):l.toString(t,r,a);return u?n.isScalar(l)||d[0]===`{`||d[0]===`[`?`${u} ${d}`:`${u}\n${t.indent}${d}`:d}e.createStringifyContext=a,e.stringify=c})),SS=/* @__PURE__ */ D((e=>{var t=$(),n=hS(),r=xS(),i=vS();function a({key:e,value:a},o,s,c){let{allNullValues:l,doc:u,indent:d,indentStep:f,options:{commentString:p,indentSeq:m,simpleKeys:h}}=o,g=t.isNode(e)&&e.comment||null;if(h){if(g)throw Error(`With simple keys, key nodes cannot have comments`);if(t.isCollection(e)||!t.isNode(e)&&typeof e==`object`)throw Error(`With simple keys, collection cannot be used as a key value`)}let _=!h&&(!e||g&&a==null&&!o.inFlow||t.isCollection(e)||(t.isScalar(e)?e.type===n.Scalar.BLOCK_FOLDED||e.type===n.Scalar.BLOCK_LITERAL:typeof e==`object`));o=Object.assign({},o,{allNullValues:!1,implicitKey:!_&&(h||!l),indent:d+f});let v=!1,y=!1,b=r.stringify(e,o,()=>v=!0,()=>y=!0);if(!_&&!o.inFlow&&b.length>1024){if(h)throw Error(`With simple keys, single line scalar must not span more than 1024 characters`);_=!0}if(o.inFlow){if(l||a==null)return v&&s&&s(),b===``?`?`:_?`? ${b}`:b}else if(l&&!h||a==null&&_)return b=`? ${b}`,g&&!v?b+=i.lineComment(b,o.indent,p(g)):y&&c&&c(),b;v&&(g=null),_?(g&&(b+=i.lineComment(b,o.indent,p(g))),b=`? ${b}\n${d}:`):(b=`${b}:`,g&&(b+=i.lineComment(b,o.indent,p(g))));let x,S,C;t.isNode(a)?(x=!!a.spaceBefore,S=a.commentBefore,C=a.comment):(x=!1,S=null,C=null,a&&typeof a==`object`&&(a=u.createNode(a))),o.implicitKey=!1,!_&&!g&&t.isScalar(a)&&(o.indentAtStart=b.length+1),y=!1,!m&&f.length>=2&&!o.inFlow&&!_&&t.isSeq(a)&&!a.flow&&!a.tag&&!a.anchor&&(o.indent=o.indent.substring(2));let w=!1,T=r.stringify(a,o,()=>w=!0,()=>y=!0),E=` `;if(g||x||S){if(E=x?`
228
+ `:``,S){let e=p(S);E+=`\n${i.indentComment(e,o.indent)}`}T===``&&!o.inFlow?E===`
229
+ `&&C&&(E=`
230
+
231
+ `):E+=`\n${o.indent}`}else if(!_&&t.isCollection(a)){let e=T[0],t=T.indexOf(`
232
+ `),n=t!==-1,r=o.inFlow??a.flow??a.items.length===0;if(n||!r){let r=!1;if(n&&(e===`&`||e===`!`)){let n=T.indexOf(` `);e===`&`&&n!==-1&&n<t&&T[n+1]===`!`&&(n=T.indexOf(` `,n+1)),(n===-1||t<n)&&(r=!0)}r||(E=`\n${o.indent}`)}}else(T===``||T[0]===`
233
+ `)&&(E=``);return b+=E+T,o.inFlow?w&&s&&s():C&&!w?b+=i.lineComment(b,o.indent,p(C)):y&&c&&c(),b}e.stringifyPair=a})),CS=/* @__PURE__ */ D((e=>{var t=de(`process`);function n(e,...t){e===`debug`&&console.log(...t)}function r(e,n){(e===`debug`||e===`warn`)&&(typeof t.emitWarning==`function`?t.emitWarning(n):console.warn(n))}e.debug=n,e.warn=r})),wS=/* @__PURE__ */ D((e=>{var t=$(),n=hS();let r={identify:e=>e===`<<`||typeof e==`symbol`&&e.description===`<<`,default:`key`,tag:`tag:yaml.org,2002:merge`,test:/^<<$/,resolve:()=>Object.assign(new n.Scalar(Symbol(`<<`)),{addToJSMap:a}),stringify:()=>`<<`},i=(e,i)=>(r.identify(i)||t.isScalar(i)&&(!i.type||i.type===n.Scalar.PLAIN)&&r.identify(i.value))&&e?.doc.schema.tags.some(e=>e.tag===r.tag&&e.default);function a(e,n,r){let i=s(e,r);if(t.isSeq(i))for(let t of i.items)o(e,n,t);else if(Array.isArray(i))for(let t of i)o(e,n,t);else o(e,n,i)}function o(e,n,r){let i=s(e,r);if(!t.isMap(i))throw Error(`Merge sources must be maps or map aliases`);let a=i.toJSON(null,e,Map);for(let[e,t]of a)n instanceof Map?n.has(e)||n.set(e,t):n instanceof Set?n.add(e):Object.prototype.hasOwnProperty.call(n,e)||Object.defineProperty(n,e,{value:t,writable:!0,enumerable:!0,configurable:!0});return n}function s(e,n){return e&&t.isAlias(n)?n.resolve(e.doc,e):n}e.addMergeToJSMap=a,e.isMergeKey=i,e.merge=r})),TS=/* @__PURE__ */ D((e=>{var t=CS(),n=wS(),r=xS(),i=$(),a=fS();function o(e,t,{key:r,value:o}){if(i.isNode(r)&&r.addToJSMap)r.addToJSMap(e,t,o);else if(n.isMergeKey(e,r))n.addMergeToJSMap(e,t,o);else{let n=a.toJS(r,``,e);if(t instanceof Map)t.set(n,a.toJS(o,n,e));else if(t instanceof Set)t.add(n);else{let i=s(r,n,e),c=a.toJS(o,i,e);i in t?Object.defineProperty(t,i,{value:c,writable:!0,enumerable:!0,configurable:!0}):t[i]=c}}return t}function s(e,n,a){if(n===null)return``;if(typeof n!=`object`)return String(n);if(i.isNode(e)&&a?.doc){let n=r.createStringifyContext(a.doc,{});n.anchors=/* @__PURE__ */ new Set;for(let e of a.anchors.keys())n.anchors.add(e.anchor);n.inFlow=!0,n.inStringifyKey=!0;let i=e.toString(n);if(!a.mapKeyWarned){let e=JSON.stringify(i);e.length>40&&(e=e.substring(0,36)+`..."`),t.warn(a.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${e}. Set mapAsMap: true to use object keys.`),a.mapKeyWarned=!0}return i}return JSON.stringify(n)}e.addPairToJSMap=o})),ES=/* @__PURE__ */ D((e=>{var t=gS(),n=SS(),r=TS(),i=$();function a(e,n,r){return new o(t.createNode(e,void 0,r),t.createNode(n,void 0,r))}var o=class e{constructor(e,t=null){Object.defineProperty(this,i.NODE_TYPE,{value:i.PAIR}),this.key=e,this.value=t}clone(t){let{key:n,value:r}=this;return i.isNode(n)&&(n=n.clone(t)),i.isNode(r)&&(r=r.clone(t)),new e(n,r)}toJSON(e,t){let n=t?.mapAsMap?/* @__PURE__ */ new Map:{};return r.addPairToJSMap(t,n,this)}toString(e,t,r){return e?.doc?n.stringifyPair(this,e,t,r):JSON.stringify(this)}};e.Pair=o,e.createPair=a})),DS=/* @__PURE__ */ D((e=>{var t=$(),n=xS(),r=vS();function i(e,t,n){return(t.inFlow??e.flow?o:a)(e,t,n)}function a({comment:e,items:i},a,{blockItemPrefix:o,flowChars:c,itemIndent:l,onChompKeep:u,onComment:d}){let{indent:f,options:{commentString:p}}=a,m=Object.assign({},a,{indent:l,type:null}),h=!1,g=[];for(let e=0;e<i.length;++e){let c=i[e],u=null;if(t.isNode(c))!h&&c.spaceBefore&&g.push(``),s(a,g,c.commentBefore,h),c.comment&&(u=c.comment);else if(t.isPair(c)){let e=t.isNode(c.key)?c.key:null;e&&(!h&&e.spaceBefore&&g.push(``),s(a,g,e.commentBefore,h))}h=!1;let d=n.stringify(c,m,()=>u=null,()=>h=!0);u&&(d+=r.lineComment(d,l,p(u))),h&&u&&(h=!1),g.push(o+d)}let _;if(g.length===0)_=c.start+c.end;else{_=g[0];for(let e=1;e<g.length;++e){let t=g[e];_+=t?`\n${f}${t}`:`
234
+ `}}return e?(_+=`
235
+ `+r.indentComment(p(e),f),d&&d()):h&&u&&u(),_}function o({items:e},i,{flowChars:a,itemIndent:o}){let{indent:c,indentStep:l,flowCollectionPadding:u,options:{commentString:d}}=i;o+=l;let f=Object.assign({},i,{indent:o,inFlow:!0,type:null}),p=!1,m=0,h=[];for(let a=0;a<e.length;++a){let c=e[a],l=null;if(t.isNode(c))c.spaceBefore&&h.push(``),s(i,h,c.commentBefore,!1),c.comment&&(l=c.comment);else if(t.isPair(c)){let e=t.isNode(c.key)?c.key:null;e&&(e.spaceBefore&&h.push(``),s(i,h,e.commentBefore,!1),e.comment&&(p=!0));let n=t.isNode(c.value)?c.value:null;n?(n.comment&&(l=n.comment),n.commentBefore&&(p=!0)):c.value==null&&e?.comment&&(l=e.comment)}l&&(p=!0);let u=n.stringify(c,f,()=>l=null);p||=h.length>m||u.includes(`
236
+ `),a<e.length-1?u+=`,`:i.options.trailingComma&&(i.options.lineWidth>0&&(p||=h.reduce((e,t)=>e+t.length+2,2)+(u.length+2)>i.options.lineWidth),p&&(u+=`,`)),l&&(u+=r.lineComment(u,o,d(l))),h.push(u),m=h.length}let{start:g,end:_}=a;if(h.length===0)return g+_;if(!p){let e=h.reduce((e,t)=>e+t.length+2,2);p=i.options.lineWidth>0&&e>i.options.lineWidth}if(p){let e=g;for(let t of h)e+=t?`\n${l}${c}${t}`:`
237
+ `;return`${e}\n${c}${_}`}return`${g}${u}${h.join(` `)}${u}${_}`}function s({indent:e,options:{commentString:t}},n,i,a){if(i&&a&&(i=i.replace(/^\n+/,``)),i){let a=r.indentComment(t(i),e);n.push(a.trimStart())}}e.stringifyCollection=i})),OS=/* @__PURE__ */ D((e=>{var t=DS(),n=TS(),r=_S(),i=$(),a=ES(),o=hS();function s(e,t){let n=i.isScalar(t)?t.value:t;for(let r of e)if(i.isPair(r)&&(r.key===t||r.key===n||i.isScalar(r.key)&&r.key.value===n))return r}e.YAMLMap=class extends r.Collection{static get tagName(){return`tag:yaml.org,2002:map`}constructor(e){super(i.MAP,e),this.items=[]}static from(e,t,n){let{keepUndefined:r,replacer:i}=n,o=new this(e),s=(e,s)=>{if(typeof i==`function`)s=i.call(t,e,s);else if(Array.isArray(i)&&!i.includes(e))return;(s!==void 0||r)&&o.items.push(a.createPair(e,s,n))};if(t instanceof Map)for(let[e,n]of t)s(e,n);else if(t&&typeof t==`object`)for(let e of Object.keys(t))s(e,t[e]);return typeof e.sortMapEntries==`function`&&o.items.sort(e.sortMapEntries),o}add(e,t){let n;n=i.isPair(e)?e:!e||typeof e!=`object`||!(`key`in e)?new a.Pair(e,e?.value):new a.Pair(e.key,e.value);let r=s(this.items,n.key),c=this.schema?.sortMapEntries;if(r){if(!t)throw Error(`Key ${n.key} already set`);i.isScalar(r.value)&&o.isScalarValue(n.value)?r.value.value=n.value:r.value=n.value}else if(c){let e=this.items.findIndex(e=>c(n,e)<0);e===-1?this.items.push(n):this.items.splice(e,0,n)}else this.items.push(n)}delete(e){let t=s(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let n=s(this.items,e)?.value;return(!t&&i.isScalar(n)?n.value:n)??void 0}has(e){return!!s(this.items,e)}set(e,t){this.add(new a.Pair(e,t),!0)}toJSON(e,t,r){let i=r?new r:t?.mapAsMap?/* @__PURE__ */ new Map:{};t?.onCreate&&t.onCreate(i);for(let e of this.items)n.addPairToJSMap(t,i,e);return i}toString(e,n,r){if(!e)return JSON.stringify(this);for(let e of this.items)if(!i.isPair(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})),t.stringifyCollection(this,e,{blockItemPrefix:``,flowChars:{start:`{`,end:`}`},itemIndent:e.indent||``,onChompKeep:r,onComment:n})}},e.findPair=s})),kS=/* @__PURE__ */ D((e=>{var t=$(),n=OS();e.map={collection:`map`,default:!0,nodeClass:n.YAMLMap,tag:`tag:yaml.org,2002:map`,resolve(e,n){return t.isMap(e)||n(`Expected a mapping for this tag`),e},createNode:(e,t,r)=>n.YAMLMap.from(e,t,r)}})),AS=/* @__PURE__ */ D((e=>{var t=gS(),n=DS(),r=_S(),i=$(),a=hS(),o=fS(),s=class extends r.Collection{static get tagName(){return`tag:yaml.org,2002:seq`}constructor(e){super(i.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=c(e);return typeof t==`number`&&this.items.splice(t,1).length>0}get(e,t){let n=c(e);if(typeof n!=`number`)return;let r=this.items[n];return!t&&i.isScalar(r)?r.value:r}has(e){let t=c(e);return typeof t==`number`&&t<this.items.length}set(e,t){let n=c(e);if(typeof n!=`number`)throw Error(`Expected a valid index, not ${e}.`);let r=this.items[n];i.isScalar(r)&&a.isScalarValue(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(o.toJS(e,String(r++),t));return n}toString(e,t,r){return e?n.stringifyCollection(this,e,{blockItemPrefix:`- `,flowChars:{start:`[`,end:`]`},itemIndent:(e.indent||``)+` `,onChompKeep:r,onComment:t}):JSON.stringify(this)}static from(e,n,r){let{replacer:i}=r,a=new this(e);if(n&&Symbol.iterator in Object(n)){let e=0;for(let o of n){if(typeof i==`function`){let t=n instanceof Set?o:String(e++);o=i.call(n,t,o)}a.items.push(t.createNode(o,void 0,r))}}return a}};function c(e){let t=i.isScalar(e)?e.value:e;return t&&typeof t==`string`&&(t=Number(t)),typeof t==`number`&&Number.isInteger(t)&&t>=0?t:null}e.YAMLSeq=s})),jS=/* @__PURE__ */ D((e=>{var t=$(),n=AS();e.seq={collection:`seq`,default:!0,nodeClass:n.YAMLSeq,tag:`tag:yaml.org,2002:seq`,resolve(e,n){return t.isSeq(e)||n(`Expected a sequence for this tag`),e},createNode:(e,t,r)=>n.YAMLSeq.from(e,t,r)}})),MS=/* @__PURE__ */ D((e=>{var t=bS();e.string={identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify(e,n,r,i){return n=Object.assign({actualString:!0},n),t.stringifyString(e,n,r,i)}}})),NS=/* @__PURE__ */ D((e=>{var t=hS();let n={identify:e=>e==null,createNode:()=>new t.Scalar(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new t.Scalar(null),stringify:({source:e},t)=>typeof e==`string`&&n.test.test(e)?e:t.options.nullStr};e.nullTag=n})),PS=/* @__PURE__ */ D((e=>{var t=hS();let n={identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:e=>new t.Scalar(e[0]===`t`||e[0]===`T`),stringify({source:e,value:t},r){return e&&n.test.test(e)&&t===(e[0]===`t`||e[0]===`T`)?e:t?r.options.trueStr:r.options.falseStr}};e.boolTag=n})),FS=/* @__PURE__ */ D((e=>{function t({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}e.stringifyNumber=t})),IS=/* @__PURE__ */ D((e=>{var t=hS(),n=FS();let r={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:n.stringifyNumber};e.float={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(e){let n=new t.Scalar(parseFloat(e)),r=e.indexOf(`.`);return r!==-1&&e[e.length-1]===`0`&&(n.minFractionDigits=e.length-r-1),n},stringify:n.stringifyNumber},e.floatExp={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():n.stringifyNumber(e)}},e.floatNaN=r})),LS=/* @__PURE__ */ D((e=>{var t=FS();let n=e=>typeof e==`bigint`||Number.isInteger(e),r=(e,t,n,{intAsBigInt:r})=>r?BigInt(e):parseInt(e.substring(t),n);function i(e,r,i){let{value:a}=e;return n(a)&&a>=0?i+a.toString(r):t.stringifyNumber(e)}e.int={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9]+$/,resolve:(e,t,n)=>r(e,0,10,n),stringify:t.stringifyNumber},e.intHex={identify:e=>n(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^0x[0-9a-fA-F]+$/,resolve:(e,t,n)=>r(e,2,16,n),stringify:e=>i(e,16,`0x`)},e.intOct={identify:e=>n(e)&&e>=0,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^0o[0-7]+$/,resolve:(e,t,n)=>r(e,2,8,n),stringify:e=>i(e,8,`0o`)}})),RS=/* @__PURE__ */ D((e=>{var t=kS(),n=NS(),r=jS(),i=MS(),a=PS(),o=IS(),s=LS();e.schema=[t.map,r.seq,i.string,n.nullTag,a.boolTag,s.intOct,s.int,s.intHex,o.floatNaN,o.floatExp,o.float]})),zS=/* @__PURE__ */ D((e=>{var t=hS(),n=kS(),r=jS();function i(e){return typeof e==`bigint`||Number.isInteger(e)}let a=({value:e})=>JSON.stringify(e),o=[{identify:e=>typeof e==`string`,default:!0,tag:`tag:yaml.org,2002:str`,resolve:e=>e,stringify:a},{identify:e=>e==null,createNode:()=>new t.Scalar(null),default:!0,tag:`tag:yaml.org,2002:null`,test:/^null$/,resolve:()=>null,stringify:a},{identify:e=>typeof e==`boolean`,default:!0,tag:`tag:yaml.org,2002:bool`,test:/^true$|^false$/,resolve:e=>e===`true`,stringify:a},{identify:i,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})=>i(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:a}];e.schema=[n.map,r.seq].concat(o,{default:!0,tag:``,test:/^/,resolve(e,t){return t(`Unresolved plain scalar ${JSON.stringify(e)}`),e}})})),BS=/* @__PURE__ */ D((e=>{var t=de(`buffer`),n=hS(),r=bS();e.binary={identify:e=>e instanceof Uint8Array,default:!1,tag:`tag:yaml.org,2002:binary`,resolve(e,n){if(typeof t.Buffer==`function`)return t.Buffer.from(e,`base64`);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 n(`This environment does not support reading binary tags; either Buffer or atob is required`),e},stringify({comment:e,type:i,value:a},o,s,c){if(!a)return``;let l=a,u;if(typeof t.Buffer==`function`)u=l instanceof t.Buffer?l.toString(`base64`):t.Buffer.from(l.buffer).toString(`base64`);else if(typeof btoa==`function`){let e=``;for(let t=0;t<l.length;++t)e+=String.fromCharCode(l[t]);u=btoa(e)}else throw Error(`This environment does not support writing binary tags; either Buffer or btoa is required`);if(i??=n.Scalar.BLOCK_LITERAL,i!==n.Scalar.QUOTE_DOUBLE){let e=Math.max(o.options.lineWidth-o.indent.length,o.options.minContentWidth),t=Math.ceil(u.length/e),r=Array(t);for(let n=0,i=0;n<t;++n,i+=e)r[n]=u.substr(i,e);u=r.join(i===n.Scalar.BLOCK_LITERAL?`
238
+ `:` `)}return r.stringifyString({comment:e,type:i,value:u},o,s,c)}}})),VS=/* @__PURE__ */ D((e=>{var t=$(),n=ES(),r=hS(),i=AS();function a(e,i){if(t.isSeq(e))for(let a=0;a<e.items.length;++a){let o=e.items[a];if(!t.isPair(o)){if(t.isMap(o)){o.items.length>1&&i(`Each pair must have its own sequence indicator`);let e=o.items[0]||new n.Pair(new r.Scalar(null));if(o.commentBefore&&(e.key.commentBefore=e.key.commentBefore?`${o.commentBefore}\n${e.key.commentBefore}`:o.commentBefore),o.comment){let t=e.value??e.key;t.comment=t.comment?`${o.comment}\n${t.comment}`:o.comment}o=e}e.items[a]=t.isPair(o)?o:new n.Pair(o)}}else i(`Expected a sequence for this tag`);return e}function o(e,t,r){let{replacer:a}=r,o=new i.YAMLSeq(e);o.tag=`tag:yaml.org,2002:pairs`;let s=0;if(t&&Symbol.iterator in Object(t))for(let e of t){typeof a==`function`&&(e=a.call(t,String(s++),e));let i,c;if(Array.isArray(e)){if(e.length===2)i=e[0],c=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)i=t[0],c=e[i];else throw TypeError(`Expected tuple with one key, not ${t.length} keys`)}else i=e;o.items.push(n.createPair(i,c,r))}return o}let s={collection:`seq`,default:!1,tag:`tag:yaml.org,2002:pairs`,resolve:a,createNode:o};e.createPairs=o,e.pairs=s,e.resolvePairs=a})),HS=/* @__PURE__ */ D((e=>{var t=$(),n=fS(),r=OS(),i=AS(),a=VS(),o=class e extends i.YAMLSeq{constructor(){super(),this.add=r.YAMLMap.prototype.add.bind(this),this.delete=r.YAMLMap.prototype.delete.bind(this),this.get=r.YAMLMap.prototype.get.bind(this),this.has=r.YAMLMap.prototype.has.bind(this),this.set=r.YAMLMap.prototype.set.bind(this),this.tag=e.tag}toJSON(e,r){if(!r)return super.toJSON(e);let i=/* @__PURE__ */ new Map;r?.onCreate&&r.onCreate(i);for(let e of this.items){let a,o;if(t.isPair(e)?(a=n.toJS(e.key,``,r),o=n.toJS(e.value,a,r)):a=n.toJS(e,``,r),i.has(a))throw Error(`Ordered maps must not include duplicate keys`);i.set(a,o)}return i}static from(e,t,n){let r=a.createPairs(e,t,n),i=new this;return i.items=r.items,i}};o.tag=`tag:yaml.org,2002:omap`;let s={collection:`seq`,identify:e=>e instanceof Map,nodeClass:o,default:!1,tag:`tag:yaml.org,2002:omap`,resolve(e,n){let r=a.resolvePairs(e,n),i=[];for(let{key:e}of r.items)t.isScalar(e)&&(i.includes(e.value)?n(`Ordered maps must not include duplicate keys: ${e.value}`):i.push(e.value));return Object.assign(new o,r)},createNode:(e,t,n)=>o.from(e,t,n)};e.YAMLOMap=o,e.omap=s})),US=/* @__PURE__ */ D((e=>{var t=hS();function n({value:e,source:t},n){return t&&(e?r:i).test.test(t)?t:e?n.options.trueStr:n.options.falseStr}let r={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 t.Scalar(!0),stringify:n},i={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 t.Scalar(!1),stringify:n};e.falseTag=i,e.trueTag=r})),WS=/* @__PURE__ */ D((e=>{var t=hS(),n=FS();let r={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:n.stringifyNumber};e.float={identify:e=>typeof e==`number`,default:!0,tag:`tag:yaml.org,2002:float`,test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(e){let n=new t.Scalar(parseFloat(e.replace(/_/g,``))),r=e.indexOf(`.`);if(r!==-1){let t=e.substring(r+1).replace(/_/g,``);t[t.length-1]===`0`&&(n.minFractionDigits=t.length)}return n},stringify:n.stringifyNumber},e.floatExp={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():n.stringifyNumber(e)}},e.floatNaN=r})),GS=/* @__PURE__ */ D((e=>{var t=FS();let n=e=>typeof e==`bigint`||Number.isInteger(e);function r(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 i(e,r,i){let{value:a}=e;if(n(a)){let e=a.toString(r);return a<0?`-`+i+e.substr(1):i+e}return t.stringifyNumber(e)}let a={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,format:`BIN`,test:/^[-+]?0b[0-1_]+$/,resolve:(e,t,n)=>r(e,2,2,n),stringify:e=>i(e,2,`0b`)},o={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,format:`OCT`,test:/^[-+]?0[0-7_]+$/,resolve:(e,t,n)=>r(e,1,8,n),stringify:e=>i(e,8,`0`)},s={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,test:/^[-+]?[0-9][0-9_]*$/,resolve:(e,t,n)=>r(e,0,10,n),stringify:t.stringifyNumber},c={identify:n,default:!0,tag:`tag:yaml.org,2002:int`,format:`HEX`,test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(e,t,n)=>r(e,2,16,n),stringify:e=>i(e,16,`0x`)};e.int=s,e.intBin=a,e.intHex=c,e.intOct=o})),KS=/* @__PURE__ */ D((e=>{var t=$(),n=ES(),r=OS(),i=class e extends r.YAMLMap{constructor(t){super(t),this.tag=e.tag}add(e){let i;i=t.isPair(e)?e:e&&typeof e==`object`&&`key`in e&&`value`in e&&e.value===null?new n.Pair(e.key,null):new n.Pair(e,null),r.findPair(this.items,i.key)||this.items.push(i)}get(e,n){let i=r.findPair(this.items,e);return!n&&t.isPair(i)?t.isScalar(i.key)?i.key.value:i.key:i}set(e,t){if(typeof t!=`boolean`)throw Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let i=r.findPair(this.items,e);i&&!t?this.items.splice(this.items.indexOf(i),1):!i&&t&&this.items.push(new n.Pair(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,r){let{replacer:i}=r,a=new this(e);if(t&&Symbol.iterator in Object(t))for(let e of t)typeof i==`function`&&(e=i.call(t,e,e)),a.items.push(n.createPair(e,null,r));return a}};i.tag=`tag:yaml.org,2002:set`;let a={collection:`map`,identify:e=>e instanceof Set,nodeClass:i,default:!1,tag:`tag:yaml.org,2002:set`,createNode:(e,t,n)=>i.from(e,t,n),resolve(e,n){if(t.isMap(e)){if(e.hasAllNullValues(!0))return Object.assign(new i,e);n(`Set items must all have null values`)}else n(`Expected a mapping for this tag`);return e}};e.YAMLSet=i,e.set=a})),qS=/* @__PURE__ */ D((e=>{var t=FS();function n(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 r(e){let{value:n}=e,r=e=>e;if(typeof n==`bigint`)r=e=>BigInt(e);else if(isNaN(n)||!isFinite(n))return t.stringifyNumber(e);let i=``;n<0&&(i=`-`,n*=r(-1));let a=r(60),o=[n%a];return n<60?o.unshift(0):(n=(n-o[0])/a,o.unshift(n%a),n>=60&&(n=(n-o[0])/a,o.unshift(n))),i+o.map(e=>String(e).padStart(2,`0`)).join(`:`).replace(/000000\d*$/,``)}let i={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:r})=>n(e,r),stringify:r},a={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=>n(e,!1),stringify:r},o={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(o.test);if(!t)throw Error(`!!timestamp expects a date, starting with yyyy-mm-dd`);let[,r,i,a,s,c,l]=t.map(Number),u=t[7]?Number((t[7]+`00`).substr(1,3)):0,d=Date.UTC(r,i-1,a,s||0,c||0,l||0,u),f=t[8];if(f&&f!==`Z`){let e=n(f,!1);Math.abs(e)<30&&(e*=60),d-=6e4*e}return new Date(d)},stringify:({value:e})=>e?.toISOString().replace(/(T00:00:00)?\.000Z$/,``)??``};e.floatTime=a,e.intTime=i,e.timestamp=o})),JS=/* @__PURE__ */ D((e=>{var t=kS(),n=NS(),r=jS(),i=MS(),a=BS(),o=US(),s=WS(),c=GS(),l=wS(),u=HS(),d=VS(),f=KS(),p=qS();e.schema=[t.map,r.seq,i.string,n.nullTag,o.trueTag,o.falseTag,c.intBin,c.intOct,c.int,c.intHex,s.floatNaN,s.floatExp,s.float,a.binary,l.merge,u.omap,d.pairs,f.set,p.intTime,p.floatTime,p.timestamp]})),YS=/* @__PURE__ */ D((e=>{var t=kS(),n=NS(),r=jS(),i=MS(),a=PS(),o=IS(),s=LS(),c=RS(),l=zS(),u=BS(),d=wS(),f=HS(),p=VS(),m=JS(),h=KS(),g=qS();let _=/* @__PURE__ */ new Map([[`core`,c.schema],[`failsafe`,[t.map,r.seq,i.string]],[`json`,l.schema],[`yaml11`,m.schema],[`yaml-1.1`,m.schema]]),v={binary:u.binary,bool:a.boolTag,float:o.float,floatExp:o.floatExp,floatNaN:o.floatNaN,floatTime:g.floatTime,int:s.int,intHex:s.intHex,intOct:s.intOct,intTime:g.intTime,map:t.map,merge:d.merge,null:n.nullTag,omap:f.omap,pairs:p.pairs,seq:r.seq,set:h.set,timestamp:g.timestamp},y={"tag:yaml.org,2002:binary":u.binary,"tag:yaml.org,2002:merge":d.merge,"tag:yaml.org,2002:omap":f.omap,"tag:yaml.org,2002:pairs":p.pairs,"tag:yaml.org,2002:set":h.set,"tag:yaml.org,2002:timestamp":g.timestamp};function b(e,t,n){let r=_.get(t);if(r&&!e)return n&&!r.includes(d.merge)?r.concat(d.merge):r.slice();let i=r;if(!i){if(Array.isArray(e))i=[];else{let e=Array.from(_.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(d.merge)),i.reduce((e,t)=>{let n=typeof t==`string`?v[t]:t;if(!n){let e=JSON.stringify(t),n=Object.keys(v).map(e=>JSON.stringify(e)).join(`, `);throw Error(`Unknown custom tag ${e}; use one of ${n}`)}return e.includes(n)||e.push(n),e},[])}e.coreKnownTags=y,e.getTags=b})),XS=/* @__PURE__ */ D((e=>{var t=$(),n=kS(),r=jS(),i=MS(),a=YS();let o=(e,t)=>e.key<t.key?-1:+(e.key>t.key);e.Schema=class e{constructor({compat:e,customTags:s,merge:c,resolveKnownTags:l,schema:u,sortMapEntries:d,toStringDefaults:f}){this.compat=Array.isArray(e)?a.getTags(e,`compat`):e?a.getTags(null,e):null,this.name=typeof u==`string`&&u||`core`,this.knownTags=l?a.coreKnownTags:{},this.tags=a.getTags(s,this.name,c),this.toStringOptions=f??null,Object.defineProperty(this,t.MAP,{value:n.map}),Object.defineProperty(this,t.SCALAR,{value:i.string}),Object.defineProperty(this,t.SEQ,{value:r.seq}),this.sortMapEntries=typeof d==`function`?d:d===!0?o:null}clone(){let t=Object.create(e.prototype,Object.getOwnPropertyDescriptors(this));return t.tags=this.tags.slice(),t}}})),ZS=/* @__PURE__ */ D((e=>{var t=$(),n=xS(),r=vS();function i(e,i){let a=[],o=i.directives===!0;if(i.directives!==!1&&e.directives){let t=e.directives.toString(e);t?(a.push(t),o=!0):e.directives.docStart&&(o=!0)}o&&a.push(`---`);let s=n.createStringifyContext(e,i),{commentString:c}=s.options;if(e.commentBefore){a.length!==1&&a.unshift(``);let t=c(e.commentBefore);a.unshift(r.indentComment(t,``))}let l=!1,u=null;if(e.contents){if(t.isNode(e.contents)){if(e.contents.spaceBefore&&o&&a.push(``),e.contents.commentBefore){let t=c(e.contents.commentBefore);a.push(r.indentComment(t,``))}s.forceBlockIndent=!!e.comment,u=e.contents.comment}let i=u?void 0:()=>l=!0,d=n.stringify(e.contents,s,()=>u=null,i);u&&(d+=r.lineComment(d,``,c(u))),(d[0]===`|`||d[0]===`>`)&&a[a.length-1]===`---`?a[a.length-1]=`--- ${d}`:a.push(d)}else a.push(n.stringify(e.contents,s));if(e.directives?.docEnd){if(e.comment){let t=c(e.comment);t.includes(`
239
+ `)?(a.push(`...`),a.push(r.indentComment(t,``))):a.push(`... ${t}`)}else a.push(`...`)}else{let t=e.comment;t&&l&&(t=t.replace(/^\n+/,``)),t&&((!l||u)&&a[a.length-1]!==``&&a.push(``),a.push(r.indentComment(c(t),``)))}return a.join(`
240
+ `)+`
241
+ `}e.stringifyDocument=i})),QS=/* @__PURE__ */ D((e=>{var t=mS(),n=_S(),r=$(),i=ES(),a=fS(),o=XS(),s=ZS(),c=uS(),l=dS(),u=gS(),d=lS(),f=class e{constructor(e,t,n){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,r.NODE_TYPE,{value:r.DOC});let i=null;typeof t==`function`||Array.isArray(t)?i=t:n===void 0&&t&&(n=t,t=void 0);let a=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:`warn`,prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:`1.2`},n);this.options=a;let{version:o}=a;n?._directives?(this.directives=n._directives.atDocument(),this.directives.yaml.explicit&&(o=this.directives.yaml.version)):this.directives=new d.Directives({version:o}),this.setSchema(o,n),this.contents=e===void 0?null:this.createNode(e,i,n)}clone(){let t=Object.create(e.prototype,{[r.NODE_TYPE]:{value:r.DOC}});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=r.isNode(this.contents)?this.contents.clone(t.schema):this.contents,this.range&&(t.range=this.range.slice()),t}add(e){p(this.contents)&&this.contents.add(e)}addIn(e,t){p(this.contents)&&this.contents.addIn(e,t)}createAlias(e,n){if(!e.anchor){let t=c.anchorNames(this);e.anchor=!n||t.has(n)?c.findNewAnchor(n||`a`,t):n}return new t.Alias(e.anchor)}createNode(e,t,n){let i;if(typeof t==`function`)e=t.call({"":e},``,e),i=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)),i=t}else n===void 0&&t&&(n=t,t=void 0);let{aliasDuplicateObjects:a,anchorPrefix:o,flow:s,keepUndefined:l,onTagObj:d,tag:f}=n??{},{onAnchor:p,setAnchors:m,sourceObjects:h}=c.createNodeAnchors(this,o||`a`),g={aliasDuplicateObjects:a??!0,keepUndefined:l??!1,onAnchor:p,onTagObj:d,replacer:i,schema:this.schema,sourceObjects:h},_=u.createNode(e,f,g);return s&&r.isCollection(_)&&(_.flow=!0),m(),_}createPair(e,t,n={}){let r=this.createNode(e,null,n),a=this.createNode(t,null,n);return new i.Pair(r,a)}delete(e){return p(this.contents)?this.contents.delete(e):!1}deleteIn(e){return n.isEmptyPath(e)?this.contents!=null&&(this.contents=null,!0):p(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return r.isCollection(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return n.isEmptyPath(e)?!t&&r.isScalar(this.contents)?this.contents.value:this.contents:r.isCollection(this.contents)?this.contents.getIn(e,t):void 0}has(e){return r.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return n.isEmptyPath(e)?this.contents!==void 0:r.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=n.collectionFromPath(this.schema,[e],t):p(this.contents)&&this.contents.set(e,t)}setIn(e,t){n.isEmptyPath(e)?this.contents=t:this.contents==null?this.contents=n.collectionFromPath(this.schema,Array.from(e),t):p(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 d.Directives({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 d.Directives({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 o.Schema(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:o}={}){let s={anchors:/* @__PURE__ */ new Map,doc:this,keep:!e,mapAsMap:n===!0,mapKeyWarned:!1,maxAliasCount:typeof r==`number`?r:100},c=a.toJS(this.contents,t??``,s);if(typeof i==`function`)for(let{count:e,res:t}of s.anchors.values())i(t,e);return typeof o==`function`?l.applyReviver(o,{"":c},``,c):c}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 s.stringifyDocument(this,e)}};function p(e){if(r.isCollection(e))return!0;throw Error(`Expected a YAML collection as document contents`)}e.Document=f})),$S=/* @__PURE__ */ D((e=>{var t=class extends Error{constructor(e,t,n,r){super(),this.name=e,this.code=n,this.message=r,this.pos=t}},n=class extends t{constructor(e,t,n){super(`YAMLParseError`,e,t,n)}},r=class extends t{constructor(e,t,n){super(`YAMLWarning`,e,t,n)}};e.YAMLError=t,e.YAMLParseError=n,e.YAMLWarning=r,e.prettifyError=(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)+`…
242
+ `),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`}}})),eC=/* @__PURE__ */ D((e=>{function t(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}}e.resolveProps=t})),tC=/* @__PURE__ */ D((e=>{function t(e){if(!e)return null;switch(e.type){case`alias`:case`scalar`:case`double-quoted-scalar`:case`single-quoted-scalar`:if(e.source.includes(`
243
+ `))return!0;if(e.end){for(let t of e.end)if(t.type===`newline`)return!0}return!1;case`flow-collection`:for(let n of e.items){for(let e of n.start)if(e.type===`newline`)return!0;if(n.sep){for(let e of n.sep)if(e.type===`newline`)return!0}if(t(n.key)||t(n.value))return!0}return!1;default:return!0}}e.containsNewline=t})),nC=/* @__PURE__ */ D((e=>{var t=tC();function n(e,n,r){if(n?.type===`flow-collection`){let i=n.end[0];i.indent===e&&(i.source===`]`||i.source===`}`)&&t.containsNewline(n)&&r(i,`BAD_INDENT`,`Flow end indicator should be more indented than parent`,!0)}}e.flowIndentCheck=n})),rC=/* @__PURE__ */ D((e=>{var t=$();function n(e,n,r){let{uniqueKeys:i}=e.options;if(i===!1)return!1;let a=typeof i==`function`?i:(e,n)=>e===n||t.isScalar(e)&&t.isScalar(n)&&e.value===n.value;return n.some(e=>a(e.key,r))}e.mapIncludes=n})),iC=/* @__PURE__ */ D((e=>{var t=ES(),n=OS(),r=eC(),i=tC(),a=nC(),o=rC();let s=`All mapping items must start at the same column`;function c({composeNode:e,composeEmptyNode:c},l,u,d,f){let p=new((f?.nodeClass)??n.YAMLMap)(l.schema);l.atRoot&&=!1;let m=u.offset,h=null;for(let n of u.items){let{start:f,key:g,sep:_,value:v}=n,y=r.resolveProps(f,{indicator:`explicit-key-ind`,next:g??_?.[0],offset:m,onError:d,parentIndent:u.indent,startOnNewline:!0}),b=!y.found;if(b){if(g&&(g.type===`block-seq`?d(m,`BLOCK_AS_IMPLICIT_KEY`,`A block sequence may not be used as an implicit map key`):`indent`in g&&g.indent!==u.indent&&d(m,`BAD_INDENT`,s)),!y.anchor&&!y.tag&&!_){h=y.end,y.comment&&(p.comment?p.comment+=`
244
+ `+y.comment:p.comment=y.comment);continue}(y.newlineAfterProp||i.containsNewline(g))&&d(g??f[f.length-1],`MULTILINE_IMPLICIT_KEY`,`Implicit keys need to be on a single line`)}else y.found?.indent!==u.indent&&d(m,`BAD_INDENT`,s);l.atKey=!0;let x=y.end,S=g?e(l,g,y,d):c(l,x,f,null,y,d);l.schema.compat&&a.flowIndentCheck(u.indent,g,d),l.atKey=!1,o.mapIncludes(l,p.items,S)&&d(x,`DUPLICATE_KEY`,`Map keys must be unique`);let C=r.resolveProps(_??[],{indicator:`map-value-ind`,next:v,offset:S.range[2],onError:d,parentIndent:u.indent,startOnNewline:!g||g.type===`block-scalar`});if(m=C.end,C.found){b&&(v?.type===`block-map`&&!C.hasNewline&&d(m,`BLOCK_AS_IMPLICIT_KEY`,`Nested mappings are not allowed in compact mappings`),l.options.strict&&y.start<C.found.offset-1024&&d(S.range,`KEY_OVER_1024_CHARS`,`The : indicator must be at most 1024 chars after the start of an implicit block mapping key`));let r=v?e(l,v,C,d):c(l,m,_,null,C,d);l.schema.compat&&a.flowIndentCheck(u.indent,v,d),m=r.range[2];let i=new t.Pair(S,r);l.options.keepSourceTokens&&(i.srcToken=n),p.items.push(i)}else{b&&d(S.range,`MISSING_CHAR`,`Implicit map keys need to be followed by map values`),C.comment&&(S.comment?S.comment+=`
245
+ `+C.comment:S.comment=C.comment);let e=new t.Pair(S);l.options.keepSourceTokens&&(e.srcToken=n),p.items.push(e)}}return h&&h<m&&d(h,`IMPOSSIBLE`,`Map comment with trailing content`),p.range=[u.offset,m,h??m],p}e.resolveBlockMap=c})),aC=/* @__PURE__ */ D((e=>{var t=AS(),n=eC(),r=nC();function i({composeNode:e,composeEmptyNode:i},a,o,s,c){let l=new((c?.nodeClass)??t.YAMLSeq)(a.schema);a.atRoot&&=!1,a.atKey&&=!1;let u=o.offset,d=null;for(let{start:t,value:c}of o.items){let f=n.resolveProps(t,{indicator:`seq-item-ind`,next:c,offset:u,onError:s,parentIndent:o.indent,startOnNewline:!0});if(!f.found){if(f.anchor||f.tag||c)c?.type===`block-seq`?s(f.end,`BAD_INDENT`,`All sequence items must start at the same column`):s(u,`MISSING_CHAR`,`Sequence item without - indicator`);else{d=f.end,f.comment&&(l.comment=f.comment);continue}}let p=c?e(a,c,f,s):i(a,f.end,t,null,f,s);a.schema.compat&&r.flowIndentCheck(o.indent,c,s),u=p.range[2],l.items.push(p)}return l.range=[o.offset,u,d??u],l}e.resolveBlockSeq=i})),oC=/* @__PURE__ */ D((e=>{function t(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}}e.resolveEnd=t})),sC=/* @__PURE__ */ D((e=>{var t=$(),n=ES(),r=OS(),i=AS(),a=oC(),o=eC(),s=tC(),c=rC();let l=`Block collections are not allowed within flow collections`,u=e=>e&&(e.type===`block-map`||e.type===`block-seq`);function d({composeNode:e,composeEmptyNode:d},f,p,m,h){let g=p.start.source===`{`,_=g?`flow map`:`flow sequence`,v=new((h?.nodeClass)??(g?r.YAMLMap:i.YAMLSeq))(f.schema);v.flow=!0;let y=f.atRoot;y&&(f.atRoot=!1),f.atKey&&=!1;let b=p.offset+p.start.source.length;for(let i=0;i<p.items.length;++i){let a=p.items[i],{start:h,key:y,sep:x,value:S}=a,C=o.resolveProps(h,{flow:_,indicator:`explicit-key-ind`,next:y??x?.[0],offset:b,onError:m,parentIndent:p.indent,startOnNewline:!1});if(!C.found){if(!C.anchor&&!C.tag&&!x&&!S){i===0&&C.comma?m(C.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${_}`):i<p.items.length-1&&m(C.start,`UNEXPECTED_TOKEN`,`Unexpected empty item in ${_}`),C.comment&&(v.comment?v.comment+=`
246
+ `+C.comment:v.comment=C.comment),b=C.end;continue}!g&&f.options.strict&&s.containsNewline(y)&&m(y,`MULTILINE_IMPLICIT_KEY`,`Implicit keys of flow sequence pairs need to be on a single line`)}if(i===0)C.comma&&m(C.comma,`UNEXPECTED_TOKEN`,`Unexpected , in ${_}`);else if(C.comma||m(C.start,`MISSING_CHAR`,`Missing , between ${_} items`),C.comment){let e=``;loop:for(let t of h)switch(t.type){case`comma`:case`space`:break;case`comment`:e=t.source.substring(1);break loop;default:break loop}if(e){let n=v.items[v.items.length-1];t.isPair(n)&&(n=n.value??n.key),n.comment?n.comment+=`
247
+ `+e:n.comment=e,C.comment=C.comment.substring(e.length+1)}}if(!g&&!x&&!C.found){let t=S?e(f,S,C,m):d(f,C.end,x,null,C,m);v.items.push(t),b=t.range[2],u(S)&&m(t.range,`BLOCK_IN_FLOW`,l)}else{f.atKey=!0;let t=C.end,i=y?e(f,y,C,m):d(f,t,h,null,C,m);u(y)&&m(i.range,`BLOCK_IN_FLOW`,l),f.atKey=!1;let s=o.resolveProps(x??[],{flow:_,indicator:`map-value-ind`,next:S,offset:i.range[2],onError:m,parentIndent:p.indent,startOnNewline:!1});if(s.found){if(!g&&!C.found&&f.options.strict){if(x)for(let e of x){if(e===s.found)break;if(e.type===`newline`){m(e,`MULTILINE_IMPLICIT_KEY`,`Implicit keys of flow sequence pairs need to be on a single line`);break}}C.start<s.found.offset-1024&&m(s.found,`KEY_OVER_1024_CHARS`,`The : indicator must be at most 1024 chars after the start of an implicit flow sequence key`)}}else S&&(`source`in S&&S.source?.[0]===`:`?m(S,`MISSING_CHAR`,`Missing space after : in ${_}`):m(s.start,`MISSING_CHAR`,`Missing , or : between ${_} items`));let w=S?e(f,S,s,m):s.found?d(f,s.end,x,null,s,m):null;w?u(S)&&m(w.range,`BLOCK_IN_FLOW`,l):s.comment&&(i.comment?i.comment+=`
248
+ `+s.comment:i.comment=s.comment);let T=new n.Pair(i,w);if(f.options.keepSourceTokens&&(T.srcToken=a),g){let e=v;c.mapIncludes(f,e.items,i)&&m(t,`DUPLICATE_KEY`,`Map keys must be unique`),e.items.push(T)}else{let e=new r.YAMLMap(f.schema);e.flow=!0,e.items.push(T);let t=(w??i).range;e.range=[i.range[0],t[1],t[2]],v.items.push(e)}b=w?w.range[2]:s.end}}let x=g?`}`:`]`,[S,...C]=p.end,w=b;if(S?.source===x)w=S.offset+S.source.length;else{let e=_[0].toUpperCase()+_.substring(1),t=y?`${e} must end with a ${x}`:`${e} in block collection must be sufficiently indented and end with a ${x}`;m(b,y?`MISSING_CHAR`:`BAD_INDENT`,t),S&&S.source.length!==1&&C.unshift(S)}if(C.length>0){let e=a.resolveEnd(C,w,f.options.strict,m);e.comment&&(v.comment?v.comment+=`
249
+ `+e.comment:v.comment=e.comment),v.range=[p.offset,w,e.offset]}else v.range=[p.offset,w,w];return v}e.resolveFlowCollection=d})),cC=/* @__PURE__ */ D((e=>{var t=$(),n=hS(),r=OS(),i=AS(),a=iC(),o=aC(),s=sC();function c(e,t,n,r,i,c){let l=n.type===`block-map`?a.resolveBlockMap(e,t,n,r,c):n.type===`block-seq`?o.resolveBlockSeq(e,t,n,r,c):s.resolveFlowCollection(e,t,n,r,c),u=l.constructor;return i===`!`||i===u.tagName?(l.tag=u.tagName,l):(i&&(l.tag=i),l)}function l(e,a,o,s,l){let u=s.tag,d=u?a.directives.tagName(u.source,e=>l(u,`TAG_RESOLVE_FAILED`,e)):null;if(o.type===`block-seq`){let{anchor:e,newlineAfterProp:t}=s,n=e&&u?e.offset>u.offset?e:u:e??u;n&&(!t||t.offset<n.offset)&&l(n,`MISSING_CHAR`,`Missing newline after block sequence props`)}let f=o.type===`block-map`?`map`:o.type===`block-seq`?`seq`:o.start.source===`{`?`map`:`seq`;if(!u||!d||d===`!`||d===r.YAMLMap.tagName&&f===`map`||d===i.YAMLSeq.tagName&&f===`seq`)return c(e,a,o,l,d);let p=a.schema.tags.find(e=>e.tag===d&&e.collection===f);if(!p){let t=a.schema.knownTags[d];if(t?.collection===f)a.schema.tags.push(Object.assign({},t,{default:!1})),p=t;else return t?l(u,`BAD_COLLECTION_TYPE`,`${t.tag} used for ${f} collection, but expects ${t.collection??`scalar`}`,!0):l(u,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${d}`,!0),c(e,a,o,l,d)}let m=c(e,a,o,l,d,p),h=p.resolve?.(m,e=>l(u,`TAG_RESOLVE_FAILED`,e),a.options)??m,g=t.isNode(h)?h:new n.Scalar(h);return g.range=m.range,g.tag=d,p?.format&&(g.format=p.format),g}e.composeCollection=l})),lC=/* @__PURE__ */ D((e=>{var t=hS();function n(e,n,a){let o=n.offset,s=r(n,e.options.strict,a);if(!s)return{value:``,type:null,comment:``,range:[o,o,o]};let c=s.mode===`>`?t.Scalar.BLOCK_FOLDED:t.Scalar.BLOCK_LITERAL,l=n.source?i(n.source):[],u=l.length;for(let e=l.length-1;e>=0;--e){let t=l[e][1];if(t===``||t===`\r`)u=e;else break}if(u===0){let e=s.chomp===`+`&&l.length>0?`
250
+ `.repeat(Math.max(1,l.length-1)):``,t=o+s.length;return n.source&&(t+=n.source.length),{value:e,type:c,comment:s.comment,range:[o,t,t]}}let d=n.indent+s.indent,f=n.offset+s.length,p=0;for(let t=0;t<u;++t){let[n,r]=l[t];if(r===``||r===`\r`)s.indent===0&&n.length>d&&(d=n.length);else{n.length<d&&a(f+n.length,`MISSING_CHAR`,`Block scalars with more-indented leading empty lines must use an explicit indentation indicator`),s.indent===0&&(d=n.length),p=t,d===0&&!e.atRoot&&a(f,`BAD_INDENT`,`Block scalar values in collections must be indented`);break}f+=n.length+r.length+1}for(let e=l.length-1;e>=u;--e)l[e][0].length>d&&(u=e+1);let m=``,h=``,g=!1;for(let e=0;e<p;++e)m+=l[e][0].slice(d)+`
251
+ `;for(let e=p;e<u;++e){let[n,r]=l[e];f+=n.length+r.length+1;let i=r[r.length-1]===`\r`;
252
+ /* istanbul ignore if already caught in lexer */
253
+ if(i&&(r=r.slice(0,-1)),r&&n.length<d){let e=`Block scalar lines must not be less indented than their ${s.indent?`explicit indentation indicator`:`first line`}`;a(f-r.length-(i?2:1),`BAD_INDENT`,e),n=``}c===t.Scalar.BLOCK_LITERAL?(m+=h+n.slice(d)+r,h=`
254
+ `):n.length>d||r[0]===` `?(h===` `?h=`
255
+ `:!g&&h===`
256
+ `&&(h=`
257
+
258
+ `),m+=h+n.slice(d)+r,h=`
259
+ `,g=!0):r===``?h===`
260
+ `?m+=`
261
+ `:h=`
262
+ `:(m+=h+r,h=` `,g=!1)}switch(s.chomp){case`-`:break;case`+`:for(let e=u;e<l.length;++e)m+=`
263
+ `+l[e][0].slice(d);m[m.length-1]!==`
264
+ `&&(m+=`
265
+ `);break;default:m+=`
266
+ `}let _=o+s.length+n.source.length;return{value:m,type:c,comment:s.comment,range:[o,_,_]}}function r({offset:e,props:t},n,r){
267
+ /* istanbul ignore if should not happen */
268
+ 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;
269
+ /* istanbul ignore next should not happen */
270
+ 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 i(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}e.resolveBlockScalar=n})),uC=/* @__PURE__ */ D((e=>{var t=hS(),n=oC();function r(e,r,o){let{offset:c,type:l,source:u,end:d}=e,f,p,m=(e,t,n)=>o(c+e,t,n);switch(l){case`scalar`:f=t.Scalar.PLAIN,p=i(u,m);break;case`single-quoted-scalar`:f=t.Scalar.QUOTE_SINGLE,p=a(u,m);break;case`double-quoted-scalar`:f=t.Scalar.QUOTE_DOUBLE,p=s(u,m);break;
271
+ /* istanbul ignore next should not happen */
272
+ default:return o(e,`UNEXPECTED_TOKEN`,`Expected a flow scalar value, but found: ${l}`),{value:``,type:null,comment:``,range:[c,c+u.length,c+u.length]}}let h=c+u.length,g=n.resolveEnd(d,h,r,o);return{value:p,type:f,comment:g.comment,range:[c,h,g.offset]}}function i(e,t){let n=``;switch(e[0]){
273
+ /* istanbul ignore next should not happen */
274
+ 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}`),o(e)}function a(e,t){return(e[e.length-1]!==`'`||e.length===1)&&t(e.length,`MISSING_CHAR`,`Missing closing 'quote`),o(e.slice(1,-1)).replace(/''/g,`'`)}function o(e){let t=/(.*?)\r?\n/sy,n=t.exec(e);if(!n)return e;let r,i;try{r=RegExp(`(?<![ ])[ ]+$`),i=RegExp(`^[ ]+|(?<![ ])[ ]+$`,`g`)}catch{r=/[ \t]+$/,i=/^[ \t]+|[ \t]+$/g}let a=n[1].replace(r,``),o=` `,s=t.lastIndex;for(;n=t.exec(e);){let e=n[1].replace(i,``);e===``?o===`
275
+ `?a+=o:o=`
276
+ `:(a+=o+e,o=` `),s=t.lastIndex}let c=/[ \t]*(.*)/sy;return c.lastIndex=s,n=c.exec(e),a+o+(n?.[1]??``)}function s(e,t){let n=``;for(let r=1;r<e.length-1;++r){let i=e[r];if(i!==`\r`||e[r+1]!==`
277
+ `){if(i===`
278
+ `){let{fold:t,offset:i}=c(e,r);n+=t,r=i}else if(i===`\\`){let i=e[++r],a=l[i];if(a)n+=a;else if(i===`
279
+ `)for(i=e[r+1];i===` `||i===` `;)i=e[++r+1];else if(i===`\r`&&e[r+1]===`
280
+ `)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+=u(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!==`
281
+ `&&(a!==`\r`||e[r+2]!==`
282
+ `)&&(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 c(e,t){let n=``,r=e[t+1];for(;(r===` `||r===` `||r===`
283
+ `||r===`\r`)&&(r!==`\r`||e[t+2]===`
284
+ `);)r===`
285
+ `&&(n+=`
286
+ `),t+=1,r=e[t+1];return n||=` `,{fold:n,offset:t}}let l={0:`\0`,a:`\x07`,b:`\b`,e:`\x1B`,f:`\f`,n:`
287
+ `,r:`\r`,t:` `,v:`\v`,N:`…`,_:`\xA0`,L:`\u2028`,P:`\u2029`," ":` `,'"':`"`,"/":`/`,"\\":`\\`," ":` `};function u(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}}e.resolveFlowScalar=r})),dC=/* @__PURE__ */ D((e=>{var t=$(),n=hS(),r=lC(),i=uC();function a(e,a,c,l){let{value:u,type:d,comment:f,range:p}=a.type===`block-scalar`?r.resolveBlockScalar(e,a,l):i.resolveFlowScalar(a,e.options.strict,l),m=c?e.directives.tagName(c.source,e=>l(c,`TAG_RESOLVE_FAILED`,e)):null,h;h=e.options.stringKeys&&e.atKey?e.schema[t.SCALAR]:m?o(e.schema,u,m,c,l):a.type===`scalar`?s(e,u,a,l):e.schema[t.SCALAR];let g;try{let r=h.resolve(u,e=>l(c??a,`TAG_RESOLVE_FAILED`,e),e.options);g=t.isScalar(r)?r:new n.Scalar(r)}catch(e){let t=e instanceof Error?e.message:String(e);l(c??a,`TAG_RESOLVE_FAILED`,t),g=new n.Scalar(u)}return g.range=p,g.source=u,d&&(g.type=d),m&&(g.tag=m),h.format&&(g.format=h.format),f&&(g.comment=f),g}function o(e,n,r,i,a){if(r===`!`)return e[t.SCALAR];let o=[];for(let t of e.tags)if(!t.collection&&t.tag===r){if(t.default&&t.test)o.push(t);else return t}for(let e of o)if(e.test?.test(n))return e;let s=e.knownTags[r];return s&&!s.collection?(e.tags.push(Object.assign({},s,{default:!1,test:void 0})),s):(a(i,`TAG_RESOLVE_FAILED`,`Unresolved tag: ${r}`,r!==`tag:yaml.org,2002:str`),e[t.SCALAR])}function s({atKey:e,directives:n,schema:r},i,a,o){let s=r.tags.find(t=>(t.default===!0||e&&t.default===`key`)&&t.test?.test(i))||r[t.SCALAR];if(r.compat){let e=r.compat.find(e=>e.default&&e.test?.test(i))??r[t.SCALAR];s.tag!==e.tag&&o(a,`TAG_RESOLVE_FAILED`,`Value may be parsed as either ${n.tagString(s.tag)} or ${n.tagString(e.tag)}`,!0)}return s}e.composeScalar=a})),fC=/* @__PURE__ */ D((e=>{function t(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}e.emptyScalarPosition=t})),pC=/* @__PURE__ */ D((e=>{var t=mS(),n=$(),r=cC(),i=dC(),a=oC(),o=fC();let s={composeNode:c,composeEmptyNode:l};function c(e,t,a,o){let c=e.atKey,{spaceBefore:d,comment:f,anchor:p,tag:m}=a,h,g=!0;switch(t.type){case`alias`:h=u(e,t,o),(p||m)&&o(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`:h=i.composeScalar(e,t,m,o),p&&(h.anchor=p.source.substring(1));break;case`block-map`:case`block-seq`:case`flow-collection`:try{h=r.composeCollection(s,e,t,a,o),p&&(h.anchor=p.source.substring(1))}catch(e){o(t,`RESOURCE_EXHAUSTION`,e instanceof Error?e.message:String(e))}break;default:o(t,`UNEXPECTED_TOKEN`,t.type===`error`?t.message:`Unsupported token (type: ${t.type})`),g=!1}return h??=l(e,t.offset,void 0,null,a,o),p&&h.anchor===``&&o(p,`BAD_ALIAS`,`Anchor cannot be an empty string`),c&&e.options.stringKeys&&(!n.isScalar(h)||typeof h.value!=`string`||h.tag&&h.tag!==`tag:yaml.org,2002:str`)&&o(m??t,`NON_STRING_KEY`,`With stringKeys, all keys must be strings`),d&&(h.spaceBefore=!0),f&&(t.type===`scalar`&&t.source===``?h.comment=f:h.commentBefore=f),e.options.keepSourceTokens&&g&&(h.srcToken=t),h}function l(e,t,n,r,{spaceBefore:a,comment:s,anchor:c,tag:l,end:u},d){let f={type:`scalar`,offset:o.emptyScalarPosition(t,n,r),indent:-1,source:``},p=i.composeScalar(e,f,l,d);return c&&(p.anchor=c.source.substring(1),p.anchor===``&&d(c,`BAD_ALIAS`,`Anchor cannot be an empty string`)),a&&(p.spaceBefore=!0),s&&(p.comment=s,p.range[2]=u),p}function u({options:e},{offset:n,source:r,end:i},o){let s=new t.Alias(r.substring(1));s.source===``&&o(n,`BAD_ALIAS`,`Alias cannot be an empty string`),s.source.endsWith(`:`)&&o(n+r.length-1,`BAD_ALIAS`,`Alias ending in : is ambiguous`,!0);let c=n+r.length,l=a.resolveEnd(i,c,e.strict,o);return s.range=[n,c,l.offset],l.comment&&(s.comment=l.comment),s}e.composeEmptyNode=l,e.composeNode=c})),mC=/* @__PURE__ */ D((e=>{var t=QS(),n=pC(),r=oC(),i=eC();function a(e,a,{offset:o,start:s,value:c,end:l},u){let d=Object.assign({_directives:a},e),f=new t.Document(void 0,d),p={atKey:!1,atRoot:!0,directives:f.directives,options:f.options,schema:f.schema},m=i.resolveProps(s,{indicator:`doc-start`,next:c??l?.[0],offset:o,onError:u,parentIndent:0,startOnNewline:!0});m.found&&(f.directives.docStart=!0,c&&(c.type===`block-map`||c.type===`block-seq`)&&!m.hasNewline&&u(m.end,`MISSING_CHAR`,`Block collection cannot start on same line with directives-end marker`)),f.contents=c?n.composeNode(p,c,m,u):n.composeEmptyNode(p,m.end,s,null,m,u);let h=f.contents.range[2],g=r.resolveEnd(l,h,!1,u);return g.comment&&(f.comment=g.comment),f.range=[o,h,g.offset],f}e.composeDoc=a})),hC=/* @__PURE__ */ D((e=>{var t=de(`process`),n=lS(),r=QS(),i=$S(),a=$(),o=mC(),s=oC();function c(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 l(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?`
288
+
289
+ `:`
290
+ `)+(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}}e.Composer=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(e,t,n,r)=>{let a=c(e);r?this.warnings.push(new i.YAMLWarning(a,t,n)):this.errors.push(new i.YAMLParseError(a,t,n))},this.directives=new n.Directives({version:e.version||`1.2`}),this.options=e}decorate(e,t){let{comment:n,afterEmptyLine:r}=l(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(a.isCollection(i)&&!i.flow&&i.items.length>0){let e=i.items[0];a.isPair(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:l(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(t.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case`directive`:this.directives.add(e.source,(t,n,r)=>{let i=c(e);i[0]+=t,this.onError(i,`BAD_DIRECTIVE`,n,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case`document`:{let t=o.composeDoc(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 i.YAMLParseError(c(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 i.YAMLParseError(c(e),`UNEXPECTED_TOKEN`,`Unexpected doc-end without preceding document`));break}this.doc.directives.docEnd=!0;let t=s.resolveEnd(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 i.YAMLParseError(c(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 r.Document(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}}}})),gC=/* @__PURE__ */ D((e=>{var t=lC(),n=uC(),r=$S(),i=bS();function a(e,i=!0,a){if(e){let o=(e,t,n)=>{let i=typeof e==`number`?e:Array.isArray(e)?e[0]:e.offset;if(a)a(i,t,n);else throw new r.YAMLParseError([i,i+1],t,n)};switch(e.type){case`scalar`:case`single-quoted-scalar`:case`double-quoted-scalar`:return n.resolveFlowScalar(e,i,o);case`block-scalar`:return t.resolveBlockScalar({options:{strict:i}},e,o)}}return null}function o(e,t){let{implicitKey:n=!1,indent:r,inFlow:a=!1,offset:o=-1,type:s=`PLAIN`}=t,c=i.stringifyString({type:s,value:e},{implicitKey:n,indent:r>0?` `.repeat(r):``,inFlow:a,options:{blockQuote:!0,lineWidth:-1}}),u=t.end??[{type:`newline`,offset:-1,indent:r,source:`
291
+ `}];switch(c[0]){case`|`:case`>`:{let e=c.indexOf(`
292
+ `),t=c.substring(0,e),n=c.substring(e+1)+`
293
+ `,i=[{type:`block-scalar-header`,offset:o,indent:r,source:t}];return l(i,u)||i.push({type:`newline`,offset:-1,indent:r,source:`
294
+ `}),{type:`block-scalar`,offset:o,indent:r,props:i,source:n}}case`"`:return{type:`double-quoted-scalar`,offset:o,indent:r,source:c,end:u};case`'`:return{type:`single-quoted-scalar`,offset:o,indent:r,source:c,end:u};default:return{type:`scalar`,offset:o,indent:r,source:c,end:u}}}function s(e,t,n={}){let{afterKey:r=!1,implicitKey:a=!1,inFlow:o=!1,type:s}=n,l=`indent`in e?e.indent:null;if(r&&typeof l==`number`&&(l+=2),!s)switch(e.type){case`single-quoted-scalar`:s=`QUOTE_SINGLE`;break;case`double-quoted-scalar`:s=`QUOTE_DOUBLE`;break;case`block-scalar`:{let t=e.props[0];if(t.type!==`block-scalar-header`)throw Error(`Invalid block scalar header`);s=t.source[0]===`>`?`BLOCK_FOLDED`:`BLOCK_LITERAL`;break}default:s=`PLAIN`}let d=i.stringifyString({type:s,value:t},{implicitKey:a||l===null,indent:l!==null&&l>0?` `.repeat(l):``,inFlow:o,options:{blockQuote:!0,lineWidth:-1}});switch(d[0]){case`|`:case`>`:c(e,d);break;case`"`:u(e,d,`double-quoted-scalar`);break;case`'`:u(e,d,`single-quoted-scalar`);break;default:u(e,d,`scalar`)}}function c(e,t){let n=t.indexOf(`
295
+ `),r=t.substring(0,n),i=t.substring(n+1)+`
296
+ `;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}];l(a,`end`in e?e.end:void 0)||a.push({type:`newline`,offset:-1,indent:n,source:`
297
+ `});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 l(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 u(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:`
298
+ `};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})}}}e.createScalarToken=o,e.resolveAsScalar=a,e.setScalarValue=s})),_C=/* @__PURE__ */ D((e=>{let t=e=>`type`in e?n(e):r(e);function n(e){switch(e.type){case`block-scalar`:{let t=``;for(let r of e.props)t+=n(r);return t+e.source}case`block-map`:case`block-seq`:{let t=``;for(let n of e.items)t+=r(n);return t}case`flow-collection`:{let t=e.start.source;for(let n of e.items)t+=r(n);for(let n of e.end)t+=n.source;return t}case`document`:{let t=r(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 r({start:e,key:t,sep:r,value:i}){let a=``;for(let t of e)a+=t.source;if(t&&(a+=n(t)),r)for(let e of r)a+=e.source;return i&&(a+=n(i)),a}e.stringify=t})),vC=/* @__PURE__ */ D((e=>{let t=Symbol(`break visit`),n=Symbol(`skip children`),r=Symbol(`remove item`);function i(e,t){`type`in e&&e.type===`document`&&(e={start:e.start,value:e.value}),a(Object.freeze([]),e,t)}i.BREAK=t,i.SKIP=n,i.REMOVE=r,i.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},i.parentCollection=(e,t)=>{let n=i.itemAtPath(e,t.slice(0,-1)),r=t[t.length-1][0],a=n?.[r];if(a&&`items`in a)return a;throw Error(`Parent collection not found`)};function a(e,n,i){let o=i(n,e);if(typeof o==`symbol`)return o;for(let s of[`key`,`value`]){let c=n[s];if(c&&`items`in c){for(let n=0;n<c.items.length;++n){let o=a(Object.freeze(e.concat([[s,n]])),c.items[n],i);if(typeof o==`number`)n=o-1;else if(o===t)return t;else o===r&&(c.items.splice(n,1),--n)}typeof o==`function`&&s===`key`&&(o=o(n,e))}}return typeof o==`function`?o(n,e):o}e.visit=i})),yC=/* @__PURE__ */ D((e=>{var t=gC(),n=_C(),r=vC();let i=e=>!!e&&`items`in e,a=e=>!!e&&(e.type===`scalar`||e.type===`single-quoted-scalar`||e.type===`double-quoted-scalar`||e.type===`block-scalar`);
299
+ /* istanbul ignore next */
300
+ function o(e){switch(e){case``:return`<BOM>`;case``:return`<DOC>`;case``:return`<FLOW_END>`;case``:return`<SCALAR>`;default:return JSON.stringify(e)}}function s(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`
301
+ `:case`\r
302
+ `: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}e.createScalarToken=t.createScalarToken,e.resolveAsScalar=t.resolveAsScalar,e.setScalarValue=t.setScalarValue,e.stringify=n.stringify,e.visit=r.visit,e.BOM=``,e.DOCUMENT=``,e.FLOW_END=``,e.SCALAR=``,e.isCollection=i,e.isScalar=a,e.prettyToken=o,e.tokenType=s})),bC=/* @__PURE__ */ D((e=>{var t=yC();function n(e){switch(e){case void 0:case` `:case`
303
+ `:case`\r`:case` `:return!0;default:return!1}}let r=/* @__PURE__ */ new Set(`0123456789ABCDEFabcdef`),i=/* @__PURE__ */ new Set(`0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()`),a=/* @__PURE__ */ new Set(`,[]{}`),o=/* @__PURE__ */ new Set(` ,[]{}
304
+ \r `),s=e=>!e||o.has(e);e.Lexer=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===`
305
+ `||t===`\r`&&this.buffer[e+1]===`
306
+ `}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===`
307
+ `||!t&&!this.atEnd)return e+n+1}return t===`
308
+ `||n>=this.indentNext||!t&&!this.atEnd?e+n:-1}if(t===`-`||t===`.`){let t=this.buffer.substr(e,3);if((t===`---`||t===`...`)&&n(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(`
309
+ `,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]===t.BOM&&(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 t.DOCUMENT,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===`...`)&&n(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&&!n(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===`:`)&&n(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(s),`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,r,i=-1;do e=yield*this.pushNewline(),e>0?(r=yield*this.pushSpaces(!1),this.indentValue=i=r):r=0,r+=yield*this.pushSpaces(!0);while(e+r>0);let a=this.getLine();if(a===null)return this.setNext(`flow`);if((i!==-1&&i<this.indentNext&&a[0]!==`#`||i===0&&(a.startsWith(`---`)||a.startsWith(`...`))&&n(a[3]))&&(i!==this.indentNext-1||this.flowLevel!==1||a[0]!==`]`&&a[0]!==`}`))return this.flowLevel=0,yield t.FLOW_END,yield*this.parseLineStart();let o=0;for(;a[o]===`,`;)o+=yield*this.pushCount(1),o+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(o+=yield*this.pushIndicators(),a[o]){case void 0:return`flow`;case`#`:return yield*this.pushCount(a.length-o),`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(s),`flow`;case`"`:case`'`:return this.flowKey=!0,yield*this.parseQuotedScalar();case`:`:{let e=this.charAt(1);if(this.flowKey||n(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(`
310
+ `,this.pos);if(r!==-1){for(;r!==-1;){let e=this.continueScalar(r+1);if(e===-1)break;r=n.indexOf(`
311
+ `,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=>n(e)||e===`#`)}*parseBlockScalar(){let e=this.pos-1,n=0,r;loop:for(let t=this.pos;r=this.buffer[t];++t)switch(r){case` `:n+=1;break;case`
312
+ `:e=t,n=0;break;case`\r`:{let e=this.buffer[t+1];if(!e&&!this.atEnd)return this.setNext(`block-scalar`);if(e===`
313
+ `)break}default:break loop}if(!r&&!this.atEnd)return this.setNext(`block-scalar`);if(n>=this.indentNext){this.indentNext=this.blockScalarIndent===-1?n:this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let t=this.continueScalar(e+1);if(t===-1)break;e=this.buffer.indexOf(`
314
+ `,t)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext(`block-scalar`);e=this.buffer.length}}let i=e+1;for(r=this.buffer[i];r===` `;)r=this.buffer[++i];if(r===` `){for(;r===` `||r===` `||r===`\r`||r===`
315
+ `;)r=this.buffer[++i];e=i-1}else if(!this.blockScalarKeep)do{let t=e-1,r=this.buffer[t];r===`\r`&&(r=this.buffer[--t]);let i=t;for(;r===` `;)r=this.buffer[--t];if(r===`
316
+ `&&t>=this.pos&&t+1+n>i)e=t;else break}while(1);return yield t.SCALAR,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,r=this.pos-1,i=this.pos-1,o;for(;o=this.buffer[++i];)if(o===`:`){let t=this.buffer[i+1];if(n(t)||e&&a.has(t))break;r=i}else if(n(o)){let t=this.buffer[i+1];if(o===`\r`&&(t===`
317
+ `?(i+=1,o=`
318
+ `,t=this.buffer[i+1]):r=i),t===`#`||e&&a.has(t))break;if(o===`
319
+ `){let e=this.continueScalar(i+1);if(e===-1)break;i=Math.max(i,e-2)}}else{if(e&&a.has(o))break;r=i}return!o&&!this.atEnd?this.setNext(`plain-scalar`):(yield t.SCALAR,yield*this.pushToIndex(r+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(s),e+=yield*this.pushSpaces(!0);continue loop;case`-`:case`?`:case`:`:{let t=this.flowLevel>0,r=this.charAt(1);if(n(r)||t&&a.has(r)){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(;!n(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(i.has(t))t=this.buffer[++e];else if(t===`%`&&r.has(this.buffer[e+1])&&r.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===`
320
+ `?yield*this.pushCount(1):e===`\r`&&this.charAt(1)===`
321
+ `?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)}}})),xC=/* @__PURE__ */ D((e=>{e.LineCounter=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}}}}})),SC=/* @__PURE__ */ D((e=>{var t=de(`process`),n=yC(),r=bC();function i(e,t){for(let n=0;n<e.length;++n)if(e[n].type===t)return!0;return!1}function a(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 o(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 s(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;
322
+ /* istanbul ignore next should not happen */
323
+ 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 l(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 u(e){if(e.start.type===`flow-seq-start`)for(let t of e.items)t.sep&&!t.value&&!i(t.start,`explicit-key-ind`)&&!i(t.sep,`map-value-ind`)&&(t.key&&(t.value=t.key),delete t.key,o(t.value)?t.value.end?l(t.value.end,t.sep):t.value.end=t.sep:l(t.start,t.sep),delete t.sep)}e.Parser=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 r.Lexer,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,t.env.LOG_TOKENS&&console.log(`|`,n.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let r=n.tokenType(e);if(!r){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(r===`scalar`)this.atNewLine=!1,this.atScalar=!0,this.type=`scalar`;else{switch(this.type=r,yield*this.step(),r){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})}else{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)}
324
+ /* istanbul ignore next should not happen */
325
+ yield*this.pop()}}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e??this.stack.pop();
326
+ /* istanbul ignore if should not happen */
327
+ 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`&&u(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}
328
+ /* istanbul ignore next should not happen */
329
+ 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&&a(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`:a(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(s(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(`
330
+ `)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
331
+ `,e)+1}yield*this.pop();break;
332
+ /* istanbul ignore next should not happen */
333
+ 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)){l(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`,a=[];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&&(a=t.sep.splice(n[1]))}switch(this.type){case`anchor`:case`tag`:r||t.value?(a.push(this.sourceToken),e.items.push({start:a}),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?(a.push(this.sourceToken),e.items.push({start:a,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(i(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(i(t.sep,`map-value-ind`))this.stack.push({type:`block-map`,offset:this.offset,indent:this.indent,items:[{start:a,key:null,sep:[this.sourceToken]}]});else if(o(t.key)&&!i(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 a.length>0?t.sep=t.sep.concat(a,this.sourceToken):t.sep.push(this.sourceToken)}else t.sep?t.value||r?e.items.push({start:a,key:null,sep:[this.sourceToken]}):i(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:a,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&&!i(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:a});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)){l(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||i(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);
334
+ /* istanbul ignore else should not happen */
335
+ 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(s(t));u(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(`
336
+ `)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
337
+ `,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(s(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(s(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())}}}})),CC=/* @__PURE__ */ D((e=>{var t=hC(),n=QS(),r=$S(),i=CS(),a=$(),o=xC(),s=SC();function c(e){let t=e.prettyErrors!==!1;return{lineCounter:e.lineCounter||t&&new o.LineCounter||null,prettyErrors:t}}function l(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=Array.from(l.compose(o.parse(e)));if(a&&i)for(let t of u)t.errors.forEach(r.prettifyError(e,i)),t.warnings.forEach(r.prettifyError(e,i));return u.length>0?u:Object.assign([],{empty:!0},l.streamInfo())}function u(e,n={}){let{lineCounter:i,prettyErrors:a}=c(n),o=new s.Parser(i?.addNewLine),l=new t.Composer(n),u=null;for(let t of l.compose(o.parse(e),!0,e.length))if(!u)u=t;else if(u.options.logLevel!==`silent`){u.errors.push(new r.YAMLParseError(t.range.slice(0,2),`MULTIPLE_DOCS`,`Source contains multiple documents; please use YAML.parseAllDocuments()`));break}return a&&i&&(u.errors.forEach(r.prettifyError(e,i)),u.warnings.forEach(r.prettifyError(e,i))),u}function d(e,t,n){let r;typeof t==`function`?r=t:n===void 0&&t&&typeof t==`object`&&(n=t);let a=u(e,n);if(!a)return null;if(a.warnings.forEach(e=>i.warn(a.options.logLevel,e)),a.errors.length>0){if(a.options.logLevel!==`silent`)throw a.errors[0];a.errors=[]}return a.toJS(Object.assign({reviver:r},n))}function f(e,t,r){let i=null;if(typeof t==`function`||Array.isArray(t)?i=t:r===void 0&&t&&(r=t),typeof r==`string`&&(r=r.length),typeof r==`number`){let e=Math.round(r);r=e<1?void 0:e>8?{indent:8}:{indent:e}}if(e===void 0){let{keepUndefined:e}=r??t??{};if(!e)return}return a.isDocument(e)&&!i?e.toString(r):new n.Document(e,i,r).toString(r)}e.parse=d,e.parseAllDocuments=l,e.parseDocument=u,e.stringify=f})),wC=(/* @__PURE__ */ D((e=>{var t=hC(),n=QS(),r=XS(),i=$S(),a=mS(),o=$(),s=ES(),c=hS(),l=OS(),u=AS();yC();var d=bC(),f=xC(),p=SC(),m=CC(),h=cS();e.Composer=t.Composer,e.Document=n.Document,e.Schema=r.Schema,e.YAMLError=i.YAMLError,e.YAMLParseError=i.YAMLParseError,e.YAMLWarning=i.YAMLWarning,e.Alias=a.Alias,e.isAlias=o.isAlias,e.isCollection=o.isCollection,e.isDocument=o.isDocument,e.isMap=o.isMap,e.isNode=o.isNode,e.isPair=o.isPair,e.isScalar=o.isScalar,e.isSeq=o.isSeq,e.Pair=s.Pair,e.Scalar=c.Scalar,e.YAMLMap=l.YAMLMap,e.YAMLSeq=u.YAMLSeq,e.Lexer=d.Lexer,e.LineCounter=f.LineCounter,e.Parser=p.Parser,e.parse=m.parse,e.parseAllDocuments=m.parseAllDocuments,e.parseDocument=m.parseDocument,e.stringify=m.stringify,e.visit=h.visit,e.visitAsync=h.visitAsync})))();function TC(e,t){let n=(0,wC.parse)(e,{uniqueKeys:!1});if(!Q(n))throw Error(`not a YAML mapping`);let r=new nS(`npm`,t),i=Q(n.importers)?n.importers:{".":n};for(let e of Object.values(i))if(Q(e))for(let t of[`dependencies`,`devDependencies`,`optionalDependencies`]){let n=e[t];if(Q(n))for(let[e,t]of Object.entries(n)){let n=Q(t)?t.version:t;if(typeof n!=`string`||EC(n))continue;let i=OC(n);i?r.add(i.name,i.version,!0):r.add(e,DC(n),!0)}}for(let e of[`packages`,`snapshots`]){let t=n[e];if(Q(t))for(let e of Object.keys(t)){let t=OC(e);t&&!EC(t.version)&&r.add(t.name,t.version,!1)}}return r.rows()}function EC(e){return/^(link|file|workspace):/.test(e)}function DC(e){return e.replace(/\(.*$/,``).replace(/_(?=[^/]*@).*$/,``)}function OC(e){let t=e.replace(/^\//,``).replace(/\(.*$/,``),n=t.indexOf(`@`,1);if(n>0)return{name:t.slice(0,n),version:DC(t.slice(n+1))};if(!e.startsWith(`/`))return null;let r=t.lastIndexOf(`/`);return r<=0?null:{name:t.slice(0,r),version:DC(t.slice(r+1))}}function kC(e,t){let n=aS(e);if(!Q(n))throw Error(`not a JSON object`);let r=new nS(`npm`,t);if(Q(n.packages)){let e=/* @__PURE__ */ new Set;for(let[t,r]of Object.entries(n.packages))if(!t.includes(`node_modules/`))for(let t of iS(r))e.add(t);for(let[t,i]of Object.entries(n.packages)){let n=t.lastIndexOf(`node_modules/`);if(n===-1||!Q(i)||i.link===!0)continue;let a=t.slice(n+13),o=typeof i.name==`string`?i.name:a;if(typeof i.version!=`string`)continue;let s=t===`node_modules/${a}`;r.add(o,i.version,s&&e.has(a))}return r.rows()}if(Q(n.dependencies)){let e=(t,n)=>{for(let[i,a]of Object.entries(t)){if(!Q(a))continue;let t=a.version;typeof t==`string`&&!EC(t)&&r.add(i,t,n===0&&a.dev!==!0),Q(a.dependencies)&&e(a.dependencies,n+1)}};e(n.dependencies,0)}return r.rows()}function AC(e,t,n){let r=new nS(`npm`,t),i=[],a=!1;for(let t of e.split(/\r?\n/)){if(t===``||t.startsWith(`#`))continue;if(!/^\s/.test(t)&&t.endsWith(`:`)){let e=t.slice(0,-1).split(`,`).map(e=>e.trim().replace(/^"|"$/g,``));a=e.some(e=>/@(workspace|link|file|portal):/.test(e)),i=[...new Set(e.map(jC).filter(e=>e!==null))];continue}let e=/^\s+version:?\s+"?([^"\s]+)"?/.exec(t)?.[1];if(e&&!a){for(let t of i)r.add(t,e,n.has(t));i=[]}}return r.rows()}function jC(e){if(e===`__metadata`)return null;let t=e.indexOf(`@`,1);return t>0?e.slice(0,t):null}async function MC(e,t){let n=ix(t),r=/* @__PURE__ */ new Set,i=await NC(e,ax(n,`package.json`));for(let e of iS(i))r.add(e);if(!Q(i))return r;let a=i.workspaces,o=(Array.isArray(a)?a:Q(a)&&Array.isArray(a.packages)?a.packages:[]).filter(e=>typeof e==`string`).map(e=>PC(ax(n,e.replace(/^\.\//,``).replace(/\/$/,``))));if(o.length===0)return r;for(let t of e.files){if(!t.path.endsWith(`package.json`))continue;let n=ix(t.path);if(o.some(e=>e.test(n)))for(let n of iS(await NC(e,t.path)))r.add(n)}return r}async function NC(e,t){let n=e.file(t);if(!n)return null;let r=await e.readText(n);if(r===null)return null;try{return aS(r)}catch{return e.warnings.push(`${t}: not valid JSON, skipped`),null}}function PC(e){let t=e.split(`/`).map(e=>e===`**`?`.*`:e.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`[^/]*`)).join(`/`);return RegExp(`^${t}$`)}function FC(e){return e.toLowerCase().replace(/[-_.]+/g,`-`)}function IC(e,t,n){let r=new nS(`pip`,t),i=!1,a=null,o=null,s=!1,c=()=>{a&&o&&!s&&r.add(a,o,n.has(FC(a))),a=null,o=null,s=!1};for(let t of e.split(/\r?\n/)){if(/^\s*\[{1,2}([^\]]+)\]{1,2}\s*$/.exec(t)){t.trim()===`[[package]]`?(c(),i=!0):i=!1;continue}if(!i)continue;let e=/^\s*(name|version|source)\s*=\s*(.+)$/.exec(t);if(!e)continue;let n=e[2]?.trim()??``;if(e[1]===`source`)s=/\b(editable|virtual)\s*=/.test(n);else{let t=/^"([^"]*)"/.exec(n)?.[1];e[1]===`name`&&t&&(a=t),e[1]===`version`&&t&&(o=t)}}return c(),r.rows()}function LC(e){let t=/* @__PURE__ */ new Set,n=``,r=null,i=``,a=e=>{let n=/^\s*([A-Za-z0-9][A-Za-z0-9._-]*)/.exec(e)?.[1];n&&t.add(FC(n))},o=()=>{for(let e of i.matchAll(/"([^"]*)"|'([^']*)'/g))a(e[1]??e[2]??``);r=null,i=``};for(let a of e.split(/\r?\n/)){let e=a.replace(/\s+#.*$/,``);if(r!==null){i+=` ${e}`,e.includes(`]`)&&o();continue}let s=/^\s*\[([^\]]+)\]\s*$/.exec(e);if(s){n=(s[1]??``).trim();continue}let c=/^\s*"?([A-Za-z0-9_.-]+)"?\s*=\s*(.*)$/.exec(e);if(!c)continue;let l=c[1]??``,u=c[2]??``;n===`tool.poetry.dependencies`||n===`tool.poetry.dev-dependencies`||/^tool\.poetry\.group\.[^.]+\.dependencies$/.test(n)?FC(l)!==`python`&&t.add(FC(l)):(n===`project`&&l===`dependencies`||n===`project.optional-dependencies`||n===`dependency-groups`)&&u.trimStart().startsWith(`[`)&&(r=l,i=u,u.includes(`]`)&&o())}return t}function RC(e,t){let n=new nS(`pip`,t),r=0;for(let t of e.split(/\r?\n/)){let e=t.replace(/(^|\s)#.*$/,``).trim();if(e===``||e.startsWith(`-`))continue;let i=/^([A-Za-z0-9][A-Za-z0-9._-]*)\s*(?:\[[^\]]*\])?\s*===?\s*([^\s;,\\]+)/.exec(e);i?.[1]&&i[2]?n.add(i[1],i[2],!0):r++}return{rows:n.rows(),unpinned:r}}async function zC(e){let t=[];for(let n of e.files)try{let r=await BC(e,n);r&&t.push(...r)}catch(t){e.warnings.push(`${n.path}: could not be parsed (${ox(t)})`)}return t}async function BC(e,t){let n=rx(t.path),r=ix(t.path),i=t=>t?e.readText(t,52428800):Promise.resolve(null),a=t=>e.file(ax(r,t));switch(n){case`pnpm-lock.yaml`:{let e=await i(t);return e===null?null:TC(e,t.path)}case`package-lock.json`:case`npm-shrinkwrap.json`:{let e=await i(t);return e===null?null:kC(e,t.path)}case`yarn.lock`:{let n=await i(t);return n===null?null:AC(n,t.path,await MC(e,t.path))}case`composer.lock`:{let e=await i(t);return e===null?null:oS(e,t.path,await i(a(`composer.json`)))}case`poetry.lock`:case`uv.lock`:{let e=await i(t);if(e===null)return null;let n=await i(a(`pyproject.toml`)),r=n?LC(n):/* @__PURE__ */ new Set;return IC(e,t.path,r)}case`go.sum`:case`go.mod`:return n===`go.mod`&&a(`go.sum`)?null:sS(await i(a(`go.mod`)),n===`go.sum`?await i(t):null,t.path)}if(/^requirements[\w.-]*\.txt$/i.test(n)||/(^|\/)requirements\/[^/]+\.txt$/.test(t.path)){let n=await i(t);if(n===null)return null;let{rows:r,unpinned:a}=RC(n,t.path);return a>0&&e.warnings.push(`${t.path}: ${a} requirement${a===1?``:`s`} without an exact == pin skipped`),r}return null}const VC=n(i);async function HC(e,t){try{let{stdout:n}=await VC(`git`,t,{cwd:e,timeout:1e4}),r=n.trim();return r===``?null:r}catch{return null}}async function UC(e,t){let n=_.basename(e);if(await HC(e,[`rev-parse`,`--is-inside-work-tree`])!==`true`)return t.push(`Not a git repository (or git is not installed): repo details are empty`),{name:n,provider:null,url:null,defaultBranch:null,headSha:null,lastCommitAt:null};let[r,i,a,o,s]=await Promise.all([HC(e,[`remote`,`get-url`,`origin`]),HC(e,[`rev-parse`,`--verify`,`--quiet`,`HEAD`]),HC(e,[`log`,`-1`,`--format=%cI`]),HC(e,[`symbolic-ref`,`--quiet`,`refs/remotes/origin/HEAD`]),HC(e,[`symbolic-ref`,`--quiet`,`--short`,`HEAD`])]);i===null&&t.push(`Git repository has no commits yet`),r===null&&t.push(`Git repository has no 'origin' remote`);let c=r?WC(r):null;return r&&!c&&t.push(`Could not read the 'origin' remote URL`),{name:c?.name??n,provider:c?.provider??null,url:c?.url??null,defaultBranch:o?.replace(/^refs\/remotes\/origin\//,``)??s,headSha:i,lastCommitAt:a?new Date(a).toISOString():null}}function WC(e){let t,n,r=/^(?:[^@/]+@)?([^:/]+):(?!\/)(.+)$/.exec(e);if(/^[a-z+]+:\/\//i.test(e)){let r;try{r=new URL(e)}catch{return null}if(r.protocol===`file:`)return null;t=r.hostname,n=r.pathname}else if(r?.[1]&&r[2])t=r[1],n=r[2];else return null;if(n=n.replace(/^\/+/,``).replace(/\/+$/,``).replace(/\.git$/,``),!t||!n)return null;let i=t.toLowerCase(),a=i.includes(`github`)?`github`:i.includes(`gitlab`)?`gitlab`:null;return{name:n.slice(n.lastIndexOf(`/`)+1),provider:a,url:`https://${i}/${n}`}}const GC={ts:`TypeScript`,tsx:`TypeScript`,mts:`TypeScript`,cts:`TypeScript`,js:`JavaScript`,jsx:`JavaScript`,mjs:`JavaScript`,cjs:`JavaScript`,py:`Python`,go:`Go`,rb:`Ruby`,php:`PHP`,java:`Java`,kt:`Kotlin`,kts:`Kotlin`,swift:`Swift`,rs:`Rust`,cs:`C#`,fs:`F#`,c:`C`,h:`C`,cc:`C++`,cpp:`C++`,cxx:`C++`,hpp:`C++`,m:`Objective-C`,mm:`Objective-C++`,scala:`Scala`,dart:`Dart`,ex:`Elixir`,exs:`Elixir`,erl:`Erlang`,clj:`Clojure`,hs:`Haskell`,ml:`OCaml`,lua:`Lua`,r:`R`,pl:`Perl`,groovy:`Groovy`,zig:`Zig`,sol:`Solidity`,sql:`SQL`,sh:`Shell`,bash:`Shell`,zsh:`Shell`,ps1:`PowerShell`,tf:`HCL`,vue:`Vue`,svelte:`Svelte`,astro:`Astro`,html:`HTML`,css:`CSS`,scss:`SCSS`,sass:`SCSS`,less:`Less`};function KC(e){let t=/* @__PURE__ */ new Map;for(let n of e){let e=n.path.lastIndexOf(`.`);if(e===-1||e<n.path.lastIndexOf(`/`))continue;let r=GC[n.path.slice(e+1).toLowerCase()];r&&t.set(r,(t.get(r)??0)+1)}return[...t.entries()].sort((e,t)=>t[1]-e[1]||e[0].localeCompare(t[0])).slice(0,5).map(([e])=>e)}const qC=/* @__PURE__ */ new Set([`auth`,`storage`,`realtime`,`_realtime`,`extensions`,`graphql`,`graphql_public`,`supabase_functions`,`supabase_migrations`,`pgsodium`,`pgsodium_masks`,`vault`,`net`,`cron`,`pgbouncer`,`pg_catalog`,`information_schema`]),JC=/^(not|null|default|primary|unique|references|check|constraint|generated|collate|deferrable|initially|identity)$/i;function YC(e){if(!/\.sql$/i.test(e))return!1;let t=e.toLowerCase();return/(^|\/)migrations\//.test(t)||/(^|\/)db\/migrate\//.test(t)}async function XC(e){let t=/* @__PURE__ */ new Map,n=e.files.filter(e=>YC(e.path));n.sort((e,t)=>{let n=e.path.slice(e.path.lastIndexOf(`/`)+1),r=t.path.slice(t.path.lastIndexOf(`/`)+1);return n<r?-1:n>r?1:e.path<t.path?-1:1});for(let r of n){let n=await e.readText(r);if(n!==null)for(let i of ZC(n))try{aw(i,r.path,t,e.warnings)}catch(t){e.warnings.push(`${r.path}: could not read statement "${hw(i)}" (${t instanceof Error?t.message:String(t)})`)}}return[...t.values()].filter(e=>!qC.has(e.schema)).map(e=>{let t=e.schema===`public`?e.table:`${e.schema}.${e.table}`;return{kind:`table`,name:t,sourcePath:e.sourcePath,table:t,columns:e.columns}})}function ZC(e){let t=[],n=``,r=0;for(;r<e.length;){let i=e[r],a=e[r+1];if(i===`-`&&a===`-`){let t=e.indexOf(`
338
+ `,r);r=t===-1?e.length:t,n+=` `}else if(i===`/`&&a===`*`){let t=1;for(r+=2;r<e.length&&t>0;)e.startsWith(`/*`,r)?(t++,r+=2):e.startsWith(`*/`,r)?(t--,r+=2):r++;n+=` `}else if(i===`'`||i===`"`){let t=r+1;for(;t<e.length;)if(e[t]===i){if(e[t+1]===i)t+=2;else break}else t++;n+=e.slice(r,t+1),r=t+1}else{if(i===`$`){let t=/^\$[A-Za-z_]?[A-Za-z0-9_]*\$/.exec(e.slice(r,r+64))?.[0];if(t){let i=e.indexOf(t,r+t.length),a=i===-1?e.length:i+t.length;n+=e.slice(r,a),r=a;continue}}i===`;`?(n.trim()&&t.push(n.trim()),n=``,r++):(n+=i,r++)}}return n.trim()&&t.push(n.trim()),t.map(e=>e.replace(/\s+/g,` `))}function QC(e){let t=[],n=0,r=null,i=0;for(let a=0;a<e.length;a++){let o=e[a];r?o===r&&(r=null):o===`'`||o===`"`?r=o:o===`(`?n++:o===`)`?n--:o===`,`&&n===0&&(t.push(e.slice(i,a).trim()),i=a+1)}return t.push(e.slice(i).trim()),t.filter(Boolean)}function $C(e){let t=[],n=0;for(;n<e.length;){let r=e[n];if(/\s/.test(r)){n++;continue}if(r===`(`){let r=0,i=n,a=null;for(;i<e.length;i++){let t=e[i];if(a)t===a&&(a=null);else if(t===`'`||t===`"`)a=t;else if(t===`(`)r++;else if(t===`)`&&--r===0)break}t.push(e.slice(n,i+1)),n=i+1;continue}let i=n,a=null;for(;i<e.length;i++){let t=e[i];if(a)t===a&&(a=null);else if(t===`'`||t===`"`)a=t;else if(/\s/.test(t)||t===`(`)break}t.push(e.slice(n,i)),n=i}return t}const ew=String.raw`(?:"(?:[^"]|"")+"|[A-Za-z_][\w$]*)`,tw=String.raw`(${ew}(?:\s*\.\s*${ew})?)`;function nw(e){let t=e.trim();return t.startsWith(`"`)?t.slice(1,-1).replace(/""/g,`"`):t.toLowerCase()}function rw(e){let t=e.match(new RegExp(ew,`g`))??[e];return t.length>=2?{schema:nw(t[0]??``),table:nw(t[1]??``)}:{schema:`public`,table:nw(t[0]??e)}}function iw(e,t){return`${e}.${t}`}function aw(e,t,n,r){if(/^create\s+(?:(?:global|local)\s+)?(?:temp(?:orary)?\s+|unlogged\s+)?table\b/i.test(e)){ow(e,t,n,r);return}let i=new RegExp(String.raw`^alter\s+table\s+(?:if\s+exists\s+)?(?:only\s+)?${tw}\s+(.+)$`,`i`).exec(e);if(i?.[1]&&i[2]){pw(rw(i[1]),i[2],t,n,r);return}let a=/^drop\s+table\s+(?:if\s+exists\s+)?(.+?)(?:\s+(?:cascade|restrict))?$/i.exec(e);if(a?.[1])for(let e of QC(a[1])){let{schema:t,table:r}=rw(e);n.delete(iw(t,r))}}function ow(e,t,n,r){let i=new RegExp(String.raw`^create\s+(?:(?:global|local)\s+)?(?:temp(?:orary)?\s+|unlogged\s+)?table\s+(?:if\s+not\s+exists\s+)?${tw}\s*\(`,`i`).exec(e);if(!i?.[1]){r.push(`${t}: skipped a create table statement it couldn't read: "${hw(e)}"`);return}let{schema:a,table:o}=rw(i[1]),s=i[0].length-1,c=sw(e,s);if(c===-1){r.push(`${t}: unbalanced parentheses in create table ${o}`);return}let l=iw(a,o);if(n.has(l)&&/\bif\s+not\s+exists\b/i.test(e.slice(0,s)))return;let u={schema:a,table:o,sourcePath:t,columns:[]};for(let i of QC(e.slice(s+1,c))){if(/^(constraint|primary\s+key|unique|foreign\s+key|check|exclude|like)\b/i.test(i)){fw(u,i,n);continue}let e=cw(i,n);e?u.columns.push(e):r.push(`${t}: skipped column definition "${hw(i)}" in ${o}`)}n.set(l,u)}function sw(e,t){let n=0,r=null;for(let i=t;i<e.length;i++){let t=e[i];if(r)t===r&&(r=null);else if(t===`'`||t===`"`)r=t;else if(t===`(`)n++;else if(t===`)`&&--n===0)return i}return-1}function cw(e,t){let n=$C(e),r=n[0];if(!r||n.length<2)return null;let i=1,a=[];for(;i<n.length&&!JC.test(n[i]??``);)a.push(n[i]),i++;if(a.length===0)return null;let o={name:nw(r),type:a.join(` `).replace(/\s+\(/g,`(`).toLowerCase(),required:!1};return lw(o,n.slice(i),t),o}function lw(e,t,n){for(let r=0;r<t.length;r++){let i=t[r]?.toLowerCase(),a=t[r+1]?.toLowerCase();if(i===`not`&&a===`null`)e.required=!0,r++;else if(i===`primary`&&a===`key`)e.primaryKey=!0,e.required=!0,r++;else if(i===`unique`)e.unique=!0;else if(i==="default"){let n=[];for(;r+1<t.length&&!JC.test(t[r+1]??``);)n.push(t[r+1]),r++;n.length>0&&(e.default=uw(n))}else if(i===`references`){let i=t[r+1];if(!i)continue;let a=t[r+2]?.startsWith(`(`)?t[r+2]:void 0;e.references=dw(i,a,n),r+=a?2:1}}}function uw(e){return e.join(` `).replace(/\s+\(/g,`(`)}function dw(e,t,n){let{schema:r,table:i}=rw(e),a=r===`public`?i:`${r}.${i}`,o=t?nw(t.slice(1,-1).split(`,`)[0]??``):null;return o||=n.get(iw(r,i))?.columns.find(e=>e.primaryKey)?.name??`id`,`${a}.${o}`}function fw(e,t,n){let r=t.replace(new RegExp(String.raw`^constraint\s+${ew}\s+`,`i`),``),i=e=>(e??``).split(`,`).map(e=>nw(e)).filter(Boolean),a=/^primary\s+key\s*\(([^)]*)\)/i.exec(r);if(a){for(let t of i(a[1])){let n=e.columns.find(e=>e.name===t);n&&(n.primaryKey=!0,n.required=!0)}return}let o=/^unique\s*(?:nulls\s+(?:not\s+)?distinct\s*)?\(([^)]*)\)/i.exec(r);if(o){let t=i(o[1]),n=t.length===1?e.columns.find(e=>e.name===t[0]):void 0;n&&(n.unique=!0);return}let s=new RegExp(String.raw`^foreign\s+key\s*\(([^)]*)\)\s*references\s+${tw}\s*(\([^)]*\))?`,`i`).exec(r);if(s?.[2]){let t=i(s[1]),r=s[3]?i(s[3].slice(1,-1)):[];t.forEach((t,i)=>{let a=e.columns.find(e=>e.name===t);if(!a)return;let o=r[i];a.references=dw(s[2],o?`(${o})`:void 0,n)})}}function pw(e,t,n,r,i){let a=r.get(iw(e.schema,e.table));if(!a){!qC.has(e.schema)&&/\b(add|drop|alter|rename)\s+column\b/i.test(t)&&i.push(`${n}: alter table ${e.table} before any create table for it, skipped`);return}let o=new RegExp(String.raw`^rename\s+to\s+(${ew})$`,`i`).exec(t);if(o?.[1]){r.delete(iw(a.schema,a.table)),a.table=nw(o[1]),r.set(iw(a.schema,a.table),a);return}let s=new RegExp(String.raw`^rename\s+(?:column\s+)?(${ew})\s+to\s+(${ew})$`,`i`).exec(t);if(s?.[1]&&s[2]){let e=a.columns.find(e=>e.name===nw(s[1]));e&&(e.name=nw(s[2]))}else for(let e of QC(t)){let t=/^add\s+(?:column\s+)?(?:if\s+not\s+exists\s+)?(.+)$/i.exec(e);if(t?.[1]&&!/^add\s+(constraint|primary|unique|foreign|check|exclude)\b/i.test(e)){let o=cw(t[1],r);if(!o){i.push(`${n}: skipped "${hw(e)}" on ${a.table}`);continue}a.columns.some(e=>e.name===o.name)||a.columns.push(o);continue}let o=/^add\s+(.+)$/i.exec(e);if(o?.[1]){fw(a,o[1],r);continue}let s=new RegExp(String.raw`^drop\s+(?:column\s+)?(?:if\s+exists\s+)?(${ew})`,`i`).exec(e);if(s?.[1]&&!/^drop\s+constraint\b/i.test(e)){let e=nw(s[1]);a.columns=a.columns.filter(t=>t.name!==e);continue}let c=new RegExp(String.raw`^alter\s+(?:column\s+)?(${ew})\s+(.+)$`,`i`).exec(e);if(c?.[1]&&c[2]){let e=a.columns.find(e=>e.name===nw(c[1]));e&&mw(e,c[2])}}}function mw(e,t){if(/^set\s+not\s+null$/i.test(t))e.required=!0;else if(/^drop\s+not\s+null$/i.test(t))e.required=!!e.primaryKey;else if(/^drop\s+default$/i.test(t))delete e.default;else{let n=/^set\s+default\s+(.+)$/i.exec(t);if(n?.[1]){e.default=uw($C(n[1]));return}let r=/^(?:set\s+data\s+)?type\s+(.+?)(?:\s+(?:using|collate)\s+.*)?$/i.exec(t);r?.[1]&&(e.type=r[1].replace(/\s+\(/g,`(`).toLowerCase())}}function hw(e){return e.length>60?`${e.slice(0,57)}...`:e}const gw=[`GET`,`POST`,`PUT`,`PATCH`,`DELETE`],_w=/^(openapi|swagger)([.-][\w.-]*)?\.(json|ya?ml)$/i,vw=/\.(json|ya?ml)$/i;async function yw(e){let t=[];for(let n of e.files){let r=_w.test(rx(n.path));if(!r&&!vw.test(n.path)||!r&&(n.size>1048576||/(^|\/)[^/]*lock[^/]*$/i.test(n.path)))continue;let i=await e.readText(n,r?10485760:void 0);if(i===null||!r&&!/^\s*["']?(openapi|swagger)["']?\s*:/m.test(i))continue;let a;try{a=/\.json$/i.test(n.path)?JSON.parse(i):(0,wC.parse)(i)}catch(t){e.warnings.push(`${n.path}: OpenAPI file could not be parsed (${ox(t)})`);continue}!Q(a)||typeof a.openapi!=`string`&&typeof a.swagger!=`string`?r&&e.warnings.push(`${n.path}: no top-level openapi or swagger version, skipped`):t.push(...bw(a,n.path,e.warnings))}return t}function bw(e,t,n){let r=typeof e.swagger==`string`,i=new xw(e,t,n),a=r?e.securityDefinitions:Cw(e.components)?.securitySchemes,o=Q(a)?a:{},s=Q(e.paths)?e.paths:{},c=[];for(let[n,a]of Object.entries(s)){let s=i.resolve(a);if(s)for(let a of gw){let l=Cw(s[a.toLowerCase()]);if(!l)continue;let u=[...Array.isArray(s.parameters)?s.parameters:[],...Array.isArray(l.parameters)?l.parameters:[]],d=l.security??e.security;c.push({kind:`endpoint`,name:sx(l.summary)?.trim()||sx(l.operationId)||`${a} ${n}`,sourcePath:t,method:a,path:n,auth:Lw(d,o,i),request:r?Ow(u,l,e,i):Tw(l.requestBody,i),responses:kw(l,e,r,i)})}}return c}var xw=class{#e;#t;#n;#r=/* @__PURE__ */ new Set;constructor(e,t,n){this.#e=e,this.#t=t,this.#n=n}resolve(e){let t=e;for(let e=0;e<8;e++){if(!Q(t))return null;let e=t.$ref;if(typeof e!=`string`)return t;t=this.#i(e)}return null}refName(e){if(!Q(e)||typeof e.$ref!=`string`)return null;let t=e.$ref.slice(e.$ref.lastIndexOf(`/`)+1);return t?Sw(t):null}#i(e){if(!e.startsWith(`#/`))return this.#r.has(e)||(this.#r.add(e),this.#n.push(`${this.#t}: external $ref "${e}" not followed`)),null;let t=this.#e;for(let n of e.slice(2).split(`/`)){if(!Q(t))break;t=t[Sw(n)]}return t===void 0&&!this.#r.has(e)&&(this.#r.add(e),this.#n.push(`${this.#t}: $ref "${e}" points at nothing`)),t}};function Sw(e){return decodeURIComponent(e).replace(/~1/g,`/`).replace(/~0/g,`~`)}function Cw(e){return Q(e)?e:null}function ww(e){if(!Q(e))return null;let t=Object.entries(e).filter(e=>Q(e[1]));return t.find(([e])=>e===`application/json`)??t.find(([e])=>/json/.test(e))??t[0]??null}function Tw(e,t){let n=t.resolve(e),r=n?ww(n.content):null;return r?Ew(r[0],r[1],t):null}function Ew(e,t,n){let r=t.schema;return{contentType:e,fields:Nw(r,n),example:Dw(t,n)??Iw(r,n,0)}}function Dw(e,t){if(e.example!==void 0)return e.example;if(Q(e.examples)){let n=t.resolve(Object.values(e.examples)[0]);if(n&&n.value!==void 0)return n.value}}function Ow(e,t,n,r){let i=e.map(e=>r.resolve(e)).filter(e=>e!==null),a=jw(t.consumes)??jw(n.consumes),o=i.find(e=>e.in===`body`);if(o)return{contentType:a??`application/json`,fields:Nw(o.schema,r),example:Iw(o.schema,r,0)};let s=i.filter(e=>e.in===`formData`);if(s.length===0)return null;let c=s.map(e=>({name:sx(e.name)??``,type:Fw(e,r),required:e.required===!0,...Pw(e)}));return{contentType:a??`application/x-www-form-urlencoded`,fields:c,example:Object.fromEntries(s.map(e=>[sx(e.name)??``,Iw(e,r,1)]))}}function kw(e,t,n,r){if(!Q(e.responses))return[];let i=jw(e.produces)??jw(t.produces)??`application/json`,a=[];for(let[t,o]of Object.entries(e.responses)){let e=r.resolve(o);if(!e)continue;let s=null;if(n){if(e.schema!==void 0){let t=Cw(e.examples);s={contentType:i,fields:Nw(e.schema,r),example:t?.[i]??Iw(e.schema,r,0)}}}else{let t=ww(e.content);t&&(s=Ew(t[0],t[1],r))}a.push({status:Aw(t),description:sx(e.description)??``,body:s})}return a}function Aw(e){let t=e.replace(/x/gi,`0`),n=Number.parseInt(t,10);return Number.isNaN(n)?0:n}function jw(e){return Array.isArray(e)&&typeof e[0]==`string`?e[0]:void 0}function Mw(e,t,n=0){let r=t.resolve(e);if(!r||n>8)return r;if(Array.isArray(r.allOf)){let e={},i=[];for(let a of r.allOf){let r=Mw(a,t,n+1);r&&(Q(r.properties)&&Object.assign(e,r.properties),Array.isArray(r.required)&&i.push(...r.required.filter(e=>typeof e==`string`)))}return Q(r.properties)&&Object.assign(e,r.properties),Array.isArray(r.required)&&i.push(...r.required.filter(e=>typeof e==`string`)),{...r,type:`object`,properties:e,required:i}}let i=Array.isArray(r.oneOf)?r.oneOf:Array.isArray(r.anyOf)?r.anyOf:null;return i&&i.length>0&&!r.properties?Mw(i[0],t,n+1):r}function Nw(e,t){let n=Mw(e,t);if(n?.type===`array`&&(n=Mw(n.items,t)),!n||!Q(n.properties))return[];let r=new Set(Array.isArray(n.required)?n.required:[]);return Object.entries(n.properties).map(([e,n])=>{let i=Mw(n,t)??{};return{name:e,type:Fw(n,t),required:r.has(e),...Pw(i)}})}function Pw(e){let t={},n=sx(e.description)?.trim();return n&&(t.description=n),Array.isArray(e.enum)&&(t.values=e.enum.map(e=>String(e))),t}function Fw(e,t,n=0){let r=t.refName(e),i=Mw(e,t);if(!i)return r??`unknown`;let a=Array.isArray(i.type)?i.type.filter(e=>e!==`null`).join(` | `):sx(i.type);return a===`array`?n>8?`array`:`${Fw(i.items,t,n+1)}[]`:r&&(a===`object`||a===void 0)?r:sx(i.format)??a??(i.properties?`object`:`unknown`)}function Iw(e,t,n){let r=Mw(e,t);if(!r||n>8)return null;if(r.example!==void 0)return r.example;if(Array.isArray(r.enum)&&r.enum.length>0)return r.enum[0];let i=Array.isArray(r.type)?r.type.find(e=>e!==`null`):r.type;if(i===`object`||i===void 0&&Q(r.properties)){let e=Q(r.properties)?r.properties:{};return Object.fromEntries(Object.entries(e).map(([e,r])=>[e,Iw(r,t,n+1)]))}switch(i){case`array`:return[Iw(r.items,t,n+1)];case`string`:return`string`;case`integer`:case`number`:return 0;case`boolean`:return!1;default:return null}}function Lw(e,t,n){if(!Array.isArray(e)||e.length===0)return null;let r=[];for(let i of e){if(!Q(i))continue;let e=Object.keys(i);e.length===0?r.push(`none`):r.push(e.map(e=>Rw(e,n.resolve(t[e]))).join(` + `))}let i=[...new Set(r)];return i.length===0||i.length===1&&i[0]===`none`?null:i.map(e=>e===`none`?`no auth`:e).join(` or `)}function Rw(e,t){if(!t)return e;switch(sx(t.type)?.toLowerCase()){case`http`:{let e=sx(t.scheme)?.toLowerCase();if(e===`bearer`){let e=sx(t.bearerFormat);return e?`Bearer token (${e})`:`Bearer token`}return e===`basic`?`Basic auth`:`HTTP ${e??`auth`}`}case`basic`:return`Basic auth`;case`apikey`:return`apikey ${sx(t.in)??`header`} ${sx(t.name)??e}`;case`oauth2`:return`OAuth2`;case`openidconnect`:return`OpenID Connect`;case`mutualtls`:return`Mutual TLS`;default:return e}}const zw=[`readme.md`,`readme.mdx`,`readme.markdown`,`readme.txt`,`readme`];async function Bw(e){let t=e.files.find(e=>!e.path.includes(`/`)&&zw.includes(e.path.toLowerCase()));if(!t)return null;let n=await e.readText(t);return{path:t.path,oneLiner:n===null?null:Vw(n)}}function Vw(e){let t=e.replace(/\r\n/g,`
339
+ `).replace(/^---\n[\s\S]*?\n---\n/,``).replace(/<!--[\s\S]*?-->/g,``).replace(/^(```|~~~)[\s\S]*?^\1.*$/gm,``);for(let e of t.split(/\n\s*\n/)){let t=e.split(`
340
+ `).map(e=>e.trim()).filter(Boolean),n=t[0];if(!n||/^(#|=+$|-+$|\||[-*+] |\d+\. |>|<|\[!\[|!\[)/.test(n)||/^ {4}|^\t/.test(e))continue;let r=Hw(t.join(` `));if(!(r.length<15||!/[a-z]/i.test(r)))return Uw(/^.+?[.!?](?=\s+["'([]?[A-Z]|\s*$)/.exec(r)?.[0]??r,200)}return null}function Hw(e){return e.replace(/!\[[^\]]*\]\([^)]*\)/g,``).replace(/\[([^\]]*)\]\([^)]*\)/g,`$1`).replace(/\[([^\]]*)\]\[[^\]]*\]/g,`$1`).replace(/<[^>]+>/g,``).replace(/`([^`]*)`/g,`$1`).replace(/(\*\*|__)(.*?)\1/g,`$2`).replace(/(^|\W)[*_](\S(?:.*?\S)?)[*_](?=\W|$)/g,`$1$2`).replace(/\s+/g,` `).trim()}function Uw(e,t){if(e.length<=t)return e;let n=e.slice(0,t-1),r=n.lastIndexOf(` `);return`${(r>t/2?n.slice(0,r):n).trimEnd()}…`}const Ww={name:`Supabase`,type:`database`,provider:`Supabase Postgres`},Gw={name:`Postgres`,type:`database`,provider:`Postgres`},Kw={name:`MySQL`,type:`database`,provider:`MySQL`},qw={name:`MongoDB`,type:`database`,provider:`MongoDB`},Jw={name:`Redis`,type:`database`,provider:`Redis`},Yw={name:`Elasticsearch`,type:`database`,provider:`Elasticsearch`},Xw={name:`AWS S3`,type:`storage`,provider:`AWS S3`},Zw={name:`AWS SQS`,type:`queue`,provider:`AWS SQS`},Qw={name:`AWS`,type:`service`,provider:`AWS`},$w={name:`MinIO`,type:`storage`,provider:`MinIO`},eT={name:`Cloudinary`,type:`storage`,provider:`Cloudinary`},tT={name:`RabbitMQ`,type:`queue`,provider:`RabbitMQ`},nT={name:`Kafka`,type:`queue`,provider:`Kafka`},rT={name:`Stripe`,type:`external_api`,provider:`Stripe`},iT={name:`Twilio`,type:`external_api`,provider:`Twilio`},aT={name:`SendGrid`,type:`service`,provider:`SendGrid`},oT={name:`Postmark`,type:`service`,provider:`Postmark`},sT={name:`Resend`,type:`service`,provider:`Resend`},cT={name:`Mailgun`,type:`service`,provider:`Mailgun`},lT={name:`Email (SMTP)`,type:`service`,provider:`SMTP`},uT={name:`Firebase`,type:`service`,provider:`Firebase`},dT={name:`OpenAI`,type:`external_api`,provider:`OpenAI`},fT={name:`Anthropic`,type:`external_api`,provider:`Anthropic`},pT={name:`Sentry`,type:`service`,provider:`Sentry`},mT={name:`Auth0`,type:`auth`,provider:`Auth0`},hT={name:`Clerk`,type:`auth`,provider:`Clerk`},gT={name:`Auth.js`,type:`auth`,provider:`Auth.js`},_T={name:`Algolia`,type:`external_api`,provider:`Algolia`},vT=[[/^SUPABASE_/,Ww],[/^(DATABASE_URL|POSTGRES_|PG(HOST|USER|PASSWORD|DATABASE|PORT)$)/,Gw],[/^MYSQL_/,Kw],[/^MONGO(DB)?_/,qw],[/^(REDIS_|UPSTASH_REDIS_)/,Jw],[/^(ELASTIC(SEARCH)?_)/,Yw],[/^(AWS_)?S3_|_S3_BUCKET$|^AWS_BUCKET/,Xw],[/^(AWS_)?SQS_/,Zw],[/^AWS_(ACCESS_KEY_ID|SECRET_ACCESS_KEY|REGION|DEFAULT_REGION)$/,Qw],[/^MINIO_/,$w],[/^CLOUDINARY_/,eT],[/^(RABBITMQ_|AMQP_URL)/,tT],[/^KAFKA_/,nT],[/^STRIPE_/,rT],[/^TWILIO_/,iT],[/^SENDGRID_/,aT],[/^POSTMARK_/,oT],[/^RESEND_/,sT],[/^MAILGUN_/,cT],[/^SMTP_/,lT],[/^FIREBASE_/,uT],[/^OPENAI_/,dT],[/^ANTHROPIC_/,fT],[/^SENTRY_/,pT],[/^AUTH0_/,mT],[/^CLERK_/,hT],[/^(NEXTAUTH_|AUTH_SECRET$)/,gT],[/^ALGOLIA_/,_T]],yT=[[[`@supabase/supabase-js`,`@supabase/ssr`,`supabase`,`github.com/supabase-community/*`,`supabase/supabase-php`],Ww],[[`pg`,`postgres`,`pg-promise`,`@neondatabase/serverless`,`@vercel/postgres`,`psycopg2`,`psycopg2-binary`,`psycopg`,`asyncpg`,`github.com/jackc/pgx*`,`github.com/lib/pq`],Gw],[[`mysql`,`mysql2`,`pymysql`,`mysqlclient`,`github.com/go-sql-driver/mysql`],Kw],[[`mongodb`,`mongoose`,`pymongo`,`motor`,`go.mongodb.org/mongo-driver*`,`mongodb/mongodb`],qw],[[`redis`,`ioredis`,`@upstash/redis`,`predis/predis`,`github.com/redis/go-redis*`,`github.com/go-redis/redis*`],Jw],[[`@elastic/elasticsearch`,`elasticsearch`,`elasticsearch/elasticsearch`],Yw],[[`@aws-sdk/client-s3`,`github.com/aws/aws-sdk-go-v2/service/s3`,`league/flysystem-aws-s3-v3`],Xw],[[`@aws-sdk/client-sqs`,`github.com/aws/aws-sdk-go-v2/service/sqs`],Zw],[[`aws-sdk`,`boto3`,`aws/aws-sdk-php`,`github.com/aws/aws-sdk-go`],Qw],[[`minio`],$w],[[`cloudinary`,`cloudinary/cloudinary_php`],eT],[[`amqplib`,`pika`,`php-amqplib/php-amqplib`,`github.com/rabbitmq/amqp091-go`],tT],[[`kafkajs`,`kafka-python`,`confluent-kafka`,`github.com/segmentio/kafka-go`],nT],[[`stripe`,`@stripe/stripe-js`,`@stripe/react-stripe-js`,`stripe/stripe-php`,`github.com/stripe/stripe-go*`],rT],[[`twilio`,`twilio/sdk`,`github.com/twilio/twilio-go`],iT],[[`@sendgrid/`,`sendgrid`,`sendgrid/sendgrid`],aT],[[`postmark`,`wildbit/postmark-php`],oT],[[`resend`,`resend/resend-php`],sT],[[`mailgun.js`,`mailgun/mailgun-php`],cT],[[`nodemailer`],lT],[[`firebase`,`firebase-admin`,`kreait/firebase-php`,`firebase.google.com/go*`],uT],[[`openai`,`openai-php/client`,`github.com/sashabaranov/go-openai`],dT],[[`@anthropic-ai/sdk`,`anthropic`,`github.com/anthropics/anthropic-sdk-go`],fT],[[`@sentry/`,`sentry-sdk`,`sentry/sentry`,`sentry/sentry-laravel`,`github.com/getsentry/sentry-go`],pT],[[`@auth0/`,`auth0`,`auth0/auth0-php`],mT],[[`@clerk/`],hT],[[`next-auth`,`@auth/`],gT],[[`algoliasearch`,`algolia/algoliasearch-client-php`],_T]],bT=[[/^supabase\//,Ww],[/(^|\/)(postgres|postgis|timescaledb)$/,Gw],[/(^|\/)(mysql|mariadb)$/,Kw],[/(^|\/)mongo(db)?$/,qw],[/(^|\/)(redis|redis-stack|valkey)$/,Jw],[/(^|\/)(elasticsearch|opensearch)$/,Yw],[/(^|\/)minio$/,$w],[/(^|\/)rabbitmq$/,tT],[/(^|\/)(kafka|cp-kafka)$/,nT],[/(^|\/)localstack$/,Qw]];function xT(e){return/^\.env(\.[\w-]+)*\.(example|sample|template|dist)$/i.test(e)||/^(example|sample)\.env$/i.test(e)}function ST(e){return/^(docker-)?compose([.-][\w.-]+)?\.ya?ml$/i.test(e)}var CT=class{#e=/* @__PURE__ */ new Map;add(e,t){let n=this.#e.get(e.provider);n?n.evidence.includes(t)||n.evidence.push(t):this.#e.set(e.provider,{...e,evidence:[t]})}list(){return[...this.#e.values()].sort((e,t)=>e.name.localeCompare(t.name))}};async function wT(e,t){let n=new CT;for(let t of e.files){let r=rx(t.path);if(xT(r)){let r=await e.readText(t);if(r===null)continue;for(let e of TT(r)){let r=e.replace(/^(NEXT_PUBLIC_|VITE_|PUBLIC_|REACT_APP_|EXPO_PUBLIC_|NUXT_PUBLIC_|NUXT_)/,``),i=vT.find(([e])=>e.test(r));i&&n.add(i[1],`env: ${e} (${t.path})`)}}else if(ST(r)){let r=await e.readText(t);if(r===null)continue;let i;try{i=(0,wC.parse)(r)}catch(n){e.warnings.push(`${t.path}: could not be parsed (${ox(n)})`);continue}let a=Q(i)&&Q(i.services)?i.services:{};for(let[e,r]of Object.entries(a)){if(!Q(r)||typeof r.image!=`string`)continue;let i=ET(r.image),a=bT.find(([e])=>e.test(i));a&&n.add(a[1],`docker-compose: service ${e} (${r.image}) in ${t.path}`)}}else(t.path===`supabase/config.toml`||t.path.endsWith(`/supabase/config.toml`))&&n.add(Ww,`file: ${t.path}`)}for(let e of t){if(!e.direct)continue;let t=yT.find(([t])=>t.some(t=>DT(t,e.package)));t&&n.add(t[1],`dependency: ${e.package} (${e.sourceLockfile})`)}return n.list()}function TT(e){let t=[];for(let n of e.split(/\r?\n/)){let e=/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/.exec(n);e?.[1]&&t.push(e[1])}return t}function ET(e){let t=e.toLowerCase().replace(/@.*$/,``),n=t.lastIndexOf(`/`),r=t.indexOf(`:`,n+1);r!==-1&&(t=t.slice(0,r));let i=t.split(`/`);return i.length>1&&/[.:]|^localhost$/.test(i[0]??``)&&i.shift(),i[0]===`library`&&i.shift(),i.join(`/`)}function DT(e,t){return e.endsWith(`*`)?t.startsWith(e.slice(0,-1)):e.endsWith(`/`)?t.startsWith(e):t===e}async function OT(e){let t=_.resolve(e);if(!(await p(t)).isDirectory())throw Error(`${t} is not a folder`);let n=(/* @__PURE__ */ new Date()).toISOString(),r=await ex(t),i=[],[a,o,s,c,l,u,d]=await Promise.all([UC(t,i),Bw(r),zC(r),Gx(r),Qx(r),yw(r),XC(r)]),f=await wT(r,s);return{scannedAt:n,root:t,repo:{...a,languages:KC(r.files),readme:o},dependencies:s,docs:c,agentInstructions:l,contracts:[...u,...d],resources:f,warnings:[...i,...r.warnings]}}function kT(e){let t=(e,t,n=`${t}s`)=>e?`${e} ${e===1?t:n}`:``;return[t(e.docs,`doc`)+(e.docsChanged&&e.docsChanged<e.docs?` (${e.docsChanged} changed)`:``),t(e.dependencies,`dependency`,`dependencies`),t(e.contracts,`contract`),t(e.resources,`service`)].filter(Boolean).join(` · `)||`nothing to import yet`}async function AT(e,t,{quiet:n=!1,source:r=`connector`}={}){let i=await OT(e),a=await new Ur(await Kb()).call(`sync_repo`,{p_project:t.projectId,p_snapshot:i,p_source:r});if(!n){_x(`Synced ${fx(i.repo.name)} to ${fx(t.name)}`),vx(px(kT(a)));for(let e of i.warnings)vx(px(`! ${e}`))}return{snapshot:i,result:a}}async function jT(e){return tS(await ex(e))}async function MT(e,t,{quiet:n=!1}={}){if(!t.folder)return;let{docs:r,unsupported:i}=await jT(e),a=await new Ur(await Kb()).call(`sync_folder`,{p_project:t.projectId,p_folder:t.folder,p_folder_name:v(e),p_docs:r});return n||(_x(`Synced the documents in ${fx(`${v(e)}/`)} outside the repos`),vx(px(`${a.docs} docs (${a.docsChanged} changed${a.archived?`, ${a.archived} removed`:``})`)),i.length&&vx(px(`! ${i.length} PDF/Office files skipped: only markdown and text are read for now`))),a}async function NT(e={}){let t=await Yb();if(!t)throw new Sx("This folder isn't linked to a Quirl project. Run `quirl init`.");let n=t.link.repos?.length?t.link.repos.map(e=>x(t.root,e)):[t.root],r=n.length+ +!!t.link.folder,i=0;for(let a of n)try{await AT(a,t.link,e)}catch(e){if(i++,r===1)throw e;let n=S(t.root,a)||`.`;console.error(`${hx(`✗`)} ${n}: ${e.message}`)}if(t.link.folder)try{await MT(t.root,t.link,e)}catch(e){i++,console.error(`${hx(`✗`)} documents in ${v(t.root)}/: ${e.message}`)}if(i)throw new Sx(`${i} of ${r} parts didn't sync.`)}async function PT(e){let t=qb(),n=await lx(t),r=n.length?n:[t],i=r.length>1||r[0]!==t,a=e=>S(t,e)||v(t),o=h(),s=t.startsWith(o)?`~${t.slice(o.length)}`:t;if(console.log(`\n🌀 ${fx(`Quirl`)} ${px(`·`)} connecting ${fx(s)}`),i&&(yx(`📁`,`Found ${r.length} ${r.length===1?`repo`:`repos`}`),bx(px(r.map(a).join(` · `))),!await wx(` Import all of them into one project?`,!0)))throw new Sx("Nothing imported. Run `quirl init` inside the repo you want instead.");let c=!1;if(i&&!n.includes(t)){let{docs:e,unsupported:n}=await jT(t);if(e.length){yx(`📄`,`Also found ${e.length} ${e.length===1?`document`:`documents`} outside the repos`);for(let t of e.slice(0,8))bx(px(t.path));e.length>8&&bx(px(`…and ${e.length-8} more`)),n.length&&bx(px(`(${n.length} PDF/Office files can't be read yet and are skipped)`)),c=await wx(` Import them too? Everyone on the project will be able to read them.`,!0)}}await Ub()||await zx({quiet:!0});let l=await IT((await new Ur(await Kb()).whoami()).projects,e.project??(await Yb(t))?.link.project);if(l.role===`stakeholder`)throw new Sx(`You're a stakeholder on ${l.name}; ask an admin or dev to run \`quirl init\`.`);let u={project:l.slug,projectId:l.id,name:l.name};yx(`🔗`,`Linked to ${fx(l.name)} ${px(`· ${l.organization}`)}`);let d=e.claude!==!1,f=e.hooks??await wx(` Sync with Quirl on every git push?`,!0);yx(`📦`,`Importing docs, dependencies and schemas`);let p=[];for(let e of r){let t=xx(`Reading ${a(e)}…`);try{await Xb(e,u);let{snapshot:n,result:r}=await AT(e,u,{quiet:!0});d&&await FT(e,l.name),f&&await Rx(e),t.stop(),bx(`${mx(`✓`)} ${fx(a(e))} ${px(kT(r))}`);for(let e of n.warnings)bx(px(` ! ${e}`));p.push(e)}catch(n){t.stop(),bx(`${hx(`✗`)} ${fx(a(e))} ${n.message}`)}}if(!p.length)throw new Sx(`No repo was imported.`);if(i){let e=p.map(a),n=await Yb(t),r={...u,repos:e,folder:c?n?.root===t&&n.link.folder||w():void 0};if(await Xb(t,r),c)try{let e=await MT(t,r,{quiet:!0});bx(`${mx(`✓`)} ${fx(`documents outside the repos`)} ${px(`${e?.docs??0} docs`)}`)}catch(e){bx(`${hx(`✗`)} ${fx(`documents outside the repos`)} ${e.message}`)}d&&!p.includes(t)&&await FT(t,l.name,e)}let m=kx().portable;d&&(yx(`🤖`,`Connected Claude Code`),bx(px(`.mcp.json the quirl tools`)),bx(px(`.claude/settings.json the briefing, loaded as each session starts`)),bx(px(`CLAUDE.md when to use Quirl`))),f&&yx(`🪝`,`Quirl syncs on every ${fx(`git push`)}`);let g=r.length-p.length,_=`.quirl .mcp.json .claude/settings.json CLAUDE.md`;yx(g?`⚠️ `:`🎉`,g?`Done, but ${g} of ${r.length} repos failed. Fix them and run ${fx(`quirl init`)} again.`:fx(`All set!`)),bx(d&&!m?px(`Don't commit ${_} yet: they point at this checkout until the CLI is installed.`):`${px(`1.`)} Commit what was added${i?` in each repo`:``}: ${gx(`git add ${_}`)}`),bx(`${px(d&&!m?`→`:`2.`)} Start Claude Code here and approve the ${fx(`quirl`)} server when it asks.`),i&&!p.includes(t)&&bx(px("Run `quirl sync` here to sync every repo at once.")),console.log(``)}async function FT(e,t,n=[]){await Fx(e),await Ix(e),await Lx(e,t,n)}async function IT(e,t){if(!e.length)throw new Sx(`You aren't on any Quirl project yet. Ask an admin to invite you.`);if(t){let n=e.find(e=>e.slug===t||e.id===t);if(!n)throw new Sx(`No project "${t}" among yours: ${e.map(e=>e.slug).join(`, `)}.`);return n}if(e.length===1)return e[0];yx(`🗂️ `,`Which project is this part of?`);for(let[t,n]of e.entries())bx(`${gx(String(t+1))} ${n.name} ${px(`· ${n.organization} · ${n.role}`)}`);let n=e[Number(await Cx(` Project [1-${e.length}]: `))-1];if(!n)throw new Sx("No project picked. Run `quirl init --project <slug>`.");return n}const LT=`${fx(`quirl`)} ${px(Lb)}: connect a repo to Quirl
341
+
342
+ quirl init [--project <slug>] [--hooks|--no-hooks] [--no-claude]
343
+ Link this repo, import it, and connect Claude Code
344
+ quirl sync Send the latest docs, dependencies and schemas
345
+ quirl context Print the project briefing agents load
346
+ quirl login Sign in with your browser
347
+ quirl logout Forget this machine's key
348
+ quirl whoami Show who you're signed in as
349
+ quirl mcp Run the MCP server (used by Claude Code)
350
+ `;async function RT(){let[e,...n]=process.argv.slice(2),{values:r}=t({args:n,allowNegative:!0,options:{project:{type:`string`},hooks:{type:`boolean`},claude:{type:`boolean`},quiet:{type:`boolean`},hook:{type:`boolean`},source:{type:`string`}}});switch(e){case`init`:return PT({project:r.project,hooks:r.hooks,claude:r.claude});case`sync`:return NT({quiet:r.quiet,source:r.source});case`context`:return Zb({hook:r.hook});case`login`:await zx();return;case`logout`:return await Gb(),_x(`Signed out on this machine.`),vx(px(`The key still exists until you revoke it under Organization > Access keys in Quirl (${zb().appUrl}).`));case`whoami`:{if(!await Ub())throw new Sx("Not signed in. Run `quirl login`.");let e=await new Ur(await Kb()).whoami();console.log(fx(e.email));for(let t of e.projects)vx(`${t.name} ${px(`${t.slug} · ${t.organization} · ${t.role}`)}`);let t=await Yb();t&&vx(px(`This folder: ${t.link.name}`));return}case`mcp`:{let e=await Yb();if(!e)throw new Sx("This folder isn't linked to a Quirl project. Run `quirl init`.");return Ib({...await Kb(),project:e.link.projectId,version:Lb})}case void 0:case`help`:case`--help`:case`-h`:process.stdout.write(LT);return;case`--version`:case`-v`:return console.log(Lb);default:throw new Sx(`Unknown command "${e}".\n\n${LT}`)}}RT().catch(e=>{let t=e instanceof Error?e.message:String(e);console.error(`${hx(`✗`)} ${t}`),process.exit(1)});export{};