quirl-cli 0.1.8 → 0.1.9
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/quirl.mjs +123 -123
- package/package.json +1 -1
package/dist/quirl.mjs
CHANGED
|
@@ -1,22 +1,22 @@
|
|
|
1
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{existsSync as C}from"node:fs";import{createInterface as w}from"node:readline/promises";import{createHash as T,randomUUID as ee}from"node:crypto";var te=Object.create,ne=Object.defineProperty,re=Object.getOwnPropertyDescriptor,ie=Object.getOwnPropertyNames,ae=Object.getPrototypeOf,oe=Object.prototype.hasOwnProperty,se=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},E=(e,t)=>()=>(t||(e((t={exports:{}}).exports,t,t.exports),e=null),t.exports),ce=(e,t)=>{let n={};for(var r in e)ne(n,r,{get:e[r],enumerable:!0});return t||ne(n,Symbol.toStringTag,{value:`Module`}),n},le=(e,t,n,r)=>{if(t&&typeof t==`object`||typeof t==`function`)for(var i=ie(t),a=0,o=i.length,s;a<o;a++)s=i[a],!oe.call(e,s)&&s!==n&&ne(e,s,{get:(e=>t[e]).bind(null,s),enumerable:!(r=re(t,s))||r.enumerable});return e},ue=(e,t,n)=>(n=e==null?{}:te(ae(e)),le(t||!e||!e.__esModule||!oe.call(e,`default`)?ne(n,`default`,{value:e,enumerable:!0}):n,e)),de=e=>oe.call(e,`module.exports`)?e[`module.exports`]:le(ne({},`__esModule`,{value:!0}),e),fe=/* @__PURE__ */ e(import.meta.url);const pe=Symbol.for(`@supabase/supabase-js.traceContextExtractor`);function me(){return globalThis[pe]}var he=/* @__PURE__ */ ce({__addDisposableResource:()=>Ue,__assign:()=>qe,__asyncDelegator:()=>Fe,__asyncGenerator:()=>Pe,__asyncValues:()=>Ie,__await:()=>Ne,__awaiter:()=>Te,__classPrivateFieldGet:()=>Be,__classPrivateFieldIn:()=>He,__classPrivateFieldSet:()=>Ve,__createBinding:()=>Je,__decorate:()=>ve,__disposeResources:()=>We,__esDecorate:()=>be,__exportStar:()=>De,__extends:()=>ge,__generator:()=>Ee,__importDefault:()=>ze,__importStar:()=>Re,__makeTemplateObject:()=>Le,__metadata:()=>we,__param:()=>ye,__propKey:()=>Se,__read:()=>ke,__rest:()=>_e,__rewriteRelativeImportExtension:()=>Ge,__runInitializers:()=>xe,__setFunctionName:()=>Ce,__spread:()=>Ae,__spreadArray:()=>Me,__spreadArrays:()=>je,__values:()=>Oe,default:()=>Qe});function ge(e,t){if(typeof t!=`function`&&t!==null)throw TypeError(`Class extends value `+String(t)+` is not a constructor or null`);Ke(e,t);function n(){this.constructor=e}e.prototype=t===null?Object.create(t):(n.prototype=t.prototype,new n)}function _e(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 ve(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 ye(e,t){return function(n,r){t(n,r,e)}}function be(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 xe(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 Se(e){return typeof e==`symbol`?e:`${e}`}function Ce(e,t,n){return typeof t==`symbol`&&(t=t.description?`[${t.description}]`:``),Object.defineProperty(e,"name",{configurable:!0,value:n?`${n} ${t}`:t})}function we(e,t){if(typeof Reflect==`object`&&typeof Reflect.metadata==`function`)return Reflect.metadata(e,t)}function Te(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 Ee(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 De(e,t){for(var n in e)n!=="default"&&!Object.prototype.hasOwnProperty.call(t,n)&&Je(t,e,n)}function Oe(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 ke(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 Ae(){for(var e=[],t=0;t<arguments.length;t++)e=e.concat(ke(arguments[t]));return e}function je(){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 Me(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 Ne(e){return this instanceof Ne?(this.v=e,this):new Ne(e)}function Pe(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 Ne?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 Fe(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:Ne(e[r](t)),done:!1}:i?i(t):t}:i}}function Ie(e){if(!Symbol.asyncIterator)throw TypeError(`Symbol.asyncIterator is not defined.`);var t=e[Symbol.asyncIterator],n;return t?t.call(e):(e=typeof Oe==`function`?Oe(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 Le(e,t){return Object.defineProperty?Object.defineProperty(e,"raw",{value:t}):e.raw=t,e}function Re(e){if(e&&e.__esModule)return e;var t={};if(e!=null)for(var n=Xe(e),r=0;r<n.length;r++)n[r]!=="default"&&Je(t,e,n[r]);return Ye(t,e),t}function ze(e){return e&&e.__esModule?e:{default:e}}function Be(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 Ve(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 He(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 Ue(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 We(e){function t(t){e.error=e.hasError?new Ze(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 Ge(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 Ke,qe,Je,Ye,Xe,Ze,Qe,$e=se((()=>{Ke=function(e,t){return Ke=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])},Ke(e,t)},qe=function(){return qe=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},qe.apply(this,arguments)},Je=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]}),Ye=Object.create?(function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}):function(e,t){e.default=t},Xe=function(e){return Xe=Object.getOwnPropertyNames||function(e){var t=[];for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[t.length]=n);return t},Xe(e)},Ze=typeof SuppressedError==`function`?SuppressedError:function(e,t,n){var r=Error(n);return r.name=`SuppressedError`,r.error=e,r.suppressed=t,r},Qe={__extends:ge,__assign:qe,__rest:_e,__decorate:ve,__param:ye,__esDecorate:be,__runInitializers:xe,__propKey:Se,__setFunctionName:Ce,__metadata:we,__awaiter:Te,__generator:Ee,__createBinding:Je,__exportStar:De,__values:Oe,__read:ke,__spread:Ae,__spreadArrays:je,__spreadArray:Me,__await:Ne,__asyncGenerator:Pe,__asyncDelegator:Fe,__asyncValues:Ie,__makeTemplateObject:Le,__importStar:Re,__importDefault:ze,__classPrivateFieldGet:Be,__classPrivateFieldSet:Ve,__classPrivateFieldIn:He,__addDisposableResource:Ue,__disposeResources:We,__rewriteRelativeImportExtension:Ge}})),et=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveFetch=void 0,e.resolveFetch=e=>e?(...t)=>e(...t):(...e)=>fetch(...e)})),tt=/* @__PURE__ */ E((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={}))})),nt=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.FunctionsClient=void 0;let t=($e(),de(he)),n=et(),r=tt();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))}})}}})),rt=(/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.FunctionRegion=e.FunctionsRelayError=e.FunctionsHttpError=e.FunctionsFetchError=e.FunctionsError=e.FunctionsClient=void 0;var t=nt();Object.defineProperty(e,"FunctionsClient",{enumerable:!0,get:function(){return t.FunctionsClient}});var n=tt();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}})})))(),it=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 at=e=>Math.min(1e3*2**e,3e4),ot=[520,503],st=[`GET`,`HEAD`,`OPTIONS`];function ct(e){"@babel/helpers - typeof";return ct=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},ct(e)}function lt(e,t){if(ct(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(ct(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function ut(e){var t=lt(e,`string`);return ct(t)==`symbol`?t:t+``}function dt(e,t,n){return(t=ut(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function ft(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 pt(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?ft(Object(n),!0).forEach(function(t){dt(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):ft(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}function mt(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 ht(e,t,n,r){return!(!r||n>=3||!st.includes(e)||!ot.includes(t))}async function gt(e,t,n,r){let i=0;for(;;){let a=pt({},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||!st.includes(n.method))throw e;if(r&&i<3){let e=at(i);i++,await mt(e,n.signal);continue}throw e}if(ht(n.method,o.status,i,r)){let e=o.headers?.get(`Retry-After`)??null,t=e===null?at(i):Math.max(0,parseInt(e,10)||0)*1e3;await o.text(),i++,await mt(t,n.signal)}else return o}}var _t=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 gt(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 it({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 it(pt(pt({},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 it(n)}return{success:n===null,error:n,data:r,count:i,status:a,statusText:o}}returns(){
|
|
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{existsSync as C}from"node:fs";import{createInterface as w}from"node:readline/promises";import{createHash as T,randomUUID as E}from"node:crypto";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
3
|
/* istanbul ignore next */
|
|
4
|
-
return this}overrideTypes(){return this}},vt=class extends _t{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 yt=/* @__PURE__ */ RegExp(`[,()]`);var bt=class extends vt{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`&&yt.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`&&yt.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}},xt=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 bt({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 bt({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 bt({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 bt({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 bt({method:`DELETE`,url:t,headers:n,schema:this.schema,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}};function St(e,t){try{let t=JSON.parse(e);if(t&&typeof t==`object`&&!Array.isArray(t))return new it({message:String(t.message??e),details:t.details??``,hint:t.hint??``,code:t.code??``})}catch{}return new it({message:e||t,details:``,hint:``,code:``})}function Ct(e,t,n){let r=e;return{success:!1,error:new it({message:`${r?.name??`FetchError`}: ${r?.message}`,details:``,hint:``,code:``}),data:null,count:null,status:t,statusText:n}}var wt=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,pt(pt({},t),{},{signal:n.signal})).finally(()=>{clearTimeout(r),a.removeEventListener(`abort`,i)})}return s(e,pt(pt({},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 xt(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 gt(r,`${e.url}/`,{method:`GET`,headers:n},e.retry??!0)}catch(e){return Ct(e,0,``)}let a;try{a=await i.text()}catch(e){return Ct(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:St(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 bt({method:a,url:o,headers:u,schema:this.schemaName,body:s,fetch:this.fetch??fetch,urlLengthLimit:this.urlLengthLimit,retry:this.retry})}},Tt=/* @__PURE__ */ E((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})),Et=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.version=void 0,e.version=`2.118.0`})),Dt=/* @__PURE__ */ E((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=Et();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`}})),Ot=/* @__PURE__ */ E((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)))}}})),kt=/* @__PURE__ */ E((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}})),At=/* @__PURE__ */ E(((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:()=>ee,LongPoll:()=>re,Presence:()=>ie,Push:()=>w,Serializer:()=>ae,Socket:()=>oe,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))}},ee=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}},te=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)}`}},ne=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)},re=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 te.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=ne(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=te.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)}},ie=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))}},ae={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)}}},oe=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||re,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=ae.encode.bind(ae),this.defaultDecoder=ae.decode.bind(ae),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===re?(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 re}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=te.appendParams(te.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!==re?this.connectWithFallback(re,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 re: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 ee(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())}}})),jt=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=At();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):[]}})),Mt=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.REALTIME_PRESENCE_LISTEN_EVENTS=void 0;let t=($e(),de(he)).__importDefault(jt());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)}}})),Nt=/* @__PURE__ */ E((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`)}})),Pt=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Dt();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)}}})),Ft=/* @__PURE__ */ E((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})),It=/* @__PURE__ */ E((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=($e(),de(he)),n=Dt(),r=t.__importDefault(Mt()),i=t.__importStar(kt()),a=kt(),o=Nt(),s=t.__importDefault(Pt()),c=Ft();var l=Ft();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}}})),Lt=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=At(),n=Dt();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}}})),Rt=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=($e(),de(he)),n=t.__importDefault(Tt()),r=Dt(),i=t.__importDefault(Ot()),a=kt(),o=t.__importDefault(It()),s=t.__importDefault(Lt()),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([`
|
|
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
6
|
addEventListener("message", (e) => {
|
|
7
7
|
if (e.data.event === "start") {
|
|
8
8
|
setInterval(() => postMessage({ event: "keepAlive" }), e.data.interval);
|
|
9
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()}}})),zt=(/* @__PURE__ */ E((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=($e(),de(he));e.RealtimeClient=t.__importDefault(Rt()).default;let n=t.__importStar(It());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(Mt());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(Tt()).default})))(),Bt=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 Vt(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 Ht(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 Ut(e){let t=e.fetchImpl??globalThis.fetch;return{async request({method:n,path:r,query:i,body:a,headers:o}){let s=Vt(e.baseUrl,r,i),c=await Ht(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 Bt(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 Wt(e){return e.join(``)}var Gt=class{constructor(e,t=``){this.client=e,this.prefix=t}async listNamespaces(e){let t=e?{parent:Wt(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/${Wt(e.namespace)}`})}async loadNamespaceMetadata(e){return{properties:(await this.client.request({method:`GET`,path:`${this.prefix}/namespaces/${Wt(e.namespace)}`})).data.properties}}async namespaceExists(e){try{return await this.client.request({method:`HEAD`,path:`${this.prefix}/namespaces/${Wt(e.namespace)}`}),!0}catch(e){if(e instanceof Bt&&e.status===404)return!1;throw e}}async createNamespaceIfNotExists(e,t){try{return await this.createNamespace(e,t)}catch(e){if(e instanceof Bt&&e.status===409)return;throw e}}};function Kt(e){return e.join(``)}var qt=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/${Kt(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/${Kt(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/${Kt(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/${Kt(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/${Kt(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/${Kt(e.namespace)}/tables/${e.name}`,headers:t}),!0}catch(e){if(e instanceof Bt&&e.status===404)return!1;throw e}}async createTableIfNotExists(e,t){try{return await this.createTable(e,t)}catch(n){if(n instanceof Bt&&n.status===409)return await this.loadTable({namespace:e.namespace,name:t.name});throw n}}},Jt=class{constructor(e){let t=`v1`;e.catalogName&&(t+=`/${e.catalogName}`);let n=e.baseUrl.endsWith(`/`)?e.baseUrl:`${e.baseUrl}/`;this.client=Ut({baseUrl:n,auth:e.auth,fetchImpl:e.fetch}),this.accessDelegation=e.accessDelegation?.join(`,`),this.namespaceOps=new Gt(this.client,t),this.tableOps=new qt(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 Yt(e){"@babel/helpers - typeof";return Yt=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},Yt(e)}function Xt(e,t){if(Yt(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(Yt(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function Zt(e){var t=Xt(e,`string`);return Yt(t)==`symbol`?t:t+``}function Qt(e,t,n){return(t=Zt(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function $t(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 D(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?$t(Object(n),!0).forEach(function(t){Qt(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):$t(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}var en=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 tn(e){return typeof e==`object`&&!!e&&`__isStorageError`in e}var nn=class extends en{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 D(D({},super.toJSON()),{},{code:this.code})}},rn=class extends en{constructor(e,t,n=`storage`){super(e,n),this.name=n===`vectors`?`StorageVectorsUnknownError`:`StorageUnknownError`,this.originalError=t}};function an(e,t,n){let r=D({},e),i=t.toLowerCase();for(let e of Object.keys(r))e.toLowerCase()===i&&delete r[e];return r[i]=n,r}function on(e){let t={};for(let[n,r]of Object.entries(e))t[n.toLowerCase()]=r;return t}const sn=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),cn=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)},ln=e=>{if(Array.isArray(e))return e.map(e=>ln(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]=ln(n)}),t},un=e=>!e||typeof e!=`string`||e.length===0||e.length>100||e.trim()!==e||e.includes(`/`)||e.includes(`\\`)?!1:/^[\w!.\*'() &$@=;:+,?-]+$/.test(e),dn=e=>e.split(`/`).map(encodeURIComponent).join(`/`),fn=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)},pn=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 nn(fn(e),i,n,r,e?.code))}).catch(()=>{let e=i+``;t(new nn(n.statusText||`HTTP ${i} error`,i,e,r))})}else t(new rn(fn(e),e,r))},mn=(e,t,n,r)=>{let i={method:e,headers:t?.headers||{}};if(e===`GET`||e===`HEAD`||!r)return D(D({},i),n);if(cn(r)){let e=t?.headers||{},n;for(let[t,r]of Object.entries(e))t.toLowerCase()===`content-type`&&(n=r);i.headers=an(e,`Content-Type`,n??`application/json`),i.body=JSON.stringify(r)}else i.body=r;return t?.duplex&&(i.duplex=t.duplex),D(D({},i),n)};async function hn(e,t,n,r,i,a,o){return new Promise((s,c)=>{e(n,mn(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=>pn(e,c,r,o))})}function gn(e=`storage`){return{get:async(t,n,r,i)=>hn(t,`GET`,n,r,i,void 0,e),post:async(t,n,r,i,a)=>hn(t,`POST`,n,i,a,r,e),put:async(t,n,r,i,a)=>hn(t,`PUT`,n,i,a,r,e),head:async(t,n,r,i)=>hn(t,`HEAD`,n,D(D({},r),{},{noResolveJson:!0}),i,void 0,e),remove:async(t,n,r,i,a)=>hn(t,`DELETE`,n,i,a,r,e)}}const{get:_n,post:vn,put:yn,head:bn,remove:xn}=gn(`storage`),Sn=gn(`vectors`);var Cn=class{constructor(e,t={},n,r=`storage`){this.shouldThrowOnError=!1,this.url=e,this.headers=on(t),this.fetch=sn(n),this.namespace=r}throwOnError(){return this.shouldThrowOnError=!0,this}setHeader(e,t){return this.headers=an(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(tn(e))return{data:null,error:e};throw e}}};let wn;wn=Symbol.toStringTag;var Tn=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[wn]=`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(tn(t))return{data:null,error:t};throw t}}};let En;En=Symbol.toStringTag;var Dn=class{constructor(e,t){this.downloadFn=e,this.shouldThrowOnError=t,this[En]=`BlobDownloadBuilder`,this.promise=null}asStream(){return new Tn(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(tn(t))return{data:null,error:t};throw t}}};const On={limit:100,offset:0,sortBy:{column:`name`,order:`asc`}},kn={cacheControl:`3600`,contentType:`text/plain;charset=UTF-8`,upsert:!1};var An=class extends Cn{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=D(D({},kn),r),s=D(D({},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=an(s,e,t);let l=i._removeEmptyFolders(t),u=i._getFinalPath(l),d=await(e==`PUT`?yn:vn)(i.fetch,`${i.url}/object/${u}`,a,D({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=D(D({},kn),r),o=D(D({},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=an(o,e,t);return{path:a,fullPath:(await yn(i.fetch,s.toString(),e,D({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=D({},n.headers);t?.upsert&&(i[`x-upsert`]=`true`);let a=await vn(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 en(`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 vn(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 vn(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 vn(r.fetch,`${r.url}/object/sign/${i}`,D(D({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 vn(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=>D(D({},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 Dn(()=>_n(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()=>ln(await _n(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 bn(t.fetch,`${t.url}/object/${n}`,{headers:t.headers}),{data:!0,error:null}}catch(e){if(t.shouldThrowOnError)throw e;if(tn(e)){let t=e instanceof nn?e.status:e instanceof rn?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 xn(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=dn(r._getFinalPath(e)),a=new URLSearchParams;t?.transformations&&a.set(`transformations`,`true`);let o=a.toString();return await xn(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?D(D({},On.sortBy),t.sortBy):On.sortBy,a=D(D(D({},On),t),{},{sortBy:i,prefix:e||``});return await vn(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=D({},e);return await vn(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 jn={"X-Client-Info":`storage-js/2.118.0`};var Mn=class extends Cn{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=D(D({},jn),t);super(a,o,n,`storage`)}async listBuckets(e){var t=this;return t.handleOperation(async()=>{let n=t.listBucketOptionsToQueryString(e);return await _n(t.fetch,`${t.url}/bucket${n}`,{headers:t.headers})})}async getBucket(e){var t=this;return t.handleOperation(async()=>await _n(t.fetch,`${t.url}/bucket/${e}`,{headers:t.headers}))}async createBucket(e,t={public:!1}){var n=this;return n.handleOperation(async()=>await vn(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 yn(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 vn(t.fetch,`${t.url}/bucket/${e}/empty`,{},{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await xn(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}))}async getBucketLifecycle(e){var t=this;return t.handleOperation(async()=>await _n(t.fetch,t.bucketLifecycleUrl(e),{headers:t.headers}))}async updateBucketLifecycle(e,t){var n=this;return n.handleOperation(async()=>await yn(n.fetch,n.bucketLifecycleUrl(e),t,{headers:n.headers}))}async deleteBucketLifecycle(e){var t=this;return t.handleOperation(async()=>await xn(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 xn(r.fetch,`${r.url}/cdn/${dn(e)}${a?`?${a}`:``}`,{},{headers:r.headers},n)})}bucketLifecycleUrl(e){return`${this.url}/bucket/${dn(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():``}},Nn=class extends Cn{constructor(e,t={},n){let r=e.replace(/\/$/,``),i=D(D({},jn),t);super(r,i,n,`storage`)}async createBucket(e){var t=this;return t.handleOperation(async()=>await vn(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 _n(t.fetch,i,{headers:t.headers})})}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await xn(t.fetch,`${t.url}/bucket/${e}`,{},{headers:t.headers}))}from(e){var t=this;if(!un(e))throw new en(`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 Jt({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}})}},Pn=class extends Cn{constructor(e,t={},n){let r=e.replace(/\/$/,``),i=D(D({},jn),{},{"Content-Type":`application/json`},t);super(r,i,n,`vectors`)}async createIndex(e){var t=this;return t.handleOperation(async()=>await Sn.post(t.fetch,`${t.url}/CreateIndex`,e,{headers:t.headers})||{})}async getIndex(e,t){var n=this;return n.handleOperation(async()=>await Sn.post(n.fetch,`${n.url}/GetIndex`,{vectorBucketName:e,indexName:t},{headers:n.headers}))}async listIndexes(e){var t=this;return t.handleOperation(async()=>await Sn.post(t.fetch,`${t.url}/ListIndexes`,e,{headers:t.headers}))}async deleteIndex(e,t){var n=this;return n.handleOperation(async()=>await Sn.post(n.fetch,`${n.url}/DeleteIndex`,{vectorBucketName:e,indexName:t},{headers:n.headers})||{})}},Fn=class extends Cn{constructor(e,t={},n){let r=e.replace(/\/$/,``),i=D(D({},jn),{},{"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 Sn.post(t.fetch,`${t.url}/PutVectors`,e,{headers:t.headers})||{})}async getVectors(e){var t=this;return t.handleOperation(async()=>await Sn.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 Sn.post(t.fetch,`${t.url}/ListVectors`,e,{headers:t.headers}))}async queryVectors(e){var t=this;return t.handleOperation(async()=>await Sn.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 Sn.post(t.fetch,`${t.url}/DeleteVectors`,e,{headers:t.headers})||{})}},In=class extends Cn{constructor(e,t={},n){let r=e.replace(/\/$/,``),i=D(D({},jn),{},{"Content-Type":`application/json`},t);super(r,i,n,`vectors`)}async createBucket(e){var t=this;return t.handleOperation(async()=>await Sn.post(t.fetch,`${t.url}/CreateVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{})}async getBucket(e){var t=this;return t.handleOperation(async()=>await Sn.post(t.fetch,`${t.url}/GetVectorBucket`,{vectorBucketName:e},{headers:t.headers}))}async listBuckets(e={}){var t=this;return t.handleOperation(async()=>await Sn.post(t.fetch,`${t.url}/ListVectorBuckets`,e,{headers:t.headers}))}async deleteBucket(e){var t=this;return t.handleOperation(async()=>await Sn.post(t.fetch,`${t.url}/DeleteVectorBucket`,{vectorBucketName:e},{headers:t.headers})||{})}},Ln=class extends In{constructor(e,t={}){super(e,t.headers||{},t.fetch)}from(e){return new Rn(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)}},Rn=class extends Pn{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,D(D({},e),{},{vectorBucketName:n.vectorBucketName}))}async listIndexes(e={}){var t=()=>super.listIndexes,n=this;return t().call(n,D(D({},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 zn(this.url,this.headers,this.vectorBucketName,e,this.fetch)}},zn=class extends Fn{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,D(D({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async getVectors(e){var t=()=>super.getVectors,n=this;return t().call(n,D(D({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async listVectors(e={}){var t=()=>super.listVectors,n=this;return t().call(n,D(D({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async queryVectors(e){var t=()=>super.queryVectors,n=this;return t().call(n,D(D({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}async deleteVectors(e){var t=()=>super.deleteVectors,n=this;return t().call(n,D(D({},e),{},{vectorBucketName:n.vectorBucketName,indexName:n.indexName}))}},Bn=class extends Mn{constructor(e,t={},n,r){super(e,t,n,r)}from(e){return new An(this.url,this.headers,e,this.fetch)}get vectors(){return new Ln(this.url+`/vector`,{headers:this.headers,fetch:this.fetch})}get analytics(){return new Nn(this.url+`/iceberg`,this.headers,this.fetch)}},Vn=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.version=void 0,e.version=`2.118.0`})),Hn=/* @__PURE__ */ E((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=Vn();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})),Un=/* @__PURE__ */ E((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`)}}})),Wn=/* @__PURE__ */ E((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(``)}})),Gn=/* @__PURE__ */ E((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=ee,e.parseResponseAPIVersion=ne,e.validateExp=re,e.getAlgorithm=ie,e.validateUUID=oe,e.assertRecoveryCodesExperimentalEnabled=se,e.userNotAvailableProxy=E,e.insecureUserWarningProxy=ce,e.deepClone=le;let t=Hn(),n=Un(),r=Wn();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 ee(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 te=/^2[0-9]{3}-(0[1-9]|1[0-2])-(0[1-9]|1[0-9]|2[0-9]|3[0-1])$/i;function ne(e){let n=e.headers.get(t.API_VERSION_HEADER_NAME);if(!n||!n.match(te))return null;try{return/* @__PURE__ */ new Date(`${n}T00:00:00.0Z`)}catch{return null}}function re(e){if(!e)throw Error(`Missing exp claim`);if(e<=Math.floor(Date.now()/1e3))throw Error(`JWT has expired`)}function ie(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 ae=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;function oe(e){if(!ae.test(e))throw Error(`@supabase/auth-js: Expected parameter to be UUID but is not`)}function se(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 E(){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 ce(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 le(e){return JSON.parse(JSON.stringify(e))}})),Kn=/* @__PURE__ */ E((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=($e(),de(he)),n=Hn(),r=Gn(),i=Un(),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}})),qn=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.SIGN_OUT_SCOPES=void 0,e.SIGN_OUT_SCOPES=[`global`,`local`,`others`]})),Jn=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=($e(),de(he)),n=Kn(),r=Gn(),i=qn(),a=Un();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}}}})),Yn=/* @__PURE__ */ E((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]}}}})),Xn=/* @__PURE__ */ E((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=Gn();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}})),Zn=/* @__PURE__ */ E((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)}}})),Qn=/* @__PURE__ */ E((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(`
|
|
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
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}`}})),$n=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.WebAuthnUnknownError=e.WebAuthnError=void 0,e.isWebAuthnError=r,e.identifyRegistrationError=i,e.identifyAuthenticationError=a;let t=er();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})}})),er=/* @__PURE__ */ E((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=($e(),de(he)),n=Wn(),r=Un(),i=Gn(),a=$n();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)}}}}})),tr=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=($e(),de(he)).__importDefault(Jn()),n=Hn(),r=Un(),i=Kn(),a=Gn(),o=Yn(),s=Xn(),c=Zn(),l=Vn(),u=Wn(),d=Qn(),f=er();(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})),nr=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=($e(),de(he)).__importDefault(Jn()).default})),rr=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=($e(),de(he)).__importDefault(tr()).default})),ir=(/* @__PURE__ */ E((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=($e(),de(he));e.GoTrueAdminApi=t.__importDefault(Jn()).default,e.GoTrueClient=t.__importDefault(tr()).default,e.AuthAdminApi=t.__importDefault(nr()).default,e.AuthClient=t.__importDefault(rr()).default,t.__exportStar(qn(),e),t.__exportStar(Un(),e);var n=Xn();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 ar=``,or;if(typeof Deno<`u`)ar=`deno`,or=Deno.version?.deno;else if(typeof document<`u`)ar=`web`;else if(typeof navigator<`u`&&navigator.product===`ReactNative`)ar=`react-native`;else{var sr;ar=`node`;let e=globalThis.process;or=e==null||(sr=e.version)==null?void 0:sr.replace(/^v/,``)}const cr=[`runtime=${ar}`];or&&cr.push(`runtime-version=${or}`);const lr={headers:{"X-Client-Info":`supabase-js/2.118.0; ${cr.join(`; `)}`}},ur={schema:`public`},dr={autoRefreshToken:!0,persistSession:!0,detectSessionInUrl:!0,flowType:`implicit`},fr={},pr={enabled:!1,respectSamplingDecision:!0};function mr(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 hr(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(gr(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 gr(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 _r(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 vr(e){"@babel/helpers - typeof";return vr=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},vr(e)}function yr(e,t){if(vr(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(vr(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function br(e){var t=yr(e,`string`);return vr(t)==`symbol`?t:t+``}function xr(e,t,n){return(t=br(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function Sr(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 Cr(e){for(var t=1;t<arguments.length;t++){var n=arguments[t]==null?{}:arguments[t];t%2?Sr(Object(n),!0).forEach(function(t){xr(e,t,n[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):Sr(Object(n)).forEach(function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))})}return e}const wr=e=>e?(...t)=>e(...t):(...e)=>fetch(...e),Tr=()=>Headers,Er=e=>e.startsWith(`sb_publishable_`)||e.startsWith(`sb_secret_`),Dr=/* @__PURE__ */ new Set,Or=e=>{if(!e.startsWith(`sb_`)||Er(e)||e.startsWith(`sb_temp_`))return;let t=e.match(/^sb_[a-zA-Z0-9]+_/)?.[0]??`unknown`;Dr.has(t)||(Dr.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.`))},kr=(e,t,n,r,i,a)=>{let o=wr(r),s=Tr(),c=i?.enabled===!0,l=i?.respectSamplingDecision!==!1,u=c?_r(t):null,d=!(a?.omitApiKeyAsBearer&&Er(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=Mr(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,Cr(Cr({},r),{},{headers:a}))}};let Ar=!1,jr=!1;function Mr(e,t,n){let r=me();if(!r)return Ar||(Ar=!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(!hr(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&&!jr){jr=!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=mr(i.traceparent);if(e&&!e.isSampled)return{traceparent:i.traceparent}}return i}function Nr(e){return typeof e==`boolean`?{enabled:e}:e}function Pr(e){return e.endsWith(`/`)?e:e+`/`}let Fr=!1;function Ir(e){Fr||typeof e==`object`&&e&&`schema`in e&&e.schema!==void 0&&(Fr=!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 Lr(e,t){let{db:n,auth:r,realtime:i,global:a}=e,{db:o,auth:s,realtime:c,global:l}=t,u=Nr(e.tracePropagation),d=Nr(t.tracePropagation),f={db:Cr(Cr({},o),n),auth:Cr(Cr({},s),r),realtime:Cr(Cr({},c),i),storage:{},global:Cr(Cr(Cr({},l),a),{},{headers:Cr(Cr({},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 Rr(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(Pr(t))}catch{throw Error(`Invalid supabaseUrl: Provided URL is malformed.`)}}var zr=class extends ir.AuthClient{constructor(e){super(e)}},Br=class{constructor(e,t,n){this.supabaseUrl=e,this.supabaseKey=t;let r=Rr(e);if(!t)throw Error(`supabaseKey is required.`);Or(t),Ir(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:ur,realtime:fr,auth:Cr(Cr({},dr),{},{storageKey:i}),global:lr,tracePropagation:pr},o=Lr(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=kr(t,e,this._getSessionToken.bind(this),o.global.fetch,o.tracePropagation),this.functionsFetch=kr(t,e,this._getSessionToken.bind(this),o.global.fetch,o.tracePropagation,{omitApiKeyAsBearer:!0}),this.realtime=this._initRealtimeClient(Cr({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 wt(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 Bn(this.storageUrl.href,this.headers,this.fetch,n?.storage),o.accessToken||this._listenForAuthEvents()}get functions(){return new rt.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 zr({url:this.authUrl.href,headers:Cr(Cr({},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 zt.RealtimeClient(this.realtimeUrl.href,Cr(Cr({},e),{},{params:Cr(Cr({},{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 Vr=(e,t,n)=>new Br(e,t,n);function Hr(){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}Hr()&&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 Ur=class extends Error{},Wr=class{client;connection;constructor(e){this.connection=e,this.client=Vr(e.apiUrl,e.publishableKey,{auth:{persistSession:!1,autoRefreshToken:!1}})}async call(e,t={}){if(!this.connection.key)throw new Ur("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 Ur(Kr(r.message));return n}whoami(){return this.call(`whoami`)}context(e){return this.call(`context`,{p_project:e})}};function Gr(e,t){let n=Vr(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 Ur(Kr(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 Ur(Kr(i.message));return r}}}function Kr(e){if(/<(!doctype|html)\b/i.test(e)){let t=/<title[^>]*>([^<]*)<\/title>/i.exec(e)?.[1]?.replace(/\s+/g,` `).trim();return`Quirl's server didn't answer${t?` (${t})`:``}. Try again in a minute.`}return e.split(`
|
|
15
|
-
`,1)[0]?.trim()??``}var O;(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})(O||={});var qr;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(qr||={});const k=O.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),Jr=e=>{switch(typeof e){case`undefined`:return k.undefined;case`string`:return k.string;case`number`:return Number.isNaN(e)?k.nan:k.number;case`boolean`:return k.boolean;case`function`:return k.function;case`bigint`:return k.bigint;case`symbol`:return k.symbol;case`object`:return Array.isArray(e)?k.array:e===null?k.null:e.then&&typeof e.then==`function`&&e.catch&&typeof e.catch==`function`?k.promise:typeof Map<`u`&&e instanceof Map?k.map:typeof Set<`u`&&e instanceof Set?k.set:typeof Date<`u`&&e instanceof Date?k.date:k.object;default:return k.unknown}},A=O.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 Yr=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,O.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()}};Yr.create=e=>new Yr(e);const Xr=(e,t)=>{let n;switch(e.code){case A.invalid_type:n=e.received===k.undefined?`Required`:`Expected ${e.expected}, received ${e.received}`;break;case A.invalid_literal:n=`Invalid literal value, expected ${JSON.stringify(e.expected,O.jsonStringifyReplacer)}`;break;case A.unrecognized_keys:n=`Unrecognized key(s) in object: ${O.joinValues(e.keys,`, `)}`;break;case A.invalid_union:n=`Invalid input`;break;case A.invalid_union_discriminator:n=`Invalid discriminator value. Expected ${O.joinValues(e.options)}`;break;case A.invalid_enum_value:n=`Invalid enum value. Expected ${O.joinValues(e.options)}, received '${e.received}'`;break;case A.invalid_arguments:n=`Invalid function arguments`;break;case A.invalid_return_type:n=`Invalid function return type`;break;case A.invalid_date:n=`Invalid date`;break;case A.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}"`:O.assertNever(e.validation):n=e.validation===`regex`?`Invalid`:`Invalid ${e.validation}`;break;case A.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 A.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 A.custom:n=`Invalid input`;break;case A.invalid_intersection_types:n=`Intersection results could not be merged`;break;case A.not_multiple_of:n=`Number must be a multiple of ${e.multipleOf}`;break;case A.not_finite:n=`Number must be finite`;break;default:n=t.defaultError,O.assertNever(e)}return{message:n}};let Zr=Xr;function Qr(){return Zr}const $r=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 j(e,t){let n=Qr(),r=$r({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Xr?void 0:Xr].filter(e=>!!e)});e.common.issues.push(r)}var ei=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 M;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 M;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 M=Object.freeze({status:`aborted`}),ti=e=>({status:`dirty`,value:e}),ni=e=>({status:`valid`,value:e}),ri=e=>e.status===`aborted`,ii=e=>e.status===`dirty`,ai=e=>e.status===`valid`,oi=e=>typeof Promise<`u`&&e instanceof Promise;var N;(function(e){e.errToObj=e=>typeof e==`string`?{message:e}:e||{},e.toString=e=>typeof e==`string`?e:e?.message})(N||={});var si=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 ci=(e,t)=>{if(ai(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 Yr(e.common.issues);return this._error=t,this._error}}};function P(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 F=class{get description(){return this._def.description}_getType(e){return Jr(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:Jr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new ei,ctx:{common:e.parent.common,data:e.data,parsedType:Jr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(oi(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:Jr(e)},r=this._parseSync({data:e,path:n.path,parent:n});return ci(n,r)}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:Jr(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return ai(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=>ai(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:Jr(e)},r=this._parse({data:e,path:n.path,parent:n}),i=await(oi(r)?r:Promise.resolve(r));return ci(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:A.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 ua({schema:this,typeName:I.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 da.create(this,this._def)}nullable(){return fa.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Gi.create(this)}promise(){return la.create(this,this._def)}or(e){return Ji.create([this,e],this._def)}and(e){return Qi.create(this,e,this._def)}transform(e){return new ua({...P(this._def),schema:this,typeName:I.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new pa({...P(this._def),innerType:this,defaultValue:t,typeName:I.ZodDefault})}brand(){return new ga({typeName:I.ZodBranded,type:this,...P(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new ma({...P(this._def),innerType:this,catchValue:t,typeName:I.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return _a.create(this,e)}readonly(){return va.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const li=/^c[^\s-]{8,}$/i,ui=/^[0-9a-z]+$/,di=/^[0-9A-HJKMNP-TV-Z]{26}$/i,fi=/^[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,pi=/^[a-z0-9_-]{21}$/i,mi=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,hi=/^[-+]?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)?)??$/,gi=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let _i;const vi=/^(?:(?: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])$/,yi=/^(?:(?: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])$/,bi=/^(([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]))$/,xi=/^(([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])$/,Si=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Ci=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,wi=`((\\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])))`,Ti=RegExp(`^${wi}$`);function Ei(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 Di(e){return RegExp(`^${Ei(e)}$`)}function Oi(e){let t=`${wi}T${Ei(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function ki(e,t){return!((t!==`v4`&&t||!vi.test(e))&&(t!==`v6`&&t||!bi.test(e)))}function Ai(e,t){if(!mi.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 ji(e,t){return!((t!==`v4`&&t||!yi.test(e))&&(t!==`v6`&&t||!xi.test(e)))}var Mi=class e extends F{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==k.string){let t=this._getOrReturnCtx(e);return j(t,{code:A.invalid_type,expected:k.string,received:t.parsedType}),M}let t=new ei,n;for(let r of this._def.checks)if(r.kind===`min`)e.data.length<r.value&&(n=this._getOrReturnCtx(e,n),j(n,{code:A.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),j(n,{code:A.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?j(n,{code:A.too_big,maximum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}):a&&j(n,{code:A.too_small,minimum:r.value,type:`string`,inclusive:!0,exact:!0,message:r.message}),t.dirty())}else if(r.kind===`email`)gi.test(e.data)||(n=this._getOrReturnCtx(e,n),j(n,{validation:`email`,code:A.invalid_string,message:r.message}),t.dirty());else if(r.kind===`emoji`)_i||=RegExp(`^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`,`u`),_i.test(e.data)||(n=this._getOrReturnCtx(e,n),j(n,{validation:`emoji`,code:A.invalid_string,message:r.message}),t.dirty());else if(r.kind===`uuid`)fi.test(e.data)||(n=this._getOrReturnCtx(e,n),j(n,{validation:`uuid`,code:A.invalid_string,message:r.message}),t.dirty());else if(r.kind===`nanoid`)pi.test(e.data)||(n=this._getOrReturnCtx(e,n),j(n,{validation:`nanoid`,code:A.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid`)li.test(e.data)||(n=this._getOrReturnCtx(e,n),j(n,{validation:`cuid`,code:A.invalid_string,message:r.message}),t.dirty());else if(r.kind===`cuid2`)ui.test(e.data)||(n=this._getOrReturnCtx(e,n),j(n,{validation:`cuid2`,code:A.invalid_string,message:r.message}),t.dirty());else if(r.kind===`ulid`)di.test(e.data)||(n=this._getOrReturnCtx(e,n),j(n,{validation:`ulid`,code:A.invalid_string,message:r.message}),t.dirty());else if(r.kind===`url`)try{new URL(e.data)}catch{n=this._getOrReturnCtx(e,n),j(n,{validation:`url`,code:A.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),j(n,{validation:`regex`,code:A.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),j(n,{code:A.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),j(n,{code:A.invalid_string,validation:{startsWith:r.value},message:r.message}),t.dirty()):r.kind===`endsWith`?e.data.endsWith(r.value)||(n=this._getOrReturnCtx(e,n),j(n,{code:A.invalid_string,validation:{endsWith:r.value},message:r.message}),t.dirty()):r.kind===`datetime`?Oi(r).test(e.data)||(n=this._getOrReturnCtx(e,n),j(n,{code:A.invalid_string,validation:`datetime`,message:r.message}),t.dirty()):r.kind===`date`?Ti.test(e.data)||(n=this._getOrReturnCtx(e,n),j(n,{code:A.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?Di(r).test(e.data)||(n=this._getOrReturnCtx(e,n),j(n,{code:A.invalid_string,validation:`time`,message:r.message}),t.dirty()):r.kind===`duration`?hi.test(e.data)||(n=this._getOrReturnCtx(e,n),j(n,{validation:`duration`,code:A.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?ki(e.data,r.version)||(n=this._getOrReturnCtx(e,n),j(n,{validation:`ip`,code:A.invalid_string,message:r.message}),t.dirty()):r.kind===`jwt`?Ai(e.data,r.alg)||(n=this._getOrReturnCtx(e,n),j(n,{validation:`jwt`,code:A.invalid_string,message:r.message}),t.dirty()):r.kind===`cidr`?ji(e.data,r.version)||(n=this._getOrReturnCtx(e,n),j(n,{validation:`cidr`,code:A.invalid_string,message:r.message}),t.dirty()):r.kind===`base64`?Si.test(e.data)||(n=this._getOrReturnCtx(e,n),j(n,{validation:`base64`,code:A.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?Ci.test(e.data)||(n=this._getOrReturnCtx(e,n),j(n,{validation:`base64url`,code:A.invalid_string,message:r.message}),t.dirty()):O.assertNever(r);return{status:t.value,value:e.data}}_regex(e,t,n){return this.refinement(t=>e.test(t),{validation:t,code:A.invalid_string,...N.errToObj(n)})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}email(e){return this._addCheck({kind:`email`,...N.errToObj(e)})}url(e){return this._addCheck({kind:`url`,...N.errToObj(e)})}emoji(e){return this._addCheck({kind:`emoji`,...N.errToObj(e)})}uuid(e){return this._addCheck({kind:`uuid`,...N.errToObj(e)})}nanoid(e){return this._addCheck({kind:`nanoid`,...N.errToObj(e)})}cuid(e){return this._addCheck({kind:`cuid`,...N.errToObj(e)})}cuid2(e){return this._addCheck({kind:`cuid2`,...N.errToObj(e)})}ulid(e){return this._addCheck({kind:`ulid`,...N.errToObj(e)})}base64(e){return this._addCheck({kind:`base64`,...N.errToObj(e)})}base64url(e){return this._addCheck({kind:`base64url`,...N.errToObj(e)})}jwt(e){return this._addCheck({kind:`jwt`,...N.errToObj(e)})}ip(e){return this._addCheck({kind:`ip`,...N.errToObj(e)})}cidr(e){return this._addCheck({kind:`cidr`,...N.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,...N.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,...N.errToObj(e?.message)})}duration(e){return this._addCheck({kind:`duration`,...N.errToObj(e)})}regex(e,t){return this._addCheck({kind:`regex`,regex:e,...N.errToObj(t)})}includes(e,t){return this._addCheck({kind:`includes`,value:e,position:t?.position,...N.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:`startsWith`,value:e,...N.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:`endsWith`,value:e,...N.errToObj(t)})}min(e,t){return this._addCheck({kind:`min`,value:e,...N.errToObj(t)})}max(e,t){return this._addCheck({kind:`max`,value:e,...N.errToObj(t)})}length(e,t){return this._addCheck({kind:`length`,value:e,...N.errToObj(t)})}nonempty(e){return this.min(1,N.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}};Mi.create=e=>new Mi({checks:[],typeName:I.ZodString,coerce:e?.coerce??!1,...P(e)});function Ni(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 Pi=class e extends F{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)!==k.number){let t=this._getOrReturnCtx(e);return j(t,{code:A.invalid_type,expected:k.number,received:t.parsedType}),M}let t,n=new ei;for(let r of this._def.checks)r.kind===`int`?O.isInteger(e.data)||(t=this._getOrReturnCtx(e,t),j(t,{code:A.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),j(t,{code:A.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),j(t,{code:A.too_big,maximum:r.value,type:`number`,inclusive:r.inclusive,exact:!1,message:r.message}),n.dirty()):r.kind===`multipleOf`?Ni(e.data,r.value)!==0&&(t=this._getOrReturnCtx(e,t),j(t,{code:A.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):r.kind===`finite`?Number.isFinite(e.data)||(t=this._getOrReturnCtx(e,t),j(t,{code:A.not_finite,message:r.message}),n.dirty()):O.assertNever(r);return{status:n.value,value:e.data}}gte(e,t){return this.setLimit(`min`,e,!0,N.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,N.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,N.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,N.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:N.toString(i)}]})}_addCheck(t){return new e({...this._def,checks:[...this._def.checks,t]})}int(e){return this._addCheck({kind:`int`,message:N.toString(e)})}positive(e){return this._addCheck({kind:`min`,value:0,inclusive:!1,message:N.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:0,inclusive:!1,message:N.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:0,inclusive:!0,message:N.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:0,inclusive:!0,message:N.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:N.toString(t)})}finite(e){return this._addCheck({kind:`finite`,message:N.toString(e)})}safe(e){return this._addCheck({kind:`min`,inclusive:!0,value:-(2**53-1),message:N.toString(e)})._addCheck({kind:`max`,inclusive:!0,value:2**53-1,message:N.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`&&O.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)}};Pi.create=e=>new Pi({checks:[],typeName:I.ZodNumber,coerce:e?.coerce||!1,...P(e)});var Fi=class e extends F{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)!==k.bigint)return this._getInvalidInput(e);let t,n=new ei;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),j(t,{code:A.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),j(t,{code:A.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),j(t,{code:A.not_multiple_of,multipleOf:r.value,message:r.message}),n.dirty()):O.assertNever(r);return{status:n.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return j(t,{code:A.invalid_type,expected:k.bigint,received:t.parsedType}),M}gte(e,t){return this.setLimit(`min`,e,!0,N.toString(t))}gt(e,t){return this.setLimit(`min`,e,!1,N.toString(t))}lte(e,t){return this.setLimit(`max`,e,!0,N.toString(t))}lt(e,t){return this.setLimit(`max`,e,!1,N.toString(t))}setLimit(t,n,r,i){return new e({...this._def,checks:[...this._def.checks,{kind:t,value:n,inclusive:r,message:N.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:N.toString(e)})}negative(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!1,message:N.toString(e)})}nonpositive(e){return this._addCheck({kind:`max`,value:BigInt(0),inclusive:!0,message:N.toString(e)})}nonnegative(e){return this._addCheck({kind:`min`,value:BigInt(0),inclusive:!0,message:N.toString(e)})}multipleOf(e,t){return this._addCheck({kind:`multipleOf`,value:e,message:N.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}};Fi.create=e=>new Fi({checks:[],typeName:I.ZodBigInt,coerce:e?.coerce??!1,...P(e)});var Ii=class extends F{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==k.boolean){let t=this._getOrReturnCtx(e);return j(t,{code:A.invalid_type,expected:k.boolean,received:t.parsedType}),M}return ni(e.data)}};Ii.create=e=>new Ii({typeName:I.ZodBoolean,coerce:e?.coerce||!1,...P(e)});var Li=class e extends F{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==k.date){let t=this._getOrReturnCtx(e);return j(t,{code:A.invalid_type,expected:k.date,received:t.parsedType}),M}if(Number.isNaN(e.data.getTime()))return j(this._getOrReturnCtx(e),{code:A.invalid_date}),M;let t=new ei,n;for(let r of this._def.checks)r.kind===`min`?e.data.getTime()<r.value&&(n=this._getOrReturnCtx(e,n),j(n,{code:A.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),j(n,{code:A.too_big,message:r.message,inclusive:!0,exact:!1,maximum:r.value,type:`date`}),t.dirty()):O.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:N.toString(t)})}max(e,t){return this._addCheck({kind:`max`,value:e.getTime(),message:N.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)}};Li.create=e=>new Li({checks:[],coerce:e?.coerce||!1,typeName:I.ZodDate,...P(e)});var Ri=class extends F{_parse(e){if(this._getType(e)!==k.symbol){let t=this._getOrReturnCtx(e);return j(t,{code:A.invalid_type,expected:k.symbol,received:t.parsedType}),M}return ni(e.data)}};Ri.create=e=>new Ri({typeName:I.ZodSymbol,...P(e)});var zi=class extends F{_parse(e){if(this._getType(e)!==k.undefined){let t=this._getOrReturnCtx(e);return j(t,{code:A.invalid_type,expected:k.undefined,received:t.parsedType}),M}return ni(e.data)}};zi.create=e=>new zi({typeName:I.ZodUndefined,...P(e)});var Bi=class extends F{_parse(e){if(this._getType(e)!==k.null){let t=this._getOrReturnCtx(e);return j(t,{code:A.invalid_type,expected:k.null,received:t.parsedType}),M}return ni(e.data)}};Bi.create=e=>new Bi({typeName:I.ZodNull,...P(e)});var Vi=class extends F{constructor(){super(...arguments),this._any=!0}_parse(e){return ni(e.data)}};Vi.create=e=>new Vi({typeName:I.ZodAny,...P(e)});var Hi=class extends F{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ni(e.data)}};Hi.create=e=>new Hi({typeName:I.ZodUnknown,...P(e)});var Ui=class extends F{_parse(e){let t=this._getOrReturnCtx(e);return j(t,{code:A.invalid_type,expected:k.never,received:t.parsedType}),M}};Ui.create=e=>new Ui({typeName:I.ZodNever,...P(e)});var Wi=class extends F{_parse(e){if(this._getType(e)!==k.undefined){let t=this._getOrReturnCtx(e);return j(t,{code:A.invalid_type,expected:k.void,received:t.parsedType}),M}return ni(e.data)}};Wi.create=e=>new Wi({typeName:I.ZodVoid,...P(e)});var Gi=class e extends F{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),r=this._def;if(t.parsedType!==k.array)return j(t,{code:A.invalid_type,expected:k.array,received:t.parsedType}),M;if(r.exactLength!==null){let e=t.data.length>r.exactLength.value,i=t.data.length<r.exactLength.value;(e||i)&&(j(t,{code:e?A.too_big:A.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&&(j(t,{code:A.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&&(j(t,{code:A.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 si(t,e,t.path,n)))).then(e=>ei.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new si(t,e,t.path,n)));return ei.mergeArray(n,i)}get element(){return this._def.type}min(t,n){return new e({...this._def,minLength:{value:t,message:N.toString(n)}})}max(t,n){return new e({...this._def,maxLength:{value:t,message:N.toString(n)}})}length(t,n){return new e({...this._def,exactLength:{value:t,message:N.toString(n)}})}nonempty(e){return this.min(1,e)}};Gi.create=(e,t)=>new Gi({type:e,minLength:null,maxLength:null,exactLength:null,typeName:I.ZodArray,...P(t)});function Ki(e){if(e instanceof qi){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=da.create(Ki(r))}return new qi({...e._def,shape:()=>t})}return e instanceof Gi?new Gi({...e._def,type:Ki(e.element)}):e instanceof da?da.create(Ki(e.unwrap())):e instanceof fa?fa.create(Ki(e.unwrap())):e instanceof $i?$i.create(e.items.map(e=>Ki(e))):e}var qi=class e extends F{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=O.objectKeys(e);return this._cached={shape:e,keys:t},this._cached}_parse(e){if(this._getType(e)!==k.object){let t=this._getOrReturnCtx(e);return j(t,{code:A.invalid_type,expected:k.object,received:t.parsedType}),M}let{status:t,ctx:n}=this._processInputParams(e),{shape:r,keys:i}=this._getCached(),a=[];if(!(this._def.catchall instanceof Ui&&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 si(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof Ui){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&&(j(n,{code:A.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 si(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=>ei.mergeObjectSync(t,e)):ei.mergeObjectSync(t,o)}get shape(){return this._def.shape()}strict(t){return N.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:N.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:I.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 O.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 O.objectKeys(this.shape))t[e]||(n[e]=this.shape[e]);return new e({...this._def,shape:()=>n})}deepPartial(){return Ki(this)}partial(t){let n={};for(let e of O.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 O.objectKeys(this.shape))if(t&&!t[e])n[e]=this.shape[e];else{let t=this.shape[e];for(;t instanceof da;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return oa(O.objectKeys(this.shape))}};qi.create=(e,t)=>new qi({shape:()=>e,unknownKeys:`strip`,catchall:Ui.create(),typeName:I.ZodObject,...P(t)}),qi.strictCreate=(e,t)=>new qi({shape:()=>e,unknownKeys:`strict`,catchall:Ui.create(),typeName:I.ZodObject,...P(t)}),qi.lazycreate=(e,t)=>new qi({shape:e,unknownKeys:`strip`,catchall:Ui.create(),typeName:I.ZodObject,...P(t)});var Ji=class extends F{_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 Yr(e.ctx.common.issues));return j(t,{code:A.invalid_union,unionErrors:n}),M}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 Yr(e));return j(t,{code:A.invalid_union,unionErrors:i}),M}}get options(){return this._def.options}};Ji.create=(e,t)=>new Ji({options:e,typeName:I.ZodUnion,...P(t)});const Yi=e=>e instanceof ia?Yi(e.schema):e instanceof ua?Yi(e.innerType()):e instanceof aa?[e.value]:e instanceof sa?e.options:e instanceof ca?O.objectValues(e.enum):e instanceof pa?Yi(e._def.innerType):e instanceof zi?[void 0]:e instanceof Bi?[null]:e instanceof da?[void 0,...Yi(e.unwrap())]:e instanceof fa?[null,...Yi(e.unwrap())]:e instanceof ga||e instanceof va?Yi(e.unwrap()):e instanceof ma?Yi(e._def.innerType):[];var Xi=class e extends F{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==k.object)return j(t,{code:A.invalid_type,expected:k.object,received:t.parsedType}),M;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}):(j(t,{code:A.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),M)}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=Yi(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:I.ZodDiscriminatedUnion,discriminator:t,options:n,optionsMap:i,...P(r)})}};function Zi(e,t){let n=Jr(e),r=Jr(t);if(e===t)return{valid:!0,data:e};if(n===k.object&&r===k.object){let n=O.objectKeys(t),r=O.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=Zi(e[n],t[n]);if(!r.valid)return{valid:!1};i[n]=r.data}return{valid:!0,data:i}}if(n===k.array&&r===k.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=Zi(i,a);if(!o.valid)return{valid:!1};n.push(o.data)}return{valid:!0,data:n}}return n===k.date&&r===k.date&&+e==+t?{valid:!0,data:e}:{valid:!1}}var Qi=class extends F{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(ri(e)||ri(r))return M;let i=Zi(e.value,r.value);return i.valid?((ii(e)||ii(r))&&t.dirty(),{status:t.value,value:i.data}):(j(n,{code:A.invalid_intersection_types}),M)};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}))}};Qi.create=(e,t,n)=>new Qi({left:e,right:t,typeName:I.ZodIntersection,...P(n)});var $i=class e extends F{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==k.array)return j(n,{code:A.invalid_type,expected:k.array,received:n.parsedType}),M;if(n.data.length<this._def.items.length)return j(n,{code:A.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:`array`}),M;!this._def.rest&&n.data.length>this._def.items.length&&(j(n,{code:A.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 si(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>ei.mergeArray(t,e)):ei.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};$i.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new $i({items:e,typeName:I.ZodTuple,rest:null,...P(t)})};var ea=class e extends F{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!==k.object)return j(n,{code:A.invalid_type,expected:k.object,received:n.parsedType}),M;let r=[],i=this._def.keyType,a=this._def.valueType;for(let e in n.data)r.push({key:i._parse(new si(n,e,n.path,e)),value:a._parse(new si(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?ei.mergeObjectAsync(t,r):ei.mergeObjectSync(t,r)}get element(){return this._def.valueType}static create(t,n,r){return n instanceof F?new e({keyType:t,valueType:n,typeName:I.ZodRecord,...P(r)}):new e({keyType:Mi.create(),valueType:t,typeName:I.ZodRecord,...P(n)})}},ta=class extends F{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!==k.map)return j(n,{code:A.invalid_type,expected:k.map,received:n.parsedType}),M;let r=this._def.keyType,i=this._def.valueType,a=[...n.data.entries()].map(([e,t],a)=>({key:r._parse(new si(n,e,n.path,[a,`key`])),value:i._parse(new si(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 M;(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 M;(r.status===`dirty`||i.status===`dirty`)&&t.dirty(),e.set(r.value,i.value)}return{status:t.value,value:e}}}};ta.create=(e,t,n)=>new ta({valueType:t,keyType:e,typeName:I.ZodMap,...P(n)});var na=class e extends F{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==k.set)return j(n,{code:A.invalid_type,expected:k.set,received:n.parsedType}),M;let r=this._def;r.minSize!==null&&n.data.size<r.minSize.value&&(j(n,{code:A.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&&(j(n,{code:A.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 M;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 si(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:N.toString(n)}})}max(t,n){return new e({...this._def,maxSize:{value:t,message:N.toString(n)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};na.create=(e,t)=>new na({valueType:e,minSize:null,maxSize:null,typeName:I.ZodSet,...P(t)});var ra=class e extends F{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==k.function)return j(t,{code:A.invalid_type,expected:k.function,received:t.parsedType}),M;function n(e,n){return $r({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Qr(),Xr].filter(e=>!!e),issueData:{code:A.invalid_arguments,argumentsError:n}})}function r(e,n){return $r({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Qr(),Xr].filter(e=>!!e),issueData:{code:A.invalid_return_type,returnTypeError:n}})}let i={errorMap:t.common.contextualErrorMap},a=t.data;if(this._def.returns instanceof la){let e=this;return ni(async function(...t){let o=new Yr([]),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 ni(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new Yr([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new Yr([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:$i.create(t).rest(Hi.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||$i.create([]).rest(Hi.create()),returns:n||Hi.create(),typeName:I.ZodFunction,...P(r)})}},ia=class extends F{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})}};ia.create=(e,t)=>new ia({getter:e,typeName:I.ZodLazy,...P(t)});var aa=class extends F{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return j(t,{received:t.data,code:A.invalid_literal,expected:this._def.value}),M}return{status:`valid`,value:e.data}}get value(){return this._def.value}};aa.create=(e,t)=>new aa({value:e,typeName:I.ZodLiteral,...P(t)});function oa(e,t){return new sa({values:e,typeName:I.ZodEnum,...P(t)})}var sa=class e extends F{_parse(e){if(typeof e.data!=`string`){let t=this._getOrReturnCtx(e),n=this._def.values;return j(t,{expected:O.joinValues(n),received:t.parsedType,code:A.invalid_type}),M}if(this._cache||=new Set(this._def.values),!this._cache.has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return j(t,{received:t.data,code:A.invalid_enum_value,options:n}),M}return ni(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})}};sa.create=oa;var ca=class extends F{_parse(e){let t=O.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==k.string&&n.parsedType!==k.number){let e=O.objectValues(t);return j(n,{expected:O.joinValues(e),received:n.parsedType,code:A.invalid_type}),M}if(this._cache||=new Set(O.getValidEnumValues(this._def.values)),!this._cache.has(e.data)){let e=O.objectValues(t);return j(n,{received:n.data,code:A.invalid_enum_value,options:e}),M}return ni(e.data)}get enum(){return this._def.values}};ca.create=(e,t)=>new ca({values:e,typeName:I.ZodNativeEnum,...P(t)});var la=class extends F{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==k.promise&&t.common.async===!1)return j(t,{code:A.invalid_type,expected:k.promise,received:t.parsedType}),M;let n=t.parsedType===k.promise?t.data:Promise.resolve(t.data);return ni(n.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};la.create=(e,t)=>new la({type:e,typeName:I.ZodPromise,...P(t)});var ua=class extends F{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===I.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=>{j(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 M;let r=await this._def.schema._parseAsync({data:e,path:n.path,parent:n});return r.status===`aborted`?M:r.status===`dirty`||t.value===`dirty`?ti(r.value):r});{if(t.value===`aborted`)return M;let r=this._def.schema._parseSync({data:e,path:n.path,parent:n});return r.status===`aborted`?M:r.status===`dirty`||t.value===`dirty`?ti(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`?M:(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`?M:(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(!ai(e))return M;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=>ai(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):M)}O.assertNever(r)}};ua.create=(e,t,n)=>new ua({schema:e,typeName:I.ZodEffects,effect:t,...P(n)}),ua.createWithPreprocess=(e,t,n)=>new ua({schema:t,effect:{type:`preprocess`,transform:e},typeName:I.ZodEffects,...P(n)});var da=class extends F{_parse(e){return this._getType(e)===k.undefined?ni(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};da.create=(e,t)=>new da({innerType:e,typeName:I.ZodOptional,...P(t)});var fa=class extends F{_parse(e){return this._getType(e)===k.null?ni(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};fa.create=(e,t)=>new fa({innerType:e,typeName:I.ZodNullable,...P(t)});var pa=class extends F{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===k.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};pa.create=(e,t)=>new pa({innerType:e,typeName:I.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...P(t)});var ma=class extends F{_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 oi(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new Yr(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new Yr(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};ma.create=(e,t)=>new ma({innerType:e,typeName:I.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...P(t)});var ha=class extends F{_parse(e){if(this._getType(e)!==k.nan){let t=this._getOrReturnCtx(e);return j(t,{code:A.invalid_type,expected:k.nan,received:t.parsedType}),M}return{status:`valid`,value:e.data}}};ha.create=e=>new ha({typeName:I.ZodNaN,...P(e)});var ga=class extends F{_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}},_a=class e extends F{_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`?M:e.status===`dirty`?(t.dirty(),ti(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`?M: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:I.ZodPipeline})}},va=class extends F{_parse(e){let t=this._def.innerType._parse(e),n=e=>(ai(e)&&(e.value=Object.freeze(e.value)),e);return oi(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};va.create=(e,t)=>new va({innerType:e,typeName:I.ZodReadonly,...P(t)}),qi.lazycreate;var I;(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`})(I||={}),Mi.create,Pi.create,ha.create,Fi.create,Ii.create,Li.create,Ri.create,zi.create,Bi.create,Vi.create,Hi.create,Ui.create,Wi.create,Gi.create;const ya=qi.create;qi.strictCreate,Ji.create,Xi.create,Qi.create,$i.create,ea.create,ta.create,na.create,ra.create,ia.create,aa.create,sa.create,ca.create,la.create,ua.create,da.create,fa.create,ua.createWithPreprocess,_a.create;function ba(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 xa(e,t=`|`){return e.map(e=>Ka(e)).join(t)}function Sa(e,t){return typeof t==`bigint`?t.toString():t}var Ca=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 wa(e){return new Ca(e)}function Ta(e){return e==null}function Ea(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function Da(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 Oa(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function ka(e){let t=Object.getOwnPropertyDescriptor(e,`shape`);return t?.get?t.get.raw:t?.value}function Aa(e){return ka(e._zod.def)??e._zod.def.shape}function ja(e,t,n){Object.defineProperty(e,t,{get(){let e=n();return Oa(this,t,e),e},enumerable:!0,configurable:!0})}function Ma(e,t,n){t in e?Oa(e,t,n):e[t]=n}function Na(e,t,n,r){let i=Aa(t);for(let a of n){let n=Object.getOwnPropertyDescriptor(i,a);n.enumerable&&(n.get?ja(e,a,()=>{let e=t._zod.def.shape[a];return r?r(e,a):e}):Ma(e,a,r?r(n.value,a):n.value))}}function Pa(e,t){for(let n of Reflect.ownKeys(t)){let r=Object.getOwnPropertyDescriptor(t,n);r.enumerable&&(r.get?ja(e,n,()=>t[n]):Ma(e,n,r.value))}}function Fa(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function Ia(e){return JSON.stringify(e)}function La(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}const Ra=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function za(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const Ba=/* @__PURE__*/ wa(()=>{if(Fo.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function Va(e){if(za(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return za(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}function Ha(e){return Va(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const Ua=/* @__PURE__*/ new Set([`string`,`number`,`symbol`]);function Wa(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Ga(e,t,n){let r=new e._zod.constr(t??e._zod.def);return(!t||n?.parent)&&(r._zod.parent=e),r}function L(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 Ka(e){return typeof e==`bigint`?e.toString()+`n`:typeof e==`string`?`"${e}"`:`${e}`}function qa(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout===`optional`)}const Ja={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Ya={int64:[/* @__PURE__*/ BigInt(`-9223372036854775808`),/* @__PURE__*/ BigInt(`9223372036854775807`)],uint64:[/* @__PURE__*/ BigInt(0),/* @__PURE__*/ BigInt(`18446744073709551615`)]};function Xa(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 Na(i,e,Za(e,t)),Ga(e,Fa(n,{shape:i,checks:[]}))}function Za(e,t){let n=Aa(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 Qa(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(Za(e,t)),a={};return Na(a,e,Reflect.ownKeys(Aa(e)).filter(e=>!i.has(e))),Ga(e,Fa(n,{shape:a,checks:[]}))}function $a(e,t){if(!Va(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=Aa(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 Ga(e,Fa(e._zod.def,{shape:eo(e,t)}))}function eo(e,t){let n={};return Na(n,e,Reflect.ownKeys(Aa(e))),Pa(n,t),n}function to(e,t){if(!Va(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return Ga(e,Fa(e._zod.def,{shape:eo(e,t)}))}function no(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 Na(n,e,Reflect.ownKeys(Aa(e))),Na(n,t,Reflect.ownKeys(Aa(t))),Ga(e,Fa(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function ro(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(Za(t,n)):void 0,o={};return Na(o,t,Reflect.ownKeys(Aa(t)),e&&((t,n)=>a&&!a.has(n)?t:new e({type:`optional`,innerType:t}))),Ga(t,Fa(t._zod.def,{shape:o,checks:[]}))}function io(e,t,n){let r=n?new Set(Za(t,n)):void 0,i={};return Na(i,t,Reflect.ownKeys(Aa(t)),(t,n)=>r&&!r.has(n)?t:new e({type:`nonoptional`,innerType:t})),Ga(t,Fa(t._zod.def,{shape:i}))}function ao(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 oo(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 so(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function co(e){return typeof e==`string`?e:e?.message}function lo(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 uo(e,t,n){var r;for(let i=t;i<e.length;i++)(r=e[i]).schema??(r.schema=n)}function fo(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:co(e.inst?._zod.def?.error?.(e))??co(a?.(e))??co(t?.error?.(e))??co(n.customError?.(e))??co(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 po=/[\uD800-\uDBFF]/;function mo(e){let t=e.length;if(!po.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 ho(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function go(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 _o(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}function vo(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);r.get?Object.defineProperty(e,n,{...r,enumerable:!1}):So(e,n,r.value)}}function yo(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function bo(e,t,n){return yo(e,t,n,!1)}/* @__NO_SIDE_EFFECTS__ */
|
|
16
|
-
function
|
|
17
|
-
function z(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){Ao.value=new a(r);try{Object.defineProperty(n,"_zod",Ao)}finally{Ao.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),vo(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?Mo(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 No=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},Po=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(ko=globalThis).__zod_globalConfig??(ko.__zod_globalConfig={});const Fo=globalThis.__zod_globalConfig;function Io(e){return e&&Object.assign(Fo,e),Fo}function Lo(){let e=this._zod;return e.message??=JSON.stringify(e.def,Sa,2),e.message}function Ro(e){this._zod.message=e}const zo={get:Lo,set:Ro,enumerable:!0,configurable:!0},Bo={value:void 0,enumerable:!1},Vo=/* @__PURE__ */ new WeakSet([Object.prototype,Error.prototype]),Ho=(e,t)=>{e.name=`$ZodError`,Bo.value=t,Object.defineProperty(e,"issues",Bo),Bo.value=void 0,Object.defineProperty(e,"message",zo);let n=Object.getPrototypeOf(e);Vo.has(n)||(Vo.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})}}))},Uo=/* @__PURE__ */ z(`$ZodError`,Ho),Wo=/* @__PURE__ */ z(`$ZodError`,Ho,void 0,{Parent:Error});function Go(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 Ko(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?Go(n,i.path[0],()=>[]).push(t(i)):r.push(t(i));return{formErrors:r,fieldErrors:n}}function qo(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 Jo(e,t){return{callee:t?.callee??e,Err:t?.Err}}const Yo=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 No;if(s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>fo(e,o,Io())));throw Ra(n,a?.callee??t),n}return s.value};return t},Xo=/* @__PURE__*/ Yo(Wo),Zo=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=>fo(e,o,Io())));throw Ra(n,a?.callee??t),n}return s.value};return t},Qo=/* @__PURE__*/ Zo(Wo),$o=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 No;return a.issues.length?ts(e,a.issues,i):{success:!0,data:a.value}},es=/* @__PURE__*/ $o(Wo);function ts(e,t,n){let r;return{success:!1,get error(){return r||(r=new e(t.map(e=>fo(e,n,Io()))),t=void 0,n=void 0),r},set error(e){r=e,t=void 0,n=void 0}}}const ns=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?ts(e,a.issues,i):{success:!0,data:a.value}},rs=/* @__PURE__*/ ns(Wo),is=/* @__PURE__ */ Symbol.for(`zod.compile.invalid`),as=/* @__PURE__ */ Symbol.for(`zod.compile.fallback`),os=((e,t,n)=>{let r=e._zod.bag.validator;if(r!==void 0){if(r(t)!==is)return!0;if(r.definite===!0&&n===void 0)return!1}return ss(e,t,n)});function ss(e,t,n){let r=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},i=e._zod.bag.fallbackRun,a;if(i?(r[as]=!0,a=i({value:t,issues:[]},r)):a=e._zod.run({value:t,issues:[]},r),a instanceof Promise)throw new No;return a.issues.length===0}const cs=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},ls=e=>{let t=Yo(e),n=(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return t(e,r,o,Jo(n,a))};return n},us=e=>{let t=Yo(e),n=(e,r,i,a)=>t(e,r,i,Jo(n,a));return n},ds=e=>{let t=Zo(e),n=async(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return await t(e,r,o,Jo(n,a))};return n},fs=e=>{let t=Zo(e),n=async(e,r,i,a)=>await t(e,r,i,Jo(n,a));return n},ps=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return $o(e)(t,n,i)},ms=e=>(t,n,r)=>$o(e)(t,n,r),hs=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return ns(e)(t,n,i)},gs=e=>async(t,n,r)=>ns(e)(t,n,r),_s=/^[cC][0-9a-z]{6,}$/,vs=/^[0-9a-z]+$/,ys=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,bs=/^[0-9a-vA-V]{20}$/,xs=/^[A-Za-z0-9]{27}$/,Ss=/^[a-zA-Z0-9_-]{21}$/;function Cs(e){return RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}const ws=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,Ts=/^([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})$/,Es=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)$/,Ds=/^(?:[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 Os(){return RegExp(`^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`,`u`)}const 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])$/,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}|:))$/,js=/^((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])$/,Ms=/^(([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])$/,Ns=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ps=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,Fs=/^https?$/,Is=/^\+[1-9]\d{6,14}$/,Ls=`(?:(?:\\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 Rs(e){return RegExp(`^${e}$`)}const zs=/*@__PURE__*/ Rs(Ls);function Bs(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 Vs(e){return RegExp(`^${Bs(e)}$`)}function Hs(e){let t=[`Z`];e.offset&&t.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let n=`${Bs({precision:e.precision,seconds:!0})}(?:${t.join(`|`)})`,r=e.local?`${n}|${Bs({precision:e.precision})}`:n;return RegExp(`^${Ls}T(?:${r})$`)}const Us=/^[\s\S]{0,}$/,Ws=/^-?\d+$/,Gs=/^-?\d+(?:\.\d+)?$/,Ks=/^(?:true|false)$/i,qs=/^null$/i,Js=/^[^A-Z]*$/,Ys=/^[^a-z]*$/,Xs=/*@__PURE__*/ z(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Zs=e=>{let t=e.value;return!Ta(t)&&t.length!==void 0},Qs={number:`number`,bigint:`bigint`,object:`date`},$s=/*@__PURE__*/ z(`$ZodCheckLessThan`,(e,t)=>{Xs.init(e,t);let n=Qs[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:Qs[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})}}),ec=/*@__PURE__*/ z(`$ZodCheckGreaterThan`,(e,t)=>{Xs.init(e,t);let n=Qs[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:Qs[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})}}),tc=/*@__PURE__*/ z(`$ZodCheckMultipleOf`,(e,t)=>{Xs.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):Da(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})}}),nc=/*@__PURE__*/ z(`$ZodCheckNumberFormat`,(e,t)=>{Xs.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=Ja[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})}}),rc=/*@__PURE__*/ z(`$ZodCheckMaxLength`,(e,t)=>{var n;Xs.init(e,t),(n=e._zod.def).when??(n.when=Zs),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>t.maximum?mo(r):i)<=t.maximum)return;let a=ho(r);n.issues.push({origin:a,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),ic=/*@__PURE__*/ z(`$ZodCheckMinLength`,(e,t)=>{var n;Xs.init(e,t),(n=e._zod.def).when??(n.when=Zs),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>=t.minimum&&i<t.minimum*2?mo(r):i)>=t.minimum)return;let a=ho(r);n.issues.push({origin:a,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),ac=/*@__PURE__*/ z(`$ZodCheckLengthEquals`,(e,t)=>{var n;Xs.init(e,t),(n=e._zod.def).when??(n.when=Zs),e._zod.check=n=>{let r=n.value,i=r.length,a=typeof r==`string`&&i>=t.length&&i<=t.length*2?mo(r):i;if(a===t.length)return;let o=ho(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})}}),oc=/*@__PURE__*/ z(`$ZodCheckStringFormat`,(e,t)=>{var n,r;Xs.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=()=>{})}),sc=/*@__PURE__*/ z(`$ZodCheckRegex`,(e,t)=>{oc.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})}}),cc=/*@__PURE__*/ z(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=Js,oc.init(e,t)}),lc=/*@__PURE__*/ z(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=Ys,oc.init(e,t)}),uc=/*@__PURE__*/ z(`$ZodCheckIncludes`,(e,t)=>{Xs.init(e,t);let n=Wa(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})}}),dc=/*@__PURE__*/ z(`$ZodCheckStartsWith`,(e,t)=>{Xs.init(e,t);let n=RegExp(`^${Wa(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})}}),fc=/*@__PURE__*/ z(`$ZodCheckEndsWith`,(e,t)=>{Xs.init(e,t);let n=RegExp(`.*${Wa(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})}}),pc=/*@__PURE__*/ z(`$ZodCheckOverwrite`,(e,t)=>{Xs.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var mc=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(`
|
|
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(Gr(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(Gr(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(Gr(i.message));return r}}}function Gr(e){if(/<(!doctype|html)\b/i.test(e)){let t=/<title[^>]*>([^<]*)<\/title>/i.exec(e)?.[1]?.replace(/\s+/g,` `).trim();return`Quirl's server didn't answer${t?` (${t})`:``}. Try again in a minute.`}return e.split(`
|
|
15
|
+
`,1)[0]?.trim()??``}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 Kr;(function(e){e.mergeShapes=(e,t)=>({...e,...t})})(Kr||={});const A=k.arrayToEnum([`string`,`nan`,`number`,`integer`,`float`,`boolean`,`date`,`bigint`,`symbol`,`function`,`undefined`,`null`,`array`,`object`,`unknown`,`promise`,`void`,`never`,`map`,`set`]),qr=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 Jr=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()}};Jr.create=e=>new Jr(e);const Yr=(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 Xr=Yr;function Zr(){return Xr}const Qr=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=Zr(),r=Qr({issueData:t,data:e.data,path:e.path,errorMaps:[e.common.contextualErrorMap,e.schemaErrorMap,n,n===Yr?void 0:Yr].filter(e=>!!e)});e.common.issues.push(r)}var $r=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`}),ei=e=>({status:`dirty`,value:e}),ti=e=>({status:`valid`,value:e}),ni=e=>e.status===`aborted`,ri=e=>e.status===`dirty`,ii=e=>e.status===`valid`,ai=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 oi=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 si=(e,t)=>{if(ii(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 Jr(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 qr(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:qr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new $r,ctx:{common:e.parent.common,data:e.data,parsedType:qr(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(ai(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:qr(e)},r=this._parseSync({data:e,path:n.path,parent:n});return si(n,r)}"~validate"(e){let t={common:{issues:[],async:!!this[`~standard`].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:qr(e)};if(!this[`~standard`].async)try{let n=this._parseSync({data:e,path:[],parent:t});return ii(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=>ii(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:qr(e)},r=this._parse({data:e,path:n.path,parent:n}),i=await(ai(r)?r:Promise.resolve(r));return si(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 la({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 ua.create(this,this._def)}nullable(){return da.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return Wi.create(this)}promise(){return ca.create(this,this._def)}or(e){return qi.create([this,e],this._def)}and(e){return Zi.create(this,e,this._def)}transform(e){return new la({...F(this._def),schema:this,typeName:L.ZodEffects,effect:{type:`transform`,transform:e}})}default(e){let t=typeof e==`function`?e:()=>e;return new fa({...F(this._def),innerType:this,defaultValue:t,typeName:L.ZodDefault})}brand(){return new ha({typeName:L.ZodBranded,type:this,...F(this._def)})}catch(e){let t=typeof e==`function`?e:()=>e;return new pa({...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 ga.create(this,e)}readonly(){return _a.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}};const ci=/^c[^\s-]{8,}$/i,li=/^[0-9a-z]+$/,ui=/^[0-9A-HJKMNP-TV-Z]{26}$/i,di=/^[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,fi=/^[a-z0-9_-]{21}$/i,pi=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,mi=/^[-+]?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)?)??$/,hi=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i;let gi;const _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])$/,vi=/^(?:(?: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])$/,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]))$/,bi=/^(([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])$/,xi=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Si=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Ci=`((\\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])))`,wi=RegExp(`^${Ci}$`);function Ti(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 Ei(e){return RegExp(`^${Ti(e)}$`)}function Di(e){let t=`${Ci}T${Ti(e)}`,n=[];return n.push(e.local?`Z?`:`Z`),e.offset&&n.push(`([+-]\\d{2}:?\\d{2})`),t=`${t}(${n.join(`|`)})`,RegExp(`^${t}$`)}function Oi(e,t){return!((t!==`v4`&&t||!_i.test(e))&&(t!==`v6`&&t||!yi.test(e)))}function ki(e,t){if(!pi.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 Ai(e,t){return!((t!==`v4`&&t||!vi.test(e))&&(t!==`v6`&&t||!bi.test(e)))}var ji=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 $r,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`)hi.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`)gi||=RegExp(`^[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`,`u`),gi.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`)di.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`)fi.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`)ci.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`)li.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`)ui.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`?Di(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`?wi.test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{code:j.invalid_string,validation:`date`,message:r.message}),t.dirty()):r.kind===`time`?Ei(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`?mi.test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`duration`,code:j.invalid_string,message:r.message}),t.dirty()):r.kind===`ip`?Oi(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`?ki(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`?Ai(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`?xi.test(e.data)||(n=this._getOrReturnCtx(e,n),M(n,{validation:`base64`,code:j.invalid_string,message:r.message}),t.dirty()):r.kind===`base64url`?Si.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}};ji.create=e=>new ji({checks:[],typeName:L.ZodString,coerce:e?.coerce??!1,...F(e)});function Mi(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 Ni=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 $r;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`?Mi(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)}};Ni.create=e=>new Ni({checks:[],typeName:L.ZodNumber,coerce:e?.coerce||!1,...F(e)});var Pi=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 $r;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}};Pi.create=e=>new Pi({checks:[],typeName:L.ZodBigInt,coerce:e?.coerce??!1,...F(e)});var Fi=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 ti(e.data)}};Fi.create=e=>new Fi({typeName:L.ZodBoolean,coerce:e?.coerce||!1,...F(e)});var Ii=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 $r,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)}};Ii.create=e=>new Ii({checks:[],coerce:e?.coerce||!1,typeName:L.ZodDate,...F(e)});var Li=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 ti(e.data)}};Li.create=e=>new Li({typeName:L.ZodSymbol,...F(e)});var Ri=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 ti(e.data)}};Ri.create=e=>new Ri({typeName:L.ZodUndefined,...F(e)});var zi=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 ti(e.data)}};zi.create=e=>new zi({typeName:L.ZodNull,...F(e)});var Bi=class extends I{constructor(){super(...arguments),this._any=!0}_parse(e){return ti(e.data)}};Bi.create=e=>new Bi({typeName:L.ZodAny,...F(e)});var Vi=class extends I{constructor(){super(...arguments),this._unknown=!0}_parse(e){return ti(e.data)}};Vi.create=e=>new Vi({typeName:L.ZodUnknown,...F(e)});var Hi=class extends I{_parse(e){let t=this._getOrReturnCtx(e);return M(t,{code:j.invalid_type,expected:A.never,received:t.parsedType}),N}};Hi.create=e=>new Hi({typeName:L.ZodNever,...F(e)});var Ui=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 ti(e.data)}};Ui.create=e=>new Ui({typeName:L.ZodVoid,...F(e)});var Wi=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 oi(t,e,t.path,n)))).then(e=>$r.mergeArray(n,e));let i=[...t.data].map((e,n)=>r.type._parseSync(new oi(t,e,t.path,n)));return $r.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)}};Wi.create=(e,t)=>new Wi({type:e,minLength:null,maxLength:null,exactLength:null,typeName:L.ZodArray,...F(t)});function Gi(e){if(e instanceof Ki){let t={};for(let n in e.shape){let r=e.shape[n];t[n]=ua.create(Gi(r))}return new Ki({...e._def,shape:()=>t})}return e instanceof Wi?new Wi({...e._def,type:Gi(e.element)}):e instanceof ua?ua.create(Gi(e.unwrap())):e instanceof da?da.create(Gi(e.unwrap())):e instanceof Qi?Qi.create(e.items.map(e=>Gi(e))):e}var Ki=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 Hi&&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 oi(n,i,n.path,e)),alwaysSet:e in n.data})}if(this._def.catchall instanceof Hi){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 oi(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=>$r.mergeObjectSync(t,e)):$r.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 Gi(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 ua;)t=t._def.innerType;n[e]=t}return new e({...this._def,shape:()=>n})}keyof(){return aa(k.objectKeys(this.shape))}};Ki.create=(e,t)=>new Ki({shape:()=>e,unknownKeys:`strip`,catchall:Hi.create(),typeName:L.ZodObject,...F(t)}),Ki.strictCreate=(e,t)=>new Ki({shape:()=>e,unknownKeys:`strict`,catchall:Hi.create(),typeName:L.ZodObject,...F(t)}),Ki.lazycreate=(e,t)=>new Ki({shape:e,unknownKeys:`strip`,catchall:Hi.create(),typeName:L.ZodObject,...F(t)});var qi=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 Jr(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 Jr(e));return M(t,{code:j.invalid_union,unionErrors:i}),N}}get options(){return this._def.options}};qi.create=(e,t)=>new qi({options:e,typeName:L.ZodUnion,...F(t)});const Ji=e=>e instanceof ra?Ji(e.schema):e instanceof la?Ji(e.innerType()):e instanceof ia?[e.value]:e instanceof oa?e.options:e instanceof sa?k.objectValues(e.enum):e instanceof fa?Ji(e._def.innerType):e instanceof Ri?[void 0]:e instanceof zi?[null]:e instanceof ua?[void 0,...Ji(e.unwrap())]:e instanceof da?[null,...Ji(e.unwrap())]:e instanceof ha||e instanceof _a?Ji(e.unwrap()):e instanceof pa?Ji(e._def.innerType):[];var Yi=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=Ji(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 Xi(e,t){let n=qr(e),r=qr(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=Xi(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=Xi(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 Zi=class extends I{_parse(e){let{status:t,ctx:n}=this._processInputParams(e),r=(e,r)=>{if(ni(e)||ni(r))return N;let i=Xi(e.value,r.value);return i.valid?((ri(e)||ri(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}))}};Zi.create=(e,t,n)=>new Zi({left:e,right:t,typeName:L.ZodIntersection,...F(n)});var Qi=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 oi(n,e,n.path,t)):null}).filter(e=>!!e);return n.common.async?Promise.all(r).then(e=>$r.mergeArray(t,e)):$r.mergeArray(t,r)}get items(){return this._def.items}rest(t){return new e({...this._def,rest:t})}};Qi.create=(e,t)=>{if(!Array.isArray(e))throw Error(`You must pass an array of schemas to z.tuple([ ... ])`);return new Qi({items:e,typeName:L.ZodTuple,rest:null,...F(t)})};var $i=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 oi(n,e,n.path,e)),value:a._parse(new oi(n,n.data[e],n.path,e)),alwaysSet:e in n.data});return n.common.async?$r.mergeObjectAsync(t,r):$r.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:ji.create(),valueType:t,typeName:L.ZodRecord,...F(n)})}},ea=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 oi(n,e,n.path,[a,`key`])),value:i._parse(new oi(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}}}};ea.create=(e,t,n)=>new ea({valueType:t,keyType:e,typeName:L.ZodMap,...F(n)});var ta=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 oi(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)}};ta.create=(e,t)=>new ta({valueType:e,minSize:null,maxSize:null,typeName:L.ZodSet,...F(t)});var na=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 Qr({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Zr(),Yr].filter(e=>!!e),issueData:{code:j.invalid_arguments,argumentsError:n}})}function r(e,n){return Qr({data:e,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,Zr(),Yr].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 ca){let e=this;return ti(async function(...t){let o=new Jr([]),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 ti(function(...t){let o=e._def.args.safeParse(t,i);if(!o.success)throw new Jr([n(t,o.error)]);let s=Reflect.apply(a,this,o.data),c=e._def.returns.safeParse(s,i);if(!c.success)throw new Jr([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:Qi.create(t).rest(Vi.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||Qi.create([]).rest(Vi.create()),returns:n||Vi.create(),typeName:L.ZodFunction,...F(r)})}},ra=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})}};ra.create=(e,t)=>new ra({getter:e,typeName:L.ZodLazy,...F(t)});var ia=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}};ia.create=(e,t)=>new ia({value:e,typeName:L.ZodLiteral,...F(t)});function aa(e,t){return new oa({values:e,typeName:L.ZodEnum,...F(t)})}var oa=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 ti(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})}};oa.create=aa;var sa=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 ti(e.data)}get enum(){return this._def.values}};sa.create=(e,t)=>new sa({values:e,typeName:L.ZodNativeEnum,...F(t)});var ca=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 ti(n.then(e=>this._def.type.parseAsync(e,{path:t.path,errorMap:t.common.contextualErrorMap})))}};ca.create=(e,t)=>new ca({type:e,typeName:L.ZodPromise,...F(t)});var la=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`?ei(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`?ei(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(!ii(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=>ii(e)?Promise.resolve(r.transform(e.value,i)).then(e=>({status:t.value,value:e})):N)}k.assertNever(r)}};la.create=(e,t,n)=>new la({schema:e,typeName:L.ZodEffects,effect:t,...F(n)}),la.createWithPreprocess=(e,t,n)=>new la({schema:t,effect:{type:`preprocess`,transform:e},typeName:L.ZodEffects,...F(n)});var ua=class extends I{_parse(e){return this._getType(e)===A.undefined?ti(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ua.create=(e,t)=>new ua({innerType:e,typeName:L.ZodOptional,...F(t)});var da=class extends I{_parse(e){return this._getType(e)===A.null?ti(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};da.create=(e,t)=>new da({innerType:e,typeName:L.ZodNullable,...F(t)});var fa=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}};fa.create=(e,t)=>new fa({innerType:e,typeName:L.ZodDefault,defaultValue:typeof t.default==`function`?t.default:()=>t.default,...F(t)});var pa=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 ai(r)?r.then(e=>({status:`valid`,value:e.status===`valid`?e.value:this._def.catchValue({get error(){return new Jr(n.common.issues)},input:n.data})})):{status:`valid`,value:r.status===`valid`?r.value:this._def.catchValue({get error(){return new Jr(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};pa.create=(e,t)=>new pa({innerType:e,typeName:L.ZodCatch,catchValue:typeof t.catch==`function`?t.catch:()=>t.catch,...F(t)});var ma=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}}};ma.create=e=>new ma({typeName:L.ZodNaN,...F(e)});var ha=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}},ga=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(),ei(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})}},_a=class extends I{_parse(e){let t=this._def.innerType._parse(e),n=e=>(ii(e)&&(e.value=Object.freeze(e.value)),e);return ai(t)?t.then(e=>n(e)):n(t)}unwrap(){return this._def.innerType}};_a.create=(e,t)=>new _a({innerType:e,typeName:L.ZodReadonly,...F(t)}),Ki.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||={}),ji.create,Ni.create,ma.create,Pi.create,Fi.create,Ii.create,Li.create,Ri.create,zi.create,Bi.create,Vi.create,Hi.create,Ui.create,Wi.create;const va=Ki.create;Ki.strictCreate,qi.create,Yi.create,Zi.create,Qi.create,$i.create,ea.create,ta.create,na.create,ra.create,ia.create,oa.create,sa.create,ca.create,la.create,ua.create,da.create,la.createWithPreprocess,ga.create;function ya(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 ba(e,t=`|`){return e.map(e=>Ga(e)).join(t)}function xa(e,t){return typeof t==`bigint`?t.toString():t}var Sa=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 Ca(e){return new Sa(e)}function wa(e){return e==null}function Ta(e){let t=+!!e.startsWith(`^`),n=e.endsWith(`$`)?e.length-1:e.length;return e.slice(t,n)}function Ea(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 Da(e,t,n){Object.defineProperty(e,t,{value:n,writable:!0,enumerable:!0,configurable:!0})}function Oa(e){let t=Object.getOwnPropertyDescriptor(e,`shape`);return t?.get?t.get.raw:t?.value}function ka(e){return Oa(e._zod.def)??e._zod.def.shape}function Aa(e,t,n){Object.defineProperty(e,t,{get(){let e=n();return Da(this,t,e),e},enumerable:!0,configurable:!0})}function ja(e,t,n){t in e?Da(e,t,n):e[t]=n}function Ma(e,t,n,r){let i=ka(t);for(let a of n){let n=Object.getOwnPropertyDescriptor(i,a);n.enumerable&&(n.get?Aa(e,a,()=>{let e=t._zod.def.shape[a];return r?r(e,a):e}):ja(e,a,r?r(n.value,a):n.value))}}function Na(e,t){for(let n of Reflect.ownKeys(t)){let r=Object.getOwnPropertyDescriptor(t,n);r.enumerable&&(r.get?Aa(e,n,()=>t[n]):ja(e,n,r.value))}}function Pa(...e){let t={};for(let n of e){let e=Object.getOwnPropertyDescriptors(n);Object.assign(t,e)}return Object.defineProperties({},t)}function Fa(e){return JSON.stringify(e)}function Ia(e){return e.toLowerCase().trim().replace(/[^\w\s-]/g,``).replace(/[\s_-]+/g,`-`).replace(/^-+|-+$/g,``)}const La=`captureStackTrace`in Error?Error.captureStackTrace:(...e)=>{};function Ra(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}const za=/* @__PURE__*/ Ca(()=>{if(Po.jitless||typeof navigator<`u`&&navigator?.userAgent?.includes(`Cloudflare`))return!1;try{return Function(``),!0}catch{return!1}});function Ba(e){if(Ra(e)===!1)return!1;let t=e.constructor;if(t===void 0||typeof t!=`function`)return!0;let n=t.prototype;return Ra(n)!==!1&&Object.prototype.hasOwnProperty.call(n,`isPrototypeOf`)!==!1}function Va(e){return Ba(e)?{...e}:Array.isArray(e)?[...e]:e instanceof Map?new Map(e):e instanceof Set?new Set(e):e}const Ha=/* @__PURE__*/ new Set([`string`,`number`,`symbol`]);function Ua(e){return e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}function Wa(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 Ga(e){return typeof e==`bigint`?e.toString()+`n`:typeof e==`string`?`"${e}"`:`${e}`}function Ka(e){return Object.keys(e).filter(t=>e[t]._zod.optin!==void 0&&e[t]._zod.optout===`optional`)}const qa={safeint:[-(2**53-1),2**53-1],int32:[-2147483648,2147483647],uint32:[0,4294967295],float32:[-34028234663852886e22,34028234663852886e22],float64:[-Number.MAX_VALUE,Number.MAX_VALUE]},Ja={int64:[/* @__PURE__*/ BigInt(`-9223372036854775808`),/* @__PURE__*/ BigInt(`9223372036854775807`)],uint64:[/* @__PURE__*/ BigInt(0),/* @__PURE__*/ BigInt(`18446744073709551615`)]};function Ya(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 Ma(i,e,Xa(e,t)),Wa(e,Pa(n,{shape:i,checks:[]}))}function Xa(e,t){let n=ka(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 Za(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(Xa(e,t)),a={};return Ma(a,e,Reflect.ownKeys(ka(e)).filter(e=>!i.has(e))),Wa(e,Pa(n,{shape:a,checks:[]}))}function Qa(e,t){if(!Ba(t))throw Error(`Invalid input to extend: expected a plain object`);let n=e._zod.def.checks;if(n&&n.length>0){let n=ka(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 Wa(e,Pa(e._zod.def,{shape:$a(e,t)}))}function $a(e,t){let n={};return Ma(n,e,Reflect.ownKeys(ka(e))),Na(n,t),n}function eo(e,t){if(!Ba(t))throw Error(`Invalid input to safeExtend: expected a plain object`);return Wa(e,Pa(e._zod.def,{shape:$a(e,t)}))}function to(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 Ma(n,e,Reflect.ownKeys(ka(e))),Ma(n,t,Reflect.ownKeys(ka(t))),Wa(e,Pa(e._zod.def,{shape:n,get catchall(){return t._zod.def.catchall},checks:t._zod.def.checks??[]}))}function no(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(Xa(t,n)):void 0,o={};return Ma(o,t,Reflect.ownKeys(ka(t)),e&&((t,n)=>a&&!a.has(n)?t:new e({type:`optional`,innerType:t}))),Wa(t,Pa(t._zod.def,{shape:o,checks:[]}))}function ro(e,t,n){let r=n?new Set(Xa(t,n)):void 0,i={};return Ma(i,t,Reflect.ownKeys(ka(t)),(t,n)=>r&&!r.has(n)?t:new e({type:`nonoptional`,innerType:t})),Wa(t,Pa(t._zod.def,{shape:i}))}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!==!0)return!0;return!1}function ao(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 oo(e,t){return t.map(t=>{var n;return(n=t).path??(n.path=[]),t.path.unshift(e),t})}function so(e){return typeof e==`string`?e:e?.message}function co(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 lo(e,t,n){var r;for(let i=t;i<e.length;i++)(r=e[i]).schema??(r.schema=n)}function uo(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:so(e.inst?._zod.def?.error?.(e))??so(a?.(e))??so(t?.error?.(e))??so(n.customError?.(e))??so(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 fo=/[\uD800-\uDBFF]/;function po(e){let t=e.length;if(!fo.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 mo(e){return Array.isArray(e)?`array`:typeof e==`string`?`string`:`unknown`}function ho(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 go(...e){let[t,n,r]=e;return typeof t==`string`?{message:t,code:`custom`,input:n,inst:r}:{...t}}function _o(e,t){for(let n in t){let r=Object.getOwnPropertyDescriptor(t,n);r.get?Object.defineProperty(e,n,{...r,enumerable:!1}):xo(e,n,r.value)}}function vo(e,t,n,r=!0){return Object.defineProperty(e,t,{configurable:!0,writable:!0,enumerable:r,value:n}),n}function yo(e,t,n){return vo(e,t,n,!1)}/* @__NO_SIDE_EFFECTS__ */
|
|
16
|
+
function bo(e,t){for(let n in e){let r=e[n];Object.defineProperty(t,n,{configurable:!0,enumerable:!0,get(){return vo(this,n,r(this))},set(e){vo(this,n,e)}})}return t}function xo(e,t,n){Object.defineProperty(e,t,{configurable:!0,get(){return this==null?n:vo(this,t,n.bind(this))},set(e){vo(this,t,e)}})}function So(e,t){let n=Object.getPrototypeOf(e);return t in n?void 0:n}let Co,wo=!1;const To={configurable:!0,get(){wo=!0}};function z(e,t,n){let r=Object.getPrototypeOf(e._zod);t in r&&Co!==e._zod?Co=void 0:(Co=e._zod,Object.defineProperty(r,t,{configurable:!0,get(){Object.defineProperty(this,t,To);let e=wo;wo=!1;try{let r=n(this);return wo?delete this[t]:Object.defineProperty(this,t,{configurable:!0,writable:!0,value:r}),wo||=e,r}catch(n){throw delete this[t],wo||=e,n}},set(e){Object.defineProperty(this,t,{configurable:!0,writable:!0,value:e})}}))}function Eo(e,t,n,r){let i=So(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 Do(e){let t=()=>e;return t[`~constantCatch`]=!0,t}var Oo;const ko={value:void 0,enumerable:!1};let Ao=`captureStackTrace`in Error?Error:null;function jo(e){let t=Ao;if(t){let n=t.stackTraceLimit;if(typeof n==`number`){try{t.stackTraceLimit=0}catch{return Ao=null,new e}try{return new e}finally{t.stackTraceLimit=n}}}return new e}/* @__NO_SIDE_EFFECTS__ */
|
|
17
|
+
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){ko.value=new a(r);try{Object.defineProperty(n,"_zod",ko)}finally{ko.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),_o(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?jo(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 Mo=class extends Error{constructor(){super(`Encountered Promise during synchronous parse. Use .parseAsync() instead.`)}},No=class extends Error{constructor(e){super(`Encountered unidirectional transform during encode: ${e}`),this.name=`ZodEncodeError`}};(Oo=globalThis).__zod_globalConfig??(Oo.__zod_globalConfig={});const Po=globalThis.__zod_globalConfig;function Fo(e){return e&&Object.assign(Po,e),Po}function Io(){let e=this._zod;return e.message??=JSON.stringify(e.def,xa,2),e.message}function Lo(e){this._zod.message=e}const Ro={get:Io,set:Lo,enumerable:!0,configurable:!0},zo={value:void 0,enumerable:!1},Bo=/* @__PURE__ */ new WeakSet([Object.prototype,Error.prototype]),Vo=(e,t)=>{e.name=`$ZodError`,zo.value=t,Object.defineProperty(e,"issues",zo),zo.value=void 0,Object.defineProperty(e,"message",Ro);let n=Object.getPrototypeOf(e);Bo.has(n)||(Bo.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})}}))},Ho=/* @__PURE__ */ B(`$ZodError`,Vo),Uo=/* @__PURE__ */ B(`$ZodError`,Vo,void 0,{Parent:Error});function Wo(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 Go(e,t=e=>e.message){let n={},r=[];for(let i of e.issues)i.path.length>0?Wo(n,i.path[0],()=>[]).push(t(i)):r.push(t(i));return{formErrors:r,fieldErrors:n}}function Ko(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 qo(e,t){return{callee:t?.callee??e,Err:t?.Err}}const Jo=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 Mo;if(s.issues.length){let n=new((a?.Err)??e)(s.issues.map(e=>uo(e,o,Fo())));throw La(n,a?.callee??t),n}return s.value};return t},Yo=/* @__PURE__*/ Jo(Uo),Xo=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=>uo(e,o,Fo())));throw La(n,a?.callee??t),n}return s.value};return t},Zo=/* @__PURE__*/ Xo(Uo),Qo=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 Mo;return a.issues.length?es(e,a.issues,i):{success:!0,data:a.value}},$o=/* @__PURE__*/ Qo(Uo);function es(e,t,n){let r;return{success:!1,get error(){return r||(r=new e(t.map(e=>uo(e,n,Fo()))),t=void 0,n=void 0),r},set error(e){r=e,t=void 0,n=void 0}}}const ts=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?es(e,a.issues,i):{success:!0,data:a.value}},ns=/* @__PURE__*/ ts(Uo),rs=/* @__PURE__ */ Symbol.for(`zod.compile.invalid`),is=/* @__PURE__ */ Symbol.for(`zod.compile.fallback`),as=((e,t,n)=>{let r=e._zod.bag.validator;if(r!==void 0){if(r(t)!==rs)return!0;if(r.definite===!0&&n===void 0)return!1}return os(e,t,n)});function os(e,t,n){let r=n?{...n,async:!1,abortEarly:!0}:{async:!1,abortEarly:!0},i=e._zod.bag.fallbackRun,a;if(i?(r[is]=!0,a=i({value:t,issues:[]},r)):a=e._zod.run({value:t,issues:[]},r),a instanceof Promise)throw new Mo;return a.issues.length===0}const ss=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},cs=e=>{let t=Jo(e),n=(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return t(e,r,o,qo(n,a))};return n},ls=e=>{let t=Jo(e),n=(e,r,i,a)=>t(e,r,i,qo(n,a));return n},us=e=>{let t=Xo(e),n=async(e,r,i,a)=>{let o=i?{...i,direction:`backward`}:{direction:`backward`};return await t(e,r,o,qo(n,a))};return n},ds=e=>{let t=Xo(e),n=async(e,r,i,a)=>await t(e,r,i,qo(n,a));return n},fs=e=>(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return Qo(e)(t,n,i)},ps=e=>(t,n,r)=>Qo(e)(t,n,r),ms=e=>async(t,n,r)=>{let i=r?{...r,direction:`backward`}:{direction:`backward`};return ts(e)(t,n,i)},hs=e=>async(t,n,r)=>ts(e)(t,n,r),gs=/^[cC][0-9a-z]{6,}$/,_s=/^[0-9a-z]+$/,vs=/^[0-7][0-9A-HJKMNP-TV-Za-hjkmnp-tv-z]{25}$/,ys=/^[0-9a-vA-V]{20}$/,bs=/^[A-Za-z0-9]{27}$/,xs=/^[a-zA-Z0-9_-]{21}$/;function Ss(e){return RegExp(`^[a-zA-Z0-9_-]{${e}}$`)}const Cs=/^P(?:(\d+W)|(?!.*W)(?=\d|T\d)(\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+([.,]\d+)?S)?)?)$/,ws=/^([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})$/,Ts=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)$/,Es=/^(?:[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 Ds(){return RegExp(`^(?=[\\s\\S]*[\\p{Extended_Pictographic}\\p{Regional_Indicator}\\u20E3])[\\p{Extended_Pictographic}\\p{Emoji_Component}]+$`,`u`)}const Os=/^(?:(?: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])$/,ks=/^(([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}|:))$/,As=/^((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])$/,js=/^(([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])$/,Ms=/^$|^(?:[0-9a-zA-Z+/]{4})*(?:(?:[0-9a-zA-Z+/]{2}==)|(?:[0-9a-zA-Z+/]{3}=))?$/,Ns=/^(?:[A-Za-z0-9_-]{4})*(?:[A-Za-z0-9_-]{2,3})?$/,Ps=/^https?$/,Fs=/^\+[1-9]\d{6,14}$/,Is=`(?:(?:\\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 Ls(e){return RegExp(`^${e}$`)}const Rs=/*@__PURE__*/ Ls(Is);function zs(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 Bs(e){return RegExp(`^${zs(e)}$`)}function Vs(e){let t=[`Z`];e.offset&&t.push(`([+-](?:[01]\\d|2[0-3]):[0-5]\\d)`);let n=`${zs({precision:e.precision,seconds:!0})}(?:${t.join(`|`)})`,r=e.local?`${n}|${zs({precision:e.precision})}`:n;return RegExp(`^${Is}T(?:${r})$`)}const Hs=/^[\s\S]{0,}$/,Us=/^-?\d+$/,Ws=/^-?\d+(?:\.\d+)?$/,Gs=/^(?:true|false)$/i,Ks=/^null$/i,qs=/^[^A-Z]*$/,Js=/^[^a-z]*$/,Ys=/*@__PURE__*/ B(`$ZodCheck`,(e,t)=>{var n;e._zod??={},e._zod.def=t,(n=e._zod).onattach??(n.onattach=[])}),Xs=e=>{let t=e.value;return!wa(t)&&t.length!==void 0},Zs={number:`number`,bigint:`bigint`,object:`date`},Qs=/*@__PURE__*/ B(`$ZodCheckLessThan`,(e,t)=>{Ys.init(e,t);let n=Zs[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value<=t.value:r.value<t.value)||r.issues.push({origin:Zs[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})}}),$s=/*@__PURE__*/ B(`$ZodCheckGreaterThan`,(e,t)=>{Ys.init(e,t);let n=Zs[typeof t.value];e._zod.check=r=>{(t.inclusive?r.value>=t.value:r.value>t.value)||r.issues.push({origin:Zs[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})}}),ec=/*@__PURE__*/ B(`$ZodCheckMultipleOf`,(e,t)=>{Ys.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):Ea(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})}}),tc=/*@__PURE__*/ B(`$ZodCheckNumberFormat`,(e,t)=>{Ys.init(e,t),t.format=t.format||`float64`;let n=t.format?.includes(`int`),r=n?`int`:`number`,[i,a]=qa[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})}}),nc=/*@__PURE__*/ B(`$ZodCheckMaxLength`,(e,t)=>{var n;Ys.init(e,t),(n=e._zod.def).when??(n.when=Xs),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>t.maximum?po(r):i)<=t.maximum)return;let a=mo(r);n.issues.push({origin:a,code:`too_big`,maximum:t.maximum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),rc=/*@__PURE__*/ B(`$ZodCheckMinLength`,(e,t)=>{var n;Ys.init(e,t),(n=e._zod.def).when??(n.when=Xs),e._zod.check=n=>{let r=n.value,i=r.length;if((typeof r==`string`&&i>=t.minimum&&i<t.minimum*2?po(r):i)>=t.minimum)return;let a=mo(r);n.issues.push({origin:a,code:`too_small`,minimum:t.minimum,inclusive:!0,input:r,inst:e,continue:!t.abort})}}),ic=/*@__PURE__*/ B(`$ZodCheckLengthEquals`,(e,t)=>{var n;Ys.init(e,t),(n=e._zod.def).when??(n.when=Xs),e._zod.check=n=>{let r=n.value,i=r.length,a=typeof r==`string`&&i>=t.length&&i<=t.length*2?po(r):i;if(a===t.length)return;let o=mo(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})}}),ac=/*@__PURE__*/ B(`$ZodCheckStringFormat`,(e,t)=>{var n,r;Ys.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=()=>{})}),oc=/*@__PURE__*/ B(`$ZodCheckRegex`,(e,t)=>{ac.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})}}),sc=/*@__PURE__*/ B(`$ZodCheckLowerCase`,(e,t)=>{t.pattern??=qs,ac.init(e,t)}),cc=/*@__PURE__*/ B(`$ZodCheckUpperCase`,(e,t)=>{t.pattern??=Js,ac.init(e,t)}),lc=/*@__PURE__*/ B(`$ZodCheckIncludes`,(e,t)=>{Ys.init(e,t);let n=Ua(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})}}),uc=/*@__PURE__*/ B(`$ZodCheckStartsWith`,(e,t)=>{Ys.init(e,t);let n=RegExp(`^${Ua(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})}}),dc=/*@__PURE__*/ B(`$ZodCheckEndsWith`,(e,t)=>{Ys.init(e,t);let n=RegExp(`.*${Ua(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})}}),fc=/*@__PURE__*/ B(`$ZodCheckOverwrite`,(e,t)=>{Ys.init(e,t),e._zod.check=e=>{e.value=t.tx(e.value)}});var pc=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(`
|
|
18
18
|
`).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(`
|
|
19
|
-
`)}\n};`)(...Object.values(this.closed))}};const hc={major:4,minor:6,patch:7},gc=/*@__PURE__*/ z(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=hc;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=ao(t),a;for(let o of n){if(o._zod.def.when){if(oo(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 No;if(a||s instanceof Promise)a=(a??Promise.resolve()).then(async()=>{await s,t.issues.length!==n&&(uo(t.issues,n,e),i||=ao(t,n))});else{if(t.issues.length===n)continue;uo(t.issues,n,e),i||=ao(t,n)}}return a?a.then(()=>t):t},n=(n,r,a)=>{if(ao(n))return n.aborted=!0,n;let o=t(r,i,a);if(o instanceof Promise){if(a.async===!1)throw new No;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 No;return o.then(e=>t(e,i,a))}return t(o,i,a)}}},{get"~standard"(){return bo(this,`~standard`,yc(this))},set"~standard"(e){yo(this,`~standard`,e)}}),_c=(e,t)=>e.issues.length?{issues:e.issues.map(e=>fo(e,t,Io()))}:{value:e.value};async function vc(e,t){let n={async:!0};return _c(await e._zod.run({value:t,issues:[]},n),n)}function yc(e){return{validate:t=>{let n={async:!1};try{let r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return _c(r,n)}catch{}return vc(e,t)},vendor:`zod`,version:1}}const bc=/*@__PURE__*/ z(`$ZodString`,(e,t)=>{gc.init(e,t),e._zod.pattern=t.pattern??Us,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}}),xc=/*@__PURE__*/ z(`$ZodStringFormat`,(e,t)=>{oc.init(e,t),bc.init(e,t)}),Sc=/*@__PURE__*/ z(`$ZodGUID`,(e,t)=>{t.pattern??=Ts,xc.init(e,t)}),Cc=/*@__PURE__*/ z(`$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??=Es(e)}else t.pattern??=Es();xc.init(e,t)}),wc=/*@__PURE__*/ z(`$ZodEmail`,(e,t)=>{t.pattern??=Ds,xc.init(e,t)});function Tc(e){try{return typeof URL<`u`&&typeof URL.canParse==`function`?URL.canParse(e):(new URL(e),!0)}catch{return!1}}function Ec(e,t){return!(`normalize`in t)&&!(`hostname`in t)&&!(`protocol`in t)?Tc(e)||2:Dc(e,t)}function Dc(e,t){if(!t.normalize&&t.protocol?.source===Fs.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 Oc=/[\t\n\r]/g;function kc(e){return e.replace(Oc,``)}function Ac(e,t){return t.lastIndex=0,t.test(e.hostname)}function jc(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(`:`)?e.protocol.slice(0,-1):e.protocol)}const Mc=/*@__PURE__*/ z(`$ZodURL`,(e,t)=>{xc.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),i=Ec(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=kc(r);return}t.hostname&&!Ac(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&&!jc(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:kc(r);return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),Nc=/*@__PURE__*/ z(`$ZodEmoji`,(e,t)=>{t.pattern??=Os(),xc.init(e,t)}),Pc=/*@__PURE__*/ z(`$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?Ss:Cs(t.length),xc.init(e,t)}),Fc=/*@__PURE__*/ z(`$ZodCUID`,(e,t)=>{t.pattern??=_s,xc.init(e,t)}),Ic=/*@__PURE__*/ z(`$ZodCUID2`,(e,t)=>{t.pattern??=vs,xc.init(e,t)}),Lc=/*@__PURE__*/ z(`$ZodULID`,(e,t)=>{t.pattern??=ys,xc.init(e,t)}),Rc=/*@__PURE__*/ z(`$ZodXID`,(e,t)=>{t.pattern??=bs,xc.init(e,t)}),zc=/*@__PURE__*/ z(`$ZodKSUID`,(e,t)=>{t.pattern??=xs,xc.init(e,t)}),Bc=/*@__PURE__*/ z(`$ZodISODateTime`,(e,t)=>{t.pattern??=Hs(t),xc.init(e,t)}),Vc=/*@__PURE__*/ z(`$ZodISODate`,(e,t)=>{t.pattern??=zs,xc.init(e,t)}),Hc=/*@__PURE__*/ z(`$ZodISOTime`,(e,t)=>{t.pattern??=Vs(t),xc.init(e,t)}),Uc=/*@__PURE__*/ z(`$ZodISODuration`,(e,t)=>{t.pattern??=ws,xc.init(e,t)}),Wc=/*@__PURE__*/ z(`$ZodIPv4`,(e,t)=>{t.pattern??=ks,xc.init(e,t)}),Gc=/^[0-9a-fA-F:.]+$/;function Kc(e){return Gc.test(e)?Tc(`http://[${e}]`):!1}const qc=/*@__PURE__*/ z(`$ZodIPv6`,(e,t)=>{t.pattern??=As,xc.init(e,t),e._zod.check=n=>{Kc(n.value)||n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}),Jc=/*@__PURE__*/ z(`$ZodCIDRv4`,(e,t)=>{t.pattern??=js,xc.init(e,t)});function Yc(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:Kc(n)}const Xc=/*@__PURE__*/ z(`$ZodCIDRv6`,(e,t)=>{t.pattern??=Ms,xc.init(e,t),e._zod.check=n=>{Yc(n.value)||n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}});function Zc(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const Qc=/^[0-9a-zA-Z+/]*={0,2}$/,$c=/*@__PURE__*/ z(`$ZodBase64`,(e,t)=>{t.pattern??=Qc,xc.init(e,t),e._zod.check=n=>{Zc(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}}),el=/^[A-Za-z0-9_-]*$/;function tl(e){if(!el.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return Zc(t.padEnd(Math.ceil(t.length/4)*4,`=`))}const nl=/*@__PURE__*/ z(`$ZodBase64URL`,(e,t)=>{t.pattern??=el,xc.init(e,t),e._zod.check=n=>{tl(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),rl=/*@__PURE__*/ z(`$ZodE164`,(e,t)=>{t.pattern??=Is,xc.init(e,t)});function il(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 al=/*@__PURE__*/ z(`$ZodJWT`,(e,t)=>{xc.init(e,t),e._zod.check=n=>{il(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),ol=/*@__PURE__*/ z(`$ZodNumber`,(e,t)=>{gc.init(e,t),e._zod.pattern=Gs,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}}),sl=/*@__PURE__*/ z(`$ZodNumberFormat`,(e,t)=>{nc.init(e,t),ol.init(e,t)}),cl=/*@__PURE__*/ z(`$ZodBoolean`,(e,t)=>{gc.init(e,t),e._zod.pattern=Ks,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}}),ll=/*@__PURE__*/ z(`$ZodNull`,(e,t)=>{gc.init(e,t),e._zod.pattern=qs,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}}),ul=/*@__PURE__*/ z(`$ZodUnknown`,(e,t)=>{gc.init(e,t),e._zod.parse=e=>e}),dl=/*@__PURE__*/ z(`$ZodNever`,(e,t)=>{gc.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function fl(e,t){let n=lo(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 lo(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,uo(n.issues,t,e),n}}return i(n,a)}}const pl=e=>Array.isArray(e)?e.length:-1;function ml(e,t,n){e.issues.length&&t.issues.push(...so(n,e.issues)),t.value[n]=e.value}const hl=/*@__PURE__*/ z(`$ZodArray`,(e,t)=>{gc.init(e,t);let n=Fo.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=>ml(t,r,e)));else if(ml(c,r,e),s&&c.issues.length!==0&&ao(c))break}return o.length?Promise.all(o).then(()=>r):r},fl(e,pl)});function gl(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(...so(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 _l=[];function vl(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:_l,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=qa(e.shape);return{...e,allKeys:i,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(a)}}function yl(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(ao(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=>gl(e,n,i,t,d,f))):gl(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 bl=/*@__PURE__*/ z(`$ZodObject`,(e,t)=>{gc.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=wa(()=>vl(t));R(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)||Oa(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=za,o=t.catchall,s,c=Fo.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(ao(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=>gl(n,t,e,r,a,o))):gl(s,t,e,r,a,o)}return o?yl(l,r,t,n,i.value,e,d===!0):l.length?Promise.all(l).then(()=>t):t}}),xl=/*@__PURE__*/ z(`$ZodObjectJIT`,(e,t)=>{bl.init(e,t);let n=e._zod.parse,r=wa(()=>vl(t)),i=Fo.memoizer,a=t=>{let n=r.value,a=n.symbolKeys,o=new mc([`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
|
+
`)}\n};`)(...Object.values(this.closed))}};const mc={major:4,minor:6,patch:7},hc=/*@__PURE__*/ B(`$ZodType`,(e,t)=>{var n;e??={},e._zod.def=t,e._zod.bag=e._zod.bag||{},e._zod.version=mc;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=io(t),a;for(let o of n){if(o._zod.def.when){if(ao(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 Mo;if(a||s instanceof Promise)a=(a??Promise.resolve()).then(async()=>{await s,t.issues.length!==n&&(lo(t.issues,n,e),i||=io(t,n))});else{if(t.issues.length===n)continue;lo(t.issues,n,e),i||=io(t,n)}}return a?a.then(()=>t):t},n=(n,r,a)=>{if(io(n))return n.aborted=!0,n;let o=t(r,i,a);if(o instanceof Promise){if(a.async===!1)throw new Mo;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 Mo;return o.then(e=>t(e,i,a))}return t(o,i,a)}}},{get"~standard"(){return yo(this,`~standard`,vc(this))},set"~standard"(e){vo(this,`~standard`,e)}}),gc=(e,t)=>e.issues.length?{issues:e.issues.map(e=>uo(e,t,Fo()))}:{value:e.value};async function _c(e,t){let n={async:!0};return gc(await e._zod.run({value:t,issues:[]},n),n)}function vc(e){return{validate:t=>{let n={async:!1};try{let r=e._zod.run({value:t,issues:[]},n);if(!(r instanceof Promise))return gc(r,n)}catch{}return _c(e,t)},vendor:`zod`,version:1}}const yc=/*@__PURE__*/ B(`$ZodString`,(e,t)=>{hc.init(e,t),e._zod.pattern=t.pattern??Hs,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}}),bc=/*@__PURE__*/ B(`$ZodStringFormat`,(e,t)=>{ac.init(e,t),yc.init(e,t)}),xc=/*@__PURE__*/ B(`$ZodGUID`,(e,t)=>{t.pattern??=ws,bc.init(e,t)}),Sc=/*@__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??=Ts(e)}else t.pattern??=Ts();bc.init(e,t)}),Cc=/*@__PURE__*/ B(`$ZodEmail`,(e,t)=>{t.pattern??=Es,bc.init(e,t)});function wc(e){try{return typeof URL<`u`&&typeof URL.canParse==`function`?URL.canParse(e):(new URL(e),!0)}catch{return!1}}function Tc(e,t){return!(`normalize`in t)&&!(`hostname`in t)&&!(`protocol`in t)?wc(e)||2:Ec(e,t)}function Ec(e,t){if(!t.normalize&&t.protocol?.source===Ps.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 Dc=/[\t\n\r]/g;function Oc(e){return e.replace(Dc,``)}function kc(e,t){return t.lastIndex=0,t.test(e.hostname)}function Ac(e,t){return t.lastIndex=0,t.test(e.protocol.endsWith(`:`)?e.protocol.slice(0,-1):e.protocol)}const jc=/*@__PURE__*/ B(`$ZodURL`,(e,t)=>{bc.init(e,t),e._zod.check=n=>{try{let r=n.value.trim(),i=Tc(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=Oc(r);return}t.hostname&&!kc(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&&!Ac(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:Oc(r);return}catch{n.issues.push({code:`invalid_format`,format:`url`,input:n.value,inst:e,continue:!t.abort})}}}),Mc=/*@__PURE__*/ B(`$ZodEmoji`,(e,t)=>{t.pattern??=Ds(),bc.init(e,t)}),Nc=/*@__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?xs:Ss(t.length),bc.init(e,t)}),Pc=/*@__PURE__*/ B(`$ZodCUID`,(e,t)=>{t.pattern??=gs,bc.init(e,t)}),Fc=/*@__PURE__*/ B(`$ZodCUID2`,(e,t)=>{t.pattern??=_s,bc.init(e,t)}),Ic=/*@__PURE__*/ B(`$ZodULID`,(e,t)=>{t.pattern??=vs,bc.init(e,t)}),Lc=/*@__PURE__*/ B(`$ZodXID`,(e,t)=>{t.pattern??=ys,bc.init(e,t)}),Rc=/*@__PURE__*/ B(`$ZodKSUID`,(e,t)=>{t.pattern??=bs,bc.init(e,t)}),zc=/*@__PURE__*/ B(`$ZodISODateTime`,(e,t)=>{t.pattern??=Vs(t),bc.init(e,t)}),Bc=/*@__PURE__*/ B(`$ZodISODate`,(e,t)=>{t.pattern??=Rs,bc.init(e,t)}),Vc=/*@__PURE__*/ B(`$ZodISOTime`,(e,t)=>{t.pattern??=Bs(t),bc.init(e,t)}),Hc=/*@__PURE__*/ B(`$ZodISODuration`,(e,t)=>{t.pattern??=Cs,bc.init(e,t)}),Uc=/*@__PURE__*/ B(`$ZodIPv4`,(e,t)=>{t.pattern??=Os,bc.init(e,t)}),Wc=/^[0-9a-fA-F:.]+$/;function Gc(e){return Wc.test(e)?wc(`http://[${e}]`):!1}const Kc=/*@__PURE__*/ B(`$ZodIPv6`,(e,t)=>{t.pattern??=ks,bc.init(e,t),e._zod.check=n=>{Gc(n.value)||n.issues.push({code:`invalid_format`,format:`ipv6`,input:n.value,inst:e,continue:!t.abort})}}),qc=/*@__PURE__*/ B(`$ZodCIDRv4`,(e,t)=>{t.pattern??=As,bc.init(e,t)});function Jc(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:Gc(n)}const Yc=/*@__PURE__*/ B(`$ZodCIDRv6`,(e,t)=>{t.pattern??=js,bc.init(e,t),e._zod.check=n=>{Jc(n.value)||n.issues.push({code:`invalid_format`,format:`cidrv6`,input:n.value,inst:e,continue:!t.abort})}});function Xc(e){if(e===``)return!0;if(/\s/.test(e)||e.length%4!=0)return!1;try{return atob(e),!0}catch{return!1}}const Zc=/^[0-9a-zA-Z+/]*={0,2}$/,Qc=/*@__PURE__*/ B(`$ZodBase64`,(e,t)=>{t.pattern??=Zc,bc.init(e,t),e._zod.check=n=>{Xc(n.value)||n.issues.push({code:`invalid_format`,format:`base64`,input:n.value,inst:e,continue:!t.abort})}}),$c=/^[A-Za-z0-9_-]*$/;function el(e){if(!$c.test(e))return!1;let t=e.replace(/[-_]/g,e=>e===`-`?`+`:`/`);return Xc(t.padEnd(Math.ceil(t.length/4)*4,`=`))}const tl=/*@__PURE__*/ B(`$ZodBase64URL`,(e,t)=>{t.pattern??=$c,bc.init(e,t),e._zod.check=n=>{el(n.value)||n.issues.push({code:`invalid_format`,format:`base64url`,input:n.value,inst:e,continue:!t.abort})}}),nl=/*@__PURE__*/ B(`$ZodE164`,(e,t)=>{t.pattern??=Fs,bc.init(e,t)});function rl(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 il=/*@__PURE__*/ B(`$ZodJWT`,(e,t)=>{bc.init(e,t),e._zod.check=n=>{rl(n.value,t.alg)||n.issues.push({code:`invalid_format`,format:`jwt`,input:n.value,inst:e,continue:!t.abort})}}),al=/*@__PURE__*/ B(`$ZodNumber`,(e,t)=>{hc.init(e,t),e._zod.pattern=Ws,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}}),ol=/*@__PURE__*/ B(`$ZodNumberFormat`,(e,t)=>{tc.init(e,t),al.init(e,t)}),sl=/*@__PURE__*/ B(`$ZodBoolean`,(e,t)=>{hc.init(e,t),e._zod.pattern=Gs,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}}),cl=/*@__PURE__*/ B(`$ZodNull`,(e,t)=>{hc.init(e,t),e._zod.pattern=Ks,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}}),ll=/*@__PURE__*/ B(`$ZodUnknown`,(e,t)=>{hc.init(e,t),e._zod.parse=e=>e}),ul=/*@__PURE__*/ B(`$ZodNever`,(e,t)=>{hc.init(e,t),e._zod.parse=(t,n)=>(t.issues.push({expected:`never`,code:`invalid_type`,input:t.value,inst:e}),t)});function dl(e,t){let n=co(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 co(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,lo(n.issues,t,e),n}}return i(n,a)}}const fl=e=>Array.isArray(e)?e.length:-1;function pl(e,t,n){e.issues.length&&t.issues.push(...oo(n,e.issues)),t.value[n]=e.value}const ml=/*@__PURE__*/ B(`$ZodArray`,(e,t)=>{hc.init(e,t);let n=Po.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=>pl(t,r,e)));else if(pl(c,r,e),s&&c.issues.length!==0&&io(c))break}return o.length?Promise.all(o).then(()=>r):r},dl(e,fl)});function hl(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(...oo(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 gl=[];function _l(e){let t=Object.keys(e.shape),n=Object.getOwnPropertySymbols(e.shape),r=n.length?n:gl,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=Ka(e.shape);return{...e,allKeys:i,symbolKeys:r,keySet:new Set(t),numKeys:t.length,optionalKeys:new Set(a)}}function vl(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(io(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=>hl(e,n,i,t,d,f))):hl(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 yl=/*@__PURE__*/ B(`$ZodObject`,(e,t)=>{hc.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=Ca(()=>_l(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)||Da(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=Ra,o=t.catchall,s,c=Po.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(io(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=>hl(n,t,e,r,a,o))):hl(s,t,e,r,a,o)}return o?vl(l,r,t,n,i.value,e,d===!0):l.length?Promise.all(l).then(()=>t):t}}),bl=/*@__PURE__*/ B(`$ZodObjectJIT`,(e,t)=>{yl.init(e,t);let n=e._zod.parse,r=Ca(()=>_l(t)),i=Po.memoizer,a=t=>{let n=r.value,a=n.symbolKeys,o=new pc([`payload`,`ctx`],{shape:t,inst:e,memo:i,syms:a}),s=e=>`shape[${e}]._zod.run({ value: input[${e}], issues: [] }, ctx)`,c=(e,t)=>`
|
|
20
20
|
let ${e}_ab = false;
|
|
21
21
|
for (let i = 0; i < ${e}.issues.length; i++) {
|
|
22
22
|
const iss = ${e}.issues[i];
|
|
@@ -27,7 +27,7 @@ function z(e,t,n,r){let i={};function a(e){this.def=e,this.constr=d,this.traits=
|
|
|
27
27
|
if (${e}_ab && ctx && ctx.abortEarly) {
|
|
28
28
|
payload.value = newResult;
|
|
29
29
|
return payload;
|
|
30
|
-
}`;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)}]`:
|
|
30
|
+
}`;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)}]`:Fa(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(`
|
|
31
31
|
const ${n}_present = ${i};
|
|
32
32
|
if (!${n}.issues.length || ${n}_present) {
|
|
33
33
|
if (${n}.issues.length) {${c(n,r)}
|
|
@@ -66,97 +66,97 @@ function z(e,t,n,r){let i={};function a(e){this.def=e,this.constr=d,this.traits=
|
|
|
66
66
|
newResult[${r}] = ${n}.value;
|
|
67
67
|
}
|
|
68
68
|
|
|
69
|
-
`)}return o.write(`payload.value = newResult;`),o.write(`return payload;`),o.compile()},o,s=za,c=!Fo.jitless,l=c&&Ba.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?yl([],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 Sl(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=>!ao(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=>fo(e,r,Io())))}),t)}const Cl=/*@__PURE__*/ z(`$ZodUnion`,(e,t)=>{gc.init(e,t),R(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),R(e,`optout`,e=>e.def.options.some(e=>e._zod.optout===`optional`)?`optional`:void 0),R(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)))}),R(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=>Ea(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=>Sl(t,r,e,i)):Sl(o,r,e,i)}});function wl(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 Tl=/*@__PURE__*/ z(`$ZodDiscriminatedUnion`,(e,t)=>{t.inclusive=!1,Cl.init(e,t);let n=e._zod.parse;R(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)||Oa(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=ka(e._zod.def);if(r&&!Object.prototype.hasOwnProperty.call(r,t.discriminator))throw Error(`Invalid discriminated union option at index "${n}"`)});let r=wa(()=>wl(t));e._zod.parse=(i,a)=>{let o=i.value;if(!za(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)}}),El=/*@__PURE__*/ z(`$ZodIntersection`,(e,t)=>{gc.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])=>Ol(e,t,n)):Ol(e,i,a)}});function Dl(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Va(e)&&Va(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=Dl(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=Dl(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 Ol(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=Dl(t.value,n.value);if(!c.valid){if(ao(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}const kl=/*@__PURE__*/ z(`$ZodRecord`,(e,t)=>{gc.init(e,t);let n=Fo.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!Va(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=>fo(e,i,Io())),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(...so(n,e.issues)),r.value[l]=e.value})):(u.issues.length&&r.issues.push(...so(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`&&Gs.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=>fo(e,i,Io())),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(...so(n,e.issues)),r.value[u]=e.value})):(d.issues.length&&r.issues.push(...so(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}}),Al=/*@__PURE__*/ z(`$ZodEnum`,(e,t)=>{gc.init(e,t);let n=ba(t.entries),r=new Set(n);e._zod.values=r,R(e,`pattern`,e=>{let t=ba(e.def.entries).filter(e=>Ua.has(typeof e));return RegExp(t.length?`^(${t.map(e=>Wa(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}}),jl=/*@__PURE__*/ z(`$ZodLiteral`,(e,t)=>{gc.init(e,t);let n=new Set(t.values);e._zod.values=n,R(e,`pattern`,e=>{let t=e.def.values;return RegExp(t.length?`^(${t.map(e=>typeof e==`string`?Wa(e):e?Wa(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}}),Ml=/*@__PURE__*/ z(`$ZodTransform`,(e,t)=>{gc.init(e,t),e._zod.optin=`optional`,Fo.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Po(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 No;return n.value=i,n}});function Nl(e,t){return e.value=t.issues.length?void 0:t.value,e}const Pl=/*@__PURE__*/ z(`$ZodOptional`,(e,t)=>{gc.init(e,t),R(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),e._zod.optout=`optional`,R(e,`values`,e=>{let t=e.def.innerType._zod.values;return t?/* @__PURE__ */ new Set([...t,void 0]):void 0}),R(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${Ea(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=>Nl(e,t)):Nl(e,r)}return t.innerType._zod.run(e,n)}}),Fl=/*@__PURE__*/ z(`$ZodExactOptional`,(e,t)=>{Pl.init(e,t),R(e,`values`,e=>e.def.innerType._zod.values),R(e,`pattern`,e=>e.def.innerType._zod.pattern),e._zod.parse=(e,n)=>t.innerType._zod.run(e,n)}),Il=/*@__PURE__*/ z(`$ZodNullable`,(e,t)=>{gc.init(e,t),R(e,`optin`,e=>e.def.innerType._zod.optin),R(e,`optout`,e=>e.def.innerType._zod.optout),R(e,`pattern`,e=>{let t=e.def.innerType._zod.pattern;return t?RegExp(`^(${Ea(t.source)}|null)$`):void 0}),R(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)}),Ll=/*@__PURE__*/ z(`$ZodDefault`,(e,t)=>{gc.init(e,t),e._zod.optin=`defaulted`,R(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=>Rl(e,t)):Rl(r,t)}});function Rl(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const zl=/*@__PURE__*/ z(`$ZodPrefault`,(e,t)=>{gc.init(e,t),e._zod.optin=`defaulted`,R(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))}),Bl=/*@__PURE__*/ z(`$ZodNonOptional`,(e,t)=>{gc.init(e,t),R(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=>Vl(t,e)):Vl(i,e)}});function Vl(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 Hl(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(e=>fo(e,r,Io()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}const Ul=/*@__PURE__*/ z(`$ZodCatch`,(e,t)=>{gc.init(e,t),R(e,`optin`,e=>e.def.innerType._zod.optin===`defaulted`?`defaulted`:`optional`),R(e,`optout`,e=>e.def.innerType._zod.optout),R(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=>Hl(e,r,t,n)):Hl(e,r,t,n)}}),Wl=/*@__PURE__*/ z(`$ZodPipe`,(e,t)=>{gc.init(e,t),R(e,`values`,e=>e.def.in._zod.values),R(e,`optin`,e=>e.def.in._zod.optin),R(e,`optout`,e=>e.def.out._zod.optout),R(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=>Gl(e,t.in,n)):Gl(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Gl(e,t.out,n)):Gl(r,t.out,n)}});function Gl(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 Kl=/*@__PURE__*/ z(`$ZodPreprocess`,(e,t)=>{Wl.init(e,t)}),ql=/*@__PURE__*/ z(`$ZodReadonly`,(e,t)=>{gc.init(e,t),R(e,`propValues`,e=>e.def.innerType._zod.propValues),R(e,`values`,e=>e.def.innerType._zod.values),R(e,`optin`,e=>e.def.innerType?._zod?.optin),R(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(Jl):Jl(r)}});function Jl(e){return e.memo||(e.value=Object.freeze(e.value)),e}const Yl=/*@__PURE__*/ z(`$ZodCustom`,(e,t)=>{Xs.init(e,t),gc.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=>Xl(t,n,r,e));Xl(i,n,r,e)}});function Xl(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(_o(e))}}var Zl=class extends Error{constructor(){super(`Cannot parse a reference cycle that closes through a transform`),this.name=`ZodCyclicError`}};const Ql=`~memo`,$l=[];function eu(e){return typeof e==`object`&&!!e}function tu(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}const nu=/*@__PURE__*/ new WeakMap;function ru(e,t,n){let r=nu.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=ru(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?ru(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=ka(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?ru(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),iu(e,i)}function iu(e,t){return t!==1&&nu.set(e,t===2),t}function au(e,t){let n=e.buckets.get(t);return n||(n=/* @__PURE__ */ new WeakMap,e.buckets.set(t,n)),n}let ou;const su=[],cu={alloc(e,t,n){let r=ou;if(!r)return n;ou=void 0;let i={value:n,issues:null};return r.set(t.value,i),su.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`&&uu(n,e.value))throw new Zl;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=ru(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(!eu(l))return t(s,c);let u=c[Ql];u||(u={buckets:/* @__PURE__ */ new WeakMap,backEdges:void 0},c[Ql]=u);let d;i===c?d=a:(d=au(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(...tu(f.issues)):(s.memo=!0,u.backEdges??(u.backEdges=/* @__PURE__ */ new WeakSet),u.backEdges.add(f.value)),s;ou=d;let p=su.length,m=t(s,c);ou=void 0;let h=su.length>p?su.pop():void 0;return m instanceof Promise?m.then(e=>(h&&(h.issues=e.issues.length?tu(e.issues):$l),e)):(h&&(h.issues=m.issues.length?tu(m.issues):$l),m)};e._zod.parse=o,e._zod.run===t&&(e._zod.run=o)})}};function lu(){return cu}function uu(e,t){let n=e[Ql]?.backEdges;return n!==void 0&&eu(t)&&n.has(t)}const du=()=>{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(go(e.input),e.input)}`;case`invalid_value`:return e.values.length===1?`Invalid input: expected ${Ka(e.values[0])}`:`Invalid option: expected one of ${xa(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`:``}: ${xa(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 fu(){return{localeError:du()}}var pu,mu=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 hu(){return new mu}(pu=globalThis).__zod_globalRegistry??(pu.__zod_globalRegistry=hu());const gu=globalThis.__zod_globalRegistry;function _u(e){return e.checks&&=[...e.checks],e}// @__NO_SIDE_EFFECTS__
|
|
70
|
-
function
|
|
71
|
-
function
|
|
72
|
-
function
|
|
73
|
-
function
|
|
74
|
-
function
|
|
75
|
-
function
|
|
76
|
-
function
|
|
77
|
-
function
|
|
78
|
-
function
|
|
79
|
-
function
|
|
80
|
-
function
|
|
81
|
-
function
|
|
82
|
-
function
|
|
83
|
-
function
|
|
84
|
-
function
|
|
85
|
-
function
|
|
86
|
-
function
|
|
87
|
-
function
|
|
88
|
-
function
|
|
89
|
-
function
|
|
90
|
-
function
|
|
91
|
-
function
|
|
92
|
-
function
|
|
93
|
-
function
|
|
94
|
-
function
|
|
95
|
-
function
|
|
96
|
-
function
|
|
97
|
-
function
|
|
98
|
-
function
|
|
99
|
-
function
|
|
100
|
-
function
|
|
101
|
-
function
|
|
102
|
-
function
|
|
103
|
-
function
|
|
104
|
-
function
|
|
105
|
-
function
|
|
106
|
-
function
|
|
107
|
-
function
|
|
108
|
-
function
|
|
109
|
-
function
|
|
110
|
-
function
|
|
111
|
-
function
|
|
112
|
-
function
|
|
113
|
-
function
|
|
114
|
-
function
|
|
115
|
-
function
|
|
116
|
-
function
|
|
117
|
-
function
|
|
118
|
-
function
|
|
119
|
-
function
|
|
120
|
-
function
|
|
121
|
-
function
|
|
122
|
-
function
|
|
123
|
-
function
|
|
124
|
-
function
|
|
125
|
-
function
|
|
126
|
-
function
|
|
127
|
-
function
|
|
69
|
+
`)}return o.write(`payload.value = newResult;`),o.write(`return payload;`),o.compile()},o,s=Ra,c=!Po.jitless,l=c&&za.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?vl([],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 xl(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=>!io(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=>uo(e,r,Fo())))}),t)}const Sl=/*@__PURE__*/ B(`$ZodUnion`,(e,t)=>{hc.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=>Ta(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=>xl(t,r,e,i)):xl(o,r,e,i)}});function Cl(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 wl=/*@__PURE__*/ B(`$ZodDiscriminatedUnion`,(e,t)=>{t.inclusive=!1,Sl.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)||Da(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=Oa(e._zod.def);if(r&&!Object.prototype.hasOwnProperty.call(r,t.discriminator))throw Error(`Invalid discriminated union option at index "${n}"`)});let r=Ca(()=>Cl(t));e._zod.parse=(i,a)=>{let o=i.value;if(!Ra(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)}}),Tl=/*@__PURE__*/ B(`$ZodIntersection`,(e,t)=>{hc.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])=>Dl(e,t,n)):Dl(e,i,a)}});function El(e,t){if(e===t||e instanceof Date&&t instanceof Date&&+e==+t)return{valid:!0,data:e};if(Ba(e)&&Ba(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=El(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=El(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 Dl(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=El(t.value,n.value);if(!c.valid){if(io(e))return e;throw Error(`Unmergable intersection. Error path: ${JSON.stringify(c.mergeErrorPath)}`)}return e.value=c.data,e}const Ol=/*@__PURE__*/ B(`$ZodRecord`,(e,t)=>{hc.init(e,t);let n=Po.memoizer;n?.attach(e),e._zod.parse=(r,i)=>{let a=r.value;if(!Ba(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=>uo(e,i,Fo())),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(...oo(n,e.issues)),r.value[l]=e.value})):(u.issues.length&&r.issues.push(...oo(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`&&Ws.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=>uo(e,i,Fo())),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(...oo(n,e.issues)),r.value[u]=e.value})):(d.issues.length&&r.issues.push(...oo(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}}),kl=/*@__PURE__*/ B(`$ZodEnum`,(e,t)=>{hc.init(e,t);let n=ya(t.entries),r=new Set(n);e._zod.values=r,z(e,`pattern`,e=>{let t=ya(e.def.entries).filter(e=>Ha.has(typeof e));return RegExp(t.length?`^(${t.map(e=>Ua(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}}),Al=/*@__PURE__*/ B(`$ZodLiteral`,(e,t)=>{hc.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`?Ua(e):e?Ua(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}}),jl=/*@__PURE__*/ B(`$ZodTransform`,(e,t)=>{hc.init(e,t),e._zod.optin=`optional`,Po.memoizer?.guard(e),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new No(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 Mo;return n.value=i,n}});function Ml(e,t){return e.value=t.issues.length?void 0:t.value,e}const Nl=/*@__PURE__*/ B(`$ZodOptional`,(e,t)=>{hc.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(`^(${Ta(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=>Ml(e,t)):Ml(e,r)}return t.innerType._zod.run(e,n)}}),Pl=/*@__PURE__*/ B(`$ZodExactOptional`,(e,t)=>{Nl.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)}),Fl=/*@__PURE__*/ B(`$ZodNullable`,(e,t)=>{hc.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(`^(${Ta(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)}),Il=/*@__PURE__*/ B(`$ZodDefault`,(e,t)=>{hc.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=>Ll(e,t)):Ll(r,t)}});function Ll(e,t){return e.value===void 0&&(e.value=t.defaultValue),e}const Rl=/*@__PURE__*/ B(`$ZodPrefault`,(e,t)=>{hc.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))}),zl=/*@__PURE__*/ B(`$ZodNonOptional`,(e,t)=>{hc.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=>Bl(t,e)):Bl(i,e)}});function Bl(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 Vl(e,t,n,r){return t.issues.length?(e.value=n.catchValue({...t,value:e.value,error:{issues:t.issues.map(e=>uo(e,r,Fo()))},input:e.value}),e):(e.value=t.value,t.memo&&(e.memo=!0),e)}const Hl=/*@__PURE__*/ B(`$ZodCatch`,(e,t)=>{hc.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=>Vl(e,r,t,n)):Vl(e,r,t,n)}}),Ul=/*@__PURE__*/ B(`$ZodPipe`,(e,t)=>{hc.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=>Wl(e,t.in,n)):Wl(r,t.in,n)}let r=t.in._zod.run(e,n);return r instanceof Promise?r.then(e=>Wl(e,t.out,n)):Wl(r,t.out,n)}});function Wl(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 Gl=/*@__PURE__*/ B(`$ZodPreprocess`,(e,t)=>{Ul.init(e,t)}),Kl=/*@__PURE__*/ B(`$ZodReadonly`,(e,t)=>{hc.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(ql):ql(r)}});function ql(e){return e.memo||(e.value=Object.freeze(e.value)),e}const Jl=/*@__PURE__*/ B(`$ZodCustom`,(e,t)=>{Ys.init(e,t),hc.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=>Yl(t,n,r,e));Yl(i,n,r,e)}});function Yl(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(go(e))}}var Xl=class extends Error{constructor(){super(`Cannot parse a reference cycle that closes through a transform`),this.name=`ZodCyclicError`}};const Zl=`~memo`,Ql=[];function $l(e){return typeof e==`object`&&!!e}function eu(e){return e.map(e=>e.path?{...e,path:e.path.slice()}:{...e})}const tu=/*@__PURE__*/ new WeakMap;function nu(e,t,n){let r=tu.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=nu(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?nu(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=Oa(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?nu(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),ru(e,i)}function ru(e,t){return t!==1&&tu.set(e,t===2),t}function iu(e,t){let n=e.buckets.get(t);return n||(n=/* @__PURE__ */ new WeakMap,e.buckets.set(t,n)),n}let au;const ou=[],su={alloc(e,t,n){let r=au;if(!r)return n;au=void 0;let i={value:n,issues:null};return r.set(t.value,i),ou.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`&&lu(n,e.value))throw new Xl;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=nu(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(!$l(l))return t(s,c);let u=c[Zl];u||(u={buckets:/* @__PURE__ */ new WeakMap,backEdges:void 0},c[Zl]=u);let d;i===c?d=a:(d=iu(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(...eu(f.issues)):(s.memo=!0,u.backEdges??(u.backEdges=/* @__PURE__ */ new WeakSet),u.backEdges.add(f.value)),s;au=d;let p=ou.length,m=t(s,c);au=void 0;let h=ou.length>p?ou.pop():void 0;return m instanceof Promise?m.then(e=>(h&&(h.issues=e.issues.length?eu(e.issues):Ql),e)):(h&&(h.issues=m.issues.length?eu(m.issues):Ql),m)};e._zod.parse=o,e._zod.run===t&&(e._zod.run=o)})}};function cu(){return su}function lu(e,t){let n=e[Zl]?.backEdges;return n!==void 0&&$l(t)&&n.has(t)}const uu=()=>{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(ho(e.input),e.input)}`;case`invalid_value`:return e.values.length===1?`Invalid input: expected ${Ga(e.values[0])}`:`Invalid option: expected one of ${ba(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`:``}: ${ba(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 du(){return{localeError:uu()}}var fu,pu=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 mu(){return new pu}(fu=globalThis).__zod_globalRegistry??(fu.__zod_globalRegistry=mu());const hu=globalThis.__zod_globalRegistry;function gu(e){return e.checks&&=[...e.checks],e}// @__NO_SIDE_EFFECTS__
|
|
70
|
+
function _u(e,t){return new e(gu({type:`string`,...R(t)}))}// @__NO_SIDE_EFFECTS__
|
|
71
|
+
function vu(e,t){return new e({type:`string`,format:`email`,check:`string_format`,abort:!1,...R(t)})}// @__NO_SIDE_EFFECTS__
|
|
72
|
+
function yu(e,t){return new e({type:`string`,format:`guid`,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,...R(t)})}// @__NO_SIDE_EFFECTS__
|
|
74
|
+
function xu(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v4`,...R(t)})}// @__NO_SIDE_EFFECTS__
|
|
75
|
+
function Su(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v6`,...R(t)})}// @__NO_SIDE_EFFECTS__
|
|
76
|
+
function Cu(e,t){return new e({type:`string`,format:`uuid`,check:`string_format`,abort:!1,version:`v7`,...R(t)})}// @__NO_SIDE_EFFECTS__
|
|
77
|
+
function wu(e,t){return new e({type:`string`,format:`url`,check:`string_format`,abort:!1,...R(t)})}// @__NO_SIDE_EFFECTS__
|
|
78
|
+
function Tu(e,t){return new e({type:`string`,format:`emoji`,check:`string_format`,abort:!1,...R(t)})}// @__NO_SIDE_EFFECTS__
|
|
79
|
+
function Eu(e,t){return new e({type:`string`,format:`nanoid`,check:`string_format`,abort:!1,...R(t)})}// @__NO_SIDE_EFFECTS__
|
|
80
|
+
function Du(e,t){return new e({type:`string`,format:`cuid`,check:`string_format`,abort:!1,...R(t)})}// @__NO_SIDE_EFFECTS__
|
|
81
|
+
function Ou(e,t){return new e({type:`string`,format:`cuid2`,check:`string_format`,abort:!1,...R(t)})}// @__NO_SIDE_EFFECTS__
|
|
82
|
+
function ku(e,t){return new e({type:`string`,format:`ulid`,check:`string_format`,abort:!1,...R(t)})}// @__NO_SIDE_EFFECTS__
|
|
83
|
+
function Au(e,t){return new e({type:`string`,format:`xid`,check:`string_format`,abort:!1,...R(t)})}// @__NO_SIDE_EFFECTS__
|
|
84
|
+
function ju(e,t){return new e({type:`string`,format:`ksuid`,check:`string_format`,abort:!1,...R(t)})}// @__NO_SIDE_EFFECTS__
|
|
85
|
+
function Mu(e,t){return new e({type:`string`,format:`ipv4`,check:`string_format`,abort:!1,...R(t)})}// @__NO_SIDE_EFFECTS__
|
|
86
|
+
function Nu(e,t){return new e({type:`string`,format:`ipv6`,check:`string_format`,abort:!1,...R(t)})}// @__NO_SIDE_EFFECTS__
|
|
87
|
+
function Pu(e,t){return new e({type:`string`,format:`cidrv4`,check:`string_format`,abort:!1,...R(t)})}// @__NO_SIDE_EFFECTS__
|
|
88
|
+
function Fu(e,t){return new e({type:`string`,format:`cidrv6`,check:`string_format`,abort:!1,...R(t)})}// @__NO_SIDE_EFFECTS__
|
|
89
|
+
function Iu(e,t){return new e({type:`string`,format:`base64`,check:`string_format`,abort:!1,...R(t)})}// @__NO_SIDE_EFFECTS__
|
|
90
|
+
function Lu(e,t){return new e({type:`string`,format:`base64url`,check:`string_format`,abort:!1,...R(t)})}// @__NO_SIDE_EFFECTS__
|
|
91
|
+
function Ru(e,t){return new e({type:`string`,format:`e164`,check:`string_format`,abort:!1,...R(t)})}// @__NO_SIDE_EFFECTS__
|
|
92
|
+
function zu(e,t){return new e({type:`string`,format:`jwt`,check:`string_format`,abort:!1,...R(t)})}// @__NO_SIDE_EFFECTS__
|
|
93
|
+
function Bu(e,t){return new e({type:`string`,format:`datetime`,check:`string_format`,offset:!1,local:!1,precision:null,...R(t)})}// @__NO_SIDE_EFFECTS__
|
|
94
|
+
function Vu(e,t){return new e({type:`string`,format:`date`,check:`string_format`,...R(t)})}// @__NO_SIDE_EFFECTS__
|
|
95
|
+
function Hu(e,t){return new e({type:`string`,format:`time`,check:`string_format`,precision:null,...R(t)})}// @__NO_SIDE_EFFECTS__
|
|
96
|
+
function Uu(e,t){return new e({type:`string`,format:`duration`,check:`string_format`,...R(t)})}// @__NO_SIDE_EFFECTS__
|
|
97
|
+
function Wu(e,t){return new e(gu({type:`number`,checks:[],...R(t)}))}// @__NO_SIDE_EFFECTS__
|
|
98
|
+
function Gu(e,t){return new e({type:`number`,check:`number_format`,abort:!1,format:`safeint`,...R(t)})}// @__NO_SIDE_EFFECTS__
|
|
99
|
+
function Ku(e,t){return new e({type:`boolean`,...R(t)})}// @__NO_SIDE_EFFECTS__
|
|
100
|
+
function qu(e,t){return new e({type:`null`,...R(t)})}// @__NO_SIDE_EFFECTS__
|
|
101
|
+
function Ju(e){return new e({type:`unknown`})}// @__NO_SIDE_EFFECTS__
|
|
102
|
+
function Yu(e,t){return new e({type:`never`,...R(t)})}// @__NO_SIDE_EFFECTS__
|
|
103
|
+
function Xu(e,t){return new Qs({check:`less_than`,...R(t),value:e,inclusive:!1})}// @__NO_SIDE_EFFECTS__
|
|
104
|
+
function Zu(e,t){return new Qs({check:`less_than`,...R(t),value:e,inclusive:!0})}// @__NO_SIDE_EFFECTS__
|
|
105
|
+
function Qu(e,t){return new $s({check:`greater_than`,...R(t),value:e,inclusive:!1})}// @__NO_SIDE_EFFECTS__
|
|
106
|
+
function $u(e,t){return new $s({check:`greater_than`,...R(t),value:e,inclusive:!0})}// @__NO_SIDE_EFFECTS__
|
|
107
|
+
function ed(e,t){return new ec({check:`multiple_of`,...R(t),value:e})}// @__NO_SIDE_EFFECTS__
|
|
108
|
+
function td(e,t){return new nc({check:`max_length`,...R(t),maximum:e})}// @__NO_SIDE_EFFECTS__
|
|
109
|
+
function nd(e,t){return new rc({check:`min_length`,...R(t),minimum:e})}// @__NO_SIDE_EFFECTS__
|
|
110
|
+
function rd(e,t){return new ic({check:`length_equals`,...R(t),length:e})}// @__NO_SIDE_EFFECTS__
|
|
111
|
+
function id(e,t){return new oc({check:`string_format`,format:`regex`,...R(t),pattern:e})}// @__NO_SIDE_EFFECTS__
|
|
112
|
+
function ad(e){return new sc({check:`string_format`,format:`lowercase`,...R(e)})}// @__NO_SIDE_EFFECTS__
|
|
113
|
+
function od(e){return new cc({check:`string_format`,format:`uppercase`,...R(e)})}// @__NO_SIDE_EFFECTS__
|
|
114
|
+
function sd(e,t){return new lc({check:`string_format`,format:`includes`,...R(t),includes:e})}// @__NO_SIDE_EFFECTS__
|
|
115
|
+
function cd(e,t){return new uc({check:`string_format`,format:`starts_with`,...R(t),prefix:e})}// @__NO_SIDE_EFFECTS__
|
|
116
|
+
function ld(e,t){return new dc({check:`string_format`,format:`ends_with`,...R(t),suffix:e})}// @__NO_SIDE_EFFECTS__
|
|
117
|
+
function ud(e){return new fc({check:`overwrite`,tx:e})}// @__NO_SIDE_EFFECTS__
|
|
118
|
+
function dd(e){return/* @__PURE__ */ ud(t=>t.normalize(e))}// @__NO_SIDE_EFFECTS__
|
|
119
|
+
function fd(){return/* @__PURE__ */ ud(e=>e.trim())}// @__NO_SIDE_EFFECTS__
|
|
120
|
+
function pd(){return/* @__PURE__ */ ud(e=>e.toLowerCase())}// @__NO_SIDE_EFFECTS__
|
|
121
|
+
function md(){return/* @__PURE__ */ ud(e=>e.toUpperCase())}// @__NO_SIDE_EFFECTS__
|
|
122
|
+
function hd(){return/* @__PURE__ */ ud(e=>Ia(e))}// @__NO_SIDE_EFFECTS__
|
|
123
|
+
function gd(e,t,n){return new e({type:`array`,element:t,...R(n)})}// @__NO_SIDE_EFFECTS__
|
|
124
|
+
function _d(e,t,n){let r=R(n);return r.abort??=!0,new e({type:`custom`,check:`custom`,fn:t,...r})}// @__NO_SIDE_EFFECTS__
|
|
125
|
+
function vd(e,t,n){return new e({type:`custom`,check:`custom`,fn:t,...R(n)})}// @__NO_SIDE_EFFECTS__
|
|
126
|
+
function yd(e,t){let n=/* @__PURE__ */ bd(t=>(t.addIssue=e=>{if(typeof e==`string`)t.issues.push(go(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(go(r))}},e(t.value,t)),t);return n}// @__NO_SIDE_EFFECTS__
|
|
127
|
+
function bd(e,t){let n=new Ys({check:`custom`,...R(t)});return n._zod.check=e,n}function xd(e,...t){for(let n of t)for(let t of Reflect.ownKeys(n))Object.prototype.propertyIsEnumerable.call(n,t)&&Da(e,t,n[t]);return e}function Sd(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??hu,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 Cd(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 wd(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,wd(a,t,r),t.seen.get(a).isParent=!0)}let c=t.metadataRegistry.get(e);return c&&xd(o.schema,c),t.io===`input`&&Pd(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 Td(e){return e.replace(/~/g,`~0`).replace(/\//g,`~1`)}function Ed(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}/${Td(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+Td(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>
|
|
128
128
|
|
|
129
|
-
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 Od(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;Od(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 kd=/* @__PURE__ */ new Set([`type`,`properties`,`required`,`additionalProperties`]),Ad=[`oneOf`,`anyOf`];function jd(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function Md(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!kd.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]??jd(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}Oa(n,r,e.length===1?e[0]:Md(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=jd(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 Nd(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of kd)if(t in e)return;let n=t.filter(e=>Ad.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=Md(t);else{let e=n[0],i=Ad.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=>Md([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,Sd(e,r))}function Pd(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)):Sd(i,s),Sd(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())Od(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)??[])Nd(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)}Sd(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,Oa(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:Ld(t,`input`,e.processors),output:Ld(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function Fd(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 Fd(r.element,n);if(r.type===`set`)return Fd(r.valueType,n);if(r.type===`lazy`)return Fd(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 Fd(r.innerType,n);if(r.type===`intersection`)return Fd(r.left,n)||Fd(r.right,n);if(r.type===`record`||r.type===`map`)return Fd(r.keyType,n)||Fd(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:Fd(r.in,n)||Fd(r.out,n);if(r.type===`object`){for(let e in r.shape)if(Fd(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(Fd(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(Fd(e,n))return!0;return!!(r.rest&&Fd(r.rest,n))}return!1}const Id=(e,t={})=>n=>{let r=Cd({...n,processors:t});return Td(e,r),Dd(r,e),Pd(r,e)},Ld=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=Cd({...i??{},target:a,io:t,processors:n});return Td(e,o),Dd(o,e),Pd(o,e)},Rd=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},zd=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},Bd=(e,t)=>{Rd(e,`minimum`,t),zd(e,`maximum`,t)},Vd=(e,t)=>{e.multipleOf??=[],e.multipleOf.includes(t)||e.multipleOf.push(t)},Hd=(e,t)=>{e.patterns??=/* @__PURE__ */ new Set,e.patterns.add(t)},Ud=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},Wd=(e,t)=>{e.format=t,t.includes(`int`)&&(e.isInt=!0)},Gd=(e,t)=>Rd(e,`minimum`,t.minimum),Kd=(e,t)=>zd(e,`maximum`,t.maximum),qd=e=>(t,n)=>{Wd(t,n.format);let[r,i]=e[n.format];Rd(t,`minimum`,r),zd(t,`maximum`,i)},Jd={greater_than:(e,t)=>Rd(e,t.inclusive?`minimum`:`exclusiveMinimum`,t.value),less_than:(e,t)=>zd(e,t.inclusive?`maximum`:`exclusiveMaximum`,t.value),multiple_of:(e,t)=>Vd(e,t.value),number_format:qd(Ja),bigint_format:qd(Ya),min_length:Gd,max_length:Kd,length_equals:(e,t)=>Bd(e,t.length),min_size:Gd,max_size:Kd,size_equals:(e,t)=>Bd(e,t.size),string_format:(e,t)=>{Wd(e,t.format),t.pattern&&Hd(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)=>Ud(e,t.mime)};function Yd(e){let t={},n=e._zod.def,r=e._zod.traits.has(`$ZodCheck`)?[e,...n.checks??[]]:n.checks??[];for(let e of r)Jd[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;i.minimum!==void 0&&Rd(t,`minimum`,i.minimum),i.exclusiveMinimum!==void 0&&Rd(t,`exclusiveMinimum`,i.exclusiveMinimum),i.maximum!==void 0&&zd(t,`maximum`,i.maximum),i.exclusiveMaximum!==void 0&&zd(t,`exclusiveMaximum`,i.exclusiveMaximum),i.multipleOf!==void 0&&Vd(t,i.multipleOf),i.format!==void 0&&(t.format??=i.format,i.format.includes(`int`)&&(t.isInt=!0)),i.mime&&Ud(t,i.mime);for(let e of i.patterns??[])Hd(t,e);return t}const Xd={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Zd=/* @__PURE__ */ new Map([[Qc,Ns],[el,Ps]]),Qd=e=>Zd.get(e)??e,$d=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=Yd(e);if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Xd[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(Qd);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}))])}},ef=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=Yd(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)):wd(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}))])}},tf=(e,t,n,r)=>{n.type=`boolean`},nf=(e,t,n,r)=>{wd(e,t,n,r,`BigInt cannot be represented in JSON Schema`)},rf=(e,t,n,r)=>{wd(e,t,n,r,`Symbols cannot be represented in JSON Schema`)},af=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},of=(e,t,n,r)=>{wd(e,t,n,r,`Undefined cannot be represented in JSON Schema`)},sf=(e,t,n,r)=>{wd(e,t,n,r,`Void cannot be represented in JSON Schema`)},cf=(e,t,n,r)=>{n.not={}},lf=(e,t,n,r)=>{},uf=(e,t,n,r)=>{},df=(e,t,n,r)=>{wd(e,t,n,r,`Date cannot be represented in JSON Schema`)},ff=(e,t,n,r)=>{let i=e._zod.def,a=ba(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)},pf=(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(wd(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof o==`bigint`){if(wd(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}},mf=(e,t,n,r)=>{wd(e,t,n,r,`NaN cannot be represented in JSON Schema`)},hf=(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},gf=(e,t,n,r)=>{let i=n;i.type=`string`,i.format=`binary`,i.contentEncoding=`binary`;let{minimum:a,maximum:o,mime:s}=Yd(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})))},_f=(e,t,n,r)=>{n.type=`boolean`},vf=(e,t,n,r)=>{wd(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},yf=(e,t,n,r)=>{wd(e,t,n,r,`Function types cannot be represented in JSON Schema`)},bf=(e,t,n,r)=>{wd(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},xf=(e,t,n,r)=>{wd(e,t,n,r,`Map cannot be represented in JSON Schema`)},Sf=(e,t,n,r)=>{wd(e,t,n,r,`Set cannot be represented in JSON Schema`)},Cf=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=Yd(e);typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=Td(a.element,t,{...r,path:[...r.path,`items`]})};function wf(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?wf(t.out):t.type===`catch`?wf(t.innerType):e._zod.optin}const Tf=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&wd(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in o)Oa(i.properties,e,Td(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`?wf(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=Td(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Ef=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>Td(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Df=(e,t,n,r)=>{let i=e._zod.def,a=Td(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=Td(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)},Of=(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)=>Td(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?Td(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`?wf(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}=Yd(e);typeof p==`number`&&(i.minItems=p),typeof m==`number`&&(i.maxItems=m)};function kf(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=kf(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=>kf(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`)?Gs:Ws).source)),p}const Af=/* @__PURE__ */ new WeakMap;function jf(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 Af.get(e)??[]){let i=e.seen.get(r),a=(i?.def??i?.schema)?.propertyNames;if(!a||a===!0||n.has(a))continue;let o=kf(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 Mf=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=Yd(o).patterns;if(a.mode===`loose`&&s&&s.size>0){let e=Td(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)Oa(i.patternProperties,Qd(t).source,e)}else{if(t.target===`draft-07`||t.target===`draft-2020-12`){i.propertyNames=Td(a.keyType,t,{...r,path:[...r.path,`propertyNames`]});let n=Af.get(t);n||(n=[],Af.set(t,n),t.deferred.push(()=>jf(t))),n.push(e)}i.additionalProperties=Td(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]})}let c=o._zod.values,l=t.io===`input`&&wf(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))}},Nf=(e,t,n,r)=>{let i=e._zod.def,a=Td(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`}]},Pf=(e,t,n,r)=>{let i=e._zod.def;Td(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Ff=Symbol();function If(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(wd(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),Ff):JSON.parse(o)}const Lf=(e,t,n,r)=>{let i=e._zod.def;Td(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=If(i.defaultValue,e,t,n,r);o!==Ff&&(n.default=o)},Rf=(e,t,n,r)=>{let i=e._zod.def;Td(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=If(i.defaultValue,e,t,n,r);o!==Ff&&(n._prefault=o)},zf=(e,t,n,r)=>{let i=e._zod.def;Td(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{wd(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},Bf=(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;Td(o,t,r);let s=t.seen.get(e);s.ref=o},Vf=(e,t,n,r)=>{let i=e._zod.def;Td(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},Hf=(e,t,n,r)=>{let i=e._zod.def;Td(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Uf=(e,t,n,r)=>{let i=e._zod.def;Td(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Wf={string:$d,number:ef,boolean:tf,bigint:nf,symbol:rf,null:af,undefined:of,void:sf,never:cf,any:lf,unknown:uf,date:df,enum:ff,literal:pf,nan:mf,template_literal:hf,file:gf,success:_f,custom:vf,function:yf,transform:bf,map:xf,set:Sf,array:Cf,object:Tf,union:Ef,intersection:Df,tuple:Of,record:Mf,nullable:Nf,nonoptional:Pf,default:Lf,prefault:Rf,catch:zf,pipe:Bf,readonly:Vf,promise:Hf,optional:Uf,lazy:(e,t,n,r)=>{let i=e._zod.innerType;Td(i,t,r);let a=t.seen.get(e);a.ref=i}};function Gf(e,t){if(`_idmap`in e){let n=e,r=Cd({...t,processors:Wf}),i={};for(let e of n._idmap.entries()){let[t,n]=e;Td(n,r)}let a={};r.external={registry:n,uri:t?.uri,defs:i};for(let e of n._idmap.entries()){let[t,n]=e;Dd(r,n),Oa(a,t,Pd(r,n))}return Object.keys(i).length>0&&(a.__shared={[r.target===`draft-2020-12`?`$defs`:`definitions`]:i}),{schemas:a}}let n=Cd({...t,processors:Wf});return Td(e,n),Dd(n,e),Pd(n,e)}const Kf=/*@__PURE__*/ z(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);gc.init(e,t),e.def=t,e.type=t.type},{get with(){return this.check},set with(e){yo(this,`with`,e)},parse(e,t){return Xo(this,e,t,{callee:this.parse})},parseAsync(e,t){return Qo(this,e,t,{callee:this.parseAsync})},safeParse(e,t){return es(this,e,t)},safeParseAsync(e,t){return rs(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 Ga(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)}}),qf=/*@__PURE__*/ z(`ZodMiniObject`,(e,t)=>{bl.init(e,t),Kf.init(e,t),Do(e,`shape`,e=>e._zod.def.shape,!1)});// @__NO_SIDE_EFFECTS__
|
|
130
|
-
function
|
|
131
|
-
`);if(`message`in e&&typeof e.message==`string`)return e.message;try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function rp(e){return e.description}function ip(e){if(Yf(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function ap(e){if(Yf(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 op=/* @__PURE__ */ new WeakSet([Object.prototype,Error.prototype]);function sp(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 cp=/*@__PURE__*/ z(`ZodError`,(e,t)=>{Uo.init(e,t),e.name=`ZodError`;let n=Object.getPrototypeOf(e);op.has(n)||(op.add(n),sp(n,`format`,e=>t=>qo(e,t)),sp(n,`flatten`,e=>t=>Ko(e,t)),sp(n,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,Sa,2)}),sp(n,`addIssues`,e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,Sa,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},void 0,{Parent:Error}),lp=/* @__PURE__ */ Yo(cp),up=/* @__PURE__ */ Zo(cp),dp=/* @__PURE__ */ $o(cp),fp=/* @__PURE__ */ ns(cp),pp=/* @__PURE__ */ ls(cp),mp=/* @__PURE__ */ us(cp),hp=/* @__PURE__ */ ds(cp),gp=/* @__PURE__ */ fs(cp),_p=/* @__PURE__ */ ps(cp),vp=/* @__PURE__ */ ms(cp),yp=/* @__PURE__ */ hs(cp),bp=/* @__PURE__ */ gs(cp);function xp(){Fo.localeError||Io(fu())}function Sp(){Fo.memoizer||Io({memoizer:lu()})}const Cp=/*@__PURE__*/ z(`ZodType`,(e,t)=>(xp(),gc.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(Fa(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 Ga(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Wm(e,t))},superRefine(e,t){return this.check(Gm(e,t))},overwrite(e){return this.check(/* @__PURE__ */ dd(e))},optional(){return wm(this)},exactOptional(){return Em(this)},nullable(){return Om(this)},nullish(){return wm(Om(this))},nonoptional(e){return Pm(this,e)},array(){return H(this)},or(e){return dm([this,e])},and(e){return hm(this,e)},transform(e){return Rm(this,Sm(e))},default(e){return Am(this,e)},prefault(e){return Mm(this,e)},catch(e){return Im(this,e)},pipe(e){return Rm(this,e)},readonly(){return Vm(this)},describe(e){let t=this.clone();return gu.add(t,{description:e}),t},meta(...e){if(e.length===0)return gu.get(this);let t=this.clone();return gu.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 bo(this,`~standard`,{...yc(this),jsonSchema:{input:Ld(this,`input`),output:Ld(this,`output`)}})},set"~standard"(e){yo(this,`~standard`,e)},parse:function e(t,n){return lp(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await up(this,t,n,{callee:e})},safeParse(e,t){return dp(this,e,t)},async safeParseAsync(e,t){return fp(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){yo(this,`spa`,e)},validate(e,t){return os(this,e,t)},validateAsync(e,t){return cs(this,e,t)},encode:function e(t,n){return pp(this,t,n,{callee:e})},decode:function e(t,n){return mp(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await hp(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await gp(this,t,n,{callee:e})},safeEncode(e,t){return _p(this,e,t)},safeDecode(e,t){return vp(this,e,t)},async safeEncodeAsync(e,t){return yp(this,e,t)},async safeDecodeAsync(e,t){return bp(this,e,t)},toJSONSchema(e){return Id(this,{})(e)},get description(){return gu.get(this)?.description},get _def(){return this._zod.def}}),wp=/*@__PURE__*/ z(`_ZodString`,(e,t)=>{bc.init(e,t),Cp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$d(e,t,n,r)},/*@__PURE__*/ xo({format:e=>Yd(e).format??null,minLength:e=>Yd(e).minimum??null,maxLength:e=>Yd(e).maximum??null},{regex(...e){return this.check(/* @__PURE__ */ ad(...e))},includes(...e){return this.check(/* @__PURE__ */ cd(...e))},startsWith(...e){return this.check(/* @__PURE__ */ ld(...e))},endsWith(...e){return this.check(/* @__PURE__ */ ud(...e))},min(...e){return this.check(/* @__PURE__ */ rd(...e))},max(...e){return this.check(/* @__PURE__ */ nd(...e))},length(...e){return this.check(/* @__PURE__ */ id(...e))},nonempty(...e){return this.check(/* @__PURE__ */ rd(1,...e))},lowercase(e){return this.check(/* @__PURE__ */ od(e))},uppercase(e){return this.check(/* @__PURE__ */ sd(e))},trim(){return this.check(/* @__PURE__ */ pd())},normalize(...e){return this.check(/* @__PURE__ */ fd(...e))},toLowerCase(){return this.check(/* @__PURE__ */ md())},toUpperCase(){return this.check(/* @__PURE__ */ hd())},slugify(){return this.check(/* @__PURE__ */ gd())}})),Tp=/*@__PURE__*/ z(`ZodString`,(e,t)=>{bc.init(e,t),wp.init(e,t)},{email(e){return this.check(/* @__PURE__ */ yu(jp,e))},url(e){return this.check(/* @__PURE__ */ Tu(Pp,e))},jwt(e){return this.check(/* @__PURE__ */ Bu(Yp,e))},emoji(e){return this.check(/* @__PURE__ */ Eu(Fp,e))},guid(e){return this.check(/* @__PURE__ */ bu(Mp,e))},uuid(e){return this.check(/* @__PURE__ */ xu(Np,e))},uuidv4(e){return this.check(/* @__PURE__ */ Su(Np,e))},uuidv6(e){return this.check(/* @__PURE__ */ Cu(Np,e))},uuidv7(e){return this.check(/* @__PURE__ */ wu(Np,e))},nanoid(e){return this.check(/* @__PURE__ */ Du(Ip,e))},cuid(e){return this.check(/* @__PURE__ */ Ou(Lp,e))},cuid2(e){return this.check(/* @__PURE__ */ ku(Rp,e))},ulid(e){return this.check(/* @__PURE__ */ Au(zp,e))},base64(e){return this.check(/* @__PURE__ */ Lu(Kp,e))},base64url(e){return this.check(/* @__PURE__ */ Ru(qp,e))},xid(e){return this.check(/* @__PURE__ */ ju(Bp,e))},ksuid(e){return this.check(/* @__PURE__ */ Mu(Vp,e))},ipv4(e){return this.check(/* @__PURE__ */ Nu(Hp,e))},ipv6(e){return this.check(/* @__PURE__ */ Pu(Up,e))},cidrv4(e){return this.check(/* @__PURE__ */ Fu(Wp,e))},cidrv6(e){return this.check(/* @__PURE__ */ Iu(Gp,e))},e164(e){return this.check(/* @__PURE__ */ zu(Jp,e))},datetime(e){return this.check(/* @__PURE__ */ Vu(Dp,e))},date(e){return this.check(/* @__PURE__ */ Hu(Op,e))},time(e){return this.check(/* @__PURE__ */ Uu(kp,e))},duration(e){return this.check(/* @__PURE__ */ Wu(Ap,e))}});function B(e){return/* @__PURE__ */ vu(Tp,e)}const Ep=/*@__PURE__*/ z(`ZodStringFormat`,(e,t)=>{xc.init(e,t),wp.init(e,t)}),Dp=/*@__PURE__*/ z(`ZodISODateTime`,(e,t)=>{Bc.init(e,t),Ep.init(e,t)}),Op=/*@__PURE__*/ z(`ZodISODate`,(e,t)=>{Vc.init(e,t),Ep.init(e,t)}),kp=/*@__PURE__*/ z(`ZodISOTime`,(e,t)=>{Hc.init(e,t),Ep.init(e,t)}),Ap=/*@__PURE__*/ z(`ZodISODuration`,(e,t)=>{Uc.init(e,t),Ep.init(e,t)}),jp=/*@__PURE__*/ z(`ZodEmail`,(e,t)=>{wc.init(e,t),Ep.init(e,t)}),Mp=/*@__PURE__*/ z(`ZodGUID`,(e,t)=>{Sc.init(e,t),Ep.init(e,t)}),Np=/*@__PURE__*/ z(`ZodUUID`,(e,t)=>{Cc.init(e,t),Ep.init(e,t)}),Pp=/*@__PURE__*/ z(`ZodURL`,(e,t)=>{Mc.init(e,t),Ep.init(e,t)}),Fp=/*@__PURE__*/ z(`ZodEmoji`,(e,t)=>{Nc.init(e,t),Ep.init(e,t)}),Ip=/*@__PURE__*/ z(`ZodNanoID`,(e,t)=>{Pc.init(e,t),Ep.init(e,t)}),Lp=/*@__PURE__*/ z(`ZodCUID`,(e,t)=>{Fc.init(e,t),Ep.init(e,t)}),Rp=/*@__PURE__*/ z(`ZodCUID2`,(e,t)=>{Ic.init(e,t),Ep.init(e,t)}),zp=/*@__PURE__*/ z(`ZodULID`,(e,t)=>{Lc.init(e,t),Ep.init(e,t)}),Bp=/*@__PURE__*/ z(`ZodXID`,(e,t)=>{Rc.init(e,t),Ep.init(e,t)}),Vp=/*@__PURE__*/ z(`ZodKSUID`,(e,t)=>{zc.init(e,t),Ep.init(e,t)}),Hp=/*@__PURE__*/ z(`ZodIPv4`,(e,t)=>{Wc.init(e,t),Ep.init(e,t)}),Up=/*@__PURE__*/ z(`ZodIPv6`,(e,t)=>{qc.init(e,t),Ep.init(e,t)}),Wp=/*@__PURE__*/ z(`ZodCIDRv4`,(e,t)=>{Jc.init(e,t),Ep.init(e,t)}),Gp=/*@__PURE__*/ z(`ZodCIDRv6`,(e,t)=>{Xc.init(e,t),Ep.init(e,t)}),Kp=/*@__PURE__*/ z(`ZodBase64`,(e,t)=>{$c.init(e,t),Ep.init(e,t)}),qp=/*@__PURE__*/ z(`ZodBase64URL`,(e,t)=>{nl.init(e,t),Ep.init(e,t)}),Jp=/*@__PURE__*/ z(`ZodE164`,(e,t)=>{rl.init(e,t),Ep.init(e,t)}),Yp=/*@__PURE__*/ z(`ZodJWT`,(e,t)=>{al.init(e,t),Ep.init(e,t)}),Xp=/*@__PURE__*/ z(`ZodNumber`,(e,t)=>{ol.init(e,t),Cp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ef(e,t,n,r),e.isFinite=!0},/*@__PURE__*/ xo({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=Yd(e);return Math.max(t??-1/0,n??-1/0)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=Yd(e);return Math.min(t??1/0,n??1/0)},isInt:e=>{let{isInt:t,multipleOf:n}=Yd(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>Yd(e).format??null},{gt(e,t){return this.check(/* @__PURE__ */ $u(e,t))},gte(e,t){return this.check(/* @__PURE__ */ ed(e,t))},min(e,t){return this.check(/* @__PURE__ */ ed(e,t))},lt(e,t){return this.check(/* @__PURE__ */ Zu(e,t))},lte(e,t){return this.check(/* @__PURE__ */ Qu(e,t))},max(e,t){return this.check(/* @__PURE__ */ Qu(e,t))},int(e){return this.check(Qp(e))},safe(e){return this.check(Qp(e))},positive(e){return this.check(/* @__PURE__ */ $u(0,e))},nonnegative(e){return this.check(/* @__PURE__ */ ed(0,e))},negative(e){return this.check(/* @__PURE__ */ Zu(0,e))},nonpositive(e){return this.check(/* @__PURE__ */ Qu(0,e))},multipleOf(e,t){return this.check(/* @__PURE__ */ td(e,t))},step(e,t){return this.check(/* @__PURE__ */ td(e,t))},finite(){return this}}));function V(e){return/* @__PURE__ */ Gu(Xp,e)}const Zp=/*@__PURE__*/ z(`ZodNumberFormat`,(e,t)=>{sl.init(e,t),Xp.init(e,t)});function Qp(e){return/* @__PURE__ */ Ku(Zp,e)}const $p=/*@__PURE__*/ z(`ZodBoolean`,(e,t)=>{cl.init(e,t),Cp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>tf(e,t,n,r)});function em(e){return/* @__PURE__ */ qu($p,e)}const tm=/*@__PURE__*/ z(`ZodNull`,(e,t)=>{ll.init(e,t),Cp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>af(e,t,n,r)});function nm(e){return/* @__PURE__ */ Ju(tm,e)}const rm=/*@__PURE__*/ z(`ZodUnknown`,(e,t)=>{ul.init(e,t),Cp.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function im(){return/* @__PURE__ */ Yu(rm)}const am=/*@__PURE__*/ z(`ZodNever`,(e,t)=>{dl.init(e,t),Cp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>cf(e,t,n,r)});function om(e){return/* @__PURE__ */ Xu(am,e)}const sm=/*@__PURE__*/ z(`ZodArray`,(e,t)=>{Sp(),hl.init(e,t),Cp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Cf(e,t,n,r),e.element=t.element},{min(e,t){return this.check(/* @__PURE__ */ rd(e,t))},nonempty(e){return this.check(/* @__PURE__ */ rd(1,e))},max(e,t){return this.check(/* @__PURE__ */ nd(e,t))},length(e,t){return this.check(/* @__PURE__ */ id(e,t))},unwrap(){return this.element}});function H(e,t){return/* @__PURE__ */ _d(sm,e,t)}const cm=/*@__PURE__*/ z(`ZodObject`,(e,t)=>{Sp(),xl.init(e,t),Cp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Tf(e,t,n,r),Do(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return ym(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(Fa(this._zod.def,{catchall:e}))},passthrough(){return this.clone(Fa(this._zod.def,{catchall:im()}))},loose(){return this.clone(Fa(this._zod.def,{catchall:im()}))},strict(){return this.clone(Fa(this._zod.def,{catchall:om()}))},strip(){return this.clone(Fa(this._zod.def,{catchall:void 0}))},extend(e){return $a(this,e)},safeExtend(e){return to(this,e)},merge(e){return no(this,e)},pick(e){return Xa(this,e)},omit(e){return Qa(this,e)},partial(...e){return ro(Cm,this,e[0])},exactPartial(...e){return ro(Tm,this,e[0],`exactPartial`)},required(...e){return io(Nm,this,e[0])}});function U(e,t){let n={type:`object`,shape:e??{},...L(t)};return new cm(n)}function lm(e,t){return new cm({type:`object`,shape:e,catchall:im(),...L(t)})}const um=/*@__PURE__*/ z(`ZodUnion`,(e,t)=>{Cl.init(e,t),Cp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ef(e,t,n,r),e.options=t.options});function dm(e,t){return new um({type:`union`,options:e,...L(t)})}const fm=/*@__PURE__*/ z(`ZodDiscriminatedUnion`,(e,t)=>{um.init(e,t),Tl.init(e,t)});function pm(e,t,n){return new fm({type:`union`,options:t,discriminator:e,...L(n)})}const mm=/*@__PURE__*/ z(`ZodIntersection`,(e,t)=>{El.init(e,t),Cp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Df(e,t,n,r)});function hm(e,t){return new mm({type:`intersection`,left:e,right:t})}const gm=/*@__PURE__*/ z(`ZodRecord`,(e,t)=>{Sp(),kl.init(e,t),Cp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Mf(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function _m(e,t,n){return!t||!t._zod?new gm({type:`record`,keyType:B(),valueType:e,...L(t)}):new gm({type:`record`,keyType:e,valueType:t,...L(n)})}const vm=/*@__PURE__*/ z(`ZodEnum`,(e,t)=>{Al.init(e,t),Cp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ff(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 vm({...t,checks:[],...L(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 vm({...t,checks:[],...L(r),entries:i})}});function ym(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new vm({type:`enum`,entries:n,...L(t)})}const bm=/*@__PURE__*/ z(`ZodLiteral`,(e,t)=>{jl.init(e,t),Cp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>pf(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 W(e,t){return new bm({type:`literal`,values:Array.isArray(e)?e:[e],...L(t)})}const xm=/*@__PURE__*/ z(`ZodTransform`,(e,t)=>{Sp(),Ml.init(e,t),Cp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>bf(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new Po(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(_o(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(_o(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function Sm(e){return new xm({type:`transform`,transform:e})}const Cm=/*@__PURE__*/ z(`ZodOptional`,(e,t)=>{Pl.init(e,t),Cp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Uf(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function wm(e){return new Cm({type:`optional`,innerType:e})}const Tm=/*@__PURE__*/ z(`ZodExactOptional`,(e,t)=>{Fl.init(e,t),Cp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Uf(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Em(e){return new Tm({type:`optional`,innerType:e})}const Dm=/*@__PURE__*/ z(`ZodNullable`,(e,t)=>{Il.init(e,t),Cp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Nf(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Om(e){return new Dm({type:`nullable`,innerType:e})}const km=/*@__PURE__*/ z(`ZodDefault`,(e,t)=>{Ll.init(e,t),Cp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Lf(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function Am(e,t){return new km({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():Ha(t)}})}const jm=/*@__PURE__*/ z(`ZodPrefault`,(e,t)=>{zl.init(e,t),Cp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Rf(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Mm(e,t){return new jm({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():Ha(t)}})}const Nm=/*@__PURE__*/ z(`ZodNonOptional`,(e,t)=>{Bl.init(e,t),Cp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Pf(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Pm(e,t){return new Nm({type:`nonoptional`,innerType:e,...L(t)})}const Fm=/*@__PURE__*/ z(`ZodCatch`,(e,t)=>{Ul.init(e,t),Cp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zf(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Im(e,t){return new Fm({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:Oo(t)})}const Lm=/*@__PURE__*/ z(`ZodPipe`,(e,t)=>{Wl.init(e,t),Cp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Bf(e,t,n,r),e.in=t.in,e.out=t.out});function Rm(e,t){return new Lm({type:`pipe`,in:e,out:t})}const zm=/*@__PURE__*/ z(`ZodPreprocess`,(e,t)=>{Lm.init(e,t),Kl.init(e,t)}),Bm=/*@__PURE__*/ z(`ZodReadonly`,(e,t)=>{ql.init(e,t),Cp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Vf(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Vm(e){return new Bm({type:`readonly`,innerType:e})}const Hm=/*@__PURE__*/ z(`ZodCustom`,(e,t)=>{Yl.init(e,t),Cp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>vf(e,t,n,r)});function Um(e,t){return/* @__PURE__ */ vd(Hm,e??(()=>!0),t)}function Wm(e,t={}){return/* @__PURE__ */ yd(Hm,e,t)}function Gm(e,t){return/* @__PURE__ */ bd(e,t)}function Km(e,t){return new zm({type:`pipe`,in:Sm(e),out:t})}function qm(e){return/* @__PURE__ */ Vu(Dp,e)}const Jm=`2025-11-25`,Ym=[Jm,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],Xm=`io.modelcontextprotocol/related-task`,Zm=Um(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),Qm=dm([B(),V().int()]),$m=B();lm({ttl:V().optional(),pollInterval:V().optional()});const eh=U({ttl:V().optional()}),th=U({taskId:B()}),nh=lm({progressToken:Qm.optional(),[Xm]:th.optional()}),rh=U({_meta:nh.optional()}),ih=rh.extend({task:eh.optional()}),ah=e=>ih.safeParse(e).success,oh=U({method:B(),params:rh.loose().optional()}),sh=U({_meta:nh.optional()}),ch=U({method:B(),params:sh.loose().optional()}),lh=lm({_meta:nh.optional()}),uh=dm([B(),V().int()]),dh=U({jsonrpc:W(`2.0`),id:uh,...oh.shape}).strict(),fh=e=>dh.safeParse(e).success,ph=U({jsonrpc:W(`2.0`),...ch.shape}).strict(),mh=e=>ph.safeParse(e).success,hh=U({jsonrpc:W(`2.0`),id:uh,result:lh}).strict(),gh=e=>hh.safeParse(e).success;var G;(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`})(G||={});const _h=U({jsonrpc:W(`2.0`),id:uh.optional(),error:U({code:V().int(),message:B(),data:im().optional()})}).strict(),vh=e=>_h.safeParse(e).success,yh=dm([dh,ph,hh,_h]);dm([hh,_h]);const bh=lh.strict(),xh=sh.extend({requestId:uh.optional(),reason:B().optional()}),Sh=ch.extend({method:W(`notifications/cancelled`),params:xh}),Ch=U({icons:H(U({src:B(),mimeType:B().optional(),sizes:H(B()).optional(),theme:ym([`light`,`dark`]).optional()})).optional()}),wh=U({name:B(),title:B().optional()}),Th=wh.extend({...wh.shape,...Ch.shape,version:B(),websiteUrl:B().optional(),description:B().optional()}),Eh=Km(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,hm(U({form:hm(U({applyDefaults:em().optional()}),_m(B(),im())).optional(),url:Zm.optional()}),_m(B(),im()).optional())),Dh=lm({list:Zm.optional(),cancel:Zm.optional(),requests:lm({sampling:lm({createMessage:Zm.optional()}).optional(),elicitation:lm({create:Zm.optional()}).optional()}).optional()}),Oh=lm({list:Zm.optional(),cancel:Zm.optional(),requests:lm({tools:lm({call:Zm.optional()}).optional()}).optional()}),kh=U({experimental:_m(B(),Zm).optional(),sampling:U({context:Zm.optional(),tools:Zm.optional()}).optional(),elicitation:Eh.optional(),roots:U({listChanged:em().optional()}).optional(),tasks:Dh.optional(),extensions:_m(B(),Zm).optional()}),Ah=rh.extend({protocolVersion:B(),capabilities:kh,clientInfo:Th}),jh=oh.extend({method:W(`initialize`),params:Ah}),Mh=U({experimental:_m(B(),Zm).optional(),logging:Zm.optional(),completions:Zm.optional(),prompts:U({listChanged:em().optional()}).optional(),resources:U({subscribe:em().optional(),listChanged:em().optional()}).optional(),tools:U({listChanged:em().optional()}).optional(),tasks:Oh.optional(),extensions:_m(B(),Zm).optional()}),Nh=lh.extend({protocolVersion:B(),capabilities:Mh,serverInfo:Th,instructions:B().optional()}),Ph=ch.extend({method:W(`notifications/initialized`),params:sh.optional()}),Fh=oh.extend({method:W(`ping`),params:rh.optional()}),Ih=U({progress:V(),total:wm(V()),message:wm(B())}),Lh=U({...sh.shape,...Ih.shape,progressToken:Qm}),Rh=ch.extend({method:W(`notifications/progress`),params:Lh}),zh=rh.extend({cursor:$m.optional()}),Bh=oh.extend({params:zh.optional()}),Vh=lh.extend({nextCursor:$m.optional()}),Hh=ym([`working`,`input_required`,`completed`,`failed`,`cancelled`]),Uh=U({taskId:B(),status:Hh,ttl:dm([V(),nm()]),createdAt:B(),lastUpdatedAt:B(),pollInterval:wm(V()),statusMessage:wm(B())}),Wh=lh.extend({task:Uh}),Gh=sh.merge(Uh),Kh=ch.extend({method:W(`notifications/tasks/status`),params:Gh}),qh=oh.extend({method:W(`tasks/get`),params:rh.extend({taskId:B()})}),Jh=lh.merge(Uh),Yh=oh.extend({method:W(`tasks/result`),params:rh.extend({taskId:B()})});lh.loose();const Xh=Bh.extend({method:W(`tasks/list`)}),Zh=Vh.extend({tasks:H(Uh)}),Qh=oh.extend({method:W(`tasks/cancel`),params:rh.extend({taskId:B()})}),$h=lh.merge(Uh),eg=U({uri:B(),mimeType:wm(B()),_meta:_m(B(),im()).optional()}),tg=eg.extend({text:B()}),ng=B().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),rg=eg.extend({blob:ng}),ig=ym([`user`,`assistant`]),ag=U({audience:H(ig).optional(),priority:V().min(0).max(1).optional(),lastModified:qm({offset:!0}).optional()}),og=U({...wh.shape,...Ch.shape,uri:B(),description:wm(B()),mimeType:wm(B()),size:wm(V()),annotations:ag.optional(),_meta:wm(lm({}))}),sg=U({...wh.shape,...Ch.shape,uriTemplate:B(),description:wm(B()),mimeType:wm(B()),annotations:ag.optional(),_meta:wm(lm({}))}),cg=Bh.extend({method:W(`resources/list`)}),lg=Vh.extend({resources:H(og)}),ug=Bh.extend({method:W(`resources/templates/list`)}),dg=Vh.extend({resourceTemplates:H(sg)}),fg=rh.extend({uri:B()}),pg=fg,mg=oh.extend({method:W(`resources/read`),params:pg}),hg=lh.extend({contents:H(dm([tg,rg]))}),gg=ch.extend({method:W(`notifications/resources/list_changed`),params:sh.optional()}),_g=fg,vg=oh.extend({method:W(`resources/subscribe`),params:_g}),yg=fg,bg=oh.extend({method:W(`resources/unsubscribe`),params:yg}),xg=sh.extend({uri:B()}),Sg=ch.extend({method:W(`notifications/resources/updated`),params:xg}),Cg=U({name:B(),description:wm(B()),required:wm(em())}),wg=U({...wh.shape,...Ch.shape,description:wm(B()),arguments:wm(H(Cg)),_meta:wm(lm({}))}),Tg=Bh.extend({method:W(`prompts/list`)}),Eg=Vh.extend({prompts:H(wg)}),Dg=rh.extend({name:B(),arguments:_m(B(),B()).optional()}),Og=oh.extend({method:W(`prompts/get`),params:Dg}),kg=U({type:W(`text`),text:B(),annotations:ag.optional(),_meta:_m(B(),im()).optional()}),Ag=U({type:W(`image`),data:ng,mimeType:B(),annotations:ag.optional(),_meta:_m(B(),im()).optional()}),jg=U({type:W(`audio`),data:ng,mimeType:B(),annotations:ag.optional(),_meta:_m(B(),im()).optional()}),Mg=U({type:W(`tool_use`),name:B(),id:B(),input:_m(B(),im()),_meta:_m(B(),im()).optional()}),Ng=U({type:W(`resource`),resource:dm([tg,rg]),annotations:ag.optional(),_meta:_m(B(),im()).optional()}),Pg=dm([kg,Ag,jg,og.extend({type:W(`resource_link`)}),Ng]),Fg=U({role:ig,content:Pg}),Ig=lh.extend({description:B().optional(),messages:H(Fg)}),Lg=ch.extend({method:W(`notifications/prompts/list_changed`),params:sh.optional()}),Rg=U({title:B().optional(),readOnlyHint:em().optional(),destructiveHint:em().optional(),idempotentHint:em().optional(),openWorldHint:em().optional()}),zg=U({taskSupport:ym([`required`,`optional`,`forbidden`]).optional()}),Bg=U({...wh.shape,...Ch.shape,description:B().optional(),inputSchema:U({type:W(`object`),properties:_m(B(),Zm).optional(),required:H(B()).optional()}).catchall(im()),outputSchema:U({type:W(`object`),properties:_m(B(),Zm).optional(),required:H(B()).optional()}).catchall(im()).optional(),annotations:Rg.optional(),execution:zg.optional(),_meta:_m(B(),im()).optional()}),Vg=Bh.extend({method:W(`tools/list`)}),Hg=Vh.extend({tools:H(Bg)}),Ug=lh.extend({content:H(Pg).default([]),structuredContent:_m(B(),im()).optional(),isError:em().optional()});Ug.or(lh.extend({toolResult:im()}));const Wg=ih.extend({name:B(),arguments:_m(B(),im()).optional()}),Gg=oh.extend({method:W(`tools/call`),params:Wg}),Kg=ch.extend({method:W(`notifications/tools/list_changed`),params:sh.optional()});U({autoRefresh:em().default(!0),debounceMs:V().int().nonnegative().default(300)});const qg=ym([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),Jg=rh.extend({level:qg}),Yg=oh.extend({method:W(`logging/setLevel`),params:Jg}),Xg=sh.extend({level:qg,logger:B().optional(),data:im()}),Zg=ch.extend({method:W(`notifications/message`),params:Xg}),Qg=U({hints:H(U({name:B().optional()})).optional(),costPriority:V().min(0).max(1).optional(),speedPriority:V().min(0).max(1).optional(),intelligencePriority:V().min(0).max(1).optional()}),$g=U({mode:ym([`auto`,`required`,`none`]).optional()}),e_=U({type:W(`tool_result`),toolUseId:B().describe(`The unique identifier for the corresponding tool call.`),content:H(Pg).default([]),structuredContent:U({}).loose().optional(),isError:em().optional(),_meta:_m(B(),im()).optional()}),t_=pm(`type`,[kg,Ag,jg]),n_=pm(`type`,[kg,Ag,jg,Mg,e_]),r_=U({role:ig,content:dm([n_,H(n_)]),_meta:_m(B(),im()).optional()}),i_=ih.extend({messages:H(r_),modelPreferences:Qg.optional(),systemPrompt:B().optional(),includeContext:ym([`none`,`thisServer`,`allServers`]).optional(),temperature:V().optional(),maxTokens:V().int(),stopSequences:H(B()).optional(),metadata:Zm.optional(),tools:H(Bg).optional(),toolChoice:$g.optional()}),a_=oh.extend({method:W(`sampling/createMessage`),params:i_}),o_=lh.extend({model:B(),stopReason:wm(ym([`endTurn`,`stopSequence`,`maxTokens`]).or(B())),role:ig,content:t_}),s_=lh.extend({model:B(),stopReason:wm(ym([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(B())),role:ig,content:dm([n_,H(n_)])}),c_=U({type:W(`boolean`),title:B().optional(),description:B().optional(),default:em().optional()}),l_=U({type:W(`string`),title:B().optional(),description:B().optional(),minLength:V().optional(),maxLength:V().optional(),format:ym([`email`,`uri`,`date`,`date-time`]).optional(),default:B().optional()}),u_=U({type:ym([`number`,`integer`]),title:B().optional(),description:B().optional(),minimum:V().optional(),maximum:V().optional(),default:V().optional()}),d_=U({type:W(`string`),title:B().optional(),description:B().optional(),enum:H(B()),default:B().optional()}),f_=U({type:W(`string`),title:B().optional(),description:B().optional(),oneOf:H(U({const:B(),title:B()})),default:B().optional()}),p_=dm([dm([U({type:W(`string`),title:B().optional(),description:B().optional(),enum:H(B()),enumNames:H(B()).optional(),default:B().optional()}),dm([d_,f_]),dm([U({type:W(`array`),title:B().optional(),description:B().optional(),minItems:V().optional(),maxItems:V().optional(),items:U({type:W(`string`),enum:H(B())}),default:H(B()).optional()}),U({type:W(`array`),title:B().optional(),description:B().optional(),minItems:V().optional(),maxItems:V().optional(),items:U({anyOf:H(U({const:B(),title:B()}))}),default:H(B()).optional()})])]),c_,l_,u_]),m_=dm([ih.extend({mode:W(`form`).optional(),message:B(),requestedSchema:U({type:W(`object`),properties:_m(B(),p_),required:H(B()).optional()})}),ih.extend({mode:W(`url`),message:B(),elicitationId:B(),url:B().url()})]),h_=oh.extend({method:W(`elicitation/create`),params:m_}),g_=sh.extend({elicitationId:B()}),__=ch.extend({method:W(`notifications/elicitation/complete`),params:g_}),v_=lh.extend({action:ym([`accept`,`decline`,`cancel`]),content:Km(e=>e===null?void 0:e,_m(B(),dm([B(),V(),em(),H(B())])).optional())}),y_=U({type:W(`ref/resource`),uri:B()}),b_=U({type:W(`ref/prompt`),name:B()}),x_=rh.extend({ref:dm([b_,y_]),argument:U({name:B(),value:B()}),context:U({arguments:_m(B(),B()).optional()}).optional()}),S_=oh.extend({method:W(`completion/complete`),params:x_});function C_(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function w_(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const T_=lh.extend({completion:lm({values:H(B()).max(100),total:wm(V().int()),hasMore:wm(em())})}),E_=U({uri:B().startsWith(`file://`),name:B().optional(),_meta:_m(B(),im()).optional()}),D_=oh.extend({method:W(`roots/list`),params:rh.optional()}),O_=lh.extend({roots:H(E_)}),k_=ch.extend({method:W(`notifications/roots/list_changed`),params:sh.optional()});dm([Fh,jh,S_,Yg,Og,Tg,cg,ug,mg,vg,bg,Gg,Vg,qh,Yh,Xh,Qh]),dm([Sh,Rh,Ph,k_,Kh]),dm([bh,o_,s_,v_,O_,Jh,Zh,Wh]),dm([Fh,a_,h_,D_,qh,Yh,Xh,Qh]),dm([Sh,Rh,Zg,Sg,gg,Kg,Lg,Kh,__]),dm([bh,Nh,T_,Ig,Eg,lg,dg,hg,Ug,Hg,Jh,Zh,Wh]);var K=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===G.UrlElicitationRequired&&r){let e=r;if(e.elicitations)return new A_(e.elicitations,n)}return new e(t,n,r)}},A_=class extends K{constructor(e,t=`URL elicitation${e.length>1?`s`:``} required`){super(G.UrlElicitationRequired,t,{elicitations:e})}get elicitations(){return this.data?.elicitations??[]}};function j_(e){return e===`completed`||e===`failed`||e===`cancelled`}const M_=Symbol(`Let zodToJsonSchema decide on which parser to use`),N_={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`},P_=e=>typeof e==`string`?{...N_,name:e}:{...N_,...e},F_=e=>{let t=P_(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 I_(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function q(e,t,n,r,i){e[t]=n,I_(e,t,r,i)}const L_=(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 R_(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?L_(t,e.currentPath):t.join(`/`)}}function z_(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==I.ZodAny&&(n.items=J(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&q(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&q(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(q(n,`minItems`,e.exactLength.value,e.exactLength.message,t),q(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function B_(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?q(n,`minimum`,r.value,r.message,t):q(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),q(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?q(n,`maximum`,r.value,r.message,t):q(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),q(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:q(n,`multipleOf`,r.value,r.message,t)}return n}function V_(){return{type:`boolean`}}function H_(e,t){return J(e.type._def,t)}const U_=(e,t)=>J(e.innerType._def,t);function W_(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>W_(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 G_(e,t)}}const G_=(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`:q(n,`minimum`,r.value,r.message,t);break;case`max`:q(n,`maximum`,r.value,r.message,t)}return n};function K_(e,t){return{...J(e.innerType._def,t),default:e.defaultValue()}}function q_(e,t){return t.effectStrategy===`input`?J(e.schema._def,t):R_(t)}function J_(e){return{type:`string`,enum:Array.from(e.values)}}const Y_=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function X_(e,t){let n=[J(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),J(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(Y_(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 Z_(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 Q_;const $_={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:()=>(Q_===void 0&&(Q_=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),Q_),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 ev(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:q(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:q(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`:iv(n,`email`,r.message,t);break;case`format:idn-email`:iv(n,`idn-email`,r.message,t);break;case`pattern:zod`:av(n,$_.email,r.message,t)}break;case`url`:iv(n,`uri`,r.message,t);break;case`uuid`:iv(n,`uuid`,r.message,t);break;case`regex`:av(n,r.regex,r.message,t);break;case`cuid`:av(n,$_.cuid,r.message,t);break;case`cuid2`:av(n,$_.cuid2,r.message,t);break;case`startsWith`:av(n,RegExp(`^${tv(r.value,t)}`),r.message,t);break;case`endsWith`:av(n,RegExp(`${tv(r.value,t)}$`),r.message,t);break;case`datetime`:iv(n,`date-time`,r.message,t);break;case`date`:iv(n,`date`,r.message,t);break;case`time`:iv(n,`time`,r.message,t);break;case`duration`:iv(n,`duration`,r.message,t);break;case`length`:q(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),q(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:av(n,RegExp(tv(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&iv(n,`ipv4`,r.message,t),r.version!==`v4`&&iv(n,`ipv6`,r.message,t);break;case`base64url`:av(n,$_.base64url,r.message,t);break;case`jwt`:av(n,$_.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&av(n,$_.ipv4Cidr,r.message,t),r.version!==`v4`&&av(n,$_.ipv6Cidr,r.message,t);break;case`emoji`:av(n,$_.emoji(),r.message,t);break;case`ulid`:av(n,$_.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:iv(n,`binary`,r.message,t);break;case`contentEncoding:base64`:q(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:av(n,$_.base64,r.message,t)}break;case`nanoid`:av(n,$_.nanoid,r.message,t)}return n}function tv(e,t){return t.patternStrategy===`escape`?rv(e):e}const nv=/* @__PURE__ */ new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function rv(e){let t=``;for(let n=0;n<e.length;n++)nv.has(e[n])||(t+=`\\`),t+=e[n];return t}function iv(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}}})):q(e,`format`,t,n,r)}function av(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:ov(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):q(e,`pattern`,ov(t,r),n,r)}function ov(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
|
|
129
|
+
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 Dd(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;Dd(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 Od=/* @__PURE__ */ new Set([`type`,`properties`,`required`,`additionalProperties`]),kd=[`oneOf`,`anyOf`];function Ad(e){let t=e.additionalProperties;return t===void 0||t===!1||typeof t!=`object`||!t?null:Object.keys(t).length?t:null}function jd(e){let t=[];for(let n of e){if(typeof n!=`object`||n.type!==`object`)return null;for(let e in n)if(!Od.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]??Ad(n);t!=null&&(e.some(e=>JSON.stringify(e)===JSON.stringify(t))||e.push(t))}Da(n,r,e.length===1?e[0]:jd(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=Ad(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 Md(e){let t=e.allOf;if(!Array.isArray(t)||t.length<2)return;for(let t of Od)if(t in e)return;let n=t.filter(e=>kd.some(t=>Array.isArray(e[t]))),r=null;if(!n.length)r=jd(t);else{let e=n[0],i=kd.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=>jd([...a,e]));if(o.some(e=>!e))return;r={[i]:o}}r&&(delete e.allOf,xd(e,r))}function Nd(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)):xd(i,s),xd(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())Dd(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)??[])Md(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)}xd(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,Da(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:Id(t,`input`,e.processors),output:Id(t,`output`,e.processors)}},enumerable:!1,writable:!1}),n}catch{throw Error(`Error converting schema to JSON.`)}}function Pd(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 Pd(r.element,n);if(r.type===`set`)return Pd(r.valueType,n);if(r.type===`lazy`)return Pd(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 Pd(r.innerType,n);if(r.type===`intersection`)return Pd(r.left,n)||Pd(r.right,n);if(r.type===`record`||r.type===`map`)return Pd(r.keyType,n)||Pd(r.valueType,n);if(r.type===`pipe`)return e._zod.traits.has(`$ZodCodec`)?!0:Pd(r.in,n)||Pd(r.out,n);if(r.type===`object`){for(let e in r.shape)if(Pd(r.shape[e],n))return!0;return!1}if(r.type===`union`){for(let e of r.options)if(Pd(e,n))return!0;return!1}if(r.type===`tuple`){for(let e of r.items)if(Pd(e,n))return!0;return!!(r.rest&&Pd(r.rest,n))}return!1}const Fd=(e,t={})=>n=>{let r=Sd({...n,processors:t});return wd(e,r),Ed(r,e),Nd(r,e)},Id=(e,t,n={})=>r=>{let{libraryOptions:i,target:a}=r??{},o=Sd({...i??{},target:a,io:t,processors:n});return wd(e,o),Ed(o,e),Nd(o,e)},Ld=(e,t,n)=>{(e[t]===void 0||n>e[t])&&(e[t]=n)},Rd=(e,t,n)=>{(e[t]===void 0||n<e[t])&&(e[t]=n)},zd=(e,t)=>{Ld(e,`minimum`,t),Rd(e,`maximum`,t)},Bd=(e,t)=>{e.multipleOf??=[],e.multipleOf.includes(t)||e.multipleOf.push(t)},Vd=(e,t)=>{e.patterns??=/* @__PURE__ */ new Set,e.patterns.add(t)},Hd=(e,t)=>{e.mime=e.mime?e.mime.filter(e=>t.includes(e)):[...t]},Ud=(e,t)=>{e.format=t,t.includes(`int`)&&(e.isInt=!0)},Wd=(e,t)=>Ld(e,`minimum`,t.minimum),Gd=(e,t)=>Rd(e,`maximum`,t.maximum),Kd=e=>(t,n)=>{Ud(t,n.format);let[r,i]=e[n.format];Ld(t,`minimum`,r),Rd(t,`maximum`,i)},qd={greater_than:(e,t)=>Ld(e,t.inclusive?`minimum`:`exclusiveMinimum`,t.value),less_than:(e,t)=>Rd(e,t.inclusive?`maximum`:`exclusiveMaximum`,t.value),multiple_of:(e,t)=>Bd(e,t.value),number_format:Kd(qa),bigint_format:Kd(Ja),min_length:Wd,max_length:Gd,length_equals:(e,t)=>zd(e,t.length),min_size:Wd,max_size:Gd,size_equals:(e,t)=>zd(e,t.size),string_format:(e,t)=>{Ud(e,t.format),t.pattern&&Vd(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)=>Hd(e,t.mime)};function Jd(e){let t={},n=e._zod.def,r=e._zod.traits.has(`$ZodCheck`)?[e,...n.checks??[]]:n.checks??[];for(let e of r)qd[e._zod.def.check]?.(t,e._zod.def);let i=e._zod.bag;i.minimum!==void 0&&Ld(t,`minimum`,i.minimum),i.exclusiveMinimum!==void 0&&Ld(t,`exclusiveMinimum`,i.exclusiveMinimum),i.maximum!==void 0&&Rd(t,`maximum`,i.maximum),i.exclusiveMaximum!==void 0&&Rd(t,`exclusiveMaximum`,i.exclusiveMaximum),i.multipleOf!==void 0&&Bd(t,i.multipleOf),i.format!==void 0&&(t.format??=i.format,i.format.includes(`int`)&&(t.isInt=!0)),i.mime&&Hd(t,i.mime);for(let e of i.patterns??[])Vd(t,e);return t}const Yd={guid:`uuid`,url:`uri`,datetime:`date-time`,json_string:`json-string`,regex:``},Xd=/* @__PURE__ */ new Map([[Zc,Ms],[$c,Ns]]),Zd=e=>Xd.get(e)??e,Qd=(e,t,n,r)=>{let i=n;i.type=`string`;let{minimum:a,maximum:o,format:s,patterns:c,contentEncoding:l,laxFormat:u}=Jd(e);if(typeof a==`number`&&(i.minLength=a),typeof o==`number`&&(i.maxLength=o),s&&(i.format=Yd[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(Zd);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}))])}},$d=(e,t,n,r)=>{let i=n,{minimum:a,maximum:o,multipleOf:s,exclusiveMaximum:c,exclusiveMinimum:l,isInt:u}=Jd(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)):Cd(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}))])}},ef=(e,t,n,r)=>{n.type=`boolean`},tf=(e,t,n,r)=>{Cd(e,t,n,r,`BigInt cannot be represented in JSON Schema`)},nf=(e,t,n,r)=>{Cd(e,t,n,r,`Symbols cannot be represented in JSON Schema`)},rf=(e,t,n,r)=>{t.target===`openapi-3.0`?(n.type=`string`,n.nullable=!0,n.enum=[null]):n.type=`null`},af=(e,t,n,r)=>{Cd(e,t,n,r,`Undefined cannot be represented in JSON Schema`)},of=(e,t,n,r)=>{Cd(e,t,n,r,`Void cannot be represented in JSON Schema`)},sf=(e,t,n,r)=>{n.not={}},cf=(e,t,n,r)=>{},lf=(e,t,n,r)=>{},uf=(e,t,n,r)=>{Cd(e,t,n,r,`Date cannot be represented in JSON Schema`)},df=(e,t,n,r)=>{let i=e._zod.def,a=ya(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)},ff=(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(Cd(e,t,n,r,"Literal `undefined` cannot be represented in JSON Schema"))return}else if(typeof o==`bigint`){if(Cd(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}},pf=(e,t,n,r)=>{Cd(e,t,n,r,`NaN cannot be represented in JSON Schema`)},mf=(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},hf=(e,t,n,r)=>{let i=n;i.type=`string`,i.format=`binary`,i.contentEncoding=`binary`;let{minimum:a,maximum:o,mime:s}=Jd(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})))},gf=(e,t,n,r)=>{n.type=`boolean`},_f=(e,t,n,r)=>{Cd(e,t,n,r,`Custom types cannot be represented in JSON Schema`)},vf=(e,t,n,r)=>{Cd(e,t,n,r,`Function types cannot be represented in JSON Schema`)},yf=(e,t,n,r)=>{Cd(e,t,n,r,`Transforms cannot be represented in JSON Schema`)},bf=(e,t,n,r)=>{Cd(e,t,n,r,`Map cannot be represented in JSON Schema`)},xf=(e,t,n,r)=>{Cd(e,t,n,r,`Set cannot be represented in JSON Schema`)},Sf=(e,t,n,r)=>{let i=n,a=e._zod.def,{minimum:o,maximum:s}=Jd(e);typeof o==`number`&&(i.minItems=o),typeof s==`number`&&(i.maxItems=s),i.type=`array`,i.items=wd(a.element,t,{...r,path:[...r.path,`items`]})};function Cf(e){let t=e._zod.def;return t.type===`pipe`&&t.in._zod.traits.has(`$ZodTransform`)?Cf(t.out):t.type===`catch`?Cf(t.innerType):e._zod.optin}const wf=(e,t,n,r)=>{let i=n,a=e._zod.def,o=a.shape;if(Object.getOwnPropertySymbols(o).length&&Cd(e,t,i,r,`Symbol keys cannot be represented in JSON Schema`))return;i.type=`object`,i.properties={};for(let e in o)Da(i.properties,e,wd(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`?Cf(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=wd(a.catchall,t,{...r,path:[...r.path,`additionalProperties`]})):t.io===`output`&&(i.additionalProperties=!1)},Tf=(e,t,n,r)=>{let i=e._zod.def,a=i.inclusive===!1,o=i.options.map((e,n)=>wd(e,t,{...r,path:[...r.path,a?`oneOf`:`anyOf`,n]}));a?n.oneOf=o:n.anyOf=o},Ef=(e,t,n,r)=>{let i=e._zod.def,a=wd(i.left,t,{...r,path:[...r.path,`allOf`,0]}),o=wd(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)},Df=(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)=>wd(e,t,{...r,path:[...r.path,o,n]})),l=a.rest?wd(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`?Cf(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}=Jd(e);typeof p==`number`&&(i.minItems=p),typeof m==`number`&&(i.maxItems=m)};function Of(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=Of(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=>Of(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`)?Ws:Us).source)),p}const kf=/* @__PURE__ */ new WeakMap;function Af(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 kf.get(e)??[]){let i=e.seen.get(r),a=(i?.def??i?.schema)?.propertyNames;if(!a||a===!0||n.has(a))continue;let o=Of(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 jf=(e,t,n,r)=>{let i=n,a=e._zod.def;i.type=`object`;let o=a.keyType,s=Jd(o).patterns;if(a.mode===`loose`&&s&&s.size>0){let e=wd(a.valueType,t,{...r,path:[...r.path,`patternProperties`,`*`]});i.patternProperties={};for(let t of s)Da(i.patternProperties,Zd(t).source,e)}else{if(t.target===`draft-07`||t.target===`draft-2020-12`){i.propertyNames=wd(a.keyType,t,{...r,path:[...r.path,`propertyNames`]});let n=kf.get(t);n||(n=[],kf.set(t,n),t.deferred.push(()=>Af(t))),n.push(e)}i.additionalProperties=wd(a.valueType,t,{...r,path:[...r.path,`additionalProperties`]})}let c=o._zod.values,l=t.io===`input`&&Cf(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))}},Mf=(e,t,n,r)=>{let i=e._zod.def,a=wd(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`}]},Nf=(e,t,n,r)=>{let i=e._zod.def;wd(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Pf=Symbol();function Ff(e,t,n,r,i){let a=!1,o=JSON.stringify(e,(e,t)=>typeof t==`bigint`?(a=!0,null):t);return a?(Cd(t,n,r,i,`BigInt defaults cannot be represented in JSON Schema`),Pf):JSON.parse(o)}const If=(e,t,n,r)=>{let i=e._zod.def;wd(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o=Ff(i.defaultValue,e,t,n,r);o!==Pf&&(n.default=o)},Lf=(e,t,n,r)=>{let i=e._zod.def;wd(i.innerType,t,r);let a=t.seen.get(e);if(a.ref=i.innerType,t.io!==`input`)return;let o=Ff(i.defaultValue,e,t,n,r);o!==Pf&&(n._prefault=o)},Rf=(e,t,n,r)=>{let i=e._zod.def;wd(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType;let o;try{o=i.catchValue(void 0)}catch{Cd(e,t,n,r,`Dynamic catch values are not supported in JSON Schema`);return}n.default=o},zf=(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;wd(o,t,r);let s=t.seen.get(e);s.ref=o},Bf=(e,t,n,r)=>{let i=e._zod.def;wd(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType,n.readOnly=!0},Vf=(e,t,n,r)=>{let i=e._zod.def;wd(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Hf=(e,t,n,r)=>{let i=e._zod.def;wd(i.innerType,t,r);let a=t.seen.get(e);a.ref=i.innerType},Uf={string:Qd,number:$d,boolean:ef,bigint:tf,symbol:nf,null:rf,undefined:af,void:of,never:sf,any:cf,unknown:lf,date:uf,enum:df,literal:ff,nan:pf,template_literal:mf,file:hf,success:gf,custom:_f,function:vf,transform:yf,map:bf,set:xf,array:Sf,object:wf,union:Tf,intersection:Ef,tuple:Df,record:jf,nullable:Mf,nonoptional:Nf,default:If,prefault:Lf,catch:Rf,pipe:zf,readonly:Bf,promise:Vf,optional:Hf,lazy:(e,t,n,r)=>{let i=e._zod.innerType;wd(i,t,r);let a=t.seen.get(e);a.ref=i}};function Wf(e,t){if(`_idmap`in e){let n=e,r=Sd({...t,processors:Uf}),i={};for(let e of n._idmap.entries()){let[t,n]=e;wd(n,r)}let a={};r.external={registry:n,uri:t?.uri,defs:i};for(let e of n._idmap.entries()){let[t,n]=e;Ed(r,n),Da(a,t,Nd(r,n))}return Object.keys(i).length>0&&(a.__shared={[r.target===`draft-2020-12`?`$defs`:`definitions`]:i}),{schemas:a}}let n=Sd({...t,processors:Uf});return wd(e,n),Ed(n,e),Nd(n,e)}const Gf=/*@__PURE__*/ B(`ZodMiniType`,(e,t)=>{if(!e._zod)throw Error(`Uninitialized schema in ZodMiniType.`);hc.init(e,t),e.def=t,e.type=t.type},{get with(){return this.check},set with(e){vo(this,`with`,e)},parse(e,t){return Yo(this,e,t,{callee:this.parse})},parseAsync(e,t){return Zo(this,e,t,{callee:this.parseAsync})},safeParse(e,t){return $o(this,e,t)},safeParseAsync(e,t){return ns(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 Wa(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)}}),Kf=/*@__PURE__*/ B(`ZodMiniObject`,(e,t)=>{yl.init(e,t),Gf.init(e,t),Eo(e,`shape`,e=>e._zod.def.shape,!1)});// @__NO_SIDE_EFFECTS__
|
|
130
|
+
function qf(e,t){let n={type:`object`,shape:e??{},...R(t)};return new Kf(n)}function Jf(e){return!!e._zod}function Yf(e){let t=Object.values(e);if(t.length===0)return/* @__PURE__ */ qf({});let n=t.every(Jf),r=t.every(e=>!Jf(e));if(n)return/* @__PURE__ */ qf(e);if(r)return va(e);throw Error(`Mixed Zod versions detected in object shape.`)}function Xf(e,t){return Jf(e)?$o(e,t):e.safeParse(t)}async function Zf(e,t){return Jf(e)?await ns(e,t):await e.safeParseAsync(t)}function Qf(e){if(!e)return;let t;if(t=Jf(e)?e._zod?.def?.shape:e.shape,t){if(typeof t==`function`)try{return t()}catch{return}return t}}function $f(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 Yf(e)}}if(Jf(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 ep(e){return e.length===0?`object root`:e.reduce((e,t,n)=>n===0?String(t):typeof t==`number`?`${e}[${t}]`:`${e}.${t}`,``)}function tp(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 ${ep(e.path)}`:e.message).join(`
|
|
131
|
+
`);if(`message`in e&&typeof e.message==`string`)return e.message;try{return JSON.stringify(e)}catch{return String(e)}}return String(e)}function np(e){return e.description}function rp(e){if(Jf(e))return e._zod?.def?.type===`optional`;let t=e;return typeof e.isOptional==`function`?e.isOptional():t._def?.typeName===`ZodOptional`}function ip(e){if(Jf(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 ap=/* @__PURE__ */ new WeakSet([Object.prototype,Error.prototype]);function op(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 sp=/*@__PURE__*/ B(`ZodError`,(e,t)=>{Ho.init(e,t),e.name=`ZodError`;let n=Object.getPrototypeOf(e);ap.has(n)||(ap.add(n),op(n,`format`,e=>t=>Ko(e,t)),op(n,`flatten`,e=>t=>Go(e,t)),op(n,`addIssue`,e=>t=>{e.issues.push(t),e.message=JSON.stringify(e.issues,xa,2)}),op(n,`addIssues`,e=>t=>{e.issues.push(...t),e.message=JSON.stringify(e.issues,xa,2)}),Object.defineProperty(n,"isEmpty",{configurable:!0,enumerable:!1,get(){return this.issues.length===0}}))},void 0,{Parent:Error}),cp=/* @__PURE__ */ Jo(sp),lp=/* @__PURE__ */ Xo(sp),up=/* @__PURE__ */ Qo(sp),dp=/* @__PURE__ */ ts(sp),fp=/* @__PURE__ */ cs(sp),pp=/* @__PURE__ */ ls(sp),mp=/* @__PURE__ */ us(sp),hp=/* @__PURE__ */ ds(sp),gp=/* @__PURE__ */ fs(sp),_p=/* @__PURE__ */ ps(sp),vp=/* @__PURE__ */ ms(sp),yp=/* @__PURE__ */ hs(sp);function bp(){Po.localeError||Fo(du())}function xp(){Po.memoizer||Fo({memoizer:cu()})}const Sp=/*@__PURE__*/ B(`ZodType`,(e,t)=>(bp(),hc.init(e,t),e.def=t,e.type=t.type,e),{check(...e){let t=this.def;return this.clone(Pa(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 Wa(this,e,t)},brand(){return this},register(e,t){return e.add(this,t),this},refine(e,t){return this.check(Um(e,t))},superRefine(e,t){return this.check(Wm(e,t))},overwrite(e){return this.check(/* @__PURE__ */ ud(e))},optional(){return Cm(this)},exactOptional(){return Tm(this)},nullable(){return Dm(this)},nullish(){return Cm(Dm(this))},nonoptional(e){return Nm(this,e)},array(){return U(this)},or(e){return um([this,e])},and(e){return mm(this,e)},transform(e){return Lm(this,xm(e))},default(e){return km(this,e)},prefault(e){return jm(this,e)},catch(e){return Fm(this,e)},pipe(e){return Lm(this,e)},readonly(){return Bm(this)},describe(e){let t=this.clone();return hu.add(t,{description:e}),t},meta(...e){if(e.length===0)return hu.get(this);let t=this.clone();return hu.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 yo(this,`~standard`,{...vc(this),jsonSchema:{input:Id(this,`input`),output:Id(this,`output`)}})},set"~standard"(e){vo(this,`~standard`,e)},parse:function e(t,n){return cp(this,t,n,{callee:e})},parseAsync:async function e(t,n){return await lp(this,t,n,{callee:e})},safeParse(e,t){return up(this,e,t)},async safeParseAsync(e,t){return dp(this,e,t)},get spa(){return this?.safeParseAsync},set spa(e){vo(this,`spa`,e)},validate(e,t){return as(this,e,t)},validateAsync(e,t){return ss(this,e,t)},encode:function e(t,n){return fp(this,t,n,{callee:e})},decode:function e(t,n){return pp(this,t,n,{callee:e})},encodeAsync:async function e(t,n){return await mp(this,t,n,{callee:e})},decodeAsync:async function e(t,n){return await hp(this,t,n,{callee:e})},safeEncode(e,t){return gp(this,e,t)},safeDecode(e,t){return _p(this,e,t)},async safeEncodeAsync(e,t){return vp(this,e,t)},async safeDecodeAsync(e,t){return yp(this,e,t)},toJSONSchema(e){return Fd(this,{})(e)},get description(){return hu.get(this)?.description},get _def(){return this._zod.def}}),Cp=/*@__PURE__*/ B(`_ZodString`,(e,t)=>{yc.init(e,t),Sp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Qd(e,t,n,r)},/*@__PURE__*/ bo({format:e=>Jd(e).format??null,minLength:e=>Jd(e).minimum??null,maxLength:e=>Jd(e).maximum??null},{regex(...e){return this.check(/* @__PURE__ */ id(...e))},includes(...e){return this.check(/* @__PURE__ */ sd(...e))},startsWith(...e){return this.check(/* @__PURE__ */ cd(...e))},endsWith(...e){return this.check(/* @__PURE__ */ ld(...e))},min(...e){return this.check(/* @__PURE__ */ nd(...e))},max(...e){return this.check(/* @__PURE__ */ td(...e))},length(...e){return this.check(/* @__PURE__ */ rd(...e))},nonempty(...e){return this.check(/* @__PURE__ */ nd(1,...e))},lowercase(e){return this.check(/* @__PURE__ */ ad(e))},uppercase(e){return this.check(/* @__PURE__ */ od(e))},trim(){return this.check(/* @__PURE__ */ fd())},normalize(...e){return this.check(/* @__PURE__ */ dd(...e))},toLowerCase(){return this.check(/* @__PURE__ */ pd())},toUpperCase(){return this.check(/* @__PURE__ */ md())},slugify(){return this.check(/* @__PURE__ */ hd())}})),wp=/*@__PURE__*/ B(`ZodString`,(e,t)=>{yc.init(e,t),Cp.init(e,t)},{email(e){return this.check(/* @__PURE__ */ vu(Ap,e))},url(e){return this.check(/* @__PURE__ */ wu(Np,e))},jwt(e){return this.check(/* @__PURE__ */ zu(Jp,e))},emoji(e){return this.check(/* @__PURE__ */ Tu(Pp,e))},guid(e){return this.check(/* @__PURE__ */ yu(jp,e))},uuid(e){return this.check(/* @__PURE__ */ bu(Mp,e))},uuidv4(e){return this.check(/* @__PURE__ */ xu(Mp,e))},uuidv6(e){return this.check(/* @__PURE__ */ Su(Mp,e))},uuidv7(e){return this.check(/* @__PURE__ */ Cu(Mp,e))},nanoid(e){return this.check(/* @__PURE__ */ Eu(Fp,e))},cuid(e){return this.check(/* @__PURE__ */ Du(Ip,e))},cuid2(e){return this.check(/* @__PURE__ */ Ou(Lp,e))},ulid(e){return this.check(/* @__PURE__ */ ku(Rp,e))},base64(e){return this.check(/* @__PURE__ */ Iu(Gp,e))},base64url(e){return this.check(/* @__PURE__ */ Lu(Kp,e))},xid(e){return this.check(/* @__PURE__ */ Au(zp,e))},ksuid(e){return this.check(/* @__PURE__ */ ju(Bp,e))},ipv4(e){return this.check(/* @__PURE__ */ Mu(Vp,e))},ipv6(e){return this.check(/* @__PURE__ */ Nu(Hp,e))},cidrv4(e){return this.check(/* @__PURE__ */ Pu(Up,e))},cidrv6(e){return this.check(/* @__PURE__ */ Fu(Wp,e))},e164(e){return this.check(/* @__PURE__ */ Ru(qp,e))},datetime(e){return this.check(/* @__PURE__ */ Bu(Ep,e))},date(e){return this.check(/* @__PURE__ */ Vu(Dp,e))},time(e){return this.check(/* @__PURE__ */ Hu(Op,e))},duration(e){return this.check(/* @__PURE__ */ Uu(kp,e))}});function V(e){return/* @__PURE__ */ _u(wp,e)}const Tp=/*@__PURE__*/ B(`ZodStringFormat`,(e,t)=>{bc.init(e,t),Cp.init(e,t)}),Ep=/*@__PURE__*/ B(`ZodISODateTime`,(e,t)=>{zc.init(e,t),Tp.init(e,t)}),Dp=/*@__PURE__*/ B(`ZodISODate`,(e,t)=>{Bc.init(e,t),Tp.init(e,t)}),Op=/*@__PURE__*/ B(`ZodISOTime`,(e,t)=>{Vc.init(e,t),Tp.init(e,t)}),kp=/*@__PURE__*/ B(`ZodISODuration`,(e,t)=>{Hc.init(e,t),Tp.init(e,t)}),Ap=/*@__PURE__*/ B(`ZodEmail`,(e,t)=>{Cc.init(e,t),Tp.init(e,t)}),jp=/*@__PURE__*/ B(`ZodGUID`,(e,t)=>{xc.init(e,t),Tp.init(e,t)}),Mp=/*@__PURE__*/ B(`ZodUUID`,(e,t)=>{Sc.init(e,t),Tp.init(e,t)}),Np=/*@__PURE__*/ B(`ZodURL`,(e,t)=>{jc.init(e,t),Tp.init(e,t)}),Pp=/*@__PURE__*/ B(`ZodEmoji`,(e,t)=>{Mc.init(e,t),Tp.init(e,t)}),Fp=/*@__PURE__*/ B(`ZodNanoID`,(e,t)=>{Nc.init(e,t),Tp.init(e,t)}),Ip=/*@__PURE__*/ B(`ZodCUID`,(e,t)=>{Pc.init(e,t),Tp.init(e,t)}),Lp=/*@__PURE__*/ B(`ZodCUID2`,(e,t)=>{Fc.init(e,t),Tp.init(e,t)}),Rp=/*@__PURE__*/ B(`ZodULID`,(e,t)=>{Ic.init(e,t),Tp.init(e,t)}),zp=/*@__PURE__*/ B(`ZodXID`,(e,t)=>{Lc.init(e,t),Tp.init(e,t)}),Bp=/*@__PURE__*/ B(`ZodKSUID`,(e,t)=>{Rc.init(e,t),Tp.init(e,t)}),Vp=/*@__PURE__*/ B(`ZodIPv4`,(e,t)=>{Uc.init(e,t),Tp.init(e,t)}),Hp=/*@__PURE__*/ B(`ZodIPv6`,(e,t)=>{Kc.init(e,t),Tp.init(e,t)}),Up=/*@__PURE__*/ B(`ZodCIDRv4`,(e,t)=>{qc.init(e,t),Tp.init(e,t)}),Wp=/*@__PURE__*/ B(`ZodCIDRv6`,(e,t)=>{Yc.init(e,t),Tp.init(e,t)}),Gp=/*@__PURE__*/ B(`ZodBase64`,(e,t)=>{Qc.init(e,t),Tp.init(e,t)}),Kp=/*@__PURE__*/ B(`ZodBase64URL`,(e,t)=>{tl.init(e,t),Tp.init(e,t)}),qp=/*@__PURE__*/ B(`ZodE164`,(e,t)=>{nl.init(e,t),Tp.init(e,t)}),Jp=/*@__PURE__*/ B(`ZodJWT`,(e,t)=>{il.init(e,t),Tp.init(e,t)}),Yp=/*@__PURE__*/ B(`ZodNumber`,(e,t)=>{al.init(e,t),Sp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>$d(e,t,n,r),e.isFinite=!0},/*@__PURE__*/ bo({minValue:e=>{let{minimum:t,exclusiveMinimum:n}=Jd(e);return Math.max(t??-1/0,n??-1/0)},maxValue:e=>{let{maximum:t,exclusiveMaximum:n}=Jd(e);return Math.min(t??1/0,n??1/0)},isInt:e=>{let{isInt:t,multipleOf:n}=Jd(e);return!!t||!!n?.some(Number.isSafeInteger)},format:e=>Jd(e).format??null},{gt(e,t){return this.check(/* @__PURE__ */ Qu(e,t))},gte(e,t){return this.check(/* @__PURE__ */ $u(e,t))},min(e,t){return this.check(/* @__PURE__ */ $u(e,t))},lt(e,t){return this.check(/* @__PURE__ */ Xu(e,t))},lte(e,t){return this.check(/* @__PURE__ */ Zu(e,t))},max(e,t){return this.check(/* @__PURE__ */ Zu(e,t))},int(e){return this.check(Zp(e))},safe(e){return this.check(Zp(e))},positive(e){return this.check(/* @__PURE__ */ Qu(0,e))},nonnegative(e){return this.check(/* @__PURE__ */ $u(0,e))},negative(e){return this.check(/* @__PURE__ */ Xu(0,e))},nonpositive(e){return this.check(/* @__PURE__ */ Zu(0,e))},multipleOf(e,t){return this.check(/* @__PURE__ */ ed(e,t))},step(e,t){return this.check(/* @__PURE__ */ ed(e,t))},finite(){return this}}));function H(e){return/* @__PURE__ */ Wu(Yp,e)}const Xp=/*@__PURE__*/ B(`ZodNumberFormat`,(e,t)=>{ol.init(e,t),Yp.init(e,t)});function Zp(e){return/* @__PURE__ */ Gu(Xp,e)}const Qp=/*@__PURE__*/ B(`ZodBoolean`,(e,t)=>{sl.init(e,t),Sp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ef(e,t,n,r)});function $p(e){return/* @__PURE__ */ Ku(Qp,e)}const em=/*@__PURE__*/ B(`ZodNull`,(e,t)=>{cl.init(e,t),Sp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>rf(e,t,n,r)});function tm(e){return/* @__PURE__ */ qu(em,e)}const nm=/*@__PURE__*/ B(`ZodUnknown`,(e,t)=>{ll.init(e,t),Sp.init(e,t),e._zod.processJSONSchema=(e,t,n)=>void 0});function rm(){return/* @__PURE__ */ Ju(nm)}const im=/*@__PURE__*/ B(`ZodNever`,(e,t)=>{ul.init(e,t),Sp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>sf(e,t,n,r)});function am(e){return/* @__PURE__ */ Yu(im,e)}const om=/*@__PURE__*/ B(`ZodArray`,(e,t)=>{xp(),ml.init(e,t),Sp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Sf(e,t,n,r),e.element=t.element},{min(e,t){return this.check(/* @__PURE__ */ nd(e,t))},nonempty(e){return this.check(/* @__PURE__ */ nd(1,e))},max(e,t){return this.check(/* @__PURE__ */ td(e,t))},length(e,t){return this.check(/* @__PURE__ */ rd(e,t))},unwrap(){return this.element}});function U(e,t){return/* @__PURE__ */ gd(om,e,t)}const sm=/*@__PURE__*/ B(`ZodObject`,(e,t)=>{xp(),bl.init(e,t),Sp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>wf(e,t,n,r),Eo(e,`shape`,e=>e._zod.def.shape,!1)},{keyof(){return vm(Object.keys(this._zod.def.shape))},catchall(e){return this.clone(Pa(this._zod.def,{catchall:e}))},passthrough(){return this.clone(Pa(this._zod.def,{catchall:rm()}))},loose(){return this.clone(Pa(this._zod.def,{catchall:rm()}))},strict(){return this.clone(Pa(this._zod.def,{catchall:am()}))},strip(){return this.clone(Pa(this._zod.def,{catchall:void 0}))},extend(e){return Qa(this,e)},safeExtend(e){return eo(this,e)},merge(e){return to(this,e)},pick(e){return Ya(this,e)},omit(e){return Za(this,e)},partial(...e){return no(Sm,this,e[0])},exactPartial(...e){return no(wm,this,e[0],`exactPartial`)},required(...e){return ro(Mm,this,e[0])}});function W(e,t){let n={type:`object`,shape:e??{},...R(t)};return new sm(n)}function cm(e,t){return new sm({type:`object`,shape:e,catchall:rm(),...R(t)})}const lm=/*@__PURE__*/ B(`ZodUnion`,(e,t)=>{Sl.init(e,t),Sp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Tf(e,t,n,r),e.options=t.options});function um(e,t){return new lm({type:`union`,options:e,...R(t)})}const dm=/*@__PURE__*/ B(`ZodDiscriminatedUnion`,(e,t)=>{lm.init(e,t),wl.init(e,t)});function fm(e,t,n){return new dm({type:`union`,options:t,discriminator:e,...R(n)})}const pm=/*@__PURE__*/ B(`ZodIntersection`,(e,t)=>{Tl.init(e,t),Sp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Ef(e,t,n,r)});function mm(e,t){return new pm({type:`intersection`,left:e,right:t})}const hm=/*@__PURE__*/ B(`ZodRecord`,(e,t)=>{xp(),Ol.init(e,t),Sp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>jf(e,t,n,r),e.keyType=t.keyType,e.valueType=t.valueType});function gm(e,t,n){return!t||!t._zod?new hm({type:`record`,keyType:V(),valueType:e,...R(t)}):new hm({type:`record`,keyType:e,valueType:t,...R(n)})}const _m=/*@__PURE__*/ B(`ZodEnum`,(e,t)=>{kl.init(e,t),Sp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>df(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 _m({...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 _m({...t,checks:[],...R(r),entries:i})}});function vm(e,t){let n=Array.isArray(e)?Object.fromEntries(e.map(e=>[e,e])):e;return new _m({type:`enum`,entries:n,...R(t)})}const ym=/*@__PURE__*/ B(`ZodLiteral`,(e,t)=>{Al.init(e,t),Sp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>ff(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 ym({type:`literal`,values:Array.isArray(e)?e:[e],...R(t)})}const bm=/*@__PURE__*/ B(`ZodTransform`,(e,t)=>{xp(),jl.init(e,t),Sp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>yf(e,t,n,r),e._zod.parse=(n,r)=>{if(r.direction===`backward`)throw new No(e.constructor.name);n.addIssue=r=>{if(typeof r==`string`)n.issues.push(go(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(go(t))}};let i=t.transform(n.value,n);return i instanceof Promise?i.then(e=>(n.value=e,n)):(n.value=i,n)}});function xm(e){return new bm({type:`transform`,transform:e})}const Sm=/*@__PURE__*/ B(`ZodOptional`,(e,t)=>{Nl.init(e,t),Sp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Hf(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Cm(e){return new Sm({type:`optional`,innerType:e})}const wm=/*@__PURE__*/ B(`ZodExactOptional`,(e,t)=>{Pl.init(e,t),Sp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Hf(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Tm(e){return new wm({type:`optional`,innerType:e})}const Em=/*@__PURE__*/ B(`ZodNullable`,(e,t)=>{Fl.init(e,t),Sp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Mf(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Dm(e){return new Em({type:`nullable`,innerType:e})}const Om=/*@__PURE__*/ B(`ZodDefault`,(e,t)=>{Il.init(e,t),Sp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>If(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeDefault=e.unwrap});function km(e,t){return new Om({type:`default`,innerType:e,get defaultValue(){return typeof t==`function`?t():Va(t)}})}const Am=/*@__PURE__*/ B(`ZodPrefault`,(e,t)=>{Rl.init(e,t),Sp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Lf(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function jm(e,t){return new Am({type:`prefault`,innerType:e,get defaultValue(){return typeof t==`function`?t():Va(t)}})}const Mm=/*@__PURE__*/ B(`ZodNonOptional`,(e,t)=>{zl.init(e,t),Sp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Nf(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Nm(e,t){return new Mm({type:`nonoptional`,innerType:e,...R(t)})}const Pm=/*@__PURE__*/ B(`ZodCatch`,(e,t)=>{Hl.init(e,t),Sp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Rf(e,t,n,r),e.unwrap=()=>e._zod.def.innerType,e.removeCatch=e.unwrap});function Fm(e,t){return new Pm({type:`catch`,innerType:e,catchValue:typeof t==`function`?t:Do(t)})}const Im=/*@__PURE__*/ B(`ZodPipe`,(e,t)=>{Ul.init(e,t),Sp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>zf(e,t,n,r),e.in=t.in,e.out=t.out});function Lm(e,t){return new Im({type:`pipe`,in:e,out:t})}const Rm=/*@__PURE__*/ B(`ZodPreprocess`,(e,t)=>{Im.init(e,t),Gl.init(e,t)}),zm=/*@__PURE__*/ B(`ZodReadonly`,(e,t)=>{Kl.init(e,t),Sp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>Bf(e,t,n,r),e.unwrap=()=>e._zod.def.innerType});function Bm(e){return new zm({type:`readonly`,innerType:e})}const Vm=/*@__PURE__*/ B(`ZodCustom`,(e,t)=>{Jl.init(e,t),Sp.init(e,t),e._zod.processJSONSchema=(t,n,r)=>_f(e,t,n,r)});function Hm(e,t){return/* @__PURE__ */ _d(Vm,e??(()=>!0),t)}function Um(e,t={}){return/* @__PURE__ */ vd(Vm,e,t)}function Wm(e,t){return/* @__PURE__ */ yd(e,t)}function Gm(e,t){return new Rm({type:`pipe`,in:xm(e),out:t})}function Km(e){return/* @__PURE__ */ Bu(Ep,e)}const qm=`2025-11-25`,Jm=[qm,`2025-06-18`,`2025-03-26`,`2024-11-05`,`2024-10-07`],Ym=`io.modelcontextprotocol/related-task`,Xm=Hm(e=>e!==null&&(typeof e==`object`||typeof e==`function`)),Zm=um([V(),H().int()]),Qm=V();cm({ttl:H().optional(),pollInterval:H().optional()});const $m=W({ttl:H().optional()}),eh=W({taskId:V()}),th=cm({progressToken:Zm.optional(),[Ym]:eh.optional()}),nh=W({_meta:th.optional()}),rh=nh.extend({task:$m.optional()}),ih=e=>rh.safeParse(e).success,ah=W({method:V(),params:nh.loose().optional()}),oh=W({_meta:th.optional()}),sh=W({method:V(),params:oh.loose().optional()}),ch=cm({_meta:th.optional()}),lh=um([V(),H().int()]),uh=W({jsonrpc:G(`2.0`),id:lh,...ah.shape}).strict(),dh=e=>uh.safeParse(e).success,fh=W({jsonrpc:G(`2.0`),...sh.shape}).strict(),ph=e=>fh.safeParse(e).success,mh=W({jsonrpc:G(`2.0`),id:lh,result:ch}).strict(),hh=e=>mh.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 gh=W({jsonrpc:G(`2.0`),id:lh.optional(),error:W({code:H().int(),message:V(),data:rm().optional()})}).strict(),_h=e=>gh.safeParse(e).success,vh=um([uh,fh,mh,gh]);um([mh,gh]);const yh=ch.strict(),bh=oh.extend({requestId:lh.optional(),reason:V().optional()}),xh=sh.extend({method:G(`notifications/cancelled`),params:bh}),Sh=W({icons:U(W({src:V(),mimeType:V().optional(),sizes:U(V()).optional(),theme:vm([`light`,`dark`]).optional()})).optional()}),Ch=W({name:V(),title:V().optional()}),wh=Ch.extend({...Ch.shape,...Sh.shape,version:V(),websiteUrl:V().optional(),description:V().optional()}),Th=Gm(e=>e&&typeof e==`object`&&!Array.isArray(e)&&Object.keys(e).length===0?{form:{}}:e,mm(W({form:mm(W({applyDefaults:$p().optional()}),gm(V(),rm())).optional(),url:Xm.optional()}),gm(V(),rm()).optional())),Eh=cm({list:Xm.optional(),cancel:Xm.optional(),requests:cm({sampling:cm({createMessage:Xm.optional()}).optional(),elicitation:cm({create:Xm.optional()}).optional()}).optional()}),Dh=cm({list:Xm.optional(),cancel:Xm.optional(),requests:cm({tools:cm({call:Xm.optional()}).optional()}).optional()}),Oh=W({experimental:gm(V(),Xm).optional(),sampling:W({context:Xm.optional(),tools:Xm.optional()}).optional(),elicitation:Th.optional(),roots:W({listChanged:$p().optional()}).optional(),tasks:Eh.optional(),extensions:gm(V(),Xm).optional()}),kh=nh.extend({protocolVersion:V(),capabilities:Oh,clientInfo:wh}),Ah=ah.extend({method:G(`initialize`),params:kh}),jh=W({experimental:gm(V(),Xm).optional(),logging:Xm.optional(),completions:Xm.optional(),prompts:W({listChanged:$p().optional()}).optional(),resources:W({subscribe:$p().optional(),listChanged:$p().optional()}).optional(),tools:W({listChanged:$p().optional()}).optional(),tasks:Dh.optional(),extensions:gm(V(),Xm).optional()}),Mh=ch.extend({protocolVersion:V(),capabilities:jh,serverInfo:wh,instructions:V().optional()}),Nh=sh.extend({method:G(`notifications/initialized`),params:oh.optional()}),Ph=ah.extend({method:G(`ping`),params:nh.optional()}),Fh=W({progress:H(),total:Cm(H()),message:Cm(V())}),Ih=W({...oh.shape,...Fh.shape,progressToken:Zm}),Lh=sh.extend({method:G(`notifications/progress`),params:Ih}),Rh=nh.extend({cursor:Qm.optional()}),zh=ah.extend({params:Rh.optional()}),Bh=ch.extend({nextCursor:Qm.optional()}),Vh=vm([`working`,`input_required`,`completed`,`failed`,`cancelled`]),Hh=W({taskId:V(),status:Vh,ttl:um([H(),tm()]),createdAt:V(),lastUpdatedAt:V(),pollInterval:Cm(H()),statusMessage:Cm(V())}),Uh=ch.extend({task:Hh}),Wh=oh.merge(Hh),Gh=sh.extend({method:G(`notifications/tasks/status`),params:Wh}),Kh=ah.extend({method:G(`tasks/get`),params:nh.extend({taskId:V()})}),qh=ch.merge(Hh),Jh=ah.extend({method:G(`tasks/result`),params:nh.extend({taskId:V()})});ch.loose();const Yh=zh.extend({method:G(`tasks/list`)}),Xh=Bh.extend({tasks:U(Hh)}),Zh=ah.extend({method:G(`tasks/cancel`),params:nh.extend({taskId:V()})}),Qh=ch.merge(Hh),$h=W({uri:V(),mimeType:Cm(V()),_meta:gm(V(),rm()).optional()}),eg=$h.extend({text:V()}),tg=V().refine(e=>{try{return atob(e),!0}catch{return!1}},{message:`Invalid Base64 string`}),ng=$h.extend({blob:tg}),rg=vm([`user`,`assistant`]),ig=W({audience:U(rg).optional(),priority:H().min(0).max(1).optional(),lastModified:Km({offset:!0}).optional()}),ag=W({...Ch.shape,...Sh.shape,uri:V(),description:Cm(V()),mimeType:Cm(V()),size:Cm(H()),annotations:ig.optional(),_meta:Cm(cm({}))}),og=W({...Ch.shape,...Sh.shape,uriTemplate:V(),description:Cm(V()),mimeType:Cm(V()),annotations:ig.optional(),_meta:Cm(cm({}))}),sg=zh.extend({method:G(`resources/list`)}),cg=Bh.extend({resources:U(ag)}),lg=zh.extend({method:G(`resources/templates/list`)}),ug=Bh.extend({resourceTemplates:U(og)}),dg=nh.extend({uri:V()}),fg=dg,pg=ah.extend({method:G(`resources/read`),params:fg}),mg=ch.extend({contents:U(um([eg,ng]))}),hg=sh.extend({method:G(`notifications/resources/list_changed`),params:oh.optional()}),gg=dg,_g=ah.extend({method:G(`resources/subscribe`),params:gg}),vg=dg,yg=ah.extend({method:G(`resources/unsubscribe`),params:vg}),bg=oh.extend({uri:V()}),xg=sh.extend({method:G(`notifications/resources/updated`),params:bg}),Sg=W({name:V(),description:Cm(V()),required:Cm($p())}),Cg=W({...Ch.shape,...Sh.shape,description:Cm(V()),arguments:Cm(U(Sg)),_meta:Cm(cm({}))}),wg=zh.extend({method:G(`prompts/list`)}),Tg=Bh.extend({prompts:U(Cg)}),Eg=nh.extend({name:V(),arguments:gm(V(),V()).optional()}),Dg=ah.extend({method:G(`prompts/get`),params:Eg}),Og=W({type:G(`text`),text:V(),annotations:ig.optional(),_meta:gm(V(),rm()).optional()}),kg=W({type:G(`image`),data:tg,mimeType:V(),annotations:ig.optional(),_meta:gm(V(),rm()).optional()}),Ag=W({type:G(`audio`),data:tg,mimeType:V(),annotations:ig.optional(),_meta:gm(V(),rm()).optional()}),jg=W({type:G(`tool_use`),name:V(),id:V(),input:gm(V(),rm()),_meta:gm(V(),rm()).optional()}),Mg=W({type:G(`resource`),resource:um([eg,ng]),annotations:ig.optional(),_meta:gm(V(),rm()).optional()}),Ng=um([Og,kg,Ag,ag.extend({type:G(`resource_link`)}),Mg]),Pg=W({role:rg,content:Ng}),Fg=ch.extend({description:V().optional(),messages:U(Pg)}),Ig=sh.extend({method:G(`notifications/prompts/list_changed`),params:oh.optional()}),Lg=W({title:V().optional(),readOnlyHint:$p().optional(),destructiveHint:$p().optional(),idempotentHint:$p().optional(),openWorldHint:$p().optional()}),Rg=W({taskSupport:vm([`required`,`optional`,`forbidden`]).optional()}),zg=W({...Ch.shape,...Sh.shape,description:V().optional(),inputSchema:W({type:G(`object`),properties:gm(V(),Xm).optional(),required:U(V()).optional()}).catchall(rm()),outputSchema:W({type:G(`object`),properties:gm(V(),Xm).optional(),required:U(V()).optional()}).catchall(rm()).optional(),annotations:Lg.optional(),execution:Rg.optional(),_meta:gm(V(),rm()).optional()}),Bg=zh.extend({method:G(`tools/list`)}),Vg=Bh.extend({tools:U(zg)}),Hg=ch.extend({content:U(Ng).default([]),structuredContent:gm(V(),rm()).optional(),isError:$p().optional()});Hg.or(ch.extend({toolResult:rm()}));const Ug=rh.extend({name:V(),arguments:gm(V(),rm()).optional()}),Wg=ah.extend({method:G(`tools/call`),params:Ug}),Gg=sh.extend({method:G(`notifications/tools/list_changed`),params:oh.optional()});W({autoRefresh:$p().default(!0),debounceMs:H().int().nonnegative().default(300)});const Kg=vm([`debug`,`info`,`notice`,`warning`,`error`,`critical`,`alert`,`emergency`]),qg=nh.extend({level:Kg}),Jg=ah.extend({method:G(`logging/setLevel`),params:qg}),Yg=oh.extend({level:Kg,logger:V().optional(),data:rm()}),Xg=sh.extend({method:G(`notifications/message`),params:Yg}),Zg=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()}),Qg=W({mode:vm([`auto`,`required`,`none`]).optional()}),$g=W({type:G(`tool_result`),toolUseId:V().describe(`The unique identifier for the corresponding tool call.`),content:U(Ng).default([]),structuredContent:W({}).loose().optional(),isError:$p().optional(),_meta:gm(V(),rm()).optional()}),e_=fm(`type`,[Og,kg,Ag]),t_=fm(`type`,[Og,kg,Ag,jg,$g]),n_=W({role:rg,content:um([t_,U(t_)]),_meta:gm(V(),rm()).optional()}),r_=rh.extend({messages:U(n_),modelPreferences:Zg.optional(),systemPrompt:V().optional(),includeContext:vm([`none`,`thisServer`,`allServers`]).optional(),temperature:H().optional(),maxTokens:H().int(),stopSequences:U(V()).optional(),metadata:Xm.optional(),tools:U(zg).optional(),toolChoice:Qg.optional()}),i_=ah.extend({method:G(`sampling/createMessage`),params:r_}),a_=ch.extend({model:V(),stopReason:Cm(vm([`endTurn`,`stopSequence`,`maxTokens`]).or(V())),role:rg,content:e_}),o_=ch.extend({model:V(),stopReason:Cm(vm([`endTurn`,`stopSequence`,`maxTokens`,`toolUse`]).or(V())),role:rg,content:um([t_,U(t_)])}),s_=W({type:G(`boolean`),title:V().optional(),description:V().optional(),default:$p().optional()}),c_=W({type:G(`string`),title:V().optional(),description:V().optional(),minLength:H().optional(),maxLength:H().optional(),format:vm([`email`,`uri`,`date`,`date-time`]).optional(),default:V().optional()}),l_=W({type:vm([`number`,`integer`]),title:V().optional(),description:V().optional(),minimum:H().optional(),maximum:H().optional(),default:H().optional()}),u_=W({type:G(`string`),title:V().optional(),description:V().optional(),enum:U(V()),default:V().optional()}),d_=W({type:G(`string`),title:V().optional(),description:V().optional(),oneOf:U(W({const:V(),title:V()})),default:V().optional()}),f_=um([um([W({type:G(`string`),title:V().optional(),description:V().optional(),enum:U(V()),enumNames:U(V()).optional(),default:V().optional()}),um([u_,d_]),um([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()})])]),s_,c_,l_]),p_=um([rh.extend({mode:G(`form`).optional(),message:V(),requestedSchema:W({type:G(`object`),properties:gm(V(),f_),required:U(V()).optional()})}),rh.extend({mode:G(`url`),message:V(),elicitationId:V(),url:V().url()})]),m_=ah.extend({method:G(`elicitation/create`),params:p_}),h_=oh.extend({elicitationId:V()}),g_=sh.extend({method:G(`notifications/elicitation/complete`),params:h_}),__=ch.extend({action:vm([`accept`,`decline`,`cancel`]),content:Gm(e=>e===null?void 0:e,gm(V(),um([V(),H(),$p(),U(V())])).optional())}),v_=W({type:G(`ref/resource`),uri:V()}),y_=W({type:G(`ref/prompt`),name:V()}),b_=nh.extend({ref:um([y_,v_]),argument:W({name:V(),value:V()}),context:W({arguments:gm(V(),V()).optional()}).optional()}),x_=ah.extend({method:G(`completion/complete`),params:b_});function S_(e){if(e.params.ref.type!==`ref/prompt`)throw TypeError(`Expected CompleteRequestPrompt, but got ${e.params.ref.type}`)}function C_(e){if(e.params.ref.type!==`ref/resource`)throw TypeError(`Expected CompleteRequestResourceTemplate, but got ${e.params.ref.type}`)}const w_=ch.extend({completion:cm({values:U(V()).max(100),total:Cm(H().int()),hasMore:Cm($p())})}),T_=W({uri:V().startsWith(`file://`),name:V().optional(),_meta:gm(V(),rm()).optional()}),E_=ah.extend({method:G(`roots/list`),params:nh.optional()}),D_=ch.extend({roots:U(T_)}),O_=sh.extend({method:G(`notifications/roots/list_changed`),params:oh.optional()});um([Ph,Ah,x_,Jg,Dg,wg,sg,lg,pg,_g,yg,Wg,Bg,Kh,Jh,Yh,Zh]),um([xh,Lh,Nh,O_,Gh]),um([yh,a_,o_,__,D_,qh,Xh,Uh]),um([Ph,i_,m_,E_,Kh,Jh,Yh,Zh]),um([xh,Lh,Xg,xg,hg,Gg,Ig,Gh,g_]),um([yh,Mh,w_,Fg,Tg,cg,ug,mg,Hg,Vg,qh,Xh,Uh]);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 k_(e.elicitations,n)}return new e(t,n,r)}},k_=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 A_(e){return e===`completed`||e===`failed`||e===`cancelled`}const j_=Symbol(`Let zodToJsonSchema decide on which parser to use`),M_={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`},N_=e=>typeof e==`string`?{...M_,name:e}:{...M_,...e},P_=e=>{let t=N_(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 F_(e,t,n,r){r?.errorMessages&&n&&(e.errorMessage={...e.errorMessage,[t]:n})}function I_(e,t,n,r,i){e[t]=n,F_(e,t,r,i)}const L_=(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 R_(e){if(e.target!==`openAi`)return{};let t=[...e.basePath,e.definitionPath,e.openAiAnyTypeName];return e.flags.hasReferencedOpenAiAnyType=!0,{$ref:e.$refStrategy===`relative`?L_(t,e.currentPath):t.join(`/`)}}function z_(e,t){let n={type:`array`};return e.type?._def&&e.type?._def?.typeName!==L.ZodAny&&(n.items=J(e.type._def,{...t,currentPath:[...t.currentPath,`items`]})),e.minLength&&I_(n,`minItems`,e.minLength.value,e.minLength.message,t),e.maxLength&&I_(n,`maxItems`,e.maxLength.value,e.maxLength.message,t),e.exactLength&&(I_(n,`minItems`,e.exactLength.value,e.exactLength.message,t),I_(n,`maxItems`,e.exactLength.value,e.exactLength.message,t)),n}function B_(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?I_(n,`minimum`,r.value,r.message,t):I_(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),I_(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?I_(n,`maximum`,r.value,r.message,t):I_(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),I_(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:I_(n,`multipleOf`,r.value,r.message,t)}return n}function V_(){return{type:`boolean`}}function H_(e,t){return J(e.type._def,t)}const U_=(e,t)=>J(e.innerType._def,t);function W_(e,t,n){let r=n??t.dateStrategy;if(Array.isArray(r))return{anyOf:r.map((n,r)=>W_(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 G_(e,t)}}const G_=(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`:I_(n,`minimum`,r.value,r.message,t);break;case`max`:I_(n,`maximum`,r.value,r.message,t)}return n};function K_(e,t){return{...J(e.innerType._def,t),default:e.defaultValue()}}function q_(e,t){return t.effectStrategy===`input`?J(e.schema._def,t):R_(t)}function J_(e){return{type:`string`,enum:Array.from(e.values)}}const Y_=e=>`type`in e&&e.type===`string`?!1:`allOf`in e;function X_(e,t){let n=[J(e.left._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]}),J(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(Y_(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 Z_(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 Q_;const $_={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:()=>(Q_===void 0&&(Q_=RegExp(`^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$`,`u`)),Q_),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 ev(e,t){let n={type:`string`};if(e.checks)for(let r of e.checks)switch(r.kind){case`min`:I_(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t);break;case`max`:I_(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`:iv(n,`email`,r.message,t);break;case`format:idn-email`:iv(n,`idn-email`,r.message,t);break;case`pattern:zod`:av(n,$_.email,r.message,t)}break;case`url`:iv(n,`uri`,r.message,t);break;case`uuid`:iv(n,`uuid`,r.message,t);break;case`regex`:av(n,r.regex,r.message,t);break;case`cuid`:av(n,$_.cuid,r.message,t);break;case`cuid2`:av(n,$_.cuid2,r.message,t);break;case`startsWith`:av(n,RegExp(`^${tv(r.value,t)}`),r.message,t);break;case`endsWith`:av(n,RegExp(`${tv(r.value,t)}$`),r.message,t);break;case`datetime`:iv(n,`date-time`,r.message,t);break;case`date`:iv(n,`date`,r.message,t);break;case`time`:iv(n,`time`,r.message,t);break;case`duration`:iv(n,`duration`,r.message,t);break;case`length`:I_(n,`minLength`,typeof n.minLength==`number`?Math.max(n.minLength,r.value):r.value,r.message,t),I_(n,`maxLength`,typeof n.maxLength==`number`?Math.min(n.maxLength,r.value):r.value,r.message,t);break;case`includes`:av(n,RegExp(tv(r.value,t)),r.message,t);break;case`ip`:r.version!==`v6`&&iv(n,`ipv4`,r.message,t),r.version!==`v4`&&iv(n,`ipv6`,r.message,t);break;case`base64url`:av(n,$_.base64url,r.message,t);break;case`jwt`:av(n,$_.jwt,r.message,t);break;case`cidr`:r.version!==`v6`&&av(n,$_.ipv4Cidr,r.message,t),r.version!==`v4`&&av(n,$_.ipv6Cidr,r.message,t);break;case`emoji`:av(n,$_.emoji(),r.message,t);break;case`ulid`:av(n,$_.ulid,r.message,t);break;case`base64`:switch(t.base64Strategy){case`format:binary`:iv(n,`binary`,r.message,t);break;case`contentEncoding:base64`:I_(n,`contentEncoding`,`base64`,r.message,t);break;case`pattern:zod`:av(n,$_.base64,r.message,t)}break;case`nanoid`:av(n,$_.nanoid,r.message,t)}return n}function tv(e,t){return t.patternStrategy===`escape`?rv(e):e}const nv=/* @__PURE__ */ new Set(`ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789`);function rv(e){let t=``;for(let n=0;n<e.length;n++)nv.has(e[n])||(t+=`\\`),t+=e[n];return t}function iv(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}}})):I_(e,`format`,t,n,r)}function av(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:ov(t,r),...n&&r.errorMessages&&{errorMessage:{pattern:n}}})):I_(e,`pattern`,ov(t,r),n,r)}function ov(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
|
|
132
132
|
]))`;continue}if(r[e]===`$`){i+=`($|(?=[\r
|
|
133
|
-
]))`;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 sv(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===I.ZodEnum)return{type:`object`,required:e.keyType._def.values,properties:e.keyType._def.values.reduce((n,r)=>({...n,[r]:J(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??R_(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:J(e.valueType._def,{...t,currentPath:[...t.currentPath,`additionalProperties`]})??t.allowedAdditionalProperties};if(t.target===`openApi3`)return n;if(e.keyType?._def.typeName===I.ZodString&&e.keyType._def.checks?.length){let{type:r,...i}=ev(e.keyType._def,t);return{...n,propertyNames:i}}if(e.keyType?._def.typeName===I.ZodEnum)return{...n,propertyNames:{enum:e.keyType._def.values}};if(e.keyType?._def.typeName===I.ZodBranded&&e.keyType._def.type._def.typeName===I.ZodString&&e.keyType._def.type._def.checks?.length){let{type:r,...i}=H_(e.keyType._def,t);return{...n,propertyNames:i}}return n}function cv(e,t){return t.mapStrategy===`record`?sv(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[J(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||R_(t),J(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||R_(t)],minItems:2,maxItems:2}}}function lv(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 uv(e){return e.target===`openAi`?void 0:{not:R_({...e,currentPath:[...e.currentPath,`not`]})}}function dv(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}const fv={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function pv(e,t){if(t.target===`openApi3`)return mv(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in fv&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=fv[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 mv(e,t)}const mv=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>J(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 hv(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:fv[e.innerType._def.typeName],nullable:!0}:{type:[fv[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=J(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=J(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function gv(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`,I_(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?q(n,`minimum`,r.value,r.message,t):q(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),q(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?q(n,`maximum`,r.value,r.message,t):q(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),q(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:q(n,`multipleOf`,r.value,r.message,t)}return n}function _v(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=yv(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=J(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=vv(e,t);return o!==void 0&&(r.additionalProperties=o),r}function vv(e,t){if(e.catchall._def.typeName!==`ZodNever`)return J(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 yv(e){try{return e.isOptional()}catch{return!0}}const bv=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return J(e.innerType._def,t);let n=J(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:R_(t)},n]}:R_(t)},xv=(e,t)=>{if(t.pipeStrategy===`input`)return J(e.in._def,t);if(t.pipeStrategy===`output`)return J(e.out._def,t);let n=J(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,J(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function Sv(e,t){return J(e.type._def,t)}function Cv(e,t){let n={type:`array`,uniqueItems:!0,items:J(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&q(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&q(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function wv(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>J(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:J(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>J(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function Tv(e){return{not:R_(e)}}function Ev(e){return R_(e)}const Dv=(e,t)=>J(e.innerType._def,t),Ov=(e,t,n)=>{switch(t){case I.ZodString:return ev(e,n);case I.ZodNumber:return gv(e,n);case I.ZodObject:return _v(e,n);case I.ZodBigInt:return B_(e,n);case I.ZodBoolean:return V_();case I.ZodDate:return W_(e,n);case I.ZodUndefined:return Tv(n);case I.ZodNull:return dv(n);case I.ZodArray:return z_(e,n);case I.ZodUnion:case I.ZodDiscriminatedUnion:return pv(e,n);case I.ZodIntersection:return X_(e,n);case I.ZodTuple:return wv(e,n);case I.ZodRecord:return sv(e,n);case I.ZodLiteral:return Z_(e,n);case I.ZodEnum:return J_(e);case I.ZodNativeEnum:return lv(e);case I.ZodNullable:return hv(e,n);case I.ZodOptional:return bv(e,n);case I.ZodMap:return cv(e,n);case I.ZodSet:return Cv(e,n);case I.ZodLazy:return()=>e.getter()._def;case I.ZodPromise:return Sv(e,n);case I.ZodNaN:case I.ZodNever:return uv(n);case I.ZodEffects:return q_(e,n);case I.ZodAny:return R_(n);case I.ZodUnknown:return Ev(n);case I.ZodDefault:return K_(e,n);case I.ZodBranded:return H_(e,n);case I.ZodReadonly:return Dv(e,n);case I.ZodCatch:return U_(e,n);case I.ZodPipeline:return xv(e,n);case I.ZodFunction:case I.ZodVoid:case I.ZodSymbol:return;default:return(e=>void 0)(t)}};function J(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==M_)return i}if(r&&!n){let e=kv(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=Ov(e,e.typeName,t),o=typeof a==`function`?J(a(),t):a;if(o&&Av(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}const kv=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:L_(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`),R_(t)):t.$refStrategy===`seen`?R_(t):void 0}},Av=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),jv=(e,t)=>{let n=F_(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:J(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??R_(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=J(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??R_(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 Mv(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function Nv(e,t){return Yf(e)?Gf(e,{target:Mv(t?.target),io:t?.pipeStrategy??`input`}):jv(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function Pv(e){let t=$f(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=ap(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function Fv(e,t){let n=Zf(e,t);if(!n.success)throw n.error;return n.data}var Iv=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(Sh,e=>{this._oncancel(e)}),this.setNotificationHandler(Rh,e=>{this._onprogress(e)}),this.setRequestHandler(Fh,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(qh,async(e,t)=>{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new K(G.InvalidParams,`Failed to retrieve task: Task not found`);return{...n}}),this.setRequestHandler(Yh,async(e,t)=>{let n=async()=>{let r=e.params.taskId;if(!await this._taskStore.getTask(r,t.sessionId))throw new K(G.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 K(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 K(G.InvalidParams,`Task not found: ${r}`);if(!j_(i.status))return await this._waitForTaskUpdate(r,t.signal,t.sessionId),await n();if(j_(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r,t.sessionId),{...e,_meta:{...e._meta,[Xm]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(Xh,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 K(G.InvalidParams,`Failed to list tasks: ${e instanceof Error?e.message:String(e)}`)}}),this.setRequestHandler(Qh,async(e,t)=>{try{let n=await this._taskStore.getTask(e.params.taskId,t.sessionId);if(!n)throw new K(G.InvalidParams,`Task not found: ${e.params.taskId}`);if(j_(n.status))throw new K(G.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 K(G.InvalidParams,`Task not found after cancellation: ${e.params.taskId}`);return{_meta:{},...r}}catch(e){throw e instanceof K?e:new K(G.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),K.fromError(G.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),gh(e)||vh(e)?this._onresponse(e):fh(e)?this._onrequest(e,t):mh(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=K.fromError(G.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?.[Xm]?.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 K(G.InvalidParams,`Task not found: ${i}`);s=!0})()),n===void 0){let t={jsonrpc:`2.0`,id:e.id,error:{code:G.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=ah(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 K(G.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 K(G.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:G.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),gh(e)?n(e):n(new K(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(gh(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),gh(e)?r(e):r(K.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 K?e:new K(G.InternalError,String(e))}}return}let i;try{let r=await this.request(e,Wh,n);if(r.task)i=r.task.taskId,yield{type:`taskCreated`,task:r.task};else throw new K(G.InternalError,`Task creation did not return a task`);for(;;){let e=await this.getTask({taskId:i},n);if(yield{type:`taskStatus`,task:e},j_(e.status)){e.status===`completed`?yield{type:`result`,result:await this.getTaskResult({taskId:i},t,n)}:e.status===`failed`?yield{type:`error`,error:new K(G.InternalError,`Task ${i} failed`)}:e.status===`cancelled`&&(yield{type:`error`,error:new K(G.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 K?e:new K(G.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||{},[Xm]: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 K?e:new K(G.RequestTimeout,String(e)))};this._responseHandlers.set(d,e=>{if(!n?.signal?.aborted){if(e instanceof Error)return l(e);try{let n=Zf(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(K.fromError(G.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},Jh,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},Zh,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},$h,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||{},[Xm]: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||{},[Xm]: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||{},[Xm]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=Pv(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=Fv(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=Pv(e);this._notificationHandlers.set(n,n=>{let r=Fv(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`&&fh(t.message)){let n=t.message.id,r=this._requestResolvers.get(n);r?(r(new K(G.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 K(G.InvalidRequest,`Request cancelled`));return}let i=setTimeout(e,r);t.addEventListener(`abort`,()=>{clearTimeout(i),n(new K(G.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 K(G.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=Kh.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),j_(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 K(G.InvalidParams,`Task "${e}" not found - it may have been cleaned up`);if(j_(a.status))throw new K(G.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=Kh.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),j_(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function Lv(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Rv(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]=Lv(a)&&Lv(i)?{...a,...i}:i}return n}var zv=/* @__PURE__ */ E((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})),Bv=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=zv();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}}})),Y=/* @__PURE__ */ E((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=zv(),n=Bv();var r=zv();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=Bv();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&&=re(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=re(this.rhs,e,n),this}get names(){return ne(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=re(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)||(ie(e,i.names),n.splice(r,1))}return n.length>0?this:void 0}get names(){return this.nodes.reduce((e,t)=>te(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(ae(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=re(this.condition,e,t),this}get names(){let e=super.names;return ne(e,this.condition),this.else&&te(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=re(this.iteration,e,t),this}get names(){return te(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 ne(ne(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=re(this.iterable,e,t),this}get names(){return te(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&&te(e,this.catch.names),this.finally&&te(e,this.finally.names),e}},T=class extends m{constructor(e){super(),this.error=e}render(e){return`catch(${this.error})`+super.render(e)}};T.kind=`catch`;var ee=class extends m{render(e){return`finally`+super.render(e)}};ee.kind=`finally`,e.CodeGen=class{constructor(e,t={}){this._values={},this._blockStarts=[],this._constants={},this.opts={...t,_n:t.lines?`
|
|
134
|
-
`:``},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 ee,this.code(n)),this._endBlockNode(T,ee)}throw(e){return this._leafNode(new d(e))}block(e,t){return this._blockStarts.push(this._nodes.length),e&&this.code(e).endBlock(t),this}endBlock(e){let t=this._blockStarts.pop();if(t===void 0)throw Error(`CodeGen: not in self-balancing block`);let n=this._nodes.length-t;if(n<0||e!==void 0&&n!==e)throw Error(`CodeGen: wrong number of nodes: ${n} vs ${e} expected`);return this._nodes.length=t,this}func(e,n=t.nil,r,i){return this._blockNode(new S(e,n,r)),i&&this.code(i).endFunc(),this}endFunc(){return this._endBlockNode(S)}optimize(e=1){for(;e-->0;)this._root.optimizeNodes(),this._root.optimizeNames(this._root.names,this._constants)}_leafNode(e){return this._currNode.nodes.push(e),this}_blockNode(e){this._currNode.nodes.push(e),this._nodes.push(e)}_endBlockNode(e,t){let n=this._currNode;if(n instanceof e||t&&n instanceof t)return this._nodes.pop(),this;throw Error(`CodeGen: not in block "${t?`${e.kind}/${t.kind}`:e.kind}"`)}_elseNode(e){let t=this._currNode;if(!(t instanceof _))throw Error(`CodeGen: "else" without "if"`);return this._currNode=t.else=e,this}get _root(){return this._nodes[0]}get _currNode(){let e=this._nodes;return e[e.length-1]}set _currNode(e){let t=this._nodes;t[t.length-1]=e}};function te(e,t){for(let n in t)e[n]=(e[n]||0)+(t[n]||0);return e}function ne(e,n){return n instanceof t._CodeOrName?te(e,n.names):e}function re(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 ie(e,t){for(let n in t)e[n]=(e[n]||0)-(t[n]||0)}function ae(e){return typeof e==`boolean`||typeof e==`number`||e===null?!e:(0,t._)`!${ue(e)}`}e.not=ae;let oe=le(e.operators.AND);function se(...e){return e.reduce(oe)}e.and=se;let E=le(e.operators.OR);function ce(...e){return e.reduce(E)}e.or=ce;function le(e){return(n,r)=>n===t.nil?r:r===t.nil?n:(0,t._)`${ue(n)} ${e} ${ue(r)}`}function ue(e){return e instanceof t.Name?e:(0,t._)`(${e})`}})),X=/* @__PURE__ */ E((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=Y(),n=zv();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})),Vv=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Y();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`)}})),Hv=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendErrors=e.resetErrorsCount=e.reportExtraError=e.reportError=e.keyword$DataError=e.keywordError=void 0;let t=Y(),n=X(),r=Vv();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}){
|
|
133
|
+
]))`;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 sv(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]:J(e.valueType._def,{...t,currentPath:[...t.currentPath,`properties`,r]})??R_(t)}),{}),additionalProperties:t.rejectedAdditionalProperties};let n={type:`object`,additionalProperties:J(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}=ev(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}=H_(e.keyType._def,t);return{...n,propertyNames:i}}return n}function cv(e,t){return t.mapStrategy===`record`?sv(e,t):{type:`array`,maxItems:125,items:{type:`array`,items:[J(e.keyType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`0`]})||R_(t),J(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`,`items`,`1`]})||R_(t)],minItems:2,maxItems:2}}}function lv(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 uv(e){return e.target===`openAi`?void 0:{not:R_({...e,currentPath:[...e.currentPath,`not`]})}}function dv(e){return e.target===`openApi3`?{enum:[`null`],nullable:!0}:{type:`null`}}const fv={ZodString:`string`,ZodNumber:`number`,ZodBigInt:`integer`,ZodBoolean:`boolean`,ZodNull:`null`};function pv(e,t){if(t.target===`openApi3`)return mv(e,t);let n=e.options instanceof Map?Array.from(e.options.values()):e.options;if(n.every(e=>e._def.typeName in fv&&(!e._def.checks||!e._def.checks.length))){let e=n.reduce((e,t)=>{let n=fv[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 mv(e,t)}const mv=(e,t)=>{let n=(e.options instanceof Map?Array.from(e.options.values()):e.options).map((e,n)=>J(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 hv(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:fv[e.innerType._def.typeName],nullable:!0}:{type:[fv[e.innerType._def.typeName],`null`]};if(t.target===`openApi3`){let n=J(e.innerType._def,{...t,currentPath:[...t.currentPath]});return n&&`$ref`in n?{allOf:[n],nullable:!0}:n&&{...n,nullable:!0}}let n=J(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`0`]});return n&&{anyOf:[n,{type:`null`}]}}function gv(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`,F_(n,`type`,r.message,t);break;case`min`:t.target===`jsonSchema7`?r.inclusive?I_(n,`minimum`,r.value,r.message,t):I_(n,`exclusiveMinimum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMinimum=!0),I_(n,`minimum`,r.value,r.message,t));break;case`max`:t.target===`jsonSchema7`?r.inclusive?I_(n,`maximum`,r.value,r.message,t):I_(n,`exclusiveMaximum`,r.value,r.message,t):(r.inclusive||(n.exclusiveMaximum=!0),I_(n,`maximum`,r.value,r.message,t));break;case`multipleOf`:I_(n,`multipleOf`,r.value,r.message,t)}return n}function _v(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=yv(o);s&&n&&(o._def.typeName===`ZodOptional`&&(o=o._def.innerType),o.isNullable()||(o=o.nullable()),s=!1);let c=J(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=vv(e,t);return o!==void 0&&(r.additionalProperties=o),r}function vv(e,t){if(e.catchall._def.typeName!==`ZodNever`)return J(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 yv(e){try{return e.isOptional()}catch{return!0}}const bv=(e,t)=>{if(t.currentPath.toString()===t.propertyPath?.toString())return J(e.innerType._def,t);let n=J(e.innerType._def,{...t,currentPath:[...t.currentPath,`anyOf`,`1`]});return n?{anyOf:[{not:R_(t)},n]}:R_(t)},xv=(e,t)=>{if(t.pipeStrategy===`input`)return J(e.in._def,t);if(t.pipeStrategy===`output`)return J(e.out._def,t);let n=J(e.in._def,{...t,currentPath:[...t.currentPath,`allOf`,`0`]});return{allOf:[n,J(e.out._def,{...t,currentPath:[...t.currentPath,`allOf`,n?`1`:`0`]})].filter(e=>e!==void 0)}};function Sv(e,t){return J(e.type._def,t)}function Cv(e,t){let n={type:`array`,uniqueItems:!0,items:J(e.valueType._def,{...t,currentPath:[...t.currentPath,`items`]})};return e.minSize&&I_(n,`minItems`,e.minSize.value,e.minSize.message,t),e.maxSize&&I_(n,`maxItems`,e.maxSize.value,e.maxSize.message,t),n}function wv(e,t){return e.rest?{type:`array`,minItems:e.items.length,items:e.items.map((e,n)=>J(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[]),additionalItems:J(e.rest._def,{...t,currentPath:[...t.currentPath,`additionalItems`]})}:{type:`array`,minItems:e.items.length,maxItems:e.items.length,items:e.items.map((e,n)=>J(e._def,{...t,currentPath:[...t.currentPath,`items`,`${n}`]})).reduce((e,t)=>t===void 0?e:[...e,t],[])}}function Tv(e){return{not:R_(e)}}function Ev(e){return R_(e)}const Dv=(e,t)=>J(e.innerType._def,t),Ov=(e,t,n)=>{switch(t){case L.ZodString:return ev(e,n);case L.ZodNumber:return gv(e,n);case L.ZodObject:return _v(e,n);case L.ZodBigInt:return B_(e,n);case L.ZodBoolean:return V_();case L.ZodDate:return W_(e,n);case L.ZodUndefined:return Tv(n);case L.ZodNull:return dv(n);case L.ZodArray:return z_(e,n);case L.ZodUnion:case L.ZodDiscriminatedUnion:return pv(e,n);case L.ZodIntersection:return X_(e,n);case L.ZodTuple:return wv(e,n);case L.ZodRecord:return sv(e,n);case L.ZodLiteral:return Z_(e,n);case L.ZodEnum:return J_(e);case L.ZodNativeEnum:return lv(e);case L.ZodNullable:return hv(e,n);case L.ZodOptional:return bv(e,n);case L.ZodMap:return cv(e,n);case L.ZodSet:return Cv(e,n);case L.ZodLazy:return()=>e.getter()._def;case L.ZodPromise:return Sv(e,n);case L.ZodNaN:case L.ZodNever:return uv(n);case L.ZodEffects:return q_(e,n);case L.ZodAny:return R_(n);case L.ZodUnknown:return Ev(n);case L.ZodDefault:return K_(e,n);case L.ZodBranded:return H_(e,n);case L.ZodReadonly:return Dv(e,n);case L.ZodCatch:return U_(e,n);case L.ZodPipeline:return xv(e,n);case L.ZodFunction:case L.ZodVoid:case L.ZodSymbol:return;default:return(e=>void 0)(t)}};function J(e,t,n=!1){let r=t.seen.get(e);if(t.override){let i=t.override?.(e,t,r,n);if(i!==j_)return i}if(r&&!n){let e=kv(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=Ov(e,e.typeName,t),o=typeof a==`function`?J(a(),t):a;if(o&&Av(e,t,o),t.postProcess){let n=t.postProcess(o,e,t);return i.jsonSchema=o,n}return i.jsonSchema=o,o}const kv=(e,t)=>{switch(t.$refStrategy){case`root`:return{$ref:e.path.join(`/`)};case`relative`:return{$ref:L_(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`),R_(t)):t.$refStrategy===`seen`?R_(t):void 0}},Av=(e,t,n)=>(e.description&&(n.description=e.description,t.markdownDescription&&(n.markdownDescription=e.description)),n),jv=(e,t)=>{let n=P_(t),r=typeof t==`object`&&t.definitions?Object.entries(t.definitions).reduce((e,[t,r])=>({...e,[t]:J(r._def,{...n,currentPath:[...n.basePath,n.definitionPath,t]},!0)??R_(n)}),{}):void 0,i=typeof t==`string`?t:t?.nameStrategy===`title`?void 0:t?.name,a=J(e._def,i===void 0?n:{...n,currentPath:[...n.basePath,n.definitionPath,i]},!1)??R_(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 Mv(e){return!e||e===`jsonSchema7`||e===`draft-7`?`draft-7`:e===`jsonSchema2019-09`||e===`draft-2020-12`?`draft-2020-12`:`draft-7`}function Nv(e,t){return Jf(e)?Wf(e,{target:Mv(t?.target),io:t?.pipeStrategy??`input`}):jv(e,{strictUnions:t?.strictUnions??!0,pipeStrategy:t?.pipeStrategy??`input`})}function Pv(e){let t=Qf(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=ip(t);if(typeof n!=`string`)throw Error(`Schema method literal must be a string`);return n}function Fv(e,t){let n=Xf(e,t);if(!n.success)throw n.error;return n.data}var Iv=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(xh,e=>{this._oncancel(e)}),this.setNotificationHandler(Lh,e=>{this._onprogress(e)}),this.setRequestHandler(Ph,e=>({})),this._taskStore=e?.taskStore,this._taskMessageQueue=e?.taskMessageQueue,this._taskStore&&(this.setRequestHandler(Kh,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(Jh,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(!A_(i.status))return await this._waitForTaskUpdate(r,t.signal,t.sessionId),await n();if(A_(i.status)){let e=await this._taskStore.getTaskResult(r,t.sessionId);return this._clearTaskQueue(r,t.sessionId),{...e,_meta:{...e._meta,[Ym]:{taskId:r}}}}return await n()};return await n()}),this.setRequestHandler(Yh,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(Zh,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(A_(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),hh(e)||_h(e)?this._onresponse(e):dh(e)?this._onrequest(e,t):ph(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?.[Ym]?.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=ih(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),hh(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(hh(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),hh(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,Uh,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},A_(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||{},[Ym]: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=Xf(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},qh,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},Xh,t)}async cancelTask(e,t){return this.request({method:`tasks/cancel`,params:e},Qh,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||{},[Ym]: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||{},[Ym]: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||{},[Ym]:t.relatedTask}}}),await this._transport.send(r,t)}setRequestHandler(e,t){let n=Pv(e);this.assertRequestHandlerCapability(n),this._requestHandlers.set(n,(n,r)=>{let i=Fv(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=Pv(e);this._notificationHandlers.set(n,n=>{let r=Fv(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`&&dh(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=Gh.parse({method:`notifications/tasks/status`,params:a});await this.notification(t),A_(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(A_(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=Gh.parse({method:`notifications/tasks/status`,params:o});await this.notification(t),A_(o.status)&&this._cleanupTaskProgressHandler(e)}},listTasks:e=>n.listTasks(e,t)}}};function Lv(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Rv(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]=Lv(a)&&Lv(i)?{...a,...i}:i}return n}var zv=/* @__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})),Bv=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.ValueScope=e.ValueScopeName=e.Scope=e.varKinds=e.UsedValueState=void 0;let t=zv();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}}})),Y=/* @__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=zv(),n=Bv();var r=zv();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=Bv();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?`
|
|
134
|
+
`:``},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})`}})),X=/* @__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=Y(),n=zv();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})),Vv=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Y();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`)}})),Hv=/* @__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=Y(),n=X(),r=Vv();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}){
|
|
135
135
|
/* istanbul ignore if */
|
|
136
|
-
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])}})),Uv=/* @__PURE__ */
|
|
136
|
+
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])}})),Uv=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.boolOrEmptySchema=e.topBoolOrEmptySchema=void 0;let t=Hv(),n=Y(),r=Vv(),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)}})),Wv=/* @__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})),Gv=/* @__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})),Kv=/* @__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=Wv(),n=Gv(),r=Hv(),i=Y(),a=X();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
|
|
137
137
|
|| (${s} == "string" && ${a} && ${a} == +${a})`).assign(c,(0,i._)`+${a}`);return;case`integer`:r.elseIf((0,i._)`${s} === "boolean" || ${a} === null
|
|
138
138
|
|| (${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"
|
|
139
|
-
|| ${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}}})),qv=/* @__PURE__ */
|
|
139
|
+
|| ${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}}})),qv=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.assignDefaults=void 0;let t=Y(),n=X();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)}`)}})),Jv=/* @__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=Y(),n=X(),r=Vv(),i=X();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;
|
|
140
140
|
/* istanbul ignore if */
|
|
141
|
-
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})),Yv=/* @__PURE__ */
|
|
141
|
+
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})),Yv=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateKeywordUsage=e.validSchemaType=e.funcKeywordCode=e.macroKeywordCode=void 0;let t=Y(),n=Vv(),r=Jv(),i=Hv();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){
|
|
142
142
|
/* istanbul ignore if */
|
|
143
|
-
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})),Xv=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;let t=Y(),n=X();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})),Zv=/* @__PURE__ */ E(((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}})),Qv=/* @__PURE__ */ E(((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`)}})),$v=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getSchemaRefs=e.resolveUrl=e.normalizeId=e._getFullPath=e.getFullPath=e.inlineRef=void 0;let t=X(),n=Zv(),r=Qv(),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})),ey=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=Uv(),n=Kv(),r=Gv(),i=Kv(),a=qv(),o=Yv(),s=Xv(),c=Y(),l=Vv(),u=$v(),d=X(),f=Hv();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&&ie(e),te(e),r.let(l.default.vErrors,null),r.let(l.default.errors,0),n.unevaluated&&v(e),T(e),ae(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&&ie(e),ne(e),re(e);let a=r.const(`_errs`,l.default.errors);T(e,a),r.var(t,(0,c._)`${a} === ${l.default.errors}`)}function w(e){(0,d.checkUnknownRules)(e),ee(e)}function T(e,t){if(e.opts.jtd)return se(e,[],!1,t);let r=(0,n.getSchemaTypes)(e.schema);se(e,r,!(0,n.coerceAndCheckDataType)(e,r),t)}function ee(e){let{schema:t,errSchemaPath:n,opts:r,self:i}=e;t.$ref&&r.ignoreKeywordsWithRef&&(0,d.schemaHasRulesButRef)(t,i.RULES)&&i.logger.warn(`$ref: keywords ignored in schema at path "${n}"`)}function te(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 ne(e){let t=e.schema[e.opts.schemaId];t&&(e.baseId=(0,u.resolveUrl)(e.opts.uriResolver,e.baseId,t))}function re(e){if(e.schema.$async&&!e.schemaEnv.$async)throw Error(`async schema in sync schema`)}function ie({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 ae(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&&oe(e),t.return((0,c._)`${l.default.errors} === 0`))}function oe({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 se(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(()=>_e(e,`$ref`,h.all.$ref.definition));return}p.jtd||ce(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)),E(e,d),t.length===1&&t[0]===d.type&&n&&(o.else(),(0,i.reportTypeError)(e)),o.endIf()):E(e,d),f||o.if((0,c._)`${l.default.errors} === ${a||0}`))}}function E(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)&&_e(e,n.keyword,n.definition,t.type)})}function ce(e,t){!e.schemaEnv.meta&&e.opts.strictTypes&&(le(e,t),e.opts.allowUnionTypes||ue(e,t),de(e,e.dataTypes))}function le(e,t){t.length&&(e.dataTypes.length?(t.forEach(t=>{pe(e.dataTypes,t)||he(e,`type "${t}" not allowed by context "${e.dataTypes.join(`,`)}"`)}),me(e,t)):e.dataTypes=t)}function ue(e,t){t.length>1&&!(t.length===2&&t.includes(`null`))&&he(e,`use allowUnionTypes to allow union type keyword`)}function de(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=>fe(t,e))&&he(e,`missing type "${n.join(`,`)}" for keyword "${i}"`)}}}function fe(e,t){return e.includes(t)||t===`number`&&e.includes(`integer`)}function pe(e,t){return e.includes(t)||t===`integer`&&e.includes(`number`)}function me(e,t){let n=[];for(let r of e.dataTypes)pe(t,r)?n.push(r):t.includes(`integer`)&&r===`number`&&n.push(`integer`);e.dataTypes=n}function he(e,t){let n=e.schemaEnv.baseId+e.errSchemaPath;t+=` at "${n}" (strictTypes)`,(0,d.checkStrictMode)(e,t,e.opts.strictTypes)}var ge=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`,be(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
|
+
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})),Xv=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.extendSubschemaMode=e.extendSubschemaData=e.getSubschema=void 0;let t=Y(),n=X();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})),Zv=/* @__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}})),Qv=/* @__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`)}})),$v=/* @__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=X(),n=Zv(),r=Qv(),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})),ey=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.getData=e.KeywordCxt=e.validateFunctionCode=void 0;let t=Uv(),n=Kv(),r=Gv(),i=Kv(),a=qv(),o=Yv(),s=Xv(),c=Y(),l=Vv(),u=$v(),d=X(),f=Hv();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){
|
|
144
144
|
/* istanbul ignore if */
|
|
145
|
-
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=ge;function _e(e,t,n,r){let i=new ge(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 ve=/^\/(?:[^~]|~0|~1)*$/,ye=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function be(e,{dataLevel:t,dataNames:n,dataPathArr:r}){let i,a;if(e===``)return l.default.rootData;if(e[0]===`/`){if(!ve.test(e))throw Error(`Invalid JSON-pointer: ${e}`);i=e,a=l.default.rootData}else{let o=ye.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=be})),ty=/* @__PURE__ */ E((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}}})),ny=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=$v();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))}}})),ry=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=Y(),n=ty(),r=Vv(),i=$v(),a=X(),o=ey();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}})),iy=/* @__PURE__ */ E(((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}})),ay=/* @__PURE__ */ E(((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,ee=/[@/?#]/g;function te(e,t){let n=t?ee:T;return n.lastIndex=0,e.replace(n,e=>w[e])}function ne(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 re(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+=ce(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 ie(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 ae(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 oe(e){return ae(e,l)}function se(e){return ae(e,c)}function E(e){return ae(e,c)}function ce(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 le(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+=ce(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 ue(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 de(e){let t=[];if(e.userinfo!==void 0&&(t.push(oe(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=ne(n,!0),e=b(n)),n=e.isIPV6===!0||e.isIPVFuture===!0?`[${e.escapedHost}]`:te(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:de,reescapeHostDelimiters:te,normalizePercentEncoding:ne,normalizePathEncoding:re,serializePathEncoding:ie,normalizeQueryFragmentEncoding:le,encodeUserinfo:oe,encodeQuery:se,encodeFragment:E,escapePreservingEscapes:ue,removeDotSegments:S,removeDotSegmentsRelative:C,isIPv4:r,isUUID:n,normalizeIPv6:b,stringArrayToHexStripped:f}})),oy=/* @__PURE__ */ E(((e,t)=>{let{isUUID:n}=ay(),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}})),sy=/* @__PURE__ */ E(((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}=ay(),{SCHEMES:h,getSchemeHandler:g}=oy(),_=/^[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=fe(e,t):typeof e==`object`&&(e=de(ee(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}=ue(e,i),{parsed:d,malformedAuthorityOrPort:f,malformedPercentEncoding:m,malformedSchemeSpecific:h,malformedHost:_,malformedScheme:v}=ue(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(ce(b,r||{},x,C))throw Error(y);E(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,ee(b,i)}function w(e,t,n,a){let o={};if(a||(e=de(ee(e,n),n),t=de(ee(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=me(e,n),i=me(t,n);return r!==void 0&&i!==void 0&&r===i}function ee(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 te=/^(?:([^#/:?]+):)?(?:\/\/((?:([^#/?@]*)@)?(\[[^#/?\]]+\]|[^#/:?]*)(?::(\d*))?))?([^#?]*)(?:\?([^#]*))?(?:#((?:.|[\n\r])*))?/u,ne=/^(?:[^#/:?]+:)?\/\/([^/?#]*)/,re=/^(?:[^#/:?]+:)?([/\\\t\n\r]*)/;function ie(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 ae(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 oe(e){return e[0]===`[`&&e[e.length-1]===`]`}function se(e){let t=e[4];return ae(e[3])||t!==void 0&&!oe(t)&&ae(t)||ae(e[6])||ae(e[7])||ae(e[8])}function E(e,t,n,r){if(ce(e,t,n,r))return e.error=e.error||y,!0;if(!t.unicodeSupport&&(!n||!n.unicodeSupport)&&e.host&&!oe(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(!le(t))return e.error=e.error||y,!0;e.host=t.hostname}return!1}function ce(e,t,n,r){return!!(e.host&&r===!1&&!oe(e.host)&&(t.domainHost||n&&n.domainHost)&&b.test(e.host))}function le(e){return e.username===``&&e.password===``&&e.port===``&&e.pathname===`/`&&e.search===``&&e.hash===``&&e.hostname!==``}function ue(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(ne);S!==null&&S[1].indexOf(`\\`)!==-1&&(i.error=`URI authority must not contain a literal backslash.`,a=!0);let C=e.match(re);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(te);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=se(w),c&&(i.error=i.error||`URI contains malformed percent-encoding.`),isNaN(i.port)&&(i.port=w[5]);let t=ie(i,w);if(t!==void 0&&(i.error=i.error||t,a=!0),i.host){if(p(i.host)===!1){let e=oe(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=E(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 de(e,t){return ue(e,t).parsed}function fe(e,t){return pe(e,t).normalized}function pe(e,t){let{parsed:n,malformedAuthorityOrPort:r,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:o,malformedScheme:s}=ue(e,t);return{normalized:r||i||a||o||s?e:ee(n,t),malformedAuthorityOrPort:r,malformedPercentEncoding:i,malformedSchemeSpecific:a,malformedHost:o,malformedScheme:s}}function me(e,t){if(typeof e!=`string`&&typeof e!=`object`)return;let n;try{n=typeof e==`string`?e:ee(e,t)}catch{return}let{normalized:r,malformedAuthorityOrPort:i,malformedPercentEncoding:a,malformedSchemeSpecific:o,malformedHost:s,malformedScheme:c}=pe(n,t);return i||a||o||s||c?void 0:r}let he={SCHEMES:h,normalize:S,resolve:C,resolveComponent:w,equal:T,serialize:ee,parse:de};t.exports=he,t.exports.default=he,t.exports.fastUri=he})),cy=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=sy();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),ly=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.CodeGen=e.Name=e.nil=e.stringify=e.str=e._=e.KeywordCxt=void 0;var t=ey();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var n=Y();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=ty(),i=ny(),a=Wv(),o=ry(),s=Y(),c=$v(),l=Kv(),u=X(),d=iy(),f=cy(),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=te(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(re.call(this,n,t),!t)return(0,u.eachItem)(n,e=>ie.call(this,e)),this;oe.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=>ie.call(this,e,r):e=>r.type.forEach(t=>ie.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]=E(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
|
+
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})),ty=/* @__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}}})),ny=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=$v();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))}}})),ry=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.resolveSchema=e.getCompilingSchema=e.resolveRef=e.compileSchema=e.SchemaEnv=void 0;let t=Y(),n=ty(),r=Vv(),i=$v(),a=X(),o=ey();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}})),iy=/* @__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}})),ay=/* @__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}})),oy=/* @__PURE__ */ D(((e,t)=>{let{isUUID:n}=ay(),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}})),sy=/* @__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}=ay(),{SCHEMES:h,getSchemeHandler:g}=oy(),_=/^[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})),cy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=sy();t.code=`require("ajv/dist/runtime/uri").default`,e.default=t})),ly=/* @__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=ey();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return t.KeywordCxt}});var n=Y();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=ty(),i=ny(),a=Wv(),o=ry(),s=Y(),c=$v(),l=Kv(),u=X(),d=iy(),f=cy(),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){
|
|
146
146
|
/* istanbul ignore if */
|
|
147
|
-
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 ee={log(){},warn(){},error(){}};function te(e){if(e===!1)return ee;if(e===void 0)return console;if(e.log&&e.warn&&e.error)return e;throw Error(`logger must implement log, warn and error methods`)}let ne=/^[a-z_$][a-z0-9_$:-]*$/i;function re(e,t){let{RULES:n}=this;if((0,u.eachItem)(e,e=>{if(n.keywords[e])throw Error(`Keyword ${e} is already defined`);if(!ne.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 ie(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?ae.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 ae(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 oe(e){let{metaSchema:t}=e;t!==void 0&&(e.$data&&this.opts.$data&&(t=E(t)),e.validateSchema=this.compile(t,!0))}let se={$ref:`https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#`};function E(e){return{anyOf:[e,se]}}})),uy=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`id`,code(){throw Error(`NOT SUPPORTED: keyword "id", use "$id" for schema ID`)}}})),dy=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.callRef=e.getValidate=void 0;let t=ny(),n=Jv(),r=Y(),i=Vv(),a=ry(),o=X(),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})),fy=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=uy(),n=dy();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),py=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Y(),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})`)}}})),my=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Y();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}))`)}}})),hy=/* @__PURE__ */ E((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`})),gy=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Y(),n=X(),r=hy();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}`)}}})),_y=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Jv(),n=X(),r=Y();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})`)}}}})),vy=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Y();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}`)}}})),yy=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Jv(),n=Y(),r=X();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)}}}})),by=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Y();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}`)}}})),xy=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Zv();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),Sy=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Kv(),n=Y(),r=X(),i=xy();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)})))}}}})),Cy=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Y(),n=X(),r=xy();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}`)}}})),wy=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Y(),n=X(),r=xy();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
|
+
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]}}})),uy=/* @__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`)}}})),dy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.callRef=e.getValidate=void 0;let t=ny(),n=Jv(),r=Y(),i=Vv(),a=ry(),o=X(),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})),fy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=uy(),n=dy();e.default=[`$schema`,`$id`,`$defs`,`$vocabulary`,{keyword:`$comment`},`definitions`,t.default,n.default]})),py=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Y(),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})`)}}})),my=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Y();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}))`)}}})),hy=/* @__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`})),gy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Y(),n=X(),r=hy();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}`)}}})),_y=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Jv(),n=X(),r=Y();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})`)}}}})),vy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Y();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}`)}}})),yy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Jv(),n=Y(),r=X();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)}}}})),by=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Y();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}`)}}})),xy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Zv();t.code=`require("ajv/dist/runtime/equal").default`,e.default=t})),Sy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Kv(),n=Y(),r=X(),i=xy();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)})))}}}})),Cy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Y(),n=X(),r=xy();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}`)}}})),wy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Y(),n=X(),r=xy();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{
|
|
148
148
|
/* istanbul ignore if */
|
|
149
|
-
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}`}}}})),Ty=/* @__PURE__ */
|
|
149
|
+
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}`}}}})),Ty=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=py(),n=my(),r=gy(),i=_y(),a=vy(),o=yy(),s=by(),c=Sy(),l=Cy(),u=wy();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]})),Ey=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateAdditionalItems=void 0;let t=Y(),n=X(),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})),Dy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateTuple=void 0;let t=Y(),n=X(),r=Jv(),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})),Oy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Dy();e.default={keyword:`prefixItems`,type:`array`,schemaType:[`array`],before:`uniqueItems`,code:e=>(0,t.validateTuple)(e,`items`)}})),ky=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Y(),n=X(),r=Jv(),i=Ey();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)))}}})),Ay=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Y(),n=X();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)))}}}})),jy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.validateSchemaDeps=e.validatePropertyDeps=e.error=void 0;let t=Y(),n=X(),r=Jv();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},
|
|
150
150
|
missingProperty: ${i},
|
|
151
151
|
depsCount: ${n},
|
|
152
|
-
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})),My=/* @__PURE__ */
|
|
152
|
+
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})),My=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Y(),n=X();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)}}})),Ny=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Jv(),n=Y(),r=Vv(),i=X();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;
|
|
153
153
|
/* istanbul ignore if */
|
|
154
|
-
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)}}}})),Py=/* @__PURE__ */
|
|
154
|
+
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)}}}})),Py=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=ey(),n=Jv(),r=X(),i=Ny();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)}}}})),Fy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Jv(),n=Y(),r=X(),i=X();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())})})}}}})),Iy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=X();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`}}})),Ly=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default={keyword:`anyOf`,schemaType:`array`,trackErrors:!0,code:Jv().validateUnion,error:{message:`must match a schema in anyOf`}}})),Ry=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Y(),n=X();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;
|
|
155
155
|
/* istanbul ignore if */
|
|
156
|
-
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)})})}}}})),zy=/* @__PURE__ */
|
|
156
|
+
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)})})}}}})),zy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=X();e.default={keyword:`allOf`,schemaType:`array`,code(e){let{gen:n,schema:r,it:i}=e;
|
|
157
157
|
/* istanbul ignore if */
|
|
158
|
-
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)})}}})),By=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Y(),n=X(),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})),Vy=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=X();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`)}}})),Hy=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Ey(),n=Oy(),r=Dy(),i=ky(),a=Ay(),o=jy(),s=My(),c=Ny(),l=Py(),u=Fy(),d=Iy(),f=Ly(),p=Ry(),m=zy(),h=By(),g=Vy();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=_})),Uy=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Y();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})`}}}}})),Wy=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=[Uy().default]})),Gy=/* @__PURE__ */ E((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`]})),Ky=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=fy(),n=Ty(),r=Hy(),i=Wy(),a=Gy();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),qy=/* @__PURE__ */ E((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={}))})),Jy=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Y(),n=qy(),r=ry(),i=ny(),a=X();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}}}}})),Yy=/* @__PURE__ */ E(((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}})),Xy=/* @__PURE__ */ E(((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=ly(),r=Ky(),i=Jy(),a=Yy(),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=ey();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return l.KeywordCxt}});var u=Y();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=ty();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return d.default}});var f=ny();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return f.default}})})),Zy=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatNames=e.fastFormats=e.fullFormats=void 0;function t(e,t){return{validate:e,compare:t}}e.fullFormats={date:t(a,o),time:t(c(!0),l),"date-time":t(f(!0),p),"iso-time":t(c(),u),"iso-date-time":t(f(),m),duration:/^P(?!$)((\d+Y)?(\d+M)?(\d+D)?(T(?=\d)(\d+H)?(\d+M)?(\d+S)?)?|(\d+W)?)$/,uri:_,"uri-reference":/^(?:[a-z][a-z0-9+\-.]*:)?(?:\/?\/(?:(?:[a-z0-9\-._~!$&'()*+,;=:]|%[0-9a-f]{2})*@)?(?:\[(?:(?:(?:(?:[0-9a-f]{1,4}:){6}|::(?:[0-9a-f]{1,4}:){5}|(?:[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){4}|(?:(?:[0-9a-f]{1,4}:){0,1}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){3}|(?:(?:[0-9a-f]{1,4}:){0,2}[0-9a-f]{1,4})?::(?:[0-9a-f]{1,4}:){2}|(?:(?:[0-9a-f]{1,4}:){0,3}[0-9a-f]{1,4})?::[0-9a-f]{1,4}:|(?:(?:[0-9a-f]{1,4}:){0,4}[0-9a-f]{1,4})?::)(?:[0-9a-f]{1,4}:[0-9a-f]{1,4}|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?))|(?:(?:[0-9a-f]{1,4}:){0,5}[0-9a-f]{1,4})?::[0-9a-f]{1,4}|(?:(?:[0-9a-f]{1,4}:){0,6}[0-9a-f]{1,4})?::)|[Vv][0-9a-f]+\.[a-z0-9\-._~!$&'()*+,;=:]+)\]|(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)|(?:[a-z0-9\-._~!$&'"()*+,;=]|%[0-9a-f]{2})*)(?::\d*)?(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*|\/(?:(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?|(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})+(?:\/(?:[a-z0-9\-._~!$&'"()*+,;=:@]|%[0-9a-f]{2})*)*)?(?:\?(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?(?:#(?:[a-z0-9\-._~!$&'"()*+,;=:@/?]|%[0-9a-f]{2})*)?$/i,"uri-template":/^(?:(?:[^\x00-\x20"'<>%\\^`{|}]|%[0-9a-f]{2})|\{[+#./;?&=,!@|]?(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?(?:,(?:[a-z0-9_]|%[0-9a-f]{2})+(?::[1-9][0-9]{0,3}|\*)?)*\})*$/i,url:/^(?:https?|ftp):\/\/(?:\S+(?::\S*)?@)?(?:(?!(?:10|127)(?:\.\d{1,3}){3})(?!(?:169\.254|192\.168)(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)(?:\.(?:[a-z0-9\u{00a1}-\u{ffff}]+-)*[a-z0-9\u{00a1}-\u{ffff}]+)*(?:\.(?:[a-z\u{00a1}-\u{ffff}]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?$/iu,email:/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i,hostname:/^(?=.{1,253}\.?$)[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[-0-9a-z]{0,61}[0-9a-z])?)*\.?$/i,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)$/,ipv6:/^((([0-9a-f]{1,4}:){7}([0-9a-f]{1,4}|:))|(([0-9a-f]{1,4}:){6}(:[0-9a-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){5}(((:[0-9a-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9a-f]{1,4}:){4}(((:[0-9a-f]{1,4}){1,3})|((:[0-9a-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){3}(((:[0-9a-f]{1,4}){1,4})|((:[0-9a-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){2}(((:[0-9a-f]{1,4}){1,5})|((:[0-9a-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9a-f]{1,4}:){1}(((:[0-9a-f]{1,4}){1,6})|((:[0-9a-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9a-f]{1,4}){1,7})|((:[0-9a-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))$/i,regex:ee,uuid:/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,"json-pointer":/^(?:\/(?:[^~/]|~0|~1)*)*$/,"json-pointer-uri-fragment":/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,"relative-json-pointer":/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/,byte:y,int32:{type:`number`,validate:S},int64:{type:`number`,validate:C},float:{type:`number`,validate:w},double:{type:`number`,validate:w},password:!0,binary:!0},e.fastFormats={...e.fullFormats,date:t(/^\d\d\d\d-[0-1]\d-[0-3]\d$/,o),time:t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,l),"date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\dt(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)$/i,p),"iso-time":t(/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,u),"iso-date-time":t(/^\d\d\d\d-[0-1]\d-[0-3]\d[t\s](?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,m),uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,email:/^[a-z0-9.!#$%&'*+/=?^_`{|}~-]+@[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*$/i},e.formatNames=Object.keys(e.fullFormats);function n(e){return e%4==0&&(e%100!=0||e%400==0)}let r=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,i=[0,31,28,31,30,31,30,31,31,30,31,30,31];function a(e){let t=r.exec(e);if(!t)return!1;let a=+t[1],o=+t[2],s=+t[3];return o>=1&&o<=12&&s>=1&&s<=(o===2&&n(a)?29:i[o])}function o(e,t){if(e&&t)return e>t?1:e<t?-1:0}let s=/^(\d\d):(\d\d):(\d\d(?:\.\d+)?)(z|([+-])(\d\d)(?::?(\d\d))?)?$/i;function c(e){return function(t){let n=s.exec(t);if(!n)return!1;let r=+n[1],i=+n[2],a=+n[3],o=n[4],c=n[5]===`-`?-1:1,l=+(n[6]||0),u=+(n[7]||0);if(l>23||u>59||e&&!o)return!1;if(r<=23&&i<=59&&a<60)return!0;let d=i-u*c,f=r-l*c-+(d<0);return(f===23||f===-1)&&(d===59||d===-1)&&a<61}}function l(e,t){if(!(e&&t))return;let n=(/* @__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 ee(e){if(T.test(e))return!1;try{return new RegExp(e),!0}catch{return!1}}})),Qy=/* @__PURE__ */ E((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;let t=Xy(),n=Y(),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)})),$y=/* @__PURE__ */ E(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});let n=Zy(),r=Qy(),i=Y(),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})),eb=/* @__PURE__ */ ue(Xy(),1),tb=/* @__PURE__ */ ue($y(),1);function nb(){let e=new eb.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,tb.default)(e),e}var rb=class{constructor(e){this._ajv=e??nb()}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)}}},ib=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},o_,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},v_,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 ab(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 ob(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 sb=class extends Iv{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=/* @__PURE__ */ new Map,this.LOG_LEVEL_SEVERITY=new Map(qg.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 rb,this.setRequestHandler(jh,e=>this._oninitialize(e)),this.setNotificationHandler(Ph,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Yg,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=qg.safeParse(r);return i.success&&this._loggingLevels.set(n,i.data),{}})}get experimental(){return this._experimental||={tasks:new ib(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=Rv(this._capabilities,e)}setRequestHandler(e,t){let n=$f(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r=ap(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=Zf(Gg,e);if(!r.success){let e=r.error instanceof Error?r.error.message:String(r.error);throw new K(G.InvalidParams,`Invalid tools/call request: ${e}`)}let{params:i}=r.data,a=await Promise.resolve(t(e,n));if(i.task){let e=Zf(Wh,a);if(!e.success){let t=e.error instanceof Error?e.error.message:String(e.error);throw new K(G.InvalidParams,`Invalid task creation result: ${t}`)}return e.data}let o=Zf(Ug,a);if(!o.success){let e=o.error instanceof Error?o.error.message:String(o.error);throw new K(G.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){ob(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&ab(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:Ym.includes(t)?t:Jm,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`},bh)}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},s_,t):this.request({method:`sampling/createMessage`,params:e},o_,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},v_,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},v_,t);if(r.action===`accept`&&r.content&&n.requestedSchema)try{let e=this._jsonSchemaValidator.getValidator(n.requestedSchema)(r.content);if(!e.valid)throw new K(G.InvalidParams,`Elicitation response content does not match requested schema: ${e.errorMessage}`)}catch(e){throw e instanceof K?e:new K(G.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},O_,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 cb=Symbol.for(`mcp.completable`);function lb(e){return!!e&&typeof e==`object`&&cb in e}function ub(e){return e[cb]?.complete}var db;(function(e){e.Completable=`McpCompletable`})(db||={});const fb=/^[A-Za-z0-9._-]{1,128}$/;function pb(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`),!fb.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 mb(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 hb(e){let t=pb(e);return mb(e,t.warnings),t.isValid}var gb=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 _b(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 vb(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 yb=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 sb(e,t),this._maxToolInputElements=vb(t?.maxToolInputElements),t?.capabilities?.tools&&this.setToolRequestHandlers(),t?.capabilities?.resources&&this.setResourceRequestHandlers(),t?.capabilities?.prompts&&this.setPromptRequestHandlers()}get experimental(){return this._experimental||={tasks:new gb(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(Eb(Vg)),this.server.assertCanSetRequestHandler(Eb(Gg)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Vg,()=>({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=ep(t.inputSchema);return e?Nv(e,{strictUnions:!0,pipeStrategy:`input`}):bb})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=ep(t.outputSchema);e&&(n.outputSchema=Nv(e,{strictUnions:!0,pipeStrategy:`output`}))}return n})})),this.server.setRequestHandler(Gg,async(e,t)=>{try{let n=this._registeredTools[e.params.name];if(!n)throw new K(G.InvalidParams,`Tool ${e.params.name} not found`);if(!n.enabled)throw new K(G.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 K(G.InternalError,`Tool ${e.params.name} has taskSupport '${i}' but was not registered with registerToolTask`);if(i===`required`&&!r)throw new K(G.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 K&&e.code===G.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&&_b(t,this._maxToolInputElements)>this._maxToolInputElements)throw new K(G.InvalidParams,`Invalid arguments for tool ${n}: arguments contain more than the maximum of ${this._maxToolInputElements} elements`);if(!e.inputSchema)return;let r=await Qf(ep(e.inputSchema)??e.inputSchema,t??{});if(!r.success){let e=np(`error`in r?r.error:`Unknown error`);throw new K(G.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 K(G.InvalidParams,`Output validation error: Tool ${n} has an output schema but no structured content was provided`);let r=await Qf(ep(e.outputSchema),t.structuredContent);if(!r.success){let e=np(`error`in r?r.error:`Unknown error`);throw new K(G.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 K(G.InternalError,`Task ${s} not found during polling`);c=e}return await n.taskStore.getTaskResult(s)}setCompletionRequestHandler(){this._completionHandlerInitialized||=(this.server.assertCanSetRequestHandler(Eb(S_)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(S_,async e=>{switch(e.params.ref.type){case`ref/prompt`:return C_(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return w_(e),this.handleResourceCompletion(e,e.params.ref);default:throw new K(G.InvalidParams,`Invalid completion reference: ${e.params.ref}`)}}),!0)}async handlePromptCompletion(e,t){let n=this._registeredPrompts[t.name];if(!n)throw new K(G.InvalidParams,`Prompt ${t.name} not found`);if(!n.enabled)throw new K(G.InvalidParams,`Prompt ${t.name} disabled`);if(!n.argsSchema)return Ob;let r=$f(n.argsSchema)?.[e.params.argument.name];if(!lb(r))return Ob;let i=ub(r);return i?Db(await i(e.params.argument.value,e.params.context)):Ob}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 Ob;throw new K(G.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?Db(await r(e.params.argument.value,e.params.context)):Ob}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(Eb(cg)),this.server.assertCanSetRequestHandler(Eb(ug)),this.server.assertCanSetRequestHandler(Eb(mg)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(cg,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(ug,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(mg,async(e,t)=>{let n=new URL(e.params.uri),r=this._registeredResources[n.toString()];if(r){if(!r.enabled)throw new K(G.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 K(G.InvalidParams,`Resource ${n} not found`)}),!0)}setPromptRequestHandlers(){this._promptHandlersInitialized||=(this.server.assertCanSetRequestHandler(Eb(Tg)),this.server.assertCanSetRequestHandler(Eb(Og)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(Tg,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?Tb(t.argsSchema):void 0}))})),this.server.setRequestHandler(Og,async(e,t)=>{let n=this._registeredPrompts[e.params.name];if(!n)throw new K(G.InvalidParams,`Prompt ${e.params.name} not found`);if(!n.enabled)throw new K(G.InvalidParams,`Prompt ${e.params.name} disabled`);if(n.argsSchema){let r=await Qf(ep(n.argsSchema),e.params.arguments??{});if(!r.success){let t=np(`error`in r?r.error:`Unknown error`);throw new K(G.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:Xf(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=Xf(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=>lb(e instanceof Cm?e._def?.innerType:e))&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,t,n,r,i,a,o,s,c){hb(e);let l={title:t,description:n,inputSchema:wb(r),outputSchema:wb(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`&&hb(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=Xf(t.paramsSchema)),t.outputSchema!==void 0&&(l.outputSchema=Xf(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(Cb(n))r=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!Cb(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 bb={type:`object`,properties:{}};function xb(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function Sb(e){return`_def`in e||`_zod`in e||xb(e)}function Cb(e){return typeof e!=`object`||!e||Sb(e)?!1:Object.keys(e).length===0||Object.values(e).some(xb)}function wb(e){if(e){if(Cb(e))return Xf(e);if(!Sb(e))throw Error(`inputSchema must be a Zod schema or raw shape, received an unrecognized object`);return e}}function Tb(e){let t=$f(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:rp(t),required:!ip(t)})):[]}function Eb(e){let t=$f(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=ap(t);if(typeof n==`string`)return n;throw Error(`Schema method literal must be a string`)}function Db(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const Ob={completion:{values:[],hasMore:!1}};var kb=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(`
|
|
159
|
-
`);if(e===-1)return null;let t=this._buffer.toString(`utf8`,0,e).replace(/\r$/,``);return this._buffer=this._buffer.subarray(e+1),Ab(t)}clear(){this._buffer=void 0}};function Ab(e){return
|
|
158
|
+
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)})}}})),By=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Y(),n=X(),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})),Vy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=X();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`)}}})),Hy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Ey(),n=Oy(),r=Dy(),i=ky(),a=Ay(),o=jy(),s=My(),c=Ny(),l=Py(),u=Fy(),d=Iy(),f=Ly(),p=Ry(),m=zy(),h=By(),g=Vy();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=_})),Uy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Y();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})`}}}}})),Wy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.default=[Uy().default]})),Gy=/* @__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`]})),Ky=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=fy(),n=Ty(),r=Hy(),i=Wy(),a=Gy();e.default=[t.default,n.default,(0,r.default)(),i.default,a.metadataVocabulary,a.contentVocabulary]})),qy=/* @__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={}))})),Jy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0});let t=Y(),n=qy(),r=ry(),i=ny(),a=X();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}}}}})),Yy=/* @__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}})),Xy=/* @__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=ly(),r=Ky(),i=Jy(),a=Yy(),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=ey();Object.defineProperty(e,"KeywordCxt",{enumerable:!0,get:function(){return l.KeywordCxt}});var u=Y();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=ty();Object.defineProperty(e,"ValidationError",{enumerable:!0,get:function(){return d.default}});var f=ny();Object.defineProperty(e,"MissingRefError",{enumerable:!0,get:function(){return f.default}})})),Zy=/* @__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}}})),Qy=/* @__PURE__ */ D((e=>{Object.defineProperty(e,"__esModule",{value:!0}),e.formatLimitDefinition=void 0;let t=Xy(),n=Y(),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)})),$y=/* @__PURE__ */ D(((e,t)=>{Object.defineProperty(e,"__esModule",{value:!0});let n=Zy(),r=Qy(),i=Y(),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})),eb=/* @__PURE__ */ le(Xy(),1),tb=/* @__PURE__ */ le($y(),1);function nb(){let e=new eb.default({strict:!1,validateFormats:!0,validateSchema:!1,allErrors:!0});return(0,tb.default)(e),e}var rb=class{constructor(e){this._ajv=e??nb()}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)}}},ib=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},a_,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},__,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 ab(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 ob(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 sb=class extends Iv{constructor(e,t){super(t),this._serverInfo=e,this._loggingLevels=/* @__PURE__ */ new Map,this.LOG_LEVEL_SEVERITY=new Map(Kg.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 rb,this.setRequestHandler(Ah,e=>this._oninitialize(e)),this.setNotificationHandler(Nh,()=>this.oninitialized?.()),this._capabilities.logging&&this.setRequestHandler(Jg,async(e,t)=>{let n=t.sessionId||t.requestInfo?.headers[`mcp-session-id`]||void 0,{level:r}=e.params,i=Kg.safeParse(r);return i.success&&this._loggingLevels.set(n,i.data),{}})}get experimental(){return this._experimental||={tasks:new ib(this)},this._experimental}registerCapabilities(e){if(this.transport)throw Error(`Cannot register capabilities after connecting to transport`);this._capabilities=Rv(this._capabilities,e)}setRequestHandler(e,t){let n=Qf(e)?.method;if(!n)throw Error(`Schema is missing a method literal`);let r=ip(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=Xf(Wg,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=Xf(Uh,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=Xf(Hg,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){ob(this._clientCapabilities?.tasks?.requests,e,`Client`)}assertTaskHandlerCapability(e){this._capabilities&&ab(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:Jm.includes(t)?t:qm,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`},yh)}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},o_,t):this.request({method:`sampling/createMessage`,params:e},a_,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},__,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},__,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},D_,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 cb=Symbol.for(`mcp.completable`);function lb(e){return!!e&&typeof e==`object`&&cb in e}function ub(e){return e[cb]?.complete}var db;(function(e){e.Completable=`McpCompletable`})(db||={});const fb=/^[A-Za-z0-9._-]{1,128}$/;function pb(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`),!fb.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 mb(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 hb(e){let t=pb(e);return mb(e,t.warnings),t.isValid}var gb=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 _b(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 vb(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 yb=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 sb(e,t),this._maxToolInputElements=vb(t?.maxToolInputElements),t?.capabilities?.tools&&this.setToolRequestHandlers(),t?.capabilities?.resources&&this.setResourceRequestHandlers(),t?.capabilities?.prompts&&this.setPromptRequestHandlers()}get experimental(){return this._experimental||={tasks:new gb(this)},this._experimental}async connect(e){return await this.server.connect(e)}async close(){await this.server.close()}setToolRequestHandlers(){this._toolHandlersInitialized||=(this.server.assertCanSetRequestHandler(Eb(Bg)),this.server.assertCanSetRequestHandler(Eb(Wg)),this.server.registerCapabilities({tools:{listChanged:!0}}),this.server.setRequestHandler(Bg,()=>({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=$f(t.inputSchema);return e?Nv(e,{strictUnions:!0,pipeStrategy:`input`}):bb})(),annotations:t.annotations,execution:t.execution,_meta:t._meta};if(t.outputSchema){let e=$f(t.outputSchema);e&&(n.outputSchema=Nv(e,{strictUnions:!0,pipeStrategy:`output`}))}return n})})),this.server.setRequestHandler(Wg,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&&_b(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 Zf($f(e.inputSchema)??e.inputSchema,t??{});if(!r.success){let e=tp(`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 Zf($f(e.outputSchema),t.structuredContent);if(!r.success){let e=tp(`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(Eb(x_)),this.server.registerCapabilities({completions:{}}),this.server.setRequestHandler(x_,async e=>{switch(e.params.ref.type){case`ref/prompt`:return S_(e),this.handlePromptCompletion(e,e.params.ref);case`ref/resource`:return C_(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 Ob;let r=Qf(n.argsSchema)?.[e.params.argument.name];if(!lb(r))return Ob;let i=ub(r);return i?Db(await i(e.params.argument.value,e.params.context)):Ob}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 Ob;throw new q(K.InvalidParams,`Resource template ${e.params.ref.uri} not found`)}let r=n.resourceTemplate.completeCallback(e.params.argument.name);return r?Db(await r(e.params.argument.value,e.params.context)):Ob}setResourceRequestHandlers(){this._resourceHandlersInitialized||=(this.server.assertCanSetRequestHandler(Eb(sg)),this.server.assertCanSetRequestHandler(Eb(lg)),this.server.assertCanSetRequestHandler(Eb(pg)),this.server.registerCapabilities({resources:{listChanged:!0}}),this.server.setRequestHandler(sg,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(lg,async()=>({resourceTemplates:Object.entries(this._registeredResourceTemplates).map(([e,t])=>({name:e,uriTemplate:t.resourceTemplate.uriTemplate.toString(),...t.metadata}))})),this.server.setRequestHandler(pg,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(Eb(wg)),this.server.assertCanSetRequestHandler(Eb(Dg)),this.server.registerCapabilities({prompts:{listChanged:!0}}),this.server.setRequestHandler(wg,()=>({prompts:Object.entries(this._registeredPrompts).filter(([,e])=>e.enabled).map(([e,t])=>({name:e,title:t.title,description:t.description,arguments:t.argsSchema?Tb(t.argsSchema):void 0}))})),this.server.setRequestHandler(Dg,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 Zf($f(n.argsSchema),e.params.arguments??{});if(!r.success){let t=tp(`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:Yf(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=Yf(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=>lb(e instanceof Sm?e._def?.innerType:e))&&this.setCompletionRequestHandler(),a}_createRegisteredTool(e,t,n,r,i,a,o,s,c){hb(e);let l={title:t,description:n,inputSchema:wb(r),outputSchema:wb(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`&&hb(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=Yf(t.paramsSchema)),t.outputSchema!==void 0&&(l.outputSchema=Yf(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(Cb(n))r=t.shift(),t.length>1&&typeof t[0]==`object`&&t[0]!==null&&!Cb(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 bb={type:`object`,properties:{}};function xb(e){return typeof e==`object`&&!!e&&`parse`in e&&typeof e.parse==`function`&&`safeParse`in e&&typeof e.safeParse==`function`}function Sb(e){return`_def`in e||`_zod`in e||xb(e)}function Cb(e){return typeof e!=`object`||!e||Sb(e)?!1:Object.keys(e).length===0||Object.values(e).some(xb)}function wb(e){if(e){if(Cb(e))return Yf(e);if(!Sb(e))throw Error(`inputSchema must be a Zod schema or raw shape, received an unrecognized object`);return e}}function Tb(e){let t=Qf(e);return t?Object.entries(t).map(([e,t])=>({name:e,description:np(t),required:!rp(t)})):[]}function Eb(e){let t=Qf(e)?.method;if(!t)throw Error(`Schema is missing a method literal`);let n=ip(t);if(typeof n==`string`)return n;throw Error(`Schema method literal must be a string`)}function Db(e){return{completion:{values:e.slice(0,100),total:e.length,hasMore:e.length>100}}}const Ob={completion:{values:[],hasMore:!1}};var kb=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(`
|
|
159
|
+
`);if(e===-1)return null;let t=this._buffer.toString(`utf8`,0,e).replace(/\r$/,``);return this._buffer=this._buffer.subarray(e+1),Ab(t)}clear(){this._buffer=void 0}};function Ab(e){return vh.parse(JSON.parse(e))}function jb(e){return JSON.stringify(e)+`
|
|
160
160
|
`}var Mb=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 kb({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=jb(e);this._stdout.write(n)?t():this._stdout.once(`drain`,t)})}};function Nb(e,t){let n=e===``?[]:e.replace(/\r\n/g,`
|
|
161
161
|
`).split(`
|
|
162
162
|
`),r=t===``?[]:t.replace(/\r\n/g,`
|
|
@@ -182,7 +182,7 @@ if(!Array.isArray(r))throw Error(`ajv implementation error`);let a=n.name(`valid
|
|
|
182
182
|
`):[m[0],``,...i.split(`
|
|
183
183
|
`)]:[...Wb(m),``,...i.split(`
|
|
184
184
|
`)];let g=[...f,...Wb(h),...p.length?[``,...p]:[]];return`${Wb(g).join(`
|
|
185
|
-
`)}\n`}const Kb=e=>({content:[{type:`text`,text:typeof e==`string`?e:JSON.stringify(e,null,2)}]}),qb=[`database`,`storage`,`service`,`queue`,`auth`,`external_api`],Jb={resource:
|
|
185
|
+
`)}\n`}const Kb=e=>({content:[{type:`text`,text:typeof e==`string`?e:JSON.stringify(e,null,2)}]}),qb=[`database`,`storage`,`service`,`queue`,`auth`,`external_api`],Jb={resource:V().describe(`The resource's name, provider or id (from list_resources)`),inEnvironment:V().optional().describe(`Its current environment, when the same resource exists in several`)};function Yb(e){let t=new Ur(e),n=new yb({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.
|
|
186
186
|
- 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.
|
|
187
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). Don't use deprecated terms.
|
|
188
188
|
- When you start, finish or get blocked on work, update the task (update_task), and attach branches, commits and pull requests as evidence.
|
|
@@ -195,11 +195,11 @@ if(!Array.isArray(r))throw Error(`ajv implementation error`);let a=n.name(`valid
|
|
|
195
195
|
- 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.
|
|
196
196
|
- Docs written in Quirl (source 'quirl' in read_doc), such as PRDs and specs, are created and changed here: create_doc, edit_doc (one section at a time), archive_doc; doc_history shows who changed what. Docs synced from a repo are changed in the repo.
|
|
197
197
|
- Correct what's wrong instead of leaving it: update_feature or withdraw_feature for a feature, update_task or archive_task for a task, propose_capability_update (also its name) for a capability. list_capabilities gives them as data.
|
|
198
|
-
- Resources (databases, hosted services, external APIs) come from quirl sync. If the project runs on something sync can't see from the code, add it with add_resource; correct or relabel one with update_resource (e.g. its environment), and drop a wrong one with remove_resource. Never pass secret values.
|
|
198
|
+
- Resources (databases, hosted services, external APIs) come from quirl sync. If the project runs on something sync can't see from the code, add it with add_resource; correct or relabel one with update_resource (e.g. its environment), and drop a wrong one with remove_resource. Never pass secret values. If tables or endpoints are filed under the wrong resource, move them with move_contracts.
|
|
199
199
|
- A repo is named after its git remote. To give it another name, set "repoName" in its .quirl/project.json (in a folder of repos, { "path", "name" } in "repos") and run quirl sync; everything linked to it stays. remove_repo takes a repo out of the project, only when the person asks.
|
|
200
200
|
- If the project has no capabilities yet, offer to read the codebase and draft them with propose_capability.
|
|
201
|
-
- 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 Kb(await e(t))}catch(e){if(e instanceof Ur)return{...Kb(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()=>zb(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:B().describe(`Words to search for, e.g. 'refund approval limits'`),limit:V().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. source says where it lives: 'quirl' for docs written in Quirl (editable with edit_doc), otherwise the repo or folder it's synced from.`,inputSchema:{doc:B().describe(`Doc id, title or path, e.g. 'docs/adr/004-queues.md'`)}},a(({doc:e})=>t.call(`read_doc`,{...r,p_doc:e})));let o=[`product`,`guideline`,`architecture`,`decision`,`how_to`,`reference`];n.registerTool(`create_doc`,{title:`Write a new doc`,description:`Write a doc in Quirl itself: a PRD, spec or product note with no file behind it. Docs about code that tests or builds rely on belong in their repo, where sync picks them up. Use product for PRDs and specs. Never include secret values.`,inputSchema:{title:B(),body:B().describe(`Markdown. Headings (##, ###) split it into sections edit_doc can change one at a time.`),type:ym(o).optional().describe(`Defaults to reference`)}},a(({title:e,body:n,type:a})=>t.call(`create_doc`,{...r,p_title:e,p_body:n,p_type:a??`reference`,p_agent:i()}))),n.registerTool(`edit_doc`,{title:`Edit a doc written in Quirl`,description:`Change one section of a doc written in Quirl, or the whole doc, without rewriting the rest. A section is named by its heading, or by its path when a heading repeats ('Billing > Refunds'). replace swaps the section's text (keeping its heading, unless the new text starts with one); append adds to the end of it. Without a section, replace rewrites the doc and append adds to its end. Docs synced from a repo or folder are changed there instead. The edit fails if the doc changed since it was read, rather than overwriting that change.`,inputSchema:{doc:B().describe(`Doc id or title`),section:B().optional().describe(`Heading text or path, e.g. 'Scope' or 'Billing > Refunds'`),content:B().describe(`Markdown`),mode:ym([`replace`,`append`]).optional().describe(`Defaults to replace`),title:B().optional().describe(`A new title for the doc`),type:ym(o).optional()}},a(async({doc:e,section:n,content:a,mode:o,title:s,type:c})=>{let l=await t.call(`read_doc`,{...r,p_doc:e});if(!l.editable)throw new Ur(`"${l.title}" comes from ${l.source}. Change it there; sync brings it into Quirl.`);let u;try{u=Gb(l.body,n,a,o??`replace`)}catch(e){throw new Ur(e.message)}return{...await t.call(`update_doc`,{...r,p_doc:l.id,p_title:s??null,p_body:u,p_type:c??null,p_expected_hash:l.contentHash,p_agent:i()}),edited:n??`the whole doc`,sections:Hb(u)}})),n.registerTool(`doc_history`,{title:`A doc's history`,description:`Who changed a doc and when, newest first, with lines added and removed. Pass a version to see what it changed (a diff against the version before), or full to get that version's whole text, e.g. to bring back wording with edit_doc.`,inputSchema:{doc:B().describe(`Doc id or title`),version:V().int().optional(),full:em().optional().describe(`With version: its whole text instead of the diff`)}},a(async({doc:e,version:n,full:i})=>{let a=await t.call(`doc_history`,{...r,p_doc:e,p_limit:n?200:21}),o=a.versions,s=e=>o.find(t=>t.version===e-1);if(n){let e=o.find(e=>e.version===n);if(!e)throw new Ur(`"${a.title}" has no version ${n}; the latest is ${o[0]?.version??0}.`);if(i)return{version:n,title:e.title,body:e.body};let t=s(n);return{version:n,author:e.author??`unknown`,at:e.createdAt,...t&&t.title!==e.title?{renamed:`${t.title} → ${e.title}`}:{},diff:t?Ib(t.body,e.body)||`(no text changes)`:`(first version)`}}return{title:a.title,source:a.source,versions:o.slice(0,20).map(e=>{let t=s(e.version);return{version:e.version,author:e.author??`unknown`,at:e.createdAt,change:t?Pb(Nb(t.body,e.body)):`first version`}})}})),n.registerTool(`archive_doc`,{title:`Archive a doc written in Quirl`,description:`Remove a doc written in Quirl that's no longer true or was a mistake. It's archived and stays in history. Docs synced from a repo or folder are deleted there instead.`,inputSchema:{doc:B().describe(`Doc id or title`),reason:B().optional().describe(`Why, for history`)}},a(({doc:e,reason:n})=>t.call(`archive_doc`,{...r,p_doc:e,p_reason:n??null,p_agent:i()}))),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:B().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 s=(e,t,r,i)=>{n.registerTool(e,r,i),n.registerTool(t,{...r,description:`Old name for ${e}; use ${e}. ${r.description}`},i)};s(`list_tasks`,`list_cards`,{title:`List tasks`,description:`List tasks on the board. Defaults to your own tasks that aren't done.`,inputSchema:{onlyMine:em().optional(),includeDone:em().optional()}},a(({onlyMine:e,includeDone:n})=>t.call(`list_cards`,{...r,p_only_mine:e??!0,p_include_done:n??!1})));let c=`Markdown: short paragraphs, and lists for steps or parts, not one long block.`,l=`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).`,u=B().describe(`Task number, e.g. 'K-104' or '104'`),d=B().optional().describe(`Who does it: "me", a member's email or name (only people on the project), or "none"`);return s(`get_task`,`get_card`,{title:`Get a task`,description:`A task with its feature, docs, dependencies and evidence.`,inputSchema:{task:u.optional(),card:u.optional()}},a(({task:e,card:n})=>t.call(`get_card`,{...r,p_card:e??n}))),s(`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:B(),description:B().optional().describe(`What to do and why. ${c}`),type:ym([`feature_work`,`bug`,`chore`,`research`]).optional(),feature:B().optional().describe(`Feature name or id (e.g. F-4) this task belongs to`),tags:H(B()).optional().describe(l),assignee:d.describe(`Who does it: "me" (the default), a member's email or name, or "none"`)}},a(async({title:e,description:n,type:a,feature:o,tags:s,assignee:c})=>{let l=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||c)&&await t.call(`update_card`,{...r,p_card:l,p_patch:{...s?.length?{tags:s}:{},...c?{assignee:c}:{}},p_agent:i()}),l})),s(`update_task`,`update_card`,{title:`Update a task`,description:`Move a task, mark it blocked (with a reason) or unblocked, assign it, 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:u.optional(),card:u.optional(),assignee:d,status:ym([`backlog`,`todo`,`in_progress`,`review`,`done`]).optional(),feature:B().optional().describe(`Feature name or id (e.g. F-4) to put the task under; an empty string takes it off its feature`),title:B().optional(),description:B().optional().describe(`Replaces the description. ${c}`),tags:H(B()).optional().describe(`${l} Replaces the current tags.`),blocked:em().optional(),blockedReason:B().optional(),addBranch:U({repo:B(),name:B()}).optional(),addCommit:U({repo:B(),sha:B(),message:B().optional()}).optional(),addPullRequest:U({repo:B(),number:V().int(),url:B(),state:ym([`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(`archive_task`,{title:`Archive a task`,description:`Remove a task that shouldn't be there: a duplicate or a mistake. It's archived and stays in history, and its feature's status is worked out without it. For work that's finished, move it to done instead.`,inputSchema:{task:u,reason:B().optional().describe(`Why, for history`)}},a(({task:e,reason:n})=>t.call(`archive_card`,{...r,p_card:e,p_reason:n??null,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:B(),plain:B().describe(`What it means, for someone non-technical`),technical:B().describe(`What it means in the code`),kind:ym([`concept`,`tag`,`name`]).optional(),tagSet:B().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:B().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:B().describe(`The term or tag to retire`),replaceWith:B().optional().describe(`An approved term to say instead, if there is one`),reason:B().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:ym([`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:B().describe(`The flag's id, from the briefing or list_flags`),decision:ym([`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:B().describe(`The flag's id, from the briefing or list_flags`),note:B().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:B().describe(`Capability name or id (e.g. C-12)`),icon:ym(Lb)}},a(({capability:e,icon:n})=>t.call(`set_capability_icon`,{...r,p_capability:e,p_icon:n,p_agent:i()}))),n.registerTool(`add_resource`,{title:`Add or fill in a resource`,description:"Record a service the project runs on that `quirl sync` can't see from the code: a hosted database another team runs, a SaaS named only in docs or the console, a staging copy. Sync already finds most things from env templates, docker-compose and client packages, so check Stack first (lookup) and don't add what it found. A resource with the same provider and environment is filled in rather than duplicated: the fields you give are set, and repos and capabilities are added to its links. Never pass URLs with credentials, keys or other secret values.",inputSchema:{name:B().describe(`What the team calls it, e.g. "Postgres", "Stripe"`),type:ym(qb),provider:B().optional().describe(`Who runs it, e.g. "Google Cloud SQL", "Stripe". Resources are matched on this. Defaults to the name.`),description:B().optional().describe(`One plain sentence on what the project uses it for`),technical:B().optional().describe(`Technical notes for developers: setup, access, limits`),environment:B().optional().describe(`Defaults to "production"; e.g. "staging"`),repos:H(B()).optional().describe(`Repos that use it, by name`),capabilities:H(B()).optional().describe(`Capabilities that run on it, by name or id (e.g. C-12)`)}},a(e=>t.call(`add_resource`,{...r,p_name:e.name,p_type:e.type,p_provider:e.provider??null,p_description:e.description??null,p_technical:e.technical??null,p_environment:e.environment??null,p_repos:e.repos??null,p_capabilities:e.capabilities??null,p_agent:i()}))),n.registerTool(`list_resources`,{title:`List the project's resources`,description:`Every resource on Stack: name, type, provider, environment, whether sync found it or someone added it, the repos that use it and the capabilities that run on it.`,inputSchema:{}},a(()=>t.call(`list_resources`,r))),n.registerTool(`update_resource`,{title:`Change a resource`,description:`Correct a resource: rename it, relabel its environment (a scanned one that's really the local docker database becomes 'local'), or change its type, provider, descriptions or links. Only the fields you pass change. repos and capabilities replace its links; use add_resource to add to them. Sync keeps updating a relabelled resource instead of adding it again. Never pass secret values.`,inputSchema:{...Jb,name:B().optional(),type:ym(qb).optional(),provider:B().optional(),environment:B().optional().describe(`e.g. "production", "staging", "dev", "local"`),description:B().optional().describe(`One plain sentence on what the project uses it for`),technical:B().optional().describe(`Notes for developers`),repos:H(B()).optional().describe(`Replaces the repos that use it`),capabilities:H(B()).optional().describe(`Replaces the capabilities that run on it (names or C-12)`)}},a(e=>t.call(`update_resource`,{...r,p_resource:e.resource,p_in_environment:e.inEnvironment??null,p_name:e.name??null,p_type:e.type??null,p_provider:e.provider??null,p_environment:e.environment??null,p_description:e.description??null,p_technical:e.technical??null,p_repos:e.repos??null,p_capabilities:e.capabilities??null,p_agent:i()}))),n.registerTool(`remove_resource`,{title:`Remove a wrong resource`,description:`Remove a resource that isn't one: a false match from sync, a duplicate, something no longer used. It's archived, stays in history, and sync won't add it again. A resource holding endpoints or tables from sync can't be removed; relabel it instead.`,inputSchema:{...Jb,reason:B().optional().describe(`Why it's wrong, for history`)}},a(e=>t.call(`remove_resource`,{...r,p_resource:e.resource,p_in_environment:e.inEnvironment??null,p_reason:e.reason??null,p_agent:i()}))),n.registerTool(`remove_repo`,{title:`Remove a repo`,description:"Remove a repo from the project, for admins: one that's retired, or was imported by mistake. Its dependencies, endpoints, tables and synced docs are archived with it, and it's unlinked from capabilities, tasks and resources. Sync skips it from then on; running `quirl init` in it adds it back. Only on the person's request: confirm with them first. To rename a repo instead, set its name in .quirl/project.json and sync.",inputSchema:{repo:B().describe(`The repo's name, URL or id`),reason:B().optional().describe(`Why it's removed, for history`)}},a(e=>t.call(`remove_repo`,{...r,p_repo:e.repo,p_reason:e.reason??null,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:em().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:B().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:B().describe(`Short name, e.g. 'Repeat appointments'`),description:B().describe(`What changes for the user, in plain words. Markdown: short paragraphs, and lists for parts`),capability:B().optional().describe(`Capability name or id (e.g. C-12) it changes. Leave it out when the feature creates a new capability`),tags:H(B()).optional().describe(`Kind of change: e.g. New, Improvement, Visual, Fix, Performance, Security, Removal, Internal (the feature_change set in quirl_context)`),reason:B().optional().describe(`Why it's worth doing`),icon:ym(Lb).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:B().describe(`Feature name or id (e.g. F-4)`),icon:ym(Lb)}},a(({feature:e,icon:n})=>t.call(`set_feature_icon`,{...r,p_feature:e,p_icon:n,p_agent:i()}))),n.registerTool(`update_feature`,{title:`Correct a feature`,description:`Fix a feature's name, description or the capability it changes, e.g. after requesting it with the wrong one. Only the fields you pass change; it shows in the feature's history. Tags: tag_feature; icon: set_feature_icon.`,inputSchema:{feature:B().describe(`Feature name or id (e.g. F-4)`),name:B().optional(),description:B().optional().describe(`What changes for the user, in plain words. Markdown: short paragraphs, and lists for parts`),capability:B().optional().describe(`The capability it changes (name or C-12), or "none" when it creates a new one`)}},a(({feature:e,name:n,description:a,capability:o})=>t.call(`update_feature`,{...r,p_feature:e,p_name:n??null,p_description:a??null,p_capability:o??null,p_agent:i()}))),n.registerTool(`withdraw_feature`,{title:`Withdraw a feature`,description:`Remove a feature that shouldn't be there: a duplicate, a mistake, or an idea dropped before any work. It's archived and stays in history. One that shipped can't be withdrawn; move or archive its tasks first (update_task, archive_task).`,inputSchema:{feature:B().describe(`Feature name or id (e.g. F-4)`),reason:B().optional().describe(`Why, for history`)}},a(({feature:e,reason:n})=>t.call(`withdraw_feature`,{...r,p_feature:e,p_reason:n??null,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:B().describe(`Feature name or id (e.g. F-4)`),tags:H(B()).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(`list_capabilities`,{title:`List the capabilities`,description:`Every capability as data: id (C-12), name, status, icon, the capability it's part of, what it does, what it relies on, its tags and the features changing it. Retired ones only with includeRetired.`,inputSchema:{includeRetired:em().optional()}},a(({includeRetired:e})=>t.call(`list_capabilities`,{...r,p_include_retired:e??!1}))),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:B().describe(`Short name, e.g. 'Online booking'`),whatItDoes:B().describe(`One or two plain sentences, no jargon`),technical:B().optional().describe(`Where it lives in the code and how it works. Markdown: short paragraphs, and lists for parts, not one long block`),features:H(B()).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:B().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:B().describe(`Capability name or id (e.g. C-12)`),reason:B().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 name or description for a capability when the code no longer matches it. A person approves it.`,inputSchema:{capability:B().describe(`Capability name or id (e.g. C-12)`),field:ym([`name`,`what_it_does`,`technical_description`]),after:B().describe(`The new name, or the corrected text. Markdown: short paragraphs, and lists for parts, not one long block`),reason:B().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:B().describe(`Capability name or id (e.g. C-12)`),howItWorks:H(B()).optional().describe(`3 to 5 plain-language steps, as the user experiences it`),reliesOn:H(U({capability:B().describe(`Capability name or id (e.g. C-12)`),label:B().describe(`How it relies on it, read before the name, e.g. 'extends'`)})).optional(),parent:B().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:H(B()).optional().describe(`Repo names`),resources:H(B()).optional().describe(`Resource names it runs on`),terms:H(B()).optional().describe(`Glossary terms`),docs:H(B()).optional().describe(`Doc titles, or <repo>/<path> (e.g. quirl/AGENTS.md) when titles repeat`),tags:H(B()).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:B().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 Xb(e){await Yb(e).connect(new Mb)}const Zb=`0.1.8`,Qb=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 $b(){return{apiUrl:process.env.QUIRL_API_URL??Qb.apiUrl,publishableKey:process.env.QUIRL_PUBLISHABLE_KEY??Qb.publishableKey,appUrl:process.env.QUIRL_APP_URL??Qb.appUrl}}const ex=()=>x(process.env.XDG_CONFIG_HOME??x(h(),`.config`),`quirl`),tx=()=>x(ex(),`credentials.json`);async function nx(){try{return JSON.parse(await u(tx(),`utf8`))}catch{return{}}}async function rx(){return process.env.QUIRL_KEY?{apiUrl:$b().apiUrl,key:process.env.QUIRL_KEY,email:``}:(await nx())[$b().apiUrl]??null}async function ix(e){let t=await nx();t[e.apiUrl]=e,await l(ex(),{recursive:!0,mode:448}),await m(tx(),`${JSON.stringify(t,null,` `)}\n`,{mode:384}),await s(tx(),384)}async function ax(){let e=await nx();delete e[$b().apiUrl],Object.keys(e).length?await m(tx(),`${JSON.stringify(e,null,` `)}\n`,{mode:384}):await f(tx(),{force:!0})}async function ox(){let e=$b();return{apiUrl:e.apiUrl,publishableKey:e.publishableKey,key:(await rx())?.key??``}}function sx(e){return(e.repos??[]).map(e=>typeof e==`string`?{path:e}:e)}function cx(e=process.cwd()){try{return a(`git`,[`rev-parse`,`--show-toplevel`],{cwd:e,stdio:[`ignore`,`pipe`,`ignore`]}).toString().trim()}catch{return e}}const lx=e=>x(e,`.quirl`,`project.json`);async function ux(e=process.cwd()){let t=e;for(;;)try{return{root:t,link:JSON.parse(await u(lx(t),`utf8`))}}catch{let e=y(t);if(e===t)return null;t=e}}async function dx(e,t){await l(x(e,`.quirl`),{recursive:!0}),await m(lx(e),`${JSON.stringify(t,null,` `)}\n`)}function fx(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];r===`*`?e[n+1]===`*`?(t+=e[n+2]===`/`?`(?:.*/)?`:`.*`,n+=e[n+2]===`/`?2:1):t+=`[^/]*`:t+=r===`?`?`[^/]`:r.replace(/[.+^${}()|[\]\\]/g,`\\$&`)}return RegExp(`^${t}$`)}function px(e){let t=[];for(let n of e.split(/\r?\n/)){let e=n.replace(/\s+$/,``);if(!e||e.startsWith(`#`))continue;let r=e.startsWith(`!`);r&&(e=e.slice(1));let i=e.endsWith(`/`);i&&(e=e.slice(0,-1));let a=e.includes(`/`);e=e.replace(/^\//,``);let o=fx(e).source.slice(1,-1);t.push({regex:RegExp(a?`^${o}$`:`^(?:.*/)?${o}$`),negate:r,dirOnly:i})}return t}function mx(e,t){if(!e.length)return!1;let n=t.split(`/`);for(let t=1;t<=n.length;t++){let r=n.slice(0,t).join(`/`),i=t<n.length,a=!1;for(let t of e)(!t.dirOnly||i)&&t.regex.test(r)&&(a=!t.negate);if(a)return!0}return!1}async function hx(e){try{return px(await u(_.join(e,`.quirlignore`),`utf8`))}catch{return[]}}function gx(e,t){return new Promise(n=>{if(!t.length)return n(/* @__PURE__ */ new Set);i(`git`,[`check-ignore`,`--stdin`,`-z`],{cwd:e,maxBuffer:268435456,timeout:6e4},(e,t)=>n(new Set(String(t??``).split(`\0`).filter(Boolean)))).stdin?.end(`${t.join(`\0`)}\0`)})}const _x=n(i),vx=/* @__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`]),yx=1048576,bx=2e5;async function xx(e){let t=[],n=await hx(e),r=(await Cx(e,t)).filter(e=>!mx(n,e.path)),i=await gx(e,r.map(e=>e.path)),a=r.filter(e=>!i.has(e.path)),o=new Map(a.map(e=>[e.path,e]));return{root:e,files:a,warnings:t,file:e=>o.get(e),async readText(e,n=yx){if(e.size>n)return t.push(`${e.path}: skipped, ${Ax(e.size)} is over the ${Ax(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 Sx(e,t){let n=[],r=await hx(e),{stdout:i}=await _x(`git`,[`ls-tree`,`-r`,`-l`,`-z`,`--full-tree`,t],{cwd:e,maxBuffer:268435456,timeout:6e4}),a=[];for(let e of i.split(`\0`)){let t=e.indexOf(` `);if(t===-1)continue;let[i,o,s,c]=e.slice(0,t).trim().split(/\s+/),l=e.slice(t+1);if(o===`blob`&&i!==`120000`&&s&&!l.split(`/`).some(e=>vx.has(e))&&!mx(r,l)){if(a.length>=bx){n.push(`Stopped after ${bx} files; the rest of the tree was not scanned`);break}a.push({path:l,absolutePath:s,size:Number(c)||0})}}wx(a);let o=new Map(a.map(e=>[e.path,e]));return{root:e,files:a,warnings:n,file:e=>o.get(e),async readText(t,r=yx){if(t.size>r)return n.push(`${t.path}: skipped, ${Ax(t.size)} is over the ${Ax(r)} limit`),null;try{let{stdout:n}=await _x(`git`,[`cat-file`,`blob`,t.absolutePath],{cwd:e,maxBuffer:r+1024,timeout:3e4});return n}catch(e){return n.push(`${t.path}: could not be read (${Ox(e)})`),null}}}}async function Cx(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()){!vx.has(o.name)&&!C(_.join(e,a,`.git`))&&r.push(a);continue}if(!o.isFile())continue;if(n.length>=bx)return t.push(`Stopped after ${bx} files; the rest of the tree was not scanned`),wx(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 wx(n)}function wx(e){return e.sort((e,t)=>e.path<t.path?-1:+(e.path>t.path))}function Tx(e){let t=e.lastIndexOf(`/`);return t===-1?e:e.slice(t+1)}function Ex(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}function Dx(e,t){return e?`${e}/${t}`:t}function Ox(e){return Kr(e instanceof Error?e.message:String(e))}function Z(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function kx(e){return typeof e==`string`?e:void 0}function Ax(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:`${Math.ceil(e/1024)} KB`}async function jx({hook:e=!1}={}){let t=await ux();if(!t){if(e)return;throw Error("This folder isn't linked to a Quirl project. Run `quirl init`.")}try{let n=await new Wr(await ox()).context(t.link.projectId);process.stdout.write(`${zb(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 (${Ox(n)}). The quirl MCP tools may still work.\n`)}}const Mx=process.stdout.isTTY&&!process.env.NO_COLOR,Nx=e=>t=>Mx?`\x1b[${e}m${t}\x1b[0m`:t,Px=Nx(1),Q=Nx(2),Fx=Nx(32),Ix=Nx(31),Lx=Nx(36),Rx=e=>console.log(`${Fx(`✓`)} ${e}`),zx=e=>console.log(` ${e}`),Bx=(e,t)=>console.log(`\n${e} ${t}`),Vx=e=>console.log(` ${e}`);function Hx(e){if(!Mx)return Vx(Q(e)),{stop:()=>{}};let t=0,n=setInterval(()=>{process.stdout.write(`\r ${Lx(`⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏`[t++%10]??``)} ${Q(e)}`)},80);return{stop:()=>{clearInterval(n),process.stdout.write(`\r\x1B[2K`)}}}var Ux=class extends Error{};async function Wx(e,t=``){if(!process.stdin.isTTY)return t;let n=w({input:process.stdin,output:process.stdout});try{return(await n.question(e)).trim()||t}finally{n.close()}}async function Gx(e,t){let n=await Wx(`${e} ${Q(t?`[Y/n]`:`[y/N]`)} `,t?`y`:`n`);return/^y/i.test(n)}function Kx(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 qx=`.quirl-export.json`,Jx=e=>e.toLowerCase().normalize(`NFKD`).replace(/[̀-ͯ]/g,``).replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,80)||`untitled`;function Yx(e){return`---\n${[[`title`,e.title],[`type`,e.type],[`status`,e.status],[`source`,e.source],[`alwaysLoad`,e.alwaysLoad],[`id`,e.id],[`created`,e.createdAt],[`updated`,e.updatedAt]].map(([e,t])=>`${e}: ${JSON.stringify(t)}`).join(`
|
|
202
|
-
`)}\n---\n\n`}async function Xx({dir:e=`quirl-docs`,all:t=!1}){let n=await ux();if(!n)throw new Ux("This folder isn't linked to a Quirl project. Run `quirl init`.");let r=new
|
|
201
|
+
- 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 Kb(await e(t))}catch(e){if(e instanceof Hr)return{...Kb(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()=>zb(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. source says where it lives: 'quirl' for docs written in Quirl (editable with edit_doc), otherwise the repo or folder it's synced from.`,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})));let o=[`product`,`guideline`,`architecture`,`decision`,`how_to`,`reference`];n.registerTool(`create_doc`,{title:`Write a new doc`,description:`Write a doc in Quirl itself: a PRD, spec or product note with no file behind it. Docs about code that tests or builds rely on belong in their repo, where sync picks them up. Use product for PRDs and specs. Never include secret values.`,inputSchema:{title:V(),body:V().describe(`Markdown. Headings (##, ###) split it into sections edit_doc can change one at a time.`),type:vm(o).optional().describe(`Defaults to reference`)}},a(({title:e,body:n,type:a})=>t.call(`create_doc`,{...r,p_title:e,p_body:n,p_type:a??`reference`,p_agent:i()}))),n.registerTool(`edit_doc`,{title:`Edit a doc written in Quirl`,description:`Change one section of a doc written in Quirl, or the whole doc, without rewriting the rest. A section is named by its heading, or by its path when a heading repeats ('Billing > Refunds'). replace swaps the section's text (keeping its heading, unless the new text starts with one); append adds to the end of it. Without a section, replace rewrites the doc and append adds to its end. Docs synced from a repo or folder are changed there instead. The edit fails if the doc changed since it was read, rather than overwriting that change.`,inputSchema:{doc:V().describe(`Doc id or title`),section:V().optional().describe(`Heading text or path, e.g. 'Scope' or 'Billing > Refunds'`),content:V().describe(`Markdown`),mode:vm([`replace`,`append`]).optional().describe(`Defaults to replace`),title:V().optional().describe(`A new title for the doc`),type:vm(o).optional()}},a(async({doc:e,section:n,content:a,mode:o,title:s,type:c})=>{let l=await t.call(`read_doc`,{...r,p_doc:e});if(!l.editable)throw new Hr(`"${l.title}" comes from ${l.source}. Change it there; sync brings it into Quirl.`);let u;try{u=Gb(l.body,n,a,o??`replace`)}catch(e){throw new Hr(e.message)}return{...await t.call(`update_doc`,{...r,p_doc:l.id,p_title:s??null,p_body:u,p_type:c??null,p_expected_hash:l.contentHash,p_agent:i()}),edited:n??`the whole doc`,sections:Hb(u)}})),n.registerTool(`doc_history`,{title:`A doc's history`,description:`Who changed a doc and when, newest first, with lines added and removed. Pass a version to see what it changed (a diff against the version before), or full to get that version's whole text, e.g. to bring back wording with edit_doc.`,inputSchema:{doc:V().describe(`Doc id or title`),version:H().int().optional(),full:$p().optional().describe(`With version: its whole text instead of the diff`)}},a(async({doc:e,version:n,full:i})=>{let a=await t.call(`doc_history`,{...r,p_doc:e,p_limit:n?200:21}),o=a.versions,s=e=>o.find(t=>t.version===e-1);if(n){let e=o.find(e=>e.version===n);if(!e)throw new Hr(`"${a.title}" has no version ${n}; the latest is ${o[0]?.version??0}.`);if(i)return{version:n,title:e.title,body:e.body};let t=s(n);return{version:n,author:e.author??`unknown`,at:e.createdAt,...t&&t.title!==e.title?{renamed:`${t.title} → ${e.title}`}:{},diff:t?Ib(t.body,e.body)||`(no text changes)`:`(first version)`}}return{title:a.title,source:a.source,versions:o.slice(0,20).map(e=>{let t=s(e.version);return{version:e.version,author:e.author??`unknown`,at:e.createdAt,change:t?Pb(Nb(t.body,e.body)):`first version`}})}})),n.registerTool(`archive_doc`,{title:`Archive a doc written in Quirl`,description:`Remove a doc written in Quirl that's no longer true or was a mistake. It's archived and stays in history. Docs synced from a repo or folder are deleted there instead.`,inputSchema:{doc:V().describe(`Doc id or title`),reason:V().optional().describe(`Why, for history`)}},a(({doc:e,reason:n})=>t.call(`archive_doc`,{...r,p_doc:e,p_reason:n??null,p_agent:i()}))),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 s=(e,t,r,i)=>{n.registerTool(e,r,i),n.registerTool(t,{...r,description:`Old name for ${e}; use ${e}. ${r.description}`},i)};s(`list_tasks`,`list_cards`,{title:`List tasks`,description:`List tasks on the board. Defaults to your own tasks that aren't done.`,inputSchema:{onlyMine:$p().optional(),includeDone:$p().optional()}},a(({onlyMine:e,includeDone:n})=>t.call(`list_cards`,{...r,p_only_mine:e??!0,p_include_done:n??!1})));let c=`Markdown: short paragraphs, and lists for steps or parts, not one long block.`,l=`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).`,u=V().describe(`Task number, e.g. 'K-104' or '104'`),d=V().optional().describe(`Who does it: "me", a member's email or name (only people on the project), or "none"`);return s(`get_task`,`get_card`,{title:`Get a task`,description:`A task with its feature, docs, dependencies and evidence.`,inputSchema:{task:u.optional(),card:u.optional()}},a(({task:e,card:n})=>t.call(`get_card`,{...r,p_card:e??n}))),s(`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. ${c}`),type:vm([`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(l),assignee:d.describe(`Who does it: "me" (the default), a member's email or name, or "none"`)}},a(async({title:e,description:n,type:a,feature:o,tags:s,assignee:c})=>{let l=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||c)&&await t.call(`update_card`,{...r,p_card:l,p_patch:{...s?.length?{tags:s}:{},...c?{assignee:c}:{}},p_agent:i()}),l})),s(`update_task`,`update_card`,{title:`Update a task`,description:`Move a task, mark it blocked (with a reason) or unblocked, assign it, 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:u.optional(),card:u.optional(),assignee:d,status:vm([`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. ${c}`),tags:U(V()).optional().describe(`${l} Replaces the current tags.`),blocked:$p().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:vm([`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(`archive_task`,{title:`Archive a task`,description:`Remove a task that shouldn't be there: a duplicate or a mistake. It's archived and stays in history, and its feature's status is worked out without it. For work that's finished, move it to done instead.`,inputSchema:{task:u,reason:V().optional().describe(`Why, for history`)}},a(({task:e,reason:n})=>t.call(`archive_card`,{...r,p_card:e,p_reason:n??null,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:vm([`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:vm([`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:vm([`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:vm(Lb)}},a(({capability:e,icon:n})=>t.call(`set_capability_icon`,{...r,p_capability:e,p_icon:n,p_agent:i()}))),n.registerTool(`add_resource`,{title:`Add or fill in a resource`,description:"Record a service the project runs on that `quirl sync` can't see from the code: a hosted database another team runs, a SaaS named only in docs or the console, a staging copy. Sync already finds most things from env templates, docker-compose and client packages, so check Stack first (lookup) and don't add what it found. A resource with the same provider and environment is filled in rather than duplicated: the fields you give are set, and repos and capabilities are added to its links. Never pass URLs with credentials, keys or other secret values.",inputSchema:{name:V().describe(`What the team calls it, e.g. "Postgres", "Stripe"`),type:vm(qb),provider:V().optional().describe(`Who runs it, e.g. "Google Cloud SQL", "Stripe". Resources are matched on this. Defaults to the name.`),description:V().optional().describe(`One plain sentence on what the project uses it for`),technical:V().optional().describe(`Technical notes for developers: setup, access, limits`),environment:V().optional().describe(`Defaults to "production"; e.g. "staging"`),repos:U(V()).optional().describe(`Repos that use it, by name`),capabilities:U(V()).optional().describe(`Capabilities that run on it, by name or id (e.g. C-12)`)}},a(e=>t.call(`add_resource`,{...r,p_name:e.name,p_type:e.type,p_provider:e.provider??null,p_description:e.description??null,p_technical:e.technical??null,p_environment:e.environment??null,p_repos:e.repos??null,p_capabilities:e.capabilities??null,p_agent:i()}))),n.registerTool(`list_resources`,{title:`List the project's resources`,description:`Every resource on Stack: name, type, provider, environment, whether sync found it or someone added it, the repos that use it, the capabilities that run on it, and the tables and endpoints filed under it (per repo, with a few names). Tables in the wrong database or endpoints under the wrong API: fix with move_contracts.`,inputSchema:{}},a(()=>t.call(`list_resources`,r))),n.registerTool(`update_resource`,{title:`Change a resource`,description:`Correct a resource: rename it, relabel its environment (a scanned one that's really the local docker database becomes 'local'), or change its type, provider, descriptions or links. Only the fields you pass change. repos and capabilities replace its links; use add_resource to add to them. Sync keeps updating a relabelled resource instead of adding it again. Never pass secret values.`,inputSchema:{...Jb,name:V().optional(),type:vm(qb).optional(),provider:V().optional(),environment:V().optional().describe(`e.g. "production", "staging", "dev", "local"`),description:V().optional().describe(`One plain sentence on what the project uses it for`),technical:V().optional().describe(`Notes for developers`),repos:U(V()).optional().describe(`Replaces the repos that use it`),capabilities:U(V()).optional().describe(`Replaces the capabilities that run on it (names or C-12)`)}},a(e=>t.call(`update_resource`,{...r,p_resource:e.resource,p_in_environment:e.inEnvironment??null,p_name:e.name??null,p_type:e.type??null,p_provider:e.provider??null,p_environment:e.environment??null,p_description:e.description??null,p_technical:e.technical??null,p_repos:e.repos??null,p_capabilities:e.capabilities??null,p_agent:i()}))),n.registerTool(`remove_resource`,{title:`Remove a wrong resource`,description:`Remove a resource that isn't one: a false match from sync, a duplicate, something no longer used. It's archived, stays in history, and sync won't add it again. A resource holding endpoints or tables from sync can't be removed; relabel it instead.`,inputSchema:{...Jb,reason:V().optional().describe(`Why it's wrong, for history`)}},a(e=>t.call(`remove_resource`,{...r,p_resource:e.resource,p_in_environment:e.inEnvironment??null,p_reason:e.reason??null,p_agent:i()}))),n.registerTool(`move_contracts`,{title:`Move tables or endpoints to another resource`,description:`Correct where sync filed a repo's tables (which database) or endpoints (which API). Without names, all of the repo's tables or endpoints move and later syncs put new ones there too. With names, only those move and sync leaves them there. list_resources shows what's filed where.`,inputSchema:{repo:V().describe(`The repo they come from: name, URL or id`),kind:vm([`tables`,`endpoints`]),to:V().describe(`The resource they belong to: name, provider or id`),toEnvironment:V().optional().describe(`Its environment, when it exists in several`),names:U(V()).optional().describe(`Only these, e.g. ["bookings"] or ["GET /bookings"]; leave out to move all`)}},a(e=>t.call(`move_contracts`,{...r,p_repo:e.repo,p_kind:e.kind,p_to:e.to,p_in_environment:e.toEnvironment??null,p_names:e.names??null,p_agent:i()}))),n.registerTool(`remove_repo`,{title:`Remove a repo`,description:"Remove a repo from the project, for admins: one that's retired, or was imported by mistake. Its dependencies, endpoints, tables and synced docs are archived with it, and it's unlinked from capabilities, tasks and resources. Sync skips it from then on; running `quirl init` in it adds it back. Only on the person's request: confirm with them first. To rename a repo instead, set its name in .quirl/project.json and sync.",inputSchema:{repo:V().describe(`The repo's name, URL or id`),reason:V().optional().describe(`Why it's removed, for history`)}},a(e=>t.call(`remove_repo`,{...r,p_repo:e.repo,p_reason:e.reason??null,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:$p().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:vm(Lb).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:vm(Lb)}},a(({feature:e,icon:n})=>t.call(`set_feature_icon`,{...r,p_feature:e,p_icon:n,p_agent:i()}))),n.registerTool(`update_feature`,{title:`Correct a feature`,description:`Fix a feature's name, description or the capability it changes, e.g. after requesting it with the wrong one. Only the fields you pass change; it shows in the feature's history. Tags: tag_feature; icon: set_feature_icon.`,inputSchema:{feature:V().describe(`Feature name or id (e.g. F-4)`),name:V().optional(),description:V().optional().describe(`What changes for the user, in plain words. Markdown: short paragraphs, and lists for parts`),capability:V().optional().describe(`The capability it changes (name or C-12), or "none" when it creates a new one`)}},a(({feature:e,name:n,description:a,capability:o})=>t.call(`update_feature`,{...r,p_feature:e,p_name:n??null,p_description:a??null,p_capability:o??null,p_agent:i()}))),n.registerTool(`withdraw_feature`,{title:`Withdraw a feature`,description:`Remove a feature that shouldn't be there: a duplicate, a mistake, or an idea dropped before any work. It's archived and stays in history. One that shipped can't be withdrawn; move or archive its tasks first (update_task, archive_task).`,inputSchema:{feature:V().describe(`Feature name or id (e.g. F-4)`),reason:V().optional().describe(`Why, for history`)}},a(({feature:e,reason:n})=>t.call(`withdraw_feature`,{...r,p_feature:e,p_reason:n??null,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(`list_capabilities`,{title:`List the capabilities`,description:`Every capability as data: id (C-12), name, status, icon, the capability it's part of, what it does, what it relies on, its tags and the features changing it. Retired ones only with includeRetired.`,inputSchema:{includeRetired:$p().optional()}},a(({includeRetired:e})=>t.call(`list_capabilities`,{...r,p_include_retired:e??!1}))),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 name or 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:vm([`name`,`what_it_does`,`technical_description`]),after:V().describe(`The new name, or 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 Xb(e){await Yb(e).connect(new Mb)}const Zb=`0.1.9`,Qb=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 $b(){return{apiUrl:process.env.QUIRL_API_URL??Qb.apiUrl,publishableKey:process.env.QUIRL_PUBLISHABLE_KEY??Qb.publishableKey,appUrl:process.env.QUIRL_APP_URL??Qb.appUrl}}const ex=()=>x(process.env.XDG_CONFIG_HOME??x(h(),`.config`),`quirl`),tx=()=>x(ex(),`credentials.json`);async function nx(){try{return JSON.parse(await u(tx(),`utf8`))}catch{return{}}}async function rx(){return process.env.QUIRL_KEY?{apiUrl:$b().apiUrl,key:process.env.QUIRL_KEY,email:``}:(await nx())[$b().apiUrl]??null}async function ix(e){let t=await nx();t[e.apiUrl]=e,await l(ex(),{recursive:!0,mode:448}),await m(tx(),`${JSON.stringify(t,null,` `)}\n`,{mode:384}),await s(tx(),384)}async function ax(){let e=await nx();delete e[$b().apiUrl],Object.keys(e).length?await m(tx(),`${JSON.stringify(e,null,` `)}\n`,{mode:384}):await f(tx(),{force:!0})}async function ox(){let e=$b();return{apiUrl:e.apiUrl,publishableKey:e.publishableKey,key:(await rx())?.key??``}}function sx(e){return(e.repos??[]).map(e=>typeof e==`string`?{path:e}:e)}function cx(e=process.cwd()){try{return a(`git`,[`rev-parse`,`--show-toplevel`],{cwd:e,stdio:[`ignore`,`pipe`,`ignore`]}).toString().trim()}catch{return e}}const lx=e=>x(e,`.quirl`,`project.json`);async function ux(e=process.cwd()){let t=e;for(;;)try{return{root:t,link:JSON.parse(await u(lx(t),`utf8`))}}catch{let e=y(t);if(e===t)return null;t=e}}async function dx(e,t){await l(x(e,`.quirl`),{recursive:!0}),await m(lx(e),`${JSON.stringify(t,null,` `)}\n`)}function fx(e){let t=``;for(let n=0;n<e.length;n++){let r=e[n];r===`*`?e[n+1]===`*`?(t+=e[n+2]===`/`?`(?:.*/)?`:`.*`,n+=e[n+2]===`/`?2:1):t+=`[^/]*`:t+=r===`?`?`[^/]`:r.replace(/[.+^${}()|[\]\\]/g,`\\$&`)}return RegExp(`^${t}$`)}function px(e){let t=[];for(let n of e.split(/\r?\n/)){let e=n.replace(/\s+$/,``);if(!e||e.startsWith(`#`))continue;let r=e.startsWith(`!`);r&&(e=e.slice(1));let i=e.endsWith(`/`);i&&(e=e.slice(0,-1));let a=e.includes(`/`);e=e.replace(/^\//,``);let o=fx(e).source.slice(1,-1);t.push({regex:RegExp(a?`^${o}$`:`^(?:.*/)?${o}$`),negate:r,dirOnly:i})}return t}function mx(e,t){if(!e.length)return!1;let n=t.split(`/`);for(let t=1;t<=n.length;t++){let r=n.slice(0,t).join(`/`),i=t<n.length,a=!1;for(let t of e)(!t.dirOnly||i)&&t.regex.test(r)&&(a=!t.negate);if(a)return!0}return!1}async function hx(e){try{return px(await u(_.join(e,`.quirlignore`),`utf8`))}catch{return[]}}function gx(e,t){return new Promise(n=>{if(!t.length)return n(/* @__PURE__ */ new Set);i(`git`,[`check-ignore`,`--stdin`,`-z`],{cwd:e,maxBuffer:268435456,timeout:6e4},(e,t)=>n(new Set(String(t??``).split(`\0`).filter(Boolean)))).stdin?.end(`${t.join(`\0`)}\0`)})}const _x=n(i),vx=/* @__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`]),yx=1048576,bx=2e5;async function xx(e){let t=[],n=await hx(e),r=(await Cx(e,t)).filter(e=>!mx(n,e.path)),i=await gx(e,r.map(e=>e.path)),a=r.filter(e=>!i.has(e.path)),o=new Map(a.map(e=>[e.path,e]));return{root:e,files:a,warnings:t,file:e=>o.get(e),async readText(e,n=yx){if(e.size>n)return t.push(`${e.path}: skipped, ${Ax(e.size)} is over the ${Ax(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 Sx(e,t){let n=[],r=await hx(e),{stdout:i}=await _x(`git`,[`ls-tree`,`-r`,`-l`,`-z`,`--full-tree`,t],{cwd:e,maxBuffer:268435456,timeout:6e4}),a=[];for(let e of i.split(`\0`)){let t=e.indexOf(` `);if(t===-1)continue;let[i,o,s,c]=e.slice(0,t).trim().split(/\s+/),l=e.slice(t+1);if(o===`blob`&&i!==`120000`&&s&&!l.split(`/`).some(e=>vx.has(e))&&!mx(r,l)){if(a.length>=bx){n.push(`Stopped after ${bx} files; the rest of the tree was not scanned`);break}a.push({path:l,absolutePath:s,size:Number(c)||0})}}wx(a);let o=new Map(a.map(e=>[e.path,e]));return{root:e,files:a,warnings:n,file:e=>o.get(e),async readText(t,r=yx){if(t.size>r)return n.push(`${t.path}: skipped, ${Ax(t.size)} is over the ${Ax(r)} limit`),null;try{let{stdout:n}=await _x(`git`,[`cat-file`,`blob`,t.absolutePath],{cwd:e,maxBuffer:r+1024,timeout:3e4});return n}catch(e){return n.push(`${t.path}: could not be read (${Ox(e)})`),null}}}}async function Cx(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()){!vx.has(o.name)&&!C(_.join(e,a,`.git`))&&r.push(a);continue}if(!o.isFile())continue;if(n.length>=bx)return t.push(`Stopped after ${bx} files; the rest of the tree was not scanned`),wx(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 wx(n)}function wx(e){return e.sort((e,t)=>e.path<t.path?-1:+(e.path>t.path))}function Tx(e){let t=e.lastIndexOf(`/`);return t===-1?e:e.slice(t+1)}function Ex(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}function Dx(e,t){return e?`${e}/${t}`:t}function Ox(e){return Gr(e instanceof Error?e.message:String(e))}function Z(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function kx(e){return typeof e==`string`?e:void 0}function Ax(e){return e>=1048576?`${(e/1048576).toFixed(1)} MB`:`${Math.ceil(e/1024)} KB`}async function jx({hook:e=!1}={}){let t=await ux();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 ox()).context(t.link.projectId);process.stdout.write(`${zb(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 (${Ox(n)}). The quirl MCP tools may still work.\n`)}}const Mx=process.stdout.isTTY&&!process.env.NO_COLOR,Nx=e=>t=>Mx?`\x1b[${e}m${t}\x1b[0m`:t,Px=Nx(1),Q=Nx(2),Fx=Nx(32),Ix=Nx(31),Lx=Nx(36),Rx=e=>console.log(`${Fx(`✓`)} ${e}`),zx=e=>console.log(` ${e}`),Bx=(e,t)=>console.log(`\n${e} ${t}`),Vx=e=>console.log(` ${e}`);function Hx(e){if(!Mx)return Vx(Q(e)),{stop:()=>{}};let t=0,n=setInterval(()=>{process.stdout.write(`\r ${Lx(`⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏`[t++%10]??``)} ${Q(e)}`)},80);return{stop:()=>{clearInterval(n),process.stdout.write(`\r\x1B[2K`)}}}var Ux=class extends Error{};async function Wx(e,t=``){if(!process.stdin.isTTY)return t;let n=w({input:process.stdin,output:process.stdout});try{return(await n.question(e)).trim()||t}finally{n.close()}}async function Gx(e,t){let n=await Wx(`${e} ${Q(t?`[Y/n]`:`[y/N]`)} `,t?`y`:`n`);return/^y/i.test(n)}function Kx(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 qx=`.quirl-export.json`,Jx=e=>e.toLowerCase().normalize(`NFKD`).replace(/[̀-ͯ]/g,``).replace(/[^a-z0-9]+/g,`-`).replace(/^-+|-+$/g,``).slice(0,80)||`untitled`;function Yx(e){return`---\n${[[`title`,e.title],[`type`,e.type],[`status`,e.status],[`source`,e.source],[`alwaysLoad`,e.alwaysLoad],[`id`,e.id],[`created`,e.createdAt],[`updated`,e.updatedAt]].map(([e,t])=>`${e}: ${JSON.stringify(t)}`).join(`
|
|
202
|
+
`)}\n---\n\n`}async function Xx({dir:e=`quirl-docs`,all:t=!1}){let n=await ux();if(!n)throw new Ux("This folder isn't linked to a Quirl project. Run `quirl init`.");let r=new Ur(await ox()),i=_.resolve(e);Bx(`📤`,`Exporting ${t?`all`:`Quirl-written`} docs from ${Px(n.link.name)}`);let a=[];for(let e=0;;e+=100){let i=await r.call(`export_docs`,{p_project:n.link.projectId,p_only_quirl:!t,p_offset:e,p_limit:100});if(a.push(...i),i.length<100)break}let o=[],s=/* @__PURE__ */ new Set;await l(i,{recursive:!0});for(let e of a){let t=`${e.type}/${Jx(e.title)}.md`;for(let n=2;s.has(t);n++)t=`${e.type}/${Jx(e.title)}-${n}.md`;s.add(t),await l(_.join(i,e.type),{recursive:!0}),await m(_.join(i,t),Yx(e)+e.body.replace(/\n*$/,`
|
|
203
203
|
`)),o.push(t)}let c=0;try{let e=JSON.parse(await u(_.join(i,qx),`utf8`));for(let t of e.files??[])s.has(t)||t.includes(`..`)||(await f(_.join(i,t),{force:!0}),c++)}catch{}await m(_.join(i,qx),`${JSON.stringify({project:n.link.project,exportedAt:(/* @__PURE__ */ new Date()).toISOString(),all:t,files:o},null,` `)}\n`),Vx(`${Fx(`✓`)} ${a.length} ${a.length===1?`doc`:`docs`} written to ${Lx(_.relative(process.cwd(),i)||`.`)}${c?Q(` · ${c} removed`):``}`),t||Vx(Q(`Docs synced from repos are left out; add --all to include them.`)),console.log(``)}async function Zx(e,t=3){let n=[],r=async(e,i)=>{if(C(_.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(`.`)||vx.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 Qx=`<!-- quirl:start -->`,$x=`<!-- quirl:end -->`,eS=`# quirl: keep the project in sync`;function tS(){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 nS=[`QUIRL_SERVER`,`QUIRL_API_URL`,`QUIRL_PUBLISHABLE_KEY`,`QUIRL_APP_URL`];function rS(){return Object.fromEntries(nS.flatMap(e=>process.env[e]?[[e,process.env[e]]]:[]))}function iS(){return`${Object.entries(rS()).map(([e,t])=>`${e}="${t}" `).join(``)}${tS().shell}`}async function aS(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 oS=async(e,t)=>{await l(y(e),{recursive:!0}),await m(e,`${JSON.stringify(t,null,2)}\n`)};async function sS(e){let t=x(e,`.mcp.json`),n=await aS(t),r=tS();n.mcpServers={...n.mcpServers,quirl:{command:r.command,args:[...r.args,`mcp`],...Object.keys(rS()).length?{env:rS()}:{}}},await oS(t,n)}async function cS(e){let t=x(e,`.claude`,`settings.json`),n=await aS(t),r=n.hooks??{},i=`${iS()} 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 oS(t,n)}async function lS(e,t,n=[]){let r=x(e,`CLAUDE.md`),i=``;try{i=await u(r,`utf8`)}catch{}let a=`${Qx}
|
|
204
204
|
## Quirl
|
|
205
205
|
|
|
@@ -217,20 +217,20 @@ ${$x}`,o=RegExp(`${Qx}[\\s\\S]*?${$x}`);i=o.test(i)?i.replace(o,a):`${i.trimEnd(
|
|
|
217
217
|
|
|
218
218
|
`:``}${a}\n`,await m(r,i)}async function uS(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=`${eS}\n${iS()} sync --quiet --source=git_hook || echo "quirl: sync skipped"\n`,o=r.indexOf(eS);if(o>=0){let e=r.indexOf(`
|
|
219
219
|
`,r.indexOf(`
|
|
220
|
-
`,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 dS({quiet:e=!1}={}){let t=$b(),n=await rx();Bx(`🔑`,Px(`Sign in to Quirl`)),n&&!e&&Vx(Q(`Already signed in as ${n.email}. Signing in again replaces this machine's key.`));let r=
|
|
220
|
+
`,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 dS({quiet:e=!1}={}){let t=$b(),n=await rx();Bx(`🔑`,Px(`Sign in to Quirl`)),n&&!e&&Vx(Q(`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}`;Vx(`Approve this computer in your browser:`),Vx(Lx(a)),Vx(`Check the code matches ${Px(fS(i.user_code))}`),Kx(a);let o=Hx(`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 ix({apiUrl:t.apiUrl,key:e.key,email:n.email}),Vx(`${Fx(`✓`)} Signed in as ${Px(n.email)}`),n}if(e.status!==`pending`)throw o.stop(),new Ux(`Sign-in ${e.status}. Run \`quirl login\` again.`)}throw o.stop(),new Ux("Sign-in timed out. Run `quirl login` again.")}const fS=e=>`${e.slice(0,4)}-${e.slice(4)}`,pS=/* @__PURE__ */ new Set([`docs`,`doc`,`adr`,`adrs`,`architecture`]),mS=/* @__PURE__ */ new Set([`readme.md`,`contributing.md`,`architecture.md`]),hS=/^(changelog|changes|history|license|licence|copying|notice|code_of_conduct|claude|agents)(\.|$)/i,gS=/\.(md|mdx|markdown)$/i,_S=/* @__PURE__ */ new Set([`tasks`,`todo`,`todos`,`issues`,`tickets`,`inbox`,`archive`,`archived`]),vS=/^(package\.json|pyproject\.toml|requirements\.txt|go\.mod|cargo\.toml|composer\.json|gemfile|pom\.xml|build\.gradle(\.kts)?|mix\.exs|pubspec\.yaml)$/i;async function yS(e){let t=e.file(`.quirl/config.json`);if(!t)return{};let n=await e.readText(t);try{let e=JSON.parse(n??`{}`),t=e=>Array.isArray(e)?e.filter(e=>typeof e==`string`):void 0;return{docs:t(e.docs),alwaysLoad:t(e.alwaysLoad)}}catch{return e.warnings.push(`.quirl/config.json: not valid JSON, ignored`),{}}}function bS(e){if(e.files.some(e=>vS.test(Tx(e.path))))return!1;let t=e.files.filter(e=>gS.test(e.path)).length;return t>0&&t*2>=e.files.length}async function xS(e,t={}){let n=px((t.docs??[]).join(`
|
|
221
221
|
`)),r=!t.docs&&bS(e),i=t.alwaysLoad?px(t.alwaysLoad.join(`
|
|
222
222
|
`)):null,a=e=>{let t=Tx(e);if(!gS.test(t)||hS.test(t))return!1;let i=e.toLowerCase().split(`/`);return e.toLowerCase()===`.github/contributing.md`?!0:i.some(e=>e.startsWith(`.`))?!1:SS(e)||mx(n,e)?!0:r&&!i.slice(0,-1).some(e=>_S.has(e))},o=[];for(let t of e.files){if(!a(t.path))continue;let n=await e.readText(t);if(n===null)continue;let r=CS(n)??Tx(t.path).replace(gS,``),s=TS(t.path,r),c;i?(c=mx(i,t.path),c&&n.length>2e4&&e.warnings.push(`${t.path}: listed in alwaysLoad but ${Math.round(n.length/1e3)}k characters; every agent session loads all of it`)):c=ES(t.path,s)&&n.length<=2e4,o.push({path:t.path,title:r,type:s,body:n,alwaysLoadCandidate:c,contentHash:T(`sha256`).update(n).digest(`hex`)})}return o}function SS(e){let t=Tx(e);if(!gS.test(t)||hS.test(t))return!1;let n=e.toLowerCase().split(`/`);return n.length===1?mS.has(n[0]??``):e.toLowerCase()===`.github/contributing.md`||n.slice(0,-1).some(e=>pS.has(e))}function CS(e){let t=e.replace(/\r\n/g,`
|
|
223
|
-
`),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?wS(s):null}function wS(e){return e.replace(/!\[[^\]]*\]\([^)]*\)/g,``).replace(/\[([^\]]*)\]\([^)]*\)/g,`$1`).replace(/[`*_]/g,``).trim()}function TS(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 ES(e,t){if(t===`guideline`)return!0;let n=Tx(e).toLowerCase();return/architecture|conventions?|guidelines?|contributing|style-?guide/.test(n)||t===`architecture`&&/overview/.test(n)}const DS=/* @__PURE__ */ new Set([`claude.md`,`agents.md`,`.cursorrules`]);async function OS(e){let t=[];for(let n of e.files){if(!(DS.has(Tx(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 kS=/\.(md|mdx|markdown|txt)$/i,AS=/\.(pdf|docx?|odt|rtf|pages|pptx?|key|xlsx?|numbers)$/i;async function jS(e){let t=[],n=[];for(let r of e.files){if(r.path.split(`/`).some(e=>e.startsWith(`.`)))continue;let i=Tx(r.path);if(AS.test(i)){n.push(r.path);continue}if(!kS.test(i)||/^(claude|agents)\.md$/i.test(i))continue;let a=await e.readText(r);if(!a?.trim())continue;let o=i.replace(kS,``),s=(gS.test(i)?CS(a):null)??o,c=TS(r.path,s);t.push({path:r.path,title:s,type:c,body:a,alwaysLoadCandidate:!1,contentHash:T(`sha256`).update(a).digest(`hex`)})}return{docs:t,unsupported:n}}const MS=n(i);async function NS(e,t){try{let{stdout:n}=await MS(`git`,t,{cwd:e,timeout:1e4}),r=n.trim();return r===``?null:r}catch{return null}}async function PS(e){let t=await NS(e,[`symbolic-ref`,`--quiet`,`refs/remotes/origin/HEAD`]),n=[...t?[t.replace(/^refs\/remotes\//,``)]:[],`origin/main`,`origin/master`,`main`,`master`];for(let t of n)if(await NS(e,[`rev-parse`,`--verify`,`--quiet`,`${t}^{commit}`]))return{ref:t,branch:t.replace(/^origin\//,``)};return null}async function FS(e){try{return await MS(`git`,[`fetch`,`--quiet`,`--no-tags`,`origin`],{cwd:e,timeout:6e4}),await MS(`git`,[`remote`,`set-head`,`origin`,`--auto`],{cwd:e,timeout:3e4}).catch(()=>{}),!0}catch{return!1}}async function IS(e,t,n){let r=_.basename(e);if(await NS(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:r,provider:null,url:null,defaultBranch:null,headSha:null,lastCommitAt:null,scannedRef:null};let i=n??`HEAD`,[a,o,s,c,l]=await Promise.all([NS(e,[`remote`,`get-url`,`origin`]),NS(e,[`rev-parse`,`--verify`,`--quiet`,`${i}^{commit}`]),NS(e,[`log`,`-1`,`--format=%cI`,i]),NS(e,[`symbolic-ref`,`--quiet`,`refs/remotes/origin/HEAD`]),NS(e,[`symbolic-ref`,`--quiet`,`--short`,`HEAD`])]);o===null&&t.push(`Git repository has no commits yet`),a===null&&t.push(`Git repository has no 'origin' remote`);let u=a?LS(a):null;return a&&!u&&t.push(`Could not read the 'origin' remote URL`),{name:u?.name??r,provider:u?.provider??null,url:u?.url??null,defaultBranch:n?.replace(/^origin\//,``)??c?.replace(/^refs\/remotes\/origin\//,``)??l,headSha:o,scannedRef:n,lastCommitAt:s?new Date(s).toISOString():null}}function LS(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}`}}var RS=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&&zS(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 zS(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 BS(e){let t=/* @__PURE__ */ new Set;if(!Z(e))return t;for(let n of[`dependencies`,`devDependencies`,`optionalDependencies`,`peerDependencies`]){let r=e[n];if(Z(r))for(let e of Object.keys(r))t.add(e)}return t}function VS(e){return JSON.parse(e)}function HS(e,t,n){let r=VS(e);if(!Z(r))throw Error(`not a JSON object`);let i=/* @__PURE__ */ new Set;if(n!==null){let e=VS(n);if(Z(e))for(let t of[`require`,`require-dev`]){let n=e[t];if(Z(n))for(let e of Object.keys(n))i.add(e.toLowerCase())}}let a=new RS(`composer`,t);for(let e of[`packages`,`packages-dev`]){let t=r[e];if(Array.isArray(t))for(let e of t){if(!Z(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 US(e,t,n){let r=new RS(`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__ */ E((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})),WS=/* @__PURE__ */ E((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})),GS=/* @__PURE__ */ E((e=>{var t=$(),n=WS();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(`
|
|
224
|
-
`)}};a.defaultYaml={explicit:!1,version:`1.2`},a.defaultTags={"!!":`tag:yaml.org,2002:`},e.Directives=a})),KS=/* @__PURE__ */
|
|
223
|
+
`),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?wS(s):null}function wS(e){return e.replace(/!\[[^\]]*\]\([^)]*\)/g,``).replace(/\[([^\]]*)\]\([^)]*\)/g,`$1`).replace(/[`*_]/g,``).trim()}function TS(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 ES(e,t){if(t===`guideline`)return!0;let n=Tx(e).toLowerCase();return/architecture|conventions?|guidelines?|contributing|style-?guide/.test(n)||t===`architecture`&&/overview/.test(n)}const DS=/* @__PURE__ */ new Set([`claude.md`,`agents.md`,`.cursorrules`]);async function OS(e){let t=[];for(let n of e.files){if(!(DS.has(Tx(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 kS=/\.(md|mdx|markdown|txt)$/i,AS=/\.(pdf|docx?|odt|rtf|pages|pptx?|key|xlsx?|numbers)$/i;async function jS(e){let t=[],n=[];for(let r of e.files){if(r.path.split(`/`).some(e=>e.startsWith(`.`)))continue;let i=Tx(r.path);if(AS.test(i)){n.push(r.path);continue}if(!kS.test(i)||/^(claude|agents)\.md$/i.test(i))continue;let a=await e.readText(r);if(!a?.trim())continue;let o=i.replace(kS,``),s=(gS.test(i)?CS(a):null)??o,c=TS(r.path,s);t.push({path:r.path,title:s,type:c,body:a,alwaysLoadCandidate:!1,contentHash:T(`sha256`).update(a).digest(`hex`)})}return{docs:t,unsupported:n}}const MS=n(i);async function NS(e,t){try{let{stdout:n}=await MS(`git`,t,{cwd:e,timeout:1e4}),r=n.trim();return r===``?null:r}catch{return null}}async function PS(e){let t=await NS(e,[`symbolic-ref`,`--quiet`,`refs/remotes/origin/HEAD`]),n=[...t?[t.replace(/^refs\/remotes\//,``)]:[],`origin/main`,`origin/master`,`main`,`master`];for(let t of n)if(await NS(e,[`rev-parse`,`--verify`,`--quiet`,`${t}^{commit}`]))return{ref:t,branch:t.replace(/^origin\//,``)};return null}async function FS(e){try{return await MS(`git`,[`fetch`,`--quiet`,`--no-tags`,`origin`],{cwd:e,timeout:6e4}),await MS(`git`,[`remote`,`set-head`,`origin`,`--auto`],{cwd:e,timeout:3e4}).catch(()=>{}),!0}catch{return!1}}async function IS(e,t,n){let r=_.basename(e);if(await NS(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:r,provider:null,url:null,defaultBranch:null,headSha:null,lastCommitAt:null,scannedRef:null};let i=n??`HEAD`,[a,o,s,c,l]=await Promise.all([NS(e,[`remote`,`get-url`,`origin`]),NS(e,[`rev-parse`,`--verify`,`--quiet`,`${i}^{commit}`]),NS(e,[`log`,`-1`,`--format=%cI`,i]),NS(e,[`symbolic-ref`,`--quiet`,`refs/remotes/origin/HEAD`]),NS(e,[`symbolic-ref`,`--quiet`,`--short`,`HEAD`])]);o===null&&t.push(`Git repository has no commits yet`),a===null&&t.push(`Git repository has no 'origin' remote`);let u=a?LS(a):null;return a&&!u&&t.push(`Could not read the 'origin' remote URL`),{name:u?.name??r,provider:u?.provider??null,url:u?.url??null,defaultBranch:n?.replace(/^origin\//,``)??c?.replace(/^refs\/remotes\/origin\//,``)??l,headSha:o,scannedRef:n,lastCommitAt:s?new Date(s).toISOString():null}}function LS(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}`}}var RS=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&&zS(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 zS(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 BS(e){let t=/* @__PURE__ */ new Set;if(!Z(e))return t;for(let n of[`dependencies`,`devDependencies`,`optionalDependencies`,`peerDependencies`]){let r=e[n];if(Z(r))for(let e of Object.keys(r))t.add(e)}return t}function VS(e){return JSON.parse(e)}function HS(e,t,n){let r=VS(e);if(!Z(r))throw Error(`not a JSON object`);let i=/* @__PURE__ */ new Set;if(n!==null){let e=VS(n);if(Z(e))for(let t of[`require`,`require-dev`]){let n=e[t];if(Z(n))for(let e of Object.keys(n))i.add(e.toLowerCase())}}let a=new RS(`composer`,t);for(let e of[`packages`,`packages-dev`]){let t=r[e];if(Array.isArray(t))for(let e of t){if(!Z(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 US(e,t,n){let r=new RS(`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})),WS=/* @__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})),GS=/* @__PURE__ */ D((e=>{var t=$(),n=WS();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(`
|
|
224
|
+
`)}};a.defaultYaml={explicit:!1,version:`1.2`},a.defaultTags={"!!":`tag:yaml.org,2002:`},e.Directives=a})),KS=/* @__PURE__ */ D((e=>{var t=$(),n=WS();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})),qS=/* @__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})),JS=/* @__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})),YS=/* @__PURE__ */ D((e=>{var t=qS(),n=$(),r=JS();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}}})),XS=/* @__PURE__ */ D((e=>{var t=KS(),n=WS(),r=$(),i=YS(),a=JS(),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);
|
|
225
225
|
/* istanbul ignore if */
|
|
226
|
-
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})),ZS=/* @__PURE__ */
|
|
226
|
+
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})),ZS=/* @__PURE__ */ D((e=>{var t=$(),n=YS(),r=JS();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})),QS=/* @__PURE__ */ D((e=>{var t=XS(),n=$(),r=ZS();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=QS(),n=$(),r=YS();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})),eC=/* @__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(`
|
|
227
227
|
`)?n(r,t):r.includes(`
|
|
228
228
|
`)?`
|
|
229
|
-
`+n(r,t):(e.endsWith(` `)?``:` `)+r,e.stringifyComment=t})),tC=/* @__PURE__ */
|
|
229
|
+
`+n(r,t):(e.endsWith(` `)?``:` `)+r,e.stringifyComment=t})),tC=/* @__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===`
|
|
230
230
|
`)a===t&&(v=i(e,v,r.length)),m=v+r.length+d,h=void 0;else{if(o===` `&&g&&g!==` `&&g!==`
|
|
231
231
|
`&&g!==` `){let t=e[v+1];t&&t!==` `&&t!==`
|
|
232
232
|
`&&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!==`
|
|
233
|
-
`);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})),nC=/* @__PURE__ */
|
|
233
|
+
`);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})),nC=/* @__PURE__ */ D((e=>{var t=ZS(),n=tC();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]===`
|
|
234
234
|
`){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)+`
|
|
235
235
|
|
|
236
236
|
`;a[e+2]===`\\`&&a[e+3]===`n`&&a[e+4]!==`"`;)l+=`
|
|
@@ -244,33 +244,33 @@ if(i||=(a.toJS(o,null,t),e.get(o)),i?.res===void 0)throw ReferenceError(`This sh
|
|
|
244
244
|
`&&e!==` `&&e!==` `)break}let b=s.substring(y),x=b.indexOf(`
|
|
245
245
|
`);x===-1?v=`-`:s===b||x!==b.length-1?(v=`+`,f&&f()):v=``,b&&=(s=s.slice(0,-b.length),b[b.length-1]===`
|
|
246
246
|
`&&(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===`
|
|
247
|
-
`)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
|
|
248
|
-
$&`).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`>${
|
|
247
|
+
`)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,`
|
|
248
|
+
$&`).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(`
|
|
249
249
|
`)||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(`
|
|
250
250
|
`)?c(d,a):u(e,a,o,s);if(!p&&!g&&l!==t.Scalar.PLAIN&&d.includes(`
|
|
251
|
-
`))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})),rC=/* @__PURE__ */
|
|
252
|
-
`:``,S){let e=p(S);
|
|
253
|
-
`&&C&&(
|
|
251
|
+
`))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})),rC=/* @__PURE__ */ D((e=>{var t=KS(),n=$(),r=eC(),i=nC();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})),iC=/* @__PURE__ */ D((e=>{var t=$(),n=ZS(),r=rC(),i=eC();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?`
|
|
252
|
+
`:``,S){let e=p(S);E+=`\n${i.indentComment(e,o.indent)}`}T===``&&!o.inFlow?E===`
|
|
253
|
+
`&&C&&(E=`
|
|
254
254
|
|
|
255
|
-
`):
|
|
256
|
-
`),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||(
|
|
257
|
-
`)&&(
|
|
255
|
+
`):E+=`\n${o.indent}`}else if(!_&&t.isCollection(a)){let e=T[0],t=T.indexOf(`
|
|
256
|
+
`),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]===`
|
|
257
|
+
`)&&(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})),aC=/* @__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})),oC=/* @__PURE__ */ D((e=>{var t=$(),n=ZS();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})),sC=/* @__PURE__ */ D((e=>{var t=aC(),n=oC(),r=rC(),i=$(),a=JS();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})),cC=/* @__PURE__ */ D((e=>{var t=QS(),n=iC(),r=sC(),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})),lC=/* @__PURE__ */ D((e=>{var t=$(),n=rC(),r=eC();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}`:`
|
|
258
258
|
`}}return e?(_+=`
|
|
259
259
|
`+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(`
|
|
260
260
|
`),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}`:`
|
|
261
|
-
`;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})),uC=/* @__PURE__ */
|
|
262
|
-
`:` `)}return r.stringifyString({comment:e,type:i,value:u},o,s,c)}}})),CC=/* @__PURE__ */ E((e=>{var t=$(),n=cC(),r=ZS(),i=fC();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})),wC=/* @__PURE__ */ E((e=>{var t=$(),n=JS(),r=uC(),i=fC(),a=CC(),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})),TC=/* @__PURE__ */ E((e=>{var t=ZS();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})),EC=/* @__PURE__ */ E((e=>{var t=ZS(),n=_C();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})),DC=/* @__PURE__ */ E((e=>{var t=_C();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})),OC=/* @__PURE__ */ E((e=>{var t=$(),n=cC(),r=uC(),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})),kC=/* @__PURE__ */ E((e=>{var t=_C();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})),AC=/* @__PURE__ */ E((e=>{var t=dC(),n=hC(),r=pC(),i=mC(),a=SC(),o=TC(),s=EC(),c=DC(),l=oC(),u=wC(),d=CC(),f=OC(),p=kC();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]})),jC=/* @__PURE__ */ E((e=>{var t=dC(),n=hC(),r=pC(),i=mC(),a=gC(),o=vC(),s=yC(),c=bC(),l=xC(),u=SC(),d=oC(),f=wC(),p=CC(),m=AC(),h=OC(),g=kC();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})),MC=/* @__PURE__ */ E((e=>{var t=$(),n=dC(),r=pC(),i=mC(),a=jC();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}}})),NC=/* @__PURE__ */ E((e=>{var t=$(),n=rC(),r=eC();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(`
|
|
261
|
+
`;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})),uC=/* @__PURE__ */ D((e=>{var t=lC(),n=sC(),r=$S(),i=$(),a=cC(),o=ZS();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})),dC=/* @__PURE__ */ D((e=>{var t=$(),n=uC();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)}})),fC=/* @__PURE__ */ D((e=>{var t=QS(),n=lC(),r=$S(),i=$(),a=ZS(),o=JS(),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})),pC=/* @__PURE__ */ D((e=>{var t=$(),n=fC();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)}})),mC=/* @__PURE__ */ D((e=>{var t=nC();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)}}})),hC=/* @__PURE__ */ D((e=>{var t=ZS();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})),gC=/* @__PURE__ */ D((e=>{var t=ZS();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})),_C=/* @__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})),vC=/* @__PURE__ */ D((e=>{var t=ZS(),n=_C();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})),yC=/* @__PURE__ */ D((e=>{var t=_C();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`)}})),bC=/* @__PURE__ */ D((e=>{var t=dC(),n=hC(),r=pC(),i=mC(),a=gC(),o=vC(),s=yC();e.schema=[t.map,r.seq,i.string,n.nullTag,a.boolTag,s.intOct,s.int,s.intHex,o.floatNaN,o.floatExp,o.float]})),xC=/* @__PURE__ */ D((e=>{var t=ZS(),n=dC(),r=pC();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}})})),SC=/* @__PURE__ */ D((e=>{var t=de(`buffer`),n=ZS(),r=nC();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?`
|
|
262
|
+
`:` `)}return r.stringifyString({comment:e,type:i,value:u},o,s,c)}}})),CC=/* @__PURE__ */ D((e=>{var t=$(),n=cC(),r=ZS(),i=fC();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})),wC=/* @__PURE__ */ D((e=>{var t=$(),n=JS(),r=uC(),i=fC(),a=CC(),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})),TC=/* @__PURE__ */ D((e=>{var t=ZS();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})),EC=/* @__PURE__ */ D((e=>{var t=ZS(),n=_C();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})),DC=/* @__PURE__ */ D((e=>{var t=_C();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})),OC=/* @__PURE__ */ D((e=>{var t=$(),n=cC(),r=uC(),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})),kC=/* @__PURE__ */ D((e=>{var t=_C();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})),AC=/* @__PURE__ */ D((e=>{var t=dC(),n=hC(),r=pC(),i=mC(),a=SC(),o=TC(),s=EC(),c=DC(),l=oC(),u=wC(),d=CC(),f=OC(),p=kC();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]})),jC=/* @__PURE__ */ D((e=>{var t=dC(),n=hC(),r=pC(),i=mC(),a=gC(),o=vC(),s=yC(),c=bC(),l=xC(),u=SC(),d=oC(),f=wC(),p=CC(),m=AC(),h=OC(),g=kC();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})),MC=/* @__PURE__ */ D((e=>{var t=$(),n=dC(),r=pC(),i=mC(),a=jC();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}}})),NC=/* @__PURE__ */ D((e=>{var t=$(),n=rC(),r=eC();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(`
|
|
263
263
|
`)?(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(`
|
|
264
264
|
`)+`
|
|
265
|
-
`}e.stringifyDocument=i})),PC=/* @__PURE__ */
|
|
266
|
-
`),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`}}})),IC=/* @__PURE__ */
|
|
267
|
-
`))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})),RC=/* @__PURE__ */
|
|
265
|
+
`}e.stringifyDocument=i})),PC=/* @__PURE__ */ D((e=>{var t=XS(),n=$S(),r=$(),i=cC(),a=JS(),o=MC(),s=NC(),c=KS(),l=qS(),u=QS(),d=GS(),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})),FC=/* @__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)+`…
|
|
266
|
+
`),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`}}})),IC=/* @__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})),LC=/* @__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(`
|
|
267
|
+
`))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})),RC=/* @__PURE__ */ D((e=>{var t=LC();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})),zC=/* @__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})),BC=/* @__PURE__ */ D((e=>{var t=cC(),n=uC(),r=IC(),i=LC(),a=RC(),o=zC();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+=`
|
|
268
268
|
`+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+=`
|
|
269
|
-
`+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})),VC=/* @__PURE__ */
|
|
269
|
+
`+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})),VC=/* @__PURE__ */ D((e=>{var t=fC(),n=IC(),r=RC();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})),HC=/* @__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})),UC=/* @__PURE__ */ D((e=>{var t=$(),n=cC(),r=uC(),i=fC(),a=HC(),o=IC(),s=LC(),c=zC();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+=`
|
|
270
270
|
`+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+=`
|
|
271
271
|
`+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+=`
|
|
272
272
|
`+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+=`
|
|
273
|
-
`+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})),WC=/* @__PURE__ */
|
|
273
|
+
`+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})),WC=/* @__PURE__ */ D((e=>{var t=$(),n=ZS(),r=uC(),i=fC(),a=BC(),o=VC(),s=UC();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})),GC=/* @__PURE__ */ D((e=>{var t=ZS();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?`
|
|
274
274
|
`.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)+`
|
|
275
275
|
`;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`;
|
|
276
276
|
/* istanbul ignore if already caught in lexer */
|
|
@@ -291,7 +291,7 @@ if(i&&(r=r.slice(0,-1)),r&&n.length<d){let e=`Block scalar lines must not be les
|
|
|
291
291
|
/* istanbul ignore if should not happen */
|
|
292
292
|
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;
|
|
293
293
|
/* istanbul ignore next should not happen */
|
|
294
|
-
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})),KC=/* @__PURE__ */
|
|
294
|
+
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})),KC=/* @__PURE__ */ D((e=>{var t=ZS(),n=HC();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;
|
|
295
295
|
/* istanbul ignore next should not happen */
|
|
296
296
|
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]){
|
|
297
297
|
/* istanbul ignore next should not happen */
|
|
@@ -308,10 +308,10 @@ case` `:n=`a tab character`;break;case`,`:n=`flow indicator character ,`;break;c
|
|
|
308
308
|
`);)r===`
|
|
309
309
|
`&&(n+=`
|
|
310
310
|
`),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:`
|
|
311
|
-
`,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})),qC=/* @__PURE__ */
|
|
311
|
+
`,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})),qC=/* @__PURE__ */ D((e=>{var t=$(),n=ZS(),r=GC(),i=KC();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})),JC=/* @__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})),YC=/* @__PURE__ */ D((e=>{var t=XS(),n=$(),r=WC(),i=qC(),a=HC(),o=JC();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})),XC=/* @__PURE__ */ D((e=>{var t=PC(),n=YC(),r=HC(),i=IC();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})),ZC=/* @__PURE__ */ D((e=>{var t=de(`process`),n=GS(),r=PC(),i=FC(),a=$(),o=XC(),s=HC();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?`
|
|
312
312
|
|
|
313
313
|
`:`
|
|
314
|
-
`)+(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}}}})),QC=/* @__PURE__ */
|
|
314
|
+
`)+(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}}}})),QC=/* @__PURE__ */ D((e=>{var t=GC(),n=KC(),r=FC(),i=nC();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:`
|
|
315
315
|
`}];switch(c[0]){case`|`:case`>`:{let e=c.indexOf(`
|
|
316
316
|
`),t=c.substring(0,e),n=c.substring(e+1)+`
|
|
317
317
|
`,i=[{type:`block-scalar-header`,offset:o,indent:r,source:t}];return l(i,u)||i.push({type:`newline`,offset:-1,indent:r,source:`
|
|
@@ -319,11 +319,11 @@ case` `:n=`a tab character`;break;case`,`:n=`flow indicator character ,`;break;c
|
|
|
319
319
|
`),r=t.substring(0,n),i=t.substring(n+1)+`
|
|
320
320
|
`;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:`
|
|
321
321
|
`});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:`
|
|
322
|
-
`};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__ */
|
|
322
|
+
`};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})),ew=/* @__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})),tw=/* @__PURE__ */ D((e=>{var t=QC(),n=$C(),r=ew();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`);
|
|
323
323
|
/* istanbul ignore next */
|
|
324
324
|
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`
|
|
325
325
|
`:case`\r
|
|
326
|
-
`: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})),nw=/* @__PURE__ */
|
|
326
|
+
`: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})),nw=/* @__PURE__ */ D((e=>{var t=tw();function n(e){switch(e){case void 0:case` `:case`
|
|
327
327
|
`: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(` ,[]{}
|
|
328
328
|
\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===`
|
|
329
329
|
`||t===`\r`&&this.buffer[e+1]===`
|
|
@@ -342,7 +342,7 @@ function o(e){switch(e){case``:return`<BOM>`;case``:return`<DOC>`;case``:re
|
|
|
342
342
|
`,t=this.buffer[i+1]):r=i),t===`#`||e&&a.has(t))break;if(o===`
|
|
343
343
|
`){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===`
|
|
344
344
|
`?yield*this.pushCount(1):e===`\r`&&this.charAt(1)===`
|
|
345
|
-
`?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)}}})),rw=/* @__PURE__ */
|
|
345
|
+
`?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)}}})),rw=/* @__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}}}}})),iw=/* @__PURE__ */ D((e=>{var t=de(`process`),n=tw(),r=nw();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;
|
|
346
346
|
/* istanbul ignore next should not happen */
|
|
347
347
|
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)}
|
|
348
348
|
/* istanbul ignore next should not happen */
|
|
@@ -358,10 +358,10 @@ default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.l
|
|
|
358
358
|
/* istanbul ignore else should not happen */
|
|
359
359
|
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(`
|
|
360
360
|
`)+1;for(;e!==0;)this.onNewLine(this.offset+e),e=this.source.indexOf(`
|
|
361
|
-
`,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())}}}})),aw=/* @__PURE__ */ E((e=>{var t=ZC(),n=PC(),r=FC(),i=aC(),a=$(),o=rw(),s=iw();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})),ow=(/* @__PURE__ */ E((e=>{var t=ZC(),n=PC(),r=MC(),i=FC(),a=XS(),o=$(),s=cC(),c=ZS(),l=uC(),u=fC();tw();var d=nw(),f=rw(),p=iw(),m=aw(),h=WS();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 sw(e,t){let n=(0,ow.parse)(e,{uniqueKeys:!1});if(!Z(n))throw Error(`not a YAML mapping`);let r=new RS(`npm`,t),i=Z(n.importers)?n.importers:{".":n};for(let e of Object.values(i))if(Z(e))for(let t of[`dependencies`,`devDependencies`,`optionalDependencies`]){let n=e[t];if(Z(n))for(let[e,t]of Object.entries(n)){let n=Z(t)?t.version:t;if(typeof n!=`string`||cw(n))continue;let i=uw(n);i?r.add(i.name,i.version,!0):r.add(e,lw(n),!0)}}for(let e of[`packages`,`snapshots`]){let t=n[e];if(Z(t))for(let e of Object.keys(t)){let t=uw(e);t&&!cw(t.version)&&r.add(t.name,t.version,!1)}}return r.rows()}function cw(e){return/^(link|file|workspace):/.test(e)}function lw(e){return e.replace(/\(.*$/,``).replace(/_(?=[^/]*@).*$/,``)}function uw(e){let t=e.replace(/^\//,``).replace(/\(.*$/,``),n=t.indexOf(`@`,1);if(n>0)return{name:t.slice(0,n),version:lw(t.slice(n+1))};if(!e.startsWith(`/`))return null;let r=t.lastIndexOf(`/`);return r<=0?null:{name:t.slice(0,r),version:lw(t.slice(r+1))}}function dw(e,t){let n=VS(e);if(!Z(n))throw Error(`not a JSON object`);let r=new RS(`npm`,t);if(Z(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 BS(r))e.add(t);for(let[t,i]of Object.entries(n.packages)){let n=t.lastIndexOf(`node_modules/`);if(n===-1||!Z(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(Z(n.dependencies)){let e=(t,n)=>{for(let[i,a]of Object.entries(t)){if(!Z(a))continue;let t=a.version;typeof t==`string`&&!cw(t)&&r.add(i,t,n===0&&a.dev!==!0),Z(a.dependencies)&&e(a.dependencies,n+1)}};e(n.dependencies,0)}return r.rows()}function fw(e,t,n){let r=new RS(`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(pw).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 pw(e){if(e===`__metadata`)return null;let t=e.indexOf(`@`,1);return t>0?e.slice(0,t):null}async function mw(e,t){let n=Ex(t),r=/* @__PURE__ */ new Set,i=await hw(e,Dx(n,`package.json`));for(let e of BS(i))r.add(e);if(!Z(i))return r;let a=i.workspaces,o=(Array.isArray(a)?a:Z(a)&&Array.isArray(a.packages)?a.packages:[]).filter(e=>typeof e==`string`).map(e=>gw(Dx(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=Ex(t.path);if(o.some(e=>e.test(n)))for(let n of BS(await hw(e,t.path)))r.add(n)}return r}async function hw(e,t){let n=e.file(t);if(!n)return null;let r=await e.readText(n);if(r===null)return null;try{return VS(r)}catch{return e.warnings.push(`${t}: not valid JSON, skipped`),null}}function gw(e){let t=e.split(`/`).map(e=>e===`**`?`.*`:e.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`[^/]*`)).join(`/`);return RegExp(`^${t}$`)}function _w(e){return e.toLowerCase().replace(/[-_.]+/g,`-`)}function vw(e,t,n){let r=new RS(`pip`,t),i=!1,a=null,o=null,s=!1,c=()=>{a&&o&&!s&&r.add(a,o,n.has(_w(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 yw(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(_w(n))},o=()=>{for(let e of i.matchAll(/"([^"]*)"|'([^']*)'/g))a(e[1]??e[2]??``);r=null,i=``},s=e=>e.replace(/"[^"]*"|'[^']*'/g,``).includes(`]`);for(let a of e.split(/\r?\n/)){let e=a.replace(/\s+#.*$/,``);if(r!==null){i+=` ${e}`,s(e)&&o();continue}let c=/^\s*\[([^\]]+)\]\s*$/.exec(e);if(c){n=(c[1]??``).trim();continue}let l=/^\s*"?([A-Za-z0-9_.-]+)"?\s*=\s*(.*)$/.exec(e);if(!l)continue;let u=l[1]??``,d=l[2]??``;n===`tool.poetry.dependencies`||n===`tool.poetry.dev-dependencies`||/^tool\.poetry\.group\.[^.]+\.dependencies$/.test(n)?_w(u)!==`python`&&t.add(_w(u)):(n===`project`&&u===`dependencies`||n===`project.optional-dependencies`||n===`dependency-groups`)&&d.trimStart().startsWith(`[`)&&(r=u,i=d,s(d.trimStart().slice(1))&&o())}return t}function bw(e,t){let n=new RS(`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 xw(e){let t=[];for(let n of e.files)try{let r=await Sw(e,n);r&&t.push(...r)}catch(t){e.warnings.push(`${n.path}: could not be parsed (${Ox(t)})`)}return t}async function Sw(e,t){let n=Tx(t.path),r=Ex(t.path),i=t=>t?e.readText(t,52428800):Promise.resolve(null),a=t=>e.file(Dx(r,t));switch(n){case`pnpm-lock.yaml`:{let e=await i(t);return e===null?null:sw(e,t.path)}case`package-lock.json`:case`npm-shrinkwrap.json`:{let e=await i(t);return e===null?null:dw(e,t.path)}case`yarn.lock`:{let n=await i(t);return n===null?null:fw(n,t.path,await mw(e,t.path))}case`composer.lock`:{let e=await i(t);return e===null?null:HS(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?yw(n):/* @__PURE__ */ new Set;return vw(e,t.path,r)}case`go.sum`:case`go.mod`:return n===`go.mod`&&a(`go.sum`)?null:US(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}=bw(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 Cw={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 ww(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=Cw[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 Tw=/* @__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`]),Ew=/^(not|null|default|primary|unique|references|check|constraint|generated|collate|deferrable|initially|identity)$/i;function Dw(e){if(!/\.sql$/i.test(e))return!1;let t=e.toLowerCase();return/(^|\/)migrations\//.test(t)||/(^|\/)db\/migrate\//.test(t)}const Ow=e=>e.slice(0,e.lastIndexOf(`/`)+1);function kw(e,t){let n=e.toLowerCase();if(!n.endsWith(`.sql`)||Dw(e))return!1;let r=n.slice(n.lastIndexOf(`/`)+1);return/seed|fixture|sample|test|demo/.test(r)?!1:/schema|structure/.test(r)||t.has(Ow(n))||/(^|\/)docker-entrypoint-initdb\.d\//.test(n)}async function Aw(e){let t=/* @__PURE__ */ new Map,n=e.files.filter(e=>Dw(e.path)),r=new Set(n.flatMap(e=>{let t=/^(.*\/)?(migrations|db\/migrate)\//.exec(e.path.toLowerCase());return t?[t[1]??``]:[]})),i=e.files.filter(e=>kw(e.path,r)).sort((e,t)=>e.path<t.path?-1:1);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[...i,...n]){let n=await e.readText(r);if(n!==null)for(let i of jw(n))try{zw(i,r.path,t,e.warnings)}catch(t){e.warnings.push(`${r.path}: could not read statement "${Yw(i)}" (${Ox(t)})`)}}return[...t.values()].filter(e=>!Tw.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 jw(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(`
|
|
362
|
-
`,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 Mw(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 Nw(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 Pw=String.raw`(?:"(?:[^"]|"")+"|[A-Za-z_][\w$]*)`,Fw=String.raw`(${Pw}(?:\s*\.\s*${Pw})?)`;function Iw(e){let t=e.trim();return t.startsWith(`"`)?t.slice(1,-1).replace(/""/g,`"`):t.toLowerCase()}function Lw(e){let t=e.match(new RegExp(Pw,`g`))??[e];return t.length>=2?{schema:Iw(t[0]??``),table:Iw(t[1]??``)}:{schema:`public`,table:Iw(t[0]??e)}}function Rw(e,t){return`${e}.${t}`}function zw(e,t,n,r){if(/^create\s+(?:(?:global|local)\s+)?(?:temp(?:orary)?\s+|unlogged\s+)?table\b/i.test(e)){Bw(e,t,n,r);return}let i=new RegExp(String.raw`^alter\s+table\s+(?:if\s+exists\s+)?(?:only\s+)?${Fw}\s+(.+)$`,`i`).exec(e);if(i?.[1]&&i[2]){qw(Lw(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 Mw(a[1])){let{schema:t,table:r}=Lw(e);n.delete(Rw(t,r))}}function Bw(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+)?${Fw}\s*\(`,`i`).exec(e);if(!i?.[1]){r.push(`${t}: skipped a create table statement it couldn't read: "${Yw(e)}"`);return}let{schema:a,table:o}=Lw(i[1]),s=i[0].length-1,c=Vw(e,s);if(c===-1){r.push(`${t}: unbalanced parentheses in create table ${o}`);return}let l=Rw(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 Mw(e.slice(s+1,c))){if(/^(constraint|primary\s+key|unique|foreign\s+key|check|exclude|like)\b/i.test(i)){Kw(u,i,n);continue}let e=Hw(i,n);e?u.columns.push(e):r.push(`${t}: skipped column definition "${Yw(i)}" in ${o}`)}n.set(l,u)}function Vw(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 Hw(e,t){let n=Nw(e),r=n[0];if(!r||n.length<2)return null;let i=1,a=[];for(;i<n.length&&!Ew.test(n[i]??``);)a.push(n[i]),i++;if(a.length===0)return null;let o={name:Iw(r),type:a.join(` `).replace(/\s+\(/g,`(`).toLowerCase(),required:!1};return Uw(o,n.slice(i),t),o}function Uw(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&&!Ew.test(t[r+1]??``);)n.push(t[r+1]),r++;n.length>0&&(e.default=Ww(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=Gw(i,a,n),r+=a?2:1}}}function Ww(e){return e.join(` `).replace(/\s+\(/g,`(`)}function Gw(e,t,n){let{schema:r,table:i}=Lw(e),a=r===`public`?i:`${r}.${i}`,o=t?Iw(t.slice(1,-1).split(`,`)[0]??``):null;return o||=n.get(Rw(r,i))?.columns.find(e=>e.primaryKey)?.name??`id`,`${a}.${o}`}function Kw(e,t,n){let r=t.replace(new RegExp(String.raw`^constraint\s+${Pw}\s+`,`i`),``),i=e=>(e??``).split(`,`).map(e=>Iw(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+${Fw}\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=Gw(s[2],o?`(${o})`:void 0,n)})}}function qw(e,t,n,r,i){let a=r.get(Rw(e.schema,e.table));if(!a){!Tw.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+(${Pw})$`,`i`).exec(t);if(o?.[1]){r.delete(Rw(a.schema,a.table)),a.table=Iw(o[1]),r.set(Rw(a.schema,a.table),a);return}let s=new RegExp(String.raw`^rename\s+(?:column\s+)?(${Pw})\s+to\s+(${Pw})$`,`i`).exec(t);if(s?.[1]&&s[2]){let e=a.columns.find(e=>e.name===Iw(s[1]));e&&(e.name=Iw(s[2]))}else for(let e of Mw(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=Hw(t[1],r);if(!o){i.push(`${n}: skipped "${Yw(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]){Kw(a,o[1],r);continue}let s=new RegExp(String.raw`^drop\s+(?:column\s+)?(?:if\s+exists\s+)?(${Pw})`,`i`).exec(e);if(s?.[1]&&!/^drop\s+constraint\b/i.test(e)){let e=Iw(s[1]);a.columns=a.columns.filter(t=>t.name!==e);continue}let c=new RegExp(String.raw`^alter\s+(?:column\s+)?(${Pw})\s+(.+)$`,`i`).exec(e);if(c?.[1]&&c[2]){let e=a.columns.find(e=>e.name===Iw(c[1]));e&&Jw(e,c[2])}}}function Jw(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=Ww(Nw(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 Yw(e){return e.length>60?`${e.slice(0,57)}...`:e}const Xw=[`GET`,`POST`,`PUT`,`PATCH`,`DELETE`],Zw=/^(openapi|swagger)([.-][\w.-]*)?\.(json|ya?ml)$/i,Qw=/\.(json|ya?ml)$/i;async function $w(e){let t=[];for(let n of e.files){let r=Zw.test(Tx(n.path));if(!r&&!Qw.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,ow.parse)(i)}catch(t){e.warnings.push(`${n.path}: OpenAPI file could not be parsed (${Ox(t)})`);continue}!Z(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(...eT(a,n.path,e.warnings))}return t}function eT(e,t,n){let r=typeof e.swagger==`string`,i=new tT(e,t,n),a=r?e.securityDefinitions:rT(e.components)?.securitySchemes,o=Z(a)?a:{},s=Z(e.paths)?e.paths:{},c=[];for(let[n,a]of Object.entries(s)){let s=i.resolve(a);if(s)for(let a of Xw){let l=rT(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:kx(l.summary)?.trim()||kx(l.operationId)||`${a} ${n}`,sourcePath:t,method:a,path:n,auth:_T(d,o,i),request:r?cT(u,l,e,i):aT(l.requestBody,i),responses:lT(l,e,r,i)})}}return c}var tT=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(!Z(t))return null;let e=t.$ref;if(typeof e!=`string`)return t;t=this.#i(e)}return null}refName(e){if(!Z(e)||typeof e.$ref!=`string`)return null;let t=e.$ref.slice(e.$ref.lastIndexOf(`/`)+1);return t?nT(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(!Z(t))break;t=t[nT(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 nT(e){return decodeURIComponent(e).replace(/~1/g,`/`).replace(/~0/g,`~`)}function rT(e){return Z(e)?e:null}function iT(e){if(!Z(e))return null;let t=Object.entries(e).filter(e=>Z(e[1]));return t.find(([e])=>e===`application/json`)??t.find(([e])=>/json/.test(e))??t[0]??null}function aT(e,t){let n=t.resolve(e),r=n?iT(n.content):null;return r?oT(r[0],r[1],t):null}function oT(e,t,n){let r=t.schema;return{contentType:e,fields:pT(r,n),example:sT(t,n)??gT(r,n,0)}}function sT(e,t){if(e.example!==void 0)return e.example;if(Z(e.examples)){let n=t.resolve(Object.values(e.examples)[0]);if(n&&n.value!==void 0)return n.value}}function cT(e,t,n,r){let i=e.map(e=>r.resolve(e)).filter(e=>e!==null),a=dT(t.consumes)??dT(n.consumes),o=i.find(e=>e.in===`body`);if(o)return{contentType:a??`application/json`,fields:pT(o.schema,r),example:gT(o.schema,r,0)};let s=i.filter(e=>e.in===`formData`);if(s.length===0)return null;let c=s.map(e=>({name:kx(e.name)??``,type:hT(e,r),required:e.required===!0,...mT(e)}));return{contentType:a??`application/x-www-form-urlencoded`,fields:c,example:Object.fromEntries(s.map(e=>[kx(e.name)??``,gT(e,r,1)]))}}function lT(e,t,n,r){if(!Z(e.responses))return[];let i=dT(e.produces)??dT(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=rT(e.examples);s={contentType:i,fields:pT(e.schema,r),example:t?.[i]??gT(e.schema,r,0)}}}else{let t=iT(e.content);t&&(s=oT(t[0],t[1],r))}a.push({status:uT(t),description:kx(e.description)??``,body:s})}return a}function uT(e){let t=e.replace(/x/gi,`0`),n=Number.parseInt(t,10);return Number.isNaN(n)?0:n}function dT(e){return Array.isArray(e)&&typeof e[0]==`string`?e[0]:void 0}function fT(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=fT(a,t,n+1);r&&(Z(r.properties)&&Object.assign(e,r.properties),Array.isArray(r.required)&&i.push(...r.required.filter(e=>typeof e==`string`)))}return Z(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?fT(i[0],t,n+1):r}function pT(e,t){let n=fT(e,t);if(n?.type===`array`&&(n=fT(n.items,t)),!n||!Z(n.properties))return[];let r=new Set(Array.isArray(n.required)?n.required:[]);return Object.entries(n.properties).map(([e,n])=>{let i=fT(n,t)??{};return{name:e,type:hT(n,t),required:r.has(e),...mT(i)}})}function mT(e){let t={},n=kx(e.description)?.trim();return n&&(t.description=n),Array.isArray(e.enum)&&(t.values=e.enum.map(e=>String(e))),t}function hT(e,t,n=0){let r=t.refName(e),i=fT(e,t);if(!i)return r??`unknown`;let a=Array.isArray(i.type)?i.type.filter(e=>e!==`null`).join(` | `):kx(i.type);return a===`array`?n>8?`array`:`${hT(i.items,t,n+1)}[]`:r&&(a===`object`||a===void 0)?r:kx(i.format)??a??(i.properties?`object`:`unknown`)}function gT(e,t,n){let r=fT(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&&Z(r.properties)){let e=Z(r.properties)?r.properties:{};return Object.fromEntries(Object.entries(e).map(([e,r])=>[e,gT(r,t,n+1)]))}switch(i){case`array`:return[gT(r.items,t,n+1)];case`string`:return`string`;case`integer`:case`number`:return 0;case`boolean`:return!1;default:return null}}function _T(e,t,n){if(!Array.isArray(e)||e.length===0)return null;let r=[];for(let i of e){if(!Z(i))continue;let e=Object.keys(i);e.length===0?r.push(`none`):r.push(e.map(e=>vT(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 vT(e,t){if(!t)return e;switch(kx(t.type)?.toLowerCase()){case`http`:{let e=kx(t.scheme)?.toLowerCase();if(e===`bearer`){let e=kx(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 ${kx(t.in)??`header`} ${kx(t.name)??e}`;case`oauth2`:return`OAuth2`;case`openidconnect`:return`OpenID Connect`;case`mutualtls`:return`Mutual TLS`;default:return e}}const yT=[`readme.md`,`readme.mdx`,`readme.markdown`,`readme.txt`,`readme`];async function bT(e){let t=e.files.find(e=>!e.path.includes(`/`)&&yT.includes(e.path.toLowerCase()));if(!t)return null;let n=await e.readText(t);return{path:t.path,oneLiner:n===null?null:xT(n)}}function xT(e){let t=e.replace(/\r\n/g,`
|
|
361
|
+
`,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())}}}})),aw=/* @__PURE__ */ D((e=>{var t=ZC(),n=PC(),r=FC(),i=aC(),a=$(),o=rw(),s=iw();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})),ow=(/* @__PURE__ */ D((e=>{var t=ZC(),n=PC(),r=MC(),i=FC(),a=XS(),o=$(),s=cC(),c=ZS(),l=uC(),u=fC();tw();var d=nw(),f=rw(),p=iw(),m=aw(),h=WS();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 sw(e,t){let n=(0,ow.parse)(e,{uniqueKeys:!1});if(!Z(n))throw Error(`not a YAML mapping`);let r=new RS(`npm`,t),i=Z(n.importers)?n.importers:{".":n};for(let e of Object.values(i))if(Z(e))for(let t of[`dependencies`,`devDependencies`,`optionalDependencies`]){let n=e[t];if(Z(n))for(let[e,t]of Object.entries(n)){let n=Z(t)?t.version:t;if(typeof n!=`string`||cw(n))continue;let i=uw(n);i?r.add(i.name,i.version,!0):r.add(e,lw(n),!0)}}for(let e of[`packages`,`snapshots`]){let t=n[e];if(Z(t))for(let e of Object.keys(t)){let t=uw(e);t&&!cw(t.version)&&r.add(t.name,t.version,!1)}}return r.rows()}function cw(e){return/^(link|file|workspace):/.test(e)}function lw(e){return e.replace(/\(.*$/,``).replace(/_(?=[^/]*@).*$/,``)}function uw(e){let t=e.replace(/^\//,``).replace(/\(.*$/,``),n=t.indexOf(`@`,1);if(n>0)return{name:t.slice(0,n),version:lw(t.slice(n+1))};if(!e.startsWith(`/`))return null;let r=t.lastIndexOf(`/`);return r<=0?null:{name:t.slice(0,r),version:lw(t.slice(r+1))}}function dw(e,t){let n=VS(e);if(!Z(n))throw Error(`not a JSON object`);let r=new RS(`npm`,t);if(Z(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 BS(r))e.add(t);for(let[t,i]of Object.entries(n.packages)){let n=t.lastIndexOf(`node_modules/`);if(n===-1||!Z(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(Z(n.dependencies)){let e=(t,n)=>{for(let[i,a]of Object.entries(t)){if(!Z(a))continue;let t=a.version;typeof t==`string`&&!cw(t)&&r.add(i,t,n===0&&a.dev!==!0),Z(a.dependencies)&&e(a.dependencies,n+1)}};e(n.dependencies,0)}return r.rows()}function fw(e,t,n){let r=new RS(`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(pw).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 pw(e){if(e===`__metadata`)return null;let t=e.indexOf(`@`,1);return t>0?e.slice(0,t):null}async function mw(e,t){let n=Ex(t),r=/* @__PURE__ */ new Set,i=await hw(e,Dx(n,`package.json`));for(let e of BS(i))r.add(e);if(!Z(i))return r;let a=i.workspaces,o=(Array.isArray(a)?a:Z(a)&&Array.isArray(a.packages)?a.packages:[]).filter(e=>typeof e==`string`).map(e=>gw(Dx(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=Ex(t.path);if(o.some(e=>e.test(n)))for(let n of BS(await hw(e,t.path)))r.add(n)}return r}async function hw(e,t){let n=e.file(t);if(!n)return null;let r=await e.readText(n);if(r===null)return null;try{return VS(r)}catch{return e.warnings.push(`${t}: not valid JSON, skipped`),null}}function gw(e){let t=e.split(`/`).map(e=>e===`**`?`.*`:e.replace(/[.+^${}()|[\]\\]/g,`\\$&`).replace(/\*/g,`[^/]*`)).join(`/`);return RegExp(`^${t}$`)}function _w(e){return e.toLowerCase().replace(/[-_.]+/g,`-`)}function vw(e,t,n){let r=new RS(`pip`,t),i=!1,a=null,o=null,s=!1,c=()=>{a&&o&&!s&&r.add(a,o,n.has(_w(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 yw(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(_w(n))},o=()=>{for(let e of i.matchAll(/"([^"]*)"|'([^']*)'/g))a(e[1]??e[2]??``);r=null,i=``},s=e=>e.replace(/"[^"]*"|'[^']*'/g,``).includes(`]`);for(let a of e.split(/\r?\n/)){let e=a.replace(/\s+#.*$/,``);if(r!==null){i+=` ${e}`,s(e)&&o();continue}let c=/^\s*\[([^\]]+)\]\s*$/.exec(e);if(c){n=(c[1]??``).trim();continue}let l=/^\s*"?([A-Za-z0-9_.-]+)"?\s*=\s*(.*)$/.exec(e);if(!l)continue;let u=l[1]??``,d=l[2]??``;n===`tool.poetry.dependencies`||n===`tool.poetry.dev-dependencies`||/^tool\.poetry\.group\.[^.]+\.dependencies$/.test(n)?_w(u)!==`python`&&t.add(_w(u)):(n===`project`&&u===`dependencies`||n===`project.optional-dependencies`||n===`dependency-groups`)&&d.trimStart().startsWith(`[`)&&(r=u,i=d,s(d.trimStart().slice(1))&&o())}return t}function bw(e,t){let n=new RS(`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 xw(e){let t=[];for(let n of e.files)try{let r=await Sw(e,n);r&&t.push(...r)}catch(t){e.warnings.push(`${n.path}: could not be parsed (${Ox(t)})`)}return t}async function Sw(e,t){let n=Tx(t.path),r=Ex(t.path),i=t=>t?e.readText(t,52428800):Promise.resolve(null),a=t=>e.file(Dx(r,t));switch(n){case`pnpm-lock.yaml`:{let e=await i(t);return e===null?null:sw(e,t.path)}case`package-lock.json`:case`npm-shrinkwrap.json`:{let e=await i(t);return e===null?null:dw(e,t.path)}case`yarn.lock`:{let n=await i(t);return n===null?null:fw(n,t.path,await mw(e,t.path))}case`composer.lock`:{let e=await i(t);return e===null?null:HS(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?yw(n):/* @__PURE__ */ new Set;return vw(e,t.path,r)}case`go.sum`:case`go.mod`:return n===`go.mod`&&a(`go.sum`)?null:US(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}=bw(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 Cw={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 ww(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=Cw[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 Tw=/* @__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`]),Ew=/^(not|null|default|primary|unique|references|check|constraint|generated|collate|deferrable|initially|identity)$/i;function Dw(e){if(!/\.sql$/i.test(e))return!1;let t=e.toLowerCase();return/(^|\/)migrations\//.test(t)||/(^|\/)db\/migrate\//.test(t)}const Ow=e=>e.slice(0,e.lastIndexOf(`/`)+1),kw=[[`postgres`,/\b(?:bigserial|serial|jsonb|timestamptz|bytea|tsvector|plpgsql|gen_random_uuid|uuid_generate_v4|create\s+extension|create\s+policy|enable\s+row\s+level\s+security)\b|\$\$|::[a-z_]+/gi],[`mysql`,/\bauto_increment\b|\bengine\s*=|\bunsigned\b|`[^`\n]+`/gi],[`sqlite`,/\bautoincrement\b|\bwithout\s+rowid\b|\bpragma\b/gi]];function Aw(e){let t=null,n=0;for(let[r,i]of kw){let a=e.match(i)?.length??0;a>n&&(t=r,n=a)}return t}function jw(e,t){let n=e.toLowerCase();if(!n.endsWith(`.sql`)||Dw(e))return!1;let r=n.slice(n.lastIndexOf(`/`)+1);return/seed|fixture|sample|test|demo/.test(r)?!1:/schema|structure/.test(r)||t.has(Ow(n))||/(^|\/)docker-entrypoint-initdb\.d\//.test(n)}async function Mw(e){let t=/* @__PURE__ */ new Map,n=e.files.filter(e=>Dw(e.path)),r=new Set(n.flatMap(e=>{let t=/^(.*\/)?(migrations|db\/migrate)\//.exec(e.path.toLowerCase());return t?[t[1]??``]:[]})),i=e.files.filter(e=>jw(e.path,r)).sort((e,t)=>e.path<t.path?-1:1);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});let a=/* @__PURE__ */ new Map,o=/* @__PURE__ */ new Map;for(let r of[...i,...n]){let n=await e.readText(r);if(n===null)continue;let i=Aw(n);i&&(a.set(r.path,i),o.set(i,(o.get(i)??0)+1));for(let i of Nw(n))try{Vw(i,r.path,t,e.warnings)}catch(t){e.warnings.push(`${r.path}: could not read statement "${Zw(i)}" (${Ox(t)})`)}}let s=[...o.entries()].sort((e,t)=>t[1]-e[1])[0]?.[0]??null;return[...t.values()].filter(e=>!Tw.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,dialect:a.get(e.sourcePath)??s}})}function Nw(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(`
|
|
362
|
+
`,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 Pw(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 Fw(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 Iw=String.raw`(?:"(?:[^"]|"")+"|[A-Za-z_][\w$]*)`,Lw=String.raw`(${Iw}(?:\s*\.\s*${Iw})?)`;function Rw(e){let t=e.trim();return t.startsWith(`"`)?t.slice(1,-1).replace(/""/g,`"`):t.toLowerCase()}function zw(e){let t=e.match(new RegExp(Iw,`g`))??[e];return t.length>=2?{schema:Rw(t[0]??``),table:Rw(t[1]??``)}:{schema:`public`,table:Rw(t[0]??e)}}function Bw(e,t){return`${e}.${t}`}function Vw(e,t,n,r){if(/^create\s+(?:(?:global|local)\s+)?(?:temp(?:orary)?\s+|unlogged\s+)?table\b/i.test(e)){Hw(e,t,n,r);return}let i=new RegExp(String.raw`^alter\s+table\s+(?:if\s+exists\s+)?(?:only\s+)?${Lw}\s+(.+)$`,`i`).exec(e);if(i?.[1]&&i[2]){Yw(zw(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 Pw(a[1])){let{schema:t,table:r}=zw(e);n.delete(Bw(t,r))}}function Hw(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+)?${Lw}\s*\(`,`i`).exec(e);if(!i?.[1]){r.push(`${t}: skipped a create table statement it couldn't read: "${Zw(e)}"`);return}let{schema:a,table:o}=zw(i[1]),s=i[0].length-1,c=Uw(e,s);if(c===-1){r.push(`${t}: unbalanced parentheses in create table ${o}`);return}let l=Bw(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 Pw(e.slice(s+1,c))){if(/^(constraint|primary\s+key|unique|foreign\s+key|check|exclude|like)\b/i.test(i)){Jw(u,i,n);continue}let e=Ww(i,n);e?u.columns.push(e):r.push(`${t}: skipped column definition "${Zw(i)}" in ${o}`)}n.set(l,u)}function Uw(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 Ww(e,t){let n=Fw(e),r=n[0];if(!r||n.length<2)return null;let i=1,a=[];for(;i<n.length&&!Ew.test(n[i]??``);)a.push(n[i]),i++;if(a.length===0)return null;let o={name:Rw(r),type:a.join(` `).replace(/\s+\(/g,`(`).toLowerCase(),required:!1};return Gw(o,n.slice(i),t),o}function Gw(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&&!Ew.test(t[r+1]??``);)n.push(t[r+1]),r++;n.length>0&&(e.default=Kw(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=qw(i,a,n),r+=a?2:1}}}function Kw(e){return e.join(` `).replace(/\s+\(/g,`(`)}function qw(e,t,n){let{schema:r,table:i}=zw(e),a=r===`public`?i:`${r}.${i}`,o=t?Rw(t.slice(1,-1).split(`,`)[0]??``):null;return o||=n.get(Bw(r,i))?.columns.find(e=>e.primaryKey)?.name??`id`,`${a}.${o}`}function Jw(e,t,n){let r=t.replace(new RegExp(String.raw`^constraint\s+${Iw}\s+`,`i`),``),i=e=>(e??``).split(`,`).map(e=>Rw(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+${Lw}\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=qw(s[2],o?`(${o})`:void 0,n)})}}function Yw(e,t,n,r,i){let a=r.get(Bw(e.schema,e.table));if(!a){!Tw.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+(${Iw})$`,`i`).exec(t);if(o?.[1]){r.delete(Bw(a.schema,a.table)),a.table=Rw(o[1]),r.set(Bw(a.schema,a.table),a);return}let s=new RegExp(String.raw`^rename\s+(?:column\s+)?(${Iw})\s+to\s+(${Iw})$`,`i`).exec(t);if(s?.[1]&&s[2]){let e=a.columns.find(e=>e.name===Rw(s[1]));e&&(e.name=Rw(s[2]))}else for(let e of Pw(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=Ww(t[1],r);if(!o){i.push(`${n}: skipped "${Zw(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]){Jw(a,o[1],r);continue}let s=new RegExp(String.raw`^drop\s+(?:column\s+)?(?:if\s+exists\s+)?(${Iw})`,`i`).exec(e);if(s?.[1]&&!/^drop\s+constraint\b/i.test(e)){let e=Rw(s[1]);a.columns=a.columns.filter(t=>t.name!==e);continue}let c=new RegExp(String.raw`^alter\s+(?:column\s+)?(${Iw})\s+(.+)$`,`i`).exec(e);if(c?.[1]&&c[2]){let e=a.columns.find(e=>e.name===Rw(c[1]));e&&Xw(e,c[2])}}}function Xw(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=Kw(Fw(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 Zw(e){return e.length>60?`${e.slice(0,57)}...`:e}const Qw=[`GET`,`POST`,`PUT`,`PATCH`,`DELETE`],$w=/^(openapi|swagger)([.-][\w.-]*)?\.(json|ya?ml)$/i,eT=/\.(json|ya?ml)$/i;async function tT(e){let t=[];for(let n of e.files){let r=$w.test(Tx(n.path));if(!r&&!eT.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,ow.parse)(i)}catch(t){e.warnings.push(`${n.path}: OpenAPI file could not be parsed (${Ox(t)})`);continue}!Z(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(...nT(a,n.path,e.warnings))}return t}function nT(e,t,n){let r=typeof e.swagger==`string`,i=new rT(e,t,n),a=r?e.securityDefinitions:aT(e.components)?.securitySchemes,o=Z(a)?a:{},s=Z(e.paths)?e.paths:{},c=[];for(let[n,a]of Object.entries(s)){let s=i.resolve(a);if(s)for(let a of Qw){let l=aT(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:kx(l.summary)?.trim()||kx(l.operationId)||`${a} ${n}`,sourcePath:t,method:a,path:n,auth:yT(d,o,i),request:r?uT(u,l,e,i):sT(l.requestBody,i),responses:dT(l,e,r,i)})}}return c}var rT=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(!Z(t))return null;let e=t.$ref;if(typeof e!=`string`)return t;t=this.#i(e)}return null}refName(e){if(!Z(e)||typeof e.$ref!=`string`)return null;let t=e.$ref.slice(e.$ref.lastIndexOf(`/`)+1);return t?iT(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(!Z(t))break;t=t[iT(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 iT(e){return decodeURIComponent(e).replace(/~1/g,`/`).replace(/~0/g,`~`)}function aT(e){return Z(e)?e:null}function oT(e){if(!Z(e))return null;let t=Object.entries(e).filter(e=>Z(e[1]));return t.find(([e])=>e===`application/json`)??t.find(([e])=>/json/.test(e))??t[0]??null}function sT(e,t){let n=t.resolve(e),r=n?oT(n.content):null;return r?cT(r[0],r[1],t):null}function cT(e,t,n){let r=t.schema;return{contentType:e,fields:hT(r,n),example:lT(t,n)??vT(r,n,0)}}function lT(e,t){if(e.example!==void 0)return e.example;if(Z(e.examples)){let n=t.resolve(Object.values(e.examples)[0]);if(n&&n.value!==void 0)return n.value}}function uT(e,t,n,r){let i=e.map(e=>r.resolve(e)).filter(e=>e!==null),a=pT(t.consumes)??pT(n.consumes),o=i.find(e=>e.in===`body`);if(o)return{contentType:a??`application/json`,fields:hT(o.schema,r),example:vT(o.schema,r,0)};let s=i.filter(e=>e.in===`formData`);if(s.length===0)return null;let c=s.map(e=>({name:kx(e.name)??``,type:_T(e,r),required:e.required===!0,...gT(e)}));return{contentType:a??`application/x-www-form-urlencoded`,fields:c,example:Object.fromEntries(s.map(e=>[kx(e.name)??``,vT(e,r,1)]))}}function dT(e,t,n,r){if(!Z(e.responses))return[];let i=pT(e.produces)??pT(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=aT(e.examples);s={contentType:i,fields:hT(e.schema,r),example:t?.[i]??vT(e.schema,r,0)}}}else{let t=oT(e.content);t&&(s=cT(t[0],t[1],r))}a.push({status:fT(t),description:kx(e.description)??``,body:s})}return a}function fT(e){let t=e.replace(/x/gi,`0`),n=Number.parseInt(t,10);return Number.isNaN(n)?0:n}function pT(e){return Array.isArray(e)&&typeof e[0]==`string`?e[0]:void 0}function mT(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=mT(a,t,n+1);r&&(Z(r.properties)&&Object.assign(e,r.properties),Array.isArray(r.required)&&i.push(...r.required.filter(e=>typeof e==`string`)))}return Z(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?mT(i[0],t,n+1):r}function hT(e,t){let n=mT(e,t);if(n?.type===`array`&&(n=mT(n.items,t)),!n||!Z(n.properties))return[];let r=new Set(Array.isArray(n.required)?n.required:[]);return Object.entries(n.properties).map(([e,n])=>{let i=mT(n,t)??{};return{name:e,type:_T(n,t),required:r.has(e),...gT(i)}})}function gT(e){let t={},n=kx(e.description)?.trim();return n&&(t.description=n),Array.isArray(e.enum)&&(t.values=e.enum.map(e=>String(e))),t}function _T(e,t,n=0){let r=t.refName(e),i=mT(e,t);if(!i)return r??`unknown`;let a=Array.isArray(i.type)?i.type.filter(e=>e!==`null`).join(` | `):kx(i.type);return a===`array`?n>8?`array`:`${_T(i.items,t,n+1)}[]`:r&&(a===`object`||a===void 0)?r:kx(i.format)??a??(i.properties?`object`:`unknown`)}function vT(e,t,n){let r=mT(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&&Z(r.properties)){let e=Z(r.properties)?r.properties:{};return Object.fromEntries(Object.entries(e).map(([e,r])=>[e,vT(r,t,n+1)]))}switch(i){case`array`:return[vT(r.items,t,n+1)];case`string`:return`string`;case`integer`:case`number`:return 0;case`boolean`:return!1;default:return null}}function yT(e,t,n){if(!Array.isArray(e)||e.length===0)return null;let r=[];for(let i of e){if(!Z(i))continue;let e=Object.keys(i);e.length===0?r.push(`none`):r.push(e.map(e=>bT(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 bT(e,t){if(!t)return e;switch(kx(t.type)?.toLowerCase()){case`http`:{let e=kx(t.scheme)?.toLowerCase();if(e===`bearer`){let e=kx(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 ${kx(t.in)??`header`} ${kx(t.name)??e}`;case`oauth2`:return`OAuth2`;case`openidconnect`:return`OpenID Connect`;case`mutualtls`:return`Mutual TLS`;default:return e}}const xT=[`readme.md`,`readme.mdx`,`readme.markdown`,`readme.txt`,`readme`];async function ST(e){let t=e.files.find(e=>!e.path.includes(`/`)&&xT.includes(e.path.toLowerCase()));if(!t)return null;let n=await e.readText(t);return{path:t.path,oneLiner:n===null?null:CT(n)}}function CT(e){let t=e.replace(/\r\n/g,`
|
|
363
363
|
`).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(`
|
|
364
|
-
`).map(e=>e.trim()).filter(Boolean),n=t[0];if(!n||/^(#|=+$|-+$|\||[-*+] |\d+\. |>|<|\[!\[|!\[)/.test(n)||/^ {4}|^\t/.test(e))continue;let r=ST(t.join(` `));if(!(r.length<15||!/[a-z]/i.test(r)))return CT(/^.+?[.!?](?=\s+["'([]?[A-Z]|\s*$)/.exec(r)?.[0]??r,200)}return null}function ST(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 CT(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 wT={name:`Supabase`,type:`database`,provider:`Supabase Postgres`},TT={name:`Postgres`,type:`database`,provider:`Postgres`},ET={name:`MySQL`,type:`database`,provider:`MySQL`},DT={name:`MongoDB`,type:`database`,provider:`MongoDB`},OT={name:`Redis`,type:`database`,provider:`Redis`},kT={name:`Elasticsearch`,type:`database`,provider:`Elasticsearch`},AT={name:`AWS S3`,type:`storage`,provider:`AWS S3`},jT={name:`AWS SQS`,type:`queue`,provider:`AWS SQS`},MT={name:`AWS`,type:`service`,provider:`AWS`},NT={name:`MinIO`,type:`storage`,provider:`MinIO`},PT={name:`Cloudinary`,type:`storage`,provider:`Cloudinary`},FT={name:`RabbitMQ`,type:`queue`,provider:`RabbitMQ`},IT={name:`Kafka`,type:`queue`,provider:`Kafka`},LT={name:`Stripe`,type:`external_api`,provider:`Stripe`},RT={name:`Twilio`,type:`external_api`,provider:`Twilio`},zT={name:`SendGrid`,type:`service`,provider:`SendGrid`},BT={name:`Postmark`,type:`service`,provider:`Postmark`},VT={name:`Resend`,type:`service`,provider:`Resend`},HT={name:`Mailgun`,type:`service`,provider:`Mailgun`},UT={name:`Email (SMTP)`,type:`service`,provider:`SMTP`},WT={name:`Firebase`,type:`service`,provider:`Firebase`},GT={name:`OpenAI`,type:`external_api`,provider:`OpenAI`},KT={name:`Anthropic`,type:`external_api`,provider:`Anthropic`},qT={name:`Sentry`,type:`service`,provider:`Sentry`},JT={name:`Auth0`,type:`auth`,provider:`Auth0`},YT={name:`Clerk`,type:`auth`,provider:`Clerk`},XT={name:`Auth.js`,type:`auth`,provider:`Auth.js`},ZT={name:`Algolia`,type:`external_api`,provider:`Algolia`},QT={name:`Google Cloud`,type:`service`,provider:`Google Cloud`},$T={name:`Cloud Storage`,type:`storage`,provider:`Google Cloud Storage`},eE={name:`Pub/Sub`,type:`queue`,provider:`Google Cloud Pub/Sub`},tE={name:`BigQuery`,type:`database`,provider:`Google BigQuery`},nE={name:`Firestore`,type:`database`,provider:`Google Firestore`},rE={name:`Secret Manager`,type:`service`,provider:`Google Secret Manager`},iE={name:`Gemini`,type:`external_api`,provider:`Google Gemini`},aE={name:`Vertex AI`,type:`external_api`,provider:`Google Vertex AI`},oE={name:`SerpApi`,type:`external_api`,provider:`SerpApi`},sE={name:`Zyte`,type:`external_api`,provider:`Zyte`},cE={name:`Open Exchange Rates`,type:`external_api`,provider:`Open Exchange Rates`},lE={name:`reCAPTCHA`,type:`external_api`,provider:`Google reCAPTCHA`},uE={name:`DuckDB`,type:`database`,provider:`DuckDB`},dE=[[/^SUPABASE_/,wT],[/^(DATABASE_URL|POSTGRES_|PG(HOST|USER|PASSWORD|DATABASE|PORT)$)/,TT],[/^MYSQL_/,ET],[/^MONGO(DB)?_/,DT],[/^(REDIS_|UPSTASH_REDIS_)/,OT],[/^(ELASTIC(SEARCH)?_)/,kT],[/^(AWS_)?S3_|_S3_BUCKET$|^AWS_BUCKET/,AT],[/^(AWS_)?SQS_/,jT],[/^AWS_(ACCESS_KEY_ID|SECRET_ACCESS_KEY|REGION|DEFAULT_REGION)$/,MT],[/^MINIO_/,NT],[/^CLOUDINARY_/,PT],[/^(RABBITMQ_|AMQP_URL)/,FT],[/^KAFKA_/,IT],[/^STRIPE_/,LT],[/^TWILIO_/,RT],[/^SENDGRID_/,zT],[/^POSTMARK_/,BT],[/^RESEND_/,VT],[/^MAILGUN_/,HT],[/^SMTP_/,UT],[/^FIREBASE_/,WT],[/^OPENAI_/,GT],[/^ANTHROPIC_/,KT],[/^SENTRY_/,qT],[/^AUTH0_/,JT],[/^CLERK_/,YT],[/^(NEXTAUTH_|AUTH_SECRET$)/,XT],[/^ALGOLIA_/,ZT],[/^(GCS_BUCKET|GOOGLE_CLOUD_STORAGE_|GCS_)/,$T],[/^(PUBSUB_|GOOGLE_PUBSUB_)/,eE],[/^BIGQUERY_/,tE],[/^FIRESTORE_/,nE],[/^(GEMINI_|GOOGLE_GENAI_)/,iE],[/^VERTEX(_AI)?_/,aE],[/^(SERPAPI_|SERP_API_)/,oE],[/^ZYTE_/,sE],[/^(OPEN_EXCHANGE_RATES_|OPENEXCHANGERATES_|OXR_)/,cE],[/^RECAPTCHA_/,lE],[/^(GOOGLE_CLOUD_PROJECT|GCP_PROJECT(_ID)?|GCLOUD_PROJECT|GOOGLE_APPLICATION_CREDENTIALS)$/,QT]],fE=[[[`@supabase/supabase-js`,`@supabase/ssr`,`supabase`,`github.com/supabase-community/*`,`supabase/supabase-php`],wT],[[`pg`,`postgres`,`pg-promise`,`@neondatabase/serverless`,`@vercel/postgres`,`psycopg2`,`psycopg2-binary`,`psycopg`,`asyncpg`,`github.com/jackc/pgx*`,`github.com/lib/pq`],TT],[[`mysql`,`mysql2`,`pymysql`,`mysqlclient`,`github.com/go-sql-driver/mysql`],ET],[[`mongodb`,`mongoose`,`pymongo`,`motor`,`go.mongodb.org/mongo-driver*`,`mongodb/mongodb`],DT],[[`redis`,`ioredis`,`@upstash/redis`,`predis/predis`,`github.com/redis/go-redis*`,`github.com/go-redis/redis*`],OT],[[`@elastic/elasticsearch`,`elasticsearch`,`elasticsearch/elasticsearch`],kT],[[`@aws-sdk/client-s3`,`github.com/aws/aws-sdk-go-v2/service/s3`,`league/flysystem-aws-s3-v3`],AT],[[`@aws-sdk/client-sqs`,`github.com/aws/aws-sdk-go-v2/service/sqs`],jT],[[`aws-sdk`,`boto3`,`aws/aws-sdk-php`,`github.com/aws/aws-sdk-go`],MT],[[`minio`],NT],[[`cloudinary`,`cloudinary/cloudinary_php`],PT],[[`amqplib`,`pika`,`php-amqplib/php-amqplib`,`github.com/rabbitmq/amqp091-go`],FT],[[`kafkajs`,`kafka-python`,`confluent-kafka`,`github.com/segmentio/kafka-go`],IT],[[`stripe`,`@stripe/stripe-js`,`@stripe/react-stripe-js`,`stripe/stripe-php`,`github.com/stripe/stripe-go*`],LT],[[`twilio`,`twilio/sdk`,`github.com/twilio/twilio-go`],RT],[[`@sendgrid/`,`sendgrid`,`sendgrid/sendgrid`],zT],[[`postmark`,`wildbit/postmark-php`],BT],[[`resend`,`resend/resend-php`],VT],[[`mailgun.js`,`mailgun/mailgun-php`],HT],[[`nodemailer`],UT],[[`firebase`,`firebase-admin`,`firebase-functions`,`kreait/firebase-php`,`firebase.google.com/go*`],WT],[[`openai`,`openai-php/client`,`github.com/sashabaranov/go-openai`],GT],[[`@anthropic-ai/sdk`,`anthropic`,`github.com/anthropics/anthropic-sdk-go`],KT],[[`@sentry/`,`sentry-sdk`,`sentry/sentry`,`sentry/sentry-laravel`,`github.com/getsentry/sentry-go`],qT],[[`@auth0/`,`auth0`,`auth0/auth0-php`],JT],[[`@clerk/`],YT],[[`next-auth`,`@auth/`],XT],[[`algoliasearch`,`algolia/algoliasearch-client-php`],ZT],[[`@google-cloud/storage`,`google-cloud-storage`,`cloud.google.com/go/storage`],$T],[[`@google-cloud/pubsub`,`google-cloud-pubsub`,`cloud.google.com/go/pubsub*`],eE],[[`@google-cloud/bigquery`,`google-cloud-bigquery`,`cloud.google.com/go/bigquery`],tE],[[`@google-cloud/firestore`,`google-cloud-firestore`,`cloud.google.com/go/firestore`],nE],[[`@google-cloud/secret-manager`,`google-cloud-secret-manager`,`cloud.google.com/go/secretmanager`],rE],[[`@google/genai`,`@google/generative-ai`,`google-genai`,`google-generativeai`],iE],[[`@google-cloud/vertexai`,`google-cloud-aiplatform`,`vertexai`],aE],[[`serpapi`,`google-search-results`],oE],[[`zyte-api`,`scrapy-zyte-api`],sE],[[`open-exchange-rates`],cE],[[`react-google-recaptcha`,`react-google-recaptcha-v3`,`vue-recaptcha`,`vue-recaptcha-v3`,`@google-cloud/recaptcha-enterprise`,`google-cloud-recaptcha-enterprise`,`django-recaptcha`],lE],[[`@google-cloud/`,`google-cloud-*`,`google-auth-library`,`google-auth`,`cloud.google.com/go*`],QT],[[`duckdb`,`@duckdb/`],uE]],pE=[[/^supabase\//,wT],[/(^|\/)(postgres|postgis|timescaledb)$/,TT],[/(^|\/)(mysql|mariadb)$/,ET],[/(^|\/)mongo(db)?$/,DT],[/(^|\/)(redis|redis-stack|valkey)$/,OT],[/(^|\/)(elasticsearch|opensearch)$/,kT],[/(^|\/)minio$/,NT],[/(^|\/)rabbitmq$/,FT],[/(^|\/)(kafka|cp-kafka)$/,IT],[/(^|\/)localstack$/,MT],[/(^|\/)(cloud-sdk|google-cloud-cli)$/,QT],[/(^|\/)(gcloud-pubsub-emulator|pubsub-emulator)$/,eE],[/(^|\/)fake-gcs-server$/,$T]];function mE(e){return/^\.env(\.[\w-]+)*\.(example|sample|template|dist)$/i.test(e)||/^(example|sample)\.env$/i.test(e)}function hE(e){let t=Tx(e);return/^\.gitlab-ci\.ya?ml$/.test(t)||/^cloudbuild\.ya?ml$/.test(t)||t===`bitbucket-pipelines.yml`||/(^|\/)\.github\/workflows\/[^/]+\.ya?ml$/.test(e)}function gE(e){return[...new Set(e.match(/\b[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+\b/g)??[])]}function _E(e){return/^(docker-)?compose([.-][\w.-]+)?\.ya?ml$/i.test(e)}var vE=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 yE(e,t){let n=new vE,r=(e,t)=>{let r=e.replace(/^(NEXT_PUBLIC_|VITE_|PUBLIC_|REACT_APP_|EXPO_PUBLIC_|NUXT_PUBLIC_|NUXT_)/,``),i=dE.find(([e])=>e.test(r));i&&n.add(i[1],t)};for(let t of e.files){let i=Tx(t.path);if(mE(i)){let n=await e.readText(t);if(n===null)continue;for(let e of bE(n))r(e,`env: ${e} (${t.path})`)}else if(hE(t.path)){let n=await e.readText(t);if(n===null)continue;for(let e of gE(n))r(e,`pipeline: ${e} (${t.path})`)}else if(_E(i)){let i=await e.readText(t);if(i===null)continue;let a;try{a=(0,ow.parse)(i)}catch(n){e.warnings.push(`${t.path}: could not be parsed (${Ox(n)})`);continue}let o=Z(a)&&Z(a.services)?a.services:{};for(let[e,i]of Object.entries(o)){if(!Z(i))continue;let a=i.environment,o=Array.isArray(a)?a.map(e=>String(e).split(`=`,1)[0]??``):Z(a)?Object.keys(a):[];for(let n of o)r(n,`docker-compose: ${e} env ${n} in ${t.path}`);if(typeof i.image!=`string`)continue;let s=xE(i.image),c=pE.find(([e])=>e.test(s));c&&n.add(c[1],`docker-compose: service ${e} (${i.image}) in ${t.path}`)}}else t.path===`supabase/config.toml`||t.path.endsWith(`/supabase/config.toml`)?n.add(wT,`file: ${t.path}`):i===`firebase.json`?n.add(WT,`file: ${t.path}`):/^cloudbuild\.ya?ml$/.test(i)&&n.add(QT,`file: ${t.path}`)}for(let e of t){if(!e.direct)continue;let t=fE.find(([t])=>t.some(t=>SE(t,e.package)));t&&n.add(t[1],`dependency: ${e.package} (${e.sourceLockfile})`)}return n.list()}function bE(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 xE(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 SE(e,t){return e.endsWith(`*`)?t.startsWith(e.slice(0,-1)):e.endsWith(`/`)?t.startsWith(e):t===e}async function CE(e,{fromDisk:t=!1}={}){let n=_.resolve(e);if(!(await p(n)).isDirectory())throw Error(`${n} is not a folder`);let r=(/* @__PURE__ */ new Date()).toISOString(),i=[],a=t?null:await PS(n);!t&&!a&&C(_.join(n,`.git`))&&i.push(`No main or master branch found: read the files on disk instead`);let o=a?await Sx(n,a.ref):await xx(n),s=await yS(o),[c,l,u,d,f,m,h]=await Promise.all([IS(n,i,a?.ref??null),bT(o),xw(o),xS(o,s),OS(o),$w(o),Aw(o)]),g=await yE(o,u);return{scannedAt:r,root:n,repo:{...c,languages:ww(o.files),readme:l},dependencies:u,docs:d,agentInstructions:f,contracts:[...m,...h],resources:g,docsConfig:{alwaysLoad:!!s.alwaysLoad},warnings:[...i,...o.warnings]}}function wE(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`}function TE(e){let{scannedRef:t,headSha:n}=e.repo;if(!t)return`files on disk`;let r=t.replace(/^origin\//,``);return n?`${r} @ ${n.slice(0,7)}`:r}async function EE(e,t,{quiet:n=!1,source:r=`connector`,name:i,restore:a}={}){await FS(e);let o=await CE(e),s=(i??t.repoName)?.trim();s&&Object.assign(o.repo,{name:s,nameFromConfig:!0}),a&&Object.assign(o.repo,{restore:!0});let c=await new Wr(await ox()).call(`sync_repo`,{p_project:t.projectId,p_snapshot:o,p_source:r});if(!n){Rx(`Synced ${Px(o.repo.name)} to ${Px(t.name)} ${Q(`from ${TE(o)}`)}`),zx(Q(wE(c)));for(let e of o.warnings)zx(Q(`! ${e}`))}return{snapshot:o,result:c}}async function DE(e){return jS(await xx(e))}const OE=26214400,kE=e=>`${(e/1024/1024).toFixed(1)} MB`;async function AE(e,t,{quiet:n=!1}={}){if(!t.folder)return;let{docs:r,unsupported:i}=await DE(e),a=e=>Buffer.byteLength(e.body),o=r.reduce((e,t)=>e+a(t),0);if(o>OE){let t=/* @__PURE__ */ new Map;for(let e of r){let n=e.path.includes(`/`)?`${e.path.split(`/`)[0]}/`:e.path;t.set(n,(t.get(n)??0)+a(e))}let n=[...t].sort((e,t)=>t[1]-e[1]).slice(0,3).map(([e,t])=>`${e} (${kE(t)})`).join(`, `);throw new Ux(`The documents outside the repos add up to ${kE(o)}, over the ${kE(OE)} a sync takes. The biggest: ${n}. List what Quirl should skip in ${x(v(e),`.quirlignore`)}, like .gitignore.`)}let s=new Wr(await ox()),c={p_project:t.projectId,p_folder:t.folder},l=await s.call(`folder_doc_hashes`,c),u=r.filter(e=>l[e.path]!==e.contentHash),d=0;for(let t=0;t<u.length;){let n=[],r=0;for(;t<u.length;){let e=u[t];if(n.length&&r+a(e)>2097152)break;n.push(e),r+=a(e),t++}let i=await s.call(`sync_folder_docs`,{...c,p_folder_name:v(e),p_docs:n});d+=i.docsChanged}let f={...await s.call(`sync_folder_finish`,{...c,p_paths:r.map(e=>e.path)}),docsChanged:d};return n||(Rx(`Synced the documents in ${Px(`${v(e)}/`)} outside the repos`),zx(Q(`${f.docs} docs (${f.docsChanged} changed${f.archived?`, ${f.archived} removed`:``})`)),i.length&&zx(Q(`! ${i.length} PDF/Office files skipped: only markdown and text are read for now`))),f}async function jE(e={}){let t=await ux();if(!t)throw new Ux("This folder isn't linked to a Quirl project. Run `quirl init`.");let n=sx(t.link),r=n.length?n.map(e=>({root:x(t.root,e.path),name:e.name})):[{root:t.root,name:void 0}],i=r.length+ +!!t.link.folder,a=0;for(let{root:o,name:s}of r)try{let r=n.length?await ux(o):null,i=s??(r?.root===o?r.link.repoName:void 0);await EE(o,t.link,{...e,name:i})}catch(e){if(a++,i===1)throw e;let n=S(t.root,o)||`.`;console.error(`${Ix(`✗`)} ${n}: ${Ox(e)}`)}if(t.link.folder)try{await AE(t.root,t.link,e)}catch(e){a++,console.error(`${Ix(`✗`)} documents in ${v(t.root)}/: ${Ox(e)}`)}if(a)throw new Ux(`${a} of ${i} parts didn't sync.`)}async function ME(e){let t=cx(),n=await Zx(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🌀 ${Px(`Quirl`)} ${Q(`·`)} connecting ${Px(s)}`),i&&(Bx(`📁`,`Found ${r.length} ${r.length===1?`repo`:`repos`}`),Vx(Q(r.map(a).join(` · `))),!await Gx(` Import all of them into one project?`,!0)))throw new Ux("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 DE(t);if(e.length){Bx(`📄`,`Also found ${e.length} ${e.length===1?`document`:`documents`} outside the repos`);for(let t of e.slice(0,8))Vx(Q(t.path));e.length>8&&Vx(Q(`…and ${e.length-8} more`)),n.length&&Vx(Q(`(${n.length} PDF/Office files can't be read yet and are skipped)`)),c=await Gx(` Import them too? Everyone on the project will be able to read them.`,!0)}}await rx()||await dS({quiet:!0});let l=await PE((await new Wr(await ox()).whoami()).projects,e.project??(await ux(t))?.link.project);if(l.role===`stakeholder`)throw new Ux(`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};Bx(`🔗`,`Linked to ${Px(l.name)} ${Q(`· ${l.organization}`)}`);let d=e.claude!==!1,f=e.hooks??await Gx(` Sync with Quirl on every git push?`,!0);Bx(`📦`,`Importing docs, dependencies and schemas`);let p=[],m=i?await ux(t):null,g=new Map((m?.root===t?sx(m.link):[]).filter(e=>e.name).map(e=>[e.path,e.name]));for(let e of r){let t=Hx(`Reading ${a(e)}…`);try{let n=await ux(e),r=(n?.root===e?n.link.repoName:void 0)??g.get(a(e));r&&g.set(a(e),r);let i=r?{...u,repoName:r}:u;await dx(e,i);let{snapshot:o,result:s}=await EE(e,i,{quiet:!0,restore:!0});d&&await NE(e,l.name),f&&await uS(e),t.stop(),Vx(`${Fx(`✓`)} ${Px(a(e))} ${Q(`(${TE(o)})`)} ${Q(wE(s))}`);for(let e of o.warnings)Vx(Q(` ! ${e}`));p.push(e)}catch(n){t.stop(),Vx(`${Ix(`✗`)} ${Px(a(e))} ${Ox(n)}`)}}if(!p.length)throw new Ux(`No repo was imported.`);if(i){let e=p.map(e=>{let t=g.get(a(e));return t?{path:a(e),name:t}:a(e)}),n=m,r={...u,repos:e,folder:c?n?.root===t&&n.link.folder||ee():void 0};if(await dx(t,r),c)try{let e=await AE(t,r,{quiet:!0});Vx(`${Fx(`✓`)} ${Px(`documents outside the repos`)} ${Q(`${e?.docs??0} docs`)}`)}catch(e){Vx(`${Ix(`✗`)} ${Px(`documents outside the repos`)} ${Ox(e)}`)}d&&!p.includes(t)&&await NE(t,l.name,p.map(a))}let _=tS().portable;d&&(Bx(`🤖`,`Connected Claude Code`),Vx(Q(`.mcp.json the quirl tools`)),Vx(Q(`.claude/settings.json the briefing, loaded as each session starts`)),Vx(Q(`CLAUDE.md when to use Quirl`))),f&&Bx(`🪝`,`Quirl syncs on every ${Px(`git push`)}`);let y=r.length-p.length,b=`.quirl .mcp.json .claude/settings.json CLAUDE.md`;Bx(y?`⚠️ `:`🎉`,y?`Done, but ${y} of ${r.length} repos failed. Fix them and run ${Px(`quirl init`)} again.`:Px(`All set!`)),Vx(d&&!_?Q(`Don't commit ${b} yet: they point at this checkout until the CLI is installed.`):`${Q(`1.`)} Commit what was added${i?` in each repo`:``}: ${Lx(`git add ${b}`)}`),Vx(`${Q(d&&!_?`→`:`2.`)} Start Claude Code here and approve the ${Px(`quirl`)} server when it asks.`),i&&!p.includes(t)&&Vx(Q("Run `quirl sync` here to sync every repo at once.")),console.log(``)}async function NE(e,t,n=[]){await sS(e),await cS(e),await lS(e,t,n)}async function PE(e,t){if(!e.length)throw new Ux(`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 Ux(`No project "${t}" among yours: ${e.map(e=>e.slug).join(`, `)}.`);return n}if(e.length===1)return e[0];Bx(`🗂️ `,`Which project is this part of?`);for(let[t,n]of e.entries())Vx(`${Lx(String(t+1))} ${n.name} ${Q(`· ${n.organization} · ${n.role}`)}`);let n=e[Number(await Wx(` Project [1-${e.length}]: `))-1];if(!n)throw new Ux("No project picked. Run `quirl init --project <slug>`.");return n}const FE=`${Px(`quirl`)} ${Q(Zb)}: connect a repo to Quirl
|
|
364
|
+
`).map(e=>e.trim()).filter(Boolean),n=t[0];if(!n||/^(#|=+$|-+$|\||[-*+] |\d+\. |>|<|\[!\[|!\[)/.test(n)||/^ {4}|^\t/.test(e))continue;let r=wT(t.join(` `));if(!(r.length<15||!/[a-z]/i.test(r)))return TT(/^.+?[.!?](?=\s+["'([]?[A-Z]|\s*$)/.exec(r)?.[0]??r,200)}return null}function wT(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 TT(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 ET={name:`Supabase`,type:`database`,provider:`Supabase Postgres`},DT={name:`Postgres`,type:`database`,provider:`Postgres`},OT={name:`MySQL`,type:`database`,provider:`MySQL`},kT={name:`MongoDB`,type:`database`,provider:`MongoDB`},AT={name:`Redis`,type:`database`,provider:`Redis`},jT={name:`Elasticsearch`,type:`database`,provider:`Elasticsearch`},MT={name:`AWS S3`,type:`storage`,provider:`AWS S3`},NT={name:`AWS SQS`,type:`queue`,provider:`AWS SQS`},PT={name:`AWS`,type:`service`,provider:`AWS`},FT={name:`MinIO`,type:`storage`,provider:`MinIO`},IT={name:`Cloudinary`,type:`storage`,provider:`Cloudinary`},LT={name:`RabbitMQ`,type:`queue`,provider:`RabbitMQ`},RT={name:`Kafka`,type:`queue`,provider:`Kafka`},zT={name:`Stripe`,type:`external_api`,provider:`Stripe`},BT={name:`Twilio`,type:`external_api`,provider:`Twilio`},VT={name:`SendGrid`,type:`service`,provider:`SendGrid`},HT={name:`Postmark`,type:`service`,provider:`Postmark`},UT={name:`Resend`,type:`service`,provider:`Resend`},WT={name:`Mailgun`,type:`service`,provider:`Mailgun`},GT={name:`Email (SMTP)`,type:`service`,provider:`SMTP`},KT={name:`Firebase`,type:`service`,provider:`Firebase`},qT={name:`OpenAI`,type:`external_api`,provider:`OpenAI`},JT={name:`Anthropic`,type:`external_api`,provider:`Anthropic`},YT={name:`Sentry`,type:`service`,provider:`Sentry`},XT={name:`Auth0`,type:`auth`,provider:`Auth0`},ZT={name:`Clerk`,type:`auth`,provider:`Clerk`},QT={name:`Auth.js`,type:`auth`,provider:`Auth.js`},$T={name:`Algolia`,type:`external_api`,provider:`Algolia`},eE={name:`Google Cloud`,type:`service`,provider:`Google Cloud`},tE={name:`Cloud Storage`,type:`storage`,provider:`Google Cloud Storage`},nE={name:`Pub/Sub`,type:`queue`,provider:`Google Cloud Pub/Sub`},rE={name:`BigQuery`,type:`database`,provider:`Google BigQuery`},iE={name:`Firestore`,type:`database`,provider:`Google Firestore`},aE={name:`Secret Manager`,type:`service`,provider:`Google Secret Manager`},oE={name:`Gemini`,type:`external_api`,provider:`Google Gemini`},sE={name:`Vertex AI`,type:`external_api`,provider:`Google Vertex AI`},cE={name:`SerpApi`,type:`external_api`,provider:`SerpApi`},lE={name:`Zyte`,type:`external_api`,provider:`Zyte`},uE={name:`Open Exchange Rates`,type:`external_api`,provider:`Open Exchange Rates`},dE={name:`reCAPTCHA`,type:`external_api`,provider:`Google reCAPTCHA`},fE={name:`DuckDB`,type:`database`,provider:`DuckDB`},pE=[[/^SUPABASE_/,ET],[/^(DATABASE_URL|POSTGRES_|PG(HOST|USER|PASSWORD|DATABASE|PORT)$)/,DT],[/^MYSQL_/,OT],[/^MONGO(DB)?_/,kT],[/^(REDIS_|UPSTASH_REDIS_)/,AT],[/^(ELASTIC(SEARCH)?_)/,jT],[/^(AWS_)?S3_|_S3_BUCKET$|^AWS_BUCKET/,MT],[/^(AWS_)?SQS_/,NT],[/^AWS_(ACCESS_KEY_ID|SECRET_ACCESS_KEY|REGION|DEFAULT_REGION)$/,PT],[/^MINIO_/,FT],[/^CLOUDINARY_/,IT],[/^(RABBITMQ_|AMQP_URL)/,LT],[/^KAFKA_/,RT],[/^STRIPE_/,zT],[/^TWILIO_/,BT],[/^SENDGRID_/,VT],[/^POSTMARK_/,HT],[/^RESEND_/,UT],[/^MAILGUN_/,WT],[/^SMTP_/,GT],[/^FIREBASE_/,KT],[/^OPENAI_/,qT],[/^ANTHROPIC_/,JT],[/^SENTRY_/,YT],[/^AUTH0_/,XT],[/^CLERK_/,ZT],[/^(NEXTAUTH_|AUTH_SECRET$)/,QT],[/^ALGOLIA_/,$T],[/^(GCS_BUCKET|GOOGLE_CLOUD_STORAGE_|GCS_)/,tE],[/^(PUBSUB_|GOOGLE_PUBSUB_)/,nE],[/^BIGQUERY_/,rE],[/^FIRESTORE_/,iE],[/^(GEMINI_|GOOGLE_GENAI_)/,oE],[/^VERTEX(_AI)?_/,sE],[/^(SERPAPI_|SERP_API_)/,cE],[/^ZYTE_/,lE],[/^(OPEN_EXCHANGE_RATES_|OPENEXCHANGERATES_|OXR_)/,uE],[/^RECAPTCHA_/,dE],[/^(GOOGLE_CLOUD_PROJECT|GCP_PROJECT(_ID)?|GCLOUD_PROJECT|GOOGLE_APPLICATION_CREDENTIALS)$/,eE]],mE=[[[`@supabase/supabase-js`,`@supabase/ssr`,`supabase`,`github.com/supabase-community/*`,`supabase/supabase-php`],ET],[[`pg`,`postgres`,`pg-promise`,`@neondatabase/serverless`,`@vercel/postgres`,`psycopg2`,`psycopg2-binary`,`psycopg`,`asyncpg`,`github.com/jackc/pgx*`,`github.com/lib/pq`],DT],[[`mysql`,`mysql2`,`pymysql`,`mysqlclient`,`github.com/go-sql-driver/mysql`],OT],[[`mongodb`,`mongoose`,`pymongo`,`motor`,`go.mongodb.org/mongo-driver*`,`mongodb/mongodb`],kT],[[`redis`,`ioredis`,`@upstash/redis`,`predis/predis`,`github.com/redis/go-redis*`,`github.com/go-redis/redis*`],AT],[[`@elastic/elasticsearch`,`elasticsearch`,`elasticsearch/elasticsearch`],jT],[[`@aws-sdk/client-s3`,`github.com/aws/aws-sdk-go-v2/service/s3`,`league/flysystem-aws-s3-v3`],MT],[[`@aws-sdk/client-sqs`,`github.com/aws/aws-sdk-go-v2/service/sqs`],NT],[[`aws-sdk`,`boto3`,`aws/aws-sdk-php`,`github.com/aws/aws-sdk-go`],PT],[[`minio`],FT],[[`cloudinary`,`cloudinary/cloudinary_php`],IT],[[`amqplib`,`pika`,`php-amqplib/php-amqplib`,`github.com/rabbitmq/amqp091-go`],LT],[[`kafkajs`,`kafka-python`,`confluent-kafka`,`github.com/segmentio/kafka-go`],RT],[[`stripe`,`@stripe/stripe-js`,`@stripe/react-stripe-js`,`stripe/stripe-php`,`github.com/stripe/stripe-go*`],zT],[[`twilio`,`twilio/sdk`,`github.com/twilio/twilio-go`],BT],[[`@sendgrid/`,`sendgrid`,`sendgrid/sendgrid`],VT],[[`postmark`,`wildbit/postmark-php`],HT],[[`resend`,`resend/resend-php`],UT],[[`mailgun.js`,`mailgun/mailgun-php`],WT],[[`nodemailer`],GT],[[`firebase`,`firebase-admin`,`firebase-functions`,`kreait/firebase-php`,`firebase.google.com/go*`],KT],[[`openai`,`openai-php/client`,`github.com/sashabaranov/go-openai`],qT],[[`@anthropic-ai/sdk`,`anthropic`,`github.com/anthropics/anthropic-sdk-go`],JT],[[`@sentry/`,`sentry-sdk`,`sentry/sentry`,`sentry/sentry-laravel`,`github.com/getsentry/sentry-go`],YT],[[`@auth0/`,`auth0`,`auth0/auth0-php`],XT],[[`@clerk/`],ZT],[[`next-auth`,`@auth/`],QT],[[`algoliasearch`,`algolia/algoliasearch-client-php`],$T],[[`@google-cloud/storage`,`google-cloud-storage`,`cloud.google.com/go/storage`],tE],[[`@google-cloud/pubsub`,`google-cloud-pubsub`,`cloud.google.com/go/pubsub*`],nE],[[`@google-cloud/bigquery`,`google-cloud-bigquery`,`cloud.google.com/go/bigquery`],rE],[[`@google-cloud/firestore`,`google-cloud-firestore`,`cloud.google.com/go/firestore`],iE],[[`@google-cloud/secret-manager`,`google-cloud-secret-manager`,`cloud.google.com/go/secretmanager`],aE],[[`@google/genai`,`@google/generative-ai`,`google-genai`,`google-generativeai`],oE],[[`@google-cloud/vertexai`,`google-cloud-aiplatform`,`vertexai`],sE],[[`serpapi`,`google-search-results`],cE],[[`zyte-api`,`scrapy-zyte-api`],lE],[[`open-exchange-rates`],uE],[[`react-google-recaptcha`,`react-google-recaptcha-v3`,`vue-recaptcha`,`vue-recaptcha-v3`,`@google-cloud/recaptcha-enterprise`,`google-cloud-recaptcha-enterprise`,`django-recaptcha`],dE],[[`@google-cloud/`,`google-cloud-*`,`google-auth-library`,`google-auth`,`cloud.google.com/go*`],eE],[[`duckdb`,`@duckdb/`],fE]],hE=[[/^supabase\//,ET],[/(^|\/)(postgres|postgis|timescaledb)$/,DT],[/(^|\/)(mysql|mariadb)$/,OT],[/(^|\/)mongo(db)?$/,kT],[/(^|\/)(redis|redis-stack|valkey)$/,AT],[/(^|\/)(elasticsearch|opensearch)$/,jT],[/(^|\/)minio$/,FT],[/(^|\/)rabbitmq$/,LT],[/(^|\/)(kafka|cp-kafka)$/,RT],[/(^|\/)localstack$/,PT],[/(^|\/)(cloud-sdk|google-cloud-cli)$/,eE],[/(^|\/)(gcloud-pubsub-emulator|pubsub-emulator)$/,nE],[/(^|\/)fake-gcs-server$/,tE]];function gE(e){return/^\.env(\.[\w-]+)*\.(example|sample|template|dist)$/i.test(e)||/^(example|sample)\.env$/i.test(e)}function _E(e){let t=Tx(e);return/^\.gitlab-ci\.ya?ml$/.test(t)||/^cloudbuild\.ya?ml$/.test(t)||t===`bitbucket-pipelines.yml`||/(^|\/)\.github\/workflows\/[^/]+\.ya?ml$/.test(e)}function vE(e){return[...new Set(e.match(/\b[A-Z][A-Z0-9]*(?:_[A-Z0-9]+)+\b/g)??[])]}function yE(e){return/^(docker-)?compose([.-][\w.-]+)?\.ya?ml$/i.test(e)}var bE=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 xE(e,t){let n=new bE,r=(e,t)=>{let r=e.replace(/^(NEXT_PUBLIC_|VITE_|PUBLIC_|REACT_APP_|EXPO_PUBLIC_|NUXT_PUBLIC_|NUXT_)/,``),i=pE.find(([e])=>e.test(r));i&&n.add(i[1],t)};for(let t of e.files){let i=Tx(t.path);if(gE(i)){let n=await e.readText(t);if(n===null)continue;for(let e of SE(n))r(e,`env: ${e} (${t.path})`)}else if(_E(t.path)){let n=await e.readText(t);if(n===null)continue;for(let e of vE(n))r(e,`pipeline: ${e} (${t.path})`)}else if(yE(i)){let i=await e.readText(t);if(i===null)continue;let a;try{a=(0,ow.parse)(i)}catch(n){e.warnings.push(`${t.path}: could not be parsed (${Ox(n)})`);continue}let o=Z(a)&&Z(a.services)?a.services:{};for(let[e,i]of Object.entries(o)){if(!Z(i))continue;let a=i.environment,o=Array.isArray(a)?a.map(e=>String(e).split(`=`,1)[0]??``):Z(a)?Object.keys(a):[];for(let n of o)r(n,`docker-compose: ${e} env ${n} in ${t.path}`);if(typeof i.image!=`string`)continue;let s=CE(i.image),c=hE.find(([e])=>e.test(s));c&&n.add(c[1],`docker-compose: service ${e} (${i.image}) in ${t.path}`)}}else t.path===`supabase/config.toml`||t.path.endsWith(`/supabase/config.toml`)?n.add(ET,`file: ${t.path}`):i===`firebase.json`?n.add(KT,`file: ${t.path}`):/^cloudbuild\.ya?ml$/.test(i)&&n.add(eE,`file: ${t.path}`)}for(let e of t){if(!e.direct)continue;let t=mE.find(([t])=>t.some(t=>wE(t,e.package)));t&&n.add(t[1],`dependency: ${e.package} (${e.sourceLockfile})`)}return n.list()}function SE(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 CE(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 wE(e,t){return e.endsWith(`*`)?t.startsWith(e.slice(0,-1)):e.endsWith(`/`)?t.startsWith(e):t===e}const TE={postgres:[ET,DT],mysql:[OT]};function EE(e,t){let n=new Map(t.map(e=>[e.provider,e])),r=(e,t)=>{let r=n.get(e.provider);if(r)return r.provider;let i={...e,evidence:[t]};return n.set(e.provider,i),i.provider};for(let t of e){let e=t.sourcePath.slice(0,t.sourcePath.lastIndexOf(`/`)+1);if(/(^|\/)supabase\//i.test(t.sourcePath)){t.resource=r(ET,`migrations: ${e}`);continue}let i=(t.dialect===`postgres`||t.dialect===`mysql`?TE[t.dialect]:[...TE.postgres,...TE.mysql]).find(e=>n.has(e.provider));i?t.resource=i.provider:t.dialect===`postgres`?t.resource=r(DT,`migrations: ${e}`):t.dialect===`mysql`&&(t.resource=r(OT,`migrations: ${e}`))}return[...n.values()].sort((e,t)=>e.name.localeCompare(t.name))}async function DE(e,{fromDisk:t=!1}={}){let n=_.resolve(e);if(!(await p(n)).isDirectory())throw Error(`${n} is not a folder`);let r=(/* @__PURE__ */ new Date()).toISOString(),i=[],a=t?null:await PS(n);!t&&!a&&C(_.join(n,`.git`))&&i.push(`No main or master branch found: read the files on disk instead`);let o=a?await Sx(n,a.ref):await xx(n),s=await yS(o),[c,l,u,d,f,m,h]=await Promise.all([IS(n,i,a?.ref??null),ST(o),xw(o),xS(o,s),OS(o),tT(o),Mw(o)]),g=EE(h,await xE(o,u));return{scannedAt:r,root:n,repo:{...c,languages:ww(o.files),readme:l},dependencies:u,docs:d,agentInstructions:f,contracts:[...m,...h],resources:g,docsConfig:{alwaysLoad:!!s.alwaysLoad},warnings:[...i,...o.warnings]}}function OE(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`}function kE(e){let{scannedRef:t,headSha:n}=e.repo;if(!t)return`files on disk`;let r=t.replace(/^origin\//,``);return n?`${r} @ ${n.slice(0,7)}`:r}async function AE(e,t,{quiet:n=!1,source:r=`connector`,name:i,restore:a}={}){await FS(e);let o=await DE(e),s=(i??t.repoName)?.trim();s&&Object.assign(o.repo,{name:s,nameFromConfig:!0}),a&&Object.assign(o.repo,{restore:!0});let c=await new Ur(await ox()).call(`sync_repo`,{p_project:t.projectId,p_snapshot:o,p_source:r});if(!n){Rx(`Synced ${Px(o.repo.name)} to ${Px(t.name)} ${Q(`from ${kE(o)}`)}`),zx(Q(OE(c)));for(let e of o.warnings)zx(Q(`! ${e}`))}return{snapshot:o,result:c}}async function jE(e){return jS(await xx(e))}const ME=26214400,NE=e=>`${(e/1024/1024).toFixed(1)} MB`;async function PE(e,t,{quiet:n=!1}={}){if(!t.folder)return;let{docs:r,unsupported:i}=await jE(e),a=e=>Buffer.byteLength(e.body),o=r.reduce((e,t)=>e+a(t),0);if(o>ME){let t=/* @__PURE__ */ new Map;for(let e of r){let n=e.path.includes(`/`)?`${e.path.split(`/`)[0]}/`:e.path;t.set(n,(t.get(n)??0)+a(e))}let n=[...t].sort((e,t)=>t[1]-e[1]).slice(0,3).map(([e,t])=>`${e} (${NE(t)})`).join(`, `);throw new Ux(`The documents outside the repos add up to ${NE(o)}, over the ${NE(ME)} a sync takes. The biggest: ${n}. List what Quirl should skip in ${x(v(e),`.quirlignore`)}, like .gitignore.`)}let s=new Ur(await ox()),c={p_project:t.projectId,p_folder:t.folder},l=await s.call(`folder_doc_hashes`,c),u=r.filter(e=>l[e.path]!==e.contentHash),d=0;for(let t=0;t<u.length;){let n=[],r=0;for(;t<u.length;){let e=u[t];if(n.length&&r+a(e)>2097152)break;n.push(e),r+=a(e),t++}let i=await s.call(`sync_folder_docs`,{...c,p_folder_name:v(e),p_docs:n});d+=i.docsChanged}let f={...await s.call(`sync_folder_finish`,{...c,p_paths:r.map(e=>e.path)}),docsChanged:d};return n||(Rx(`Synced the documents in ${Px(`${v(e)}/`)} outside the repos`),zx(Q(`${f.docs} docs (${f.docsChanged} changed${f.archived?`, ${f.archived} removed`:``})`)),i.length&&zx(Q(`! ${i.length} PDF/Office files skipped: only markdown and text are read for now`))),f}async function FE(e={}){let t=await ux();if(!t)throw new Ux("This folder isn't linked to a Quirl project. Run `quirl init`.");let n=sx(t.link),r=n.length?n.map(e=>({root:x(t.root,e.path),name:e.name})):[{root:t.root,name:void 0}],i=r.length+ +!!t.link.folder,a=0;for(let{root:o,name:s}of r)try{let r=n.length?await ux(o):null,i=s??(r?.root===o?r.link.repoName:void 0);await AE(o,t.link,{...e,name:i})}catch(e){if(a++,i===1)throw e;let n=S(t.root,o)||`.`;console.error(`${Ix(`✗`)} ${n}: ${Ox(e)}`)}if(t.link.folder)try{await PE(t.root,t.link,e)}catch(e){a++,console.error(`${Ix(`✗`)} documents in ${v(t.root)}/: ${Ox(e)}`)}if(a)throw new Ux(`${a} of ${i} parts didn't sync.`)}async function IE(e){let t=cx(),n=await Zx(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🌀 ${Px(`Quirl`)} ${Q(`·`)} connecting ${Px(s)}`),i&&(Bx(`📁`,`Found ${r.length} ${r.length===1?`repo`:`repos`}`),Vx(Q(r.map(a).join(` · `))),!await Gx(` Import all of them into one project?`,!0)))throw new Ux("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 jE(t);if(e.length){Bx(`📄`,`Also found ${e.length} ${e.length===1?`document`:`documents`} outside the repos`);for(let t of e.slice(0,8))Vx(Q(t.path));e.length>8&&Vx(Q(`…and ${e.length-8} more`)),n.length&&Vx(Q(`(${n.length} PDF/Office files can't be read yet and are skipped)`)),c=await Gx(` Import them too? Everyone on the project will be able to read them.`,!0)}}await rx()||await dS({quiet:!0});let l=await RE((await new Ur(await ox()).whoami()).projects,e.project??(await ux(t))?.link.project);if(l.role===`stakeholder`)throw new Ux(`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};Bx(`🔗`,`Linked to ${Px(l.name)} ${Q(`· ${l.organization}`)}`);let d=e.claude!==!1,f=e.hooks??await Gx(` Sync with Quirl on every git push?`,!0);Bx(`📦`,`Importing docs, dependencies and schemas`);let p=[],m=i?await ux(t):null,g=new Map((m?.root===t?sx(m.link):[]).filter(e=>e.name).map(e=>[e.path,e.name]));for(let e of r){let t=Hx(`Reading ${a(e)}…`);try{let n=await ux(e),r=(n?.root===e?n.link.repoName:void 0)??g.get(a(e));r&&g.set(a(e),r);let i=r?{...u,repoName:r}:u;await dx(e,i);let{snapshot:o,result:s}=await AE(e,i,{quiet:!0,restore:!0});d&&await LE(e,l.name),f&&await uS(e),t.stop(),Vx(`${Fx(`✓`)} ${Px(a(e))} ${Q(`(${kE(o)})`)} ${Q(OE(s))}`);for(let e of o.warnings)Vx(Q(` ! ${e}`));p.push(e)}catch(n){t.stop(),Vx(`${Ix(`✗`)} ${Px(a(e))} ${Ox(n)}`)}}if(!p.length)throw new Ux(`No repo was imported.`);if(i){let e=p.map(e=>{let t=g.get(a(e));return t?{path:a(e),name:t}:a(e)}),n=m,r={...u,repos:e,folder:c?n?.root===t&&n.link.folder||E():void 0};if(await dx(t,r),c)try{let e=await PE(t,r,{quiet:!0});Vx(`${Fx(`✓`)} ${Px(`documents outside the repos`)} ${Q(`${e?.docs??0} docs`)}`)}catch(e){Vx(`${Ix(`✗`)} ${Px(`documents outside the repos`)} ${Ox(e)}`)}d&&!p.includes(t)&&await LE(t,l.name,p.map(a))}let _=tS().portable;d&&(Bx(`🤖`,`Connected Claude Code`),Vx(Q(`.mcp.json the quirl tools`)),Vx(Q(`.claude/settings.json the briefing, loaded as each session starts`)),Vx(Q(`CLAUDE.md when to use Quirl`))),f&&Bx(`🪝`,`Quirl syncs on every ${Px(`git push`)}`);let y=r.length-p.length,b=`.quirl .mcp.json .claude/settings.json CLAUDE.md`;Bx(y?`⚠️ `:`🎉`,y?`Done, but ${y} of ${r.length} repos failed. Fix them and run ${Px(`quirl init`)} again.`:Px(`All set!`)),Vx(d&&!_?Q(`Don't commit ${b} yet: they point at this checkout until the CLI is installed.`):`${Q(`1.`)} Commit what was added${i?` in each repo`:``}: ${Lx(`git add ${b}`)}`),Vx(`${Q(d&&!_?`→`:`2.`)} Start Claude Code here and approve the ${Px(`quirl`)} server when it asks.`),i&&!p.includes(t)&&Vx(Q("Run `quirl sync` here to sync every repo at once.")),console.log(``)}async function LE(e,t,n=[]){await sS(e),await cS(e),await lS(e,t,n)}async function RE(e,t){if(!e.length)throw new Ux(`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 Ux(`No project "${t}" among yours: ${e.map(e=>e.slug).join(`, `)}.`);return n}if(e.length===1)return e[0];Bx(`🗂️ `,`Which project is this part of?`);for(let[t,n]of e.entries())Vx(`${Lx(String(t+1))} ${n.name} ${Q(`· ${n.organization} · ${n.role}`)}`);let n=e[Number(await Wx(` Project [1-${e.length}]: `))-1];if(!n)throw new Ux("No project picked. Run `quirl init --project <slug>`.");return n}const zE=`${Px(`quirl`)} ${Q(Zb)}: connect a repo to Quirl
|
|
365
365
|
|
|
366
366
|
quirl init [--project <slug>] [--hooks|--no-hooks] [--no-claude]
|
|
367
367
|
Link this repo, import it, and connect Claude Code
|
|
@@ -374,4 +374,4 @@ n?this.stack.push(n):(yield*this.pop(),yield*this.step())}else{let t=this.peek(2
|
|
|
374
374
|
quirl logout Forget this machine's key
|
|
375
375
|
quirl whoami Show who you're signed in as
|
|
376
376
|
quirl mcp Run the MCP server (used by Claude Code)
|
|
377
|
-
`;async function
|
|
377
|
+
`;async function BE(){let[e,...n]=process.argv.slice(2),{values:r,positionals:i}=t({args:n,allowNegative:!0,allowPositionals:!0,options:{all:{type:`boolean`},project:{type:`string`},hooks:{type:`boolean`},claude:{type:`boolean`},quiet:{type:`boolean`},hook:{type:`boolean`},source:{type:`string`}}});switch(e){case`init`:return IE({project:r.project,hooks:r.hooks,claude:r.claude});case`sync`:return FE({quiet:r.quiet,source:r.source});case`export`:return Xx({dir:i[0],all:r.all});case`context`:return jx({hook:r.hook});case`login`:await dS();return;case`logout`:return await ax(),Rx(`Signed out on this machine.`),zx(Q(`The key still exists until you revoke it under Organization > Access keys in Quirl (${$b().appUrl}).`));case`whoami`:{if(!await rx())throw new Ux("Not signed in. Run `quirl login`.");let e=await new Ur(await ox()).whoami();console.log(Px(e.email));for(let t of e.projects)zx(`${t.name} ${Q(`${t.slug} · ${t.organization} · ${t.role}`)}`);let t=await ux();t&&zx(Q(`This folder: ${t.link.name}`));return}case`mcp`:{let e=await ux();if(!e)throw new Ux("This folder isn't linked to a Quirl project. Run `quirl init`.");return Xb({...await ox(),project:e.link.projectId,version:Zb})}case void 0:case`help`:case`--help`:case`-h`:process.stdout.write(zE);return;case`--version`:case`-v`:return console.log(Zb);default:throw new Ux(`Unknown command "${e}".\n\n${zE}`)}}BE().catch(e=>{let t=e instanceof Ux?e.message:Ox(e);console.error(`${Ix(`✗`)} ${t}`),process.exit(1)});export{};
|