c5e68a17c8
* Refactor code structure for improved readability and maintainability * Add test results for search API and related functionalities - Created test result files for various search-related functionalities, including: - test-11-search-server-changes.json - test-12-context-hook-changes.json - test-13-worker-service-changes.json - test-14-patterns.json - test-15-gotchas.json - test-16-discoveries.json - test-17-all-bugfixes.json - test-18-all-features.json - test-19-all-decisions.json - test-20-session-search.json - test-21-prompt-search.json - test-22-decisions-endpoint.json - test-23-changes-endpoint.json - test-24-how-it-works-endpoint.json - test-25-contextualize-endpoint.json - test-26-timeline-around-observation.json - test-27-multi-param-combo.json - test-28-file-type-combo.json - Each test result file captures specific search failures or outcomes, including issues with undefined properties and successful execution of search queries. - Enhanced documentation of search architecture and testing strategies, ensuring compliance with established guidelines and improving overall search functionality. * feat: Enhance unified search API with catch-all parameters and backward compatibility - Implemented a unified search API at /api/search that accepts catch-all parameters for filtering by type, observation type, concepts, and files. - Maintained backward compatibility by keeping granular endpoints functional while routing through the same infrastructure. - Completed comprehensive testing of search capabilities with real-world query scenarios. fix: Address missing debug output in search API query tests - Flushed PM2 logs and executed search queries to verify functionality. - Diagnosed absence of "Raw Chroma" debug messages in worker logs, indicating potential issues with logging or query processing. refactor: Improve build and deployment pipeline for claude-mem plugin - Successfully built and synced all hooks and services to the marketplace directory. - Ensured all dependencies are installed and up-to-date in the deployment location. feat: Implement hybrid search filters with 90-day recency window - Enhanced search server to apply a 90-day recency filter to Chroma results before categorizing by document type. fix: Correct parameter handling in searchUserPrompts method - Added support for filter-only queries and improved dual-path logic for clarity. refactor: Rename FTS5 method to clarify fallback status - Renamed escapeFTS5 to escapeFTS5_fallback_when_chroma_unavailable to indicate its temporary usage. feat: Introduce contextualize tool for comprehensive project overview - Added a new tool to fetch recent observations, sessions, and user prompts, providing a quick project overview. feat: Add semantic shortcut tools for common search patterns - Implemented 'decisions', 'changes', and 'how_it_works' tools for convenient access to frequently searched observation categories. feat: Unified timeline tool supports anchor and query modes - Combined get_context_timeline and get_timeline_by_query into a single interface for timeline exploration. feat: Unified search tool added to MCP server - New tool queries all memory types simultaneously, providing combined chronological results for improved search efficiency. * Refactor search functionality to clarify FTS5 fallback usage - Updated `worker-service.cjs` to replace FTS5 fallback function with a more descriptive name and improved error handling. - Enhanced documentation in `SKILL.md` to specify the unified API endpoint and clarify the behavior of the search engine, including the conditions under which FTS5 is used. - Modified `search-server.ts` to provide clearer logging and descriptions regarding the fallback to FTS5 when UVX/Python is unavailable. - Renamed and updated the `SessionSearch.ts` methods to reflect the conditions for using FTS5, emphasizing the lack of semantic understanding in fallback scenarios. * feat: Add ID-based fetch endpoints and simplify mem-search skill **Problem:** - Search returns IDs but no way to fetch by ID - Skill documentation was bloated with too many options - Claude wasn't using IDs because we didn't tell it how **Solution:** 1. Added three new HTTP endpoints: - GET /api/observation/:id - GET /api/session/:id - GET /api/prompt/:id 2. Completely rewrote SKILL.md: - Stripped complexity down to essentials - Clear 3-step prescriptive workflow: Search → Review IDs → Fetch by ID - Emphasized ID usage: "The IDs are there for a reason - USE THEM" - Removed confusing multi-endpoint documentation - Kept only unified search with filters **Impact:** - Token efficiency: Claude can now fetch full details only for relevant IDs - Clarity: One clear workflow instead of 10+ options to choose from - Usability: IDs are no longer wasted context - they're actionable 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * chore: Move internal docs to private directory Moved POSTMORTEM and planning docs to ./private to exclude from PR reviews. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * refactor: Remove experimental contextualize endpoint - Removed contextualize MCP tool from search-server (saves ~4KB) - Disabled FTS5 fallback paths in SessionSearch (now vector-first) - Cleaned up CLAUDE.md documentation - Removed contextualize-rewrite-plan.md doc Rationale: - Contextualize is better suited as a skill (LLM-powered) than an endpoint - Search API already provides vector search with configurable limits - Created issue #132 to track future contextualize skill implementation Changes: - src/servers/search-server.ts: Removed contextualize tool definition - src/services/sqlite/SessionSearch.ts: Disabled FTS5 fallback, added deprecation warnings - CLAUDE.md: Cleaned up outdated skill documentation - docs/: Removed contextualize plan document 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * refactor: Complete FTS5 cleanup - remove all deprecated search code This completes the FTS5 cleanup work by removing all commented-out FTS5 search code while preserving database tables for backward compatibility. Changes: - Removed 200+ lines of commented FTS5 search code from SessionSearch.ts - Removed deprecated degraded_search_query__when_uvx_unavailable method - Updated all method documentation to clarify vector-first architecture - Updated class documentation to reflect filter-only query support - Updated CLAUDE.md to remove FTS5 search references - Clarified that FTS5 tables exist for backward compatibility only - Updated "Why SQLite FTS5" section to "Why Vector-First Search" Database impact: NONE - FTS5 tables remain intact for existing installations Search architecture: - ChromaDB: All text-based vector search queries - SQLite: Filter-only queries (date ranges, metadata, no query text) - FTS5 tables: Maintained but unused (backward compatibility) 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * refactor: Remove all FTS5 fallback execution code from search-server Completes the FTS5 cleanup by removing all fallback execution paths that attempted to use FTS5 when ChromaDB was unavailable. Changes: - Removed all FTS5 fallback code execution paths - When ChromaDB fails or is unavailable, return empty results with helpful error messages - Updated all deprecated tool descriptions (search_observations, search_sessions, search_user_prompts) - Changed error messages to indicate FTS5 fallback has been removed - Added installation instructions for UVX/Python when vector search is unavailable - Updated comments from "hybrid search" to "vector-first search" - Removed ~100 lines of dead FTS5 fallback code Database impact: NONE - FTS5 tables remain intact (backward compatibility) Search behavior when ChromaDB unavailable: - Text queries: Return empty results with error explaining ChromaDB is required - Filter-only queries (no text): Continue to work via direct SQLite 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> * fix: Address PR 133 review feedback Critical fixes: - Remove contextualize endpoint from worker-service (route + handler) - Fix build script logging to show correct .cjs extension (was .mjs) Documentation improvements: - Add comprehensive FTS5 retention rationale documentation - Include v7.0.0 removal TODO for future cleanup Testing: - Build succeeds with correct output logging - Worker restarts successfully (30th restart) - Contextualize endpoint properly removed (404 response) - Search endpoint verified working This addresses all critical review feedback from PR 133. 🤖 Generated with [Claude Code](https://claude.com/claude-code) Co-Authored-By: Claude <noreply@anthropic.com> --------- Co-authored-by: Claude <noreply@anthropic.com>
649 lines
328 KiB
JavaScript
Executable File
649 lines
328 KiB
JavaScript
Executable File
#!/usr/bin/env node
|
|
"use strict";var Jl=Object.create;var Hs=Object.defineProperty;var Yl=Object.getOwnPropertyDescriptor;var eu=Object.getOwnPropertyNames;var tu=Object.getPrototypeOf,ru=Object.prototype.hasOwnProperty;var H=(s,e)=>()=>(e||s((e={exports:{}}).exports,e),e.exports),su=(s,e)=>{for(var r in e)Hs(s,r,{get:e[r],enumerable:!0})},au=(s,e,r,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let t of eu(e))!ru.call(s,t)&&t!==r&&Hs(s,t,{get:()=>e[t],enumerable:!(a=Yl(e,t))||a.enumerable});return s};var Mt=(s,e,r)=>(r=s!=null?Jl(tu(s)):{},au(e||!s||!s.__esModule?Hs(r,"default",{value:s,enumerable:!0}):r,s));var Wn=H((cs,Qn)=>{(function(s,e){typeof cs=="object"&&typeof Qn<"u"?e(cs):typeof define=="function"&&define.amd?define(["exports"],e):e(s.URI=s.URI||{})})(cs,(function(s){"use strict";function e(){for(var _=arguments.length,h=Array(_),b=0;b<_;b++)h[b]=arguments[b];if(h.length>1){h[0]=h[0].slice(0,-1);for(var P=h.length-1,O=1;O<P;++O)h[O]=h[O].slice(1,-1);return h[P]=h[P].slice(1),h.join("")}else return h[0]}function r(_){return"(?:"+_+")"}function a(_){return _===void 0?"undefined":_===null?"null":Object.prototype.toString.call(_).split(" ").pop().split("]").shift().toLowerCase()}function t(_){return _.toUpperCase()}function n(_){return _!=null?_ instanceof Array?_:typeof _.length!="number"||_.split||_.setInterval||_.call?[_]:Array.prototype.slice.call(_):[]}function o(_,h){var b=_;if(h)for(var P in h)b[P]=h[P];return b}function i(_){var h="[A-Za-z]",b="[\\x0D]",P="[0-9]",O="[\\x22]",B=e(P,"[A-Fa-f]"),K="[\\x0A]",ae="[\\x20]",le=r(r("%[EFef]"+B+"%"+B+B+"%"+B+B)+"|"+r("%[89A-Fa-f]"+B+"%"+B+B)+"|"+r("%"+B+B)),Se="[\\:\\/\\?\\#\\[\\]\\@]",se="[\\!\\$\\&\\'\\(\\)\\*\\+\\,\\;\\=]",me=e(Se,se),xe=_?"[\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF]":"[]",fe=_?"[\\uE000-\\uF8FF]":"[]",oe=e(h,P,"[\\-\\.\\_\\~]",xe),ve=r(h+e(h,P,"[\\+\\-\\.]")+"*"),ue=r(r(le+"|"+e(oe,se,"[\\:]"))+"*"),Lt=r(r("25[0-5]")+"|"+r("2[0-4]"+P)+"|"+r("1"+P+P)+"|"+r("[1-9]"+P)+"|"+P),Ve=r(r("25[0-5]")+"|"+r("2[0-4]"+P)+"|"+r("1"+P+P)+"|"+r("0?[1-9]"+P)+"|0?0?"+P),Ze=r(Ve+"\\."+Ve+"\\."+Ve+"\\."+Ve),de=r(B+"{1,4}"),He=r(r(de+"\\:"+de)+"|"+Ze),Ge=r(r(de+"\\:")+"{6}"+He),it=r("\\:\\:"+r(de+"\\:")+"{5}"+He),jt=r(r(de)+"?\\:\\:"+r(de+"\\:")+"{4}"+He),ht=r(r(r(de+"\\:")+"{0,1}"+de)+"?\\:\\:"+r(de+"\\:")+"{3}"+He),wr=r(r(r(de+"\\:")+"{0,2}"+de)+"?\\:\\:"+r(de+"\\:")+"{2}"+He),Hr=r(r(r(de+"\\:")+"{0,3}"+de)+"?\\:\\:"+de+"\\:"+He),zr=r(r(r(de+"\\:")+"{0,4}"+de)+"?\\:\\:"+He),or=r(r(r(de+"\\:")+"{0,5}"+de)+"?\\:\\:"+de),ir=r(r(r(de+"\\:")+"{0,6}"+de)+"?\\:\\:"),mt=r([Ge,it,jt,ht,wr,Hr,zr,or,ir].join("|")),cr=r(r(oe+"|"+le)+"+"),Bs=r(mt+"\\%25"+cr),Ft=r(mt+r("\\%25|\\%(?!"+B+"{2})")+cr),zl=r("[vV]"+B+"+\\."+e(oe,se,"[\\:]")+"+"),Zl=r("\\["+r(Ft+"|"+mt+"|"+zl)+"\\]"),yn=r(r(le+"|"+e(oe,se))+"*"),Pr=r(Zl+"|"+Ze+"(?!"+yn+")|"+yn),Or=r(P+"*"),_n=r(r(ue+"@")+"?"+Pr+r("\\:"+Or)+"?"),Ir=r(le+"|"+e(oe,se,"[\\:\\@]")),Gl=r(Ir+"*"),bn=r(Ir+"+"),Xl=r(r(le+"|"+e(oe,se,"[\\@]"))+"+"),vt=r(r("\\/"+Gl)+"*"),lr=r("\\/"+r(bn+vt)+"?"),Vs=r(Xl+vt),Zr=r(bn+vt),ur="(?!"+Ir+")",wh=r(vt+"|"+lr+"|"+Vs+"|"+Zr+"|"+ur),dr=r(r(Ir+"|"+e("[\\/\\?]",fe))+"*"),$r=r(r(Ir+"|[\\/\\?]")+"*"),En=r(r("\\/\\/"+_n+vt)+"|"+lr+"|"+Zr+"|"+ur),Ql=r(ve+"\\:"+En+r("\\?"+dr)+"?"+r("\\#"+$r)+"?"),Wl=r(r("\\/\\/"+_n+vt)+"|"+lr+"|"+Vs+"|"+ur),Kl=r(Wl+r("\\?"+dr)+"?"+r("\\#"+$r)+"?"),Ph=r(Ql+"|"+Kl),Oh=r(ve+"\\:"+En+r("\\?"+dr)+"?"),Ih="^("+ve+")\\:"+r(r("\\/\\/("+r("("+ue+")@")+"?("+Pr+")"+r("\\:("+Or+")")+"?)")+"?("+vt+"|"+lr+"|"+Zr+"|"+ur+")")+r("\\?("+dr+")")+"?"+r("\\#("+$r+")")+"?$",$h="^(){0}"+r(r("\\/\\/("+r("("+ue+")@")+"?("+Pr+")"+r("\\:("+Or+")")+"?)")+"?("+vt+"|"+lr+"|"+Vs+"|"+ur+")")+r("\\?("+dr+")")+"?"+r("\\#("+$r+")")+"?$",Ah="^("+ve+")\\:"+r(r("\\/\\/("+r("("+ue+")@")+"?("+Pr+")"+r("\\:("+Or+")")+"?)")+"?("+vt+"|"+lr+"|"+Zr+"|"+ur+")")+r("\\?("+dr+")")+"?$",Nh="^"+r("\\#("+$r+")")+"?$",Dh="^"+r("("+ue+")@")+"?("+Pr+")"+r("\\:("+Or+")")+"?$";return{NOT_SCHEME:new RegExp(e("[^]",h,P,"[\\+\\-\\.]"),"g"),NOT_USERINFO:new RegExp(e("[^\\%\\:]",oe,se),"g"),NOT_HOST:new RegExp(e("[^\\%\\[\\]\\:]",oe,se),"g"),NOT_PATH:new RegExp(e("[^\\%\\/\\:\\@]",oe,se),"g"),NOT_PATH_NOSCHEME:new RegExp(e("[^\\%\\/\\@]",oe,se),"g"),NOT_QUERY:new RegExp(e("[^\\%]",oe,se,"[\\:\\@\\/\\?]",fe),"g"),NOT_FRAGMENT:new RegExp(e("[^\\%]",oe,se,"[\\:\\@\\/\\?]"),"g"),ESCAPE:new RegExp(e("[^]",oe,se),"g"),UNRESERVED:new RegExp(oe,"g"),OTHER_CHARS:new RegExp(e("[^\\%]",oe,me),"g"),PCT_ENCODED:new RegExp(le,"g"),IPV4ADDRESS:new RegExp("^("+Ze+")$"),IPV6ADDRESS:new RegExp("^\\[?("+mt+")"+r(r("\\%25|\\%(?!"+B+"{2})")+"("+cr+")")+"?\\]?$")}}var l=i(!1),u=i(!0),d=(function(){function _(h,b){var P=[],O=!0,B=!1,K=void 0;try{for(var ae=h[Symbol.iterator](),le;!(O=(le=ae.next()).done)&&(P.push(le.value),!(b&&P.length===b));O=!0);}catch(Se){B=!0,K=Se}finally{try{!O&&ae.return&&ae.return()}finally{if(B)throw K}}return P}return function(h,b){if(Array.isArray(h))return h;if(Symbol.iterator in Object(h))return _(h,b);throw new TypeError("Invalid attempt to destructure non-iterable instance")}})(),f=function(_){if(Array.isArray(_)){for(var h=0,b=Array(_.length);h<_.length;h++)b[h]=_[h];return b}else return Array.from(_)},m=2147483647,p=36,g=1,y=26,v=38,E=700,w=72,S=128,R="-",x=/^xn--/,T=/[^\0-\x7E]/,N=/[\x2E\u3002\uFF0E\uFF61]/g,j={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},$=p-g,D=Math.floor,C=String.fromCharCode;function F(_){throw new RangeError(j[_])}function I(_,h){for(var b=[],P=_.length;P--;)b[P]=h(_[P]);return b}function A(_,h){var b=_.split("@"),P="";b.length>1&&(P=b[0]+"@",_=b[1]),_=_.replace(N,".");var O=_.split("."),B=I(O,h).join(".");return P+B}function M(_){for(var h=[],b=0,P=_.length;b<P;){var O=_.charCodeAt(b++);if(O>=55296&&O<=56319&&b<P){var B=_.charCodeAt(b++);(B&64512)==56320?h.push(((O&1023)<<10)+(B&1023)+65536):(h.push(O),b--)}else h.push(O)}return h}var ee=function(h){return String.fromCodePoint.apply(String,f(h))},Q=function(h){return h-48<10?h-22:h-65<26?h-65:h-97<26?h-97:p},Y=function(h,b){return h+22+75*(h<26)-((b!=0)<<5)},X=function(h,b,P){var O=0;for(h=P?D(h/E):h>>1,h+=D(h/b);h>$*y>>1;O+=p)h=D(h/$);return D(O+($+1)*h/(h+v))},z=function(h){var b=[],P=h.length,O=0,B=S,K=w,ae=h.lastIndexOf(R);ae<0&&(ae=0);for(var le=0;le<ae;++le)h.charCodeAt(le)>=128&&F("not-basic"),b.push(h.charCodeAt(le));for(var Se=ae>0?ae+1:0;Se<P;){for(var se=O,me=1,xe=p;;xe+=p){Se>=P&&F("invalid-input");var fe=Q(h.charCodeAt(Se++));(fe>=p||fe>D((m-O)/me))&&F("overflow"),O+=fe*me;var oe=xe<=K?g:xe>=K+y?y:xe-K;if(fe<oe)break;var ve=p-oe;me>D(m/ve)&&F("overflow"),me*=ve}var ue=b.length+1;K=X(O-se,ue,se==0),D(O/ue)>m-B&&F("overflow"),B+=D(O/ue),O%=ue,b.splice(O++,0,B)}return String.fromCodePoint.apply(String,b)},pe=function(h){var b=[];h=M(h);var P=h.length,O=S,B=0,K=w,ae=!0,le=!1,Se=void 0;try{for(var se=h[Symbol.iterator](),me;!(ae=(me=se.next()).done);ae=!0){var xe=me.value;xe<128&&b.push(C(xe))}}catch(Ft){le=!0,Se=Ft}finally{try{!ae&&se.return&&se.return()}finally{if(le)throw Se}}var fe=b.length,oe=fe;for(fe&&b.push(R);oe<P;){var ve=m,ue=!0,Lt=!1,Ve=void 0;try{for(var Ze=h[Symbol.iterator](),de;!(ue=(de=Ze.next()).done);ue=!0){var He=de.value;He>=O&&He<ve&&(ve=He)}}catch(Ft){Lt=!0,Ve=Ft}finally{try{!ue&&Ze.return&&Ze.return()}finally{if(Lt)throw Ve}}var Ge=oe+1;ve-O>D((m-B)/Ge)&&F("overflow"),B+=(ve-O)*Ge,O=ve;var it=!0,jt=!1,ht=void 0;try{for(var wr=h[Symbol.iterator](),Hr;!(it=(Hr=wr.next()).done);it=!0){var zr=Hr.value;if(zr<O&&++B>m&&F("overflow"),zr==O){for(var or=B,ir=p;;ir+=p){var mt=ir<=K?g:ir>=K+y?y:ir-K;if(or<mt)break;var cr=or-mt,Bs=p-mt;b.push(C(Y(mt+cr%Bs,0))),or=D(cr/Bs)}b.push(C(Y(or,0))),K=X(B,Ge,oe==fe),B=0,++oe}}}catch(Ft){jt=!0,ht=Ft}finally{try{!it&&wr.return&&wr.return()}finally{if(jt)throw ht}}++B,++O}return b.join("")},Oe=function(h){return A(h,function(b){return x.test(b)?z(b.slice(4).toLowerCase()):b})},De=function(h){return A(h,function(b){return T.test(b)?"xn--"+pe(b):b})},ne={version:"2.1.0",ucs2:{decode:M,encode:ee},decode:z,encode:pe,toASCII:De,toUnicode:Oe},be={};function Re(_){var h=_.charCodeAt(0),b=void 0;return h<16?b="%0"+h.toString(16).toUpperCase():h<128?b="%"+h.toString(16).toUpperCase():h<2048?b="%"+(h>>6|192).toString(16).toUpperCase()+"%"+(h&63|128).toString(16).toUpperCase():b="%"+(h>>12|224).toString(16).toUpperCase()+"%"+(h>>6&63|128).toString(16).toUpperCase()+"%"+(h&63|128).toString(16).toUpperCase(),b}function Ce(_){for(var h="",b=0,P=_.length;b<P;){var O=parseInt(_.substr(b+1,2),16);if(O<128)h+=String.fromCharCode(O),b+=3;else if(O>=194&&O<224){if(P-b>=6){var B=parseInt(_.substr(b+4,2),16);h+=String.fromCharCode((O&31)<<6|B&63)}else h+=_.substr(b,6);b+=6}else if(O>=224){if(P-b>=9){var K=parseInt(_.substr(b+4,2),16),ae=parseInt(_.substr(b+7,2),16);h+=String.fromCharCode((O&15)<<12|(K&63)<<6|ae&63)}else h+=_.substr(b,9);b+=9}else h+=_.substr(b,3),b+=3}return h}function St(_,h){function b(P){var O=Ce(P);return O.match(h.UNRESERVED)?O:P}return _.scheme&&(_.scheme=String(_.scheme).replace(h.PCT_ENCODED,b).toLowerCase().replace(h.NOT_SCHEME,"")),_.userinfo!==void 0&&(_.userinfo=String(_.userinfo).replace(h.PCT_ENCODED,b).replace(h.NOT_USERINFO,Re).replace(h.PCT_ENCODED,t)),_.host!==void 0&&(_.host=String(_.host).replace(h.PCT_ENCODED,b).toLowerCase().replace(h.NOT_HOST,Re).replace(h.PCT_ENCODED,t)),_.path!==void 0&&(_.path=String(_.path).replace(h.PCT_ENCODED,b).replace(_.scheme?h.NOT_PATH:h.NOT_PATH_NOSCHEME,Re).replace(h.PCT_ENCODED,t)),_.query!==void 0&&(_.query=String(_.query).replace(h.PCT_ENCODED,b).replace(h.NOT_QUERY,Re).replace(h.PCT_ENCODED,t)),_.fragment!==void 0&&(_.fragment=String(_.fragment).replace(h.PCT_ENCODED,b).replace(h.NOT_FRAGMENT,Re).replace(h.PCT_ENCODED,t)),_}function pt(_){return _.replace(/^0*(.*)/,"$1")||"0"}function Ee(_,h){var b=_.match(h.IPV4ADDRESS)||[],P=d(b,2),O=P[1];return O?O.split(".").map(pt).join("."):_}function ge(_,h){var b=_.match(h.IPV6ADDRESS)||[],P=d(b,3),O=P[1],B=P[2];if(O){for(var K=O.toLowerCase().split("::").reverse(),ae=d(K,2),le=ae[0],Se=ae[1],se=Se?Se.split(":").map(pt):[],me=le.split(":").map(pt),xe=h.IPV4ADDRESS.test(me[me.length-1]),fe=xe?7:8,oe=me.length-fe,ve=Array(fe),ue=0;ue<fe;++ue)ve[ue]=se[ue]||me[oe+ue]||"";xe&&(ve[fe-1]=Ee(ve[fe-1],h));var Lt=ve.reduce(function(Ge,it,jt){if(!it||it==="0"){var ht=Ge[Ge.length-1];ht&&ht.index+ht.length===jt?ht.length++:Ge.push({index:jt,length:1})}return Ge},[]),Ve=Lt.sort(function(Ge,it){return it.length-Ge.length})[0],Ze=void 0;if(Ve&&Ve.length>1){var de=ve.slice(0,Ve.index),He=ve.slice(Ve.index+Ve.length);Ze=de.join(":")+"::"+He.join(":")}else Ze=ve.join(":");return B&&(Ze+="%"+B),Ze}else return _}var Dt=/^(?:([^:\/?#]+):)?(?:\/\/((?:([^\/?#@]*)@)?(\[[^\/?#\]]+\]|[^\/?#:]*)(?:\:(\d*))?))?([^?#]*)(?:\?([^#]*))?(?:#((?:.|\n|\r)*))?/i,Ie="".match(/(){0}/)[1]===void 0;function ce(_){var h=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},b={},P=h.iri!==!1?u:l;h.reference==="suffix"&&(_=(h.scheme?h.scheme+":":"")+"//"+_);var O=_.match(Dt);if(O){Ie?(b.scheme=O[1],b.userinfo=O[3],b.host=O[4],b.port=parseInt(O[5],10),b.path=O[6]||"",b.query=O[7],b.fragment=O[8],isNaN(b.port)&&(b.port=O[5])):(b.scheme=O[1]||void 0,b.userinfo=_.indexOf("@")!==-1?O[3]:void 0,b.host=_.indexOf("//")!==-1?O[4]:void 0,b.port=parseInt(O[5],10),b.path=O[6]||"",b.query=_.indexOf("?")!==-1?O[7]:void 0,b.fragment=_.indexOf("#")!==-1?O[8]:void 0,isNaN(b.port)&&(b.port=_.match(/\/\/(?:.|\n)*\:(?:\/|\?|\#|$)/)?O[4]:void 0)),b.host&&(b.host=ge(Ee(b.host,P),P)),b.scheme===void 0&&b.userinfo===void 0&&b.host===void 0&&b.port===void 0&&!b.path&&b.query===void 0?b.reference="same-document":b.scheme===void 0?b.reference="relative":b.fragment===void 0?b.reference="absolute":b.reference="uri",h.reference&&h.reference!=="suffix"&&h.reference!==b.reference&&(b.error=b.error||"URI is not a "+h.reference+" reference.");var B=be[(h.scheme||b.scheme||"").toLowerCase()];if(!h.unicodeSupport&&(!B||!B.unicodeSupport)){if(b.host&&(h.domainHost||B&&B.domainHost))try{b.host=ne.toASCII(b.host.replace(P.PCT_ENCODED,Ce).toLowerCase())}catch(K){b.error=b.error||"Host's domain name can not be converted to ASCII via punycode: "+K}St(b,l)}else St(b,P);B&&B.parse&&B.parse(b,h)}else b.error=b.error||"URI can not be parsed.";return b}function xt(_,h){var b=h.iri!==!1?u:l,P=[];return _.userinfo!==void 0&&(P.push(_.userinfo),P.push("@")),_.host!==void 0&&P.push(ge(Ee(String(_.host),b),b).replace(b.IPV6ADDRESS,function(O,B,K){return"["+B+(K?"%25"+K:"")+"]"})),(typeof _.port=="number"||typeof _.port=="string")&&(P.push(":"),P.push(String(_.port))),P.length?P.join(""):void 0}var ft=/^\.\.?\//,Ct=/^\/\.(\/|$)/,kt=/^\/\.\.(\/|$)/,we=/^\/?(?:.|\n)*?(?=\/|$)/;function ze(_){for(var h=[];_.length;)if(_.match(ft))_=_.replace(ft,"");else if(_.match(Ct))_=_.replace(Ct,"/");else if(_.match(kt))_=_.replace(kt,"/"),h.pop();else if(_==="."||_==="..")_="";else{var b=_.match(we);if(b){var P=b[0];_=_.slice(P.length),h.push(P)}else throw new Error("Unexpected dot segment condition")}return h.join("")}function Fe(_){var h=arguments.length>1&&arguments[1]!==void 0?arguments[1]:{},b=h.iri?u:l,P=[],O=be[(h.scheme||_.scheme||"").toLowerCase()];if(O&&O.serialize&&O.serialize(_,h),_.host&&!b.IPV6ADDRESS.test(_.host)){if(h.domainHost||O&&O.domainHost)try{_.host=h.iri?ne.toUnicode(_.host):ne.toASCII(_.host.replace(b.PCT_ENCODED,Ce).toLowerCase())}catch(ae){_.error=_.error||"Host's domain name can not be converted to "+(h.iri?"Unicode":"ASCII")+" via punycode: "+ae}}St(_,b),h.reference!=="suffix"&&_.scheme&&(P.push(_.scheme),P.push(":"));var B=xt(_,h);if(B!==void 0&&(h.reference!=="suffix"&&P.push("//"),P.push(B),_.path&&_.path.charAt(0)!=="/"&&P.push("/")),_.path!==void 0){var K=_.path;!h.absolutePath&&(!O||!O.absolutePath)&&(K=ze(K)),B===void 0&&(K=K.replace(/^\/\//,"/%2F")),P.push(K)}return _.query!==void 0&&(P.push("?"),P.push(_.query)),_.fragment!==void 0&&(P.push("#"),P.push(_.fragment)),P.join("")}function ke(_,h){var b=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},P=arguments[3],O={};return P||(_=ce(Fe(_,b),b),h=ce(Fe(h,b),b)),b=b||{},!b.tolerant&&h.scheme?(O.scheme=h.scheme,O.userinfo=h.userinfo,O.host=h.host,O.port=h.port,O.path=ze(h.path||""),O.query=h.query):(h.userinfo!==void 0||h.host!==void 0||h.port!==void 0?(O.userinfo=h.userinfo,O.host=h.host,O.port=h.port,O.path=ze(h.path||""),O.query=h.query):(h.path?(h.path.charAt(0)==="/"?O.path=ze(h.path):((_.userinfo!==void 0||_.host!==void 0||_.port!==void 0)&&!_.path?O.path="/"+h.path:_.path?O.path=_.path.slice(0,_.path.lastIndexOf("/")+1)+h.path:O.path=h.path,O.path=ze(O.path)),O.query=h.query):(O.path=_.path,h.query!==void 0?O.query=h.query:O.query=_.query),O.userinfo=_.userinfo,O.host=_.host,O.port=_.port),O.scheme=_.scheme),O.fragment=h.fragment,O}function nt(_,h,b){var P=o({scheme:"null"},b);return Fe(ke(ce(_,P),ce(h,P),P,!0),P)}function Be(_,h){return typeof _=="string"?_=Fe(ce(_,h),h):a(_)==="object"&&(_=ce(Fe(_,h),h)),_}function Vr(_,h,b){return typeof _=="string"?_=Fe(ce(_,b),b):a(_)==="object"&&(_=Fe(_,b)),typeof h=="string"?h=Fe(ce(h,b),b):a(h)==="object"&&(h=Fe(h,b)),_===h}function qs(_,h){return _&&_.toString().replace(!h||!h.iri?l.ESCAPE:u.ESCAPE,Re)}function et(_,h){return _&&_.toString().replace(!h||!h.iri?l.PCT_ENCODED:u.PCT_ENCODED,Ce)}var Rr={scheme:"http",domainHost:!0,parse:function(h,b){return h.host||(h.error=h.error||"HTTP URIs must have a host."),h},serialize:function(h,b){var P=String(h.scheme).toLowerCase()==="https";return(h.port===(P?443:80)||h.port==="")&&(h.port=void 0),h.path||(h.path="/"),h}},un={scheme:"https",domainHost:Rr.domainHost,parse:Rr.parse,serialize:Rr.serialize};function dn(_){return typeof _.secure=="boolean"?_.secure:String(_.scheme).toLowerCase()==="wss"}var Tr={scheme:"ws",domainHost:!0,parse:function(h,b){var P=h;return P.secure=dn(P),P.resourceName=(P.path||"/")+(P.query?"?"+P.query:""),P.path=void 0,P.query=void 0,P},serialize:function(h,b){if((h.port===(dn(h)?443:80)||h.port==="")&&(h.port=void 0),typeof h.secure=="boolean"&&(h.scheme=h.secure?"wss":"ws",h.secure=void 0),h.resourceName){var P=h.resourceName.split("?"),O=d(P,2),B=O[0],K=O[1];h.path=B&&B!=="/"?B:void 0,h.query=K,h.resourceName=void 0}return h.fragment=void 0,h}},pn={scheme:"wss",domainHost:Tr.domainHost,parse:Tr.parse,serialize:Tr.serialize},Dl={},Cl=!0,fn="[A-Za-z0-9\\-\\.\\_\\~"+(Cl?"\\xA0-\\u200D\\u2010-\\u2029\\u202F-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFEF":"")+"]",ot="[0-9A-Fa-f]",kl=r(r("%[EFef]"+ot+"%"+ot+ot+"%"+ot+ot)+"|"+r("%[89A-Fa-f]"+ot+"%"+ot+ot)+"|"+r("%"+ot+ot)),Ll="[A-Za-z0-9\\!\\$\\%\\'\\*\\+\\-\\^\\_\\`\\{\\|\\}\\~]",jl="[\\!\\$\\%\\'\\(\\)\\*\\+\\,\\-\\.0-9\\<\\>A-Z\\x5E-\\x7E]",Fl=e(jl,'[\\"\\\\]'),Ml="[\\!\\$\\'\\(\\)\\*\\+\\,\\;\\:\\@]",ql=new RegExp(fn,"g"),nr=new RegExp(kl,"g"),Ul=new RegExp(e("[^]",Ll,"[\\.]",'[\\"]',Fl),"g"),hn=new RegExp(e("[^]",fn,Ml),"g"),Bl=hn;function Us(_){var h=Ce(_);return h.match(ql)?h:_}var mn={scheme:"mailto",parse:function(h,b){var P=h,O=P.to=P.path?P.path.split(","):[];if(P.path=void 0,P.query){for(var B=!1,K={},ae=P.query.split("&"),le=0,Se=ae.length;le<Se;++le){var se=ae[le].split("=");switch(se[0]){case"to":for(var me=se[1].split(","),xe=0,fe=me.length;xe<fe;++xe)O.push(me[xe]);break;case"subject":P.subject=et(se[1],b);break;case"body":P.body=et(se[1],b);break;default:B=!0,K[et(se[0],b)]=et(se[1],b);break}}B&&(P.headers=K)}P.query=void 0;for(var oe=0,ve=O.length;oe<ve;++oe){var ue=O[oe].split("@");if(ue[0]=et(ue[0]),b.unicodeSupport)ue[1]=et(ue[1],b).toLowerCase();else try{ue[1]=ne.toASCII(et(ue[1],b).toLowerCase())}catch(Lt){P.error=P.error||"Email address's domain name can not be converted to ASCII via punycode: "+Lt}O[oe]=ue.join("@")}return P},serialize:function(h,b){var P=h,O=n(h.to);if(O){for(var B=0,K=O.length;B<K;++B){var ae=String(O[B]),le=ae.lastIndexOf("@"),Se=ae.slice(0,le).replace(nr,Us).replace(nr,t).replace(Ul,Re),se=ae.slice(le+1);try{se=b.iri?ne.toUnicode(se):ne.toASCII(et(se,b).toLowerCase())}catch(oe){P.error=P.error||"Email address's domain name can not be converted to "+(b.iri?"Unicode":"ASCII")+" via punycode: "+oe}O[B]=Se+"@"+se}P.path=O.join(",")}var me=h.headers=h.headers||{};h.subject&&(me.subject=h.subject),h.body&&(me.body=h.body);var xe=[];for(var fe in me)me[fe]!==Dl[fe]&&xe.push(fe.replace(nr,Us).replace(nr,t).replace(hn,Re)+"="+me[fe].replace(nr,Us).replace(nr,t).replace(Bl,Re));return xe.length&&(P.query=xe.join("&")),P}},Vl=/^([^\:]+)\:(.*)/,vn={scheme:"urn",parse:function(h,b){var P=h.path&&h.path.match(Vl),O=h;if(P){var B=b.scheme||O.scheme||"urn",K=P[1].toLowerCase(),ae=P[2],le=B+":"+(b.nid||K),Se=be[le];O.nid=K,O.nss=ae,O.path=void 0,Se&&(O=Se.parse(O,b))}else O.error=O.error||"URN can not be parsed.";return O},serialize:function(h,b){var P=b.scheme||h.scheme||"urn",O=h.nid,B=P+":"+(b.nid||O),K=be[B];K&&(h=K.serialize(h,b));var ae=h,le=h.nss;return ae.path=(O||b.nid)+":"+le,ae}},Hl=/^[0-9A-Fa-f]{8}(?:\-[0-9A-Fa-f]{4}){3}\-[0-9A-Fa-f]{12}$/,gn={scheme:"urn:uuid",parse:function(h,b){var P=h;return P.uuid=P.nss,P.nss=void 0,!b.tolerant&&(!P.uuid||!P.uuid.match(Hl))&&(P.error=P.error||"UUID is not valid."),P},serialize:function(h,b){var P=h;return P.nss=(h.uuid||"").toLowerCase(),P}};be[Rr.scheme]=Rr,be[un.scheme]=un,be[Tr.scheme]=Tr,be[pn.scheme]=pn,be[mn.scheme]=mn,be[vn.scheme]=vn,be[gn.scheme]=gn,s.SCHEMES=be,s.pctEncChar=Re,s.pctDecChars=Ce,s.parse=ce,s.removeDotSegments=ze,s.serialize=Fe,s.resolveComponents=ke,s.resolve=nt,s.normalize=Be,s.equal=Vr,s.escapeComponent=qs,s.unescapeComponent=et,Object.defineProperty(s,"__esModule",{value:!0})}))});var ls=H((ym,Kn)=>{"use strict";Kn.exports=function s(e,r){if(e===r)return!0;if(e&&r&&typeof e=="object"&&typeof r=="object"){if(e.constructor!==r.constructor)return!1;var a,t,n;if(Array.isArray(e)){if(a=e.length,a!=r.length)return!1;for(t=a;t--!==0;)if(!s(e[t],r[t]))return!1;return!0}if(e.constructor===RegExp)return e.source===r.source&&e.flags===r.flags;if(e.valueOf!==Object.prototype.valueOf)return e.valueOf()===r.valueOf();if(e.toString!==Object.prototype.toString)return e.toString()===r.toString();if(n=Object.keys(e),a=n.length,a!==Object.keys(r).length)return!1;for(t=a;t--!==0;)if(!Object.prototype.hasOwnProperty.call(r,n[t]))return!1;for(t=a;t--!==0;){var o=n[t];if(!s(e[o],r[o]))return!1}return!0}return e!==e&&r!==r}});var Yn=H((_m,Jn)=>{"use strict";Jn.exports=function(e){for(var r=0,a=e.length,t=0,n;t<a;)r++,n=e.charCodeAt(t++),n>=55296&&n<=56319&&t<a&&(n=e.charCodeAt(t),(n&64512)==56320&&t++);return r}});var rr=H((bm,ro)=>{"use strict";ro.exports={copy:sp,checkDataType:ma,checkDataTypes:ap,coerceToTypes:np,toHash:ga,getProperty:ya,escapeQuotes:_a,equal:ls(),ucs2length:Yn(),varOccurences:cp,varReplace:lp,schemaHasRules:up,schemaHasRulesExcept:dp,schemaUnknownRules:pp,toQuotedString:va,getPathExpr:fp,getPath:hp,getData:gp,unescapeFragment:yp,unescapeJsonPointer:Ea,escapeFragment:_p,escapeJsonPointer:ba};function sp(s,e){e=e||{};for(var r in s)e[r]=s[r];return e}function ma(s,e,r,a){var t=a?" !== ":" === ",n=a?" || ":" && ",o=a?"!":"",i=a?"":"!";switch(s){case"null":return e+t+"null";case"array":return o+"Array.isArray("+e+")";case"object":return"("+o+e+n+"typeof "+e+t+'"object"'+n+i+"Array.isArray("+e+"))";case"integer":return"(typeof "+e+t+'"number"'+n+i+"("+e+" % 1)"+n+e+t+e+(r?n+o+"isFinite("+e+")":"")+")";case"number":return"(typeof "+e+t+'"'+s+'"'+(r?n+o+"isFinite("+e+")":"")+")";default:return"typeof "+e+t+'"'+s+'"'}}function ap(s,e,r){switch(s.length){case 1:return ma(s[0],e,r,!0);default:var a="",t=ga(s);t.array&&t.object&&(a=t.null?"(":"(!"+e+" || ",a+="typeof "+e+' !== "object")',delete t.null,delete t.array,delete t.object),t.number&&delete t.integer;for(var n in t)a+=(a?" && ":"")+ma(n,e,r,!0);return a}}var eo=ga(["string","number","integer","boolean","null"]);function np(s,e){if(Array.isArray(e)){for(var r=[],a=0;a<e.length;a++){var t=e[a];(eo[t]||s==="array"&&t==="array")&&(r[r.length]=t)}if(r.length)return r}else{if(eo[e])return[e];if(s==="array"&&e==="array")return["array"]}}function ga(s){for(var e={},r=0;r<s.length;r++)e[s[r]]=!0;return e}var op=/^[a-z$_][a-z$_0-9]*$/i,ip=/'|\\/g;function ya(s){return typeof s=="number"?"["+s+"]":op.test(s)?"."+s:"['"+_a(s)+"']"}function _a(s){return s.replace(ip,"\\$&").replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\f/g,"\\f").replace(/\t/g,"\\t")}function cp(s,e){e+="[^0-9]";var r=s.match(new RegExp(e,"g"));return r?r.length:0}function lp(s,e,r){return e+="([^0-9])",r=r.replace(/\$/g,"$$$$"),s.replace(new RegExp(e,"g"),r+"$1")}function up(s,e){if(typeof s=="boolean")return!s;for(var r in s)if(e[r])return!0}function dp(s,e,r){if(typeof s=="boolean")return!s&&r!="not";for(var a in s)if(a!=r&&e[a])return!0}function pp(s,e){if(typeof s!="boolean"){for(var r in s)if(!e[r])return r}}function va(s){return"'"+_a(s)+"'"}function fp(s,e,r,a){var t=r?"'/' + "+e+(a?"":".replace(/~/g, '~0').replace(/\\//g, '~1')"):a?"'[' + "+e+" + ']'":"'[\\'' + "+e+" + '\\']'";return to(s,t)}function hp(s,e,r){var a=va(r?"/"+ba(e):ya(e));return to(s,a)}var mp=/^\/(?:[^~]|~0|~1)*$/,vp=/^([0-9]+)(#|\/(?:[^~]|~0|~1)*)?$/;function gp(s,e,r){var a,t,n,o;if(s==="")return"rootData";if(s[0]=="/"){if(!mp.test(s))throw new Error("Invalid JSON-pointer: "+s);t=s,n="rootData"}else{if(o=s.match(vp),!o)throw new Error("Invalid JSON-pointer: "+s);if(a=+o[1],t=o[2],t=="#"){if(a>=e)throw new Error("Cannot access property/index "+a+" levels up, current level is "+e);return r[e-a]}if(a>e)throw new Error("Cannot access data "+a+" levels up, current level is "+e);if(n="data"+(e-a||""),!t)return n}for(var i=n,l=t.split("/"),u=0;u<l.length;u++){var d=l[u];d&&(n+=ya(Ea(d)),i+=" && "+n)}return i}function to(s,e){return s=='""'?e:(s+" + "+e).replace(/([^\\])' \+ '/g,"$1")}function yp(s){return Ea(decodeURIComponent(s))}function _p(s){return encodeURIComponent(ba(s))}function ba(s){return s.replace(/~/g,"~0").replace(/\//g,"~1")}function Ea(s){return s.replace(/~1/g,"/").replace(/~0/g,"~")}});var Sa=H((Em,so)=>{"use strict";var bp=rr();so.exports=Ep;function Ep(s){bp.copy(s,this)}});var no=H((Sm,ao)=>{"use strict";var Ot=ao.exports=function(s,e,r){typeof e=="function"&&(r=e,e={}),r=e.cb||r;var a=typeof r=="function"?r:r.pre||function(){},t=r.post||function(){};us(e,a,t,s,"",s)};Ot.keywords={additionalItems:!0,items:!0,contains:!0,additionalProperties:!0,propertyNames:!0,not:!0};Ot.arrayKeywords={items:!0,allOf:!0,anyOf:!0,oneOf:!0};Ot.propsKeywords={definitions:!0,properties:!0,patternProperties:!0,dependencies:!0};Ot.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 us(s,e,r,a,t,n,o,i,l,u){if(a&&typeof a=="object"&&!Array.isArray(a)){e(a,t,n,o,i,l,u);for(var d in a){var f=a[d];if(Array.isArray(f)){if(d in Ot.arrayKeywords)for(var m=0;m<f.length;m++)us(s,e,r,f[m],t+"/"+d+"/"+m,n,t,d,a,m)}else if(d in Ot.propsKeywords){if(f&&typeof f=="object")for(var p in f)us(s,e,r,f[p],t+"/"+d+"/"+Sp(p),n,t,d,a,p)}else(d in Ot.keywords||s.allKeys&&!(d in Ot.skipKeywords))&&us(s,e,r,f,t+"/"+d,n,t,d,a)}r(a,t,n,o,i,l,u)}}function Sp(s){return s.replace(/~/g,"~0").replace(/\//g,"~1")}});var vs=H((xm,lo)=>{"use strict";var Mr=Wn(),oo=ls(),hs=rr(),ds=Sa(),xp=no();lo.exports=$t;$t.normalizeId=It;$t.fullPath=ps;$t.url=fs;$t.ids=Op;$t.inlineRef=xa;$t.schema=ms;function $t(s,e,r){var a=this._refs[r];if(typeof a=="string")if(this._refs[a])a=this._refs[a];else return $t.call(this,s,e,a);if(a=a||this._schemas[r],a instanceof ds)return xa(a.schema,this._opts.inlineRefs)?a.schema:a.validate||this._compile(a);var t=ms.call(this,e,r),n,o,i;return t&&(n=t.schema,e=t.root,i=t.baseId),n instanceof ds?o=n.validate||s.call(this,n.schema,e,void 0,i):n!==void 0&&(o=xa(n,this._opts.inlineRefs)?n:s.call(this,n,e,void 0,i)),o}function ms(s,e){var r=Mr.parse(e),a=co(r),t=ps(this._getId(s.schema));if(Object.keys(s.schema).length===0||a!==t){var n=It(a),o=this._refs[n];if(typeof o=="string")return Rp.call(this,s,o,r);if(o instanceof ds)o.validate||this._compile(o),s=o;else if(o=this._schemas[n],o instanceof ds){if(o.validate||this._compile(o),n==It(e))return{schema:o,root:s,baseId:t};s=o}else return;if(!s.schema)return;t=ps(this._getId(s.schema))}return io.call(this,r,t,s.schema,s)}function Rp(s,e,r){var a=ms.call(this,s,e);if(a){var t=a.schema,n=a.baseId;s=a.root;var o=this._getId(t);return o&&(n=fs(n,o)),io.call(this,r,n,t,s)}}var Tp=hs.toHash(["properties","patternProperties","enum","dependencies","definitions"]);function io(s,e,r,a){if(s.fragment=s.fragment||"",s.fragment.slice(0,1)=="/"){for(var t=s.fragment.split("/"),n=1;n<t.length;n++){var o=t[n];if(o){if(o=hs.unescapeFragment(o),r=r[o],r===void 0)break;var i;if(!Tp[o]&&(i=this._getId(r),i&&(e=fs(e,i)),r.$ref)){var l=fs(e,r.$ref),u=ms.call(this,a,l);u&&(r=u.schema,a=u.root,e=u.baseId)}}}if(r!==void 0&&r!==a.schema)return{schema:r,root:a,baseId:e}}}var wp=hs.toHash(["type","format","pattern","maxLength","minLength","maxProperties","minProperties","maxItems","minItems","maximum","minimum","uniqueItems","multipleOf","required","enum"]);function xa(s,e){if(e===!1)return!1;if(e===void 0||e===!0)return Ra(s);if(e)return Ta(s)<=e}function Ra(s){var e;if(Array.isArray(s)){for(var r=0;r<s.length;r++)if(e=s[r],typeof e=="object"&&!Ra(e))return!1}else for(var a in s)if(a=="$ref"||(e=s[a],typeof e=="object"&&!Ra(e)))return!1;return!0}function Ta(s){var e=0,r;if(Array.isArray(s)){for(var a=0;a<s.length;a++)if(r=s[a],typeof r=="object"&&(e+=Ta(r)),e==1/0)return 1/0}else for(var t in s){if(t=="$ref")return 1/0;if(wp[t])e++;else if(r=s[t],typeof r=="object"&&(e+=Ta(r)+1),e==1/0)return 1/0}return e}function ps(s,e){e!==!1&&(s=It(s));var r=Mr.parse(s);return co(r)}function co(s){return Mr.serialize(s).split("#")[0]+"#"}var Pp=/#\/?$/;function It(s){return s?s.replace(Pp,""):""}function fs(s,e){return e=It(e),Mr.resolve(s,e)}function Op(s){var e=It(this._getId(s)),r={"":e},a={"":ps(e,!1)},t={},n=this;return xp(s,{allKeys:!0},function(o,i,l,u,d,f,m){if(i!==""){var p=n._getId(o),g=r[u],y=a[u]+"/"+d;if(m!==void 0&&(y+="/"+(typeof m=="number"?m:hs.escapeFragment(m))),typeof p=="string"){p=g=It(g?Mr.resolve(g,p):p);var v=n._refs[p];if(typeof v=="string"&&(v=n._refs[v]),v&&v.schema){if(!oo(o,v.schema))throw new Error('id "'+p+'" resolves to more than one schema')}else if(p!=It(y))if(p[0]=="#"){if(t[p]&&!oo(o,t[p]))throw new Error('id "'+p+'" resolves to more than one schema');t[p]=o}else n._refs[p]=y}r[i]=g,a[i]=y}}),t}});var gs=H((Rm,po)=>{"use strict";var wa=vs();po.exports={Validation:uo(Ip),MissingRef:uo(Pa)};function Ip(s){this.message="validation failed",this.errors=s,this.ajv=this.validation=!0}Pa.message=function(s,e){return"can't resolve reference "+e+" from id "+s};function Pa(s,e,r){this.message=r||Pa.message(s,e),this.missingRef=wa.url(s,e),this.missingSchema=wa.normalizeId(wa.fullPath(this.missingRef))}function uo(s){return s.prototype=Object.create(Error.prototype),s.prototype.constructor=s,s}});var Oa=H((Tm,fo)=>{"use strict";fo.exports=function(s,e){e||(e={}),typeof e=="function"&&(e={cmp:e});var r=typeof e.cycles=="boolean"?e.cycles:!1,a=e.cmp&&(function(n){return function(o){return function(i,l){var u={key:i,value:o[i]},d={key:l,value:o[l]};return n(u,d)}}})(e.cmp),t=[];return(function n(o){if(o&&o.toJSON&&typeof o.toJSON=="function"&&(o=o.toJSON()),o!==void 0){if(typeof o=="number")return isFinite(o)?""+o:"null";if(typeof o!="object")return JSON.stringify(o);var i,l;if(Array.isArray(o)){for(l="[",i=0;i<o.length;i++)i&&(l+=","),l+=n(o[i])||"null";return l+"]"}if(o===null)return"null";if(t.indexOf(o)!==-1){if(r)return JSON.stringify("__cycle__");throw new TypeError("Converting circular structure to JSON")}var u=t.push(o)-1,d=Object.keys(o).sort(a&&a(o));for(l="",i=0;i<d.length;i++){var f=d[i],m=n(o[f]);m&&(l&&(l+=","),l+=JSON.stringify(f)+":"+m)}return t.splice(u,1),"{"+l+"}"}})(s)}});var Ia=H((wm,ho)=>{"use strict";ho.exports=function(e,r,a){var t="",n=e.schema.$async===!0,o=e.util.schemaHasRulesExcept(e.schema,e.RULES.all,"$ref"),i=e.self._getId(e.schema);if(e.opts.strictKeywords){var l=e.util.schemaUnknownRules(e.schema,e.RULES.keywords);if(l){var u="unknown keyword: "+l;if(e.opts.strictKeywords==="log")e.logger.warn(u);else throw new Error(u)}}if(e.isTop&&(t+=" var validate = ",n&&(e.async=!0,t+="async "),t+="function(data, dataPath, parentData, parentDataProperty, rootData) { 'use strict'; ",i&&(e.opts.sourceCode||e.opts.processCode)&&(t+=" "+("/*# sourceURL="+i+" */")+" ")),typeof e.schema=="boolean"||!(o||e.schema.$ref)){var r="false schema",d=e.level,f=e.dataLevel,m=e.schema[r],p=e.schemaPath+e.util.getProperty(r),g=e.errSchemaPath+"/"+r,x=!e.opts.allErrors,j,y="data"+(f||""),R="valid"+d;if(e.schema===!1){e.isTop?x=!0:t+=" var "+R+" = false; ";var v=v||[];v.push(t),t="",e.createErrors!==!1?(t+=" { keyword: '"+(j||"false schema")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(g)+" , params: {} ",e.opts.messages!==!1&&(t+=" , message: 'boolean schema is false' "),e.opts.verbose&&(t+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+y+" "),t+=" } "):t+=" {} ";var E=t;t=v.pop(),!e.compositeRule&&x?e.async?t+=" throw new ValidationError(["+E+"]); ":t+=" validate.errors = ["+E+"]; return false; ":t+=" var err = "+E+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else e.isTop?n?t+=" return data; ":t+=" validate.errors = null; return true; ":t+=" var "+R+" = true; ";return e.isTop&&(t+=" }; return validate; "),t}if(e.isTop){var w=e.isTop,d=e.level=0,f=e.dataLevel=0,y="data";if(e.rootId=e.resolve.fullPath(e.self._getId(e.root.schema)),e.baseId=e.baseId||e.rootId,delete e.isTop,e.dataPathArr=[""],e.schema.default!==void 0&&e.opts.useDefaults&&e.opts.strictDefaults){var S="default is ignored in the schema root";if(e.opts.strictDefaults==="log")e.logger.warn(S);else throw new Error(S)}t+=" var vErrors = null; ",t+=" var errors = 0; ",t+=" if (rootData === undefined) rootData = data; "}else{var d=e.level,f=e.dataLevel,y="data"+(f||"");if(i&&(e.baseId=e.resolve.url(e.baseId,i)),n&&!e.async)throw new Error("async schema in sync schema");t+=" var errs_"+d+" = errors;"}var R="valid"+d,x=!e.opts.allErrors,T="",N="",j,$=e.schema.type,D=Array.isArray($);if($&&e.opts.nullable&&e.schema.nullable===!0&&(D?$.indexOf("null")==-1&&($=$.concat("null")):$!="null"&&($=[$,"null"],D=!0)),D&&$.length==1&&($=$[0],D=!1),e.schema.$ref&&o){if(e.opts.extendRefs=="fail")throw new Error('$ref: validation keywords used in schema at path "'+e.errSchemaPath+'" (see option extendRefs)');e.opts.extendRefs!==!0&&(o=!1,e.logger.warn('$ref: keywords ignored in schema at path "'+e.errSchemaPath+'"'))}if(e.schema.$comment&&e.opts.$comment&&(t+=" "+e.RULES.all.$comment.code(e,"$comment")),$){if(e.opts.coerceTypes)var C=e.util.coerceToTypes(e.opts.coerceTypes,$);var F=e.RULES.types[$];if(C||D||F===!0||F&&!we(F)){var p=e.schemaPath+".type",g=e.errSchemaPath+"/type",p=e.schemaPath+".type",g=e.errSchemaPath+"/type",I=D?"checkDataTypes":"checkDataType";if(t+=" if ("+e.util[I]($,y,e.opts.strictNumbers,!0)+") { ",C){var A="dataType"+d,M="coerced"+d;t+=" var "+A+" = typeof "+y+"; var "+M+" = undefined; ",e.opts.coerceTypes=="array"&&(t+=" if ("+A+" == 'object' && Array.isArray("+y+") && "+y+".length == 1) { "+y+" = "+y+"[0]; "+A+" = typeof "+y+"; if ("+e.util.checkDataType(e.schema.type,y,e.opts.strictNumbers)+") "+M+" = "+y+"; } "),t+=" if ("+M+" !== undefined) ; ";var ee=C;if(ee)for(var Q,Y=-1,X=ee.length-1;Y<X;)Q=ee[Y+=1],Q=="string"?t+=" else if ("+A+" == 'number' || "+A+" == 'boolean') "+M+" = '' + "+y+"; else if ("+y+" === null) "+M+" = ''; ":Q=="number"||Q=="integer"?(t+=" else if ("+A+" == 'boolean' || "+y+" === null || ("+A+" == 'string' && "+y+" && "+y+" == +"+y+" ",Q=="integer"&&(t+=" && !("+y+" % 1)"),t+=")) "+M+" = +"+y+"; "):Q=="boolean"?t+=" else if ("+y+" === 'false' || "+y+" === 0 || "+y+" === null) "+M+" = false; else if ("+y+" === 'true' || "+y+" === 1) "+M+" = true; ":Q=="null"?t+=" else if ("+y+" === '' || "+y+" === 0 || "+y+" === false) "+M+" = null; ":e.opts.coerceTypes=="array"&&Q=="array"&&(t+=" else if ("+A+" == 'string' || "+A+" == 'number' || "+A+" == 'boolean' || "+y+" == null) "+M+" = ["+y+"]; ");t+=" else { ";var v=v||[];v.push(t),t="",e.createErrors!==!1?(t+=" { keyword: '"+(j||"type")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(g)+" , params: { type: '",D?t+=""+$.join(","):t+=""+$,t+="' } ",e.opts.messages!==!1&&(t+=" , message: 'should be ",D?t+=""+$.join(","):t+=""+$,t+="' "),e.opts.verbose&&(t+=" , schema: validate.schema"+p+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+y+" "),t+=" } "):t+=" {} ";var E=t;t=v.pop(),!e.compositeRule&&x?e.async?t+=" throw new ValidationError(["+E+"]); ":t+=" validate.errors = ["+E+"]; return false; ":t+=" var err = "+E+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+=" } if ("+M+" !== undefined) { ";var z=f?"data"+(f-1||""):"parentData",pe=f?e.dataPathArr[f]:"parentDataProperty";t+=" "+y+" = "+M+"; ",f||(t+="if ("+z+" !== undefined)"),t+=" "+z+"["+pe+"] = "+M+"; } "}else{var v=v||[];v.push(t),t="",e.createErrors!==!1?(t+=" { keyword: '"+(j||"type")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(g)+" , params: { type: '",D?t+=""+$.join(","):t+=""+$,t+="' } ",e.opts.messages!==!1&&(t+=" , message: 'should be ",D?t+=""+$.join(","):t+=""+$,t+="' "),e.opts.verbose&&(t+=" , schema: validate.schema"+p+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+y+" "),t+=" } "):t+=" {} ";var E=t;t=v.pop(),!e.compositeRule&&x?e.async?t+=" throw new ValidationError(["+E+"]); ":t+=" validate.errors = ["+E+"]; return false; ":t+=" var err = "+E+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}t+=" } "}}if(e.schema.$ref&&!o)t+=" "+e.RULES.all.$ref.code(e,"$ref")+" ",x&&(t+=" } if (errors === ",w?t+="0":t+="errs_"+d,t+=") { ",N+="}");else{var Oe=e.RULES;if(Oe){for(var F,De=-1,ne=Oe.length-1;De<ne;)if(F=Oe[De+=1],we(F)){if(F.type&&(t+=" if ("+e.util.checkDataType(F.type,y,e.opts.strictNumbers)+") { "),e.opts.useDefaults){if(F.type=="object"&&e.schema.properties){var m=e.schema.properties,be=Object.keys(m),Re=be;if(Re)for(var Ce,St=-1,pt=Re.length-1;St<pt;){Ce=Re[St+=1];var Ee=m[Ce];if(Ee.default!==void 0){var ge=y+e.util.getProperty(Ce);if(e.compositeRule){if(e.opts.strictDefaults){var S="default is ignored for: "+ge;if(e.opts.strictDefaults==="log")e.logger.warn(S);else throw new Error(S)}}else t+=" if ("+ge+" === undefined ",e.opts.useDefaults=="empty"&&(t+=" || "+ge+" === null || "+ge+" === '' "),t+=" ) "+ge+" = ",e.opts.useDefaults=="shared"?t+=" "+e.useDefault(Ee.default)+" ":t+=" "+JSON.stringify(Ee.default)+" ",t+="; "}}}else if(F.type=="array"&&Array.isArray(e.schema.items)){var Dt=e.schema.items;if(Dt){for(var Ee,Y=-1,Ie=Dt.length-1;Y<Ie;)if(Ee=Dt[Y+=1],Ee.default!==void 0){var ge=y+"["+Y+"]";if(e.compositeRule){if(e.opts.strictDefaults){var S="default is ignored for: "+ge;if(e.opts.strictDefaults==="log")e.logger.warn(S);else throw new Error(S)}}else t+=" if ("+ge+" === undefined ",e.opts.useDefaults=="empty"&&(t+=" || "+ge+" === null || "+ge+" === '' "),t+=" ) "+ge+" = ",e.opts.useDefaults=="shared"?t+=" "+e.useDefault(Ee.default)+" ":t+=" "+JSON.stringify(Ee.default)+" ",t+="; "}}}}var ce=F.rules;if(ce){for(var xt,ft=-1,Ct=ce.length-1;ft<Ct;)if(xt=ce[ft+=1],ze(xt)){var kt=xt.code(e,xt.keyword,F.type);kt&&(t+=" "+kt+" ",x&&(T+="}"))}}if(x&&(t+=" "+T+" ",T=""),F.type&&(t+=" } ",$&&$===F.type&&!C)){t+=" else { ";var p=e.schemaPath+".type",g=e.errSchemaPath+"/type",v=v||[];v.push(t),t="",e.createErrors!==!1?(t+=" { keyword: '"+(j||"type")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(g)+" , params: { type: '",D?t+=""+$.join(","):t+=""+$,t+="' } ",e.opts.messages!==!1&&(t+=" , message: 'should be ",D?t+=""+$.join(","):t+=""+$,t+="' "),e.opts.verbose&&(t+=" , schema: validate.schema"+p+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+y+" "),t+=" } "):t+=" {} ";var E=t;t=v.pop(),!e.compositeRule&&x?e.async?t+=" throw new ValidationError(["+E+"]); ":t+=" validate.errors = ["+E+"]; return false; ":t+=" var err = "+E+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+=" } "}x&&(t+=" if (errors === ",w?t+="0":t+="errs_"+d,t+=") { ",N+="}")}}}x&&(t+=" "+N+" "),w?(n?(t+=" if (errors === 0) return data; ",t+=" else throw new ValidationError(vErrors); "):(t+=" validate.errors = vErrors; ",t+=" return errors === 0; "),t+=" }; return validate;"):t+=" var "+R+" = errors === errs_"+d+";";function we(ke){for(var nt=ke.rules,Be=0;Be<nt.length;Be++)if(ze(nt[Be]))return!0}function ze(ke){return e.schema[ke.keyword]!==void 0||ke.implements&&Fe(ke)}function Fe(ke){for(var nt=ke.implements,Be=0;Be<nt.length;Be++)if(e.schema[nt[Be]]!==void 0)return!0}return t}});var _o=H((Pm,yo)=>{"use strict";var ys=vs(),bs=rr(),vo=gs(),$p=Oa(),mo=Ia(),Ap=bs.ucs2length,Np=ls(),Dp=vo.Validation;yo.exports=$a;function $a(s,e,r,a){var t=this,n=this._opts,o=[void 0],i={},l=[],u={},d=[],f={},m=[];e=e||{schema:s,refVal:o,refs:i};var p=Cp.call(this,s,e,a),g=this._compilations[p.index];if(p.compiling)return g.callValidate=S;var y=this._formats,v=this.RULES;try{var E=R(s,e,r,a);g.validate=E;var w=g.callValidate;return w&&(w.schema=E.schema,w.errors=null,w.refs=E.refs,w.refVal=E.refVal,w.root=E.root,w.$async=E.$async,n.sourceCode&&(w.source=E.source)),E}finally{kp.call(this,s,e,a)}function S(){var I=g.validate,A=I.apply(this,arguments);return S.errors=I.errors,A}function R(I,A,M,ee){var Q=!A||A&&A.schema==I;if(A.schema!=e.schema)return $a.call(t,I,A,M,ee);var Y=I.$async===!0,X=mo({isTop:!0,schema:I,isRoot:Q,baseId:ee,root:A,schemaPath:"",errSchemaPath:"#",errorPath:'""',MissingRefError:vo.MissingRef,RULES:v,validate:mo,util:bs,resolve:ys,resolveRef:x,usePattern:D,useDefault:C,useCustomRule:F,opts:n,formats:y,logger:t.logger,self:t});X=_s(o,Fp)+_s(l,Lp)+_s(d,jp)+_s(m,Mp)+X,n.processCode&&(X=n.processCode(X,I));var z;try{var pe=new Function("self","RULES","formats","root","refVal","defaults","customRules","equal","ucs2length","ValidationError",X);z=pe(t,v,y,e,o,d,m,Np,Ap,Dp),o[0]=z}catch(Oe){throw t.logger.error("Error compiling schema, function code:",X),Oe}return z.schema=I,z.errors=null,z.refs=i,z.refVal=o,z.root=Q?z:A,Y&&(z.$async=!0),n.sourceCode===!0&&(z.source={code:X,patterns:l,defaults:d}),z}function x(I,A,M){A=ys.url(I,A);var ee=i[A],Q,Y;if(ee!==void 0)return Q=o[ee],Y="refVal["+ee+"]",$(Q,Y);if(!M&&e.refs){var X=e.refs[A];if(X!==void 0)return Q=e.refVal[X],Y=T(A,Q),$(Q,Y)}Y=T(A);var z=ys.call(t,R,e,A);if(z===void 0){var pe=r&&r[A];pe&&(z=ys.inlineRef(pe,n.inlineRefs)?pe:$a.call(t,pe,e,r,I))}if(z===void 0)N(A);else return j(A,z),$(z,Y)}function T(I,A){var M=o.length;return o[M]=A,i[I]=M,"refVal"+M}function N(I){delete i[I]}function j(I,A){var M=i[I];o[M]=A}function $(I,A){return typeof I=="object"||typeof I=="boolean"?{code:A,schema:I,inline:!0}:{code:A,$async:I&&!!I.$async}}function D(I){var A=u[I];return A===void 0&&(A=u[I]=l.length,l[A]=I),"pattern"+A}function C(I){switch(typeof I){case"boolean":case"number":return""+I;case"string":return bs.toQuotedString(I);case"object":if(I===null)return"null";var A=$p(I),M=f[A];return M===void 0&&(M=f[A]=d.length,d[M]=I),"default"+M}}function F(I,A,M,ee){if(t._opts.validateSchema!==!1){var Q=I.definition.dependencies;if(Q&&!Q.every(function(Re){return Object.prototype.hasOwnProperty.call(M,Re)}))throw new Error("parent schema must have all required keywords: "+Q.join(","));var Y=I.definition.validateSchema;if(Y){var X=Y(A);if(!X){var z="keyword schema is invalid: "+t.errorsText(Y.errors);if(t._opts.validateSchema=="log")t.logger.error(z);else throw new Error(z)}}}var pe=I.definition.compile,Oe=I.definition.inline,De=I.definition.macro,ne;if(pe)ne=pe.call(t,A,M,ee);else if(De)ne=De.call(t,A,M,ee),n.validateSchema!==!1&&t.validateSchema(ne,!0);else if(Oe)ne=Oe.call(t,ee,I.keyword,A,M);else if(ne=I.definition.validate,!ne)return;if(ne===void 0)throw new Error('custom keyword "'+I.keyword+'"failed to compile');var be=m.length;return m[be]=ne,{code:"customRule"+be,validate:ne}}}function Cp(s,e,r){var a=go.call(this,s,e,r);return a>=0?{index:a,compiling:!0}:(a=this._compilations.length,this._compilations[a]={schema:s,root:e,baseId:r},{index:a,compiling:!1})}function kp(s,e,r){var a=go.call(this,s,e,r);a>=0&&this._compilations.splice(a,1)}function go(s,e,r){for(var a=0;a<this._compilations.length;a++){var t=this._compilations[a];if(t.schema==s&&t.root==e&&t.baseId==r)return a}return-1}function Lp(s,e){return"var pattern"+s+" = new RegExp("+bs.toQuotedString(e[s])+");"}function jp(s){return"var default"+s+" = defaults["+s+"];"}function Fp(s,e){return e[s]===void 0?"":"var refVal"+s+" = refVal["+s+"];"}function Mp(s){return"var customRule"+s+" = customRules["+s+"];"}function _s(s,e){if(!s.length)return"";for(var r="",a=0;a<s.length;a++)r+=e(a,s);return r}});var Eo=H((Om,bo)=>{"use strict";var Es=bo.exports=function(){this._cache={}};Es.prototype.put=function(e,r){this._cache[e]=r};Es.prototype.get=function(e){return this._cache[e]};Es.prototype.del=function(e){delete this._cache[e]};Es.prototype.clear=function(){this._cache={}}});var Do=H((Im,No)=>{"use strict";var qp=rr(),Up=/^(\d\d\d\d)-(\d\d)-(\d\d)$/,Bp=[0,31,28,31,30,31,30,31,31,30,31,30,31],Vp=/^(\d\d):(\d\d):(\d\d)(\.\d+)?(z|[+-]\d\d(?::?\d\d)?)?$/i,So=/^(?=.{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,Hp=/^(?:[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,zp=/^(?:[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,xo=/^(?:(?:[^\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,Ro=/^(?:(?:http[s\u017F]?|ftp):\/\/)(?:(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+(?::(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?@)?(?:(?!10(?:\.[0-9]{1,3}){3})(?!127(?:\.[0-9]{1,3}){3})(?!169\.254(?:\.[0-9]{1,3}){2})(?!192\.168(?:\.[0-9]{1,3}){2})(?!172\.(?:1[6-9]|2[0-9]|3[01])(?:\.[0-9]{1,3}){2})(?:[1-9][0-9]?|1[0-9][0-9]|2[01][0-9]|22[0-3])(?:\.(?:1?[0-9]{1,2}|2[0-4][0-9]|25[0-5])){2}(?:\.(?:[1-9][0-9]?|1[0-9][0-9]|2[0-4][0-9]|25[0-4]))|(?:(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)(?:\.(?:(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+-)*(?:[0-9a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])+)*(?:\.(?:(?:[a-z\xA1-\uD7FF\uE000-\uFFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF]){2,})))(?::[0-9]{2,5})?(?:\/(?:[\0-\x08\x0E-\x1F!-\x9F\xA1-\u167F\u1681-\u1FFF\u200B-\u2027\u202A-\u202E\u2030-\u205E\u2060-\u2FFF\u3001-\uD7FF\uE000-\uFEFE\uFF00-\uFFFF]|[\uD800-\uDBFF][\uDC00-\uDFFF]|[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?:[^\uD800-\uDBFF]|^)[\uDC00-\uDFFF])*)?$/i,To=/^(?:urn:uuid:)?[0-9a-f]{8}-(?:[0-9a-f]{4}-){3}[0-9a-f]{12}$/i,wo=/^(?:\/(?:[^~/]|~0|~1)*)*$/,Po=/^#(?:\/(?:[a-z0-9_\-.!$&'()*+,;:=@]|%[0-9a-f]{2}|~0|~1)*)*$/i,Oo=/^(?:0|[1-9][0-9]*)(?:#|(?:\/(?:[^~/]|~0|~1)*)*)$/;No.exports=Ss;function Ss(s){return s=s=="full"?"full":"fast",qp.copy(Ss[s])}Ss.fast={date:/^\d\d\d\d-[0-1]\d-[0-3]\d$/,time:/^(?:[0-2]\d:[0-5]\d:[0-5]\d|23:59:60)(?:\.\d+)?(?:z|[+-]\d\d(?::?\d\d)?)?$/i,"date-time":/^\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,uri:/^(?:[a-z][a-z0-9+\-.]*:)(?:\/?\/)?[^\s]*$/i,"uri-reference":/^(?:(?:[a-z][a-z0-9+\-.]*:)?\/?\/)?(?:[^\\\s#][^\s#]*)?(?:#[^\\\s]*)?$/i,"uri-template":xo,url:Ro,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,hostname:So,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[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}))|:)))(?:%.+)?\s*$/i,regex:Ao,uuid:To,"json-pointer":wo,"json-pointer-uri-fragment":Po,"relative-json-pointer":Oo};Ss.full={date:Io,time:$o,"date-time":Xp,uri:Wp,"uri-reference":zp,"uri-template":xo,url:Ro,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:So,ipv4:/^(?:(?:25[0-5]|2[0-4]\d|[01]?\d\d?)\.){3}(?:25[0-5]|2[0-4]\d|[01]?\d\d?)$/,ipv6:/^\s*(?:(?:(?:[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}))|:)))(?:%.+)?\s*$/i,regex:Ao,uuid:To,"json-pointer":wo,"json-pointer-uri-fragment":Po,"relative-json-pointer":Oo};function Zp(s){return s%4===0&&(s%100!==0||s%400===0)}function Io(s){var e=s.match(Up);if(!e)return!1;var r=+e[1],a=+e[2],t=+e[3];return a>=1&&a<=12&&t>=1&&t<=(a==2&&Zp(r)?29:Bp[a])}function $o(s,e){var r=s.match(Vp);if(!r)return!1;var a=r[1],t=r[2],n=r[3],o=r[5];return(a<=23&&t<=59&&n<=59||a==23&&t==59&&n==60)&&(!e||o)}var Gp=/t|\s/i;function Xp(s){var e=s.split(Gp);return e.length==2&&Io(e[0])&&$o(e[1],!0)}var Qp=/\/|:/;function Wp(s){return Qp.test(s)&&Hp.test(s)}var Kp=/[^\\]\\Z/;function Ao(s){if(Kp.test(s))return!1;try{return new RegExp(s),!0}catch{return!1}}});var ko=H(($m,Co)=>{"use strict";Co.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.errSchemaPath+"/"+r,u=!e.opts.allErrors,d="data"+(o||""),f="valid"+n,m,p;if(i=="#"||i=="#/")e.isRoot?(m=e.async,p="validate"):(m=e.root.schema.$async===!0,p="root.refVal[0]");else{var g=e.resolveRef(e.baseId,i,e.isRoot);if(g===void 0){var y=e.MissingRefError.message(e.baseId,i);if(e.opts.missingRefs=="fail"){e.logger.error(y);var v=v||[];v.push(t),t="",e.createErrors!==!1?(t+=" { keyword: '$ref' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(l)+" , params: { ref: '"+e.util.escapeQuotes(i)+"' } ",e.opts.messages!==!1&&(t+=" , message: 'can\\'t resolve reference "+e.util.escapeQuotes(i)+"' "),e.opts.verbose&&(t+=" , schema: "+e.util.toQuotedString(i)+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+d+" "),t+=" } "):t+=" {} ";var E=t;t=v.pop(),!e.compositeRule&&u?e.async?t+=" throw new ValidationError(["+E+"]); ":t+=" validate.errors = ["+E+"]; return false; ":t+=" var err = "+E+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",u&&(t+=" if (false) { ")}else if(e.opts.missingRefs=="ignore")e.logger.warn(y),u&&(t+=" if (true) { ");else throw new e.MissingRefError(e.baseId,i,y)}else if(g.inline){var w=e.util.copy(e);w.level++;var S="valid"+w.level;w.schema=g.schema,w.schemaPath="",w.errSchemaPath=i;var R=e.validate(w).replace(/validate\.schema/g,g.code);t+=" "+R+" ",u&&(t+=" if ("+S+") { ")}else m=g.$async===!0||e.async&&g.$async!==!1,p=g.code}if(p){var v=v||[];v.push(t),t="",e.opts.passContext?t+=" "+p+".call(this, ":t+=" "+p+"( ",t+=" "+d+", (dataPath || '')",e.errorPath!='""'&&(t+=" + "+e.errorPath);var x=o?"data"+(o-1||""):"parentData",T=o?e.dataPathArr[o]:"parentDataProperty";t+=" , "+x+" , "+T+", rootData) ";var N=t;if(t=v.pop(),m){if(!e.async)throw new Error("async schema referenced by sync schema");u&&(t+=" var "+f+"; "),t+=" try { await "+N+"; ",u&&(t+=" "+f+" = true; "),t+=" } catch (e) { if (!(e instanceof ValidationError)) throw e; if (vErrors === null) vErrors = e.errors; else vErrors = vErrors.concat(e.errors); errors = vErrors.length; ",u&&(t+=" "+f+" = false; "),t+=" } ",u&&(t+=" if ("+f+") { ")}else t+=" if (!"+N+") { if (vErrors === null) vErrors = "+p+".errors; else vErrors = vErrors.concat("+p+".errors); errors = vErrors.length; } ",u&&(t+=" else { ")}return t}});var jo=H((Am,Lo)=>{"use strict";Lo.exports=function(e,r,a){var t=" ",n=e.schema[r],o=e.schemaPath+e.util.getProperty(r),i=e.errSchemaPath+"/"+r,l=!e.opts.allErrors,u=e.util.copy(e),d="";u.level++;var f="valid"+u.level,m=u.baseId,p=!0,g=n;if(g)for(var y,v=-1,E=g.length-1;v<E;)y=g[v+=1],(e.opts.strictKeywords?typeof y=="object"&&Object.keys(y).length>0||y===!1:e.util.schemaHasRules(y,e.RULES.all))&&(p=!1,u.schema=y,u.schemaPath=o+"["+v+"]",u.errSchemaPath=i+"/"+v,t+=" "+e.validate(u)+" ",u.baseId=m,l&&(t+=" if ("+f+") { ",d+="}"));return l&&(p?t+=" if (true) { ":t+=" "+d.slice(0,-1)+" "),t}});var Mo=H((Nm,Fo)=>{"use strict";Fo.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,f="data"+(o||""),m="valid"+n,p="errs__"+n,g=e.util.copy(e),y="";g.level++;var v="valid"+g.level,E=i.every(function(j){return e.opts.strictKeywords?typeof j=="object"&&Object.keys(j).length>0||j===!1:e.util.schemaHasRules(j,e.RULES.all)});if(E){var w=g.baseId;t+=" var "+p+" = errors; var "+m+" = false; ";var S=e.compositeRule;e.compositeRule=g.compositeRule=!0;var R=i;if(R)for(var x,T=-1,N=R.length-1;T<N;)x=R[T+=1],g.schema=x,g.schemaPath=l+"["+T+"]",g.errSchemaPath=u+"/"+T,t+=" "+e.validate(g)+" ",g.baseId=w,t+=" "+m+" = "+m+" || "+v+"; if (!"+m+") { ",y+="}";e.compositeRule=g.compositeRule=S,t+=" "+y+" if (!"+m+") { var err = ",e.createErrors!==!1?(t+=" { keyword: 'anyOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: {} ",e.opts.messages!==!1&&(t+=" , message: 'should match some schema in anyOf' "),e.opts.verbose&&(t+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),t+=" } "):t+=" {} ",t+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&d&&(e.async?t+=" throw new ValidationError(vErrors); ":t+=" validate.errors = vErrors; return false; "),t+=" } else { errors = "+p+"; if (vErrors !== null) { if ("+p+") vErrors.length = "+p+"; else vErrors = null; } ",e.opts.allErrors&&(t+=" } ")}else d&&(t+=" if (true) { ");return t}});var Uo=H((Dm,qo)=>{"use strict";qo.exports=function(e,r,a){var t=" ",n=e.schema[r],o=e.errSchemaPath+"/"+r,i=!e.opts.allErrors,l=e.util.toQuotedString(n);return e.opts.$comment===!0?t+=" console.log("+l+");":typeof e.opts.$comment=="function"&&(t+=" self._opts.$comment("+l+", "+e.util.toQuotedString(o)+", validate.root.schema);"),t}});var Vo=H((Cm,Bo)=>{"use strict";Bo.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,f="data"+(o||""),m="valid"+n,p=e.opts.$data&&i&&i.$data,g;p?(t+=" var schema"+n+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",g="schema"+n):g=i,p||(t+=" var schema"+n+" = validate.schema"+l+";"),t+="var "+m+" = equal("+f+", schema"+n+"); if (!"+m+") { ";var y=y||[];y.push(t),t="",e.createErrors!==!1?(t+=" { keyword: 'const' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { allowedValue: schema"+n+" } ",e.opts.messages!==!1&&(t+=" , message: 'should be equal to constant' "),e.opts.verbose&&(t+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),t+=" } "):t+=" {} ";var v=t;return t=y.pop(),!e.compositeRule&&d?e.async?t+=" throw new ValidationError(["+v+"]); ":t+=" validate.errors = ["+v+"]; return false; ":t+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+=" }",d&&(t+=" else { "),t}});var zo=H((km,Ho)=>{"use strict";Ho.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,f="data"+(o||""),m="valid"+n,p="errs__"+n,g=e.util.copy(e),y="";g.level++;var v="valid"+g.level,E="i"+n,w=g.dataLevel=e.dataLevel+1,S="data"+w,R=e.baseId,x=e.opts.strictKeywords?typeof i=="object"&&Object.keys(i).length>0||i===!1:e.util.schemaHasRules(i,e.RULES.all);if(t+="var "+p+" = errors;var "+m+";",x){var T=e.compositeRule;e.compositeRule=g.compositeRule=!0,g.schema=i,g.schemaPath=l,g.errSchemaPath=u,t+=" var "+v+" = false; for (var "+E+" = 0; "+E+" < "+f+".length; "+E+"++) { ",g.errorPath=e.util.getPathExpr(e.errorPath,E,e.opts.jsonPointers,!0);var N=f+"["+E+"]";g.dataPathArr[w]=E;var j=e.validate(g);g.baseId=R,e.util.varOccurences(j,S)<2?t+=" "+e.util.varReplace(j,S,N)+" ":t+=" var "+S+" = "+N+"; "+j+" ",t+=" if ("+v+") break; } ",e.compositeRule=g.compositeRule=T,t+=" "+y+" if (!"+v+") {"}else t+=" if ("+f+".length == 0) {";var $=$||[];$.push(t),t="",e.createErrors!==!1?(t+=" { keyword: 'contains' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: {} ",e.opts.messages!==!1&&(t+=" , message: 'should contain a valid item' "),e.opts.verbose&&(t+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),t+=" } "):t+=" {} ";var D=t;return t=$.pop(),!e.compositeRule&&d?e.async?t+=" throw new ValidationError(["+D+"]); ":t+=" validate.errors = ["+D+"]; return false; ":t+=" var err = "+D+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+=" } else { ",x&&(t+=" errors = "+p+"; if (vErrors !== null) { if ("+p+") vErrors.length = "+p+"; else vErrors = null; } "),e.opts.allErrors&&(t+=" } "),t}});var Go=H((Lm,Zo)=>{"use strict";Zo.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,f="data"+(o||""),m="errs__"+n,p=e.util.copy(e),g="";p.level++;var y="valid"+p.level,v={},E={},w=e.opts.ownProperties;for(T in i)if(T!="__proto__"){var S=i[T],R=Array.isArray(S)?E:v;R[T]=S}t+="var "+m+" = errors;";var x=e.errorPath;t+="var missing"+n+";";for(var T in E)if(R=E[T],R.length){if(t+=" if ( "+f+e.util.getProperty(T)+" !== undefined ",w&&(t+=" && Object.prototype.hasOwnProperty.call("+f+", '"+e.util.escapeQuotes(T)+"') "),d){t+=" && ( ";var N=R;if(N)for(var j,$=-1,D=N.length-1;$<D;){j=N[$+=1],$&&(t+=" || ");var C=e.util.getProperty(j),F=f+C;t+=" ( ( "+F+" === undefined ",w&&(t+=" || ! Object.prototype.hasOwnProperty.call("+f+", '"+e.util.escapeQuotes(j)+"') "),t+=") && (missing"+n+" = "+e.util.toQuotedString(e.opts.jsonPointers?j:C)+") ) "}t+=")) { ";var I="missing"+n,A="' + "+I+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(x,I,!0):x+" + "+I);var M=M||[];M.push(t),t="",e.createErrors!==!1?(t+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { property: '"+e.util.escapeQuotes(T)+"', missingProperty: '"+A+"', depsCount: "+R.length+", deps: '"+e.util.escapeQuotes(R.length==1?R[0]:R.join(", "))+"' } ",e.opts.messages!==!1&&(t+=" , message: 'should have ",R.length==1?t+="property "+e.util.escapeQuotes(R[0]):t+="properties "+e.util.escapeQuotes(R.join(", ")),t+=" when property "+e.util.escapeQuotes(T)+" is present' "),e.opts.verbose&&(t+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),t+=" } "):t+=" {} ";var ee=t;t=M.pop(),!e.compositeRule&&d?e.async?t+=" throw new ValidationError(["+ee+"]); ":t+=" validate.errors = ["+ee+"]; return false; ":t+=" var err = "+ee+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; "}else{t+=" ) { ";var Q=R;if(Q)for(var j,Y=-1,X=Q.length-1;Y<X;){j=Q[Y+=1];var C=e.util.getProperty(j),A=e.util.escapeQuotes(j),F=f+C;e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(x,j,e.opts.jsonPointers)),t+=" if ( "+F+" === undefined ",w&&(t+=" || ! Object.prototype.hasOwnProperty.call("+f+", '"+e.util.escapeQuotes(j)+"') "),t+=") { var err = ",e.createErrors!==!1?(t+=" { keyword: 'dependencies' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { property: '"+e.util.escapeQuotes(T)+"', missingProperty: '"+A+"', depsCount: "+R.length+", deps: '"+e.util.escapeQuotes(R.length==1?R[0]:R.join(", "))+"' } ",e.opts.messages!==!1&&(t+=" , message: 'should have ",R.length==1?t+="property "+e.util.escapeQuotes(R[0]):t+="properties "+e.util.escapeQuotes(R.join(", ")),t+=" when property "+e.util.escapeQuotes(T)+" is present' "),e.opts.verbose&&(t+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),t+=" } "):t+=" {} ",t+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}t+=" } ",d&&(g+="}",t+=" else { ")}e.errorPath=x;var z=p.baseId;for(var T in v){var S=v[T];(e.opts.strictKeywords?typeof S=="object"&&Object.keys(S).length>0||S===!1:e.util.schemaHasRules(S,e.RULES.all))&&(t+=" "+y+" = true; if ( "+f+e.util.getProperty(T)+" !== undefined ",w&&(t+=" && Object.prototype.hasOwnProperty.call("+f+", '"+e.util.escapeQuotes(T)+"') "),t+=") { ",p.schema=S,p.schemaPath=l+e.util.getProperty(T),p.errSchemaPath=u+"/"+e.util.escapeFragment(T),t+=" "+e.validate(p)+" ",p.baseId=z,t+=" } ",d&&(t+=" if ("+y+") { ",g+="}"))}return d&&(t+=" "+g+" if ("+m+" == errors) {"),t}});var Qo=H((jm,Xo)=>{"use strict";Xo.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,f="data"+(o||""),m="valid"+n,p=e.opts.$data&&i&&i.$data,g;p?(t+=" var schema"+n+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",g="schema"+n):g=i;var y="i"+n,v="schema"+n;p||(t+=" var "+v+" = validate.schema"+l+";"),t+="var "+m+";",p&&(t+=" if (schema"+n+" === undefined) "+m+" = true; else if (!Array.isArray(schema"+n+")) "+m+" = false; else {"),t+=""+m+" = false;for (var "+y+"=0; "+y+"<"+v+".length; "+y+"++) if (equal("+f+", "+v+"["+y+"])) { "+m+" = true; break; }",p&&(t+=" } "),t+=" if (!"+m+") { ";var E=E||[];E.push(t),t="",e.createErrors!==!1?(t+=" { keyword: 'enum' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { allowedValues: schema"+n+" } ",e.opts.messages!==!1&&(t+=" , message: 'should be equal to one of the allowed values' "),e.opts.verbose&&(t+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),t+=" } "):t+=" {} ";var w=t;return t=E.pop(),!e.compositeRule&&d?e.async?t+=" throw new ValidationError(["+w+"]); ":t+=" validate.errors = ["+w+"]; return false; ":t+=" var err = "+w+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+=" }",d&&(t+=" else { "),t}});var Ko=H((Fm,Wo)=>{"use strict";Wo.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,f="data"+(o||"");if(e.opts.format===!1)return d&&(t+=" if (true) { "),t;var m=e.opts.$data&&i&&i.$data,p;m?(t+=" var schema"+n+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",p="schema"+n):p=i;var g=e.opts.unknownFormats,y=Array.isArray(g);if(m){var v="format"+n,E="isObject"+n,w="formatType"+n;t+=" var "+v+" = formats["+p+"]; var "+E+" = typeof "+v+" == 'object' && !("+v+" instanceof RegExp) && "+v+".validate; var "+w+" = "+E+" && "+v+".type || 'string'; if ("+E+") { ",e.async&&(t+=" var async"+n+" = "+v+".async; "),t+=" "+v+" = "+v+".validate; } if ( ",m&&(t+=" ("+p+" !== undefined && typeof "+p+" != 'string') || "),t+=" (",g!="ignore"&&(t+=" ("+p+" && !"+v+" ",y&&(t+=" && self._opts.unknownFormats.indexOf("+p+") == -1 "),t+=") || "),t+=" ("+v+" && "+w+" == '"+a+"' && !(typeof "+v+" == 'function' ? ",e.async?t+=" (async"+n+" ? await "+v+"("+f+") : "+v+"("+f+")) ":t+=" "+v+"("+f+") ",t+=" : "+v+".test("+f+"))))) {"}else{var v=e.formats[i];if(!v){if(g=="ignore")return e.logger.warn('unknown format "'+i+'" ignored in schema at path "'+e.errSchemaPath+'"'),d&&(t+=" if (true) { "),t;if(y&&g.indexOf(i)>=0)return d&&(t+=" if (true) { "),t;throw new Error('unknown format "'+i+'" is used in schema at path "'+e.errSchemaPath+'"')}var E=typeof v=="object"&&!(v instanceof RegExp)&&v.validate,w=E&&v.type||"string";if(E){var S=v.async===!0;v=v.validate}if(w!=a)return d&&(t+=" if (true) { "),t;if(S){if(!e.async)throw new Error("async format in sync schema");var R="formats"+e.util.getProperty(i)+".validate";t+=" if (!(await "+R+"("+f+"))) { "}else{t+=" if (! ";var R="formats"+e.util.getProperty(i);E&&(R+=".validate"),typeof v=="function"?t+=" "+R+"("+f+") ":t+=" "+R+".test("+f+") ",t+=") { "}}var x=x||[];x.push(t),t="",e.createErrors!==!1?(t+=" { keyword: 'format' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { format: ",m?t+=""+p:t+=""+e.util.toQuotedString(i),t+=" } ",e.opts.messages!==!1&&(t+=` , message: 'should match format "`,m?t+="' + "+p+" + '":t+=""+e.util.escapeQuotes(i),t+=`"' `),e.opts.verbose&&(t+=" , schema: ",m?t+="validate.schema"+l:t+=""+e.util.toQuotedString(i),t+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),t+=" } "):t+=" {} ";var T=t;return t=x.pop(),!e.compositeRule&&d?e.async?t+=" throw new ValidationError(["+T+"]); ":t+=" validate.errors = ["+T+"]; return false; ":t+=" var err = "+T+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+=" } ",d&&(t+=" else { "),t}});var Yo=H((Mm,Jo)=>{"use strict";Jo.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,f="data"+(o||""),m="valid"+n,p="errs__"+n,g=e.util.copy(e);g.level++;var y="valid"+g.level,v=e.schema.then,E=e.schema.else,w=v!==void 0&&(e.opts.strictKeywords?typeof v=="object"&&Object.keys(v).length>0||v===!1:e.util.schemaHasRules(v,e.RULES.all)),S=E!==void 0&&(e.opts.strictKeywords?typeof E=="object"&&Object.keys(E).length>0||E===!1:e.util.schemaHasRules(E,e.RULES.all)),R=g.baseId;if(w||S){var x;g.createErrors=!1,g.schema=i,g.schemaPath=l,g.errSchemaPath=u,t+=" var "+p+" = errors; var "+m+" = true; ";var T=e.compositeRule;e.compositeRule=g.compositeRule=!0,t+=" "+e.validate(g)+" ",g.baseId=R,g.createErrors=!0,t+=" errors = "+p+"; if (vErrors !== null) { if ("+p+") vErrors.length = "+p+"; else vErrors = null; } ",e.compositeRule=g.compositeRule=T,w?(t+=" if ("+y+") { ",g.schema=e.schema.then,g.schemaPath=e.schemaPath+".then",g.errSchemaPath=e.errSchemaPath+"/then",t+=" "+e.validate(g)+" ",g.baseId=R,t+=" "+m+" = "+y+"; ",w&&S?(x="ifClause"+n,t+=" var "+x+" = 'then'; "):x="'then'",t+=" } ",S&&(t+=" else { ")):t+=" if (!"+y+") { ",S&&(g.schema=e.schema.else,g.schemaPath=e.schemaPath+".else",g.errSchemaPath=e.errSchemaPath+"/else",t+=" "+e.validate(g)+" ",g.baseId=R,t+=" "+m+" = "+y+"; ",w&&S?(x="ifClause"+n,t+=" var "+x+" = 'else'; "):x="'else'",t+=" } "),t+=" if (!"+m+") { var err = ",e.createErrors!==!1?(t+=" { keyword: 'if' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { failingKeyword: "+x+" } ",e.opts.messages!==!1&&(t+=` , message: 'should match "' + `+x+` + '" schema' `),e.opts.verbose&&(t+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),t+=" } "):t+=" {} ",t+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&d&&(e.async?t+=" throw new ValidationError(vErrors); ":t+=" validate.errors = vErrors; return false; "),t+=" } ",d&&(t+=" else { ")}else d&&(t+=" if (true) { ");return t}});var ti=H((qm,ei)=>{"use strict";ei.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,f="data"+(o||""),m="valid"+n,p="errs__"+n,g=e.util.copy(e),y="";g.level++;var v="valid"+g.level,E="i"+n,w=g.dataLevel=e.dataLevel+1,S="data"+w,R=e.baseId;if(t+="var "+p+" = errors;var "+m+";",Array.isArray(i)){var x=e.schema.additionalItems;if(x===!1){t+=" "+m+" = "+f+".length <= "+i.length+"; ";var T=u;u=e.errSchemaPath+"/additionalItems",t+=" if (!"+m+") { ";var N=N||[];N.push(t),t="",e.createErrors!==!1?(t+=" { keyword: 'additionalItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+i.length+" } ",e.opts.messages!==!1&&(t+=" , message: 'should NOT have more than "+i.length+" items' "),e.opts.verbose&&(t+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),t+=" } "):t+=" {} ";var j=t;t=N.pop(),!e.compositeRule&&d?e.async?t+=" throw new ValidationError(["+j+"]); ":t+=" validate.errors = ["+j+"]; return false; ":t+=" var err = "+j+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+=" } ",u=T,d&&(y+="}",t+=" else { ")}var $=i;if($){for(var D,C=-1,F=$.length-1;C<F;)if(D=$[C+=1],e.opts.strictKeywords?typeof D=="object"&&Object.keys(D).length>0||D===!1:e.util.schemaHasRules(D,e.RULES.all)){t+=" "+v+" = true; if ("+f+".length > "+C+") { ";var I=f+"["+C+"]";g.schema=D,g.schemaPath=l+"["+C+"]",g.errSchemaPath=u+"/"+C,g.errorPath=e.util.getPathExpr(e.errorPath,C,e.opts.jsonPointers,!0),g.dataPathArr[w]=C;var A=e.validate(g);g.baseId=R,e.util.varOccurences(A,S)<2?t+=" "+e.util.varReplace(A,S,I)+" ":t+=" var "+S+" = "+I+"; "+A+" ",t+=" } ",d&&(t+=" if ("+v+") { ",y+="}")}}if(typeof x=="object"&&(e.opts.strictKeywords?typeof x=="object"&&Object.keys(x).length>0||x===!1:e.util.schemaHasRules(x,e.RULES.all))){g.schema=x,g.schemaPath=e.schemaPath+".additionalItems",g.errSchemaPath=e.errSchemaPath+"/additionalItems",t+=" "+v+" = true; if ("+f+".length > "+i.length+") { for (var "+E+" = "+i.length+"; "+E+" < "+f+".length; "+E+"++) { ",g.errorPath=e.util.getPathExpr(e.errorPath,E,e.opts.jsonPointers,!0);var I=f+"["+E+"]";g.dataPathArr[w]=E;var A=e.validate(g);g.baseId=R,e.util.varOccurences(A,S)<2?t+=" "+e.util.varReplace(A,S,I)+" ":t+=" var "+S+" = "+I+"; "+A+" ",d&&(t+=" if (!"+v+") break; "),t+=" } } ",d&&(t+=" if ("+v+") { ",y+="}")}}else if(e.opts.strictKeywords?typeof i=="object"&&Object.keys(i).length>0||i===!1:e.util.schemaHasRules(i,e.RULES.all)){g.schema=i,g.schemaPath=l,g.errSchemaPath=u,t+=" for (var "+E+" = 0; "+E+" < "+f+".length; "+E+"++) { ",g.errorPath=e.util.getPathExpr(e.errorPath,E,e.opts.jsonPointers,!0);var I=f+"["+E+"]";g.dataPathArr[w]=E;var A=e.validate(g);g.baseId=R,e.util.varOccurences(A,S)<2?t+=" "+e.util.varReplace(A,S,I)+" ":t+=" var "+S+" = "+I+"; "+A+" ",d&&(t+=" if (!"+v+") break; "),t+=" }"}return d&&(t+=" "+y+" if ("+p+" == errors) {"),t}});var Aa=H((Um,ri)=>{"use strict";ri.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,R,f="data"+(o||""),m=e.opts.$data&&i&&i.$data,p;m?(t+=" var schema"+n+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",p="schema"+n):p=i;var g=r=="maximum",y=g?"exclusiveMaximum":"exclusiveMinimum",v=e.schema[y],E=e.opts.$data&&v&&v.$data,w=g?"<":">",S=g?">":"<",R=void 0;if(!(m||typeof i=="number"||i===void 0))throw new Error(r+" must be number");if(!(E||v===void 0||typeof v=="number"||typeof v=="boolean"))throw new Error(y+" must be number or boolean");if(E){var x=e.util.getData(v.$data,o,e.dataPathArr),T="exclusive"+n,N="exclType"+n,j="exclIsNumber"+n,$="op"+n,D="' + "+$+" + '";t+=" var schemaExcl"+n+" = "+x+"; ",x="schemaExcl"+n,t+=" var "+T+"; var "+N+" = typeof "+x+"; if ("+N+" != 'boolean' && "+N+" != 'undefined' && "+N+" != 'number') { ";var R=y,C=C||[];C.push(t),t="",e.createErrors!==!1?(t+=" { keyword: '"+(R||"_exclusiveLimit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: {} ",e.opts.messages!==!1&&(t+=" , message: '"+y+" should be boolean' "),e.opts.verbose&&(t+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),t+=" } "):t+=" {} ";var F=t;t=C.pop(),!e.compositeRule&&d?e.async?t+=" throw new ValidationError(["+F+"]); ":t+=" validate.errors = ["+F+"]; return false; ":t+=" var err = "+F+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+=" } else if ( ",m&&(t+=" ("+p+" !== undefined && typeof "+p+" != 'number') || "),t+=" "+N+" == 'number' ? ( ("+T+" = "+p+" === undefined || "+x+" "+w+"= "+p+") ? "+f+" "+S+"= "+x+" : "+f+" "+S+" "+p+" ) : ( ("+T+" = "+x+" === true) ? "+f+" "+S+"= "+p+" : "+f+" "+S+" "+p+" ) || "+f+" !== "+f+") { var op"+n+" = "+T+" ? '"+w+"' : '"+w+"='; ",i===void 0&&(R=y,u=e.errSchemaPath+"/"+y,p=x,m=E)}else{var j=typeof v=="number",D=w;if(j&&m){var $="'"+D+"'";t+=" if ( ",m&&(t+=" ("+p+" !== undefined && typeof "+p+" != 'number') || "),t+=" ( "+p+" === undefined || "+v+" "+w+"= "+p+" ? "+f+" "+S+"= "+v+" : "+f+" "+S+" "+p+" ) || "+f+" !== "+f+") { "}else{j&&i===void 0?(T=!0,R=y,u=e.errSchemaPath+"/"+y,p=v,S+="="):(j&&(p=Math[g?"min":"max"](v,i)),v===(j?p:!0)?(T=!0,R=y,u=e.errSchemaPath+"/"+y,S+="="):(T=!1,D+="="));var $="'"+D+"'";t+=" if ( ",m&&(t+=" ("+p+" !== undefined && typeof "+p+" != 'number') || "),t+=" "+f+" "+S+" "+p+" || "+f+" !== "+f+") { "}}R=R||r;var C=C||[];C.push(t),t="",e.createErrors!==!1?(t+=" { keyword: '"+(R||"_limit")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { comparison: "+$+", limit: "+p+", exclusive: "+T+" } ",e.opts.messages!==!1&&(t+=" , message: 'should be "+D+" ",m?t+="' + "+p:t+=""+p+"'"),e.opts.verbose&&(t+=" , schema: ",m?t+="validate.schema"+l:t+=""+i,t+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),t+=" } "):t+=" {} ";var F=t;return t=C.pop(),!e.compositeRule&&d?e.async?t+=" throw new ValidationError(["+F+"]); ":t+=" validate.errors = ["+F+"]; return false; ":t+=" var err = "+F+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+=" } ",d&&(t+=" else { "),t}});var Na=H((Bm,si)=>{"use strict";si.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,y,f="data"+(o||""),m=e.opts.$data&&i&&i.$data,p;if(m?(t+=" var schema"+n+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",p="schema"+n):p=i,!(m||typeof i=="number"))throw new Error(r+" must be number");var g=r=="maxItems"?">":"<";t+="if ( ",m&&(t+=" ("+p+" !== undefined && typeof "+p+" != 'number') || "),t+=" "+f+".length "+g+" "+p+") { ";var y=r,v=v||[];v.push(t),t="",e.createErrors!==!1?(t+=" { keyword: '"+(y||"_limitItems")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+p+" } ",e.opts.messages!==!1&&(t+=" , message: 'should NOT have ",r=="maxItems"?t+="more":t+="fewer",t+=" than ",m?t+="' + "+p+" + '":t+=""+i,t+=" items' "),e.opts.verbose&&(t+=" , schema: ",m?t+="validate.schema"+l:t+=""+i,t+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),t+=" } "):t+=" {} ";var E=t;return t=v.pop(),!e.compositeRule&&d?e.async?t+=" throw new ValidationError(["+E+"]); ":t+=" validate.errors = ["+E+"]; return false; ":t+=" var err = "+E+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+="} ",d&&(t+=" else { "),t}});var Da=H((Vm,ai)=>{"use strict";ai.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,y,f="data"+(o||""),m=e.opts.$data&&i&&i.$data,p;if(m?(t+=" var schema"+n+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",p="schema"+n):p=i,!(m||typeof i=="number"))throw new Error(r+" must be number");var g=r=="maxLength"?">":"<";t+="if ( ",m&&(t+=" ("+p+" !== undefined && typeof "+p+" != 'number') || "),e.opts.unicode===!1?t+=" "+f+".length ":t+=" ucs2length("+f+") ",t+=" "+g+" "+p+") { ";var y=r,v=v||[];v.push(t),t="",e.createErrors!==!1?(t+=" { keyword: '"+(y||"_limitLength")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+p+" } ",e.opts.messages!==!1&&(t+=" , message: 'should NOT be ",r=="maxLength"?t+="longer":t+="shorter",t+=" than ",m?t+="' + "+p+" + '":t+=""+i,t+=" characters' "),e.opts.verbose&&(t+=" , schema: ",m?t+="validate.schema"+l:t+=""+i,t+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),t+=" } "):t+=" {} ";var E=t;return t=v.pop(),!e.compositeRule&&d?e.async?t+=" throw new ValidationError(["+E+"]); ":t+=" validate.errors = ["+E+"]; return false; ":t+=" var err = "+E+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+="} ",d&&(t+=" else { "),t}});var Ca=H((Hm,ni)=>{"use strict";ni.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,y,f="data"+(o||""),m=e.opts.$data&&i&&i.$data,p;if(m?(t+=" var schema"+n+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",p="schema"+n):p=i,!(m||typeof i=="number"))throw new Error(r+" must be number");var g=r=="maxProperties"?">":"<";t+="if ( ",m&&(t+=" ("+p+" !== undefined && typeof "+p+" != 'number') || "),t+=" Object.keys("+f+").length "+g+" "+p+") { ";var y=r,v=v||[];v.push(t),t="",e.createErrors!==!1?(t+=" { keyword: '"+(y||"_limitProperties")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { limit: "+p+" } ",e.opts.messages!==!1&&(t+=" , message: 'should NOT have ",r=="maxProperties"?t+="more":t+="fewer",t+=" than ",m?t+="' + "+p+" + '":t+=""+i,t+=" properties' "),e.opts.verbose&&(t+=" , schema: ",m?t+="validate.schema"+l:t+=""+i,t+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),t+=" } "):t+=" {} ";var E=t;return t=v.pop(),!e.compositeRule&&d?e.async?t+=" throw new ValidationError(["+E+"]); ":t+=" validate.errors = ["+E+"]; return false; ":t+=" var err = "+E+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+="} ",d&&(t+=" else { "),t}});var ii=H((zm,oi)=>{"use strict";oi.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,f="data"+(o||""),m=e.opts.$data&&i&&i.$data,p;if(m?(t+=" var schema"+n+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",p="schema"+n):p=i,!(m||typeof i=="number"))throw new Error(r+" must be number");t+="var division"+n+";if (",m&&(t+=" "+p+" !== undefined && ( typeof "+p+" != 'number' || "),t+=" (division"+n+" = "+f+" / "+p+", ",e.opts.multipleOfPrecision?t+=" Math.abs(Math.round(division"+n+") - division"+n+") > 1e-"+e.opts.multipleOfPrecision+" ":t+=" division"+n+" !== parseInt(division"+n+") ",t+=" ) ",m&&(t+=" ) "),t+=" ) { ";var g=g||[];g.push(t),t="",e.createErrors!==!1?(t+=" { keyword: 'multipleOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { multipleOf: "+p+" } ",e.opts.messages!==!1&&(t+=" , message: 'should be multiple of ",m?t+="' + "+p:t+=""+p+"'"),e.opts.verbose&&(t+=" , schema: ",m?t+="validate.schema"+l:t+=""+i,t+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),t+=" } "):t+=" {} ";var y=t;return t=g.pop(),!e.compositeRule&&d?e.async?t+=" throw new ValidationError(["+y+"]); ":t+=" validate.errors = ["+y+"]; return false; ":t+=" var err = "+y+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+="} ",d&&(t+=" else { "),t}});var li=H((Zm,ci)=>{"use strict";ci.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,f="data"+(o||""),m="errs__"+n,p=e.util.copy(e);p.level++;var g="valid"+p.level;if(e.opts.strictKeywords?typeof i=="object"&&Object.keys(i).length>0||i===!1:e.util.schemaHasRules(i,e.RULES.all)){p.schema=i,p.schemaPath=l,p.errSchemaPath=u,t+=" var "+m+" = errors; ";var y=e.compositeRule;e.compositeRule=p.compositeRule=!0,p.createErrors=!1;var v;p.opts.allErrors&&(v=p.opts.allErrors,p.opts.allErrors=!1),t+=" "+e.validate(p)+" ",p.createErrors=!0,v&&(p.opts.allErrors=v),e.compositeRule=p.compositeRule=y,t+=" if ("+g+") { ";var E=E||[];E.push(t),t="",e.createErrors!==!1?(t+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: {} ",e.opts.messages!==!1&&(t+=" , message: 'should NOT be valid' "),e.opts.verbose&&(t+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),t+=" } "):t+=" {} ";var w=t;t=E.pop(),!e.compositeRule&&d?e.async?t+=" throw new ValidationError(["+w+"]); ":t+=" validate.errors = ["+w+"]; return false; ":t+=" var err = "+w+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+=" } else { errors = "+m+"; if (vErrors !== null) { if ("+m+") vErrors.length = "+m+"; else vErrors = null; } ",e.opts.allErrors&&(t+=" } ")}else t+=" var err = ",e.createErrors!==!1?(t+=" { keyword: 'not' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: {} ",e.opts.messages!==!1&&(t+=" , message: 'should NOT be valid' "),e.opts.verbose&&(t+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),t+=" } "):t+=" {} ",t+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",d&&(t+=" if (false) { ");return t}});var di=H((Gm,ui)=>{"use strict";ui.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,f="data"+(o||""),m="valid"+n,p="errs__"+n,g=e.util.copy(e),y="";g.level++;var v="valid"+g.level,E=g.baseId,w="prevValid"+n,S="passingSchemas"+n;t+="var "+p+" = errors , "+w+" = false , "+m+" = false , "+S+" = null; ";var R=e.compositeRule;e.compositeRule=g.compositeRule=!0;var x=i;if(x)for(var T,N=-1,j=x.length-1;N<j;)T=x[N+=1],(e.opts.strictKeywords?typeof T=="object"&&Object.keys(T).length>0||T===!1:e.util.schemaHasRules(T,e.RULES.all))?(g.schema=T,g.schemaPath=l+"["+N+"]",g.errSchemaPath=u+"/"+N,t+=" "+e.validate(g)+" ",g.baseId=E):t+=" var "+v+" = true; ",N&&(t+=" if ("+v+" && "+w+") { "+m+" = false; "+S+" = ["+S+", "+N+"]; } else { ",y+="}"),t+=" if ("+v+") { "+m+" = "+w+" = true; "+S+" = "+N+"; }";return e.compositeRule=g.compositeRule=R,t+=""+y+"if (!"+m+") { var err = ",e.createErrors!==!1?(t+=" { keyword: 'oneOf' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { passingSchemas: "+S+" } ",e.opts.messages!==!1&&(t+=" , message: 'should match exactly one schema in oneOf' "),e.opts.verbose&&(t+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),t+=" } "):t+=" {} ",t+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&d&&(e.async?t+=" throw new ValidationError(vErrors); ":t+=" validate.errors = vErrors; return false; "),t+="} else { errors = "+p+"; if (vErrors !== null) { if ("+p+") vErrors.length = "+p+"; else vErrors = null; }",e.opts.allErrors&&(t+=" } "),t}});var fi=H((Xm,pi)=>{"use strict";pi.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,f="data"+(o||""),m=e.opts.$data&&i&&i.$data,p;m?(t+=" var schema"+n+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",p="schema"+n):p=i;var g=m?"(new RegExp("+p+"))":e.usePattern(i);t+="if ( ",m&&(t+=" ("+p+" !== undefined && typeof "+p+" != 'string') || "),t+=" !"+g+".test("+f+") ) { ";var y=y||[];y.push(t),t="",e.createErrors!==!1?(t+=" { keyword: 'pattern' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { pattern: ",m?t+=""+p:t+=""+e.util.toQuotedString(i),t+=" } ",e.opts.messages!==!1&&(t+=` , message: 'should match pattern "`,m?t+="' + "+p+" + '":t+=""+e.util.escapeQuotes(i),t+=`"' `),e.opts.verbose&&(t+=" , schema: ",m?t+="validate.schema"+l:t+=""+e.util.toQuotedString(i),t+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),t+=" } "):t+=" {} ";var v=t;return t=y.pop(),!e.compositeRule&&d?e.async?t+=" throw new ValidationError(["+v+"]); ":t+=" validate.errors = ["+v+"]; return false; ":t+=" var err = "+v+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+="} ",d&&(t+=" else { "),t}});var mi=H((Qm,hi)=>{"use strict";hi.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,f="data"+(o||""),m="errs__"+n,p=e.util.copy(e),g="";p.level++;var y="valid"+p.level,v="key"+n,E="idx"+n,w=p.dataLevel=e.dataLevel+1,S="data"+w,R="dataProperties"+n,x=Object.keys(i||{}).filter(Y),T=e.schema.patternProperties||{},N=Object.keys(T).filter(Y),j=e.schema.additionalProperties,$=x.length||N.length,D=j===!1,C=typeof j=="object"&&Object.keys(j).length,F=e.opts.removeAdditional,I=D||C||F,A=e.opts.ownProperties,M=e.baseId,ee=e.schema.required;if(ee&&!(e.opts.$data&&ee.$data)&&ee.length<e.opts.loopRequired)var Q=e.util.toHash(ee);function Y(et){return et!=="__proto__"}if(t+="var "+m+" = errors;var "+y+" = true;",A&&(t+=" var "+R+" = undefined;"),I){if(A?t+=" "+R+" = "+R+" || Object.keys("+f+"); for (var "+E+"=0; "+E+"<"+R+".length; "+E+"++) { var "+v+" = "+R+"["+E+"]; ":t+=" for (var "+v+" in "+f+") { ",$){if(t+=" var isAdditional"+n+" = !(false ",x.length)if(x.length>8)t+=" || validate.schema"+l+".hasOwnProperty("+v+") ";else{var X=x;if(X)for(var z,pe=-1,Oe=X.length-1;pe<Oe;)z=X[pe+=1],t+=" || "+v+" == "+e.util.toQuotedString(z)+" "}if(N.length){var De=N;if(De)for(var ne,be=-1,Re=De.length-1;be<Re;)ne=De[be+=1],t+=" || "+e.usePattern(ne)+".test("+v+") "}t+=" ); if (isAdditional"+n+") { "}if(F=="all")t+=" delete "+f+"["+v+"]; ";else{var Ce=e.errorPath,St="' + "+v+" + '";if(e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(e.errorPath,v,e.opts.jsonPointers)),D)if(F)t+=" delete "+f+"["+v+"]; ";else{t+=" "+y+" = false; ";var pt=u;u=e.errSchemaPath+"/additionalProperties";var Ee=Ee||[];Ee.push(t),t="",e.createErrors!==!1?(t+=" { keyword: 'additionalProperties' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { additionalProperty: '"+St+"' } ",e.opts.messages!==!1&&(t+=" , message: '",e.opts._errorDataPathProperty?t+="is an invalid additional property":t+="should NOT have additional properties",t+="' "),e.opts.verbose&&(t+=" , schema: false , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),t+=" } "):t+=" {} ";var ge=t;t=Ee.pop(),!e.compositeRule&&d?e.async?t+=" throw new ValidationError(["+ge+"]); ":t+=" validate.errors = ["+ge+"]; return false; ":t+=" var err = "+ge+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",u=pt,d&&(t+=" break; ")}else if(C)if(F=="failing"){t+=" var "+m+" = errors; ";var Dt=e.compositeRule;e.compositeRule=p.compositeRule=!0,p.schema=j,p.schemaPath=e.schemaPath+".additionalProperties",p.errSchemaPath=e.errSchemaPath+"/additionalProperties",p.errorPath=e.opts._errorDataPathProperty?e.errorPath:e.util.getPathExpr(e.errorPath,v,e.opts.jsonPointers);var Ie=f+"["+v+"]";p.dataPathArr[w]=v;var ce=e.validate(p);p.baseId=M,e.util.varOccurences(ce,S)<2?t+=" "+e.util.varReplace(ce,S,Ie)+" ":t+=" var "+S+" = "+Ie+"; "+ce+" ",t+=" if (!"+y+") { errors = "+m+"; if (validate.errors !== null) { if (errors) validate.errors.length = errors; else validate.errors = null; } delete "+f+"["+v+"]; } ",e.compositeRule=p.compositeRule=Dt}else{p.schema=j,p.schemaPath=e.schemaPath+".additionalProperties",p.errSchemaPath=e.errSchemaPath+"/additionalProperties",p.errorPath=e.opts._errorDataPathProperty?e.errorPath:e.util.getPathExpr(e.errorPath,v,e.opts.jsonPointers);var Ie=f+"["+v+"]";p.dataPathArr[w]=v;var ce=e.validate(p);p.baseId=M,e.util.varOccurences(ce,S)<2?t+=" "+e.util.varReplace(ce,S,Ie)+" ":t+=" var "+S+" = "+Ie+"; "+ce+" ",d&&(t+=" if (!"+y+") break; ")}e.errorPath=Ce}$&&(t+=" } "),t+=" } ",d&&(t+=" if ("+y+") { ",g+="}")}var xt=e.opts.useDefaults&&!e.compositeRule;if(x.length){var ft=x;if(ft)for(var z,Ct=-1,kt=ft.length-1;Ct<kt;){z=ft[Ct+=1];var we=i[z];if(e.opts.strictKeywords?typeof we=="object"&&Object.keys(we).length>0||we===!1:e.util.schemaHasRules(we,e.RULES.all)){var ze=e.util.getProperty(z),Ie=f+ze,Fe=xt&&we.default!==void 0;p.schema=we,p.schemaPath=l+ze,p.errSchemaPath=u+"/"+e.util.escapeFragment(z),p.errorPath=e.util.getPath(e.errorPath,z,e.opts.jsonPointers),p.dataPathArr[w]=e.util.toQuotedString(z);var ce=e.validate(p);if(p.baseId=M,e.util.varOccurences(ce,S)<2){ce=e.util.varReplace(ce,S,Ie);var ke=Ie}else{var ke=S;t+=" var "+S+" = "+Ie+"; "}if(Fe)t+=" "+ce+" ";else{if(Q&&Q[z]){t+=" if ( "+ke+" === undefined ",A&&(t+=" || ! Object.prototype.hasOwnProperty.call("+f+", '"+e.util.escapeQuotes(z)+"') "),t+=") { "+y+" = false; ";var Ce=e.errorPath,pt=u,nt=e.util.escapeQuotes(z);e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(Ce,z,e.opts.jsonPointers)),u=e.errSchemaPath+"/required";var Ee=Ee||[];Ee.push(t),t="",e.createErrors!==!1?(t+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+nt+"' } ",e.opts.messages!==!1&&(t+=" , message: '",e.opts._errorDataPathProperty?t+="is a required property":t+="should have required property \\'"+nt+"\\'",t+="' "),e.opts.verbose&&(t+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),t+=" } "):t+=" {} ";var ge=t;t=Ee.pop(),!e.compositeRule&&d?e.async?t+=" throw new ValidationError(["+ge+"]); ":t+=" validate.errors = ["+ge+"]; return false; ":t+=" var err = "+ge+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",u=pt,e.errorPath=Ce,t+=" } else { "}else d?(t+=" if ( "+ke+" === undefined ",A&&(t+=" || ! Object.prototype.hasOwnProperty.call("+f+", '"+e.util.escapeQuotes(z)+"') "),t+=") { "+y+" = true; } else { "):(t+=" if ("+ke+" !== undefined ",A&&(t+=" && Object.prototype.hasOwnProperty.call("+f+", '"+e.util.escapeQuotes(z)+"') "),t+=" ) { ");t+=" "+ce+" } "}}d&&(t+=" if ("+y+") { ",g+="}")}}if(N.length){var Be=N;if(Be)for(var ne,Vr=-1,qs=Be.length-1;Vr<qs;){ne=Be[Vr+=1];var we=T[ne];if(e.opts.strictKeywords?typeof we=="object"&&Object.keys(we).length>0||we===!1:e.util.schemaHasRules(we,e.RULES.all)){p.schema=we,p.schemaPath=e.schemaPath+".patternProperties"+e.util.getProperty(ne),p.errSchemaPath=e.errSchemaPath+"/patternProperties/"+e.util.escapeFragment(ne),A?t+=" "+R+" = "+R+" || Object.keys("+f+"); for (var "+E+"=0; "+E+"<"+R+".length; "+E+"++) { var "+v+" = "+R+"["+E+"]; ":t+=" for (var "+v+" in "+f+") { ",t+=" if ("+e.usePattern(ne)+".test("+v+")) { ",p.errorPath=e.util.getPathExpr(e.errorPath,v,e.opts.jsonPointers);var Ie=f+"["+v+"]";p.dataPathArr[w]=v;var ce=e.validate(p);p.baseId=M,e.util.varOccurences(ce,S)<2?t+=" "+e.util.varReplace(ce,S,Ie)+" ":t+=" var "+S+" = "+Ie+"; "+ce+" ",d&&(t+=" if (!"+y+") break; "),t+=" } ",d&&(t+=" else "+y+" = true; "),t+=" } ",d&&(t+=" if ("+y+") { ",g+="}")}}}return d&&(t+=" "+g+" if ("+m+" == errors) {"),t}});var gi=H((Wm,vi)=>{"use strict";vi.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,f="data"+(o||""),m="errs__"+n,p=e.util.copy(e),g="";p.level++;var y="valid"+p.level;if(t+="var "+m+" = errors;",e.opts.strictKeywords?typeof i=="object"&&Object.keys(i).length>0||i===!1:e.util.schemaHasRules(i,e.RULES.all)){p.schema=i,p.schemaPath=l,p.errSchemaPath=u;var v="key"+n,E="idx"+n,w="i"+n,S="' + "+v+" + '",R=p.dataLevel=e.dataLevel+1,x="data"+R,T="dataProperties"+n,N=e.opts.ownProperties,j=e.baseId;N&&(t+=" var "+T+" = undefined; "),N?t+=" "+T+" = "+T+" || Object.keys("+f+"); for (var "+E+"=0; "+E+"<"+T+".length; "+E+"++) { var "+v+" = "+T+"["+E+"]; ":t+=" for (var "+v+" in "+f+") { ",t+=" var startErrs"+n+" = errors; ";var $=v,D=e.compositeRule;e.compositeRule=p.compositeRule=!0;var C=e.validate(p);p.baseId=j,e.util.varOccurences(C,x)<2?t+=" "+e.util.varReplace(C,x,$)+" ":t+=" var "+x+" = "+$+"; "+C+" ",e.compositeRule=p.compositeRule=D,t+=" if (!"+y+") { for (var "+w+"=startErrs"+n+"; "+w+"<errors; "+w+"++) { vErrors["+w+"].propertyName = "+v+"; } var err = ",e.createErrors!==!1?(t+=" { keyword: 'propertyNames' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { propertyName: '"+S+"' } ",e.opts.messages!==!1&&(t+=" , message: 'property name \\'"+S+"\\' is invalid' "),e.opts.verbose&&(t+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),t+=" } "):t+=" {} ",t+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&d&&(e.async?t+=" throw new ValidationError(vErrors); ":t+=" validate.errors = vErrors; return false; "),d&&(t+=" break; "),t+=" } }"}return d&&(t+=" "+g+" if ("+m+" == errors) {"),t}});var _i=H((Km,yi)=>{"use strict";yi.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,f="data"+(o||""),m="valid"+n,p=e.opts.$data&&i&&i.$data,g;p?(t+=" var schema"+n+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",g="schema"+n):g=i;var y="schema"+n;if(!p)if(i.length<e.opts.loopRequired&&e.schema.properties&&Object.keys(e.schema.properties).length){var v=[],E=i;if(E)for(var w,S=-1,R=E.length-1;S<R;){w=E[S+=1];var x=e.schema.properties[w];x&&(e.opts.strictKeywords?typeof x=="object"&&Object.keys(x).length>0||x===!1:e.util.schemaHasRules(x,e.RULES.all))||(v[v.length]=w)}}else var v=i;if(p||v.length){var T=e.errorPath,N=p||v.length>=e.opts.loopRequired,j=e.opts.ownProperties;if(d)if(t+=" var missing"+n+"; ",N){p||(t+=" var "+y+" = validate.schema"+l+"; ");var $="i"+n,D="schema"+n+"["+$+"]",C="' + "+D+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(T,D,e.opts.jsonPointers)),t+=" var "+m+" = true; ",p&&(t+=" if (schema"+n+" === undefined) "+m+" = true; else if (!Array.isArray(schema"+n+")) "+m+" = false; else {"),t+=" for (var "+$+" = 0; "+$+" < "+y+".length; "+$+"++) { "+m+" = "+f+"["+y+"["+$+"]] !== undefined ",j&&(t+=" && Object.prototype.hasOwnProperty.call("+f+", "+y+"["+$+"]) "),t+="; if (!"+m+") break; } ",p&&(t+=" } "),t+=" if (!"+m+") { ";var F=F||[];F.push(t),t="",e.createErrors!==!1?(t+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+C+"' } ",e.opts.messages!==!1&&(t+=" , message: '",e.opts._errorDataPathProperty?t+="is a required property":t+="should have required property \\'"+C+"\\'",t+="' "),e.opts.verbose&&(t+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),t+=" } "):t+=" {} ";var I=t;t=F.pop(),!e.compositeRule&&d?e.async?t+=" throw new ValidationError(["+I+"]); ":t+=" validate.errors = ["+I+"]; return false; ":t+=" var err = "+I+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+=" } else { "}else{t+=" if ( ";var A=v;if(A)for(var M,$=-1,ee=A.length-1;$<ee;){M=A[$+=1],$&&(t+=" || ");var Q=e.util.getProperty(M),Y=f+Q;t+=" ( ( "+Y+" === undefined ",j&&(t+=" || ! Object.prototype.hasOwnProperty.call("+f+", '"+e.util.escapeQuotes(M)+"') "),t+=") && (missing"+n+" = "+e.util.toQuotedString(e.opts.jsonPointers?M:Q)+") ) "}t+=") { ";var D="missing"+n,C="' + "+D+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.opts.jsonPointers?e.util.getPathExpr(T,D,!0):T+" + "+D);var F=F||[];F.push(t),t="",e.createErrors!==!1?(t+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+C+"' } ",e.opts.messages!==!1&&(t+=" , message: '",e.opts._errorDataPathProperty?t+="is a required property":t+="should have required property \\'"+C+"\\'",t+="' "),e.opts.verbose&&(t+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),t+=" } "):t+=" {} ";var I=t;t=F.pop(),!e.compositeRule&&d?e.async?t+=" throw new ValidationError(["+I+"]); ":t+=" validate.errors = ["+I+"]; return false; ":t+=" var err = "+I+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+=" } else { "}else if(N){p||(t+=" var "+y+" = validate.schema"+l+"; ");var $="i"+n,D="schema"+n+"["+$+"]",C="' + "+D+" + '";e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPathExpr(T,D,e.opts.jsonPointers)),p&&(t+=" if ("+y+" && !Array.isArray("+y+")) { var err = ",e.createErrors!==!1?(t+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+C+"' } ",e.opts.messages!==!1&&(t+=" , message: '",e.opts._errorDataPathProperty?t+="is a required property":t+="should have required property \\'"+C+"\\'",t+="' "),e.opts.verbose&&(t+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),t+=" } "):t+=" {} ",t+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } else if ("+y+" !== undefined) { "),t+=" for (var "+$+" = 0; "+$+" < "+y+".length; "+$+"++) { if ("+f+"["+y+"["+$+"]] === undefined ",j&&(t+=" || ! Object.prototype.hasOwnProperty.call("+f+", "+y+"["+$+"]) "),t+=") { var err = ",e.createErrors!==!1?(t+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+C+"' } ",e.opts.messages!==!1&&(t+=" , message: '",e.opts._errorDataPathProperty?t+="is a required property":t+="should have required property \\'"+C+"\\'",t+="' "),e.opts.verbose&&(t+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),t+=" } "):t+=" {} ",t+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } } ",p&&(t+=" } ")}else{var X=v;if(X)for(var M,z=-1,pe=X.length-1;z<pe;){M=X[z+=1];var Q=e.util.getProperty(M),C=e.util.escapeQuotes(M),Y=f+Q;e.opts._errorDataPathProperty&&(e.errorPath=e.util.getPath(T,M,e.opts.jsonPointers)),t+=" if ( "+Y+" === undefined ",j&&(t+=" || ! Object.prototype.hasOwnProperty.call("+f+", '"+e.util.escapeQuotes(M)+"') "),t+=") { var err = ",e.createErrors!==!1?(t+=" { keyword: 'required' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { missingProperty: '"+C+"' } ",e.opts.messages!==!1&&(t+=" , message: '",e.opts._errorDataPathProperty?t+="is a required property":t+="should have required property \\'"+C+"\\'",t+="' "),e.opts.verbose&&(t+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),t+=" } "):t+=" {} ",t+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; } "}}e.errorPath=T}else d&&(t+=" if (true) {");return t}});var Ei=H((Jm,bi)=>{"use strict";bi.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,f="data"+(o||""),m="valid"+n,p=e.opts.$data&&i&&i.$data,g;if(p?(t+=" var schema"+n+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",g="schema"+n):g=i,(i||p)&&e.opts.uniqueItems!==!1){p&&(t+=" var "+m+"; if ("+g+" === false || "+g+" === undefined) "+m+" = true; else if (typeof "+g+" != 'boolean') "+m+" = false; else { "),t+=" var i = "+f+".length , "+m+" = true , j; if (i > 1) { ";var y=e.schema.items&&e.schema.items.type,v=Array.isArray(y);if(!y||y=="object"||y=="array"||v&&(y.indexOf("object")>=0||y.indexOf("array")>=0))t+=" outer: for (;i--;) { for (j = i; j--;) { if (equal("+f+"[i], "+f+"[j])) { "+m+" = false; break outer; } } } ";else{t+=" var itemIndices = {}, item; for (;i--;) { var item = "+f+"[i]; ";var E="checkDataType"+(v?"s":"");t+=" if ("+e.util[E](y,"item",e.opts.strictNumbers,!0)+") continue; ",v&&(t+=` if (typeof item == 'string') item = '"' + item; `),t+=" if (typeof itemIndices[item] == 'number') { "+m+" = false; j = itemIndices[item]; break; } itemIndices[item] = i; } "}t+=" } ",p&&(t+=" } "),t+=" if (!"+m+") { ";var w=w||[];w.push(t),t="",e.createErrors!==!1?(t+=" { keyword: 'uniqueItems' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { i: i, j: j } ",e.opts.messages!==!1&&(t+=" , message: 'should NOT have duplicate items (items ## ' + j + ' and ' + i + ' are identical)' "),e.opts.verbose&&(t+=" , schema: ",p?t+="validate.schema"+l:t+=""+i,t+=" , parentSchema: validate.schema"+e.schemaPath+" , data: "+f+" "),t+=" } "):t+=" {} ";var S=t;t=w.pop(),!e.compositeRule&&d?e.async?t+=" throw new ValidationError(["+S+"]); ":t+=" validate.errors = ["+S+"]; return false; ":t+=" var err = "+S+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",t+=" } ",d&&(t+=" else { ")}else d&&(t+=" if (true) { ");return t}});var xi=H((Ym,Si)=>{"use strict";Si.exports={$ref:ko(),allOf:jo(),anyOf:Mo(),$comment:Uo(),const:Vo(),contains:zo(),dependencies:Go(),enum:Qo(),format:Ko(),if:Yo(),items:ti(),maximum:Aa(),minimum:Aa(),maxItems:Na(),minItems:Na(),maxLength:Da(),minLength:Da(),maxProperties:Ca(),minProperties:Ca(),multipleOf:ii(),not:li(),oneOf:di(),pattern:fi(),properties:mi(),propertyNames:gi(),required:_i(),uniqueItems:Ei(),validate:Ia()}});var wi=H((ev,Ti)=>{"use strict";var Ri=xi(),ka=rr().toHash;Ti.exports=function(){var e=[{type:"number",rules:[{maximum:["exclusiveMaximum"]},{minimum:["exclusiveMinimum"]},"multipleOf","format"]},{type:"string",rules:["maxLength","minLength","pattern","format"]},{type:"array",rules:["maxItems","minItems","items","contains","uniqueItems"]},{type:"object",rules:["maxProperties","minProperties","required","dependencies","propertyNames",{properties:["additionalProperties","patternProperties"]}]},{rules:["$ref","const","enum","not","anyOf","oneOf","allOf","if"]}],r=["type","$comment"],a=["$schema","$id","id","$data","$async","title","description","default","definitions","examples","readOnly","writeOnly","contentMediaType","contentEncoding","additionalItems","then","else"],t=["number","integer","string","array","object","boolean","null"];return e.all=ka(r),e.types=ka(t),e.forEach(function(n){n.rules=n.rules.map(function(o){var i;if(typeof o=="object"){var l=Object.keys(o)[0];i=o[l],o=l,i.forEach(function(d){r.push(d),e.all[d]=!0})}r.push(o);var u=e.all[o]={keyword:o,code:Ri[o],implements:i};return u}),e.all.$comment={keyword:"$comment",code:Ri.$comment},n.type&&(e.types[n.type]=n)}),e.keywords=ka(r.concat(a)),e.custom={},e}});var Ii=H((tv,Oi)=>{"use strict";var Pi=["multipleOf","maximum","exclusiveMaximum","minimum","exclusiveMinimum","maxLength","minLength","pattern","additionalItems","maxItems","minItems","uniqueItems","maxProperties","minProperties","required","additionalProperties","enum","format","const"];Oi.exports=function(s,e){for(var r=0;r<e.length;r++){s=JSON.parse(JSON.stringify(s));var a=e[r].split("/"),t=s,n;for(n=1;n<a.length;n++)t=t[a[n]];for(n=0;n<Pi.length;n++){var o=Pi[n],i=t[o];i&&(t[o]={anyOf:[i,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]})}}return s}});var Ni=H((rv,Ai)=>{"use strict";var Jp=gs().MissingRef;Ai.exports=$i;function $i(s,e,r){var a=this;if(typeof this._opts.loadSchema!="function")throw new Error("options.loadSchema should be a function");typeof e=="function"&&(r=e,e=void 0);var t=n(s).then(function(){var i=a._addSchema(s,void 0,e);return i.validate||o(i)});return r&&t.then(function(i){r(null,i)},r),t;function n(i){var l=i.$schema;return l&&!a.getSchema(l)?$i.call(a,{$ref:l},!0):Promise.resolve()}function o(i){try{return a._compile(i)}catch(u){if(u instanceof Jp)return l(u);throw u}function l(u){var d=u.missingSchema;if(p(d))throw new Error("Schema "+d+" is loaded but "+u.missingRef+" cannot be resolved");var f=a._loadingSchemas[d];return f||(f=a._loadingSchemas[d]=a._opts.loadSchema(d),f.then(m,m)),f.then(function(g){if(!p(d))return n(g).then(function(){p(d)||a.addSchema(g,d,void 0,e)})}).then(function(){return o(i)});function m(){delete a._loadingSchemas[d]}function p(g){return a._refs[g]||a._schemas[g]}}}}});var Ci=H((sv,Di)=>{"use strict";Di.exports=function(e,r,a){var t=" ",n=e.level,o=e.dataLevel,i=e.schema[r],l=e.schemaPath+e.util.getProperty(r),u=e.errSchemaPath+"/"+r,d=!e.opts.allErrors,f,m="data"+(o||""),p="valid"+n,g="errs__"+n,y=e.opts.$data&&i&&i.$data,v;y?(t+=" var schema"+n+" = "+e.util.getData(i.$data,o,e.dataPathArr)+"; ",v="schema"+n):v=i;var E=this,w="definition"+n,S=E.definition,R="",x,T,N,j,$;if(y&&S.$data){$="keywordValidate"+n;var D=S.validateSchema;t+=" var "+w+" = RULES.custom['"+r+"'].definition; var "+$+" = "+w+".validate;"}else{if(j=e.useCustomRule(E,i,e.schema,e),!j)return;v="validate.schema"+l,$=j.code,x=S.compile,T=S.inline,N=S.macro}var C=$+".errors",F="i"+n,I="ruleErr"+n,A=S.async;if(A&&!e.async)throw new Error("async keyword in sync schema");if(T||N||(t+=""+C+" = null;"),t+="var "+g+" = errors;var "+p+";",y&&S.$data&&(R+="}",t+=" if ("+v+" === undefined) { "+p+" = true; } else { ",D&&(R+="}",t+=" "+p+" = "+w+".validateSchema("+v+"); if ("+p+") { ")),T)S.statements?t+=" "+j.validate+" ":t+=" "+p+" = "+j.validate+"; ";else if(N){var M=e.util.copy(e),R="";M.level++;var ee="valid"+M.level;M.schema=j.validate,M.schemaPath="";var Q=e.compositeRule;e.compositeRule=M.compositeRule=!0;var Y=e.validate(M).replace(/validate\.schema/g,$);e.compositeRule=M.compositeRule=Q,t+=" "+Y}else{var X=X||[];X.push(t),t="",t+=" "+$+".call( ",e.opts.passContext?t+="this":t+="self",x||S.schema===!1?t+=" , "+m+" ":t+=" , "+v+" , "+m+" , validate.schema"+e.schemaPath+" ",t+=" , (dataPath || '')",e.errorPath!='""'&&(t+=" + "+e.errorPath);var z=o?"data"+(o-1||""):"parentData",pe=o?e.dataPathArr[o]:"parentDataProperty";t+=" , "+z+" , "+pe+" , rootData ) ";var Oe=t;t=X.pop(),S.errors===!1?(t+=" "+p+" = ",A&&(t+="await "),t+=""+Oe+"; "):A?(C="customErrors"+n,t+=" var "+C+" = null; try { "+p+" = await "+Oe+"; } catch (e) { "+p+" = false; if (e instanceof ValidationError) "+C+" = e.errors; else throw e; } "):t+=" "+C+" = null; "+p+" = "+Oe+"; "}if(S.modifying&&(t+=" if ("+z+") "+m+" = "+z+"["+pe+"];"),t+=""+R,S.valid)d&&(t+=" if (true) { ");else{t+=" if ( ",S.valid===void 0?(t+=" !",N?t+=""+ee:t+=""+p):t+=" "+!S.valid+" ",t+=") { ",f=E.keyword;var X=X||[];X.push(t),t="";var X=X||[];X.push(t),t="",e.createErrors!==!1?(t+=" { keyword: '"+(f||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { keyword: '"+E.keyword+"' } ",e.opts.messages!==!1&&(t+=` , message: 'should pass "`+E.keyword+`" keyword validation' `),e.opts.verbose&&(t+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),t+=" } "):t+=" {} ";var De=t;t=X.pop(),!e.compositeRule&&d?e.async?t+=" throw new ValidationError(["+De+"]); ":t+=" validate.errors = ["+De+"]; return false; ":t+=" var err = "+De+"; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ";var ne=t;t=X.pop(),T?S.errors?S.errors!="full"&&(t+=" for (var "+F+"="+g+"; "+F+"<errors; "+F+"++) { var "+I+" = vErrors["+F+"]; if ("+I+".dataPath === undefined) "+I+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+I+".schemaPath === undefined) { "+I+'.schemaPath = "'+u+'"; } ',e.opts.verbose&&(t+=" "+I+".schema = "+v+"; "+I+".data = "+m+"; "),t+=" } "):S.errors===!1?t+=" "+ne+" ":(t+=" if ("+g+" == errors) { "+ne+" } else { for (var "+F+"="+g+"; "+F+"<errors; "+F+"++) { var "+I+" = vErrors["+F+"]; if ("+I+".dataPath === undefined) "+I+".dataPath = (dataPath || '') + "+e.errorPath+"; if ("+I+".schemaPath === undefined) { "+I+'.schemaPath = "'+u+'"; } ',e.opts.verbose&&(t+=" "+I+".schema = "+v+"; "+I+".data = "+m+"; "),t+=" } } "):N?(t+=" var err = ",e.createErrors!==!1?(t+=" { keyword: '"+(f||"custom")+"' , dataPath: (dataPath || '') + "+e.errorPath+" , schemaPath: "+e.util.toQuotedString(u)+" , params: { keyword: '"+E.keyword+"' } ",e.opts.messages!==!1&&(t+=` , message: 'should pass "`+E.keyword+`" keyword validation' `),e.opts.verbose&&(t+=" , schema: validate.schema"+l+" , parentSchema: validate.schema"+e.schemaPath+" , data: "+m+" "),t+=" } "):t+=" {} ",t+="; if (vErrors === null) vErrors = [err]; else vErrors.push(err); errors++; ",!e.compositeRule&&d&&(e.async?t+=" throw new ValidationError(vErrors); ":t+=" validate.errors = vErrors; return false; ")):S.errors===!1?t+=" "+ne+" ":(t+=" if (Array.isArray("+C+")) { if (vErrors === null) vErrors = "+C+"; else vErrors = vErrors.concat("+C+"); errors = vErrors.length; for (var "+F+"="+g+"; "+F+"<errors; "+F+"++) { var "+I+" = vErrors["+F+"]; if ("+I+".dataPath === undefined) "+I+".dataPath = (dataPath || '') + "+e.errorPath+"; "+I+'.schemaPath = "'+u+'"; ',e.opts.verbose&&(t+=" "+I+".schema = "+v+"; "+I+".data = "+m+"; "),t+=" } } else { "+ne+" } "),t+=" } ",d&&(t+=" else { ")}return t}});var La=H((av,Yp)=>{Yp.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}});var ji=H((nv,Li)=>{"use strict";var ki=La();Li.exports={$id:"https://github.com/ajv-validator/ajv/blob/master/lib/definition_schema.js",definitions:{simpleTypes:ki.definitions.simpleTypes},type:"object",dependencies:{schema:["validate"],$data:["validate"],statements:["inline"],valid:{not:{required:["macro"]}}},properties:{type:ki.properties.type,schema:{type:"boolean"},statements:{type:"boolean"},dependencies:{type:"array",items:{type:"string"}},metaSchema:{type:"object"},modifying:{type:"boolean"},valid:{type:"boolean"},$data:{type:"boolean"},async:{type:"boolean"},errors:{anyOf:[{type:"boolean"},{const:"full"}]}}}});var Mi=H((ov,Fi)=>{"use strict";var ef=/^[a-z_$][a-z0-9_$-]*$/i,tf=Ci(),rf=ji();Fi.exports={add:sf,get:af,remove:nf,validate:ja};function sf(s,e){var r=this.RULES;if(r.keywords[s])throw new Error("Keyword "+s+" is already defined");if(!ef.test(s))throw new Error("Keyword "+s+" is not a valid identifier");if(e){this.validateKeyword(e,!0);var a=e.type;if(Array.isArray(a))for(var t=0;t<a.length;t++)o(s,a[t],e);else o(s,a,e);var n=e.metaSchema;n&&(e.$data&&this._opts.$data&&(n={anyOf:[n,{$ref:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#"}]}),e.validateSchema=this.compile(n,!0))}r.keywords[s]=r.all[s]=!0;function o(i,l,u){for(var d,f=0;f<r.length;f++){var m=r[f];if(m.type==l){d=m;break}}d||(d={type:l,rules:[]},r.push(d));var p={keyword:i,definition:u,custom:!0,code:tf,implements:u.implements};d.rules.push(p),r.custom[i]=p}return this}function af(s){var e=this.RULES.custom[s];return e?e.definition:this.RULES.keywords[s]||!1}function nf(s){var e=this.RULES;delete e.keywords[s],delete e.all[s],delete e.custom[s];for(var r=0;r<e.length;r++)for(var a=e[r].rules,t=0;t<a.length;t++)if(a[t].keyword==s){a.splice(t,1);break}return this}function ja(s,e){ja.errors=null;var r=this._validateKeyword=this._validateKeyword||this.compile(rf,!0);if(r(s))return!0;if(ja.errors=r.errors,e)throw new Error("custom keyword definition is invalid: "+this.errorsText(r.errors));return!1}});var qi=H((iv,of)=>{of.exports={$schema:"http://json-schema.org/draft-07/schema#",$id:"https://raw.githubusercontent.com/ajv-validator/ajv/master/lib/refs/data.json#",description:"Meta-schema for $data reference (JSON Schema extension proposal)",type:"object",required:["$data"],properties:{$data:{type:"string",anyOf:[{format:"relative-json-pointer"},{format:"json-pointer"}]}},additionalProperties:!1}});var Ma=H((cv,Qi)=>{"use strict";var Bi=_o(),sr=vs(),cf=Eo(),Vi=Sa(),lf=Oa(),uf=Do(),df=wi(),Hi=Ii(),zi=rr();Qi.exports=ye;ye.prototype.validate=ff;ye.prototype.compile=hf;ye.prototype.addSchema=mf;ye.prototype.addMetaSchema=vf;ye.prototype.validateSchema=gf;ye.prototype.getSchema=_f;ye.prototype.removeSchema=Ef;ye.prototype.addFormat=If;ye.prototype.errorsText=Of;ye.prototype._addSchema=Sf;ye.prototype._compile=xf;ye.prototype.compileAsync=Ni();var Ts=Mi();ye.prototype.addKeyword=Ts.add;ye.prototype.getKeyword=Ts.get;ye.prototype.removeKeyword=Ts.remove;ye.prototype.validateKeyword=Ts.validate;var Zi=gs();ye.ValidationError=Zi.Validation;ye.MissingRefError=Zi.MissingRef;ye.$dataMetaSchema=Hi;var Rs="http://json-schema.org/draft-07/schema",Ui=["removeAdditional","useDefaults","coerceTypes","strictDefaults"],pf=["/properties"];function ye(s){if(!(this instanceof ye))return new ye(s);s=this._opts=zi.copy(s)||{},kf(this),this._schemas={},this._refs={},this._fragments={},this._formats=uf(s.format),this._cache=s.cache||new cf,this._loadingSchemas={},this._compilations=[],this.RULES=df(),this._getId=Rf(s),s.loopRequired=s.loopRequired||1/0,s.errorDataPath=="property"&&(s._errorDataPathProperty=!0),s.serialize===void 0&&(s.serialize=lf),this._metaOpts=Cf(this),s.formats&&Nf(this),s.keywords&&Df(this),$f(this),typeof s.meta=="object"&&this.addMetaSchema(s.meta),s.nullable&&this.addKeyword("nullable",{metaSchema:{type:"boolean"}}),Af(this)}function ff(s,e){var r;if(typeof s=="string"){if(r=this.getSchema(s),!r)throw new Error('no schema with key or ref "'+s+'"')}else{var a=this._addSchema(s);r=a.validate||this._compile(a)}var t=r(e);return r.$async!==!0&&(this.errors=r.errors),t}function hf(s,e){var r=this._addSchema(s,void 0,e);return r.validate||this._compile(r)}function mf(s,e,r,a){if(Array.isArray(s)){for(var t=0;t<s.length;t++)this.addSchema(s[t],void 0,r,a);return this}var n=this._getId(s);if(n!==void 0&&typeof n!="string")throw new Error("schema id must be string");return e=sr.normalizeId(e||n),Xi(this,e),this._schemas[e]=this._addSchema(s,r,a,!0),this}function vf(s,e,r){return this.addSchema(s,e,r,!0),this}function gf(s,e){var r=s.$schema;if(r!==void 0&&typeof r!="string")throw new Error("$schema must be a string");if(r=r||this._opts.defaultMeta||yf(this),!r)return this.logger.warn("meta-schema not available"),this.errors=null,!0;var a=this.validate(r,s);if(!a&&e){var t="schema is invalid: "+this.errorsText();if(this._opts.validateSchema=="log")this.logger.error(t);else throw new Error(t)}return a}function yf(s){var e=s._opts.meta;return s._opts.defaultMeta=typeof e=="object"?s._getId(e)||e:s.getSchema(Rs)?Rs:void 0,s._opts.defaultMeta}function _f(s){var e=Gi(this,s);switch(typeof e){case"object":return e.validate||this._compile(e);case"string":return this.getSchema(e);case"undefined":return bf(this,s)}}function bf(s,e){var r=sr.schema.call(s,{schema:{}},e);if(r){var a=r.schema,t=r.root,n=r.baseId,o=Bi.call(s,a,t,void 0,n);return s._fragments[e]=new Vi({ref:e,fragment:!0,schema:a,root:t,baseId:n,validate:o}),o}}function Gi(s,e){return e=sr.normalizeId(e),s._schemas[e]||s._refs[e]||s._fragments[e]}function Ef(s){if(s instanceof RegExp)return xs(this,this._schemas,s),xs(this,this._refs,s),this;switch(typeof s){case"undefined":return xs(this,this._schemas),xs(this,this._refs),this._cache.clear(),this;case"string":var e=Gi(this,s);return e&&this._cache.del(e.cacheKey),delete this._schemas[s],delete this._refs[s],this;case"object":var r=this._opts.serialize,a=r?r(s):s;this._cache.del(a);var t=this._getId(s);t&&(t=sr.normalizeId(t),delete this._schemas[t],delete this._refs[t])}return this}function xs(s,e,r){for(var a in e){var t=e[a];!t.meta&&(!r||r.test(a))&&(s._cache.del(t.cacheKey),delete e[a])}}function Sf(s,e,r,a){if(typeof s!="object"&&typeof s!="boolean")throw new Error("schema should be object or boolean");var t=this._opts.serialize,n=t?t(s):s,o=this._cache.get(n);if(o)return o;a=a||this._opts.addUsedSchema!==!1;var i=sr.normalizeId(this._getId(s));i&&a&&Xi(this,i);var l=this._opts.validateSchema!==!1&&!e,u;l&&!(u=i&&i==sr.normalizeId(s.$schema))&&this.validateSchema(s,!0);var d=sr.ids.call(this,s),f=new Vi({id:i,schema:s,localRefs:d,cacheKey:n,meta:r});return i[0]!="#"&&a&&(this._refs[i]=f),this._cache.put(n,f),l&&u&&this.validateSchema(s,!0),f}function xf(s,e){if(s.compiling)return s.validate=t,t.schema=s.schema,t.errors=null,t.root=e||t,s.schema.$async===!0&&(t.$async=!0),t;s.compiling=!0;var r;s.meta&&(r=this._opts,this._opts=this._metaOpts);var a;try{a=Bi.call(this,s.schema,e,s.localRefs)}catch(n){throw delete s.validate,n}finally{s.compiling=!1,s.meta&&(this._opts=r)}return s.validate=a,s.refs=a.refs,s.refVal=a.refVal,s.root=a.root,a;function t(){var n=s.validate,o=n.apply(this,arguments);return t.errors=n.errors,o}}function Rf(s){switch(s.schemaId){case"auto":return Pf;case"id":return Tf;default:return wf}}function Tf(s){return s.$id&&this.logger.warn("schema $id ignored",s.$id),s.id}function wf(s){return s.id&&this.logger.warn("schema id ignored",s.id),s.$id}function Pf(s){if(s.$id&&s.id&&s.$id!=s.id)throw new Error("schema $id is different from id");return s.$id||s.id}function Of(s,e){if(s=s||this.errors,!s)return"No errors";e=e||{};for(var r=e.separator===void 0?", ":e.separator,a=e.dataVar===void 0?"data":e.dataVar,t="",n=0;n<s.length;n++){var o=s[n];o&&(t+=a+o.dataPath+" "+o.message+r)}return t.slice(0,-r.length)}function If(s,e){return typeof e=="string"&&(e=new RegExp(e)),this._formats[s]=e,this}function $f(s){var e;if(s._opts.$data&&(e=qi(),s.addMetaSchema(e,e.$id,!0)),s._opts.meta!==!1){var r=La();s._opts.$data&&(r=Hi(r,pf)),s.addMetaSchema(r,Rs,!0),s._refs["http://json-schema.org/schema"]=Rs}}function Af(s){var e=s._opts.schemas;if(e)if(Array.isArray(e))s.addSchema(e);else for(var r in e)s.addSchema(e[r],r)}function Nf(s){for(var e in s._opts.formats){var r=s._opts.formats[e];s.addFormat(e,r)}}function Df(s){for(var e in s._opts.keywords){var r=s._opts.keywords[e];s.addKeyword(e,r)}}function Xi(s,e){if(s._schemas[e]||s._refs[e])throw new Error('schema with key or id "'+e+'" already exists')}function Cf(s){for(var e=zi.copy(s._opts),r=0;r<Ui.length;r++)delete e[Ui[r]];return e}function kf(s){var e=s._opts.logger;if(e===!1)s.logger={log:Fa,warn:Fa,error:Fa};else{if(e===void 0&&(e=console),!(typeof e=="object"&&e.log&&e.warn&&e.error))throw new Error("logger must implement log, warn and error methods");s.logger=e}}function Fa(){}});var rc=H((_v,tc)=>{tc.exports=ec;ec.sync=Ff;var Ji=require("fs");function jf(s,e){var r=e.pathExt!==void 0?e.pathExt:process.env.PATHEXT;if(!r||(r=r.split(";"),r.indexOf("")!==-1))return!0;for(var a=0;a<r.length;a++){var t=r[a].toLowerCase();if(t&&s.substr(-t.length).toLowerCase()===t)return!0}return!1}function Yi(s,e,r){return!s.isSymbolicLink()&&!s.isFile()?!1:jf(e,r)}function ec(s,e,r){Ji.stat(s,function(a,t){r(a,a?!1:Yi(t,s,e))})}function Ff(s,e){return Yi(Ji.statSync(s),s,e)}});var ic=H((bv,oc)=>{oc.exports=ac;ac.sync=Mf;var sc=require("fs");function ac(s,e,r){sc.stat(s,function(a,t){r(a,a?!1:nc(t,e))})}function Mf(s,e){return nc(sc.statSync(s),e)}function nc(s,e){return s.isFile()&&qf(s,e)}function qf(s,e){var r=s.mode,a=s.uid,t=s.gid,n=e.uid!==void 0?e.uid:process.getuid&&process.getuid(),o=e.gid!==void 0?e.gid:process.getgid&&process.getgid(),i=parseInt("100",8),l=parseInt("010",8),u=parseInt("001",8),d=i|l,f=r&u||r&l&&t===o||r&i&&a===n||r&d&&n===0;return f}});var lc=H((Sv,cc)=>{var Ev=require("fs"),$s;process.platform==="win32"||global.TESTING_WINDOWS?$s=rc():$s=ic();cc.exports=Ua;Ua.sync=Uf;function Ua(s,e,r){if(typeof e=="function"&&(r=e,e={}),!r){if(typeof Promise!="function")throw new TypeError("callback not provided");return new Promise(function(a,t){Ua(s,e||{},function(n,o){n?t(n):a(o)})})}$s(s,e||{},function(a,t){a&&(a.code==="EACCES"||e&&e.ignoreErrors)&&(a=null,t=!1),r(a,t)})}function Uf(s,e){try{return $s.sync(s,e||{})}catch(r){if(e&&e.ignoreErrors||r.code==="EACCES")return!1;throw r}}});var vc=H((xv,mc)=>{var Sr=process.platform==="win32"||process.env.OSTYPE==="cygwin"||process.env.OSTYPE==="msys",uc=require("path"),Bf=Sr?";":":",dc=lc(),pc=s=>Object.assign(new Error(`not found: ${s}`),{code:"ENOENT"}),fc=(s,e)=>{let r=e.colon||Bf,a=s.match(/\//)||Sr&&s.match(/\\/)?[""]:[...Sr?[process.cwd()]:[],...(e.path||process.env.PATH||"").split(r)],t=Sr?e.pathExt||process.env.PATHEXT||".EXE;.CMD;.BAT;.COM":"",n=Sr?t.split(r):[""];return Sr&&s.indexOf(".")!==-1&&n[0]!==""&&n.unshift(""),{pathEnv:a,pathExt:n,pathExtExe:t}},hc=(s,e,r)=>{typeof e=="function"&&(r=e,e={}),e||(e={});let{pathEnv:a,pathExt:t,pathExtExe:n}=fc(s,e),o=[],i=u=>new Promise((d,f)=>{if(u===a.length)return e.all&&o.length?d(o):f(pc(s));let m=a[u],p=/^".*"$/.test(m)?m.slice(1,-1):m,g=uc.join(p,s),y=!p&&/^\.[\\\/]/.test(s)?s.slice(0,2)+g:g;d(l(y,u,0))}),l=(u,d,f)=>new Promise((m,p)=>{if(f===t.length)return m(i(d+1));let g=t[f];dc(u+g,{pathExt:n},(y,v)=>{if(!y&&v)if(e.all)o.push(u+g);else return m(u+g);return m(l(u,d,f+1))})});return r?i(0).then(u=>r(null,u),r):i(0)},Vf=(s,e)=>{e=e||{};let{pathEnv:r,pathExt:a,pathExtExe:t}=fc(s,e),n=[];for(let o=0;o<r.length;o++){let i=r[o],l=/^".*"$/.test(i)?i.slice(1,-1):i,u=uc.join(l,s),d=!l&&/^\.[\\\/]/.test(s)?s.slice(0,2)+u:u;for(let f=0;f<a.length;f++){let m=d+a[f];try{if(dc.sync(m,{pathExt:t}))if(e.all)n.push(m);else return m}catch{}}}if(e.all&&n.length)return n;if(e.nothrow)return null;throw pc(s)};mc.exports=hc;hc.sync=Vf});var yc=H((Rv,Ba)=>{"use strict";var gc=(s={})=>{let e=s.env||process.env;return(s.platform||process.platform)!=="win32"?"PATH":Object.keys(e).reverse().find(a=>a.toUpperCase()==="PATH")||"Path"};Ba.exports=gc;Ba.exports.default=gc});var Sc=H((Tv,Ec)=>{"use strict";var _c=require("path"),Hf=vc(),zf=yc();function bc(s,e){let r=s.options.env||process.env,a=process.cwd(),t=s.options.cwd!=null,n=t&&process.chdir!==void 0&&!process.chdir.disabled;if(n)try{process.chdir(s.options.cwd)}catch{}let o;try{o=Hf.sync(s.command,{path:r[zf({env:r})],pathExt:e?_c.delimiter:void 0})}catch{}finally{n&&process.chdir(a)}return o&&(o=_c.resolve(t?s.options.cwd:"",o)),o}function Zf(s){return bc(s)||bc(s,!0)}Ec.exports=Zf});var xc=H((wv,Ha)=>{"use strict";var Va=/([()\][%!^"`<>&|;, *?])/g;function Gf(s){return s=s.replace(Va,"^$1"),s}function Xf(s,e){return s=`${s}`,s=s.replace(/(?=(\\+?)?)\1"/g,'$1$1\\"'),s=s.replace(/(?=(\\+?)?)\1$/,"$1$1"),s=`"${s}"`,s=s.replace(Va,"^$1"),e&&(s=s.replace(Va,"^$1")),s}Ha.exports.command=Gf;Ha.exports.argument=Xf});var Tc=H((Pv,Rc)=>{"use strict";Rc.exports=/^#!(.*)/});var Pc=H((Ov,wc)=>{"use strict";var Qf=Tc();wc.exports=(s="")=>{let e=s.match(Qf);if(!e)return null;let[r,a]=e[0].replace(/#! ?/,"").split(" "),t=r.split("/").pop();return t==="env"?a:a?`${t} ${a}`:t}});var Ic=H((Iv,Oc)=>{"use strict";var za=require("fs"),Wf=Pc();function Kf(s){let r=Buffer.alloc(150),a;try{a=za.openSync(s,"r"),za.readSync(a,r,0,150,0),za.closeSync(a)}catch{}return Wf(r.toString())}Oc.exports=Kf});var Dc=H(($v,Nc)=>{"use strict";var Jf=require("path"),$c=Sc(),Ac=xc(),Yf=Ic(),eh=process.platform==="win32",th=/\.(?:com|exe)$/i,rh=/node_modules[\\/].bin[\\/][^\\/]+\.cmd$/i;function sh(s){s.file=$c(s);let e=s.file&&Yf(s.file);return e?(s.args.unshift(s.file),s.command=e,$c(s)):s.file}function ah(s){if(!eh)return s;let e=sh(s),r=!th.test(e);if(s.options.forceShell||r){let a=rh.test(e);s.command=Jf.normalize(s.command),s.command=Ac.command(s.command),s.args=s.args.map(n=>Ac.argument(n,a));let t=[s.command].concat(s.args).join(" ");s.args=["/d","/s","/c",`"${t}"`],s.command=process.env.comspec||"cmd.exe",s.options.windowsVerbatimArguments=!0}return s}function nh(s,e,r){e&&!Array.isArray(e)&&(r=e,e=null),e=e?e.slice(0):[],r=Object.assign({},r);let a={command:s,args:e,options:r,file:void 0,original:{command:s,args:e}};return r.shell?a:ah(a)}Nc.exports=nh});var Lc=H((Av,kc)=>{"use strict";var Za=process.platform==="win32";function Ga(s,e){return Object.assign(new Error(`${e} ${s.command} ENOENT`),{code:"ENOENT",errno:"ENOENT",syscall:`${e} ${s.command}`,path:s.command,spawnargs:s.args})}function oh(s,e){if(!Za)return;let r=s.emit;s.emit=function(a,t){if(a==="exit"){let n=Cc(t,e);if(n)return r.call(s,"error",n)}return r.apply(s,arguments)}}function Cc(s,e){return Za&&s===1&&!e.file?Ga(e.original,"spawn"):null}function ih(s,e){return Za&&s===1&&!e.file?Ga(e.original,"spawnSync"):null}kc.exports={hookChildProcess:oh,verifyENOENT:Cc,verifyENOENTSync:ih,notFoundError:Ga}});var Mc=H((Nv,xr)=>{"use strict";var jc=require("child_process"),Xa=Dc(),Qa=Lc();function Fc(s,e,r){let a=Xa(s,e,r),t=jc.spawn(a.command,a.args,a.options);return Qa.hookChildProcess(t,a),t}function ch(s,e,r){let a=Xa(s,e,r),t=jc.spawnSync(a.command,a.args,a.options);return t.error=t.error||Qa.verifyENOENTSync(t.status,a),t}xr.exports=Fc;xr.exports.spawn=Fc;xr.exports.sync=ch;xr.exports._parse=Xa;xr.exports._enoent=Qa});var c={};su(c,{BRAND:()=>$u,DIRTY:()=>qt,EMPTY_PATH:()=>cu,INVALID:()=>Z,NEVER:()=>hd,OK:()=>$e,ParseStatus:()=>Pe,Schema:()=>J,ZodAny:()=>wt,ZodArray:()=>bt,ZodBigInt:()=>Bt,ZodBoolean:()=>Vt,ZodBranded:()=>Nr,ZodCatch:()=>er,ZodDate:()=>Ht,ZodDefault:()=>Yt,ZodDiscriminatedUnion:()=>Qr,ZodEffects:()=>We,ZodEnum:()=>Kt,ZodError:()=>Me,ZodFirstPartyTypeKind:()=>L,ZodFunction:()=>Kr,ZodIntersection:()=>Xt,ZodIssueCode:()=>k,ZodLazy:()=>Qt,ZodLiteral:()=>Wt,ZodMap:()=>gr,ZodNaN:()=>_r,ZodNativeEnum:()=>Jt,ZodNever:()=>tt,ZodNull:()=>Zt,ZodNullable:()=>ut,ZodNumber:()=>Ut,ZodObject:()=>qe,ZodOptional:()=>Xe,ZodParsedType:()=>U,ZodPipeline:()=>Dr,ZodPromise:()=>Pt,ZodReadonly:()=>tr,ZodRecord:()=>Wr,ZodSchema:()=>J,ZodSet:()=>yr,ZodString:()=>Tt,ZodSymbol:()=>mr,ZodTransformer:()=>We,ZodTuple:()=>lt,ZodType:()=>J,ZodUndefined:()=>zt,ZodUnion:()=>Gt,ZodUnknown:()=>_t,ZodVoid:()=>vr,addIssueToContext:()=>q,any:()=>Mu,array:()=>Vu,bigint:()=>Cu,boolean:()=>Nn,coerce:()=>fd,custom:()=>In,date:()=>ku,datetimeRegex:()=>Pn,defaultErrorMap:()=>gt,discriminatedUnion:()=>Gu,effect:()=>nd,enum:()=>rd,function:()=>Yu,getErrorMap:()=>pr,getParsedType:()=>ct,instanceof:()=>Nu,intersection:()=>Xu,isAborted:()=>Gr,isAsync:()=>fr,isDirty:()=>Xr,isValid:()=>Rt,late:()=>Au,lazy:()=>ed,literal:()=>td,makeIssue:()=>Ar,map:()=>Ku,nan:()=>Du,nativeEnum:()=>sd,never:()=>Uu,null:()=>Fu,nullable:()=>id,number:()=>An,object:()=>Hu,objectUtil:()=>zs,oboolean:()=>pd,onumber:()=>dd,optional:()=>od,ostring:()=>ud,pipeline:()=>ld,preprocess:()=>cd,promise:()=>ad,quotelessJson:()=>nu,record:()=>Wu,set:()=>Ju,setErrorMap:()=>iu,strictObject:()=>zu,string:()=>$n,symbol:()=>Lu,transformer:()=>nd,tuple:()=>Qu,undefined:()=>ju,union:()=>Zu,unknown:()=>qu,util:()=>te,void:()=>Bu});var te;(function(s){s.assertEqual=t=>{};function e(t){}s.assertIs=e;function r(t){throw new Error}s.assertNever=r,s.arrayToEnum=t=>{let n={};for(let o of t)n[o]=o;return n},s.getValidEnumValues=t=>{let n=s.objectKeys(t).filter(i=>typeof t[t[i]]!="number"),o={};for(let i of n)o[i]=t[i];return s.objectValues(o)},s.objectValues=t=>s.objectKeys(t).map(function(n){return t[n]}),s.objectKeys=typeof Object.keys=="function"?t=>Object.keys(t):t=>{let n=[];for(let o in t)Object.prototype.hasOwnProperty.call(t,o)&&n.push(o);return n},s.find=(t,n)=>{for(let o of t)if(n(o))return o},s.isInteger=typeof Number.isInteger=="function"?t=>Number.isInteger(t):t=>typeof t=="number"&&Number.isFinite(t)&&Math.floor(t)===t;function a(t,n=" | "){return t.map(o=>typeof o=="string"?`'${o}'`:o).join(n)}s.joinValues=a,s.jsonStringifyReplacer=(t,n)=>typeof n=="bigint"?n.toString():n})(te||(te={}));var zs;(function(s){s.mergeShapes=(e,r)=>({...e,...r})})(zs||(zs={}));var U=te.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ct=s=>{switch(typeof s){case"undefined":return U.undefined;case"string":return U.string;case"number":return Number.isNaN(s)?U.nan:U.number;case"boolean":return U.boolean;case"function":return U.function;case"bigint":return U.bigint;case"symbol":return U.symbol;case"object":return Array.isArray(s)?U.array:s===null?U.null:s.then&&typeof s.then=="function"&&s.catch&&typeof s.catch=="function"?U.promise:typeof Map<"u"&&s instanceof Map?U.map:typeof Set<"u"&&s instanceof Set?U.set:typeof Date<"u"&&s instanceof Date?U.date:U.object;default:return U.unknown}};var k=te.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"]),nu=s=>JSON.stringify(s,null,2).replace(/"([^"]+)":/g,"$1:"),Me=class s extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=a=>{this.issues=[...this.issues,a]},this.addIssues=(a=[])=>{this.issues=[...this.issues,...a]};let r=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,r):this.__proto__=r,this.name="ZodError",this.issues=e}format(e){let r=e||function(n){return n.message},a={_errors:[]},t=n=>{for(let o of n.issues)if(o.code==="invalid_union")o.unionErrors.map(t);else if(o.code==="invalid_return_type")t(o.returnTypeError);else if(o.code==="invalid_arguments")t(o.argumentsError);else if(o.path.length===0)a._errors.push(r(o));else{let i=a,l=0;for(;l<o.path.length;){let u=o.path[l];l===o.path.length-1?(i[u]=i[u]||{_errors:[]},i[u]._errors.push(r(o))):i[u]=i[u]||{_errors:[]},i=i[u],l++}}};return t(this),a}static assert(e){if(!(e instanceof s))throw new Error(`Not a ZodError: ${e}`)}toString(){return this.message}get message(){return JSON.stringify(this.issues,te.jsonStringifyReplacer,2)}get isEmpty(){return this.issues.length===0}flatten(e=r=>r.message){let r={},a=[];for(let t of this.issues)if(t.path.length>0){let n=t.path[0];r[n]=r[n]||[],r[n].push(e(t))}else a.push(e(t));return{formErrors:a,fieldErrors:r}}get formErrors(){return this.flatten()}};Me.create=s=>new Me(s);var ou=(s,e)=>{let r;switch(s.code){case k.invalid_type:s.received===U.undefined?r="Required":r=`Expected ${s.expected}, received ${s.received}`;break;case k.invalid_literal:r=`Invalid literal value, expected ${JSON.stringify(s.expected,te.jsonStringifyReplacer)}`;break;case k.unrecognized_keys:r=`Unrecognized key(s) in object: ${te.joinValues(s.keys,", ")}`;break;case k.invalid_union:r="Invalid input";break;case k.invalid_union_discriminator:r=`Invalid discriminator value. Expected ${te.joinValues(s.options)}`;break;case k.invalid_enum_value:r=`Invalid enum value. Expected ${te.joinValues(s.options)}, received '${s.received}'`;break;case k.invalid_arguments:r="Invalid function arguments";break;case k.invalid_return_type:r="Invalid function return type";break;case k.invalid_date:r="Invalid date";break;case k.invalid_string:typeof s.validation=="object"?"includes"in s.validation?(r=`Invalid input: must include "${s.validation.includes}"`,typeof s.validation.position=="number"&&(r=`${r} at one or more positions greater than or equal to ${s.validation.position}`)):"startsWith"in s.validation?r=`Invalid input: must start with "${s.validation.startsWith}"`:"endsWith"in s.validation?r=`Invalid input: must end with "${s.validation.endsWith}"`:te.assertNever(s.validation):s.validation!=="regex"?r=`Invalid ${s.validation}`:r="Invalid";break;case k.too_small:s.type==="array"?r=`Array must contain ${s.exact?"exactly":s.inclusive?"at least":"more than"} ${s.minimum} element(s)`:s.type==="string"?r=`String must contain ${s.exact?"exactly":s.inclusive?"at least":"over"} ${s.minimum} character(s)`:s.type==="number"?r=`Number must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${s.minimum}`:s.type==="bigint"?r=`Number must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${s.minimum}`:s.type==="date"?r=`Date must be ${s.exact?"exactly equal to ":s.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(s.minimum))}`:r="Invalid input";break;case k.too_big:s.type==="array"?r=`Array must contain ${s.exact?"exactly":s.inclusive?"at most":"less than"} ${s.maximum} element(s)`:s.type==="string"?r=`String must contain ${s.exact?"exactly":s.inclusive?"at most":"under"} ${s.maximum} character(s)`:s.type==="number"?r=`Number must be ${s.exact?"exactly":s.inclusive?"less than or equal to":"less than"} ${s.maximum}`:s.type==="bigint"?r=`BigInt must be ${s.exact?"exactly":s.inclusive?"less than or equal to":"less than"} ${s.maximum}`:s.type==="date"?r=`Date must be ${s.exact?"exactly":s.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(s.maximum))}`:r="Invalid input";break;case k.custom:r="Invalid input";break;case k.invalid_intersection_types:r="Intersection results could not be merged";break;case k.not_multiple_of:r=`Number must be a multiple of ${s.multipleOf}`;break;case k.not_finite:r="Number must be finite";break;default:r=e.defaultError,te.assertNever(s)}return{message:r}},gt=ou;var Sn=gt;function iu(s){Sn=s}function pr(){return Sn}var Ar=s=>{let{data:e,path:r,errorMaps:a,issueData:t}=s,n=[...r,...t.path||[]],o={...t,path:n};if(t.message!==void 0)return{...t,path:n,message:t.message};let i="",l=a.filter(u=>!!u).slice().reverse();for(let u of l)i=u(o,{data:e,defaultError:i}).message;return{...t,path:n,message:i}},cu=[];function q(s,e){let r=pr(),a=Ar({issueData:e,data:s.data,path:s.path,errorMaps:[s.common.contextualErrorMap,s.schemaErrorMap,r,r===gt?void 0:gt].filter(t=>!!t)});s.common.issues.push(a)}var Pe=class s{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,r){let a=[];for(let t of r){if(t.status==="aborted")return Z;t.status==="dirty"&&e.dirty(),a.push(t.value)}return{status:e.value,value:a}}static async mergeObjectAsync(e,r){let a=[];for(let t of r){let n=await t.key,o=await t.value;a.push({key:n,value:o})}return s.mergeObjectSync(e,a)}static mergeObjectSync(e,r){let a={};for(let t of r){let{key:n,value:o}=t;if(n.status==="aborted"||o.status==="aborted")return Z;n.status==="dirty"&&e.dirty(),o.status==="dirty"&&e.dirty(),n.value!=="__proto__"&&(typeof o.value<"u"||t.alwaysSet)&&(a[n.value]=o.value)}return{status:e.value,value:a}}},Z=Object.freeze({status:"aborted"}),qt=s=>({status:"dirty",value:s}),$e=s=>({status:"valid",value:s}),Gr=s=>s.status==="aborted",Xr=s=>s.status==="dirty",Rt=s=>s.status==="valid",fr=s=>typeof Promise<"u"&&s instanceof Promise;var V;(function(s){s.errToObj=e=>typeof e=="string"?{message:e}:e||{},s.toString=e=>typeof e=="string"?e:e?.message})(V||(V={}));var Qe=class{constructor(e,r,a,t){this._cachedPath=[],this.parent=e,this.data=r,this._path=a,this._key=t}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}},xn=(s,e)=>{if(Rt(e))return{success:!0,data:e.value};if(!s.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let r=new Me(s.common.issues);return this._error=r,this._error}}};function W(s){if(!s)return{};let{errorMap:e,invalid_type_error:r,required_error:a,description:t}=s;if(e&&(r||a))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:t}:{errorMap:(o,i)=>{let{message:l}=s;return o.code==="invalid_enum_value"?{message:l??i.defaultError}:typeof i.data>"u"?{message:l??a??i.defaultError}:o.code!=="invalid_type"?{message:i.defaultError}:{message:l??r??i.defaultError}},description:t}}var J=class{get description(){return this._def.description}_getType(e){return ct(e.data)}_getOrReturnCtx(e,r){return r||{common:e.parent.common,data:e.data,parsedType:ct(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new Pe,ctx:{common:e.parent.common,data:e.data,parsedType:ct(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let r=this._parse(e);if(fr(r))throw new Error("Synchronous parse encountered promise.");return r}_parseAsync(e){let r=this._parse(e);return Promise.resolve(r)}parse(e,r){let a=this.safeParse(e,r);if(a.success)return a.data;throw a.error}safeParse(e,r){let a={common:{issues:[],async:r?.async??!1,contextualErrorMap:r?.errorMap},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ct(e)},t=this._parseSync({data:e,path:a.path,parent:a});return xn(a,t)}"~validate"(e){let r={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ct(e)};if(!this["~standard"].async)try{let a=this._parseSync({data:e,path:[],parent:r});return Rt(a)?{value:a.value}:{issues:r.common.issues}}catch(a){a?.message?.toLowerCase()?.includes("encountered")&&(this["~standard"].async=!0),r.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:r}).then(a=>Rt(a)?{value:a.value}:{issues:r.common.issues})}async parseAsync(e,r){let a=await this.safeParseAsync(e,r);if(a.success)return a.data;throw a.error}async safeParseAsync(e,r){let a={common:{issues:[],contextualErrorMap:r?.errorMap,async:!0},path:r?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ct(e)},t=this._parse({data:e,path:a.path,parent:a}),n=await(fr(t)?t:Promise.resolve(t));return xn(a,n)}refine(e,r){let a=t=>typeof r=="string"||typeof r>"u"?{message:r}:typeof r=="function"?r(t):r;return this._refinement((t,n)=>{let o=e(t),i=()=>n.addIssue({code:k.custom,...a(t)});return typeof Promise<"u"&&o instanceof Promise?o.then(l=>l?!0:(i(),!1)):o?!0:(i(),!1)})}refinement(e,r){return this._refinement((a,t)=>e(a)?!0:(t.addIssue(typeof r=="function"?r(a,t):r),!1))}_refinement(e){return new We({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:r=>this["~validate"](r)}}optional(){return Xe.create(this,this._def)}nullable(){return ut.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return bt.create(this)}promise(){return Pt.create(this,this._def)}or(e){return Gt.create([this,e],this._def)}and(e){return Xt.create(this,e,this._def)}transform(e){return new We({...W(this._def),schema:this,typeName:L.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let r=typeof e=="function"?e:()=>e;return new Yt({...W(this._def),innerType:this,defaultValue:r,typeName:L.ZodDefault})}brand(){return new Nr({typeName:L.ZodBranded,type:this,...W(this._def)})}catch(e){let r=typeof e=="function"?e:()=>e;return new er({...W(this._def),innerType:this,catchValue:r,typeName:L.ZodCatch})}describe(e){let r=this.constructor;return new r({...this._def,description:e})}pipe(e){return Dr.create(this,e)}readonly(){return tr.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},lu=/^c[^\s-]{8,}$/i,uu=/^[0-9a-z]+$/,du=/^[0-9A-HJKMNP-TV-Z]{26}$/i,pu=/^[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,fu=/^[a-z0-9_-]{21}$/i,hu=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,mu=/^[-+]?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)?)??$/,vu=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,gu="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Zs,yu=/^(?:(?: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])$/,_u=/^(?:(?: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])$/,bu=/^(([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]))$/,Eu=/^(([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])$/,Su=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,xu=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Tn="((\\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])))",Ru=new RegExp(`^${Tn}$`);function wn(s){let e="[0-5]\\d";s.precision?e=`${e}\\.\\d{${s.precision}}`:s.precision==null&&(e=`${e}(\\.\\d+)?`);let r=s.precision?"+":"?";return`([01]\\d|2[0-3]):[0-5]\\d(:${e})${r}`}function Tu(s){return new RegExp(`^${wn(s)}$`)}function Pn(s){let e=`${Tn}T${wn(s)}`,r=[];return r.push(s.local?"Z?":"Z"),s.offset&&r.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${r.join("|")})`,new RegExp(`^${e}$`)}function wu(s,e){return!!((e==="v4"||!e)&&yu.test(s)||(e==="v6"||!e)&&bu.test(s))}function Pu(s,e){if(!hu.test(s))return!1;try{let[r]=s.split(".");if(!r)return!1;let a=r.replace(/-/g,"+").replace(/_/g,"/").padEnd(r.length+(4-r.length%4)%4,"="),t=JSON.parse(atob(a));return!(typeof t!="object"||t===null||"typ"in t&&t?.typ!=="JWT"||!t.alg||e&&t.alg!==e)}catch{return!1}}function Ou(s,e){return!!((e==="v4"||!e)&&_u.test(s)||(e==="v6"||!e)&&Eu.test(s))}var Tt=class s extends J{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==U.string){let n=this._getOrReturnCtx(e);return q(n,{code:k.invalid_type,expected:U.string,received:n.parsedType}),Z}let a=new Pe,t;for(let n of this._def.checks)if(n.kind==="min")e.data.length<n.value&&(t=this._getOrReturnCtx(e,t),q(t,{code:k.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),a.dirty());else if(n.kind==="max")e.data.length>n.value&&(t=this._getOrReturnCtx(e,t),q(t,{code:k.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!1,message:n.message}),a.dirty());else if(n.kind==="length"){let o=e.data.length>n.value,i=e.data.length<n.value;(o||i)&&(t=this._getOrReturnCtx(e,t),o?q(t,{code:k.too_big,maximum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}):i&&q(t,{code:k.too_small,minimum:n.value,type:"string",inclusive:!0,exact:!0,message:n.message}),a.dirty())}else if(n.kind==="email")vu.test(e.data)||(t=this._getOrReturnCtx(e,t),q(t,{validation:"email",code:k.invalid_string,message:n.message}),a.dirty());else if(n.kind==="emoji")Zs||(Zs=new RegExp(gu,"u")),Zs.test(e.data)||(t=this._getOrReturnCtx(e,t),q(t,{validation:"emoji",code:k.invalid_string,message:n.message}),a.dirty());else if(n.kind==="uuid")pu.test(e.data)||(t=this._getOrReturnCtx(e,t),q(t,{validation:"uuid",code:k.invalid_string,message:n.message}),a.dirty());else if(n.kind==="nanoid")fu.test(e.data)||(t=this._getOrReturnCtx(e,t),q(t,{validation:"nanoid",code:k.invalid_string,message:n.message}),a.dirty());else if(n.kind==="cuid")lu.test(e.data)||(t=this._getOrReturnCtx(e,t),q(t,{validation:"cuid",code:k.invalid_string,message:n.message}),a.dirty());else if(n.kind==="cuid2")uu.test(e.data)||(t=this._getOrReturnCtx(e,t),q(t,{validation:"cuid2",code:k.invalid_string,message:n.message}),a.dirty());else if(n.kind==="ulid")du.test(e.data)||(t=this._getOrReturnCtx(e,t),q(t,{validation:"ulid",code:k.invalid_string,message:n.message}),a.dirty());else if(n.kind==="url")try{new URL(e.data)}catch{t=this._getOrReturnCtx(e,t),q(t,{validation:"url",code:k.invalid_string,message:n.message}),a.dirty()}else n.kind==="regex"?(n.regex.lastIndex=0,n.regex.test(e.data)||(t=this._getOrReturnCtx(e,t),q(t,{validation:"regex",code:k.invalid_string,message:n.message}),a.dirty())):n.kind==="trim"?e.data=e.data.trim():n.kind==="includes"?e.data.includes(n.value,n.position)||(t=this._getOrReturnCtx(e,t),q(t,{code:k.invalid_string,validation:{includes:n.value,position:n.position},message:n.message}),a.dirty()):n.kind==="toLowerCase"?e.data=e.data.toLowerCase():n.kind==="toUpperCase"?e.data=e.data.toUpperCase():n.kind==="startsWith"?e.data.startsWith(n.value)||(t=this._getOrReturnCtx(e,t),q(t,{code:k.invalid_string,validation:{startsWith:n.value},message:n.message}),a.dirty()):n.kind==="endsWith"?e.data.endsWith(n.value)||(t=this._getOrReturnCtx(e,t),q(t,{code:k.invalid_string,validation:{endsWith:n.value},message:n.message}),a.dirty()):n.kind==="datetime"?Pn(n).test(e.data)||(t=this._getOrReturnCtx(e,t),q(t,{code:k.invalid_string,validation:"datetime",message:n.message}),a.dirty()):n.kind==="date"?Ru.test(e.data)||(t=this._getOrReturnCtx(e,t),q(t,{code:k.invalid_string,validation:"date",message:n.message}),a.dirty()):n.kind==="time"?Tu(n).test(e.data)||(t=this._getOrReturnCtx(e,t),q(t,{code:k.invalid_string,validation:"time",message:n.message}),a.dirty()):n.kind==="duration"?mu.test(e.data)||(t=this._getOrReturnCtx(e,t),q(t,{validation:"duration",code:k.invalid_string,message:n.message}),a.dirty()):n.kind==="ip"?wu(e.data,n.version)||(t=this._getOrReturnCtx(e,t),q(t,{validation:"ip",code:k.invalid_string,message:n.message}),a.dirty()):n.kind==="jwt"?Pu(e.data,n.alg)||(t=this._getOrReturnCtx(e,t),q(t,{validation:"jwt",code:k.invalid_string,message:n.message}),a.dirty()):n.kind==="cidr"?Ou(e.data,n.version)||(t=this._getOrReturnCtx(e,t),q(t,{validation:"cidr",code:k.invalid_string,message:n.message}),a.dirty()):n.kind==="base64"?Su.test(e.data)||(t=this._getOrReturnCtx(e,t),q(t,{validation:"base64",code:k.invalid_string,message:n.message}),a.dirty()):n.kind==="base64url"?xu.test(e.data)||(t=this._getOrReturnCtx(e,t),q(t,{validation:"base64url",code:k.invalid_string,message:n.message}),a.dirty()):te.assertNever(n);return{status:a.value,value:e.data}}_regex(e,r,a){return this.refinement(t=>e.test(t),{validation:r,code:k.invalid_string,...V.errToObj(a)})}_addCheck(e){return new s({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...V.errToObj(e)})}url(e){return this._addCheck({kind:"url",...V.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...V.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...V.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...V.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...V.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...V.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...V.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...V.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...V.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...V.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...V.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...V.errToObj(e)})}datetime(e){return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:e?.offset??!1,local:e?.local??!1,...V.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...V.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...V.errToObj(e)})}regex(e,r){return this._addCheck({kind:"regex",regex:e,...V.errToObj(r)})}includes(e,r){return this._addCheck({kind:"includes",value:e,position:r?.position,...V.errToObj(r?.message)})}startsWith(e,r){return this._addCheck({kind:"startsWith",value:e,...V.errToObj(r)})}endsWith(e,r){return this._addCheck({kind:"endsWith",value:e,...V.errToObj(r)})}min(e,r){return this._addCheck({kind:"min",value:e,...V.errToObj(r)})}max(e,r){return this._addCheck({kind:"max",value:e,...V.errToObj(r)})}length(e,r){return this._addCheck({kind:"length",value:e,...V.errToObj(r)})}nonempty(e){return this.min(1,V.errToObj(e))}trim(){return new s({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new s({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new s({...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 r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxLength(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Tt.create=s=>new Tt({checks:[],typeName:L.ZodString,coerce:s?.coerce??!1,...W(s)});function Iu(s,e){let r=(s.toString().split(".")[1]||"").length,a=(e.toString().split(".")[1]||"").length,t=r>a?r:a,n=Number.parseInt(s.toFixed(t).replace(".","")),o=Number.parseInt(e.toFixed(t).replace(".",""));return n%o/10**t}var Ut=class s extends J{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)!==U.number){let n=this._getOrReturnCtx(e);return q(n,{code:k.invalid_type,expected:U.number,received:n.parsedType}),Z}let a,t=new Pe;for(let n of this._def.checks)n.kind==="int"?te.isInteger(e.data)||(a=this._getOrReturnCtx(e,a),q(a,{code:k.invalid_type,expected:"integer",received:"float",message:n.message}),t.dirty()):n.kind==="min"?(n.inclusive?e.data<n.value:e.data<=n.value)&&(a=this._getOrReturnCtx(e,a),q(a,{code:k.too_small,minimum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),t.dirty()):n.kind==="max"?(n.inclusive?e.data>n.value:e.data>=n.value)&&(a=this._getOrReturnCtx(e,a),q(a,{code:k.too_big,maximum:n.value,type:"number",inclusive:n.inclusive,exact:!1,message:n.message}),t.dirty()):n.kind==="multipleOf"?Iu(e.data,n.value)!==0&&(a=this._getOrReturnCtx(e,a),q(a,{code:k.not_multiple_of,multipleOf:n.value,message:n.message}),t.dirty()):n.kind==="finite"?Number.isFinite(e.data)||(a=this._getOrReturnCtx(e,a),q(a,{code:k.not_finite,message:n.message}),t.dirty()):te.assertNever(n);return{status:t.value,value:e.data}}gte(e,r){return this.setLimit("min",e,!0,V.toString(r))}gt(e,r){return this.setLimit("min",e,!1,V.toString(r))}lte(e,r){return this.setLimit("max",e,!0,V.toString(r))}lt(e,r){return this.setLimit("max",e,!1,V.toString(r))}setLimit(e,r,a,t){return new s({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:a,message:V.toString(t)}]})}_addCheck(e){return new s({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:V.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:V.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:V.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:V.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:V.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:V.toString(r)})}finite(e){return this._addCheck({kind:"finite",message:V.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:V.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:V.toString(e)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}get isInt(){return!!this._def.checks.find(e=>e.kind==="int"||e.kind==="multipleOf"&&te.isInteger(e.value))}get isFinite(){let e=null,r=null;for(let a of this._def.checks){if(a.kind==="finite"||a.kind==="int"||a.kind==="multipleOf")return!0;a.kind==="min"?(r===null||a.value>r)&&(r=a.value):a.kind==="max"&&(e===null||a.value<e)&&(e=a.value)}return Number.isFinite(r)&&Number.isFinite(e)}};Ut.create=s=>new Ut({checks:[],typeName:L.ZodNumber,coerce:s?.coerce||!1,...W(s)});var Bt=class s extends J{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)!==U.bigint)return this._getInvalidInput(e);let a,t=new Pe;for(let n of this._def.checks)n.kind==="min"?(n.inclusive?e.data<n.value:e.data<=n.value)&&(a=this._getOrReturnCtx(e,a),q(a,{code:k.too_small,type:"bigint",minimum:n.value,inclusive:n.inclusive,message:n.message}),t.dirty()):n.kind==="max"?(n.inclusive?e.data>n.value:e.data>=n.value)&&(a=this._getOrReturnCtx(e,a),q(a,{code:k.too_big,type:"bigint",maximum:n.value,inclusive:n.inclusive,message:n.message}),t.dirty()):n.kind==="multipleOf"?e.data%n.value!==BigInt(0)&&(a=this._getOrReturnCtx(e,a),q(a,{code:k.not_multiple_of,multipleOf:n.value,message:n.message}),t.dirty()):te.assertNever(n);return{status:t.value,value:e.data}}_getInvalidInput(e){let r=this._getOrReturnCtx(e);return q(r,{code:k.invalid_type,expected:U.bigint,received:r.parsedType}),Z}gte(e,r){return this.setLimit("min",e,!0,V.toString(r))}gt(e,r){return this.setLimit("min",e,!1,V.toString(r))}lte(e,r){return this.setLimit("max",e,!0,V.toString(r))}lt(e,r){return this.setLimit("max",e,!1,V.toString(r))}setLimit(e,r,a,t){return new s({...this._def,checks:[...this._def.checks,{kind:e,value:r,inclusive:a,message:V.toString(t)}]})}_addCheck(e){return new s({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:V.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:V.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:V.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:V.toString(e)})}multipleOf(e,r){return this._addCheck({kind:"multipleOf",value:e,message:V.toString(r)})}get minValue(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e}get maxValue(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e}};Bt.create=s=>new Bt({checks:[],typeName:L.ZodBigInt,coerce:s?.coerce??!1,...W(s)});var Vt=class extends J{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==U.boolean){let a=this._getOrReturnCtx(e);return q(a,{code:k.invalid_type,expected:U.boolean,received:a.parsedType}),Z}return $e(e.data)}};Vt.create=s=>new Vt({typeName:L.ZodBoolean,coerce:s?.coerce||!1,...W(s)});var Ht=class s extends J{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==U.date){let n=this._getOrReturnCtx(e);return q(n,{code:k.invalid_type,expected:U.date,received:n.parsedType}),Z}if(Number.isNaN(e.data.getTime())){let n=this._getOrReturnCtx(e);return q(n,{code:k.invalid_date}),Z}let a=new Pe,t;for(let n of this._def.checks)n.kind==="min"?e.data.getTime()<n.value&&(t=this._getOrReturnCtx(e,t),q(t,{code:k.too_small,message:n.message,inclusive:!0,exact:!1,minimum:n.value,type:"date"}),a.dirty()):n.kind==="max"?e.data.getTime()>n.value&&(t=this._getOrReturnCtx(e,t),q(t,{code:k.too_big,message:n.message,inclusive:!0,exact:!1,maximum:n.value,type:"date"}),a.dirty()):te.assertNever(n);return{status:a.value,value:new Date(e.data.getTime())}}_addCheck(e){return new s({...this._def,checks:[...this._def.checks,e]})}min(e,r){return this._addCheck({kind:"min",value:e.getTime(),message:V.toString(r)})}max(e,r){return this._addCheck({kind:"max",value:e.getTime(),message:V.toString(r)})}get minDate(){let e=null;for(let r of this._def.checks)r.kind==="min"&&(e===null||r.value>e)&&(e=r.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let r of this._def.checks)r.kind==="max"&&(e===null||r.value<e)&&(e=r.value);return e!=null?new Date(e):null}};Ht.create=s=>new Ht({checks:[],coerce:s?.coerce||!1,typeName:L.ZodDate,...W(s)});var mr=class extends J{_parse(e){if(this._getType(e)!==U.symbol){let a=this._getOrReturnCtx(e);return q(a,{code:k.invalid_type,expected:U.symbol,received:a.parsedType}),Z}return $e(e.data)}};mr.create=s=>new mr({typeName:L.ZodSymbol,...W(s)});var zt=class extends J{_parse(e){if(this._getType(e)!==U.undefined){let a=this._getOrReturnCtx(e);return q(a,{code:k.invalid_type,expected:U.undefined,received:a.parsedType}),Z}return $e(e.data)}};zt.create=s=>new zt({typeName:L.ZodUndefined,...W(s)});var Zt=class extends J{_parse(e){if(this._getType(e)!==U.null){let a=this._getOrReturnCtx(e);return q(a,{code:k.invalid_type,expected:U.null,received:a.parsedType}),Z}return $e(e.data)}};Zt.create=s=>new Zt({typeName:L.ZodNull,...W(s)});var wt=class extends J{constructor(){super(...arguments),this._any=!0}_parse(e){return $e(e.data)}};wt.create=s=>new wt({typeName:L.ZodAny,...W(s)});var _t=class extends J{constructor(){super(...arguments),this._unknown=!0}_parse(e){return $e(e.data)}};_t.create=s=>new _t({typeName:L.ZodUnknown,...W(s)});var tt=class extends J{_parse(e){let r=this._getOrReturnCtx(e);return q(r,{code:k.invalid_type,expected:U.never,received:r.parsedType}),Z}};tt.create=s=>new tt({typeName:L.ZodNever,...W(s)});var vr=class extends J{_parse(e){if(this._getType(e)!==U.undefined){let a=this._getOrReturnCtx(e);return q(a,{code:k.invalid_type,expected:U.void,received:a.parsedType}),Z}return $e(e.data)}};vr.create=s=>new vr({typeName:L.ZodVoid,...W(s)});var bt=class s extends J{_parse(e){let{ctx:r,status:a}=this._processInputParams(e),t=this._def;if(r.parsedType!==U.array)return q(r,{code:k.invalid_type,expected:U.array,received:r.parsedType}),Z;if(t.exactLength!==null){let o=r.data.length>t.exactLength.value,i=r.data.length<t.exactLength.value;(o||i)&&(q(r,{code:o?k.too_big:k.too_small,minimum:i?t.exactLength.value:void 0,maximum:o?t.exactLength.value:void 0,type:"array",inclusive:!0,exact:!0,message:t.exactLength.message}),a.dirty())}if(t.minLength!==null&&r.data.length<t.minLength.value&&(q(r,{code:k.too_small,minimum:t.minLength.value,type:"array",inclusive:!0,exact:!1,message:t.minLength.message}),a.dirty()),t.maxLength!==null&&r.data.length>t.maxLength.value&&(q(r,{code:k.too_big,maximum:t.maxLength.value,type:"array",inclusive:!0,exact:!1,message:t.maxLength.message}),a.dirty()),r.common.async)return Promise.all([...r.data].map((o,i)=>t.type._parseAsync(new Qe(r,o,r.path,i)))).then(o=>Pe.mergeArray(a,o));let n=[...r.data].map((o,i)=>t.type._parseSync(new Qe(r,o,r.path,i)));return Pe.mergeArray(a,n)}get element(){return this._def.type}min(e,r){return new s({...this._def,minLength:{value:e,message:V.toString(r)}})}max(e,r){return new s({...this._def,maxLength:{value:e,message:V.toString(r)}})}length(e,r){return new s({...this._def,exactLength:{value:e,message:V.toString(r)}})}nonempty(e){return this.min(1,e)}};bt.create=(s,e)=>new bt({type:s,minLength:null,maxLength:null,exactLength:null,typeName:L.ZodArray,...W(e)});function hr(s){if(s instanceof qe){let e={};for(let r in s.shape){let a=s.shape[r];e[r]=Xe.create(hr(a))}return new qe({...s._def,shape:()=>e})}else return s instanceof bt?new bt({...s._def,type:hr(s.element)}):s instanceof Xe?Xe.create(hr(s.unwrap())):s instanceof ut?ut.create(hr(s.unwrap())):s instanceof lt?lt.create(s.items.map(e=>hr(e))):s}var qe=class s extends J{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(),r=te.objectKeys(e);return this._cached={shape:e,keys:r},this._cached}_parse(e){if(this._getType(e)!==U.object){let u=this._getOrReturnCtx(e);return q(u,{code:k.invalid_type,expected:U.object,received:u.parsedType}),Z}let{status:a,ctx:t}=this._processInputParams(e),{shape:n,keys:o}=this._getCached(),i=[];if(!(this._def.catchall instanceof tt&&this._def.unknownKeys==="strip"))for(let u in t.data)o.includes(u)||i.push(u);let l=[];for(let u of o){let d=n[u],f=t.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new Qe(t,f,t.path,u)),alwaysSet:u in t.data})}if(this._def.catchall instanceof tt){let u=this._def.unknownKeys;if(u==="passthrough")for(let d of i)l.push({key:{status:"valid",value:d},value:{status:"valid",value:t.data[d]}});else if(u==="strict")i.length>0&&(q(t,{code:k.unrecognized_keys,keys:i}),a.dirty());else if(u!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let u=this._def.catchall;for(let d of i){let f=t.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new Qe(t,f,t.path,d)),alwaysSet:d in t.data})}}return t.common.async?Promise.resolve().then(async()=>{let u=[];for(let d of l){let f=await d.key,m=await d.value;u.push({key:f,value:m,alwaysSet:d.alwaysSet})}return u}).then(u=>Pe.mergeObjectSync(a,u)):Pe.mergeObjectSync(a,l)}get shape(){return this._def.shape()}strict(e){return V.errToObj,new s({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(r,a)=>{let t=this._def.errorMap?.(r,a).message??a.defaultError;return r.code==="unrecognized_keys"?{message:V.errToObj(e).message??t}:{message:t}}}:{}})}strip(){return new s({...this._def,unknownKeys:"strip"})}passthrough(){return new s({...this._def,unknownKeys:"passthrough"})}extend(e){return new s({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new s({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:L.ZodObject})}setKey(e,r){return this.augment({[e]:r})}catchall(e){return new s({...this._def,catchall:e})}pick(e){let r={};for(let a of te.objectKeys(e))e[a]&&this.shape[a]&&(r[a]=this.shape[a]);return new s({...this._def,shape:()=>r})}omit(e){let r={};for(let a of te.objectKeys(this.shape))e[a]||(r[a]=this.shape[a]);return new s({...this._def,shape:()=>r})}deepPartial(){return hr(this)}partial(e){let r={};for(let a of te.objectKeys(this.shape)){let t=this.shape[a];e&&!e[a]?r[a]=t:r[a]=t.optional()}return new s({...this._def,shape:()=>r})}required(e){let r={};for(let a of te.objectKeys(this.shape))if(e&&!e[a])r[a]=this.shape[a];else{let n=this.shape[a];for(;n instanceof Xe;)n=n._def.innerType;r[a]=n}return new s({...this._def,shape:()=>r})}keyof(){return On(te.objectKeys(this.shape))}};qe.create=(s,e)=>new qe({shape:()=>s,unknownKeys:"strip",catchall:tt.create(),typeName:L.ZodObject,...W(e)});qe.strictCreate=(s,e)=>new qe({shape:()=>s,unknownKeys:"strict",catchall:tt.create(),typeName:L.ZodObject,...W(e)});qe.lazycreate=(s,e)=>new qe({shape:s,unknownKeys:"strip",catchall:tt.create(),typeName:L.ZodObject,...W(e)});var Gt=class extends J{_parse(e){let{ctx:r}=this._processInputParams(e),a=this._def.options;function t(n){for(let i of n)if(i.result.status==="valid")return i.result;for(let i of n)if(i.result.status==="dirty")return r.common.issues.push(...i.ctx.common.issues),i.result;let o=n.map(i=>new Me(i.ctx.common.issues));return q(r,{code:k.invalid_union,unionErrors:o}),Z}if(r.common.async)return Promise.all(a.map(async n=>{let o={...r,common:{...r.common,issues:[]},parent:null};return{result:await n._parseAsync({data:r.data,path:r.path,parent:o}),ctx:o}})).then(t);{let n,o=[];for(let l of a){let u={...r,common:{...r.common,issues:[]},parent:null},d=l._parseSync({data:r.data,path:r.path,parent:u});if(d.status==="valid")return d;d.status==="dirty"&&!n&&(n={result:d,ctx:u}),u.common.issues.length&&o.push(u.common.issues)}if(n)return r.common.issues.push(...n.ctx.common.issues),n.result;let i=o.map(l=>new Me(l));return q(r,{code:k.invalid_union,unionErrors:i}),Z}}get options(){return this._def.options}};Gt.create=(s,e)=>new Gt({options:s,typeName:L.ZodUnion,...W(e)});var yt=s=>s instanceof Qt?yt(s.schema):s instanceof We?yt(s.innerType()):s instanceof Wt?[s.value]:s instanceof Kt?s.options:s instanceof Jt?te.objectValues(s.enum):s instanceof Yt?yt(s._def.innerType):s instanceof zt?[void 0]:s instanceof Zt?[null]:s instanceof Xe?[void 0,...yt(s.unwrap())]:s instanceof ut?[null,...yt(s.unwrap())]:s instanceof Nr||s instanceof tr?yt(s.unwrap()):s instanceof er?yt(s._def.innerType):[],Qr=class s extends J{_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==U.object)return q(r,{code:k.invalid_type,expected:U.object,received:r.parsedType}),Z;let a=this.discriminator,t=r.data[a],n=this.optionsMap.get(t);return n?r.common.async?n._parseAsync({data:r.data,path:r.path,parent:r}):n._parseSync({data:r.data,path:r.path,parent:r}):(q(r,{code:k.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[a]}),Z)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,r,a){let t=new Map;for(let n of r){let o=yt(n.shape[e]);if(!o.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let i of o){if(t.has(i))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(i)}`);t.set(i,n)}}return new s({typeName:L.ZodDiscriminatedUnion,discriminator:e,options:r,optionsMap:t,...W(a)})}};function Gs(s,e){let r=ct(s),a=ct(e);if(s===e)return{valid:!0,data:s};if(r===U.object&&a===U.object){let t=te.objectKeys(e),n=te.objectKeys(s).filter(i=>t.indexOf(i)!==-1),o={...s,...e};for(let i of n){let l=Gs(s[i],e[i]);if(!l.valid)return{valid:!1};o[i]=l.data}return{valid:!0,data:o}}else if(r===U.array&&a===U.array){if(s.length!==e.length)return{valid:!1};let t=[];for(let n=0;n<s.length;n++){let o=s[n],i=e[n],l=Gs(o,i);if(!l.valid)return{valid:!1};t.push(l.data)}return{valid:!0,data:t}}else return r===U.date&&a===U.date&&+s==+e?{valid:!0,data:s}:{valid:!1}}var Xt=class extends J{_parse(e){let{status:r,ctx:a}=this._processInputParams(e),t=(n,o)=>{if(Gr(n)||Gr(o))return Z;let i=Gs(n.value,o.value);return i.valid?((Xr(n)||Xr(o))&&r.dirty(),{status:r.value,value:i.data}):(q(a,{code:k.invalid_intersection_types}),Z)};return a.common.async?Promise.all([this._def.left._parseAsync({data:a.data,path:a.path,parent:a}),this._def.right._parseAsync({data:a.data,path:a.path,parent:a})]).then(([n,o])=>t(n,o)):t(this._def.left._parseSync({data:a.data,path:a.path,parent:a}),this._def.right._parseSync({data:a.data,path:a.path,parent:a}))}};Xt.create=(s,e,r)=>new Xt({left:s,right:e,typeName:L.ZodIntersection,...W(r)});var lt=class s extends J{_parse(e){let{status:r,ctx:a}=this._processInputParams(e);if(a.parsedType!==U.array)return q(a,{code:k.invalid_type,expected:U.array,received:a.parsedType}),Z;if(a.data.length<this._def.items.length)return q(a,{code:k.too_small,minimum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),Z;!this._def.rest&&a.data.length>this._def.items.length&&(q(a,{code:k.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),r.dirty());let n=[...a.data].map((o,i)=>{let l=this._def.items[i]||this._def.rest;return l?l._parse(new Qe(a,o,a.path,i)):null}).filter(o=>!!o);return a.common.async?Promise.all(n).then(o=>Pe.mergeArray(r,o)):Pe.mergeArray(r,n)}get items(){return this._def.items}rest(e){return new s({...this._def,rest:e})}};lt.create=(s,e)=>{if(!Array.isArray(s))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new lt({items:s,typeName:L.ZodTuple,rest:null,...W(e)})};var Wr=class s extends J{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:a}=this._processInputParams(e);if(a.parsedType!==U.object)return q(a,{code:k.invalid_type,expected:U.object,received:a.parsedType}),Z;let t=[],n=this._def.keyType,o=this._def.valueType;for(let i in a.data)t.push({key:n._parse(new Qe(a,i,a.path,i)),value:o._parse(new Qe(a,a.data[i],a.path,i)),alwaysSet:i in a.data});return a.common.async?Pe.mergeObjectAsync(r,t):Pe.mergeObjectSync(r,t)}get element(){return this._def.valueType}static create(e,r,a){return r instanceof J?new s({keyType:e,valueType:r,typeName:L.ZodRecord,...W(a)}):new s({keyType:Tt.create(),valueType:e,typeName:L.ZodRecord,...W(r)})}},gr=class extends J{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:r,ctx:a}=this._processInputParams(e);if(a.parsedType!==U.map)return q(a,{code:k.invalid_type,expected:U.map,received:a.parsedType}),Z;let t=this._def.keyType,n=this._def.valueType,o=[...a.data.entries()].map(([i,l],u)=>({key:t._parse(new Qe(a,i,a.path,[u,"key"])),value:n._parse(new Qe(a,l,a.path,[u,"value"]))}));if(a.common.async){let i=new Map;return Promise.resolve().then(async()=>{for(let l of o){let u=await l.key,d=await l.value;if(u.status==="aborted"||d.status==="aborted")return Z;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),i.set(u.value,d.value)}return{status:r.value,value:i}})}else{let i=new Map;for(let l of o){let u=l.key,d=l.value;if(u.status==="aborted"||d.status==="aborted")return Z;(u.status==="dirty"||d.status==="dirty")&&r.dirty(),i.set(u.value,d.value)}return{status:r.value,value:i}}}};gr.create=(s,e,r)=>new gr({valueType:e,keyType:s,typeName:L.ZodMap,...W(r)});var yr=class s extends J{_parse(e){let{status:r,ctx:a}=this._processInputParams(e);if(a.parsedType!==U.set)return q(a,{code:k.invalid_type,expected:U.set,received:a.parsedType}),Z;let t=this._def;t.minSize!==null&&a.data.size<t.minSize.value&&(q(a,{code:k.too_small,minimum:t.minSize.value,type:"set",inclusive:!0,exact:!1,message:t.minSize.message}),r.dirty()),t.maxSize!==null&&a.data.size>t.maxSize.value&&(q(a,{code:k.too_big,maximum:t.maxSize.value,type:"set",inclusive:!0,exact:!1,message:t.maxSize.message}),r.dirty());let n=this._def.valueType;function o(l){let u=new Set;for(let d of l){if(d.status==="aborted")return Z;d.status==="dirty"&&r.dirty(),u.add(d.value)}return{status:r.value,value:u}}let i=[...a.data.values()].map((l,u)=>n._parse(new Qe(a,l,a.path,u)));return a.common.async?Promise.all(i).then(l=>o(l)):o(i)}min(e,r){return new s({...this._def,minSize:{value:e,message:V.toString(r)}})}max(e,r){return new s({...this._def,maxSize:{value:e,message:V.toString(r)}})}size(e,r){return this.min(e,r).max(e,r)}nonempty(e){return this.min(1,e)}};yr.create=(s,e)=>new yr({valueType:s,minSize:null,maxSize:null,typeName:L.ZodSet,...W(e)});var Kr=class s extends J{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==U.function)return q(r,{code:k.invalid_type,expected:U.function,received:r.parsedType}),Z;function a(i,l){return Ar({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,pr(),gt].filter(u=>!!u),issueData:{code:k.invalid_arguments,argumentsError:l}})}function t(i,l){return Ar({data:i,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,pr(),gt].filter(u=>!!u),issueData:{code:k.invalid_return_type,returnTypeError:l}})}let n={errorMap:r.common.contextualErrorMap},o=r.data;if(this._def.returns instanceof Pt){let i=this;return $e(async function(...l){let u=new Me([]),d=await i._def.args.parseAsync(l,n).catch(p=>{throw u.addIssue(a(l,p)),u}),f=await Reflect.apply(o,this,d);return await i._def.returns._def.type.parseAsync(f,n).catch(p=>{throw u.addIssue(t(f,p)),u})})}else{let i=this;return $e(function(...l){let u=i._def.args.safeParse(l,n);if(!u.success)throw new Me([a(l,u.error)]);let d=Reflect.apply(o,this,u.data),f=i._def.returns.safeParse(d,n);if(!f.success)throw new Me([t(d,f.error)]);return f.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new s({...this._def,args:lt.create(e).rest(_t.create())})}returns(e){return new s({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,r,a){return new s({args:e||lt.create([]).rest(_t.create()),returns:r||_t.create(),typeName:L.ZodFunction,...W(a)})}},Qt=class extends J{get schema(){return this._def.getter()}_parse(e){let{ctx:r}=this._processInputParams(e);return this._def.getter()._parse({data:r.data,path:r.path,parent:r})}};Qt.create=(s,e)=>new Qt({getter:s,typeName:L.ZodLazy,...W(e)});var Wt=class extends J{_parse(e){if(e.data!==this._def.value){let r=this._getOrReturnCtx(e);return q(r,{received:r.data,code:k.invalid_literal,expected:this._def.value}),Z}return{status:"valid",value:e.data}}get value(){return this._def.value}};Wt.create=(s,e)=>new Wt({value:s,typeName:L.ZodLiteral,...W(e)});function On(s,e){return new Kt({values:s,typeName:L.ZodEnum,...W(e)})}var Kt=class s extends J{_parse(e){if(typeof e.data!="string"){let r=this._getOrReturnCtx(e),a=this._def.values;return q(r,{expected:te.joinValues(a),received:r.parsedType,code:k.invalid_type}),Z}if(this._cache||(this._cache=new Set(this._def.values)),!this._cache.has(e.data)){let r=this._getOrReturnCtx(e),a=this._def.values;return q(r,{received:r.data,code:k.invalid_enum_value,options:a}),Z}return $e(e.data)}get options(){return this._def.values}get enum(){let e={};for(let r of this._def.values)e[r]=r;return e}get Values(){let e={};for(let r of this._def.values)e[r]=r;return e}get Enum(){let e={};for(let r of this._def.values)e[r]=r;return e}extract(e,r=this._def){return s.create(e,{...this._def,...r})}exclude(e,r=this._def){return s.create(this.options.filter(a=>!e.includes(a)),{...this._def,...r})}};Kt.create=On;var Jt=class extends J{_parse(e){let r=te.getValidEnumValues(this._def.values),a=this._getOrReturnCtx(e);if(a.parsedType!==U.string&&a.parsedType!==U.number){let t=te.objectValues(r);return q(a,{expected:te.joinValues(t),received:a.parsedType,code:k.invalid_type}),Z}if(this._cache||(this._cache=new Set(te.getValidEnumValues(this._def.values))),!this._cache.has(e.data)){let t=te.objectValues(r);return q(a,{received:a.data,code:k.invalid_enum_value,options:t}),Z}return $e(e.data)}get enum(){return this._def.values}};Jt.create=(s,e)=>new Jt({values:s,typeName:L.ZodNativeEnum,...W(e)});var Pt=class extends J{unwrap(){return this._def.type}_parse(e){let{ctx:r}=this._processInputParams(e);if(r.parsedType!==U.promise&&r.common.async===!1)return q(r,{code:k.invalid_type,expected:U.promise,received:r.parsedType}),Z;let a=r.parsedType===U.promise?r.data:Promise.resolve(r.data);return $e(a.then(t=>this._def.type.parseAsync(t,{path:r.path,errorMap:r.common.contextualErrorMap})))}};Pt.create=(s,e)=>new Pt({type:s,typeName:L.ZodPromise,...W(e)});var We=class extends J{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:r,ctx:a}=this._processInputParams(e),t=this._def.effect||null,n={addIssue:o=>{q(a,o),o.fatal?r.abort():r.dirty()},get path(){return a.path}};if(n.addIssue=n.addIssue.bind(n),t.type==="preprocess"){let o=t.transform(a.data,n);if(a.common.async)return Promise.resolve(o).then(async i=>{if(r.value==="aborted")return Z;let l=await this._def.schema._parseAsync({data:i,path:a.path,parent:a});return l.status==="aborted"?Z:l.status==="dirty"?qt(l.value):r.value==="dirty"?qt(l.value):l});{if(r.value==="aborted")return Z;let i=this._def.schema._parseSync({data:o,path:a.path,parent:a});return i.status==="aborted"?Z:i.status==="dirty"?qt(i.value):r.value==="dirty"?qt(i.value):i}}if(t.type==="refinement"){let o=i=>{let l=t.refinement(i,n);if(a.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return i};if(a.common.async===!1){let i=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});return i.status==="aborted"?Z:(i.status==="dirty"&&r.dirty(),o(i.value),{status:r.value,value:i.value})}else return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then(i=>i.status==="aborted"?Z:(i.status==="dirty"&&r.dirty(),o(i.value).then(()=>({status:r.value,value:i.value}))))}if(t.type==="transform")if(a.common.async===!1){let o=this._def.schema._parseSync({data:a.data,path:a.path,parent:a});if(!Rt(o))return Z;let i=t.transform(o.value,n);if(i instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:r.value,value:i}}else return this._def.schema._parseAsync({data:a.data,path:a.path,parent:a}).then(o=>Rt(o)?Promise.resolve(t.transform(o.value,n)).then(i=>({status:r.value,value:i})):Z);te.assertNever(t)}};We.create=(s,e,r)=>new We({schema:s,typeName:L.ZodEffects,effect:e,...W(r)});We.createWithPreprocess=(s,e,r)=>new We({schema:e,effect:{type:"preprocess",transform:s},typeName:L.ZodEffects,...W(r)});var Xe=class extends J{_parse(e){return this._getType(e)===U.undefined?$e(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};Xe.create=(s,e)=>new Xe({innerType:s,typeName:L.ZodOptional,...W(e)});var ut=class extends J{_parse(e){return this._getType(e)===U.null?$e(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};ut.create=(s,e)=>new ut({innerType:s,typeName:L.ZodNullable,...W(e)});var Yt=class extends J{_parse(e){let{ctx:r}=this._processInputParams(e),a=r.data;return r.parsedType===U.undefined&&(a=this._def.defaultValue()),this._def.innerType._parse({data:a,path:r.path,parent:r})}removeDefault(){return this._def.innerType}};Yt.create=(s,e)=>new Yt({innerType:s,typeName:L.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...W(e)});var er=class extends J{_parse(e){let{ctx:r}=this._processInputParams(e),a={...r,common:{...r.common,issues:[]}},t=this._def.innerType._parse({data:a.data,path:a.path,parent:{...a}});return fr(t)?t.then(n=>({status:"valid",value:n.status==="valid"?n.value:this._def.catchValue({get error(){return new Me(a.common.issues)},input:a.data})})):{status:"valid",value:t.status==="valid"?t.value:this._def.catchValue({get error(){return new Me(a.common.issues)},input:a.data})}}removeCatch(){return this._def.innerType}};er.create=(s,e)=>new er({innerType:s,typeName:L.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...W(e)});var _r=class extends J{_parse(e){if(this._getType(e)!==U.nan){let a=this._getOrReturnCtx(e);return q(a,{code:k.invalid_type,expected:U.nan,received:a.parsedType}),Z}return{status:"valid",value:e.data}}};_r.create=s=>new _r({typeName:L.ZodNaN,...W(s)});var $u=Symbol("zod_brand"),Nr=class extends J{_parse(e){let{ctx:r}=this._processInputParams(e),a=r.data;return this._def.type._parse({data:a,path:r.path,parent:r})}unwrap(){return this._def.type}},Dr=class s extends J{_parse(e){let{status:r,ctx:a}=this._processInputParams(e);if(a.common.async)return(async()=>{let n=await this._def.in._parseAsync({data:a.data,path:a.path,parent:a});return n.status==="aborted"?Z:n.status==="dirty"?(r.dirty(),qt(n.value)):this._def.out._parseAsync({data:n.value,path:a.path,parent:a})})();{let t=this._def.in._parseSync({data:a.data,path:a.path,parent:a});return t.status==="aborted"?Z:t.status==="dirty"?(r.dirty(),{status:"dirty",value:t.value}):this._def.out._parseSync({data:t.value,path:a.path,parent:a})}}static create(e,r){return new s({in:e,out:r,typeName:L.ZodPipeline})}},tr=class extends J{_parse(e){let r=this._def.innerType._parse(e),a=t=>(Rt(t)&&(t.value=Object.freeze(t.value)),t);return fr(r)?r.then(t=>a(t)):a(r)}unwrap(){return this._def.innerType}};tr.create=(s,e)=>new tr({innerType:s,typeName:L.ZodReadonly,...W(e)});function Rn(s,e){let r=typeof s=="function"?s(e):typeof s=="string"?{message:s}:s;return typeof r=="string"?{message:r}:r}function In(s,e={},r){return s?wt.create().superRefine((a,t)=>{let n=s(a);if(n instanceof Promise)return n.then(o=>{if(!o){let i=Rn(e,a),l=i.fatal??r??!0;t.addIssue({code:"custom",...i,fatal:l})}});if(!n){let o=Rn(e,a),i=o.fatal??r??!0;t.addIssue({code:"custom",...o,fatal:i})}}):wt.create()}var Au={object:qe.lazycreate},L;(function(s){s.ZodString="ZodString",s.ZodNumber="ZodNumber",s.ZodNaN="ZodNaN",s.ZodBigInt="ZodBigInt",s.ZodBoolean="ZodBoolean",s.ZodDate="ZodDate",s.ZodSymbol="ZodSymbol",s.ZodUndefined="ZodUndefined",s.ZodNull="ZodNull",s.ZodAny="ZodAny",s.ZodUnknown="ZodUnknown",s.ZodNever="ZodNever",s.ZodVoid="ZodVoid",s.ZodArray="ZodArray",s.ZodObject="ZodObject",s.ZodUnion="ZodUnion",s.ZodDiscriminatedUnion="ZodDiscriminatedUnion",s.ZodIntersection="ZodIntersection",s.ZodTuple="ZodTuple",s.ZodRecord="ZodRecord",s.ZodMap="ZodMap",s.ZodSet="ZodSet",s.ZodFunction="ZodFunction",s.ZodLazy="ZodLazy",s.ZodLiteral="ZodLiteral",s.ZodEnum="ZodEnum",s.ZodEffects="ZodEffects",s.ZodNativeEnum="ZodNativeEnum",s.ZodOptional="ZodOptional",s.ZodNullable="ZodNullable",s.ZodDefault="ZodDefault",s.ZodCatch="ZodCatch",s.ZodPromise="ZodPromise",s.ZodBranded="ZodBranded",s.ZodPipeline="ZodPipeline",s.ZodReadonly="ZodReadonly"})(L||(L={}));var Nu=(s,e={message:`Input not instance of ${s.name}`})=>In(r=>r instanceof s,e),$n=Tt.create,An=Ut.create,Du=_r.create,Cu=Bt.create,Nn=Vt.create,ku=Ht.create,Lu=mr.create,ju=zt.create,Fu=Zt.create,Mu=wt.create,qu=_t.create,Uu=tt.create,Bu=vr.create,Vu=bt.create,Hu=qe.create,zu=qe.strictCreate,Zu=Gt.create,Gu=Qr.create,Xu=Xt.create,Qu=lt.create,Wu=Wr.create,Ku=gr.create,Ju=yr.create,Yu=Kr.create,ed=Qt.create,td=Wt.create,rd=Kt.create,sd=Jt.create,ad=Pt.create,nd=We.create,od=Xe.create,id=ut.create,cd=We.createWithPreprocess,ld=Dr.create,ud=()=>$n().optional(),dd=()=>An().optional(),pd=()=>Nn().optional(),fd={string:(s=>Tt.create({...s,coerce:!0})),number:(s=>Ut.create({...s,coerce:!0})),boolean:(s=>Vt.create({...s,coerce:!0})),bigint:(s=>Bt.create({...s,coerce:!0})),date:(s=>Ht.create({...s,coerce:!0}))};var hd=Z;var Cr="2025-06-18";var Jr=[Cr,"2025-03-26","2024-11-05","2024-10-07"],Yr="2.0",Dn=c.union([c.string(),c.number().int()]),Cn=c.string(),md=c.object({progressToken:c.optional(Dn)}).passthrough(),Ke=c.object({_meta:c.optional(md)}).passthrough(),Ue=c.object({method:c.string(),params:c.optional(Ke)}),kr=c.object({_meta:c.optional(c.object({}).passthrough())}).passthrough(),dt=c.object({method:c.string(),params:c.optional(kr)}),Je=c.object({_meta:c.optional(c.object({}).passthrough())}).passthrough(),es=c.union([c.string(),c.number().int()]),kn=c.object({jsonrpc:c.literal(Yr),id:es}).merge(Ue).strict(),Ln=s=>kn.safeParse(s).success,jn=c.object({jsonrpc:c.literal(Yr)}).merge(dt).strict(),Fn=s=>jn.safeParse(s).success,Mn=c.object({jsonrpc:c.literal(Yr),id:es,result:Je}).strict(),Xs=s=>Mn.safeParse(s).success,Le;(function(s){s[s.ConnectionClosed=-32e3]="ConnectionClosed",s[s.RequestTimeout=-32001]="RequestTimeout",s[s.ParseError=-32700]="ParseError",s[s.InvalidRequest=-32600]="InvalidRequest",s[s.MethodNotFound=-32601]="MethodNotFound",s[s.InvalidParams=-32602]="InvalidParams",s[s.InternalError=-32603]="InternalError"})(Le||(Le={}));var qn=c.object({jsonrpc:c.literal(Yr),id:es,error:c.object({code:c.number().int(),message:c.string(),data:c.optional(c.unknown())})}).strict(),Un=s=>qn.safeParse(s).success,Bn=c.union([kn,jn,Mn,qn]),Et=Je.strict(),ts=dt.extend({method:c.literal("notifications/cancelled"),params:kr.extend({requestId:es,reason:c.string().optional()})}),vd=c.object({src:c.string(),mimeType:c.optional(c.string()),sizes:c.optional(c.array(c.string()))}).passthrough(),Lr=c.object({icons:c.array(vd).optional()}).passthrough(),jr=c.object({name:c.string(),title:c.optional(c.string())}).passthrough(),Vn=jr.extend({version:c.string(),websiteUrl:c.optional(c.string())}).merge(Lr),gd=c.object({experimental:c.optional(c.object({}).passthrough()),sampling:c.optional(c.object({}).passthrough()),elicitation:c.optional(c.object({}).passthrough()),roots:c.optional(c.object({listChanged:c.optional(c.boolean())}).passthrough())}).passthrough(),Qs=Ue.extend({method:c.literal("initialize"),params:Ke.extend({protocolVersion:c.string(),capabilities:gd,clientInfo:Vn})});var yd=c.object({experimental:c.optional(c.object({}).passthrough()),logging:c.optional(c.object({}).passthrough()),completions:c.optional(c.object({}).passthrough()),prompts:c.optional(c.object({listChanged:c.optional(c.boolean())}).passthrough()),resources:c.optional(c.object({subscribe:c.optional(c.boolean()),listChanged:c.optional(c.boolean())}).passthrough()),tools:c.optional(c.object({listChanged:c.optional(c.boolean())}).passthrough())}).passthrough(),Ws=Je.extend({protocolVersion:c.string(),capabilities:yd,serverInfo:Vn,instructions:c.optional(c.string())}),Ks=dt.extend({method:c.literal("notifications/initialized")});var rs=Ue.extend({method:c.literal("ping")}),_d=c.object({progress:c.number(),total:c.optional(c.number()),message:c.optional(c.string())}).passthrough(),ss=dt.extend({method:c.literal("notifications/progress"),params:kr.merge(_d).extend({progressToken:Dn})}),as=Ue.extend({params:Ke.extend({cursor:c.optional(Cn)}).optional()}),ns=Je.extend({nextCursor:c.optional(Cn)}),Hn=c.object({uri:c.string(),mimeType:c.optional(c.string()),_meta:c.optional(c.object({}).passthrough())}).passthrough(),zn=Hn.extend({text:c.string()}),Js=c.string().refine(s=>{try{return atob(s),!0}catch{return!1}},{message:"Invalid Base64 string"}),Zn=Hn.extend({blob:Js}),Gn=jr.extend({uri:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),_meta:c.optional(c.object({}).passthrough())}).merge(Lr),bd=jr.extend({uriTemplate:c.string(),description:c.optional(c.string()),mimeType:c.optional(c.string()),_meta:c.optional(c.object({}).passthrough())}).merge(Lr),Ed=as.extend({method:c.literal("resources/list")}),Ys=ns.extend({resources:c.array(Gn)}),Sd=as.extend({method:c.literal("resources/templates/list")}),ea=ns.extend({resourceTemplates:c.array(bd)}),xd=Ue.extend({method:c.literal("resources/read"),params:Ke.extend({uri:c.string()})}),ta=Je.extend({contents:c.array(c.union([zn,Zn]))}),Rd=dt.extend({method:c.literal("notifications/resources/list_changed")}),Td=Ue.extend({method:c.literal("resources/subscribe"),params:Ke.extend({uri:c.string()})}),wd=Ue.extend({method:c.literal("resources/unsubscribe"),params:Ke.extend({uri:c.string()})}),Pd=dt.extend({method:c.literal("notifications/resources/updated"),params:kr.extend({uri:c.string()})}),Od=c.object({name:c.string(),description:c.optional(c.string()),required:c.optional(c.boolean())}).passthrough(),Id=jr.extend({description:c.optional(c.string()),arguments:c.optional(c.array(Od)),_meta:c.optional(c.object({}).passthrough())}).merge(Lr),$d=as.extend({method:c.literal("prompts/list")}),ra=ns.extend({prompts:c.array(Id)}),Ad=Ue.extend({method:c.literal("prompts/get"),params:Ke.extend({name:c.string(),arguments:c.optional(c.record(c.string()))})}),sa=c.object({type:c.literal("text"),text:c.string(),_meta:c.optional(c.object({}).passthrough())}).passthrough(),aa=c.object({type:c.literal("image"),data:Js,mimeType:c.string(),_meta:c.optional(c.object({}).passthrough())}).passthrough(),na=c.object({type:c.literal("audio"),data:Js,mimeType:c.string(),_meta:c.optional(c.object({}).passthrough())}).passthrough(),Nd=c.object({type:c.literal("resource"),resource:c.union([zn,Zn]),_meta:c.optional(c.object({}).passthrough())}).passthrough(),Dd=Gn.extend({type:c.literal("resource_link")}),Xn=c.union([sa,aa,na,Dd,Nd]),Cd=c.object({role:c.enum(["user","assistant"]),content:Xn}).passthrough(),oa=Je.extend({description:c.optional(c.string()),messages:c.array(Cd)}),kd=dt.extend({method:c.literal("notifications/prompts/list_changed")}),Ld=c.object({title:c.optional(c.string()),readOnlyHint:c.optional(c.boolean()),destructiveHint:c.optional(c.boolean()),idempotentHint:c.optional(c.boolean()),openWorldHint:c.optional(c.boolean())}).passthrough(),jd=jr.extend({description:c.optional(c.string()),inputSchema:c.object({type:c.literal("object"),properties:c.optional(c.object({}).passthrough()),required:c.optional(c.array(c.string()))}).passthrough(),outputSchema:c.optional(c.object({type:c.literal("object"),properties:c.optional(c.object({}).passthrough()),required:c.optional(c.array(c.string()))}).passthrough()),annotations:c.optional(Ld),_meta:c.optional(c.object({}).passthrough())}).merge(Lr),ia=as.extend({method:c.literal("tools/list")}),ca=ns.extend({tools:c.array(jd)}),os=Je.extend({content:c.array(Xn).default([]),structuredContent:c.object({}).passthrough().optional(),isError:c.optional(c.boolean())}),cm=os.or(Je.extend({toolResult:c.unknown()})),la=Ue.extend({method:c.literal("tools/call"),params:Ke.extend({name:c.string(),arguments:c.optional(c.record(c.unknown()))})}),Fd=dt.extend({method:c.literal("notifications/tools/list_changed")}),Fr=c.enum(["debug","info","notice","warning","error","critical","alert","emergency"]),ua=Ue.extend({method:c.literal("logging/setLevel"),params:Ke.extend({level:Fr})}),Md=dt.extend({method:c.literal("notifications/message"),params:kr.extend({level:Fr,logger:c.optional(c.string()),data:c.unknown()})}),qd=c.object({name:c.string().optional()}).passthrough(),Ud=c.object({hints:c.optional(c.array(qd)),costPriority:c.optional(c.number().min(0).max(1)),speedPriority:c.optional(c.number().min(0).max(1)),intelligencePriority:c.optional(c.number().min(0).max(1))}).passthrough(),Bd=c.object({role:c.enum(["user","assistant"]),content:c.union([sa,aa,na])}).passthrough(),Vd=Ue.extend({method:c.literal("sampling/createMessage"),params:Ke.extend({messages:c.array(Bd),systemPrompt:c.optional(c.string()),includeContext:c.optional(c.enum(["none","thisServer","allServers"])),temperature:c.optional(c.number()),maxTokens:c.number().int(),stopSequences:c.optional(c.array(c.string())),metadata:c.optional(c.object({}).passthrough()),modelPreferences:c.optional(Ud)})}),da=Je.extend({model:c.string(),stopReason:c.optional(c.enum(["endTurn","stopSequence","maxTokens"]).or(c.string())),role:c.enum(["user","assistant"]),content:c.discriminatedUnion("type",[sa,aa,na])}),Hd=c.object({type:c.literal("boolean"),title:c.optional(c.string()),description:c.optional(c.string()),default:c.optional(c.boolean())}).passthrough(),zd=c.object({type:c.literal("string"),title:c.optional(c.string()),description:c.optional(c.string()),minLength:c.optional(c.number()),maxLength:c.optional(c.number()),format:c.optional(c.enum(["email","uri","date","date-time"]))}).passthrough(),Zd=c.object({type:c.enum(["number","integer"]),title:c.optional(c.string()),description:c.optional(c.string()),minimum:c.optional(c.number()),maximum:c.optional(c.number())}).passthrough(),Gd=c.object({type:c.literal("string"),title:c.optional(c.string()),description:c.optional(c.string()),enum:c.array(c.string()),enumNames:c.optional(c.array(c.string()))}).passthrough(),Xd=c.union([Hd,zd,Zd,Gd]),Qd=Ue.extend({method:c.literal("elicitation/create"),params:Ke.extend({message:c.string(),requestedSchema:c.object({type:c.literal("object"),properties:c.record(c.string(),Xd),required:c.optional(c.array(c.string()))}).passthrough()})}),pa=Je.extend({action:c.enum(["accept","decline","cancel"]),content:c.optional(c.record(c.string(),c.unknown()))}),Wd=c.object({type:c.literal("ref/resource"),uri:c.string()}).passthrough();var Kd=c.object({type:c.literal("ref/prompt"),name:c.string()}).passthrough(),Jd=Ue.extend({method:c.literal("completion/complete"),params:Ke.extend({ref:c.union([Kd,Wd]),argument:c.object({name:c.string(),value:c.string()}).passthrough(),context:c.optional(c.object({arguments:c.optional(c.record(c.string(),c.string()))}))})}),fa=Je.extend({completion:c.object({values:c.array(c.string()).max(100),total:c.optional(c.number().int()),hasMore:c.optional(c.boolean())}).passthrough()}),Yd=c.object({uri:c.string().startsWith("file://"),name:c.optional(c.string()),_meta:c.optional(c.object({}).passthrough())}).passthrough(),ep=Ue.extend({method:c.literal("roots/list")}),ha=Je.extend({roots:c.array(Yd)}),tp=dt.extend({method:c.literal("notifications/roots/list_changed")}),lm=c.union([rs,Qs,Jd,ua,Ad,$d,Ed,Sd,xd,Td,wd,la,ia]),um=c.union([ts,ss,Ks,tp]),dm=c.union([Et,da,pa,ha]),pm=c.union([rs,Vd,Qd,ep]),fm=c.union([ts,ss,Md,Pd,Rd,Fd,kd]),hm=c.union([Et,Ws,fa,oa,ra,Ys,ea,ta,os,ca]),Ae=class extends Error{constructor(e,r,a){super(`MCP error ${e}: ${r}`),this.code=e,this.data=a,this.name="McpError"}};var rp=6e4,br=class{constructor(e){this._options=e,this._requestMessageId=0,this._requestHandlers=new Map,this._requestHandlerAbortControllers=new Map,this._notificationHandlers=new Map,this._responseHandlers=new Map,this._progressHandlers=new Map,this._timeoutInfo=new Map,this._pendingDebouncedNotifications=new Set,this.setNotificationHandler(ts,r=>{let a=this._requestHandlerAbortControllers.get(r.params.requestId);a?.abort(r.params.reason)}),this.setNotificationHandler(ss,r=>{this._onprogress(r)}),this.setRequestHandler(rs,r=>({}))}_setupTimeout(e,r,a,t,n=!1){this._timeoutInfo.set(e,{timeoutId:setTimeout(t,r),startTime:Date.now(),timeout:r,maxTotalTimeout:a,resetTimeoutOnProgress:n,onTimeout:t})}_resetTimeout(e){let r=this._timeoutInfo.get(e);if(!r)return!1;let a=Date.now()-r.startTime;if(r.maxTotalTimeout&&a>=r.maxTotalTimeout)throw this._timeoutInfo.delete(e),new Ae(Le.RequestTimeout,"Maximum total timeout exceeded",{maxTotalTimeout:r.maxTotalTimeout,totalElapsed:a});return clearTimeout(r.timeoutId),r.timeoutId=setTimeout(r.onTimeout,r.timeout),!0}_cleanupTimeout(e){let r=this._timeoutInfo.get(e);r&&(clearTimeout(r.timeoutId),this._timeoutInfo.delete(e))}async connect(e){var r,a,t;this._transport=e;let n=(r=this.transport)===null||r===void 0?void 0:r.onclose;this._transport.onclose=()=>{n?.(),this._onclose()};let o=(a=this.transport)===null||a===void 0?void 0:a.onerror;this._transport.onerror=l=>{o?.(l),this._onerror(l)};let i=(t=this._transport)===null||t===void 0?void 0:t.onmessage;this._transport.onmessage=(l,u)=>{i?.(l,u),Xs(l)||Un(l)?this._onresponse(l):Ln(l)?this._onrequest(l,u):Fn(l)?this._onnotification(l):this._onerror(new Error(`Unknown message type: ${JSON.stringify(l)}`))},await this._transport.start()}_onclose(){var e;let r=this._responseHandlers;this._responseHandlers=new Map,this._progressHandlers.clear(),this._pendingDebouncedNotifications.clear(),this._transport=void 0,(e=this.onclose)===null||e===void 0||e.call(this);let a=new Ae(Le.ConnectionClosed,"Connection closed");for(let t of r.values())t(a)}_onerror(e){var r;(r=this.onerror)===null||r===void 0||r.call(this,e)}_onnotification(e){var r;let a=(r=this._notificationHandlers.get(e.method))!==null&&r!==void 0?r:this.fallbackNotificationHandler;a!==void 0&&Promise.resolve().then(()=>a(e)).catch(t=>this._onerror(new Error(`Uncaught error in notification handler: ${t}`)))}_onrequest(e,r){var a,t;let n=(a=this._requestHandlers.get(e.method))!==null&&a!==void 0?a:this.fallbackRequestHandler,o=this._transport;if(n===void 0){o?.send({jsonrpc:"2.0",id:e.id,error:{code:Le.MethodNotFound,message:"Method not found"}}).catch(u=>this._onerror(new Error(`Failed to send an error response: ${u}`)));return}let i=new AbortController;this._requestHandlerAbortControllers.set(e.id,i);let l={signal:i.signal,sessionId:o?.sessionId,_meta:(t=e.params)===null||t===void 0?void 0:t._meta,sendNotification:u=>this.notification(u,{relatedRequestId:e.id}),sendRequest:(u,d,f)=>this.request(u,d,{...f,relatedRequestId:e.id}),authInfo:r?.authInfo,requestId:e.id,requestInfo:r?.requestInfo};Promise.resolve().then(()=>n(e,l)).then(u=>{if(!i.signal.aborted)return o?.send({result:u,jsonrpc:"2.0",id:e.id})},u=>{var d;if(!i.signal.aborted)return o?.send({jsonrpc:"2.0",id:e.id,error:{code:Number.isSafeInteger(u.code)?u.code:Le.InternalError,message:(d=u.message)!==null&&d!==void 0?d:"Internal error"}})}).catch(u=>this._onerror(new Error(`Failed to send response: ${u}`))).finally(()=>{this._requestHandlerAbortControllers.delete(e.id)})}_onprogress(e){let{progressToken:r,...a}=e.params,t=Number(r),n=this._progressHandlers.get(t);if(!n){this._onerror(new Error(`Received a progress notification for an unknown token: ${JSON.stringify(e)}`));return}let o=this._responseHandlers.get(t),i=this._timeoutInfo.get(t);if(i&&o&&i.resetTimeoutOnProgress)try{this._resetTimeout(t)}catch(l){o(l);return}n(a)}_onresponse(e){let r=Number(e.id),a=this._responseHandlers.get(r);if(a===void 0){this._onerror(new Error(`Received a response for an unknown message ID: ${JSON.stringify(e)}`));return}if(this._responseHandlers.delete(r),this._progressHandlers.delete(r),this._cleanupTimeout(r),Xs(e))a(e);else{let t=new Ae(e.error.code,e.error.message,e.error.data);a(t)}}get transport(){return this._transport}async close(){var e;await((e=this._transport)===null||e===void 0?void 0:e.close())}request(e,r,a){let{relatedRequestId:t,resumptionToken:n,onresumptiontoken:o}=a??{};return new Promise((i,l)=>{var u,d,f,m,p,g;if(!this._transport){l(new Error("Not connected"));return}((u=this._options)===null||u===void 0?void 0:u.enforceStrictCapabilities)===!0&&this.assertCapabilityForMethod(e.method),(d=a?.signal)===null||d===void 0||d.throwIfAborted();let y=this._requestMessageId++,v={...e,jsonrpc:"2.0",id:y};a?.onprogress&&(this._progressHandlers.set(y,a.onprogress),v.params={...e.params,_meta:{...((f=e.params)===null||f===void 0?void 0:f._meta)||{},progressToken:y}});let E=R=>{var x;this._responseHandlers.delete(y),this._progressHandlers.delete(y),this._cleanupTimeout(y),(x=this._transport)===null||x===void 0||x.send({jsonrpc:"2.0",method:"notifications/cancelled",params:{requestId:y,reason:String(R)}},{relatedRequestId:t,resumptionToken:n,onresumptiontoken:o}).catch(T=>this._onerror(new Error(`Failed to send cancellation: ${T}`))),l(R)};this._responseHandlers.set(y,R=>{var x;if(!(!((x=a?.signal)===null||x===void 0)&&x.aborted)){if(R instanceof Error)return l(R);try{let T=r.parse(R.result);i(T)}catch(T){l(T)}}}),(m=a?.signal)===null||m===void 0||m.addEventListener("abort",()=>{var R;E((R=a?.signal)===null||R===void 0?void 0:R.reason)});let w=(p=a?.timeout)!==null&&p!==void 0?p:rp,S=()=>E(new Ae(Le.RequestTimeout,"Request timed out",{timeout:w}));this._setupTimeout(y,w,a?.maxTotalTimeout,S,(g=a?.resetTimeoutOnProgress)!==null&&g!==void 0?g:!1),this._transport.send(v,{relatedRequestId:t,resumptionToken:n,onresumptiontoken:o}).catch(R=>{this._cleanupTimeout(y),l(R)})})}async notification(e,r){var a,t;if(!this._transport)throw new Error("Not connected");if(this.assertNotificationCapability(e.method),((t=(a=this._options)===null||a===void 0?void 0:a.debouncedNotificationMethods)!==null&&t!==void 0?t:[]).includes(e.method)&&!e.params&&!r?.relatedRequestId){if(this._pendingDebouncedNotifications.has(e.method))return;this._pendingDebouncedNotifications.add(e.method),Promise.resolve().then(()=>{var l;if(this._pendingDebouncedNotifications.delete(e.method),!this._transport)return;let u={...e,jsonrpc:"2.0"};(l=this._transport)===null||l===void 0||l.send(u,r).catch(d=>this._onerror(d))});return}let i={...e,jsonrpc:"2.0"};await this._transport.send(i,r)}setRequestHandler(e,r){let a=e.shape.method.value;this.assertRequestHandlerCapability(a),this._requestHandlers.set(a,(t,n)=>Promise.resolve(r(e.parse(t),n)))}removeRequestHandler(e){this._requestHandlers.delete(e)}assertCanSetRequestHandler(e){if(this._requestHandlers.has(e))throw new Error(`A request handler for ${e} already exists, which would be overridden`)}setNotificationHandler(e,r){this._notificationHandlers.set(e.shape.method.value,a=>Promise.resolve(r(e.parse(a))))}removeNotificationHandler(e){this._notificationHandlers.delete(e)}};function is(s,e){return Object.entries(e).reduce((r,[a,t])=>(t&&typeof t=="object"?r[a]=r[a]?{...r[a],...t}:t:r[a]=t,r),{...s})}var Wi=Mt(Ma(),1),ws=class extends br{constructor(e,r){var a;super(r),this._serverInfo=e,this._loggingLevels=new Map,this.LOG_LEVEL_SEVERITY=new Map(Fr.options.map((t,n)=>[t,n])),this.isMessageIgnored=(t,n)=>{let o=this._loggingLevels.get(n);return o?this.LOG_LEVEL_SEVERITY.get(t)<this.LOG_LEVEL_SEVERITY.get(o):!1},this._capabilities=(a=r?.capabilities)!==null&&a!==void 0?a:{},this._instructions=r?.instructions,this.setRequestHandler(Qs,t=>this._oninitialize(t)),this.setNotificationHandler(Ks,()=>{var t;return(t=this.oninitialized)===null||t===void 0?void 0:t.call(this)}),this._capabilities.logging&&this.setRequestHandler(ua,async(t,n)=>{var o;let i=n.sessionId||((o=n.requestInfo)===null||o===void 0?void 0:o.headers["mcp-session-id"])||void 0,{level:l}=t.params,u=Fr.safeParse(l);return u.success&&this._loggingLevels.set(i,u.data),{}})}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=is(this._capabilities,e)}assertCapabilityForMethod(e){var r,a,t;switch(e){case"sampling/createMessage":if(!(!((r=this._clientCapabilities)===null||r===void 0)&&r.sampling))throw new Error(`Client does not support sampling (required for ${e})`);break;case"elicitation/create":if(!(!((a=this._clientCapabilities)===null||a===void 0)&&a.elicitation))throw new Error(`Client does not support elicitation (required for ${e})`);break;case"roots/list":if(!(!((t=this._clientCapabilities)===null||t===void 0)&&t.roots))throw new Error(`Client does not support listing roots (required for ${e})`);break;case"ping":break}}assertNotificationCapability(e){switch(e){case"notifications/message":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"notifications/resources/updated":case"notifications/resources/list_changed":if(!this._capabilities.resources)throw new Error(`Server does not support notifying about resources (required for ${e})`);break;case"notifications/tools/list_changed":if(!this._capabilities.tools)throw new Error(`Server does not support notifying of tool list changes (required for ${e})`);break;case"notifications/prompts/list_changed":if(!this._capabilities.prompts)throw new Error(`Server does not support notifying of prompt list changes (required for ${e})`);break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Server does not support sampling (required for ${e})`);break;case"logging/setLevel":if(!this._capabilities.logging)throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!this._capabilities.prompts)throw new 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 new Error(`Server does not support resources (required for ${e})`);break;case"tools/call":case"tools/list":if(!this._capabilities.tools)throw new Error(`Server does not support tools (required for ${e})`);break;case"ping":case"initialize":break}}async _oninitialize(e){let r=e.params.protocolVersion;return this._clientCapabilities=e.params.capabilities,this._clientVersion=e.params.clientInfo,{protocolVersion:Jr.includes(r)?r:Cr,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"},Et)}async createMessage(e,r){return this.request({method:"sampling/createMessage",params:e},da,r)}async elicitInput(e,r){let a=await this.request({method:"elicitation/create",params:e},pa,r);if(a.action==="accept"&&a.content)try{let t=new Wi.default,n=t.compile(e.requestedSchema);if(!n(a.content))throw new Ae(Le.InvalidParams,`Elicitation response content does not match requested schema: ${t.errorsText(n.errors)}`)}catch(t){throw t instanceof Ae?t:new Ae(Le.InternalError,`Error validating elicitation response: ${t}`)}return a}async listRoots(e,r){return this.request({method:"roots/list",params:e},ha,r)}async sendLoggingMessage(e,r){if(this._capabilities.logging&&!this.isMessageIgnored(e.level,r))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"})}};var qa=Mt(require("node:process"),1);var Er=class{append(e){this._buffer=this._buffer?Buffer.concat([this._buffer,e]):e}readMessage(){if(!this._buffer)return null;let e=this._buffer.indexOf(`
|
|
`);if(e===-1)return null;let r=this._buffer.toString("utf8",0,e).replace(/\r$/,"");return this._buffer=this._buffer.subarray(e+1),Lf(r)}clear(){this._buffer=void 0}};function Lf(s){return Bn.parse(JSON.parse(s))}function Ps(s){return JSON.stringify(s)+`
|
|
`}var Os=class{constructor(e=qa.default.stdin,r=qa.default.stdout){this._stdin=e,this._stdout=r,this._readBuffer=new Er,this._started=!1,this._ondata=a=>{this._readBuffer.append(a),this.processReadBuffer()},this._onerror=a=>{var t;(t=this.onerror)===null||t===void 0||t.call(this,a)}}async start(){if(this._started)throw new 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(var e,r;;)try{let a=this._readBuffer.readMessage();if(a===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,a)}catch(a){(r=this.onerror)===null||r===void 0||r.call(this,a)}}async close(){var e;this._stdin.off("data",this._ondata),this._stdin.off("error",this._onerror),this._stdin.listenerCount("data")===0&&this._stdin.pause(),this._readBuffer.clear(),(e=this.onclose)===null||e===void 0||e.call(this)}send(e){return new Promise(r=>{let a=Ps(e);this._stdout.write(a)?r():this._stdout.once("drain",r)})}};var Ki=Mt(Ma(),1),Is=class extends br{constructor(e,r){var a;super(r),this._clientInfo=e,this._cachedToolOutputValidators=new Map,this._capabilities=(a=r?.capabilities)!==null&&a!==void 0?a:{},this._ajv=new Ki.default}registerCapabilities(e){if(this.transport)throw new Error("Cannot register capabilities after connecting to transport");this._capabilities=is(this._capabilities,e)}assertCapability(e,r){var a;if(!(!((a=this._serverCapabilities)===null||a===void 0)&&a[e]))throw new Error(`Server does not support ${e} (required for ${r})`)}async connect(e,r){if(await super.connect(e),e.sessionId===void 0)try{let a=await this.request({method:"initialize",params:{protocolVersion:Cr,capabilities:this._capabilities,clientInfo:this._clientInfo}},Ws,r);if(a===void 0)throw new Error(`Server sent invalid initialize result: ${a}`);if(!Jr.includes(a.protocolVersion))throw new Error(`Server's protocol version is not supported: ${a.protocolVersion}`);this._serverCapabilities=a.capabilities,this._serverVersion=a.serverInfo,e.setProtocolVersion&&e.setProtocolVersion(a.protocolVersion),this._instructions=a.instructions,await this.notification({method:"notifications/initialized"})}catch(a){throw this.close(),a}}getServerCapabilities(){return this._serverCapabilities}getServerVersion(){return this._serverVersion}getInstructions(){return this._instructions}assertCapabilityForMethod(e){var r,a,t,n,o;switch(e){case"logging/setLevel":if(!(!((r=this._serverCapabilities)===null||r===void 0)&&r.logging))throw new Error(`Server does not support logging (required for ${e})`);break;case"prompts/get":case"prompts/list":if(!(!((a=this._serverCapabilities)===null||a===void 0)&&a.prompts))throw new Error(`Server does not support prompts (required for ${e})`);break;case"resources/list":case"resources/templates/list":case"resources/read":case"resources/subscribe":case"resources/unsubscribe":if(!(!((t=this._serverCapabilities)===null||t===void 0)&&t.resources))throw new Error(`Server does not support resources (required for ${e})`);if(e==="resources/subscribe"&&!this._serverCapabilities.resources.subscribe)throw new Error(`Server does not support resource subscriptions (required for ${e})`);break;case"tools/call":case"tools/list":if(!(!((n=this._serverCapabilities)===null||n===void 0)&&n.tools))throw new Error(`Server does not support tools (required for ${e})`);break;case"completion/complete":if(!(!((o=this._serverCapabilities)===null||o===void 0)&&o.completions))throw new Error(`Server does not support completions (required for ${e})`);break;case"initialize":break;case"ping":break}}assertNotificationCapability(e){var r;switch(e){case"notifications/roots/list_changed":if(!(!((r=this._capabilities.roots)===null||r===void 0)&&r.listChanged))throw new Error(`Client does not support roots list changed notifications (required for ${e})`);break;case"notifications/initialized":break;case"notifications/cancelled":break;case"notifications/progress":break}}assertRequestHandlerCapability(e){switch(e){case"sampling/createMessage":if(!this._capabilities.sampling)throw new Error(`Client does not support sampling capability (required for ${e})`);break;case"elicitation/create":if(!this._capabilities.elicitation)throw new Error(`Client does not support elicitation capability (required for ${e})`);break;case"roots/list":if(!this._capabilities.roots)throw new Error(`Client does not support roots capability (required for ${e})`);break;case"ping":break}}async ping(e){return this.request({method:"ping"},Et,e)}async complete(e,r){return this.request({method:"completion/complete",params:e},fa,r)}async setLoggingLevel(e,r){return this.request({method:"logging/setLevel",params:{level:e}},Et,r)}async getPrompt(e,r){return this.request({method:"prompts/get",params:e},oa,r)}async listPrompts(e,r){return this.request({method:"prompts/list",params:e},ra,r)}async listResources(e,r){return this.request({method:"resources/list",params:e},Ys,r)}async listResourceTemplates(e,r){return this.request({method:"resources/templates/list",params:e},ea,r)}async readResource(e,r){return this.request({method:"resources/read",params:e},ta,r)}async subscribeResource(e,r){return this.request({method:"resources/subscribe",params:e},Et,r)}async unsubscribeResource(e,r){return this.request({method:"resources/unsubscribe",params:e},Et,r)}async callTool(e,r=os,a){let t=await this.request({method:"tools/call",params:e},r,a),n=this.getToolOutputValidator(e.name);if(n){if(!t.structuredContent&&!t.isError)throw new Ae(Le.InvalidRequest,`Tool ${e.name} has an output schema but did not return structured content`);if(t.structuredContent)try{if(!n(t.structuredContent))throw new Ae(Le.InvalidParams,`Structured content does not match the tool's output schema: ${this._ajv.errorsText(n.errors)}`)}catch(o){throw o instanceof Ae?o:new Ae(Le.InvalidParams,`Failed to validate structured content: ${o instanceof Error?o.message:String(o)}`)}}return t}cacheToolOutputSchemas(e){this._cachedToolOutputValidators.clear();for(let r of e)if(r.outputSchema)try{let a=this._ajv.compile(r.outputSchema);this._cachedToolOutputValidators.set(r.name,a)}catch{}}getToolOutputValidator(e){return this._cachedToolOutputValidators.get(e)}async listTools(e,r){let a=await this.request({method:"tools/list",params:e},ca,r);return this.cacheToolOutputSchemas(a.tools),a}async sendRootsListChanged(){return this.notification({method:"notifications/roots/list_changed"})}};var qc=Mt(Mc(),1),qr=Mt(require("node:process"),1),Uc=require("node:stream");var lh=qr.default.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE","PROGRAMFILES"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];function uh(){let s={};for(let e of lh){let r=qr.default.env[e];r!==void 0&&(r.startsWith("()")||(s[e]=r))}return s}var As=class{constructor(e){this._abortController=new AbortController,this._readBuffer=new Er,this._stderrStream=null,this._serverParams=e,(e.stderr==="pipe"||e.stderr==="overlapped")&&(this._stderrStream=new Uc.PassThrough)}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((e,r)=>{var a,t,n,o,i;this._process=(0,qc.default)(this._serverParams.command,(a=this._serverParams.args)!==null&&a!==void 0?a:[],{env:{...uh(),...this._serverParams.env},stdio:["pipe","pipe",(t=this._serverParams.stderr)!==null&&t!==void 0?t:"inherit"],shell:!1,signal:this._abortController.signal,windowsHide:qr.default.platform==="win32"&&dh(),cwd:this._serverParams.cwd}),this._process.on("error",l=>{var u,d;if(l.name==="AbortError"){(u=this.onclose)===null||u===void 0||u.call(this);return}r(l),(d=this.onerror)===null||d===void 0||d.call(this,l)}),this._process.on("spawn",()=>{e()}),this._process.on("close",l=>{var u;this._process=void 0,(u=this.onclose)===null||u===void 0||u.call(this)}),(n=this._process.stdin)===null||n===void 0||n.on("error",l=>{var u;(u=this.onerror)===null||u===void 0||u.call(this,l)}),(o=this._process.stdout)===null||o===void 0||o.on("data",l=>{this._readBuffer.append(l),this.processReadBuffer()}),(i=this._process.stdout)===null||i===void 0||i.on("error",l=>{var u;(u=this.onerror)===null||u===void 0||u.call(this,l)}),this._stderrStream&&this._process.stderr&&this._process.stderr.pipe(this._stderrStream)})}get stderr(){var e,r;return this._stderrStream?this._stderrStream:(r=(e=this._process)===null||e===void 0?void 0:e.stderr)!==null&&r!==void 0?r:null}get pid(){var e,r;return(r=(e=this._process)===null||e===void 0?void 0:e.pid)!==null&&r!==void 0?r:null}processReadBuffer(){for(var e,r;;)try{let a=this._readBuffer.readMessage();if(a===null)break;(e=this.onmessage)===null||e===void 0||e.call(this,a)}catch(a){(r=this.onerror)===null||r===void 0||r.call(this,a)}}async close(){this._abortController.abort(),this._process=void 0,this._readBuffer.clear()}send(e){return new Promise(r=>{var a;if(!(!((a=this._process)===null||a===void 0)&&a.stdin))throw new Error("Not connected");let t=Ps(e);this._process.stdin.write(t)?r():this._process.stdin.once("drain",r)})}};function dh(){return"type"in qr.default}var Vc=Symbol("Let zodToJsonSchema decide on which parser to use");var Bc={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"},Hc=s=>typeof s=="string"?{...Bc,name:s}:{...Bc,...s};var zc=s=>{let e=Hc(s),r=e.name!==void 0?[...e.basePath,e.definitionPath,e.name]:e.basePath;return{...e,flags:{hasReferencedOpenAiAnyType:!1},currentPath:r,propertyPath:void 0,seen:new Map(Object.entries(e.definitions).map(([a,t])=>[t._def,{def:t._def,path:[...e.basePath,e.definitionPath,a],jsonSchema:void 0}]))}};function Wa(s,e,r,a){a?.errorMessages&&r&&(s.errorMessage={...s.errorMessage,[e]:r})}function re(s,e,r,a,t){s[e]=r,Wa(s,e,a,t)}var Ns=(s,e)=>{let r=0;for(;r<s.length&&r<e.length&&s[r]===e[r];r++);return[(s.length-r).toString(),...e.slice(r)].join("/")};function he(s){if(s.target!=="openAi")return{};let e=[...s.basePath,s.definitionPath,s.openAiAnyTypeName];return s.flags.hasReferencedOpenAiAnyType=!0,{$ref:s.$refStrategy==="relative"?Ns(e,s.currentPath):e.join("/")}}function Zc(s,e){let r={type:"array"};return s.type?._def&&s.type?._def?.typeName!==L.ZodAny&&(r.items=G(s.type._def,{...e,currentPath:[...e.currentPath,"items"]})),s.minLength&&re(r,"minItems",s.minLength.value,s.minLength.message,e),s.maxLength&&re(r,"maxItems",s.maxLength.value,s.maxLength.message,e),s.exactLength&&(re(r,"minItems",s.exactLength.value,s.exactLength.message,e),re(r,"maxItems",s.exactLength.value,s.exactLength.message,e)),r}function Gc(s,e){let r={type:"integer",format:"int64"};if(!s.checks)return r;for(let a of s.checks)switch(a.kind){case"min":e.target==="jsonSchema7"?a.inclusive?re(r,"minimum",a.value,a.message,e):re(r,"exclusiveMinimum",a.value,a.message,e):(a.inclusive||(r.exclusiveMinimum=!0),re(r,"minimum",a.value,a.message,e));break;case"max":e.target==="jsonSchema7"?a.inclusive?re(r,"maximum",a.value,a.message,e):re(r,"exclusiveMaximum",a.value,a.message,e):(a.inclusive||(r.exclusiveMaximum=!0),re(r,"maximum",a.value,a.message,e));break;case"multipleOf":re(r,"multipleOf",a.value,a.message,e);break}return r}function Xc(){return{type:"boolean"}}function Ds(s,e){return G(s.type._def,e)}var Qc=(s,e)=>G(s.innerType._def,e);function Ka(s,e,r){let a=r??e.dateStrategy;if(Array.isArray(a))return{anyOf:a.map((t,n)=>Ka(s,e,t))};switch(a){case"string":case"format:date-time":return{type:"string",format:"date-time"};case"format:date":return{type:"string",format:"date"};case"integer":return ph(s,e)}}var ph=(s,e)=>{let r={type:"integer",format:"unix-time"};if(e.target==="openApi3")return r;for(let a of s.checks)switch(a.kind){case"min":re(r,"minimum",a.value,a.message,e);break;case"max":re(r,"maximum",a.value,a.message,e);break}return r};function Wc(s,e){return{...G(s.innerType._def,e),default:s.defaultValue()}}function Kc(s,e){return e.effectStrategy==="input"?G(s.schema._def,e):he(e)}function Jc(s){return{type:"string",enum:Array.from(s.values)}}var fh=s=>"type"in s&&s.type==="string"?!1:"allOf"in s;function Yc(s,e){let r=[G(s.left._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),G(s.right._def,{...e,currentPath:[...e.currentPath,"allOf","1"]})].filter(n=>!!n),a=e.target==="jsonSchema2019-09"?{unevaluatedProperties:!1}:void 0,t=[];return r.forEach(n=>{if(fh(n))t.push(...n.allOf),n.unevaluatedProperties===void 0&&(a=void 0);else{let o=n;if("additionalProperties"in n&&n.additionalProperties===!1){let{additionalProperties:i,...l}=n;o=l}else a=void 0;t.push(o)}}),t.length?{allOf:t,...a}:void 0}function el(s,e){let r=typeof s.value;return r!=="bigint"&&r!=="number"&&r!=="boolean"&&r!=="string"?{type:Array.isArray(s.value)?"array":"object"}:e.target==="openApi3"?{type:r==="bigint"?"integer":r,enum:[s.value]}:{type:r==="bigint"?"integer":r,const:s.value}}var Ja,rt={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:()=>(Ja===void 0&&(Ja=RegExp("^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$","u")),Ja),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 Cs(s,e){let r={type:"string"};if(s.checks)for(let a of s.checks)switch(a.kind){case"min":re(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,a.value):a.value,a.message,e);break;case"max":re(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,a.value):a.value,a.message,e);break;case"email":switch(e.emailStrategy){case"format:email":st(r,"email",a.message,e);break;case"format:idn-email":st(r,"idn-email",a.message,e);break;case"pattern:zod":je(r,rt.email,a.message,e);break}break;case"url":st(r,"uri",a.message,e);break;case"uuid":st(r,"uuid",a.message,e);break;case"regex":je(r,a.regex,a.message,e);break;case"cuid":je(r,rt.cuid,a.message,e);break;case"cuid2":je(r,rt.cuid2,a.message,e);break;case"startsWith":je(r,RegExp(`^${Ya(a.value,e)}`),a.message,e);break;case"endsWith":je(r,RegExp(`${Ya(a.value,e)}$`),a.message,e);break;case"datetime":st(r,"date-time",a.message,e);break;case"date":st(r,"date",a.message,e);break;case"time":st(r,"time",a.message,e);break;case"duration":st(r,"duration",a.message,e);break;case"length":re(r,"minLength",typeof r.minLength=="number"?Math.max(r.minLength,a.value):a.value,a.message,e),re(r,"maxLength",typeof r.maxLength=="number"?Math.min(r.maxLength,a.value):a.value,a.message,e);break;case"includes":{je(r,RegExp(Ya(a.value,e)),a.message,e);break}case"ip":{a.version!=="v6"&&st(r,"ipv4",a.message,e),a.version!=="v4"&&st(r,"ipv6",a.message,e);break}case"base64url":je(r,rt.base64url,a.message,e);break;case"jwt":je(r,rt.jwt,a.message,e);break;case"cidr":{a.version!=="v6"&&je(r,rt.ipv4Cidr,a.message,e),a.version!=="v4"&&je(r,rt.ipv6Cidr,a.message,e);break}case"emoji":je(r,rt.emoji(),a.message,e);break;case"ulid":{je(r,rt.ulid,a.message,e);break}case"base64":{switch(e.base64Strategy){case"format:binary":{st(r,"binary",a.message,e);break}case"contentEncoding:base64":{re(r,"contentEncoding","base64",a.message,e);break}case"pattern:zod":{je(r,rt.base64,a.message,e);break}}break}case"nanoid":je(r,rt.nanoid,a.message,e);case"toLowerCase":case"toUpperCase":case"trim":break;default:}return r}function Ya(s,e){return e.patternStrategy==="escape"?mh(s):s}var hh=new Set("ABCDEFGHIJKLMNOPQRSTUVXYZabcdefghijklmnopqrstuvxyz0123456789");function mh(s){let e="";for(let r=0;r<s.length;r++)hh.has(s[r])||(e+="\\"),e+=s[r];return e}function st(s,e,r,a){s.format||s.anyOf?.some(t=>t.format)?(s.anyOf||(s.anyOf=[]),s.format&&(s.anyOf.push({format:s.format,...s.errorMessage&&a.errorMessages&&{errorMessage:{format:s.errorMessage.format}}}),delete s.format,s.errorMessage&&(delete s.errorMessage.format,Object.keys(s.errorMessage).length===0&&delete s.errorMessage)),s.anyOf.push({format:e,...r&&a.errorMessages&&{errorMessage:{format:r}}})):re(s,"format",e,r,a)}function je(s,e,r,a){s.pattern||s.allOf?.some(t=>t.pattern)?(s.allOf||(s.allOf=[]),s.pattern&&(s.allOf.push({pattern:s.pattern,...s.errorMessage&&a.errorMessages&&{errorMessage:{pattern:s.errorMessage.pattern}}}),delete s.pattern,s.errorMessage&&(delete s.errorMessage.pattern,Object.keys(s.errorMessage).length===0&&delete s.errorMessage)),s.allOf.push({pattern:tl(e,a),...r&&a.errorMessages&&{errorMessage:{pattern:r}}})):re(s,"pattern",tl(e,a),r,a)}function tl(s,e){if(!e.applyRegexFlags||!s.flags)return s.source;let r={i:s.flags.includes("i"),m:s.flags.includes("m"),s:s.flags.includes("s")},a=r.i?s.source.toLowerCase():s.source,t="",n=!1,o=!1,i=!1;for(let l=0;l<a.length;l++){if(n){t+=a[l],n=!1;continue}if(r.i){if(o){if(a[l].match(/[a-z]/)){i?(t+=a[l],t+=`${a[l-2]}-${a[l]}`.toUpperCase(),i=!1):a[l+1]==="-"&&a[l+2]?.match(/[a-z]/)?(t+=a[l],i=!0):t+=`${a[l]}${a[l].toUpperCase()}`;continue}}else if(a[l].match(/[a-z]/)){t+=`[${a[l]}${a[l].toUpperCase()}]`;continue}}if(r.m){if(a[l]==="^"){t+=`(^|(?<=[\r
|
|
]))`;continue}else if(a[l]==="$"){t+=`($|(?=[\r
|
|
]))`;continue}}if(r.s&&a[l]==="."){t+=o?`${a[l]}\r
|
|
`:`[${a[l]}\r
|
|
]`;continue}t+=a[l],a[l]==="\\"?n=!0:o&&a[l]==="]"?o=!1:!o&&a[l]==="["&&(o=!0)}try{new RegExp(t)}catch{return console.warn(`Could not convert regex pattern at ${e.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),s.source}return t}function ks(s,e){if(e.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),e.target==="openApi3"&&s.keyType?._def.typeName===L.ZodEnum)return{type:"object",required:s.keyType._def.values,properties:s.keyType._def.values.reduce((a,t)=>({...a,[t]:G(s.valueType._def,{...e,currentPath:[...e.currentPath,"properties",t]})??he(e)}),{}),additionalProperties:e.rejectedAdditionalProperties};let r={type:"object",additionalProperties:G(s.valueType._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]})??e.allowedAdditionalProperties};if(e.target==="openApi3")return r;if(s.keyType?._def.typeName===L.ZodString&&s.keyType._def.checks?.length){let{type:a,...t}=Cs(s.keyType._def,e);return{...r,propertyNames:t}}else{if(s.keyType?._def.typeName===L.ZodEnum)return{...r,propertyNames:{enum:s.keyType._def.values}};if(s.keyType?._def.typeName===L.ZodBranded&&s.keyType._def.type._def.typeName===L.ZodString&&s.keyType._def.type._def.checks?.length){let{type:a,...t}=Ds(s.keyType._def,e);return{...r,propertyNames:t}}}return r}function rl(s,e){if(e.mapStrategy==="record")return ks(s,e);let r=G(s.keyType._def,{...e,currentPath:[...e.currentPath,"items","items","0"]})||he(e),a=G(s.valueType._def,{...e,currentPath:[...e.currentPath,"items","items","1"]})||he(e);return{type:"array",maxItems:125,items:{type:"array",items:[r,a],minItems:2,maxItems:2}}}function sl(s){let e=s.values,a=Object.keys(s.values).filter(n=>typeof e[e[n]]!="number").map(n=>e[n]),t=Array.from(new Set(a.map(n=>typeof n)));return{type:t.length===1?t[0]==="string"?"string":"number":["string","number"],enum:a}}function al(s){return s.target==="openAi"?void 0:{not:he({...s,currentPath:[...s.currentPath,"not"]})}}function nl(s){return s.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}var Ur={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function il(s,e){if(e.target==="openApi3")return ol(s,e);let r=s.options instanceof Map?Array.from(s.options.values()):s.options;if(r.every(a=>a._def.typeName in Ur&&(!a._def.checks||!a._def.checks.length))){let a=r.reduce((t,n)=>{let o=Ur[n._def.typeName];return o&&!t.includes(o)?[...t,o]:t},[]);return{type:a.length>1?a:a[0]}}else if(r.every(a=>a._def.typeName==="ZodLiteral"&&!a.description)){let a=r.reduce((t,n)=>{let o=typeof n._def.value;switch(o){case"string":case"number":case"boolean":return[...t,o];case"bigint":return[...t,"integer"];case"object":if(n._def.value===null)return[...t,"null"];case"symbol":case"undefined":case"function":default:return t}},[]);if(a.length===r.length){let t=a.filter((n,o,i)=>i.indexOf(n)===o);return{type:t.length>1?t:t[0],enum:r.reduce((n,o)=>n.includes(o._def.value)?n:[...n,o._def.value],[])}}}else if(r.every(a=>a._def.typeName==="ZodEnum"))return{type:"string",enum:r.reduce((a,t)=>[...a,...t._def.values.filter(n=>!a.includes(n))],[])};return ol(s,e)}var ol=(s,e)=>{let r=(s.options instanceof Map?Array.from(s.options.values()):s.options).map((a,t)=>G(a._def,{...e,currentPath:[...e.currentPath,"anyOf",`${t}`]})).filter(a=>!!a&&(!e.strictUnions||typeof a=="object"&&Object.keys(a).length>0));return r.length?{anyOf:r}:void 0};function cl(s,e){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(s.innerType._def.typeName)&&(!s.innerType._def.checks||!s.innerType._def.checks.length))return e.target==="openApi3"?{type:Ur[s.innerType._def.typeName],nullable:!0}:{type:[Ur[s.innerType._def.typeName],"null"]};if(e.target==="openApi3"){let a=G(s.innerType._def,{...e,currentPath:[...e.currentPath]});return a&&"$ref"in a?{allOf:[a],nullable:!0}:a&&{...a,nullable:!0}}let r=G(s.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","0"]});return r&&{anyOf:[r,{type:"null"}]}}function ll(s,e){let r={type:"number"};if(!s.checks)return r;for(let a of s.checks)switch(a.kind){case"int":r.type="integer",Wa(r,"type",a.message,e);break;case"min":e.target==="jsonSchema7"?a.inclusive?re(r,"minimum",a.value,a.message,e):re(r,"exclusiveMinimum",a.value,a.message,e):(a.inclusive||(r.exclusiveMinimum=!0),re(r,"minimum",a.value,a.message,e));break;case"max":e.target==="jsonSchema7"?a.inclusive?re(r,"maximum",a.value,a.message,e):re(r,"exclusiveMaximum",a.value,a.message,e):(a.inclusive||(r.exclusiveMaximum=!0),re(r,"maximum",a.value,a.message,e));break;case"multipleOf":re(r,"multipleOf",a.value,a.message,e);break}return r}function ul(s,e){let r=e.target==="openAi",a={type:"object",properties:{}},t=[],n=s.shape();for(let i in n){let l=n[i];if(l===void 0||l._def===void 0)continue;let u=gh(l);u&&r&&(l._def.typeName==="ZodOptional"&&(l=l._def.innerType),l.isNullable()||(l=l.nullable()),u=!1);let d=G(l._def,{...e,currentPath:[...e.currentPath,"properties",i],propertyPath:[...e.currentPath,"properties",i]});d!==void 0&&(a.properties[i]=d,u||t.push(i))}t.length&&(a.required=t);let o=vh(s,e);return o!==void 0&&(a.additionalProperties=o),a}function vh(s,e){if(s.catchall._def.typeName!=="ZodNever")return G(s.catchall._def,{...e,currentPath:[...e.currentPath,"additionalProperties"]});switch(s.unknownKeys){case"passthrough":return e.allowedAdditionalProperties;case"strict":return e.rejectedAdditionalProperties;case"strip":return e.removeAdditionalStrategy==="strict"?e.allowedAdditionalProperties:e.rejectedAdditionalProperties}}function gh(s){try{return s.isOptional()}catch{return!0}}var dl=(s,e)=>{if(e.currentPath.toString()===e.propertyPath?.toString())return G(s.innerType._def,e);let r=G(s.innerType._def,{...e,currentPath:[...e.currentPath,"anyOf","1"]});return r?{anyOf:[{not:he(e)},r]}:he(e)};var pl=(s,e)=>{if(e.pipeStrategy==="input")return G(s.in._def,e);if(e.pipeStrategy==="output")return G(s.out._def,e);let r=G(s.in._def,{...e,currentPath:[...e.currentPath,"allOf","0"]}),a=G(s.out._def,{...e,currentPath:[...e.currentPath,"allOf",r?"1":"0"]});return{allOf:[r,a].filter(t=>t!==void 0)}};function fl(s,e){return G(s.type._def,e)}function hl(s,e){let a={type:"array",uniqueItems:!0,items:G(s.valueType._def,{...e,currentPath:[...e.currentPath,"items"]})};return s.minSize&&re(a,"minItems",s.minSize.value,s.minSize.message,e),s.maxSize&&re(a,"maxItems",s.maxSize.value,s.maxSize.message,e),a}function ml(s,e){return s.rest?{type:"array",minItems:s.items.length,items:s.items.map((r,a)=>G(r._def,{...e,currentPath:[...e.currentPath,"items",`${a}`]})).reduce((r,a)=>a===void 0?r:[...r,a],[]),additionalItems:G(s.rest._def,{...e,currentPath:[...e.currentPath,"additionalItems"]})}:{type:"array",minItems:s.items.length,maxItems:s.items.length,items:s.items.map((r,a)=>G(r._def,{...e,currentPath:[...e.currentPath,"items",`${a}`]})).reduce((r,a)=>a===void 0?r:[...r,a],[])}}function vl(s){return{not:he(s)}}function gl(s){return he(s)}var yl=(s,e)=>G(s.innerType._def,e);var _l=(s,e,r)=>{switch(e){case L.ZodString:return Cs(s,r);case L.ZodNumber:return ll(s,r);case L.ZodObject:return ul(s,r);case L.ZodBigInt:return Gc(s,r);case L.ZodBoolean:return Xc();case L.ZodDate:return Ka(s,r);case L.ZodUndefined:return vl(r);case L.ZodNull:return nl(r);case L.ZodArray:return Zc(s,r);case L.ZodUnion:case L.ZodDiscriminatedUnion:return il(s,r);case L.ZodIntersection:return Yc(s,r);case L.ZodTuple:return ml(s,r);case L.ZodRecord:return ks(s,r);case L.ZodLiteral:return el(s,r);case L.ZodEnum:return Jc(s);case L.ZodNativeEnum:return sl(s);case L.ZodNullable:return cl(s,r);case L.ZodOptional:return dl(s,r);case L.ZodMap:return rl(s,r);case L.ZodSet:return hl(s,r);case L.ZodLazy:return()=>s.getter()._def;case L.ZodPromise:return fl(s,r);case L.ZodNaN:case L.ZodNever:return al(r);case L.ZodEffects:return Kc(s,r);case L.ZodAny:return he(r);case L.ZodUnknown:return gl(r);case L.ZodDefault:return Wc(s,r);case L.ZodBranded:return Ds(s,r);case L.ZodReadonly:return yl(s,r);case L.ZodCatch:return Qc(s,r);case L.ZodPipeline:return pl(s,r);case L.ZodFunction:case L.ZodVoid:case L.ZodSymbol:return;default:return(a=>{})(e)}};function G(s,e,r=!1){let a=e.seen.get(s);if(e.override){let i=e.override?.(s,e,a,r);if(i!==Vc)return i}if(a&&!r){let i=yh(a,e);if(i!==void 0)return i}let t={def:s,path:e.currentPath,jsonSchema:void 0};e.seen.set(s,t);let n=_l(s,s.typeName,e),o=typeof n=="function"?G(n(),e):n;if(o&&_h(s,e,o),e.postProcess){let i=e.postProcess(o,s,e);return t.jsonSchema=o,i}return t.jsonSchema=o,o}var yh=(s,e)=>{switch(e.$refStrategy){case"root":return{$ref:s.path.join("/")};case"relative":return{$ref:Ns(e.currentPath,s.path)};case"none":case"seen":return s.path.length<e.currentPath.length&&s.path.every((r,a)=>e.currentPath[a]===r)?(console.warn(`Recursive reference detected at ${e.currentPath.join("/")}! Defaulting to any`),he(e)):e.$refStrategy==="seen"?he(e):void 0}},_h=(s,e,r)=>(s.description&&(r.description=s.description,e.markdownDescription&&(r.markdownDescription=s.description)),r);var en=(s,e)=>{let r=zc(e),a=typeof e=="object"&&e.definitions?Object.entries(e.definitions).reduce((l,[u,d])=>({...l,[u]:G(d._def,{...r,currentPath:[...r.basePath,r.definitionPath,u]},!0)??he(r)}),{}):void 0,t=typeof e=="string"?e:e?.nameStrategy==="title"?void 0:e?.name,n=G(s._def,t===void 0?r:{...r,currentPath:[...r.basePath,r.definitionPath,t]},!1)??he(r),o=typeof e=="object"&&e.name!==void 0&&e.nameStrategy==="title"?e.name:void 0;o!==void 0&&(n.title=o),r.flags.hasReferencedOpenAiAnyType&&(a||(a={}),a[r.openAiAnyTypeName]||(a[r.openAiAnyTypeName]={type:["string","number","integer","boolean","array","null"],items:{$ref:r.$refStrategy==="relative"?"1":[...r.basePath,r.definitionPath,r.openAiAnyTypeName].join("/")}}));let i=t===void 0?a?{...n,[r.definitionPath]:a}:n:{$ref:[...r.$refStrategy==="relative"?[]:r.basePath,r.definitionPath,t].join("/"),[r.definitionPath]:{...a,[t]:n}};return r.target==="jsonSchema7"?i.$schema="http://json-schema.org/draft-07/schema#":(r.target==="jsonSchema2019-09"||r.target==="openAi")&&(i.$schema="https://json-schema.org/draft/2019-09/schema#"),r.target==="openAi"&&("anyOf"in i||"oneOf"in i||"allOf"in i||"type"in i&&Array.isArray(i.type))&&console.warn("Warning: OpenAI may not support schemas with unions as roots! Try wrapping it in an object property."),i};var $l=require("path");var Sl=Mt(require("better-sqlite3"),1);var Ne=require("path"),tn=require("os"),rn=require("fs");var bl=require("url"),Eh={};function bh(){return typeof __dirname<"u"?__dirname:(0,Ne.dirname)((0,bl.fileURLToPath)(Eh.url))}var P_=bh(),at=process.env.CLAUDE_MEM_DATA_DIR||(0,Ne.join)((0,tn.homedir)(),".claude-mem"),sn=process.env.CLAUDE_CONFIG_DIR||(0,Ne.join)((0,tn.homedir)(),".claude"),O_=(0,Ne.join)(at,"archives"),I_=(0,Ne.join)(at,"logs"),$_=(0,Ne.join)(at,"trash"),A_=(0,Ne.join)(at,"backups"),N_=(0,Ne.join)(at,"settings.json"),Ls=(0,Ne.join)(at,"claude-mem.db"),El=(0,Ne.join)(at,"vector-db"),D_=(0,Ne.join)(sn,"settings.json"),C_=(0,Ne.join)(sn,"commands"),k_=(0,Ne.join)(sn,"CLAUDE.md");function js(s){(0,rn.mkdirSync)(s,{recursive:!0})}var Fs=class{db;constructor(e){e||(js(at),e=Ls),this.db=new Sl.default(e),this.db.pragma("journal_mode = WAL"),this.ensureFTSTables()}ensureFTSTables(){try{if(this.db.prepare("SELECT name FROM sqlite_master WHERE type='table' AND name LIKE '%_fts'").all().some(a=>a.name==="observations_fts"||a.name==="session_summaries_fts"))return;console.error("[SessionSearch] Creating FTS5 tables..."),this.db.exec(`
|
|
CREATE VIRTUAL TABLE IF NOT EXISTS observations_fts USING fts5(
|
|
title,
|
|
subtitle,
|
|
narrative,
|
|
text,
|
|
facts,
|
|
concepts,
|
|
content='observations',
|
|
content_rowid='id'
|
|
);
|
|
`),this.db.exec(`
|
|
INSERT INTO observations_fts(rowid, title, subtitle, narrative, text, facts, concepts)
|
|
SELECT id, title, subtitle, narrative, text, facts, concepts
|
|
FROM observations;
|
|
`),this.db.exec(`
|
|
CREATE TRIGGER IF NOT EXISTS observations_ai AFTER INSERT ON observations BEGIN
|
|
INSERT INTO observations_fts(rowid, title, subtitle, narrative, text, facts, concepts)
|
|
VALUES (new.id, new.title, new.subtitle, new.narrative, new.text, new.facts, new.concepts);
|
|
END;
|
|
|
|
CREATE TRIGGER IF NOT EXISTS observations_ad AFTER DELETE ON observations BEGIN
|
|
INSERT INTO observations_fts(observations_fts, rowid, title, subtitle, narrative, text, facts, concepts)
|
|
VALUES('delete', old.id, old.title, old.subtitle, old.narrative, old.text, old.facts, old.concepts);
|
|
END;
|
|
|
|
CREATE TRIGGER IF NOT EXISTS observations_au AFTER UPDATE ON observations BEGIN
|
|
INSERT INTO observations_fts(observations_fts, rowid, title, subtitle, narrative, text, facts, concepts)
|
|
VALUES('delete', old.id, old.title, old.subtitle, old.narrative, old.text, old.facts, old.concepts);
|
|
INSERT INTO observations_fts(rowid, title, subtitle, narrative, text, facts, concepts)
|
|
VALUES (new.id, new.title, new.subtitle, new.narrative, new.text, new.facts, new.concepts);
|
|
END;
|
|
`),this.db.exec(`
|
|
CREATE VIRTUAL TABLE IF NOT EXISTS session_summaries_fts USING fts5(
|
|
request,
|
|
investigated,
|
|
learned,
|
|
completed,
|
|
next_steps,
|
|
notes,
|
|
content='session_summaries',
|
|
content_rowid='id'
|
|
);
|
|
`),this.db.exec(`
|
|
INSERT INTO session_summaries_fts(rowid, request, investigated, learned, completed, next_steps, notes)
|
|
SELECT id, request, investigated, learned, completed, next_steps, notes
|
|
FROM session_summaries;
|
|
`),this.db.exec(`
|
|
CREATE TRIGGER IF NOT EXISTS session_summaries_ai AFTER INSERT ON session_summaries BEGIN
|
|
INSERT INTO session_summaries_fts(rowid, request, investigated, learned, completed, next_steps, notes)
|
|
VALUES (new.id, new.request, new.investigated, new.learned, new.completed, new.next_steps, new.notes);
|
|
END;
|
|
|
|
CREATE TRIGGER IF NOT EXISTS session_summaries_ad AFTER DELETE ON session_summaries BEGIN
|
|
INSERT INTO session_summaries_fts(session_summaries_fts, rowid, request, investigated, learned, completed, next_steps, notes)
|
|
VALUES('delete', old.id, old.request, old.investigated, old.learned, old.completed, old.next_steps, old.notes);
|
|
END;
|
|
|
|
CREATE TRIGGER IF NOT EXISTS session_summaries_au AFTER UPDATE ON session_summaries BEGIN
|
|
INSERT INTO session_summaries_fts(session_summaries_fts, rowid, request, investigated, learned, completed, next_steps, notes)
|
|
VALUES('delete', old.id, old.request, old.investigated, old.learned, old.completed, old.next_steps, old.notes);
|
|
INSERT INTO session_summaries_fts(rowid, request, investigated, learned, completed, next_steps, notes)
|
|
VALUES (new.id, new.request, new.investigated, new.learned, new.completed, new.next_steps, new.notes);
|
|
END;
|
|
`),console.error("[SessionSearch] FTS5 tables created successfully")}catch(e){console.error("[SessionSearch] FTS migration error:",e.message)}}buildFilterClause(e,r,a="o"){let t=[];if(e.project&&(t.push(`${a}.project = ?`),r.push(e.project)),e.type)if(Array.isArray(e.type)){let n=e.type.map(()=>"?").join(",");t.push(`${a}.type IN (${n})`),r.push(...e.type)}else t.push(`${a}.type = ?`),r.push(e.type);if(e.dateRange){let{start:n,end:o}=e.dateRange;if(n){let i=typeof n=="number"?n:new Date(n).getTime();t.push(`${a}.created_at_epoch >= ?`),r.push(i)}if(o){let i=typeof o=="number"?o:new Date(o).getTime();t.push(`${a}.created_at_epoch <= ?`),r.push(i)}}if(e.concepts){let n=Array.isArray(e.concepts)?e.concepts:[e.concepts],o=n.map(()=>`EXISTS (SELECT 1 FROM json_each(${a}.concepts) WHERE value = ?)`);o.length>0&&(t.push(`(${o.join(" OR ")})`),r.push(...n))}if(e.files){let n=Array.isArray(e.files)?e.files:[e.files],o=n.map(()=>`(
|
|
EXISTS (SELECT 1 FROM json_each(${a}.files_read) WHERE value LIKE ?)
|
|
OR EXISTS (SELECT 1 FROM json_each(${a}.files_modified) WHERE value LIKE ?)
|
|
)`);o.length>0&&(t.push(`(${o.join(" OR ")})`),n.forEach(i=>{r.push(`%${i}%`,`%${i}%`)}))}return t.length>0?t.join(" AND "):""}buildOrderClause(e="relevance",r=!0,a="observations_fts"){switch(e){case"relevance":return r?`ORDER BY ${a}.rank ASC`:"ORDER BY o.created_at_epoch DESC";case"date_desc":return"ORDER BY o.created_at_epoch DESC";case"date_asc":return"ORDER BY o.created_at_epoch ASC";default:return"ORDER BY o.created_at_epoch DESC"}}searchObservations(e,r={}){let a=[],{limit:t=50,offset:n=0,orderBy:o="relevance",...i}=r;if(!e){let l=this.buildFilterClause(i,a,"o");if(!l)throw new Error("Either query or filters required for search");let u=this.buildOrderClause(o,!1),d=`
|
|
SELECT o.*, o.discovery_tokens
|
|
FROM observations o
|
|
WHERE ${l}
|
|
${u}
|
|
LIMIT ? OFFSET ?
|
|
`;return a.push(t,n),this.db.prepare(d).all(...a)}return console.warn("[SessionSearch] Text search not supported - use ChromaDB for vector search"),[]}searchSessions(e,r={}){let a=[],{limit:t=50,offset:n=0,orderBy:o="relevance",...i}=r;if(!e){let l={...i};delete l.type;let u=this.buildFilterClause(l,a,"s");if(!u)throw new Error("Either query or filters required for search");let f=`
|
|
SELECT s.*, s.discovery_tokens
|
|
FROM session_summaries s
|
|
WHERE ${u}
|
|
${o==="date_asc"?"ORDER BY s.created_at_epoch ASC":"ORDER BY s.created_at_epoch DESC"}
|
|
LIMIT ? OFFSET ?
|
|
`;return a.push(t,n),this.db.prepare(f).all(...a)}return console.warn("[SessionSearch] Text search not supported - use ChromaDB for vector search"),[]}findByConcept(e,r={}){let a=[],{limit:t=50,offset:n=0,orderBy:o="date_desc",...i}=r,l={...i,concepts:e},u=this.buildFilterClause(l,a,"o"),d=this.buildOrderClause(o,!1),f=`
|
|
SELECT o.*, o.discovery_tokens
|
|
FROM observations o
|
|
WHERE ${u}
|
|
${d}
|
|
LIMIT ? OFFSET ?
|
|
`;return a.push(t,n),this.db.prepare(f).all(...a)}findByFile(e,r={}){let a=[],{limit:t=50,offset:n=0,orderBy:o="date_desc",...i}=r,l={...i,files:e},u=this.buildFilterClause(l,a,"o"),d=this.buildOrderClause(o,!1),f=`
|
|
SELECT o.*, o.discovery_tokens
|
|
FROM observations o
|
|
WHERE ${u}
|
|
${d}
|
|
LIMIT ? OFFSET ?
|
|
`;a.push(t,n);let m=this.db.prepare(f).all(...a),p=[],g={...i};delete g.type;let y=[];if(g.project&&(y.push("s.project = ?"),p.push(g.project)),g.dateRange){let{start:w,end:S}=g.dateRange;if(w){let R=typeof w=="number"?w:new Date(w).getTime();y.push("s.created_at_epoch >= ?"),p.push(R)}if(S){let R=typeof S=="number"?S:new Date(S).getTime();y.push("s.created_at_epoch <= ?"),p.push(R)}}y.push(`(
|
|
EXISTS (SELECT 1 FROM json_each(s.files_read) WHERE value LIKE ?)
|
|
OR EXISTS (SELECT 1 FROM json_each(s.files_edited) WHERE value LIKE ?)
|
|
)`),p.push(`%${e}%`,`%${e}%`);let v=`
|
|
SELECT s.*, s.discovery_tokens
|
|
FROM session_summaries s
|
|
WHERE ${y.join(" AND ")}
|
|
ORDER BY s.created_at_epoch DESC
|
|
LIMIT ? OFFSET ?
|
|
`;p.push(t,n);let E=this.db.prepare(v).all(...p);return{observations:m,sessions:E}}findByType(e,r={}){let a=[],{limit:t=50,offset:n=0,orderBy:o="date_desc",...i}=r,l={...i,type:e},u=this.buildFilterClause(l,a,"o"),d=this.buildOrderClause(o,!1),f=`
|
|
SELECT o.*, o.discovery_tokens
|
|
FROM observations o
|
|
WHERE ${u}
|
|
${d}
|
|
LIMIT ? OFFSET ?
|
|
`;return a.push(t,n),this.db.prepare(f).all(...a)}searchUserPrompts(e,r={}){let a=[],{limit:t=20,offset:n=0,orderBy:o="relevance",...i}=r,l=[];if(i.project&&(l.push("s.project = ?"),a.push(i.project)),i.dateRange){let{start:u,end:d}=i.dateRange;if(u){let f=typeof u=="number"?u:new Date(u).getTime();l.push("up.created_at_epoch >= ?"),a.push(f)}if(d){let f=typeof d=="number"?d:new Date(d).getTime();l.push("up.created_at_epoch <= ?"),a.push(f)}}if(!e){if(l.length===0)throw new Error("Either query or filters required for search");let f=`
|
|
SELECT up.*
|
|
FROM user_prompts up
|
|
JOIN sdk_sessions s ON up.claude_session_id = s.claude_session_id
|
|
${`WHERE ${l.join(" AND ")}`}
|
|
${o==="date_asc"?"ORDER BY up.created_at_epoch ASC":"ORDER BY up.created_at_epoch DESC"}
|
|
LIMIT ? OFFSET ?
|
|
`;return a.push(t,n),this.db.prepare(f).all(...a)}return console.warn("[SessionSearch] Text search not supported - use ChromaDB for vector search"),[]}getUserPromptsBySession(e){return this.db.prepare(`
|
|
SELECT
|
|
id,
|
|
claude_session_id,
|
|
prompt_number,
|
|
prompt_text,
|
|
created_at,
|
|
created_at_epoch
|
|
FROM user_prompts
|
|
WHERE claude_session_id = ?
|
|
ORDER BY prompt_number ASC
|
|
`).all(e)}close(){this.db.close()}};var Rl=Mt(require("better-sqlite3"),1);var an=(n=>(n[n.DEBUG=0]="DEBUG",n[n.INFO=1]="INFO",n[n.WARN=2]="WARN",n[n.ERROR=3]="ERROR",n[n.SILENT=4]="SILENT",n))(an||{}),nn=class{level;useColor;constructor(){let e=process.env.CLAUDE_MEM_LOG_LEVEL?.toUpperCase()||"INFO";this.level=an[e]??1,this.useColor=process.stdout.isTTY??!1}correlationId(e,r){return`obs-${e}-${r}`}sessionId(e){return`session-${e}`}formatData(e){if(e==null)return"";if(typeof e=="string")return e;if(typeof e=="number"||typeof e=="boolean")return e.toString();if(typeof e=="object"){if(e instanceof Error)return this.level===0?`${e.message}
|
|
${e.stack}`:e.message;if(Array.isArray(e))return`[${e.length} items]`;let r=Object.keys(e);return r.length===0?"{}":r.length<=3?JSON.stringify(e):`{${r.length} keys: ${r.slice(0,3).join(", ")}...}`}return String(e)}formatTool(e,r){if(!r)return e;try{let a=typeof r=="string"?JSON.parse(r):r;if(e==="Bash"&&a.command){let t=a.command.length>50?a.command.substring(0,50)+"...":a.command;return`${e}(${t})`}if(e==="Read"&&a.file_path){let t=a.file_path.split("/").pop()||a.file_path;return`${e}(${t})`}if(e==="Edit"&&a.file_path){let t=a.file_path.split("/").pop()||a.file_path;return`${e}(${t})`}if(e==="Write"&&a.file_path){let t=a.file_path.split("/").pop()||a.file_path;return`${e}(${t})`}return e}catch{return e}}log(e,r,a,t,n){if(e<this.level)return;let o=new Date().toISOString().replace("T"," ").substring(0,23),i=an[e].padEnd(5),l=r.padEnd(6),u="";t?.correlationId?u=`[${t.correlationId}] `:t?.sessionId&&(u=`[session-${t.sessionId}] `);let d="";n!=null&&(this.level===0&&typeof n=="object"?d=`
|
|
`+JSON.stringify(n,null,2):d=" "+this.formatData(n));let f="";if(t){let{sessionId:p,sdkSessionId:g,correlationId:y,...v}=t;Object.keys(v).length>0&&(f=` {${Object.entries(v).map(([w,S])=>`${w}=${S}`).join(", ")}}`)}let m=`[${o}] [${i}] [${l}] ${u}${a}${f}${d}`;e===3?console.error(m):console.log(m)}debug(e,r,a,t){this.log(0,e,r,a,t)}info(e,r,a,t){this.log(1,e,r,a,t)}warn(e,r,a,t){this.log(2,e,r,a,t)}error(e,r,a,t){this.log(3,e,r,a,t)}dataIn(e,r,a,t){this.info(e,`\u2192 ${r}`,a,t)}dataOut(e,r,a,t){this.info(e,`\u2190 ${r}`,a,t)}success(e,r,a,t){this.info(e,`\u2713 ${r}`,a,t)}failure(e,r,a,t){this.error(e,`\u2717 ${r}`,a,t)}timing(e,r,a,t){this.info(e,`\u23F1 ${r}`,t,{duration:`${a}ms`})}},xl=new nn;var Ms=class{db;constructor(){js(at),this.db=new Rl.default(Ls),this.db.pragma("journal_mode = WAL"),this.db.pragma("synchronous = NORMAL"),this.db.pragma("foreign_keys = ON"),this.initializeSchema(),this.ensureWorkerPortColumn(),this.ensurePromptTrackingColumns(),this.removeSessionSummariesUniqueConstraint(),this.addObservationHierarchicalFields(),this.makeObservationsTextNullable(),this.createUserPromptsTable(),this.ensureDiscoveryTokensColumn()}initializeSchema(){try{this.db.exec(`
|
|
CREATE TABLE IF NOT EXISTS schema_versions (
|
|
id INTEGER PRIMARY KEY,
|
|
version INTEGER UNIQUE NOT NULL,
|
|
applied_at TEXT NOT NULL
|
|
)
|
|
`);let e=this.db.prepare("SELECT version FROM schema_versions ORDER BY version").all();(e.length>0?Math.max(...e.map(a=>a.version)):0)===0&&(console.error("[SessionStore] Initializing fresh database with migration004..."),this.db.exec(`
|
|
CREATE TABLE IF NOT EXISTS sdk_sessions (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
claude_session_id TEXT UNIQUE NOT NULL,
|
|
sdk_session_id TEXT UNIQUE,
|
|
project TEXT NOT NULL,
|
|
user_prompt TEXT,
|
|
started_at TEXT NOT NULL,
|
|
started_at_epoch INTEGER NOT NULL,
|
|
completed_at TEXT,
|
|
completed_at_epoch INTEGER,
|
|
status TEXT CHECK(status IN ('active', 'completed', 'failed')) NOT NULL DEFAULT 'active'
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_sdk_sessions_claude_id ON sdk_sessions(claude_session_id);
|
|
CREATE INDEX IF NOT EXISTS idx_sdk_sessions_sdk_id ON sdk_sessions(sdk_session_id);
|
|
CREATE INDEX IF NOT EXISTS idx_sdk_sessions_project ON sdk_sessions(project);
|
|
CREATE INDEX IF NOT EXISTS idx_sdk_sessions_status ON sdk_sessions(status);
|
|
CREATE INDEX IF NOT EXISTS idx_sdk_sessions_started ON sdk_sessions(started_at_epoch DESC);
|
|
|
|
CREATE TABLE IF NOT EXISTS observations (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
sdk_session_id TEXT NOT NULL,
|
|
project TEXT NOT NULL,
|
|
text TEXT NOT NULL,
|
|
type TEXT NOT NULL CHECK(type IN ('decision', 'bugfix', 'feature', 'refactor', 'discovery')),
|
|
created_at TEXT NOT NULL,
|
|
created_at_epoch INTEGER NOT NULL,
|
|
FOREIGN KEY(sdk_session_id) REFERENCES sdk_sessions(sdk_session_id) ON DELETE CASCADE
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_observations_sdk_session ON observations(sdk_session_id);
|
|
CREATE INDEX IF NOT EXISTS idx_observations_project ON observations(project);
|
|
CREATE INDEX IF NOT EXISTS idx_observations_type ON observations(type);
|
|
CREATE INDEX IF NOT EXISTS idx_observations_created ON observations(created_at_epoch DESC);
|
|
|
|
CREATE TABLE IF NOT EXISTS session_summaries (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
sdk_session_id TEXT UNIQUE NOT NULL,
|
|
project TEXT NOT NULL,
|
|
request TEXT,
|
|
investigated TEXT,
|
|
learned TEXT,
|
|
completed TEXT,
|
|
next_steps TEXT,
|
|
files_read TEXT,
|
|
files_edited TEXT,
|
|
notes TEXT,
|
|
created_at TEXT NOT NULL,
|
|
created_at_epoch INTEGER NOT NULL,
|
|
FOREIGN KEY(sdk_session_id) REFERENCES sdk_sessions(sdk_session_id) ON DELETE CASCADE
|
|
);
|
|
|
|
CREATE INDEX IF NOT EXISTS idx_session_summaries_sdk_session ON session_summaries(sdk_session_id);
|
|
CREATE INDEX IF NOT EXISTS idx_session_summaries_project ON session_summaries(project);
|
|
CREATE INDEX IF NOT EXISTS idx_session_summaries_created ON session_summaries(created_at_epoch DESC);
|
|
`),this.db.prepare("INSERT INTO schema_versions (version, applied_at) VALUES (?, ?)").run(4,new Date().toISOString()),console.error("[SessionStore] Migration004 applied successfully"))}catch(e){throw console.error("[SessionStore] Schema initialization error:",e.message),e}}ensureWorkerPortColumn(){try{if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(5))return;this.db.pragma("table_info(sdk_sessions)").some(t=>t.name==="worker_port")||(this.db.exec("ALTER TABLE sdk_sessions ADD COLUMN worker_port INTEGER"),console.error("[SessionStore] Added worker_port column to sdk_sessions table")),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(5,new Date().toISOString())}catch(e){console.error("[SessionStore] Migration error:",e.message)}}ensurePromptTrackingColumns(){try{if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(6))return;this.db.pragma("table_info(sdk_sessions)").some(l=>l.name==="prompt_counter")||(this.db.exec("ALTER TABLE sdk_sessions ADD COLUMN prompt_counter INTEGER DEFAULT 0"),console.error("[SessionStore] Added prompt_counter column to sdk_sessions table")),this.db.pragma("table_info(observations)").some(l=>l.name==="prompt_number")||(this.db.exec("ALTER TABLE observations ADD COLUMN prompt_number INTEGER"),console.error("[SessionStore] Added prompt_number column to observations table")),this.db.pragma("table_info(session_summaries)").some(l=>l.name==="prompt_number")||(this.db.exec("ALTER TABLE session_summaries ADD COLUMN prompt_number INTEGER"),console.error("[SessionStore] Added prompt_number column to session_summaries table")),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(6,new Date().toISOString())}catch(e){console.error("[SessionStore] Prompt tracking migration error:",e.message)}}removeSessionSummariesUniqueConstraint(){try{if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(7))return;if(!this.db.pragma("index_list(session_summaries)").some(t=>t.unique===1)){this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(7,new Date().toISOString());return}console.error("[SessionStore] Removing UNIQUE constraint from session_summaries.sdk_session_id..."),this.db.exec("BEGIN TRANSACTION");try{this.db.exec(`
|
|
CREATE TABLE session_summaries_new (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
sdk_session_id TEXT NOT NULL,
|
|
project TEXT NOT NULL,
|
|
request TEXT,
|
|
investigated TEXT,
|
|
learned TEXT,
|
|
completed TEXT,
|
|
next_steps TEXT,
|
|
files_read TEXT,
|
|
files_edited TEXT,
|
|
notes TEXT,
|
|
prompt_number INTEGER,
|
|
created_at TEXT NOT NULL,
|
|
created_at_epoch INTEGER NOT NULL,
|
|
FOREIGN KEY(sdk_session_id) REFERENCES sdk_sessions(sdk_session_id) ON DELETE CASCADE
|
|
)
|
|
`),this.db.exec(`
|
|
INSERT INTO session_summaries_new
|
|
SELECT id, sdk_session_id, project, request, investigated, learned,
|
|
completed, next_steps, files_read, files_edited, notes,
|
|
prompt_number, created_at, created_at_epoch
|
|
FROM session_summaries
|
|
`),this.db.exec("DROP TABLE session_summaries"),this.db.exec("ALTER TABLE session_summaries_new RENAME TO session_summaries"),this.db.exec(`
|
|
CREATE INDEX idx_session_summaries_sdk_session ON session_summaries(sdk_session_id);
|
|
CREATE INDEX idx_session_summaries_project ON session_summaries(project);
|
|
CREATE INDEX idx_session_summaries_created ON session_summaries(created_at_epoch DESC);
|
|
`),this.db.exec("COMMIT"),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(7,new Date().toISOString()),console.error("[SessionStore] Successfully removed UNIQUE constraint from session_summaries.sdk_session_id")}catch(t){throw this.db.exec("ROLLBACK"),t}}catch(e){console.error("[SessionStore] Migration error (remove UNIQUE constraint):",e.message)}}addObservationHierarchicalFields(){try{if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(8))return;if(this.db.pragma("table_info(observations)").some(t=>t.name==="title")){this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(8,new Date().toISOString());return}console.error("[SessionStore] Adding hierarchical fields to observations table..."),this.db.exec(`
|
|
ALTER TABLE observations ADD COLUMN title TEXT;
|
|
ALTER TABLE observations ADD COLUMN subtitle TEXT;
|
|
ALTER TABLE observations ADD COLUMN facts TEXT;
|
|
ALTER TABLE observations ADD COLUMN narrative TEXT;
|
|
ALTER TABLE observations ADD COLUMN concepts TEXT;
|
|
ALTER TABLE observations ADD COLUMN files_read TEXT;
|
|
ALTER TABLE observations ADD COLUMN files_modified TEXT;
|
|
`),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(8,new Date().toISOString()),console.error("[SessionStore] Successfully added hierarchical fields to observations table")}catch(e){console.error("[SessionStore] Migration error (add hierarchical fields):",e.message)}}makeObservationsTextNullable(){try{if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(9))return;let a=this.db.pragma("table_info(observations)").find(t=>t.name==="text");if(!a||a.notnull===0){this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(9,new Date().toISOString());return}console.error("[SessionStore] Making observations.text nullable..."),this.db.exec("BEGIN TRANSACTION");try{this.db.exec(`
|
|
CREATE TABLE observations_new (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
sdk_session_id TEXT NOT NULL,
|
|
project TEXT NOT NULL,
|
|
text TEXT,
|
|
type TEXT NOT NULL CHECK(type IN ('decision', 'bugfix', 'feature', 'refactor', 'discovery', 'change')),
|
|
title TEXT,
|
|
subtitle TEXT,
|
|
facts TEXT,
|
|
narrative TEXT,
|
|
concepts TEXT,
|
|
files_read TEXT,
|
|
files_modified TEXT,
|
|
prompt_number INTEGER,
|
|
created_at TEXT NOT NULL,
|
|
created_at_epoch INTEGER NOT NULL,
|
|
FOREIGN KEY(sdk_session_id) REFERENCES sdk_sessions(sdk_session_id) ON DELETE CASCADE
|
|
)
|
|
`),this.db.exec(`
|
|
INSERT INTO observations_new
|
|
SELECT id, sdk_session_id, project, text, type, title, subtitle, facts,
|
|
narrative, concepts, files_read, files_modified, prompt_number,
|
|
created_at, created_at_epoch
|
|
FROM observations
|
|
`),this.db.exec("DROP TABLE observations"),this.db.exec("ALTER TABLE observations_new RENAME TO observations"),this.db.exec(`
|
|
CREATE INDEX idx_observations_sdk_session ON observations(sdk_session_id);
|
|
CREATE INDEX idx_observations_project ON observations(project);
|
|
CREATE INDEX idx_observations_type ON observations(type);
|
|
CREATE INDEX idx_observations_created ON observations(created_at_epoch DESC);
|
|
`),this.db.exec("COMMIT"),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(9,new Date().toISOString()),console.error("[SessionStore] Successfully made observations.text nullable")}catch(t){throw this.db.exec("ROLLBACK"),t}}catch(e){console.error("[SessionStore] Migration error (make text nullable):",e.message)}}createUserPromptsTable(){try{if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(10))return;if(this.db.pragma("table_info(user_prompts)").length>0){this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(10,new Date().toISOString());return}console.error("[SessionStore] Creating user_prompts table with FTS5 support..."),this.db.exec("BEGIN TRANSACTION");try{this.db.exec(`
|
|
CREATE TABLE user_prompts (
|
|
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
claude_session_id TEXT NOT NULL,
|
|
prompt_number INTEGER NOT NULL,
|
|
prompt_text TEXT NOT NULL,
|
|
created_at TEXT NOT NULL,
|
|
created_at_epoch INTEGER NOT NULL,
|
|
FOREIGN KEY(claude_session_id) REFERENCES sdk_sessions(claude_session_id) ON DELETE CASCADE
|
|
);
|
|
|
|
CREATE INDEX idx_user_prompts_claude_session ON user_prompts(claude_session_id);
|
|
CREATE INDEX idx_user_prompts_created ON user_prompts(created_at_epoch DESC);
|
|
CREATE INDEX idx_user_prompts_prompt_number ON user_prompts(prompt_number);
|
|
`),this.db.exec(`
|
|
CREATE VIRTUAL TABLE user_prompts_fts USING fts5(
|
|
prompt_text,
|
|
content='user_prompts',
|
|
content_rowid='id'
|
|
);
|
|
`),this.db.exec(`
|
|
CREATE TRIGGER user_prompts_ai AFTER INSERT ON user_prompts BEGIN
|
|
INSERT INTO user_prompts_fts(rowid, prompt_text)
|
|
VALUES (new.id, new.prompt_text);
|
|
END;
|
|
|
|
CREATE TRIGGER user_prompts_ad AFTER DELETE ON user_prompts BEGIN
|
|
INSERT INTO user_prompts_fts(user_prompts_fts, rowid, prompt_text)
|
|
VALUES('delete', old.id, old.prompt_text);
|
|
END;
|
|
|
|
CREATE TRIGGER user_prompts_au AFTER UPDATE ON user_prompts BEGIN
|
|
INSERT INTO user_prompts_fts(user_prompts_fts, rowid, prompt_text)
|
|
VALUES('delete', old.id, old.prompt_text);
|
|
INSERT INTO user_prompts_fts(rowid, prompt_text)
|
|
VALUES (new.id, new.prompt_text);
|
|
END;
|
|
`),this.db.exec("COMMIT"),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(10,new Date().toISOString()),console.error("[SessionStore] Successfully created user_prompts table with FTS5 support")}catch(a){throw this.db.exec("ROLLBACK"),a}}catch(e){console.error("[SessionStore] Migration error (create user_prompts table):",e.message)}}ensureDiscoveryTokensColumn(){try{if(this.db.prepare("SELECT version FROM schema_versions WHERE version = ?").get(11))return;this.db.pragma("table_info(observations)").some(o=>o.name==="discovery_tokens")||(this.db.exec("ALTER TABLE observations ADD COLUMN discovery_tokens INTEGER DEFAULT 0"),console.error("[SessionStore] Added discovery_tokens column to observations table")),this.db.pragma("table_info(session_summaries)").some(o=>o.name==="discovery_tokens")||(this.db.exec("ALTER TABLE session_summaries ADD COLUMN discovery_tokens INTEGER DEFAULT 0"),console.error("[SessionStore] Added discovery_tokens column to session_summaries table")),this.db.prepare("INSERT OR IGNORE INTO schema_versions (version, applied_at) VALUES (?, ?)").run(11,new Date().toISOString())}catch(e){throw console.error("[SessionStore] Discovery tokens migration error:",e.message),e}}getRecentSummaries(e,r=10){return this.db.prepare(`
|
|
SELECT
|
|
request, investigated, learned, completed, next_steps,
|
|
files_read, files_edited, notes, prompt_number, created_at
|
|
FROM session_summaries
|
|
WHERE project = ?
|
|
ORDER BY created_at_epoch DESC
|
|
LIMIT ?
|
|
`).all(e,r)}getRecentSummariesWithSessionInfo(e,r=3){return this.db.prepare(`
|
|
SELECT
|
|
sdk_session_id, request, learned, completed, next_steps,
|
|
prompt_number, created_at
|
|
FROM session_summaries
|
|
WHERE project = ?
|
|
ORDER BY created_at_epoch DESC
|
|
LIMIT ?
|
|
`).all(e,r)}getRecentObservations(e,r=20){return this.db.prepare(`
|
|
SELECT type, text, prompt_number, created_at
|
|
FROM observations
|
|
WHERE project = ?
|
|
ORDER BY created_at_epoch DESC
|
|
LIMIT ?
|
|
`).all(e,r)}getAllRecentObservations(e=100){return this.db.prepare(`
|
|
SELECT id, type, title, subtitle, text, project, prompt_number, created_at, created_at_epoch
|
|
FROM observations
|
|
ORDER BY created_at_epoch DESC
|
|
LIMIT ?
|
|
`).all(e)}getAllRecentSummaries(e=50){return this.db.prepare(`
|
|
SELECT id, request, investigated, learned, completed, next_steps,
|
|
files_read, files_edited, notes, project, prompt_number,
|
|
created_at, created_at_epoch
|
|
FROM session_summaries
|
|
ORDER BY created_at_epoch DESC
|
|
LIMIT ?
|
|
`).all(e)}getAllRecentUserPrompts(e=100){return this.db.prepare(`
|
|
SELECT
|
|
up.id,
|
|
up.claude_session_id,
|
|
s.project,
|
|
up.prompt_number,
|
|
up.prompt_text,
|
|
up.created_at,
|
|
up.created_at_epoch
|
|
FROM user_prompts up
|
|
LEFT JOIN sdk_sessions s ON up.claude_session_id = s.claude_session_id
|
|
ORDER BY up.created_at_epoch DESC
|
|
LIMIT ?
|
|
`).all(e)}getAllProjects(){return this.db.prepare(`
|
|
SELECT DISTINCT project
|
|
FROM sdk_sessions
|
|
WHERE project IS NOT NULL AND project != ''
|
|
ORDER BY project ASC
|
|
`).all().map(a=>a.project)}getRecentSessionsWithStatus(e,r=3){return this.db.prepare(`
|
|
SELECT * FROM (
|
|
SELECT
|
|
s.sdk_session_id,
|
|
s.status,
|
|
s.started_at,
|
|
s.started_at_epoch,
|
|
s.user_prompt,
|
|
CASE WHEN sum.sdk_session_id IS NOT NULL THEN 1 ELSE 0 END as has_summary
|
|
FROM sdk_sessions s
|
|
LEFT JOIN session_summaries sum ON s.sdk_session_id = sum.sdk_session_id
|
|
WHERE s.project = ? AND s.sdk_session_id IS NOT NULL
|
|
GROUP BY s.sdk_session_id
|
|
ORDER BY s.started_at_epoch DESC
|
|
LIMIT ?
|
|
)
|
|
ORDER BY started_at_epoch ASC
|
|
`).all(e,r)}getObservationsForSession(e){return this.db.prepare(`
|
|
SELECT title, subtitle, type, prompt_number
|
|
FROM observations
|
|
WHERE sdk_session_id = ?
|
|
ORDER BY created_at_epoch ASC
|
|
`).all(e)}getObservationById(e){return this.db.prepare(`
|
|
SELECT *
|
|
FROM observations
|
|
WHERE id = ?
|
|
`).get(e)||null}getObservationsByIds(e,r={}){if(e.length===0)return[];let{orderBy:a="date_desc",limit:t}=r,n=a==="date_asc"?"ASC":"DESC",o=t?`LIMIT ${t}`:"",i=e.map(()=>"?").join(",");return this.db.prepare(`
|
|
SELECT *
|
|
FROM observations
|
|
WHERE id IN (${i})
|
|
ORDER BY created_at_epoch ${n}
|
|
${o}
|
|
`).all(...e)}getSummaryForSession(e){return this.db.prepare(`
|
|
SELECT
|
|
request, investigated, learned, completed, next_steps,
|
|
files_read, files_edited, notes, prompt_number, created_at
|
|
FROM session_summaries
|
|
WHERE sdk_session_id = ?
|
|
ORDER BY created_at_epoch DESC
|
|
LIMIT 1
|
|
`).get(e)||null}getFilesForSession(e){let a=this.db.prepare(`
|
|
SELECT files_read, files_modified
|
|
FROM observations
|
|
WHERE sdk_session_id = ?
|
|
`).all(e),t=new Set,n=new Set;for(let o of a){if(o.files_read)try{let i=JSON.parse(o.files_read);Array.isArray(i)&&i.forEach(l=>t.add(l))}catch{}if(o.files_modified)try{let i=JSON.parse(o.files_modified);Array.isArray(i)&&i.forEach(l=>n.add(l))}catch{}}return{filesRead:Array.from(t),filesModified:Array.from(n)}}getSessionById(e){return this.db.prepare(`
|
|
SELECT id, claude_session_id, sdk_session_id, project, user_prompt
|
|
FROM sdk_sessions
|
|
WHERE id = ?
|
|
LIMIT 1
|
|
`).get(e)||null}findActiveSDKSession(e){return this.db.prepare(`
|
|
SELECT id, sdk_session_id, project, worker_port
|
|
FROM sdk_sessions
|
|
WHERE claude_session_id = ? AND status = 'active'
|
|
LIMIT 1
|
|
`).get(e)||null}findAnySDKSession(e){return this.db.prepare(`
|
|
SELECT id
|
|
FROM sdk_sessions
|
|
WHERE claude_session_id = ?
|
|
LIMIT 1
|
|
`).get(e)||null}reactivateSession(e,r){this.db.prepare(`
|
|
UPDATE sdk_sessions
|
|
SET status = 'active', user_prompt = ?, worker_port = NULL
|
|
WHERE id = ?
|
|
`).run(r,e)}incrementPromptCounter(e){return this.db.prepare(`
|
|
UPDATE sdk_sessions
|
|
SET prompt_counter = COALESCE(prompt_counter, 0) + 1
|
|
WHERE id = ?
|
|
`).run(e),this.db.prepare(`
|
|
SELECT prompt_counter FROM sdk_sessions WHERE id = ?
|
|
`).get(e)?.prompt_counter||1}getPromptCounter(e){return this.db.prepare(`
|
|
SELECT prompt_counter FROM sdk_sessions WHERE id = ?
|
|
`).get(e)?.prompt_counter||0}createSDKSession(e,r,a){let t=new Date,n=t.getTime(),i=this.db.prepare(`
|
|
INSERT OR IGNORE INTO sdk_sessions
|
|
(claude_session_id, sdk_session_id, project, user_prompt, started_at, started_at_epoch, status)
|
|
VALUES (?, ?, ?, ?, ?, ?, 'active')
|
|
`).run(e,e,r,a,t.toISOString(),n);return i.lastInsertRowid===0||i.changes===0?this.db.prepare(`
|
|
SELECT id FROM sdk_sessions WHERE claude_session_id = ? LIMIT 1
|
|
`).get(e).id:i.lastInsertRowid}updateSDKSessionId(e,r){return this.db.prepare(`
|
|
UPDATE sdk_sessions
|
|
SET sdk_session_id = ?
|
|
WHERE id = ? AND sdk_session_id IS NULL
|
|
`).run(r,e).changes===0?(xl.debug("DB","sdk_session_id already set, skipping update",{sessionId:e,sdkSessionId:r}),!1):!0}setWorkerPort(e,r){this.db.prepare(`
|
|
UPDATE sdk_sessions
|
|
SET worker_port = ?
|
|
WHERE id = ?
|
|
`).run(r,e)}getWorkerPort(e){return this.db.prepare(`
|
|
SELECT worker_port
|
|
FROM sdk_sessions
|
|
WHERE id = ?
|
|
LIMIT 1
|
|
`).get(e)?.worker_port||null}saveUserPrompt(e,r,a){let t=new Date,n=t.getTime();return this.db.prepare(`
|
|
INSERT INTO user_prompts
|
|
(claude_session_id, prompt_number, prompt_text, created_at, created_at_epoch)
|
|
VALUES (?, ?, ?, ?, ?)
|
|
`).run(e,r,a,t.toISOString(),n).lastInsertRowid}storeObservation(e,r,a,t,n=0){let o=new Date,i=o.getTime();this.db.prepare(`
|
|
SELECT id FROM sdk_sessions WHERE sdk_session_id = ?
|
|
`).get(e)||(this.db.prepare(`
|
|
INSERT INTO sdk_sessions
|
|
(claude_session_id, sdk_session_id, project, started_at, started_at_epoch, status)
|
|
VALUES (?, ?, ?, ?, ?, 'active')
|
|
`).run(e,e,r,o.toISOString(),i),console.error(`[SessionStore] Auto-created session record for session_id: ${e}`));let f=this.db.prepare(`
|
|
INSERT INTO observations
|
|
(sdk_session_id, project, type, title, subtitle, facts, narrative, concepts,
|
|
files_read, files_modified, prompt_number, discovery_tokens, created_at, created_at_epoch)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
`).run(e,r,a.type,a.title,a.subtitle,JSON.stringify(a.facts),a.narrative,JSON.stringify(a.concepts),JSON.stringify(a.files_read),JSON.stringify(a.files_modified),t||null,n,o.toISOString(),i);return{id:Number(f.lastInsertRowid),createdAtEpoch:i}}storeSummary(e,r,a,t,n=0){let o=new Date,i=o.getTime();this.db.prepare(`
|
|
SELECT id FROM sdk_sessions WHERE sdk_session_id = ?
|
|
`).get(e)||(this.db.prepare(`
|
|
INSERT INTO sdk_sessions
|
|
(claude_session_id, sdk_session_id, project, started_at, started_at_epoch, status)
|
|
VALUES (?, ?, ?, ?, ?, 'active')
|
|
`).run(e,e,r,o.toISOString(),i),console.error(`[SessionStore] Auto-created session record for session_id: ${e}`));let f=this.db.prepare(`
|
|
INSERT INTO session_summaries
|
|
(sdk_session_id, project, request, investigated, learned, completed,
|
|
next_steps, notes, prompt_number, discovery_tokens, created_at, created_at_epoch)
|
|
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
|
|
`).run(e,r,a.request,a.investigated,a.learned,a.completed,a.next_steps,a.notes,t||null,n,o.toISOString(),i);return{id:Number(f.lastInsertRowid),createdAtEpoch:i}}markSessionCompleted(e){let r=new Date,a=r.getTime();this.db.prepare(`
|
|
UPDATE sdk_sessions
|
|
SET status = 'completed', completed_at = ?, completed_at_epoch = ?
|
|
WHERE id = ?
|
|
`).run(r.toISOString(),a,e)}markSessionFailed(e){let r=new Date,a=r.getTime();this.db.prepare(`
|
|
UPDATE sdk_sessions
|
|
SET status = 'failed', completed_at = ?, completed_at_epoch = ?
|
|
WHERE id = ?
|
|
`).run(r.toISOString(),a,e)}getSessionSummariesByIds(e,r={}){if(e.length===0)return[];let{orderBy:a="date_desc",limit:t}=r,n=a==="date_asc"?"ASC":"DESC",o=t?`LIMIT ${t}`:"",i=e.map(()=>"?").join(",");return this.db.prepare(`
|
|
SELECT * FROM session_summaries
|
|
WHERE id IN (${i})
|
|
ORDER BY created_at_epoch ${n}
|
|
${o}
|
|
`).all(...e)}getUserPromptsByIds(e,r={}){if(e.length===0)return[];let{orderBy:a="date_desc",limit:t}=r,n=a==="date_asc"?"ASC":"DESC",o=t?`LIMIT ${t}`:"",i=e.map(()=>"?").join(",");return this.db.prepare(`
|
|
SELECT
|
|
up.*,
|
|
s.project,
|
|
s.sdk_session_id
|
|
FROM user_prompts up
|
|
JOIN sdk_sessions s ON up.claude_session_id = s.claude_session_id
|
|
WHERE up.id IN (${i})
|
|
ORDER BY up.created_at_epoch ${n}
|
|
${o}
|
|
`).all(...e)}getTimelineAroundTimestamp(e,r=10,a=10,t){return this.getTimelineAroundObservation(null,e,r,a,t)}getTimelineAroundObservation(e,r,a=10,t=10,n){let o=n?"AND project = ?":"",i=n?[n]:[],l,u;if(e!==null){let p=`
|
|
SELECT id, created_at_epoch
|
|
FROM observations
|
|
WHERE id <= ? ${o}
|
|
ORDER BY id DESC
|
|
LIMIT ?
|
|
`,g=`
|
|
SELECT id, created_at_epoch
|
|
FROM observations
|
|
WHERE id >= ? ${o}
|
|
ORDER BY id ASC
|
|
LIMIT ?
|
|
`;try{let y=this.db.prepare(p).all(e,...i,a+1),v=this.db.prepare(g).all(e,...i,t+1);if(y.length===0&&v.length===0)return{observations:[],sessions:[],prompts:[]};l=y.length>0?y[y.length-1].created_at_epoch:r,u=v.length>0?v[v.length-1].created_at_epoch:r}catch(y){return console.error("[SessionStore] Error getting boundary observations:",y.message),{observations:[],sessions:[],prompts:[]}}}else{let p=`
|
|
SELECT created_at_epoch
|
|
FROM observations
|
|
WHERE created_at_epoch <= ? ${o}
|
|
ORDER BY created_at_epoch DESC
|
|
LIMIT ?
|
|
`,g=`
|
|
SELECT created_at_epoch
|
|
FROM observations
|
|
WHERE created_at_epoch >= ? ${o}
|
|
ORDER BY created_at_epoch ASC
|
|
LIMIT ?
|
|
`;try{let y=this.db.prepare(p).all(r,...i,a),v=this.db.prepare(g).all(r,...i,t+1);if(y.length===0&&v.length===0)return{observations:[],sessions:[],prompts:[]};l=y.length>0?y[y.length-1].created_at_epoch:r,u=v.length>0?v[v.length-1].created_at_epoch:r}catch(y){return console.error("[SessionStore] Error getting boundary timestamps:",y.message),{observations:[],sessions:[],prompts:[]}}}let d=`
|
|
SELECT *
|
|
FROM observations
|
|
WHERE created_at_epoch >= ? AND created_at_epoch <= ? ${o}
|
|
ORDER BY created_at_epoch ASC
|
|
`,f=`
|
|
SELECT *
|
|
FROM session_summaries
|
|
WHERE created_at_epoch >= ? AND created_at_epoch <= ? ${o}
|
|
ORDER BY created_at_epoch ASC
|
|
`,m=`
|
|
SELECT up.*, s.project, s.sdk_session_id
|
|
FROM user_prompts up
|
|
JOIN sdk_sessions s ON up.claude_session_id = s.claude_session_id
|
|
WHERE up.created_at_epoch >= ? AND up.created_at_epoch <= ? ${o.replace("project","s.project")}
|
|
ORDER BY up.created_at_epoch ASC
|
|
`;try{let p=this.db.prepare(d).all(l,u,...i),g=this.db.prepare(f).all(l,u,...i),y=this.db.prepare(m).all(l,u,...i);return{observations:p,sessions:g.map(v=>({id:v.id,sdk_session_id:v.sdk_session_id,project:v.project,request:v.request,completed:v.completed,next_steps:v.next_steps,created_at:v.created_at,created_at_epoch:v.created_at_epoch})),prompts:y.map(v=>({id:v.id,claude_session_id:v.claude_session_id,project:v.project,prompt:v.prompt_text,created_at:v.created_at,created_at_epoch:v.created_at_epoch}))}}catch(p){return console.error("[SessionStore] Error querying timeline records:",p.message),{observations:[],sessions:[],prompts:[]}}}close(){this.db.close()}};var Tl=require("fs"),wl=require("os"),Pl=require("path"),Sh=(0,Pl.join)((0,wl.homedir)(),".claude-mem","silent.log");function Br(s,e,r=""){let a=new Date().toISOString(),i=((new Error().stack||"").split(`
|
|
`)[2]||"").match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/),l=i?`${i[1].split("/").pop()}:${i[2]}`:"unknown",u=`[${a}] [${l}] ${s}`;if(e!==void 0)try{u+=` ${JSON.stringify(e)}`}catch(d){u+=` [stringify error: ${d}]`}u+=`
|
|
`;try{(0,Tl.appendFileSync)(Sh,u)}catch(d){console.error("[silent-debug] Failed to write to log:",d)}return r}var _e,ie,Te=null,xh="cm__claude-mem";try{_e=new Fs,ie=new Ms}catch(s){console.error("[search-server] Failed to initialize search:",s.message),process.exit(1)}async function Ye(s,e,r){if(!Te)throw new Error("Chroma client not initialized");Br("queryChroma called",{query:s,limit:e,whereFilter:r});let a=r?JSON.stringify(r):void 0;Br("where filter stringified",{whereFilter:r,whereStringified:a});let t={collection_name:xh,query_texts:[s],n_results:e,include:["documents","metadatas","distances"],where:a};Br("calling chroma_query_documents",t);let n=await Te.callTool({name:"chroma_query_documents",arguments:t}),o=n.content[0]?.text||"";Br("chroma response received",{hasContent:!!n.content[0]?.text,textLength:o.length,textPreview:o.substring(0,200)});let i;try{i=JSON.parse(o)}catch(m){return console.error("[search-server] Failed to parse Chroma response as JSON:",m),console.error("[search-server] Raw Chroma response:",o),{ids:[],distances:[],metadatas:[]}}let l=[],u=i.ids?.[0]||[];for(let m of u){let p=m.match(/obs_(\d+)_/),g=m.match(/summary_(\d+)_/),y=m.match(/prompt_(\d+)/),v=null;p?v=parseInt(p[1],10):g?v=parseInt(g[1],10):y&&(v=parseInt(y[1],10)),v!==null&&!l.includes(v)&&l.push(v)}let d=i.distances?.[0]||[],f=i.metadatas?.[0]||[];return{ids:l,distances:d,metadatas:f}}function ar(){return`
|
|
---
|
|
\u{1F4A1} Search Strategy:
|
|
ALWAYS search with index format FIRST to get an overview and identify relevant results.
|
|
This is critical for token efficiency - index format uses ~10x fewer tokens than full format.
|
|
|
|
Search workflow:
|
|
1. Initial search: Use default (index) format to see titles, dates, and sources
|
|
2. Review results: Identify which items are most relevant to your needs
|
|
3. Deep dive: Only then use format: "full" on specific items of interest
|
|
4. Narrow down: Use filters (type, dateRange, concepts, files) to refine results
|
|
|
|
Other tips:
|
|
\u2022 To search by concept: Use find_by_concept tool
|
|
\u2022 To browse by type: Use find_by_type with ["decision", "feature", etc.]
|
|
\u2022 To sort by date: Use orderBy: "date_desc" or "date_asc"`}function At(s,e){let r=s.title||`Observation #${s.id}`,a=new Date(s.created_at_epoch).toLocaleString(),t=s.type?`[${s.type}]`:"";return`${e+1}. ${t} ${r}
|
|
Date: ${a}
|
|
Source: claude-mem://observation/${s.id}`}function on(s,e){let r=s.request||`Session ${s.sdk_session_id?.substring(0,8)||"unknown"}`,a=new Date(s.created_at_epoch).toLocaleString();return`${e+1}. ${r}
|
|
Date: ${a}
|
|
Source: claude-mem://session/${s.sdk_session_id}`}function Nt(s){let e=s.title||`Observation #${s.id}`,r=[];r.push(`## ${e}`),r.push(`*Source: claude-mem://observation/${s.id}*`),r.push(""),s.subtitle&&(r.push(`**${s.subtitle}**`),r.push("")),s.narrative&&(r.push(s.narrative),r.push("")),s.text&&(r.push(s.text),r.push(""));let a=[];if(a.push(`Type: ${s.type}`),s.facts)try{let n=JSON.parse(s.facts);n.length>0&&a.push(`Facts: ${n.join("; ")}`)}catch{}if(s.concepts)try{let n=JSON.parse(s.concepts);n.length>0&&a.push(`Concepts: ${n.join(", ")}`)}catch{}if(s.files_read||s.files_modified){let n=[];if(s.files_read)try{n.push(...JSON.parse(s.files_read))}catch{}if(s.files_modified)try{n.push(...JSON.parse(s.files_modified))}catch{}n.length>0&&a.push(`Files: ${[...new Set(n)].join(", ")}`)}a.length>0&&(r.push("---"),r.push(a.join(" | ")));let t=new Date(s.created_at_epoch).toLocaleString();return r.push(""),r.push("---"),r.push(`Date: ${t}`),r.join(`
|
|
`)}function cn(s){let e=s.request||`Session ${s.sdk_session_id?.substring(0,8)||"unknown"}`,r=[];r.push(`## ${e}`),r.push(`*Source: claude-mem://session/${s.sdk_session_id}*`),r.push(""),s.completed&&(r.push(`**Completed:** ${s.completed}`),r.push("")),s.learned&&(r.push(`**Learned:** ${s.learned}`),r.push("")),s.investigated&&(r.push(`**Investigated:** ${s.investigated}`),r.push("")),s.next_steps&&(r.push(`**Next Steps:** ${s.next_steps}`),r.push("")),s.notes&&(r.push(`**Notes:** ${s.notes}`),r.push(""));let a=[];if(s.files_read||s.files_edited){let n=[];if(s.files_read)try{n.push(...JSON.parse(s.files_read))}catch{}if(s.files_edited)try{n.push(...JSON.parse(s.files_edited))}catch{}n.length>0&&a.push(`Files: ${[...new Set(n)].join(", ")}`)}let t=new Date(s.created_at_epoch).toLocaleDateString();return a.push(`Date: ${t}`),a.length>0&&(r.push("---"),r.push(a.join(" | "))),r.join(`
|
|
`)}function Ol(s,e){let r=new Date(s.created_at_epoch).toLocaleString();return`${e+1}. "${s.prompt_text}"
|
|
Date: ${r} | Prompt #${s.prompt_number}
|
|
Source: claude-mem://user-prompt/${s.id}`}function Il(s){let e=[];e.push(`## User Prompt #${s.prompt_number}`),e.push(`*Source: claude-mem://user-prompt/${s.id}*`),e.push(""),e.push(s.prompt_text),e.push(""),e.push("---");let r=new Date(s.created_at_epoch).toLocaleString();return e.push(`Date: ${r}`),e.join(`
|
|
`)}var Rh=c.object({project:c.string().optional().describe("Filter by project name"),type:c.union([c.enum(["decision","bugfix","feature","refactor","discovery","change"]),c.array(c.enum(["decision","bugfix","feature","refactor","discovery","change"]))]).optional().describe("Filter by observation type"),concepts:c.union([c.string(),c.array(c.string())]).optional().describe("Filter by concept tags"),files:c.union([c.string(),c.array(c.string())]).optional().describe("Filter by file paths (partial match)"),dateRange:c.object({start:c.union([c.string(),c.number()]).optional().describe("Start date (ISO string or epoch)"),end:c.union([c.string(),c.number()]).optional().describe("End date (ISO string or epoch)")}).optional().describe("Filter by date range"),limit:c.number().min(1).max(100).default(20).describe("Maximum number of results"),offset:c.number().min(0).default(0).describe("Number of results to skip"),orderBy:c.enum(["relevance","date_desc","date_asc"]).default("date_desc").describe("Sort order")}),Al=[{name:"search",description:'Unified search across all memory types (observations, sessions, and user prompts) using vector-first semantic search (ChromaDB). Returns combined results from all document types. IMPORTANT: Always use index format first (default) to get an overview with minimal token usage, then use format: "full" only for specific items of interest.',inputSchema:c.object({query:c.string().optional().describe("Natural language search query for semantic ranking via ChromaDB vector search. Optional - omit for date-filtered queries only (Chroma cannot filter by date, requires direct SQLite)."),format:c.enum(["index","full"]).default("index").describe('Output format: "index" for titles/dates only (default, RECOMMENDED for initial search), "full" for complete details (use only after reviewing index results)'),type:c.enum(["observations","sessions","prompts"]).optional().describe("Filter by document type (observations, sessions, or prompts). Omit to search all types."),obs_type:c.union([c.enum(["decision","bugfix","feature","refactor","discovery","change"]),c.array(c.enum(["decision","bugfix","feature","refactor","discovery","change"]))]).optional().describe('Filter observations by type. Only applies when type="observations"'),concepts:c.union([c.string(),c.array(c.string())]).optional().describe('Filter by concept tags. Only applies when type="observations"'),files:c.union([c.string(),c.array(c.string())]).optional().describe('Filter by file paths (partial match). Only applies when type="observations"'),project:c.string().optional().describe("Filter by project name"),dateRange:c.object({start:c.union([c.string(),c.number()]).optional().describe("Start date (ISO string or epoch)"),end:c.union([c.string(),c.number()]).optional().describe("End date (ISO string or epoch)")}).optional().describe("Filter by date range"),limit:c.number().min(1).max(100).default(20).describe("Maximum number of results"),offset:c.number().min(0).default(0).describe("Number of results to skip"),orderBy:c.enum(["relevance","date_desc","date_asc"]).default("date_desc").describe("Sort order")}),handler:async s=>{try{let{query:e,format:r="index",type:a,obs_type:t,concepts:n,files:o,...i}=s,l=[],u=[],d=[],f=!a||a==="observations",m=!a||a==="sessions",p=!a||a==="prompts";if(e)if(Te){let w=!1;try{console.error(`[search-server] Using ChromaDB semantic search (type filter: ${a||"all"})`);let S;a==="observations"?S={doc_type:"observation"}:a==="sessions"?S={doc_type:"session_summary"}:a==="prompts"&&(S={doc_type:"user_prompt"});let R=await Ye(e,100,S);if(w=!0,console.error(`[search-server] ChromaDB returned ${R.ids.length} semantic matches`),R.ids.length>0){let x=Date.now()-7776e6,T=R.metadatas.map((D,C)=>({id:R.ids[C],meta:D,isRecent:D&&D.created_at_epoch>x})).filter(D=>D.isRecent);console.error(`[search-server] ${T.length} results within 90-day window`);let N=[],j=[],$=[];for(let D of T){let C=D.meta?.doc_type;C==="observation"&&f?N.push(D.id):C==="session_summary"&&m?j.push(D.id):C==="user_prompt"&&p&&$.push(D.id)}if(console.error(`[search-server] Categorized: ${N.length} obs, ${j.length} sessions, ${$.length} prompts`),N.length>0){let D={...i,type:t,concepts:n,files:o};l=ie.getObservationsByIds(N,D)}j.length>0&&(u=ie.getSessionSummariesByIds(j,{orderBy:"date_desc",limit:i.limit})),$.length>0&&(d=ie.getUserPromptsByIds($,{orderBy:"date_desc",limit:i.limit})),console.error(`[search-server] Hydrated ${l.length} obs, ${u.length} sessions, ${d.length} prompts from SQLite`)}else console.error("[search-server] ChromaDB found no matches (this is final - NOT falling back to FTS5)")}catch(S){console.error("[search-server] ChromaDB failed - returning empty results (FTS5 fallback removed):",S.message),console.error("[search-server] Install UVX/Python to enable vector search: https://docs.astral.sh/uv/getting-started/installation/"),l=[],u=[],d=[]}}else console.error("[search-server] ChromaDB not initialized - returning empty results (FTS5 fallback removed)"),console.error("[search-server] Install UVX/Python to enable vector search: https://docs.astral.sh/uv/getting-started/installation/"),l=[],u=[],d=[];else{console.error("[search-server] Filter-only query (no query text), using direct SQLite filtering (enables date filters)");let w={...i,type:t,concepts:n,files:o};f&&(l=_e.searchObservations(void 0,w)),m&&(u=_e.searchSessions(void 0,i)),p&&(d=_e.searchUserPrompts(void 0,i))}let g=l.length+u.length+d.length;if(g===0)return{content:[{type:"text",text:`No results found matching "${e}"`}]};let y=[...l.map(w=>({type:"observation",data:w,epoch:w.created_at_epoch})),...u.map(w=>({type:"session",data:w,epoch:w.created_at_epoch})),...d.map(w=>({type:"prompt",data:w,epoch:w.created_at_epoch}))];i.orderBy==="date_desc"?y.sort((w,S)=>S.epoch-w.epoch):i.orderBy==="date_asc"&&y.sort((w,S)=>w.epoch-S.epoch);let v=y.slice(0,i.limit||20),E;if(r==="index"){let w=`Found ${g} result(s) matching "${e}" (${l.length} obs, ${u.length} sessions, ${d.length} prompts):
|
|
|
|
`,S=v.map((R,x)=>R.type==="observation"?At(R.data,x):R.type==="session"?on(R.data,x):Ol(R.data,x));E=w+S.join(`
|
|
|
|
`)+ar()}else E=v.map(S=>S.type==="observation"?Nt(S.data):S.type==="session"?cn(S.data):Il(S.data)).join(`
|
|
|
|
---
|
|
|
|
`);return{content:[{type:"text",text:E}]}}catch(e){return{content:[{type:"text",text:`Search failed: ${e.message}`}],isError:!0}}}},{name:"timeline",description:"Get a unified timeline of context around a specific point in time OR search query. Supports two modes: (1) anchor-based: provide observation ID, session ID, or timestamp to center timeline around; (2) query-based: provide natural language query to find relevant observation and center timeline around it. All record types (observations, sessions, prompts) are interleaved chronologically.",inputSchema:c.object({anchor:c.union([c.number(),c.string()]).optional().describe('Anchor point: observation ID (number), session ID (e.g., "S123"), or ISO timestamp. Use this OR query, not both.'),query:c.string().optional().describe("Natural language search query to find relevant observation as anchor. Use this OR anchor, not both."),depth_before:c.number().min(0).max(50).default(10).describe("Number of records to retrieve before anchor (default: 10)"),depth_after:c.number().min(0).max(50).default(10).describe("Number of records to retrieve after anchor (default: 10)"),project:c.string().optional().describe("Filter by project name")}),handler:async s=>{try{let g=function(x){return new Date(x).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric"})},y=function(x){return new Date(x).toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})},v=function(x){return new Date(x).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})},E=function(x){return x?Math.ceil(x.length/4):0};var e=g,r=y,a=v,t=E;let{anchor:n,query:o,depth_before:i=10,depth_after:l=10,project:u}=s;if(!n&&!o)return{content:[{type:"text",text:'Error: Must provide either "anchor" or "query" parameter'}],isError:!0};if(n&&o)return{content:[{type:"text",text:'Error: Cannot provide both "anchor" and "query" parameters. Use one or the other.'}],isError:!0};let d,f,m;if(o){let x=[];if(Te)try{console.error("[search-server] Using hybrid semantic search for timeline query");let N=await Ye(o,100);if(console.error(`[search-server] Chroma returned ${N.ids.length} semantic matches`),N.ids.length>0){let j=Date.now()-7776e6,$=N.ids.filter((D,C)=>{let F=N.metadatas[C];return F&&F.created_at_epoch>j});$.length>0&&(x=ie.getObservationsByIds($,{orderBy:"date_desc",limit:1}))}}catch(N){console.error("[search-server] Chroma query failed - no results (FTS5 fallback removed):",N.message)}if(x.length===0)return{content:[{type:"text",text:`No observations found matching "${o}". Try a different search query.`}]};let T=x[0];d=T.id,f=T.created_at_epoch,console.error(`[search-server] Query mode: Using observation #${T.id} as timeline anchor`),m=ie.getTimelineAroundObservation(T.id,T.created_at_epoch,i,l,u)}else if(typeof n=="number"){let x=ie.getObservationById(n);if(!x)return{content:[{type:"text",text:`Observation #${n} not found`}],isError:!0};d=n,f=x.created_at_epoch,m=ie.getTimelineAroundObservation(n,f,i,l,u)}else if(typeof n=="string")if(n.startsWith("S")||n.startsWith("#S")){let x=n.replace(/^#?S/,""),T=parseInt(x,10),N=ie.getSessionSummariesByIds([T]);if(N.length===0)return{content:[{type:"text",text:`Session #${T} not found`}],isError:!0};f=N[0].created_at_epoch,d=`S${T}`,m=ie.getTimelineAroundTimestamp(f,i,l,u)}else{let x=new Date(n);if(isNaN(x.getTime()))return{content:[{type:"text",text:`Invalid timestamp: ${n}`}],isError:!0};f=x.getTime(),d=n,m=ie.getTimelineAroundTimestamp(f,i,l,u)}else return{content:[{type:"text",text:'Invalid anchor: must be observation ID (number), session ID (e.g., "S123"), or ISO timestamp'}],isError:!0};let p=[...m.observations.map(x=>({type:"observation",data:x,epoch:x.created_at_epoch})),...m.sessions.map(x=>({type:"session",data:x,epoch:x.created_at_epoch})),...m.prompts.map(x=>({type:"prompt",data:x,epoch:x.created_at_epoch}))];if(p.sort((x,T)=>x.epoch-T.epoch),p.length===0)return{content:[{type:"text",text:o?`Found observation matching "${o}", but no timeline context available (${i} records before, ${l} records after).`:`No context found around anchor (${i} records before, ${l} records after)`}]};let w=[];if(o){let x=p.find(N=>N.type==="observation"&&N.data.id===d),T=x?x.data.title||"Untitled":"Unknown";w.push(`# Timeline for query: "${o}"`),w.push(`**Anchor:** Observation #${d} - ${T}`)}else w.push(`# Timeline around anchor: ${d}`);w.push(`**Window:** ${i} records before \u2192 ${l} records after | **Items:** ${p.length} (${m.observations.length} obs, ${m.sessions.length} sessions, ${m.prompts.length} prompts)`),w.push(""),w.push("**Legend:** \u{1F3AF} session-request | \u{1F534} bugfix | \u{1F7E3} feature | \u{1F504} refactor | \u2705 change | \u{1F535} discovery | \u{1F9E0} decision"),w.push("");let S=new Map;for(let x of p){let T=g(x.epoch);S.has(T)||S.set(T,[]),S.get(T).push(x)}let R=Array.from(S.entries()).sort((x,T)=>{let N=new Date(x[0]).getTime(),j=new Date(T[0]).getTime();return N-j});for(let[x,T]of R){w.push(`### ${x}`),w.push("");let N=null,j="",$=!1;for(let D of T){let C=typeof d=="number"&&D.type==="observation"&&D.data.id===d||typeof d=="string"&&d.startsWith("S")&&D.type==="session"&&`S${D.data.id}`===d;if(D.type==="session"){$&&(w.push(""),$=!1,N=null,j="");let F=D.data,I=F.request||"Session summary",A=`claude-mem://session-summary/${F.id}`,M=C?" \u2190 **ANCHOR**":"";w.push(`**\u{1F3AF} #S${F.id}** ${I} (${v(D.epoch)}) [\u2192](${A})${M}`),w.push("")}else if(D.type==="prompt"){$&&(w.push(""),$=!1,N=null,j="");let F=D.data,I=F.prompt.length>100?F.prompt.substring(0,100)+"...":F.prompt;w.push(`**\u{1F4AC} User Prompt #${F.prompt_number}** (${v(D.epoch)})`),w.push(`> ${I}`),w.push("")}else if(D.type==="observation"){let F=D.data,I="General";I!==N&&($&&w.push(""),w.push(`**${I}**`),w.push("| ID | Time | T | Title | Tokens |"),w.push("|----|------|---|-------|--------|"),N=I,$=!0,j="");let A="\u2022";switch(F.type){case"bugfix":A="\u{1F534}";break;case"feature":A="\u{1F7E3}";break;case"refactor":A="\u{1F504}";break;case"change":A="\u2705";break;case"discovery":A="\u{1F535}";break;case"decision":A="\u{1F9E0}";break}let M=y(D.epoch),ee=F.title||"Untitled",Q=E(F.narrative),X=M!==j?M:"\u2033";j=M;let z=C?" \u2190 **ANCHOR**":"";w.push(`| #${F.id} | ${X} | ${A} | ${ee}${z} | ~${Q} |`)}}$&&w.push("")}return{content:[{type:"text",text:w.join(`
|
|
`)}]}}catch(n){return{content:[{type:"text",text:`Timeline query failed: ${n.message}`}],isError:!0}}}},{name:"decisions",description:'Semantic shortcut to find decision-type observations. Returns observations where important architectural, technical, or process decisions were made. Equivalent to find_by_type with type="decision".',inputSchema:c.object({format:c.enum(["index","full"]).default("index").describe('Output format: "index" for titles/dates only (default), "full" for complete details'),project:c.string().optional().describe("Filter by project name"),dateRange:c.object({start:c.union([c.string(),c.number()]).optional(),end:c.union([c.string(),c.number()]).optional()}).optional().describe("Filter by date range"),limit:c.number().min(1).max(100).default(20).describe("Maximum number of results"),offset:c.number().min(0).default(0).describe("Number of results to skip"),orderBy:c.enum(["relevance","date_desc","date_asc"]).default("date_desc").describe("Sort order")}),handler:async s=>{try{let{format:e="index",...r}=s,a=[];if(Te)try{console.error("[search-server] Using metadata-first + semantic ranking for decisions");let n=_e.findByType("decision",r);if(n.length>0){let o=n.map(u=>u.id),i=await Ye("decision",Math.min(o.length,100)),l=[];for(let u of i.ids)o.includes(u)&&!l.includes(u)&&l.push(u);l.length>0&&(a=ie.getObservationsByIds(l,{limit:r.limit||20}),a.sort((u,d)=>l.indexOf(u.id)-l.indexOf(d.id)))}}catch(n){console.error("[search-server] Chroma ranking failed, using SQLite order:",n.message)}if(a.length===0&&(a=_e.findByType("decision",r)),a.length===0)return{content:[{type:"text",text:"No decision observations found"}]};let t;if(e==="index"){let n=`Found ${a.length} decision(s):
|
|
|
|
`,o=a.map((i,l)=>At(i,l));t=n+o.join(`
|
|
|
|
`)}else t=a.map(o=>Nt(o)).join(`
|
|
|
|
---
|
|
|
|
`);return{content:[{type:"text",text:t}]}}catch(e){return{content:[{type:"text",text:`Search failed: ${e.message}`}],isError:!0}}}},{name:"changes",description:'Semantic shortcut to find change-related observations. Returns observations documenting what changed in the codebase, system behavior, or project state. Searches for type="change" OR concept="change" OR concept="what-changed".',inputSchema:c.object({format:c.enum(["index","full"]).default("index").describe('Output format: "index" for titles/dates only (default), "full" for complete details'),project:c.string().optional().describe("Filter by project name"),dateRange:c.object({start:c.union([c.string(),c.number()]).optional(),end:c.union([c.string(),c.number()]).optional()}).optional().describe("Filter by date range"),limit:c.number().min(1).max(100).default(20).describe("Maximum number of results"),offset:c.number().min(0).default(0).describe("Number of results to skip"),orderBy:c.enum(["relevance","date_desc","date_asc"]).default("date_desc").describe("Sort order")}),handler:async s=>{try{let{format:e="index",...r}=s,a=[];if(Te)try{console.error("[search-server] Using hybrid search for change-related observations");let n=_e.findByType("change",r),o=_e.findByConcept("change",r),i=_e.findByConcept("what-changed",r),l=new Set;if([...n,...o,...i].forEach(u=>l.add(u.id)),l.size>0){let u=Array.from(l),d=await Ye("what changed",Math.min(u.length,100)),f=[];for(let m of d.ids)u.includes(m)&&!f.includes(m)&&f.push(m);f.length>0&&(a=ie.getObservationsByIds(f,{limit:r.limit||20}),a.sort((m,p)=>f.indexOf(m.id)-f.indexOf(p.id)))}}catch(n){console.error("[search-server] Chroma ranking failed, using SQLite order:",n.message)}if(a.length===0){let n=_e.findByType("change",r),o=_e.findByConcept("change",r),i=_e.findByConcept("what-changed",r),l=new Set;[...n,...o,...i].forEach(u=>l.add(u.id)),a=Array.from(l).map(u=>n.find(d=>d.id===u)||o.find(d=>d.id===u)||i.find(d=>d.id===u)).filter(Boolean),a.sort((u,d)=>d.created_at_epoch-u.created_at_epoch),a=a.slice(0,r.limit||20)}if(a.length===0)return{content:[{type:"text",text:"No change-related observations found"}]};let t;if(e==="index"){let n=`Found ${a.length} change-related observation(s):
|
|
|
|
`,o=a.map((i,l)=>At(i,l));t=n+o.join(`
|
|
|
|
`)}else t=a.map(o=>Nt(o)).join(`
|
|
|
|
---
|
|
|
|
`);return{content:[{type:"text",text:t}]}}catch(e){return{content:[{type:"text",text:`Search failed: ${e.message}`}],isError:!0}}}},{name:"how_it_works",description:'Semantic shortcut to find "how it works" explanations. Returns observations documenting system architecture, component interactions, data flow, and technical mechanisms. Searches for concept="how-it-works".',inputSchema:c.object({format:c.enum(["index","full"]).default("index").describe('Output format: "index" for titles/dates only (default), "full" for complete details'),project:c.string().optional().describe("Filter by project name"),dateRange:c.object({start:c.union([c.string(),c.number()]).optional(),end:c.union([c.string(),c.number()]).optional()}).optional().describe("Filter by date range"),limit:c.number().min(1).max(100).default(20).describe("Maximum number of results"),offset:c.number().min(0).default(0).describe("Number of results to skip"),orderBy:c.enum(["relevance","date_desc","date_asc"]).default("date_desc").describe("Sort order")}),handler:async s=>{try{let{format:e="index",...r}=s,a=[];if(Te)try{console.error("[search-server] Using metadata-first + semantic ranking for how-it-works");let n=_e.findByConcept("how-it-works",r);if(n.length>0){let o=n.map(u=>u.id),i=await Ye("how it works architecture",Math.min(o.length,100)),l=[];for(let u of i.ids)o.includes(u)&&!l.includes(u)&&l.push(u);l.length>0&&(a=ie.getObservationsByIds(l,{limit:r.limit||20}),a.sort((u,d)=>l.indexOf(u.id)-l.indexOf(d.id)))}}catch(n){console.error("[search-server] Chroma ranking failed, using SQLite order:",n.message)}if(a.length===0&&(a=_e.findByConcept("how-it-works",r)),a.length===0)return{content:[{type:"text",text:'No "how it works" observations found'}]};let t;if(e==="index"){let n=`Found ${a.length} "how it works" observation(s):
|
|
|
|
`,o=a.map((i,l)=>At(i,l));t=n+o.join(`
|
|
|
|
`)}else t=a.map(o=>Nt(o)).join(`
|
|
|
|
---
|
|
|
|
`);return{content:[{type:"text",text:t}]}}catch(e){return{content:[{type:"text",text:`Search failed: ${e.message}`}],isError:!0}}}},{name:"search_observations",description:'DEPRECATED: Use the unified "search" tool instead. Search observations using vector-first semantic search (ChromaDB). IMPORTANT: Always use index format first (default) to get an overview with minimal token usage, then use format: "full" only for specific items of interest.',inputSchema:c.object({query:c.string().describe("Natural language search query for semantic ranking via ChromaDB vector search"),format:c.enum(["index","full"]).default("index").describe('Output format: "index" for titles/dates only (default, RECOMMENDED for initial search), "full" for complete details (use only after reviewing index results)'),...Rh.shape}),handler:async s=>{try{let{query:e,format:r="index",...a}=s,t=[];if(Te)try{console.error("[search-server] Using hybrid semantic search (Chroma + SQLite)");let o=await Ye(e,100);if(console.error(`[search-server] Chroma returned ${o.ids.length} semantic matches`),o.ids.length>0){let i=Date.now()-7776e6,l=o.ids.filter((u,d)=>{let f=o.metadatas[d];return f&&f.created_at_epoch>i});if(console.error(`[search-server] ${l.length} results within 90-day window`),l.length>0){let u=a.limit||20;t=ie.getObservationsByIds(l,{orderBy:"date_desc",limit:u}),console.error(`[search-server] Hydrated ${t.length} observations from SQLite`)}}}catch(o){console.error("[search-server] Chroma query failed - no results (FTS5 fallback removed):",o.message)}if(t.length===0)return{content:[{type:"text",text:`No observations found matching "${e}"`}]};let n;if(r==="index"){let o=`Found ${t.length} observation(s) matching "${e}":
|
|
|
|
`,i=t.map((l,u)=>At(l,u));n=o+i.join(`
|
|
|
|
`)+ar()}else n=t.map(i=>Nt(i)).join(`
|
|
|
|
---
|
|
|
|
`);return{content:[{type:"text",text:n}]}}catch(e){return{content:[{type:"text",text:`Search failed: ${e.message}`}],isError:!0}}}},{name:"search_sessions",description:'DEPRECATED: Use the unified "search" tool instead. Search session summaries using vector-first semantic search (ChromaDB). IMPORTANT: Always use index format first (default) to get an overview with minimal token usage, then use format: "full" only for specific items of interest.',inputSchema:c.object({query:c.string().describe("Natural language search query for semantic ranking via ChromaDB vector search"),format:c.enum(["index","full"]).default("index").describe('Output format: "index" for titles/dates only (default, RECOMMENDED for initial search), "full" for complete details (use only after reviewing index results)'),project:c.string().optional().describe("Filter by project name"),dateRange:c.object({start:c.union([c.string(),c.number()]).optional(),end:c.union([c.string(),c.number()]).optional()}).optional().describe("Filter by date range"),limit:c.number().min(1).max(100).default(20).describe("Maximum number of results"),offset:c.number().min(0).default(0).describe("Number of results to skip"),orderBy:c.enum(["relevance","date_desc","date_asc"]).default("date_desc").describe("Sort order")}),handler:async s=>{try{let{query:e,format:r="index",...a}=s,t=[];if(Te)try{console.error("[search-server] Using hybrid semantic search for sessions");let o=await Ye(e,100,{doc_type:"session_summary"});if(console.error(`[search-server] Chroma returned ${o.ids.length} semantic matches`),o.ids.length>0){let i=Date.now()-7776e6,l=o.ids.filter((u,d)=>{let f=o.metadatas[d];return f&&f.created_at_epoch>i});if(console.error(`[search-server] ${l.length} results within 90-day window`),l.length>0){let u=a.limit||20;t=ie.getSessionSummariesByIds(l,{orderBy:"date_desc",limit:u}),console.error(`[search-server] Hydrated ${t.length} sessions from SQLite`)}}}catch(o){console.error("[search-server] Chroma query failed - no results (FTS5 fallback removed):",o.message)}if(t.length===0)return{content:[{type:"text",text:`No sessions found matching "${e}"`}]};let n;if(r==="index"){let o=`Found ${t.length} session(s) matching "${e}":
|
|
|
|
`,i=t.map((l,u)=>on(l,u));n=o+i.join(`
|
|
|
|
`)+ar()}else n=t.map(i=>cn(i)).join(`
|
|
|
|
---
|
|
|
|
`);return{content:[{type:"text",text:n}]}}catch(e){return{content:[{type:"text",text:`Search failed: ${e.message}`}],isError:!0}}}},{name:"find_by_concept",description:'Find observations tagged with a specific concept. Available concepts: "discovery", "problem-solution", "what-changed", "how-it-works", "pattern", "gotcha", "change". IMPORTANT: Always use index format first (default) to get an overview with minimal token usage, then use format: "full" only for specific items of interest.',inputSchema:c.object({concept:c.string().describe("Concept tag to search for. Available: discovery, problem-solution, what-changed, how-it-works, pattern, gotcha, change"),format:c.enum(["index","full"]).default("index").describe('Output format: "index" for titles/dates only (default, RECOMMENDED for initial search), "full" for complete details (use only after reviewing index results)'),project:c.string().optional().describe("Filter by project name"),dateRange:c.object({start:c.union([c.string(),c.number()]).optional(),end:c.union([c.string(),c.number()]).optional()}).optional().describe("Filter by date range"),limit:c.number().min(1).max(100).default(20).describe("Maximum results. IMPORTANT: Start with 3-5 to avoid exceeding MCP token limits, even in index mode."),offset:c.number().min(0).default(0).describe("Number of results to skip"),orderBy:c.enum(["relevance","date_desc","date_asc"]).default("date_desc").describe("Sort order")}),handler:async s=>{try{let{concept:e,format:r="index",...a}=s,t=[];if(Te)try{console.error("[search-server] Using metadata-first + semantic ranking for concept search");let o=_e.findByConcept(e,a);if(console.error(`[search-server] Found ${o.length} observations with concept "${e}"`),o.length>0){let i=o.map(d=>d.id),l=await Ye(e,Math.min(i.length,100)),u=[];for(let d of l.ids)i.includes(d)&&!u.includes(d)&&u.push(d);console.error(`[search-server] Chroma ranked ${u.length} results by semantic relevance`),u.length>0&&(t=ie.getObservationsByIds(u,{limit:a.limit||20}),t.sort((d,f)=>u.indexOf(d.id)-u.indexOf(f.id)))}}catch(o){console.error("[search-server] Chroma ranking failed, using SQLite order:",o.message)}if(t.length===0&&(console.error("[search-server] Using SQLite-only concept search"),t=_e.findByConcept(e,a)),t.length===0)return{content:[{type:"text",text:`No observations found with concept "${e}"`}]};let n;if(r==="index"){let o=`Found ${t.length} observation(s) with concept "${e}":
|
|
|
|
`,i=t.map((l,u)=>At(l,u));n=o+i.join(`
|
|
|
|
`)+ar()}else n=t.map(i=>Nt(i)).join(`
|
|
|
|
---
|
|
|
|
`);return{content:[{type:"text",text:n}]}}catch(e){return{content:[{type:"text",text:`Search failed: ${e.message}`}],isError:!0}}}},{name:"find_by_file",description:'Find observations and sessions that reference a specific file path. IMPORTANT: Always use index format first (default) to get an overview with minimal token usage, then use format: "full" only for specific items of interest.',inputSchema:c.object({filePath:c.string().describe("File path to search for (supports partial matching)"),format:c.enum(["index","full"]).default("index").describe('Output format: "index" for titles/dates only (default, RECOMMENDED for initial search), "full" for complete details (use only after reviewing index results)'),project:c.string().optional().describe("Filter by project name"),dateRange:c.object({start:c.union([c.string(),c.number()]).optional(),end:c.union([c.string(),c.number()]).optional()}).optional().describe("Filter by date range"),limit:c.number().min(1).max(100).default(20).describe("Maximum results. IMPORTANT: Start with 3-5 to avoid exceeding MCP token limits, even in index mode."),offset:c.number().min(0).default(0).describe("Number of results to skip"),orderBy:c.enum(["relevance","date_desc","date_asc"]).default("date_desc").describe("Sort order")}),handler:async s=>{try{let{filePath:e,format:r="index",...a}=s,t=[],n=[];if(Te)try{console.error("[search-server] Using metadata-first + semantic ranking for file search");let l=_e.findByFile(e,a);if(console.error(`[search-server] Found ${l.observations.length} observations, ${l.sessions.length} sessions for file "${e}"`),n=l.sessions,l.observations.length>0){let u=l.observations.map(m=>m.id),d=await Ye(e,Math.min(u.length,100)),f=[];for(let m of d.ids)u.includes(m)&&!f.includes(m)&&f.push(m);console.error(`[search-server] Chroma ranked ${f.length} observations by semantic relevance`),f.length>0&&(t=ie.getObservationsByIds(f,{limit:a.limit||20}),t.sort((m,p)=>f.indexOf(m.id)-f.indexOf(p.id)))}}catch(l){console.error("[search-server] Chroma ranking failed, using SQLite order:",l.message)}if(t.length===0&&n.length===0){console.error("[search-server] Using SQLite-only file search");let l=_e.findByFile(e,a);t=l.observations,n=l.sessions}let o=t.length+n.length;if(o===0)return{content:[{type:"text",text:`No results found for file "${e}"`}]};let i;if(r==="index"){let l=`Found ${o} result(s) for file "${e}":
|
|
|
|
`,u=[];t.forEach((d,f)=>{u.push(At(d,f))}),n.forEach((d,f)=>{u.push(on(d,f+t.length))}),i=l+u.join(`
|
|
|
|
`)+ar()}else{let l=[];t.forEach(u=>{l.push(Nt(u))}),n.forEach(u=>{l.push(cn(u))}),i=l.join(`
|
|
|
|
---
|
|
|
|
`)}return{content:[{type:"text",text:i}]}}catch(e){return{content:[{type:"text",text:`Search failed: ${e.message}`}],isError:!0}}}},{name:"find_by_type",description:'Find observations of a specific type (decision, bugfix, feature, refactor, discovery, change). IMPORTANT: Always use index format first (default) to get an overview with minimal token usage, then use format: "full" only for specific items of interest.',inputSchema:c.object({type:c.union([c.enum(["decision","bugfix","feature","refactor","discovery","change"]),c.array(c.enum(["decision","bugfix","feature","refactor","discovery","change"]))]).describe("Observation type(s) to filter by"),format:c.enum(["index","full"]).default("index").describe('Output format: "index" for titles/dates only (default, RECOMMENDED for initial search), "full" for complete details (use only after reviewing index results)'),project:c.string().optional().describe("Filter by project name"),dateRange:c.object({start:c.union([c.string(),c.number()]).optional(),end:c.union([c.string(),c.number()]).optional()}).optional().describe("Filter by date range"),limit:c.number().min(1).max(100).default(20).describe("Maximum results. IMPORTANT: Start with 3-5 to avoid exceeding MCP token limits, even in index mode."),offset:c.number().min(0).default(0).describe("Number of results to skip"),orderBy:c.enum(["relevance","date_desc","date_asc"]).default("date_desc").describe("Sort order")}),handler:async s=>{try{let{type:e,format:r="index",...a}=s,t=Array.isArray(e)?e.join(", "):e,n=[];if(Te)try{console.error("[search-server] Using metadata-first + semantic ranking for type search");let i=_e.findByType(e,a);if(console.error(`[search-server] Found ${i.length} observations with type "${t}"`),i.length>0){let l=i.map(f=>f.id),u=await Ye(t,Math.min(l.length,100)),d=[];for(let f of u.ids)l.includes(f)&&!d.includes(f)&&d.push(f);console.error(`[search-server] Chroma ranked ${d.length} results by semantic relevance`),d.length>0&&(n=ie.getObservationsByIds(d,{limit:a.limit||20}),n.sort((f,m)=>d.indexOf(f.id)-d.indexOf(m.id)))}}catch(i){console.error("[search-server] Chroma ranking failed, using SQLite order:",i.message)}if(n.length===0&&(console.error("[search-server] Using SQLite-only type search"),n=_e.findByType(e,a)),n.length===0)return{content:[{type:"text",text:`No observations found with type "${t}"`}]};let o;if(r==="index"){let i=`Found ${n.length} observation(s) with type "${t}":
|
|
|
|
`,l=n.map((u,d)=>At(u,d));o=i+l.join(`
|
|
|
|
`)+ar()}else o=n.map(l=>Nt(l)).join(`
|
|
|
|
---
|
|
|
|
`);return{content:[{type:"text",text:o}]}}catch(e){return{content:[{type:"text",text:`Search failed: ${e.message}`}],isError:!0}}}},{name:"get_recent_context",description:"Get recent session context including summaries and observations for a project",inputSchema:c.object({project:c.string().optional().describe("Project name (defaults to current working directory basename)"),limit:c.number().min(1).max(10).default(3).describe("Number of recent sessions to retrieve")}),handler:async s=>{try{let e=s.project||(0,$l.basename)(process.cwd()),r=s.limit||3,a=ie.getRecentSessionsWithStatus(e,r);if(a.length===0)return{content:[{type:"text",text:`# Recent Session Context
|
|
|
|
No previous sessions found for project "${e}".`}]};let t=[];t.push("# Recent Session Context"),t.push(""),t.push(`Showing last ${a.length} session(s) for **${e}**:`),t.push("");for(let n of a)if(n.sdk_session_id){if(t.push("---"),t.push(""),n.has_summary){let o=ie.getSummaryForSession(n.sdk_session_id);if(o){let i=o.prompt_number?` (Prompt #${o.prompt_number})`:"";if(t.push(`**Summary${i}**`),t.push(""),o.request&&t.push(`**Request:** ${o.request}`),o.completed&&t.push(`**Completed:** ${o.completed}`),o.learned&&t.push(`**Learned:** ${o.learned}`),o.next_steps&&t.push(`**Next Steps:** ${o.next_steps}`),o.files_read)try{let u=JSON.parse(o.files_read);Array.isArray(u)&&u.length>0&&t.push(`**Files Read:** ${u.join(", ")}`)}catch{o.files_read.trim()&&t.push(`**Files Read:** ${o.files_read}`)}if(o.files_edited)try{let u=JSON.parse(o.files_edited);Array.isArray(u)&&u.length>0&&t.push(`**Files Edited:** ${u.join(", ")}`)}catch{o.files_edited.trim()&&t.push(`**Files Edited:** ${o.files_edited}`)}let l=new Date(o.created_at).toLocaleString();t.push(`**Date:** ${l}`)}}else if(n.status==="active"){t.push("**In Progress**"),t.push(""),n.user_prompt&&t.push(`**Request:** ${n.user_prompt}`);let o=ie.getObservationsForSession(n.sdk_session_id);if(o.length>0){t.push(""),t.push(`**Observations (${o.length}):**`);for(let l of o)t.push(`- ${l.title}`)}else t.push(""),t.push("*No observations yet*");t.push(""),t.push("**Status:** Active - summary pending");let i=new Date(n.started_at).toLocaleString();t.push(`**Date:** ${i}`)}else{t.push(`**${n.status.charAt(0).toUpperCase()+n.status.slice(1)}**`),t.push(""),n.user_prompt&&t.push(`**Request:** ${n.user_prompt}`),t.push(""),t.push(`**Status:** ${n.status} - no summary available`);let o=new Date(n.started_at).toLocaleString();t.push(`**Date:** ${o}`)}t.push("")}return{content:[{type:"text",text:t.join(`
|
|
`)}]}}catch(e){return{content:[{type:"text",text:`Failed to get recent context: ${e.message}`}],isError:!0}}}},{name:"search_user_prompts",description:'DEPRECATED: Use the unified "search" tool instead. Search raw user prompts using vector-first semantic search (ChromaDB). Use this to find what the user actually said/requested across all sessions. IMPORTANT: Always use index format first (default) to get an overview with minimal token usage, then use format: "full" only for specific items of interest.',inputSchema:c.object({query:c.string().describe("Natural language search query for semantic ranking via ChromaDB vector search"),format:c.enum(["index","full"]).default("index").describe('Output format: "index" for truncated prompts/dates (default, RECOMMENDED for initial search), "full" for complete prompt text (use only after reviewing index results)'),project:c.string().optional().describe("Filter by project name"),dateRange:c.object({start:c.union([c.string(),c.number()]).optional(),end:c.union([c.string(),c.number()]).optional()}).optional().describe("Filter by date range"),limit:c.number().min(1).max(100).default(20).describe("Maximum number of results"),offset:c.number().min(0).default(0).describe("Number of results to skip"),orderBy:c.enum(["relevance","date_desc","date_asc"]).default("date_desc").describe("Sort order")}),handler:async s=>{try{let{query:e,format:r="index",...a}=s,t=[];if(Te)try{console.error("[search-server] Using hybrid semantic search for user prompts");let o=await Ye(e,100,{doc_type:"user_prompt"});if(console.error(`[search-server] Chroma returned ${o.ids.length} semantic matches`),o.ids.length>0){let i=Date.now()-7776e6,l=o.ids.filter((u,d)=>{let f=o.metadatas[d];return f&&f.created_at_epoch>i});if(console.error(`[search-server] ${l.length} results within 90-day window`),l.length>0){let u=a.limit||20;t=ie.getUserPromptsByIds(l,{orderBy:"date_desc",limit:u}),console.error(`[search-server] Hydrated ${t.length} user prompts from SQLite`)}}}catch(o){console.error("[search-server] Chroma query failed - no results (FTS5 fallback removed):",o.message)}if(t.length===0)return{content:[{type:"text",text:`No user prompts found matching "${e}"`}]};let n;if(r==="index"){let o=`Found ${t.length} user prompt(s) matching "${e}":
|
|
|
|
`,i=t.map((l,u)=>Ol(l,u));n=o+i.join(`
|
|
|
|
`)+ar()}else n=t.map(i=>Il(i)).join(`
|
|
|
|
---
|
|
|
|
`);return{content:[{type:"text",text:n}]}}catch(e){return{content:[{type:"text",text:`Search failed: ${e.message}`}],isError:!0}}}},{name:"get_context_timeline",description:'Get a unified timeline of context (observations, sessions, and prompts) around a specific point in time. All record types are interleaved chronologically. Useful for understanding "what was happening when X occurred". Returns depth_before records before anchor + anchor + depth_after records after (total: depth_before + 1 + depth_after mixed records).',inputSchema:c.object({anchor:c.union([c.number().describe("Observation ID to center timeline around"),c.string().describe("Session ID (format: S123) or ISO timestamp to center timeline around")]).describe('Anchor point: observation ID, session ID (e.g., "S123"), or ISO timestamp'),depth_before:c.number().min(0).max(50).default(10).describe("Number of records to retrieve before anchor, not including anchor (default: 10)"),depth_after:c.number().min(0).max(50).default(10).describe("Number of records to retrieve after anchor, not including anchor (default: 10)"),project:c.string().optional().describe("Filter by project name")}),handler:async s=>{try{let p=function(R){return new Date(R).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric"})},g=function(R){return new Date(R).toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})},y=function(R){return new Date(R).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})},v=function(R){return R?Math.ceil(R.length/4):0};var e=p,r=g,a=y,t=v;let{anchor:n,depth_before:o=10,depth_after:i=10,project:l}=s,u,d=n,f;if(typeof n=="number"){let R=ie.getObservationById(n);if(!R)return{content:[{type:"text",text:`Observation #${n} not found`}],isError:!0};u=R.created_at_epoch,f=ie.getTimelineAroundObservation(n,u,o,i,l)}else if(typeof n=="string")if(n.startsWith("S")||n.startsWith("#S")){let R=n.replace(/^#?S/,""),x=parseInt(R,10),T=ie.getSessionSummariesByIds([x]);if(T.length===0)return{content:[{type:"text",text:`Session #${x} not found`}],isError:!0};u=T[0].created_at_epoch,d=`S${x}`,f=ie.getTimelineAroundTimestamp(u,o,i,l)}else{let R=new Date(n);if(isNaN(R.getTime()))return{content:[{type:"text",text:`Invalid timestamp: ${n}`}],isError:!0};u=R.getTime(),f=ie.getTimelineAroundTimestamp(u,o,i,l)}else return{content:[{type:"text",text:'Invalid anchor: must be observation ID (number), session ID (e.g., "S123"), or ISO timestamp'}],isError:!0};let m=[...f.observations.map(R=>({type:"observation",data:R,epoch:R.created_at_epoch})),...f.sessions.map(R=>({type:"session",data:R,epoch:R.created_at_epoch})),...f.prompts.map(R=>({type:"prompt",data:R,epoch:R.created_at_epoch}))];if(m.sort((R,x)=>R.epoch-x.epoch),m.length===0)return{content:[{type:"text",text:`No context found around ${new Date(u).toLocaleString()} (${o} records before, ${i} records after)`}]};let E=[];E.push(`# Timeline around anchor: ${d}`),E.push(`**Window:** ${o} records before \u2192 ${i} records after | **Items:** ${m.length} (${f.observations.length} obs, ${f.sessions.length} sessions, ${f.prompts.length} prompts)`),E.push(""),E.push("**Legend:** \u{1F3AF} session-request | \u{1F534} bugfix | \u{1F7E3} feature | \u{1F504} refactor | \u2705 change | \u{1F535} discovery | \u{1F9E0} decision"),E.push("");let w=new Map;for(let R of m){let x=p(R.epoch);w.has(x)||w.set(x,[]),w.get(x).push(R)}let S=Array.from(w.entries()).sort((R,x)=>{let T=new Date(R[0]).getTime(),N=new Date(x[0]).getTime();return T-N});for(let[R,x]of S){E.push(`### ${R}`),E.push("");let T=null,N="",j=!1;for(let $ of x){let D=typeof d=="number"&&$.type==="observation"&&$.data.id===d||typeof d=="string"&&d.startsWith("S")&&$.type==="session"&&`S${$.data.id}`===d;if($.type==="session"){j&&(E.push(""),j=!1,T=null,N="");let C=$.data,F=C.request||"Session summary",I=`claude-mem://session-summary/${C.id}`,A=D?" \u2190 **ANCHOR**":"";E.push(`**\u{1F3AF} #S${C.id}** ${F} (${y($.epoch)}) [\u2192](${I})${A}`),E.push("")}else if($.type==="prompt"){j&&(E.push(""),j=!1,T=null,N="");let C=$.data,F=C.prompt.length>100?C.prompt.substring(0,100)+"...":C.prompt;E.push(`**\u{1F4AC} User Prompt #${C.prompt_number}** (${y($.epoch)})`),E.push(`> ${F}`),E.push("")}else if($.type==="observation"){let C=$.data,F="General";F!==T&&(j&&E.push(""),E.push(`**${F}**`),E.push("| ID | Time | T | Title | Tokens |"),E.push("|----|------|---|-------|--------|"),T=F,j=!0,N="");let I="\u2022";switch(C.type){case"bugfix":I="\u{1F534}";break;case"feature":I="\u{1F7E3}";break;case"refactor":I="\u{1F504}";break;case"change":I="\u2705";break;case"discovery":I="\u{1F535}";break;case"decision":I="\u{1F9E0}";break}let A=g($.epoch),M=C.title||"Untitled",ee=v(C.narrative),Y=A!==N?A:"\u2033";N=A;let X=D?" \u2190 **ANCHOR**":"";E.push(`| #${C.id} | ${Y} | ${I} | ${M}${X} | ~${ee} |`)}}j&&E.push("")}return{content:[{type:"text",text:E.join(`
|
|
`)}]}}catch(n){return{content:[{type:"text",text:`Timeline query failed: ${n.message}`}],isError:!0}}}},{name:"get_timeline_by_query",description:'Search for observations using natural language and get timeline context around the best match. Two modes: "auto" (default) automatically uses top result as timeline anchor; "interactive" returns top matches for you to choose from. This combines search + timeline into a single operation for faster context discovery.',inputSchema:c.object({query:c.string().describe("Natural language search query to find relevant observations"),mode:c.enum(["auto","interactive"]).default("auto").describe("auto: Automatically use top search result as timeline anchor. interactive: Show top N search results for manual anchor selection."),depth_before:c.number().min(0).max(50).default(10).describe("Number of timeline records before anchor (default: 10)"),depth_after:c.number().min(0).max(50).default(10).describe("Number of timeline records after anchor (default: 10)"),limit:c.number().min(1).max(20).default(5).describe("For interactive mode: number of top search results to display (default: 5)"),project:c.string().optional().describe("Filter by project name")}),handler:async s=>{try{let{query:n,mode:o="auto",depth_before:i=10,depth_after:l=10,limit:u=5,project:d}=s,f=[];if(Te)try{console.error("[search-server] Using hybrid semantic search for timeline query");let m=await Ye(n,100);if(console.error(`[search-server] Chroma returned ${m.ids.length} semantic matches`),m.ids.length>0){let p=Date.now()-7776e6,g=m.ids.filter((y,v)=>{let E=m.metadatas[v];return E&&E.created_at_epoch>p});console.error(`[search-server] ${g.length} results within 90-day window`),g.length>0&&(f=ie.getObservationsByIds(g,{orderBy:"date_desc",limit:o==="auto"?1:u}),console.error(`[search-server] Hydrated ${f.length} observations from SQLite`))}}catch(m){console.error("[search-server] Chroma query failed - no results (FTS5 fallback removed):",m.message)}if(f.length===0)return{content:[{type:"text",text:`No observations found matching "${n}". Try a different search query.`}]};if(o==="interactive"){let m=[];m.push("# Timeline Anchor Search Results"),m.push(""),m.push(`Found ${f.length} observation(s) matching "${n}"`),m.push(""),m.push("To get timeline context around any of these observations, use the `get_context_timeline` tool with the observation ID as the anchor."),m.push(""),m.push(`**Top ${f.length} matches:**`),m.push("");for(let p=0;p<f.length;p++){let g=f[p],y=g.title||`Observation #${g.id}`,v=new Date(g.created_at_epoch).toLocaleString(),E=g.type?`[${g.type}]`:"";m.push(`${p+1}. **${E} ${y}**`),m.push(` - ID: ${g.id}`),m.push(` - Date: ${v}`),g.subtitle&&m.push(` - ${g.subtitle}`),m.push(` - Source: claude-mem://observation/${g.id}`),m.push("")}return{content:[{type:"text",text:m.join(`
|
|
`)}]}}else{let y=function(T){return new Date(T).toLocaleString("en-US",{month:"short",day:"numeric",year:"numeric"})},v=function(T){return new Date(T).toLocaleString("en-US",{hour:"numeric",minute:"2-digit",hour12:!0})},E=function(T){return new Date(T).toLocaleString("en-US",{month:"short",day:"numeric",hour:"numeric",minute:"2-digit",hour12:!0})},w=function(T){return T?Math.ceil(T.length/4):0};var e=y,r=v,a=E,t=w;let m=f[0];console.error(`[search-server] Auto mode: Using observation #${m.id} as timeline anchor`);let p=ie.getTimelineAroundObservation(m.id,m.created_at_epoch,i,l,d),g=[...p.observations.map(T=>({type:"observation",data:T,epoch:T.created_at_epoch})),...p.sessions.map(T=>({type:"session",data:T,epoch:T.created_at_epoch})),...p.prompts.map(T=>({type:"prompt",data:T,epoch:T.created_at_epoch}))];if(g.sort((T,N)=>T.epoch-N.epoch),g.length===0)return{content:[{type:"text",text:`Found observation #${m.id} matching "${n}", but no timeline context available (${i} records before, ${l} records after).`}]};let S=[];S.push(`# Timeline for query: "${n}"`),S.push(`**Anchor:** Observation #${m.id} - ${m.title||"Untitled"}`),S.push(`**Window:** ${i} records before \u2192 ${l} records after | **Items:** ${g.length} (${p.observations.length} obs, ${p.sessions.length} sessions, ${p.prompts.length} prompts)`),S.push(""),S.push("**Legend:** \u{1F3AF} session-request | \u{1F534} bugfix | \u{1F7E3} feature | \u{1F504} refactor | \u2705 change | \u{1F535} discovery | \u{1F9E0} decision"),S.push("");let R=new Map;for(let T of g){let N=y(T.epoch);R.has(N)||R.set(N,[]),R.get(N).push(T)}let x=Array.from(R.entries()).sort((T,N)=>{let j=new Date(T[0]).getTime(),$=new Date(N[0]).getTime();return j-$});for(let[T,N]of x){S.push(`### ${T}`),S.push("");let j=null,$="",D=!1;for(let C of N){let F=C.type==="observation"&&C.data.id===m.id;if(C.type==="session"){D&&(S.push(""),D=!1,j=null,$="");let I=C.data,A=I.request||"Session summary",M=`claude-mem://session-summary/${I.id}`;S.push(`**\u{1F3AF} #S${I.id}** ${A} (${E(C.epoch)}) [\u2192](${M})`),S.push("")}else if(C.type==="prompt"){D&&(S.push(""),D=!1,j=null,$="");let I=C.data,A=I.prompt.length>100?I.prompt.substring(0,100)+"...":I.prompt;S.push(`**\u{1F4AC} User Prompt #${I.prompt_number}** (${E(C.epoch)})`),S.push(`> ${A}`),S.push("")}else if(C.type==="observation"){let I=C.data,A="General";A!==j&&(D&&S.push(""),S.push(`**${A}**`),S.push("| ID | Time | T | Title | Tokens |"),S.push("|----|------|---|-------|--------|"),j=A,D=!0,$="");let M="\u2022";switch(I.type){case"bugfix":M="\u{1F534}";break;case"feature":M="\u{1F7E3}";break;case"refactor":M="\u{1F504}";break;case"change":M="\u2705";break;case"discovery":M="\u{1F535}";break;case"decision":M="\u{1F9E0}";break}let ee=v(C.epoch),Q=I.title||"Untitled",Y=w(I.narrative),z=ee!==$?ee:"\u2033";$=ee;let pe=F?" \u2190 **ANCHOR**":"";S.push(`| #${I.id} | ${z} | ${M} | ${Q}${pe} | ~${Y} |`)}}D&&S.push("")}return{content:[{type:"text",text:S.join(`
|
|
`)}]}}}catch(n){return{content:[{type:"text",text:`Timeline query failed: ${n.message}`}],isError:!0}}}}],ln=new ws({name:"claude-mem-search",version:"1.0.0"},{capabilities:{tools:{}}});ln.setRequestHandler(ia,async()=>({tools:Al.map(s=>({name:s.name,description:s.description,inputSchema:en(s.inputSchema)}))}));ln.setRequestHandler(la,async s=>{let e=Al.find(r=>r.name===s.params.name);if(!e)throw new Error(`Unknown tool: ${s.params.name}`);try{return await e.handler(s.params.arguments||{})}catch(r){return{content:[{type:"text",text:`Tool execution failed: ${r.message}`}],isError:!0}}});async function Nl(){if(console.error("[search-server] Shutting down..."),Te)try{await Te.close(),console.error("[search-server] Chroma client closed")}catch(s){console.error("[search-server] Error closing Chroma client:",s.message)}if(_e)try{_e.close(),console.error("[search-server] SessionSearch closed")}catch(s){console.error("[search-server] Error closing SessionSearch:",s.message)}if(ie)try{ie.close(),console.error("[search-server] SessionStore closed")}catch(s){console.error("[search-server] Error closing SessionStore:",s.message)}console.error("[search-server] Shutdown complete"),process.exit(0)}process.on("SIGTERM",Nl);process.on("SIGINT",Nl);async function Th(){let s=new Os;await ln.connect(s),console.error("[search-server] Claude-mem search server started"),setTimeout(async()=>{try{console.error("[search-server] Initializing Chroma client...");let e=new As({command:"uvx",args:["chroma-mcp","--client-type","persistent","--data-dir",El],stderr:"ignore"}),r=new Is({name:"claude-mem-search-chroma-client",version:"1.0.0"},{capabilities:{}});await r.connect(e),Te=r,console.error("[search-server] Chroma client connected successfully")}catch(e){console.error("[search-server] Failed to initialize Chroma client:",e.message),console.error("[search-server] Vector search unavailable - text queries will return empty results (FTS5 fallback removed)"),console.error("[search-server] Install UVX/Python to enable vector search: https://docs.astral.sh/uv/getting-started/installation/"),Te=null}},0)}Th().catch(s=>{console.error("[search-server] Fatal error:",s),process.exit(1)});
|
|
/*! Bundled license information:
|
|
|
|
uri-js/dist/es5/uri.all.js:
|
|
(** @license URI.js v4.4.1 (c) 2011 Gary Court. License: http://github.com/garycourt/uri-js *)
|
|
*/
|