@vibecontrols/agent 2026.1125.2 → 2026.1127.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/agent-config-xwvsmn6b.js +2 -0
- package/dist/{agent-ready-tracker-mewxehg9.js → agent-ready-tracker-7ebr09d9.js} +1 -1
- package/dist/app-4t875vbv.js +2 -0
- package/dist/autostart.cmd-mdyv35dn.js +2 -0
- package/dist/bootstrap-workspace-1pt0bwy6.js +2 -0
- package/dist/bootstrap.service-gehm65tt.js +2 -0
- package/dist/bridge-client-9ax1cvj6.js +2 -0
- package/dist/bridge-commands-xhzhghxt.js +2 -0
- package/dist/cli.js +2 -2
- package/dist/daemon-profile-fnhc7pcf.js +2 -0
- package/dist/{finalize-retry-worker-az74f2qv.js → finalize-retry-worker-c38km3mt.js} +1 -1
- package/dist/gateway-client-3zp6kkav.js +2 -0
- package/dist/{getMachineId-bsd-4w1wmcjv.js → getMachineId-bsd-qjqk66se.js} +1 -1
- package/dist/{getMachineId-darwin-kejwz8w5.js → getMachineId-darwin-tqhg8pqb.js} +1 -1
- package/dist/{getMachineId-linux-mpm53wat.js → getMachineId-linux-ygfapc26.js} +1 -1
- package/dist/{getMachineId-unsupported-54seyw5v.js → getMachineId-unsupported-87w3cred.js} +1 -1
- package/dist/{getMachineId-win-cva7ghz9.js → getMachineId-win-jrtkq63e.js} +1 -1
- package/dist/{index-0gmhd3hs.js → index-0rmmrrfh.js} +3 -3
- package/dist/{index-7s7ee1y9.js → index-0vbsve3v.js} +4 -4
- package/dist/{index-7f2k4g6q.js → index-12gb48hg.js} +4 -4
- package/dist/{index-4rasb3ph.js → index-12rehjp4.js} +9 -9
- package/dist/{index-7wben1jx.js → index-164mtd7z.js} +2 -2
- package/dist/index-1smr1csg.js +116 -0
- package/dist/{index-w0m3jm0s.js → index-1t74r13z.js} +2 -2
- package/dist/{index-9xrhb68w.js → index-31ssvzw8.js} +2 -2
- package/dist/{index-652f9scs.js → index-4kf3nr14.js} +2 -2
- package/dist/{index-qe3xpt41.js → index-5s4mtrqb.js} +2 -2
- package/dist/{index-jmx5awkj.js → index-62vfxd90.js} +2 -2
- package/dist/{index-5ccmrpb5.js → index-6b9vh0gq.js} +48 -48
- package/dist/{index-7gk1x74m.js → index-6nv5rdqh.js} +2 -2
- package/dist/{index-er5k6qtr.js → index-6wfd7cv3.js} +4 -4
- package/dist/{index-t6p4szqx.js → index-76vza24h.js} +3 -3
- package/dist/{index-76m37yd8.js → index-7bm1kptr.js} +3 -3
- package/dist/{index-0qjbnyg4.js → index-7wm4bqx5.js} +5 -5
- package/dist/{index-akk3rxnn.js → index-90gn0b6x.js} +3 -3
- package/dist/{index-2r6cmxxz.js → index-axkwyajz.js} +1 -1
- package/dist/index-bk17490n.js +3 -0
- package/dist/{index-2vcxt38h.js → index-bpzk441p.js} +2 -2
- package/dist/{index-4z1y39jt.js → index-cn4p1ks0.js} +2 -2
- package/dist/{index-byerrz46.js → index-damc6cvc.js} +2 -2
- package/dist/{index-xtd0j8ve.js → index-dgbe8jm8.js} +2 -2
- package/dist/index-dtxd2xmg.js +158 -0
- package/dist/index-e5jdx9c1.js +3 -0
- package/dist/{index-tahaxp6n.js → index-ednz6yz2.js} +2 -2
- package/dist/{index-hsrt2v87.js → index-f5nmxa9e.js} +1 -1
- package/dist/{index-thm1bzpj.js → index-j8j1h00a.js} +9 -9
- package/dist/{index-kwhx023z.js → index-j99tkngg.js} +10 -10
- package/dist/{index-fqz9n560.js → index-nz7mhjjn.js} +3 -3
- package/dist/index-p1b10hs1.js +11 -0
- package/dist/{index-qfxwk38p.js → index-p7fbnfwd.js} +2 -2
- package/dist/{index-jnxjjx2y.js → index-ppxayc0x.js} +2 -2
- package/dist/index-qzwbctkv.js +16 -0
- package/dist/{index-a0vx2zyx.js → index-rae5bn1c.js} +2 -2
- package/dist/{index-8rbhm4g8.js → index-rhn7wy1p.js} +2 -2
- package/dist/index-sd5bt3g5.js +2 -0
- package/dist/{index-vtsd74g0.js → index-sq5j8bjn.js} +6 -6
- package/dist/{index-t5cfkz1e.js → index-v77bb0rm.js} +3 -3
- package/dist/{index-v16qz1fa.js → index-vhz1c474.js} +2 -2
- package/dist/{index-ywnfz6nm.js → index-wxb9dgwq.js} +1 -1
- package/dist/index-x4z055t8.js +3 -0
- package/dist/{index-haww9jpq.js → index-xetd52ad.js} +2 -2
- package/dist/{index-d59kp6zr.js → index-yfk0pb00.js} +2 -2
- package/dist/{index-cy97asyh.js → index-zcnfj1q4.js} +3 -3
- package/dist/{index-c4whjk5r.js → index-zn9snqbg.js} +2 -2
- package/dist/index.js +3 -3
- package/dist/interactive-52x9hv6c.js +2 -0
- package/dist/key.cmd-y415ngam.js +2 -0
- package/dist/log-shipper-02rqvtq8.js +2 -0
- package/dist/{path-utils-r4df8d3w.js → path-utils-qgkdkp5j.js} +1 -1
- package/dist/plugin-system-7qjqrq7s.js +2 -0
- package/dist/prereqs-runner-w7z2dwa6.js +2 -0
- package/dist/profile-mount-ga5z1vx9.js +2 -0
- package/dist/prune-stale-shims-vejvb1rj.js +2 -0
- package/dist/register-core-vv5pddxj.js +2 -0
- package/dist/secondary-profile-attach-222s85md.js +2 -0
- package/dist/subprocess-p9bv9nqz.js +2 -0
- package/dist/telemetry-1d3t1mbf.js +2 -0
- package/dist/tunnel-bootstrap-20vwak7q.js +2 -0
- package/package.json +1 -1
- package/dist/agent-config-v9d7gcz0.js +0 -2
- package/dist/app-xc9c1d71.js +0 -2
- package/dist/autostart.cmd-ahet7b1t.js +0 -2
- package/dist/bootstrap-workspace-3pb8qjsh.js +0 -2
- package/dist/bootstrap.service-9m7m1ksa.js +0 -2
- package/dist/bridge-client-xvqy3n15.js +0 -2
- package/dist/daemon-profile-sg8fp50z.js +0 -2
- package/dist/gateway-client-ermpz52n.js +0 -2
- package/dist/index-5021rk8n.js +0 -3
- package/dist/index-b3v08awy.js +0 -3
- package/dist/index-mmx2kp76.js +0 -16
- package/dist/index-ss5gez2p.js +0 -2
- package/dist/index-tts92sdm.js +0 -5
- package/dist/index-x83tcr8f.js +0 -158
- package/dist/index-zcmhy3jv.js +0 -116
- package/dist/interactive-vbz68zh5.js +0 -2
- package/dist/key.cmd-f6rjvjy8.js +0 -2
- package/dist/log-shipper-0erbwn0q.js +0 -2
- package/dist/plugin-system-byzwda4c.js +0 -2
- package/dist/prereqs-runner-gca0bytz.js +0 -2
- package/dist/profile-mount-s4mc1x18.js +0 -2
- package/dist/prune-stale-shims-4nqtv0xt.js +0 -2
- package/dist/register-core-ws2axmcf.js +0 -2
- package/dist/secondary-profile-attach-em1tq7vq.js +0 -2
- package/dist/subprocess-4gg77skg.js +0 -2
- package/dist/telemetry-nmtywcba.js +0 -2
- package/dist/tunnel-bootstrap-tjwz90pb.js +0 -2
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{z,ii,Vt,It,T,O,C,N,e,it}from"./index-0qjbnyg4.js";import{M,X}from"./index-kwhx023z.js";import{_e,W}from"./index-tts92sdm.js";import{K}from"./index-mmx2kp76.js";import{pt}from"./index-qfxwk38p.js";import{Te,Ee,ke}from"./index-er5k6qtr.js";import{b}from"./index-w4jqdhc2.js";import{existsSync as Wa,readFileSync as Ja}from"fs";import{dirname as Ei,join as Ya}from"path";import{fileURLToPath as Qa}from"url";import{closeSync as Za,existsSync as eo,mkdirSync as to,openSync as io,readFileSync as ro,unlinkSync as Nr,writeFileSync as so}from"fs";import{join as no}from"path";import ao from"crypto";import rt from"path";import G from"fs";import xi from"zlib";import oo from"http";import{closeSync as lo,existsSync as co,mkdirSync as uo,openSync as ho,readFileSync as fo,unlinkSync as $r,writeFileSync as _o}from"fs";import{join as po}from"path";import go from"crypto";import st from"path";import H from"fs";import Si from"zlib";import mo from"http";import{closeSync as yo,existsSync as wo,mkdirSync as Ao,openSync as vo,readFileSync as Eo,unlinkSync as kr,writeFileSync as xo}from"fs";import{join as So}from"path";import Io from"crypto";import nt from"path";import J from"fs";import Ii from"zlib";import bo from"http";import{closeSync as To,existsSync as Oo,mkdirSync as Ro,openSync as Co,readFileSync as No,unlinkSync as Dr,writeFileSync as $o}from"fs";import{join as ko}from"path";import Do from"crypto";import at from"path";import Y from"fs";import bi from"zlib";import Lo from"http";function Po(){let t=Date.now().toString(16),i;try{i=ao.randomBytes(8).toString("hex")}catch{let r=new Uint8Array(8);crypto.getRandomValues(r),i=Array.from(r).map((s)=>s.toString(16).padStart(2,"0")).join("")}return`${t}${i}`}function Lr(t,i){let r=t instanceof Error?t.message:t;if(i==="error")console.error(r);else console.log(r)}var Pr=new Set(["__proto__","constructor","prototype"]);function ni(t,i){if(!i.includes(".")){if(Pr.has(i))return;return t[i]}let r=t;for(let s of i.split(".")){if(Pr.has(s))return;if(r==null)return;r=r[s]}return r}class Je extends Error{constructor(t,i,r={}){super(i);this.name=this.constructor.name,this.code=t,this.details=r}}class D extends Je{}class De extends Je{}class Re extends Je{}class Ve extends Je{}class Se extends Je{}class ut extends Je{}function Li(t,i){if(t===i)return!0;if(t==null||i==null)return!1;if(typeof t!==typeof i)return!1;if(t instanceof Date&&i instanceof Date)return t.getTime()===i.getTime();if(t instanceof RegExp&&i instanceof RegExp)return t.source===i.source&&t.flags===i.flags;if(Array.isArray(t)){if(!Array.isArray(i)||t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Li(t[r],i[r]))return!1;return!0}if(typeof t==="object"){if(Array.isArray(i))return!1;let r=Object.keys(t);if(r.length!==Object.keys(i).length)return!1;for(let s of r){if(!Object.prototype.hasOwnProperty.call(i,s))return!1;if(!Li(t[s],i[s]))return!1}return!0}return!1}function ie(t,i){if(typeof i==="function")return i(t);if(i==null)return!0;if(typeof i==="object"&&Object.keys(i).length===0)return!0;if("$or"in i){let r=i.$or;if(!Array.isArray(r))throw new ut("ERR_SKALEX_QUERY_INVALID_OPERATOR","$or must be an array of filters",{operator:"$or"});if(!r.some((s)=>ie(t,s)))return!1}if("$and"in i){let r=i.$and;if(!Array.isArray(r))throw new ut("ERR_SKALEX_QUERY_INVALID_OPERATOR","$and must be an array of filters",{operator:"$and"});if(!r.every((s)=>ie(t,s)))return!1}if("$not"in i){if(ie(t,i.$not))return!1}for(let r in i){if(r==="$or"||r==="$and"||r==="$not")continue;let s=i[r],n;try{n=ni(t,r)}catch{return!1}if(s instanceof RegExp){if(!s.test(String(n)))return!1}else if(typeof s==="object"&&s!==null){if(Object.keys(s).some((a)=>a.startsWith("$"))){if("$eq"in s&&n!==s.$eq)return!1;if("$ne"in s&&n===s.$ne)return!1;if("$gt"in s&&!(n>s.$gt))return!1;if("$lt"in s&&!(n<s.$lt))return!1;if("$gte"in s&&!(n>=s.$gte))return!1;if("$lte"in s&&!(n<=s.$lte))return!1;if("$in"in s&&!s.$in.includes(n))return!1;if("$nin"in s&&s.$nin.includes(n))return!1;if("$regex"in s){if(!(s.$regex instanceof RegExp?s.$regex:new RegExp(s.$regex)).test(String(n)))return!1}if("$fn"in s&&!s.$fn(n))return!1}else if(!Li(n,s))return!1}else if(n!==s)return!1}return!0}function Mo(t,i=new Set){if(typeof t!=="object"||t===null||typeof t==="function")return t;let r=[],s=[],n=[],a=[],o=[];for(let l in t){if(l==="$or"||l==="$and"||l==="$not"){o.push(l);continue}let d=t[l];if(i.has(l))r.push(l);else if(d instanceof RegExp||typeof d==="object"&&d!==null&&(("$regex"in d)||("$fn"in d))||typeof d==="function")a.push(l);else if(typeof d==="object"&&d!==null&&(("$gt"in d)||("$lt"in d)||("$gte"in d)||("$lte"in d)||("$ne"in d)||("$in"in d)||("$nin"in d)))n.push(l);else s.push(l)}let c={};for(let l of[...r,...s,...n,...a,...o])c[l]=t[l];return c}var Pi=new Set(["string","number","boolean","object","array","date","any"]);function zi(t){if(Array.isArray(t))return"array";if(t instanceof Date)return"date";return typeof t}function Ds(t){let i=new Map,r=[];for(let[s,n]of Object.entries(t)){let a;if(typeof n==="string"){if(!Pi.has(n))throw new D("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${n}" for field "${s}"`,{field:s,type:n});a={type:n,required:!1,unique:!1}}else if(typeof n==="object"&&n!==null){let{type:o="any",required:c=!1,unique:l=!1,enum:d}=n;if(!Pi.has(o))throw new D("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${o}" for field "${s}"`,{field:s,type:o});if(a={type:o,required:c,unique:l,enum:d},l)r.push(s)}else throw new D("ERR_SKALEX_VALIDATION_INVALID_SCHEMA",`Invalid schema definition for field "${s}"`,{field:s});i.set(s,a)}return{fields:i,uniqueFields:r}}function Mr(t,i,r=!1){let s=[];for(let[n,a]of i){let o=t[n],c=o===void 0||o===null;if(a.required&&c){s.push(`Field "${n}" is required`);continue}if(c)continue;if(a.type!=="any"){let l=zi(o);if(l!==a.type)s.push(`Field "${n}" must be of type "${a.type}", got "${l}"`)}if(a.enum&&!a.enum.includes(o))s.push(`Field "${n}" must be one of [${a.enum.map((l)=>JSON.stringify(l)).join(", ")}], got ${JSON.stringify(o)}`)}if(r){for(let n of Object.keys(t))if(!n.startsWith("_")&&!i.has(n))s.push(`Unknown field "${n}" (strict mode)`)}return s}function jr(t,i){let r={};for(let[s,n]of Object.entries(t)){if(s.startsWith("_")){r[s]=n;continue}if(!i.has(s))continue;let a=i.get(s);if(a.type!=="any"){if(zi(n)!==a.type)continue}if(a.enum&&!a.enum.includes(n))continue;r[s]=n}return r}function jo(t){let i={};for(let[r,s]of Object.entries(t)){if(r.startsWith("_"))continue;let n=zi(s);i[r]=Pi.has(n)?n:"any"}return i}function qo(t){if(typeof t==="number"){if(t<=0)throw new D("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got ${t}`,{ttl:t});return t*1000}if(typeof t!=="string")throw new D("ERR_SKALEX_VALIDATION_TTL",`Invalid TTL value: ${t}`,{ttl:t});let i=t.match(/^(\d+(?:\.\d+)?)(ms|s|m|h|d)$/);if(!i)throw new D("ERR_SKALEX_VALIDATION_TTL_FORMAT",`Invalid TTL format: "${t}". Use e.g. 300 (seconds), "30m", "24h", "7d"`,{ttl:t});let r=parseFloat(i[1]);if(r<=0)throw new D("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got "${t}"`,{ttl:t});let s=i[2],n=r*{ms:1,s:1000,m:60000,h:3600000,d:86400000}[s];if(!isFinite(n))throw new D("ERR_SKALEX_VALIDATION_TTL",`TTL value "${t}" is too large`,{ttl:t});return n}function Uo(t){return new Date(Date.now()+qo(t))}function Fo(t,i,r=null){let s=Date.now(),n=0,a=t.length;while(a--){let o=t[a];if(o._expiresAt&&new Date(o._expiresAt).getTime()<=s){if(t.splice(a,1),i.delete(o._id),r)r(o);n++}}return n}function qr(t,i){if(t.length!==i.length)throw new ut("ERR_SKALEX_QUERY_VECTOR_MISMATCH",`Vector dimension mismatch: ${t.length} vs ${i.length}`,{expected:t.length,got:i.length});let r=0,s=0,n=0;for(let o=0;o<t.length;o++)r+=t[o]*i[o],s+=t[o]*t[o],n+=i[o]*i[o];let a=Math.sqrt(s*n);return a===0?0:r/a}function Q(t){if(!("_vector"in t))return{...t};let{_vector:i,...r}=t;return r}function Ko(t){return t.length}function zo(t,i){let r=0;for(let s of t){let n=ni(s,i);if(typeof n==="number"&&!isNaN(n))r+=n}return r}function Bo(t,i){let r=0,s=0;for(let n of t){let a=ni(n,i);if(typeof a==="number"&&!isNaN(a))r+=a,s++}return s===0?null:r/s}function Xo(t,i){let r=Object.create(null);for(let s of t){let n=String(ni(s,i)??"__null__");if(!r[n])r[n]=[];r[n].push(s)}return r}class Ls{constructor(t){this._col=t}get _ctx(){return this._col._ctx}async execute({op:t,beforeHook:i,afterHook:r,hookPayload:s,mutate:n,afterHookPayload:a,save:o,session:c}){let l=this._ctx;await l.ensureConnected(),this._col._txSnapshotIfNeeded();let d=l.txManager,u=d.active&&this._col._activeTxId===d.context?.id,f=u?d.context.id:null,h=this._col._createdInTxId,_=()=>{if(f!==null&&d._abortedIds.has(f))throw new Re("ERR_SKALEX_TX_ABORTED",`Transaction ${f} was aborted. No further mutations allowed.`);if(h!==null&&d._abortedIds.has(h))throw new Re("ERR_SKALEX_TX_ABORTED",`Transaction ${h} was aborted. Collection obtained inside that transaction cannot be used for further mutations.`)};if(u||h!==null)_();if(i)await l.plugins.run(i,s);let{docs:p,prevDocs:g=[]}=await n(_);if(l.persistence.markDirty(l.collections,this._col.name),await this._col._saveIfNeeded(o),this._col._changelogEnabled)for(let m=0;m<p.length;m++)await l.logChange(t,this._col.name,p[m],g[m]??null,c||null);if(!u||!d.defer(()=>l.sessionStats.recordWrite(c)))l.sessionStats.recordWrite(c);for(let m of p)l.emitEvent(this._col.name,{op:t,collection:this._col.name,doc:Q(m)});if(r)if(a)await l.runAfterHook(r,a(p));else for(let m of p)await l.runAfterHook(r,{collection:this._col.name,doc:Q(m)});return{docs:p,prevDocs:g}}}function Vo(t){let i={};for(let r in t){if(r.startsWith("$"))continue;let s=t[r];if(s&&typeof s==="object"&&!Array.isArray(s)){let n=Object.keys(s);if(n.length===1&&n[0]==="$eq")i[r]=s.$eq}else i[r]=s}return i}var Ps=new Set(["__proto__","constructor","prototype"]);function Ms(t){if(typeof t!=="object"||t===null||Array.isArray(t))return t;let i={};for(let r of Object.keys(t)){if(Ps.has(r))continue;i[r]=Ms(t[r])}return i}class js{constructor(t,i){this.name=t.collectionName,this.database=i,this._ctx=i._buildCollectionContext(),this._store=t,this._pipeline=new Ls(this),this._createdInTxId=i._txManager.context?.id??null,this._activeTxId=null}get _data(){return this._store.data}set _data(t){this._store.data=t}get _index(){return this._store.index}get _fieldIndex(){return this._store.fieldIndex||null}get _schema(){return this._store.schema?this._store.schema.fields:null}get _changelogEnabled(){return this._store.changelog===!0}get _softDelete(){return this._store.softDelete===!0}get _versioning(){return this._store.versioning===!0}get _strict(){return this._store.strict===!0}get _onSchemaError(){return this._store.onSchemaError??"throw"}get _defaultTtl(){return this._store.defaultTtl||null}get _defaultEmbed(){return this._store.defaultEmbed||null}get _maxDocs(){return this._store.maxDocs||null}async insertOne(t,i={}){let{save:r,ifNotExists:s,ttl:n,embed:a,session:o}=i;if(s){await this._ctx.ensureConnected();let l=this._findRaw(t);if(l)return Q({...l})}let{docs:c}=await this._insertCore([t],{ttl:n,embed:a,session:o,save:r});return Q(c[0])}async insertMany(t,i={}){let{save:r,ttl:s,embed:n,session:a}=i,{docs:o}=await this._insertCore(t,{ttl:s,embed:n,session:a,save:r});return o.map(Q)}async _insertCore(t,{ttl:i,embed:r,session:s,save:n}){return this._pipeline.execute({op:"insert",beforeHook:null,afterHook:"afterInsert",hookPayload:null,save:n,session:s,mutate:async(a)=>{let o=[],c=new Set;for(let l of t){let d=this._applyValidation(l);await this._ctx.plugins.run("beforeInsert",{collection:this.name,doc:d});let u=await this._buildDoc(d,{ttl:i,embed:r});if(this._index.has(u._id)||c.has(u._id))throw new De("ERR_SKALEX_UNIQUE_DUPLICATE_ID",`Duplicate _id "${u._id}" in collection "${this.name}"`,{id:u._id,collection:this.name});c.add(u._id),o.push(u)}if(a(),this._fieldIndex)this._fieldIndex.assertUniqueBatch(o);for(let l of o)this._addToIndex(l);this._data.push(...o);for(let l of o)this._index.set(l._id,l);return this._enforceCapAfterInsert(),{docs:o}}})}async updateOne(t,i,r={}){await this._ctx.ensureConnected();let s=this._findRaw(t);if(!s)return null;let{save:n,session:a}=r,{docs:o}=await this._updateCore([s],t,i,{save:n,session:a});return Q(o[0])}async updateMany(t,i,r={}){await this._ctx.ensureConnected();let s=this._findAllRaw(t);if(s.length===0)return[];let{save:n,session:a}=r,{docs:o}=await this._updateCore(s,t,i,{save:n,session:a});return o.map(Q)}async _updateCore(t,i,r,{save:s,session:n}){return this._pipeline.execute({op:"update",beforeHook:"beforeUpdate",afterHook:"afterUpdate",hookPayload:{collection:this.name,filter:i,update:r},save:s,session:n,afterHookPayload:(a)=>({collection:this.name,filter:i,update:r,result:a.length===1?a[0]:a}),mutate:async(a)=>{let o=this._changelogEnabled?t.map((u)=>structuredClone(u)):t.map(()=>null),c=t.map((u)=>this._prepareUpdatedDoc(u,r));this._assertUniqueCandidates(t,c),a();let l=new Set(t),d=new Map;for(let u=0;u<this._data.length;u++)if(l.has(this._data[u]))d.set(this._data[u],u);for(let u=0;u<t.length;u++)this._commitUpdatedDoc(t[u],c[u],d);return{docs:c,prevDocs:o}}})}applyUpdate(t,i){for(let r in i){if(Ps.has(r))continue;if(r==="_id"||r==="createdAt")continue;let s=i[r];if(Array.isArray(s))t[r]=s;else if(typeof s==="object"&&s!==null){let n=Object.keys(s);if(n.some((a)=>a.startsWith("$"))){for(let a of n)if(a==="$inc"&&typeof t[r]==="number")t[r]+=s[a];else if(a==="$push"){if(!Array.isArray(t[r]))t[r]=[];t[r].push(s[a])}}else t[r]=Ms(s)}else t[r]=s}if(t.updatedAt=new Date,this._versioning)t._version=(t._version??0)+1;return t}_prepareUpdatedDoc(t,i){let r=structuredClone(t),s=structuredClone(t);if(this.applyUpdate(s,i),!this._schema)return s;let n=Mr(s,this._schema,this._strict);if(!n.length)return s;switch(this._onSchemaError){case"throw":throw new D("ERR_SKALEX_VALIDATION_UPDATE",`Update validation failed on doc "${t._id}": ${n.join("; ")}`,{id:t._id,errors:n});case"strip":return this._stripCandidateToValid(s,r);default:return this._ctx.logger(`[${this.name}] Update validation warning: ${n.join("; ")}`,"warn"),s}}_stripCandidateToValid(t,i){let r=jr(t,this._schema),s=structuredClone(i);for(let[n,a]of Object.entries(r)){if(n.startsWith("_"))continue;s[n]=a}if(s.updatedAt=t.updatedAt,this._versioning)s._version=t._version;return s}_commitUpdatedDoc(t,i,r){let s=r?r.get(t):this._data.indexOf(t);if(s===void 0||s===-1)throw new Ve("ERR_SKALEX_PERSISTENCE_DOC_MISSING",`Document "${t._id}" no longer exists in collection "${this.name}"`,{id:t._id,collection:this.name});this._data[s]=i,this._index.set(i._id,i),this._updateInIndex(t,i)}_assertUniqueCandidates(t,i){this._fieldIndex?.assertUniqueCandidates(t,i)}async upsert(t,i,r={}){if(await this._ctx.ensureConnected(),this._findRaw(t))return this.updateOne(t,i,r);return this.insertOne({...Vo(t),...i},r)}async upsertMany(t,i,r={}){await this._ctx.ensureConnected();let{save:s,...n}=r,a=[];for(let o of t)a.push(await this.upsert({[i]:o[i]},o,{...n,save:!1}));return await this._saveIfNeeded(s),a}async restore(t,i={}){if(!this._softDelete)throw new ut("ERR_SKALEX_QUERY_SOFT_DELETE_REQUIRED",`restore() requires softDelete on "${this.name}"`,{collection:this.name});await this._ctx.ensureConnected();let{save:r,session:s}=i,n=this._findRaw(t,{includeDeleted:!0});if(!n||!n._deletedAt)return null;let{docs:a}=await this._pipeline.execute({op:"restore",beforeHook:null,afterHook:null,hookPayload:null,save:r,session:s,mutate:async(o)=>(o(),delete n._deletedAt,n.updatedAt=new Date,this._index.set(n._id,n),{docs:[n]})});return Q(a[0])}watch(t,i){if(typeof t==="function")i=t,t=null;if(i)return this._ctx.eventBus.on(this.name,(r)=>{if(!t||ie(r.doc,t))i(r)});return this._watchIterator(t)}_watchIterator(t){let i=[],r=null,s=!1,n=this._ctx.eventBus.on(this.name,(a)=>{if(t&&!ie(a.doc,t))return;if(r){let o=r;r=null,o({value:a,done:!1})}else i.push(a)});return{[Symbol.asyncIterator](){return this},next(){if(i.length>0)return Promise.resolve({value:i.shift(),done:!1});if(s)return Promise.resolve({value:void 0,done:!0});return new Promise((a)=>{r=a})},return(){if(s=!0,n(),r){let a=r;r=null,a({value:void 0,done:!0})}return Promise.resolve({value:void 0,done:!0})}}}async count(t={}){return await this._ctx.ensureConnected(),Ko(this._findAllRaw(t))}async sum(t,i={}){return await this._ctx.ensureConnected(),zo(this._findAllRaw(i),t)}async avg(t,i={}){return await this._ctx.ensureConnected(),Bo(this._findAllRaw(i),t)}async groupBy(t,i={}){return await this._ctx.ensureConnected(),Xo(this._findAllRaw(i),t)}async findOne(t,i={}){await this._ctx.ensureConnected();let{populate:r,select:s,includeDeleted:n=!1}=i,a=this._findRaw(t,{includeDeleted:n});if(!a)return null;let o=this._projectDoc(a,s);if(r)await this._populateDoc(o,a,r);return o}async find(t,i={}){await this._ctx.ensureConnected();let r=Date.now(),{populate:s,select:n,sort:a,page:o=1,limit:c,session:l,includeDeleted:d=!1}=i;await this._ctx.plugins.run("beforeFind",{collection:this.name,filter:t,options:i});let u=this._getCandidates(t),f=Mo(t,this._fieldIndex?this._fieldIndex.indexedFields:new Set),h=[];for(let p of u){if(this._softDelete&&p._deletedAt&&!d)continue;if(!ie(p,f))continue;let g=this._projectDoc(p,n);if(s)await this._populateDoc(g,p,s);h.push(g)}if(a){let p=Object.keys(a);h.sort((g,m)=>{for(let w of p){let v=a[w];if(g[w]<m[w])return-v;if(g[w]>m[w])return v}return 0})}let _;if(c){let p=h.length,g=Math.ceil(p/c),m=(o-1)*c;h=h.slice(m,m+c),_={page:o,totalDocs:p,totalPages:g}}return this._ctx.queryLog?.record({collection:this.name,op:"find",filter:t,duration:Date.now()-r,resultCount:h.length}),this._ctx.sessionStats.recordRead(l),await this._ctx.plugins.run("afterFind",{collection:this.name,filter:t,options:i,docs:h}),_?{docs:h,..._}:{docs:h}}async search(t,{filter:i,limit:r=10,minScore:s=0,session:n}={}){await this._ctx.ensureConnected();let a=Date.now();await this._ctx.plugins.run("beforeSearch",{collection:this.name,query:t,options:{filter:i,limit:r,minScore:s}});let o=await this._ctx.embed(t),c=i?this._findAllRaw(i):this._data,l=[];for(let h of c){if(!h._vector)continue;let _=qr(o,h._vector);if(_>=s)l.push({doc:h,score:_})}l.sort((h,_)=>_.score-h.score);let d=l.slice(0,r);this._ctx.queryLog?.record({collection:this.name,op:"search",query:t,duration:Date.now()-a,resultCount:d.length}),this._ctx.sessionStats.recordRead(n);let u=d.map((h)=>Q(h.doc)),f=d.map((h)=>h.score);return await this._ctx.plugins.run("afterSearch",{collection:this.name,query:t,options:{filter:i,limit:r,minScore:s},docs:u,scores:f}),{docs:u,scores:f}}async similar(t,{limit:i=10,minScore:r=0}={}){await this._ctx.ensureConnected();let s=this._index.get(t);if(!s||!s._vector)return{docs:[],scores:[]};let n=[];for(let o of this._data){if(o._id===t||!o._vector)continue;let c=qr(s._vector,o._vector);if(c>=r)n.push({doc:o,score:c})}n.sort((o,c)=>c.score-o.score);let a=n.slice(0,i);return{docs:a.map((o)=>Q(o.doc)),scores:a.map((o)=>o.score)}}async deleteOne(t,i={}){await this._ctx.ensureConnected();let{save:r,session:s}=i;if(this._softDelete){let a=this._findRaw(t);if(!a)return null;let{docs:o}=await this._deleteCore("soft",[a],t,{save:r,session:s});return Q(o[0])}let{docs:n}=await this._deleteCore("hard",null,t,{save:r,session:s});if(n.length===0)return null;return Q(n[0])}async deleteMany(t,i={}){await this._ctx.ensureConnected();let{save:r,session:s}=i;if(this._softDelete){let a=this._findAllRaw(t);if(a.length===0)return[];let{docs:o}=await this._deleteCore("soft",a,t,{save:r,session:s});return o.map(Q)}let{docs:n}=await this._deleteCore("hardMany",null,t,{save:r,session:s});return n.map(Q)}async _deleteCore(t,i,r,{save:s,session:n}){return this._pipeline.execute({op:"delete",beforeHook:"beforeDelete",afterHook:"afterDelete",hookPayload:{collection:this.name,filter:r},save:s,session:n,afterHookPayload:(a)=>({collection:this.name,filter:r,result:a.length===1?a[0]:a}),mutate:async(a)=>{if(a(),t==="soft"){let l=new Date;for(let d of i)d._deletedAt=l,d.updatedAt=l,this._index.set(d._id,d);return{docs:i}}if(t==="hard"){let l=this._findIndex(r);if(l===-1)return{docs:[]};let d=this._data.splice(l,1)[0];return this._index.delete(d._id),this._removeFromIndex(d),{docs:[d]}}let o=[],c=[];for(let l of this._data)if(ie(l,r))o.push(l),this._index.delete(l._id),this._removeFromIndex(l);else c.push(l);return this._data=c,{docs:o}}})}async export(t={},i={}){let{dir:r,name:s,format:n="json"}=i;try{let a=this._data.filter((u)=>ie(u,t));if(a.length===0)throw new ut("ERR_SKALEX_QUERY_EXPORT_EMPTY",`export(): no documents matched the filter in "${this.name}"`,{collection:this.name});let o;if(n==="json")o=JSON.stringify(a,null,2);else{let u=(_)=>{if(_==null)return"";let p=typeof _==="object"?JSON.stringify(_):String(_);return p.includes(",")||p.includes('"')||p.includes(`
|
|
2
|
+
import{z,ci,Wt,xt,T,O,C,N,e,at}from"./index-7wm4bqx5.js";import{M,X}from"./index-j99tkngg.js";import{Ae,W}from"./index-p1b10hs1.js";import{K}from"./index-qzwbctkv.js";import{_t}from"./index-p7fbnfwd.js";import{xe,Ie,ve}from"./index-6wfd7cv3.js";import{b}from"./index-w4jqdhc2.js";import{existsSync as Ja,readFileSync as Ya}from"fs";import{dirname as wi,join as Qa}from"path";import{fileURLToPath as Za}from"url";import{closeSync as eo,existsSync as to,mkdirSync as io,openSync as ro,readFileSync as so,unlinkSync as $r,writeFileSync as no}from"fs";import{join as ao}from"path";import oo from"crypto";import it from"path";import G from"fs";import Ai from"zlib";import lo from"http";import{closeSync as co,existsSync as uo,mkdirSync as ho,openSync as fo,readFileSync as _o,unlinkSync as kr,writeFileSync as po}from"fs";import{join as go}from"path";import mo from"crypto";import rt from"path";import H from"fs";import vi from"zlib";import yo from"http";import{closeSync as wo,existsSync as Ao,mkdirSync as vo,openSync as Eo,readFileSync as xo,unlinkSync as Dr,writeFileSync as So}from"fs";import{join as Io}from"path";import bo from"crypto";import st from"path";import J from"fs";import Ei from"zlib";import To from"http";import{closeSync as Oo,existsSync as Ro,mkdirSync as Co,openSync as No,readFileSync as $o,unlinkSync as Lr,writeFileSync as ko}from"fs";import{join as Do}from"path";import Lo from"crypto";import nt from"path";import Y from"fs";import xi from"zlib";import Po from"http";function Mo(){let t=Date.now().toString(16),i;try{i=oo.randomBytes(8).toString("hex")}catch{let r=new Uint8Array(8);crypto.getRandomValues(r),i=Array.from(r).map((s)=>s.toString(16).padStart(2,"0")).join("")}return`${t}${i}`}function Pr(t,i){let r=t instanceof Error?t.message:t;if(i==="error")console.error(r);else console.log(r)}var Mr=new Set(["__proto__","constructor","prototype"]);function ti(t,i){if(!i.includes(".")){if(Mr.has(i))return;return t[i]}let r=t;for(let s of i.split(".")){if(Mr.has(s))return;if(r==null)return;r=r[s]}return r}class Je extends Error{constructor(t,i,r={}){super(i);this.name=this.constructor.name,this.code=t,this.details=r}}class D extends Je{}class De extends Je{}class Ce extends Je{}class Ve extends Je{}class be extends Je{}class ut extends Je{}function $i(t,i){if(t===i)return!0;if(t==null||i==null)return!1;if(typeof t!==typeof i)return!1;if(t instanceof Date&&i instanceof Date)return t.getTime()===i.getTime();if(t instanceof RegExp&&i instanceof RegExp)return t.source===i.source&&t.flags===i.flags;if(Array.isArray(t)){if(!Array.isArray(i)||t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!$i(t[r],i[r]))return!1;return!0}if(typeof t==="object"){if(Array.isArray(i))return!1;let r=Object.keys(t);if(r.length!==Object.keys(i).length)return!1;for(let s of r){if(!Object.prototype.hasOwnProperty.call(i,s))return!1;if(!$i(t[s],i[s]))return!1}return!0}return!1}function ie(t,i){if(typeof i==="function")return i(t);if(i==null)return!0;if(typeof i==="object"&&Object.keys(i).length===0)return!0;if("$or"in i){let r=i.$or;if(!Array.isArray(r))throw new ut("ERR_SKALEX_QUERY_INVALID_OPERATOR","$or must be an array of filters",{operator:"$or"});if(!r.some((s)=>ie(t,s)))return!1}if("$and"in i){let r=i.$and;if(!Array.isArray(r))throw new ut("ERR_SKALEX_QUERY_INVALID_OPERATOR","$and must be an array of filters",{operator:"$and"});if(!r.every((s)=>ie(t,s)))return!1}if("$not"in i){if(ie(t,i.$not))return!1}for(let r in i){if(r==="$or"||r==="$and"||r==="$not")continue;let s=i[r],n;try{n=ti(t,r)}catch{return!1}if(s instanceof RegExp){if(!s.test(String(n)))return!1}else if(typeof s==="object"&&s!==null){if(Object.keys(s).some((a)=>a.startsWith("$"))){if("$eq"in s&&n!==s.$eq)return!1;if("$ne"in s&&n===s.$ne)return!1;if("$gt"in s&&!(n>s.$gt))return!1;if("$lt"in s&&!(n<s.$lt))return!1;if("$gte"in s&&!(n>=s.$gte))return!1;if("$lte"in s&&!(n<=s.$lte))return!1;if("$in"in s&&!s.$in.includes(n))return!1;if("$nin"in s&&s.$nin.includes(n))return!1;if("$regex"in s){if(!(s.$regex instanceof RegExp?s.$regex:new RegExp(s.$regex)).test(String(n)))return!1}if("$fn"in s&&!s.$fn(n))return!1}else if(!$i(n,s))return!1}else if(n!==s)return!1}return!0}function jo(t,i=new Set){if(typeof t!=="object"||t===null||typeof t==="function")return t;let r=[],s=[],n=[],a=[],o=[];for(let l in t){if(l==="$or"||l==="$and"||l==="$not"){o.push(l);continue}let d=t[l];if(i.has(l))r.push(l);else if(d instanceof RegExp||typeof d==="object"&&d!==null&&(("$regex"in d)||("$fn"in d))||typeof d==="function")a.push(l);else if(typeof d==="object"&&d!==null&&(("$gt"in d)||("$lt"in d)||("$gte"in d)||("$lte"in d)||("$ne"in d)||("$in"in d)||("$nin"in d)))n.push(l);else s.push(l)}let c={};for(let l of[...r,...s,...n,...a,...o])c[l]=t[l];return c}var ki=new Set(["string","number","boolean","object","array","date","any"]);function Ui(t){if(Array.isArray(t))return"array";if(t instanceof Date)return"date";return typeof t}function Ls(t){let i=new Map,r=[];for(let[s,n]of Object.entries(t)){let a;if(typeof n==="string"){if(!ki.has(n))throw new D("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${n}" for field "${s}"`,{field:s,type:n});a={type:n,required:!1,unique:!1}}else if(typeof n==="object"&&n!==null){let{type:o="any",required:c=!1,unique:l=!1,enum:d}=n;if(!ki.has(o))throw new D("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${o}" for field "${s}"`,{field:s,type:o});if(a={type:o,required:c,unique:l,enum:d},l)r.push(s)}else throw new D("ERR_SKALEX_VALIDATION_INVALID_SCHEMA",`Invalid schema definition for field "${s}"`,{field:s});i.set(s,a)}return{fields:i,uniqueFields:r}}function jr(t,i,r=!1){let s=[];for(let[n,a]of i){let o=t[n],c=o===void 0||o===null;if(a.required&&c){s.push(`Field "${n}" is required`);continue}if(c)continue;if(a.type!=="any"){let l=Ui(o);if(l!==a.type)s.push(`Field "${n}" must be of type "${a.type}", got "${l}"`)}if(a.enum&&!a.enum.includes(o))s.push(`Field "${n}" must be one of [${a.enum.map((l)=>JSON.stringify(l)).join(", ")}], got ${JSON.stringify(o)}`)}if(r){for(let n of Object.keys(t))if(!n.startsWith("_")&&!i.has(n))s.push(`Unknown field "${n}" (strict mode)`)}return s}function qr(t,i){let r={};for(let[s,n]of Object.entries(t)){if(s.startsWith("_")){r[s]=n;continue}if(!i.has(s))continue;let a=i.get(s);if(a.type!=="any"){if(Ui(n)!==a.type)continue}if(a.enum&&!a.enum.includes(n))continue;r[s]=n}return r}function qo(t){let i={};for(let[r,s]of Object.entries(t)){if(r.startsWith("_"))continue;let n=Ui(s);i[r]=ki.has(n)?n:"any"}return i}function Uo(t){if(typeof t==="number"){if(t<=0)throw new D("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got ${t}`,{ttl:t});return t*1000}if(typeof t!=="string")throw new D("ERR_SKALEX_VALIDATION_TTL",`Invalid TTL value: ${t}`,{ttl:t});let i=t.match(/^(\d+(?:\.\d+)?)(ms|s|m|h|d)$/);if(!i)throw new D("ERR_SKALEX_VALIDATION_TTL_FORMAT",`Invalid TTL format: "${t}". Use e.g. 300 (seconds), "30m", "24h", "7d"`,{ttl:t});let r=parseFloat(i[1]);if(r<=0)throw new D("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got "${t}"`,{ttl:t});let s=i[2],n=r*{ms:1,s:1000,m:60000,h:3600000,d:86400000}[s];if(!isFinite(n))throw new D("ERR_SKALEX_VALIDATION_TTL",`TTL value "${t}" is too large`,{ttl:t});return n}function Fo(t){return new Date(Date.now()+Uo(t))}function Ko(t,i,r=null){let s=Date.now(),n=0,a=t.length;while(a--){let o=t[a];if(o._expiresAt&&new Date(o._expiresAt).getTime()<=s){if(t.splice(a,1),i.delete(o._id),r)r(o);n++}}return n}function Ur(t,i){if(t.length!==i.length)throw new ut("ERR_SKALEX_QUERY_VECTOR_MISMATCH",`Vector dimension mismatch: ${t.length} vs ${i.length}`,{expected:t.length,got:i.length});let r=0,s=0,n=0;for(let o=0;o<t.length;o++)r+=t[o]*i[o],s+=t[o]*t[o],n+=i[o]*i[o];let a=Math.sqrt(s*n);return a===0?0:r/a}function Q(t){if(!("_vector"in t))return{...t};let{_vector:i,...r}=t;return r}function zo(t){return t.length}function Bo(t,i){let r=0;for(let s of t){let n=ti(s,i);if(typeof n==="number"&&!isNaN(n))r+=n}return r}function Xo(t,i){let r=0,s=0;for(let n of t){let a=ti(n,i);if(typeof a==="number"&&!isNaN(a))r+=a,s++}return s===0?null:r/s}function Vo(t,i){let r=Object.create(null);for(let s of t){let n=String(ti(s,i)??"__null__");if(!r[n])r[n]=[];r[n].push(s)}return r}class Ps{constructor(t){this._col=t}get _ctx(){return this._col._ctx}async execute({op:t,beforeHook:i,afterHook:r,hookPayload:s,mutate:n,afterHookPayload:a,save:o,session:c}){let l=this._ctx;await l.ensureConnected(),this._col._txSnapshotIfNeeded();let d=l.txManager,u=d.active&&this._col._activeTxId===d.context?.id,f=u?d.context.id:null,h=this._col._createdInTxId,_=()=>{if(f!==null&&d._abortedIds.has(f))throw new Ce("ERR_SKALEX_TX_ABORTED",`Transaction ${f} was aborted. No further mutations allowed.`);if(h!==null&&d._abortedIds.has(h))throw new Ce("ERR_SKALEX_TX_ABORTED",`Transaction ${h} was aborted. Collection obtained inside that transaction cannot be used for further mutations.`)};if(u||h!==null)_();if(i)await l.plugins.run(i,s);let{docs:p,prevDocs:g=[]}=await n(_);if(l.persistence.markDirty(l.collections,this._col.name),await this._col._saveIfNeeded(o),this._col._changelogEnabled)for(let m=0;m<p.length;m++)await l.logChange(t,this._col.name,p[m],g[m]??null,c||null);if(!u||!d.defer(()=>l.sessionStats.recordWrite(c)))l.sessionStats.recordWrite(c);for(let m of p)l.emitEvent(this._col.name,{op:t,collection:this._col.name,doc:Q(m)});if(r)if(a)await l.runAfterHook(r,a(p));else for(let m of p)await l.runAfterHook(r,{collection:this._col.name,doc:Q(m)});return{docs:p,prevDocs:g}}}function Go(t){let i={};for(let r in t){if(r.startsWith("$"))continue;let s=t[r];if(s&&typeof s==="object"&&!Array.isArray(s)){let n=Object.keys(s);if(n.length===1&&n[0]==="$eq")i[r]=s.$eq}else i[r]=s}return i}var Ms=new Set(["__proto__","constructor","prototype"]);function js(t){if(typeof t!=="object"||t===null||Array.isArray(t))return t;let i={};for(let r of Object.keys(t)){if(Ms.has(r))continue;i[r]=js(t[r])}return i}class qs{constructor(t,i){this.name=t.collectionName,this.database=i,this._ctx=i._buildCollectionContext(),this._store=t,this._pipeline=new Ps(this),this._createdInTxId=i._txManager.context?.id??null,this._activeTxId=null}get _data(){return this._store.data}set _data(t){this._store.data=t}get _index(){return this._store.index}get _fieldIndex(){return this._store.fieldIndex||null}get _schema(){return this._store.schema?this._store.schema.fields:null}get _changelogEnabled(){return this._store.changelog===!0}get _softDelete(){return this._store.softDelete===!0}get _versioning(){return this._store.versioning===!0}get _strict(){return this._store.strict===!0}get _onSchemaError(){return this._store.onSchemaError??"throw"}get _defaultTtl(){return this._store.defaultTtl||null}get _defaultEmbed(){return this._store.defaultEmbed||null}get _maxDocs(){return this._store.maxDocs||null}async insertOne(t,i={}){let{save:r,ifNotExists:s,ttl:n,embed:a,session:o}=i;if(s){await this._ctx.ensureConnected();let l=this._findRaw(t);if(l)return Q({...l})}let{docs:c}=await this._insertCore([t],{ttl:n,embed:a,session:o,save:r});return Q(c[0])}async insertMany(t,i={}){let{save:r,ttl:s,embed:n,session:a}=i,{docs:o}=await this._insertCore(t,{ttl:s,embed:n,session:a,save:r});return o.map(Q)}async _insertCore(t,{ttl:i,embed:r,session:s,save:n}){return this._pipeline.execute({op:"insert",beforeHook:null,afterHook:"afterInsert",hookPayload:null,save:n,session:s,mutate:async(a)=>{let o=[],c=new Set;for(let l of t){let d=this._applyValidation(l);await this._ctx.plugins.run("beforeInsert",{collection:this.name,doc:d});let u=await this._buildDoc(d,{ttl:i,embed:r});if(this._index.has(u._id)||c.has(u._id))throw new De("ERR_SKALEX_UNIQUE_DUPLICATE_ID",`Duplicate _id "${u._id}" in collection "${this.name}"`,{id:u._id,collection:this.name});c.add(u._id),o.push(u)}if(a(),this._fieldIndex)this._fieldIndex.assertUniqueBatch(o);for(let l of o)this._addToIndex(l);this._data.push(...o);for(let l of o)this._index.set(l._id,l);return this._enforceCapAfterInsert(),{docs:o}}})}async updateOne(t,i,r={}){await this._ctx.ensureConnected();let s=this._findRaw(t);if(!s)return null;let{save:n,session:a}=r,{docs:o}=await this._updateCore([s],t,i,{save:n,session:a});return Q(o[0])}async updateMany(t,i,r={}){await this._ctx.ensureConnected();let s=this._findAllRaw(t);if(s.length===0)return[];let{save:n,session:a}=r,{docs:o}=await this._updateCore(s,t,i,{save:n,session:a});return o.map(Q)}async _updateCore(t,i,r,{save:s,session:n}){return this._pipeline.execute({op:"update",beforeHook:"beforeUpdate",afterHook:"afterUpdate",hookPayload:{collection:this.name,filter:i,update:r},save:s,session:n,afterHookPayload:(a)=>({collection:this.name,filter:i,update:r,result:a.length===1?a[0]:a}),mutate:async(a)=>{let o=this._changelogEnabled?t.map((u)=>structuredClone(u)):t.map(()=>null),c=t.map((u)=>this._prepareUpdatedDoc(u,r));this._assertUniqueCandidates(t,c),a();let l=new Set(t),d=new Map;for(let u=0;u<this._data.length;u++)if(l.has(this._data[u]))d.set(this._data[u],u);for(let u=0;u<t.length;u++)this._commitUpdatedDoc(t[u],c[u],d);return{docs:c,prevDocs:o}}})}applyUpdate(t,i){for(let r in i){if(Ms.has(r))continue;if(r==="_id"||r==="createdAt")continue;let s=i[r];if(Array.isArray(s))t[r]=s;else if(typeof s==="object"&&s!==null){let n=Object.keys(s);if(n.some((a)=>a.startsWith("$"))){for(let a of n)if(a==="$inc"&&typeof t[r]==="number")t[r]+=s[a];else if(a==="$push"){if(!Array.isArray(t[r]))t[r]=[];t[r].push(s[a])}}else t[r]=js(s)}else t[r]=s}if(t.updatedAt=new Date,this._versioning)t._version=(t._version??0)+1;return t}_prepareUpdatedDoc(t,i){let r=structuredClone(t),s=structuredClone(t);if(this.applyUpdate(s,i),!this._schema)return s;let n=jr(s,this._schema,this._strict);if(!n.length)return s;switch(this._onSchemaError){case"throw":throw new D("ERR_SKALEX_VALIDATION_UPDATE",`Update validation failed on doc "${t._id}": ${n.join("; ")}`,{id:t._id,errors:n});case"strip":return this._stripCandidateToValid(s,r);default:return this._ctx.logger(`[${this.name}] Update validation warning: ${n.join("; ")}`,"warn"),s}}_stripCandidateToValid(t,i){let r=qr(t,this._schema),s=structuredClone(i);for(let[n,a]of Object.entries(r)){if(n.startsWith("_"))continue;s[n]=a}if(s.updatedAt=t.updatedAt,this._versioning)s._version=t._version;return s}_commitUpdatedDoc(t,i,r){let s=r?r.get(t):this._data.indexOf(t);if(s===void 0||s===-1)throw new Ve("ERR_SKALEX_PERSISTENCE_DOC_MISSING",`Document "${t._id}" no longer exists in collection "${this.name}"`,{id:t._id,collection:this.name});this._data[s]=i,this._index.set(i._id,i),this._updateInIndex(t,i)}_assertUniqueCandidates(t,i){this._fieldIndex?.assertUniqueCandidates(t,i)}async upsert(t,i,r={}){if(await this._ctx.ensureConnected(),this._findRaw(t))return this.updateOne(t,i,r);return this.insertOne({...Go(t),...i},r)}async upsertMany(t,i,r={}){await this._ctx.ensureConnected();let{save:s,...n}=r,a=[];for(let o of t)a.push(await this.upsert({[i]:o[i]},o,{...n,save:!1}));return await this._saveIfNeeded(s),a}async restore(t,i={}){if(!this._softDelete)throw new ut("ERR_SKALEX_QUERY_SOFT_DELETE_REQUIRED",`restore() requires softDelete on "${this.name}"`,{collection:this.name});await this._ctx.ensureConnected();let{save:r,session:s}=i,n=this._findRaw(t,{includeDeleted:!0});if(!n||!n._deletedAt)return null;let{docs:a}=await this._pipeline.execute({op:"restore",beforeHook:null,afterHook:null,hookPayload:null,save:r,session:s,mutate:async(o)=>(o(),delete n._deletedAt,n.updatedAt=new Date,this._index.set(n._id,n),{docs:[n]})});return Q(a[0])}watch(t,i){if(typeof t==="function")i=t,t=null;if(i)return this._ctx.eventBus.on(this.name,(r)=>{if(!t||ie(r.doc,t))i(r)});return this._watchIterator(t)}_watchIterator(t){let i=[],r=null,s=!1,n=this._ctx.eventBus.on(this.name,(a)=>{if(t&&!ie(a.doc,t))return;if(r){let o=r;r=null,o({value:a,done:!1})}else i.push(a)});return{[Symbol.asyncIterator](){return this},next(){if(i.length>0)return Promise.resolve({value:i.shift(),done:!1});if(s)return Promise.resolve({value:void 0,done:!0});return new Promise((a)=>{r=a})},return(){if(s=!0,n(),r){let a=r;r=null,a({value:void 0,done:!0})}return Promise.resolve({value:void 0,done:!0})}}}async count(t={}){return await this._ctx.ensureConnected(),zo(this._findAllRaw(t))}async sum(t,i={}){return await this._ctx.ensureConnected(),Bo(this._findAllRaw(i),t)}async avg(t,i={}){return await this._ctx.ensureConnected(),Xo(this._findAllRaw(i),t)}async groupBy(t,i={}){return await this._ctx.ensureConnected(),Vo(this._findAllRaw(i),t)}async findOne(t,i={}){await this._ctx.ensureConnected();let{populate:r,select:s,includeDeleted:n=!1}=i,a=this._findRaw(t,{includeDeleted:n});if(!a)return null;let o=this._projectDoc(a,s);if(r)await this._populateDoc(o,a,r);return o}async find(t,i={}){await this._ctx.ensureConnected();let r=Date.now(),{populate:s,select:n,sort:a,page:o=1,limit:c,session:l,includeDeleted:d=!1}=i;await this._ctx.plugins.run("beforeFind",{collection:this.name,filter:t,options:i});let u=this._getCandidates(t),f=jo(t,this._fieldIndex?this._fieldIndex.indexedFields:new Set),h=[];for(let p of u){if(this._softDelete&&p._deletedAt&&!d)continue;if(!ie(p,f))continue;let g=this._projectDoc(p,n);if(s)await this._populateDoc(g,p,s);h.push(g)}if(a){let p=Object.keys(a);h.sort((g,m)=>{for(let w of p){let v=a[w];if(g[w]<m[w])return-v;if(g[w]>m[w])return v}return 0})}let _;if(c){let p=h.length,g=Math.ceil(p/c),m=(o-1)*c;h=h.slice(m,m+c),_={page:o,totalDocs:p,totalPages:g}}return this._ctx.queryLog?.record({collection:this.name,op:"find",filter:t,duration:Date.now()-r,resultCount:h.length}),this._ctx.sessionStats.recordRead(l),await this._ctx.plugins.run("afterFind",{collection:this.name,filter:t,options:i,docs:h}),_?{docs:h,..._}:{docs:h}}async search(t,{filter:i,limit:r=10,minScore:s=0,session:n}={}){await this._ctx.ensureConnected();let a=Date.now();await this._ctx.plugins.run("beforeSearch",{collection:this.name,query:t,options:{filter:i,limit:r,minScore:s}});let o=await this._ctx.embed(t),c=i?this._findAllRaw(i):this._data,l=[];for(let h of c){if(!h._vector)continue;let _=Ur(o,h._vector);if(_>=s)l.push({doc:h,score:_})}l.sort((h,_)=>_.score-h.score);let d=l.slice(0,r);this._ctx.queryLog?.record({collection:this.name,op:"search",query:t,duration:Date.now()-a,resultCount:d.length}),this._ctx.sessionStats.recordRead(n);let u=d.map((h)=>Q(h.doc)),f=d.map((h)=>h.score);return await this._ctx.plugins.run("afterSearch",{collection:this.name,query:t,options:{filter:i,limit:r,minScore:s},docs:u,scores:f}),{docs:u,scores:f}}async similar(t,{limit:i=10,minScore:r=0}={}){await this._ctx.ensureConnected();let s=this._index.get(t);if(!s||!s._vector)return{docs:[],scores:[]};let n=[];for(let o of this._data){if(o._id===t||!o._vector)continue;let c=Ur(s._vector,o._vector);if(c>=r)n.push({doc:o,score:c})}n.sort((o,c)=>c.score-o.score);let a=n.slice(0,i);return{docs:a.map((o)=>Q(o.doc)),scores:a.map((o)=>o.score)}}async deleteOne(t,i={}){await this._ctx.ensureConnected();let{save:r,session:s}=i;if(this._softDelete){let a=this._findRaw(t);if(!a)return null;let{docs:o}=await this._deleteCore("soft",[a],t,{save:r,session:s});return Q(o[0])}let{docs:n}=await this._deleteCore("hard",null,t,{save:r,session:s});if(n.length===0)return null;return Q(n[0])}async deleteMany(t,i={}){await this._ctx.ensureConnected();let{save:r,session:s}=i;if(this._softDelete){let a=this._findAllRaw(t);if(a.length===0)return[];let{docs:o}=await this._deleteCore("soft",a,t,{save:r,session:s});return o.map(Q)}let{docs:n}=await this._deleteCore("hardMany",null,t,{save:r,session:s});return n.map(Q)}async _deleteCore(t,i,r,{save:s,session:n}){return this._pipeline.execute({op:"delete",beforeHook:"beforeDelete",afterHook:"afterDelete",hookPayload:{collection:this.name,filter:r},save:s,session:n,afterHookPayload:(a)=>({collection:this.name,filter:r,result:a.length===1?a[0]:a}),mutate:async(a)=>{if(a(),t==="soft"){let l=new Date;for(let d of i)d._deletedAt=l,d.updatedAt=l,this._index.set(d._id,d);return{docs:i}}if(t==="hard"){let l=this._findIndex(r);if(l===-1)return{docs:[]};let d=this._data.splice(l,1)[0];return this._index.delete(d._id),this._removeFromIndex(d),{docs:[d]}}let o=[],c=[];for(let l of this._data)if(ie(l,r))o.push(l),this._index.delete(l._id),this._removeFromIndex(l);else c.push(l);return this._data=c,{docs:o}}})}async export(t={},i={}){let{dir:r,name:s,format:n="json"}=i;try{let a=this._data.filter((u)=>ie(u,t));if(a.length===0)throw new ut("ERR_SKALEX_QUERY_EXPORT_EMPTY",`export(): no documents matched the filter in "${this.name}"`,{collection:this.name});let o;if(n==="json")o=JSON.stringify(a,null,2);else{let u=(_)=>{if(_==null)return"";let p=typeof _==="object"?JSON.stringify(_):String(_);return p.includes(",")||p.includes('"')||p.includes(`
|
|
3
3
|
`)||p.includes("\r")?`"${p.replace(/"/g,'""')}"`:p},f=Object.keys(a[0]).map(u).join(","),h=a.map((_)=>Object.values(_).map(u).join(","));o=[f,...h].join(`
|
|
4
|
-
`)}if(typeof this._ctx.fs.writeRaw!=="function")throw new Se("ERR_SKALEX_ADAPTER_NO_RAW_WRITE","export() requires a file-system adapter (FsAdapter). The current adapter does not support raw file writes.");let c=r||`${this._ctx.dataDirectory}/exports`,l=`${s||this.name}.${n}`,d=this._ctx.fs.join(c,l);this._ctx.fs.ensureDir(c),await this._ctx.fs.writeRaw(d,o)}catch(a){throw this._ctx.logger(`Error exporting "${this.name}": ${a.message}`,"error"),a}}_txSnapshotIfNeeded(){let t=this._ctx.txManager;if(!t.active)return;if(this._activeTxId!==t.context?.id)return;t.snapshotIfNeeded(this.name,this._store,(i)=>this._ctx.snapshotCollection(i))}async _saveIfNeeded(t){let i=this._ctx.txManager;if(i.active&&this._activeTxId===i.context?.id)return;if(t??this._ctx.autoSave)await this._ctx.saveCollection(this.name)}_applyValidation(t){if(!this._schema)return t;let i=Mr(t,this._schema,this._strict);if(!i.length)return t;switch(this._onSchemaError){case"warn":return this._ctx.logger(`[${this.name}] Validation warning: ${i.join("; ")}`,"warn"),t;case"strip":return jr(t,this._schema);default:throw new D("ERR_SKALEX_VALIDATION_FAILED",`Validation failed: ${i.join("; ")}`,{errors:i})}}_enforceCapAfterInsert(){let t=this._maxDocs;if(!t||this._data.length<=t)return;let i=this._data.splice(0,this._data.length-t);for(let r of i)this._index.delete(r._id),this._removeFromIndex(r)}_findRaw(t,{includeDeleted:i=!1}={}){if(typeof t==="function"){for(let r of this._data){if(this._softDelete&&r._deletedAt&&!i)continue;if(t(r))return r}return null}if(t._id){let r=this._index.get(t._id)||null;if(!r)return null;if(this._softDelete&&r._deletedAt&&!i)return null;if(Object.keys(t).length>1)return ie(r,t)?r:null;return r}if(this._fieldIndex)for(let r in t){if(r==="$or"||r==="$and"||r==="$not")continue;let s=t[r];if(typeof s!=="object"||s===null){let n=this._fieldIndex._lookupIterable(r,s);if(n!==null){for(let a of n){if(this._softDelete&&a._deletedAt&&!i)continue;if(ie(a,t))return a}return null}}}for(let r of this._data){if(this._softDelete&&r._deletedAt&&!i)continue;if(ie(r,t))return r}return null}_findAllRaw(t,{includeDeleted:i=!1}={}){if(t&&typeof t!=="function"&&t._id){let s=this._index.get(t._id);if(!s)return[];if(this._softDelete&&s._deletedAt&&!i)return[];return ie(s,t)?[s]:[]}let r=[];for(let s of this._getCandidates(t)){if(this._softDelete&&s._deletedAt&&!i)continue;if(ie(s,t))r.push(s)}return r}_getCandidates(t){if(!this._fieldIndex)return this._data;if(this._fieldIndex._compoundIndexes.size>0){let i={};for(let r in t){if(r==="$or"||r==="$and"||r==="$not")continue;let s=t[r];if(typeof s!=="object"||s===null)i[r]=s}if(Object.keys(i).length>=2){let r=this._fieldIndex.lookupCompound(i);if(r!==null)return r}}for(let i in t){if(i==="$or"||i==="$and"||i==="$not")continue;let r=t[i];if(typeof r!=="object"||r===null){let s=this._fieldIndex._lookupIterable(i,r);if(s!==null)return s}}return this._data}_findIndex(t){for(let i=0;i<this._data.length;i++)if(ie(this._data[i],t))return i;return-1}_addToIndex(t){if(this._fieldIndex)this._fieldIndex.add(t)}_removeFromIndex(t){if(this._fieldIndex)this._fieldIndex.remove(t)}_updateInIndex(t,i){if(this._fieldIndex)this._fieldIndex.update(t,i)}async _buildDoc(t,{ttl:i,embed:r}={}){let s={...t,_id:t._id??(this._ctx.idGenerator??Po)(),createdAt:new Date,updatedAt:new Date},n=i??this._defaultTtl;if(n)s._expiresAt=Uo(n);let a=r??this._defaultEmbed;if(a){let o=typeof a==="function"?a(s):s[a];s._vector=await this._ctx.embed(String(o))}if(this._versioning)s._version=1;return s}_projectDoc(t,i){if(i){let s={};for(let n of i){if(n==="_vector")continue;s[n]=t[n]}return s}let r={...t};return delete r._vector,r}async _populateDoc(t,i,r){for(let s of r){let n=await this._ctx.getCollection(s).findOne({_id:i[s]});if(n)t[s]=n}}}class Bi{async read(t){throw Error("StorageAdapter.read() not implemented")}async write(t,i){throw Error("StorageAdapter.write() not implemented")}async delete(t){throw Error("StorageAdapter.delete() not implemented")}async list(){throw Error("StorageAdapter.list() not implemented")}async writeAll(t){for(let{name:i,data:r}of t)await this.write(i,r)}}class qs extends Bi{constructor({dir:t,format:i="gz"}){super();this.dir=rt.resolve(t),this.format=i,this._ensureDir(this.dir)}_ensureDir(t){if(!G.existsSync(t))G.mkdirSync(t,{recursive:!0})}_filePath(t){return rt.join(this.dir,`${t}.${this.format}`)}async read(t){let i=this._filePath(t);try{let r=await G.promises.readFile(i);if(this.format==="gz")r=xi.inflateSync(r);return r.toString("utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}}async write(t,i){let r=this._filePath(t),s=rt.join(this.dir,`${t}_${globalThis.crypto.randomUUID()}.tmp.${this.format}`);if(this.format==="gz"){let n=xi.deflateSync(i);await G.promises.writeFile(s,n)}else await G.promises.writeFile(s,i,"utf8");await G.promises.rename(s,r)}async writeAll(t){let i=[];try{for(let{name:r,data:s}of t){let n=this._filePath(r),a=rt.join(this.dir,`${r}_${globalThis.crypto.randomUUID()}.tmp.${this.format}`);if(this.format==="gz"){let o=xi.deflateSync(s);await G.promises.writeFile(a,o)}else await G.promises.writeFile(a,s,"utf8");i.push({tmp:a,fp:n})}for(let{tmp:r,fp:s}of i)await G.promises.rename(r,s)}catch(r){for(let{tmp:s}of i)try{await G.promises.unlink(s)}catch{}throw r}}async delete(t){let i=this._filePath(t);try{await G.promises.unlink(i)}catch(r){if(r.code!=="ENOENT")throw r}}async list(){try{let t=await G.promises.readdir(this.dir),i=`.${this.format}`;return t.filter((r)=>r.endsWith(i)&&!r.includes(".tmp.")).map((r)=>r.slice(0,-i.length))}catch(t){if(t.code==="ENOENT")return[];throw t}}join(...t){return rt.join(...t)}ensureDir(t){this._ensureDir(t)}async writeRaw(t,i){this._ensureDir(rt.dirname(t)),await G.promises.writeFile(t,i,"utf8")}async readRaw(t){return G.promises.readFile(rt.resolve(t),"utf8")}}class Us{constructor(){this._migrations=[]}add(t){let{version:i,up:r}=t;if(typeof i!=="number"||i<1)throw new D("ERR_SKALEX_VALIDATION_MIGRATION",`Migration version must be a positive integer, got ${i}`,{version:i});if(typeof r!=="function")throw new D("ERR_SKALEX_VALIDATION_MIGRATION",`Migration version ${i} must have an "up" function`,{version:i});if(this._migrations.some((s)=>s.version===i))throw new D("ERR_SKALEX_VALIDATION_MIGRATION_DUPLICATE",`Migration version ${i} is already registered`,{version:i});this._migrations.push({...t}),this._migrations.sort((s,n)=>s.version-n.version)}async run(t,i=[]){let r=new Set(i),s=this._migrations.filter((n)=>!r.has(n.version));for(let n of s){let a=t(n.version);await n.up(a),r.add(n.version)}return[...r].sort((n,a)=>n-a)}status(t=[]){let i=new Set(t),r=this._migrations.map((s)=>s.version).filter((s)=>!i.has(s));return{current:t.length?Math.max(...t):0,applied:[...i].sort((s,n)=>s-n),pending:r}}}var Ur={[Symbol.iterator](){return{next(){return{done:!0}}}},size:0};function Fr(t){return{[Symbol.iterator](){return t[Symbol.iterator]()},get size(){return t.size}}}function Ti(t){return t.map((i)=>{if(i===null||i===void 0)return"\x00";if(typeof i==="boolean")return i?"\x01T":"\x01F";if(typeof i==="number")return`\x02${i}`;return`\x03${String(i)}`}).join("\x1F")}class ei{constructor(t=[],i=[]){this._fields=new Set,this._compoundFields=[];for(let r of t)if(Array.isArray(r)){for(let s of r)this._validateFieldName(s);this._compoundFields.push(r)}else this._validateFieldName(r),this._fields.add(r);for(let r of i)this._validateFieldName(r);this._uniqueFields=new Set(i),this._indexedFields=new Set([...this._fields,...this._uniqueFields]),this._fieldIndexes=new Map,this._uniqueIndexes=new Map;for(let r of this._fields)this._fieldIndexes.set(r,new Map);for(let r of this._uniqueFields)if(this._uniqueIndexes.set(r,new Map),!this._fieldIndexes.has(r))this._fieldIndexes.set(r,new Map);this._compoundIndexes=new Map;for(let r of this._compoundFields)this._compoundIndexes.set(r.join("\x00"),{fields:r,map:new Map})}get indexedFields(){return this._indexedFields}buildFromData(t){for(let[,i]of this._fieldIndexes)i.clear();for(let[,i]of this._uniqueIndexes)i.clear();for(let[,i]of this._compoundIndexes)i.map.clear();for(let i of t)this._indexDoc(i)}add(t){this._checkUnique(t,null),this._indexDoc(t)}remove(t){for(let[i,r]of this._fieldIndexes){let s=t[i];if(s!==void 0){let n=r.get(s);if(n){if(n.delete(t),n.size===0)r.delete(s)}}}for(let[i,r]of this._uniqueIndexes){let s=t[i];if(s!==void 0)r.delete(s)}for(let[,i]of this._compoundIndexes){let r=Ti(i.fields.map((n)=>t[n])),s=i.map.get(r);if(s){if(s.delete(t),s.size===0)i.map.delete(r)}}}update(t,i){this._checkUnique(i,t),this.remove(t);try{this._indexDoc(i)}catch(r){try{this._indexDoc(t)}catch{}throw r}}lookup(t,i){let r=this._fieldIndexes.get(t);if(!r)return null;let s=r.get(i);return s?[...s]:[]}_lookupIterable(t,i){let r=this._fieldIndexes.get(t);if(!r)return null;let s=r.get(i);return s?Fr(s):Ur}lookupCompound(t){let i=Object.keys(t).sort();for(let[,r]of this._compoundIndexes){let s=[...r.fields].sort();if(s.length!==i.length)continue;if(s.every((n,a)=>n===i[a])){let n=Ti(r.fields.map((o)=>t[o])),a=r.map.get(n);return a?Fr(a):Ur}}return null}isUniqueTaken(t,i){let r=this._uniqueIndexes.get(t);if(!r)return!1;return r.has(i)}assertUniqueCandidates(t,i){if(this._uniqueFields.size===0)return;let r=new Set(t.map((s)=>s._id));for(let s of this._uniqueFields){let n=new Set,a=this._uniqueIndexes.get(s);if(a){for(let[c,l]of a.entries())if(!r.has(l._id))n.add(c)}let o=new Map;for(let c=0;c<i.length;c++){let l=i[c][s];if(l===void 0)continue;if(n.has(l))throw new De("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${s}" value "${l}" already exists`,{field:s,value:l});let d=o.get(l);if(d&&d!==t[c]._id)throw new De("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${s}" value "${l}" already exists`,{field:s,value:l});o.set(l,t[c]._id)}}}assertUniqueBatch(t){if(this._uniqueFields.size===0)return;for(let i of this._uniqueFields){let r=this._uniqueIndexes.get(i),s=new Set;for(let n of t){let a=n[i];if(a===void 0)continue;if(r&&r.has(a))throw new De("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${i}" value "${a}" already exists`,{field:i,value:a});if(s.has(a))throw new De("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: duplicate "${i}" value "${a}" within batch`,{field:i,value:a});s.add(a)}}}_validateFieldName(t){if(t.includes("."))throw new D("ERR_SKALEX_VALIDATION_INDEX_DOT_PATH",`Index fields cannot use dot-notation: "${t}". Use a flat field name.`,{field:t})}_indexDoc(t){for(let[i,r]of this._fieldIndexes){let s=t[i];if(s!==void 0){if(!r.has(s))r.set(s,new Set);r.get(s).add(t)}}for(let[i,r]of this._uniqueIndexes){let s=t[i];if(s!==void 0)r.set(s,t)}for(let[,i]of this._compoundIndexes){for(let s of i.fields){let n=t[s];if(n!==void 0&&n!==null&&typeof n==="object")throw new D("ERR_SKALEX_VALIDATION_COMPOUND_INDEX",`Compound index field "${s}" must be a scalar value (string, number, or boolean), got ${Array.isArray(n)?"array":typeof n}`,{field:s})}let r=Ti(i.fields.map((s)=>t[s]));if(!i.map.has(r))i.map.set(r,new Set);i.map.get(r).add(t)}}_checkUnique(t,i){for(let r of this._uniqueFields){let s=t[r];if(s===void 0)continue;let n=this._uniqueIndexes.get(r);if(!n)continue;let a=n.get(s);if(a&&a._id!==i?._id)throw new De("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${r}" value "${s}" already exists`,{field:r,value:s})}}}var jt="_flush",qt="migrations";class Fs{constructor({adapter:t,serializer:i,deserializer:r,logger:s,debug:n=!1,lenientLoad:a=!1}){this._adapter=t,this._serializer=i,this._deserializer=r,this._logger=s,this._debug=n,this._lenientLoad=a,this._saveLock=Promise.resolve()}_withSaveLock(t){let i=this._saveLock.then(t);return this._saveLock=i.catch(()=>{}),i}async loadAll(t,{parseSchema:i,buildIndex:r,IndexEngine:s}){try{let n=await this._adapter.list();await Promise.all(n.map(async(a)=>{try{let o=await this._adapter.read(a);if(!o)return;let c=this._deserializer(o),{collectionName:l,data:d}=c;if(!l)return;let u=t[l],f=u?.rawSchema??c.rawSchema??null,h=u?.schema??(f?i(f):null),_=u?.changelog??c.changelog??!1,p=u?.softDelete??c.softDelete??!1,g=u?.versioning??c.versioning??!1,m=u?.strict??c.strict??!1,w=u?.onSchemaError??c.onSchemaError??"throw",v=u?.defaultTtl??c.defaultTtl??null,q=u?.defaultEmbed??c.defaultEmbed??null,E=u?.maxDocs??c.maxDocs??null,A=u?u.fieldIndex:null;if(!A&&h?.uniqueFields?.length)A=new s([],h.uniqueFields);let tt=r(d,"_id");if(A)A.buildFromData(d);t[l]={collectionName:l,data:d,index:tt,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:h,rawSchema:f,fieldIndex:A,changelog:_,softDelete:p,versioning:g,strict:m,onSchemaError:w,defaultTtl:v,defaultEmbed:q,maxDocs:E}}catch(o){if(o.code==="ENOENT")return;if(this._lenientLoad){this._logger(`WARNING: Could not load collection "${a}": ${o.message}. Collection will be empty.`,"error");return}throw new Ve("ERR_SKALEX_PERSISTENCE_CORRUPT",`Failed to load collection "${a}": ${o.message}`,{collection:a})}})),this._detectIncompleteFlush(t),await this._cleanOrphanTempFiles()}catch(n){if(n.code!=="ENOENT")throw this._logger(`Error loading data: ${n}`,"error"),n}}async save(t,i){if(i)await this._saveOne(t,i);else await Promise.all(Object.keys(t).map((r)=>this._saveOne(t,r)))}async saveDirty(t){let i=Object.keys(t).filter((r)=>t[r]._dirty);if(i.length===0)return;await Promise.all(i.map((r)=>this._saveOne(t,r)))}saveAtomic(t,i){return this._withSaveLock(async()=>{if(i.length===0)return;this._writeFlushSentinel(t,i);let r=new Set(i);r.add("_meta");let s=[...r].filter((n)=>t[n]).map((n)=>({name:n,data:this._serializeCollection(t[n])}));try{await this._adapter.writeAll(s)}catch(n){throw new Ve("ERR_SKALEX_PERSISTENCE_FLUSH_FAILED",`Batch save failed during writeAll: ${n.message}`,{collections:i})}for(let n of i)if(t[n])t[n]._dirty=!1;try{this._clearFlushSentinel(t),await this._adapter.write("_meta",this._serializeCollection(t._meta))}catch(n){this._logger(`WARNING: Batch data committed but sentinel clear failed: ${n.message}. Next load will report an incomplete flush (false positive).`,"error")}})}markDirty(t,i){let r=t[i];if(r)r._dirty=!0}_serializeCollection(t){let i={collectionName:t.collectionName,data:t.data};if(t.rawSchema)i.rawSchema=t.rawSchema;if(t.changelog)i.changelog=t.changelog;if(t.softDelete)i.softDelete=t.softDelete;if(t.versioning)i.versioning=t.versioning;if(t.strict)i.strict=t.strict;if(t.onSchemaError!=="throw")i.onSchemaError=t.onSchemaError;if(t.defaultTtl)i.defaultTtl=t.defaultTtl;if(t.defaultEmbed)i.defaultEmbed=t.defaultEmbed;if(t.maxDocs)i.maxDocs=t.maxDocs;return this._serializer(i)}async _saveOne(t,i){let r=t[i];if(!r)return;if(r.isSaving)return r._pendingSave=!0,new Promise((s,n)=>{(r._saveWaiters??=[]).push({resolve:s,reject:n})});r.isSaving=!0,r._pendingSave=!1;try{await this._writeCollection(i,r);while(r._pendingSave)r._pendingSave=!1,await this._writeCollection(i,r);this._resolveSaveWaiters(r)}catch(s){throw this._rejectSaveWaiters(r,s),s}finally{r.isSaving=!1}}async _writeCollection(t,i){try{await this._adapter.write(t,this._serializeCollection(i)),i._dirty=!1}catch(r){throw this._logger(`Error saving "${t}": ${r.message}`,"error"),r}}_resolveSaveWaiters(t){let i=t._saveWaiters?.splice(0)??[];for(let r of i)r.resolve()}_rejectSaveWaiters(t,i){let r=t._saveWaiters?.splice(0)??[];for(let s of r)s.reject(i)}_writeFlushSentinel(t,i){let r=this._getOrCreateMeta(t);r[jt]={startedAt:new Date().toISOString(),collections:i,completedAt:null}}_clearFlushSentinel(t){let i=this._getOrCreateMeta(t);if(i[jt])i[jt].completedAt=new Date().toISOString()}_detectIncompleteFlush(t){let i=t._meta;if(!i)return;let r=i.index.get(qt);if(!r)return;let s=r[jt];if(!s)return;if(s.startedAt&&!s.completedAt)this._logger(`WARNING: Incomplete flush detected (started ${s.startedAt}, collections: ${s.collections?.join(", ")}). Data may be inconsistent.`,"error")}async _cleanOrphanTempFiles(){if(typeof this._adapter.join!=="function")return;if(typeof this._adapter.list!=="function")return;try{let t=await import("fs"),i=await import("path"),r=this._adapter.dir;if(!r)return;let s=(await t.default.promises.readdir(r)).filter((n)=>n.includes(".tmp."));for(let n of s){let a=i.default.join(r,n);try{await t.default.promises.unlink(a),this._log(`Cleaned orphan temp file: ${n}`)}catch{}}}catch{}}_getOrCreateMeta(t){if(!t._meta)t._meta={collectionName:"_meta",data:[],index:new Map,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:null,rawSchema:null,fieldIndex:null,changelog:!1,softDelete:!1,versioning:!1,strict:!1,onSchemaError:"throw",defaultTtl:null,defaultEmbed:null,maxDocs:null};let i=t._meta,r=i.index.get(qt);if(!r)r={_id:qt},i.data.push(r),i.index.set(qt,r);return r}_log(t){if(this._debug)this._logger(t,"info")}}var Go=0;class Ks{constructor(){this._txLock=Promise.resolve(),this._ctx=null,this._abortedIds=new Set}get active(){return this._ctx!==null&&!this._ctx.aborted}get context(){return this._ctx}async run(t,i,{timeout:r=0}={}){let s=async()=>{await i._ensureConnected();let a=new Set(Object.keys(i.collections)),o={id:++Go,startedAt:Date.now(),aborted:!1,preExisting:a,touchedCollections:new Set,snapshots:new Map,deferredEffects:[],timeout:r};this._ctx=o;let c=null,l=r>0?new Promise((f,h)=>{c=setTimeout(()=>{o.aborted=!0,h(new Re("ERR_SKALEX_TX_TIMEOUT",`Transaction ${o.id} timed out after ${r}ms`))},r)}):null,d=this,u=new Proxy(i,{get(f,h){if(h==="_txId")return o.id;if(o!==d._ctx)throw new Re("ERR_SKALEX_TX_STALE_PROXY",`Transaction ${o.id} has ended. This proxy is no longer usable.`);if(h==="collections")throw new Re("ERR_SKALEX_TX_DIRECT_ACCESS","Direct access to db.collections inside transaction() is not covered by rollback. Use the collection API (db.useCollection) instead.");if(h==="useCollection")return(p)=>{let g=f.useCollection(p);return g._activeTxId=o.id,g};let _=Reflect.get(f,h);return typeof _==="function"?_.bind(f):_}});try{let f=t(u),h=l?await Promise.race([f,l]):await f;if(o.aborted)throw new Re("ERR_SKALEX_TX_ABORTED",`Transaction ${o.id} was aborted`);let _=[...o.touchedCollections];if(_.length>0)await i._persistence.saveAtomic(i.collections,_);for(let p of o.deferredEffects)await p();return h}catch(f){for(let[h,_]of o.snapshots)if(o.preExisting.has(h)){if(i._applySnapshot(h,_),i.collections[h])i.collections[h]._dirty=_._dirty}for(let h in i.collections)if(!o.preExisting.has(h))delete i.collections[h],delete i._collectionInstances[h];throw f}finally{if(c)clearTimeout(c);if(o.aborted)this._abortedIds.add(o.id);this._ctx=null;for(let f in i._collectionInstances){let h=i._collectionInstances[f];if(h._createdInTxId===o.id)h._createdInTxId=null;if(h._activeTxId===o.id)h._activeTxId=null}}},n=this._txLock.then(s);return this._txLock=n.catch(()=>{}),n}snapshotIfNeeded(t,i,r){let s=this._ctx;if(!s)return;if(this._assertCtxNotAborted(s),!s.snapshots.has(t)){let n=r(i);n._dirty=i._dirty??!1,s.snapshots.set(t,n)}s.touchedCollections.add(t)}assertNotAborted(){let t=this._ctx;if(t)this._assertCtxNotAborted(t)}_assertCtxNotAborted(t){if(t.aborted)throw new Re("ERR_SKALEX_TX_ABORTED",`Transaction ${t.id} was aborted. No further mutations allowed.`)}defer(t){if(this._ctx)return this._ctx.deferredEffects.push(t),!0;return!1}}class zs{constructor(t){this._CollectionClass=t,this.stores={},this._instances={}}get(t,i){if(this._instances[t])return this._instances[t];if(!this.stores[t])this.createStore(t);let r=new this._CollectionClass(this.stores[t],i);return this._instances[t]=r,r}create(t,i={},r){this.createStore(t,i);let s=new this._CollectionClass(this.stores[t],r);return this._instances[t]=s,s}createStore(t,{schema:i,indexes:r=[],changelog:s=!1,softDelete:n=!1,versioning:a=!1,strict:o=!1,onSchemaError:c="throw",defaultTtl:l=null,defaultEmbed:d=null,maxDocs:u=null}={}){let f=null,h=null;if(i){f=Ds(i);let _=f.uniqueFields;if(r.length||_.length)h=new ei(r,_)}else if(r.length)h=new ei(r,[]);this.stores[t]={collectionName:t,data:[],index:new Map,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:f,rawSchema:i||null,fieldIndex:h,changelog:s,softDelete:n,versioning:a,strict:o,onSchemaError:c,defaultTtl:l,defaultEmbed:d,maxDocs:u}}rename(t,i){if(!this.stores[t])throw new Ve("ERR_SKALEX_PERSISTENCE_COLLECTION_NOT_FOUND",`Collection "${t}" not found`,{collection:t});if(this.stores[i])throw new Ve("ERR_SKALEX_PERSISTENCE_COLLECTION_EXISTS",`Collection "${i}" already exists`,{collection:i});let r=this.stores[t];if(r.collectionName=i,this.stores[i]=r,delete this.stores[t],this._instances[t]){let s=this._instances[t];s.name=i,this._instances[i]=s,delete this._instances[t]}}buildIndex(t,i){let r=new Map;for(let s of t)r.set(s[i],s);return r}inspect(t){if(t){let r=this.stores[t];if(!r)return null;return{name:t,count:r.data.length,schema:r.schema?Object.fromEntries(r.schema.fields):null,indexes:r.fieldIndex?[...r.fieldIndex.indexedFields]:[],softDelete:r.softDelete??!1,versioning:r.versioning??!1,strict:r.strict??!1,onSchemaError:r.onSchemaError??"throw",maxDocs:r.maxDocs??null}}let i={};for(let r in this.stores)i[r]=this.inspect(r);return i}dump(){let t={};for(let i in this.stores)if(!i.startsWith("_"))t[i]=structuredClone(this.stores[i].data);return t}schema(t){let i=this.stores[t];if(!i)return null;if(i.schema)return Object.fromEntries([...i.schema.fields.entries()].map(([r,s])=>[r,s.type]));if(i.data.length>0)return jo(i.data[0]);return null}stats(t){let i=(r)=>{let s=this.stores[r];if(!s)return null;let n=s.data.length,a=0;for(let o of s.data)try{a+=JSON.stringify(o).length}catch(c){}return{collection:r,count:n,estimatedSize:a,avgDocSize:n>0?Math.round(a/n):0}};if(t)return i(t);return Object.keys(this.stores).map(i)}clear(){this.stores={},this._instances={}}}class Xi{async embed(t){throw Error("EmbeddingAdapter.embed() not implemented")}}var we=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class Bs extends Xi{constructor({apiKey:t=we("OPENAI_API_KEY"),model:i=we("OPENAI_EMBED_MODEL")??"text-embedding-3-small",baseUrl:r=we("OPENAI_EMBED_BASE_URL")??"https://api.openai.com/v1/embeddings",dimensions:s=we("OPENAI_EMBED_DIMENSIONS")!=null?Number(we("OPENAI_EMBED_DIMENSIONS")):void 0,organization:n=we("OPENAI_ORGANIZATION")??void 0,timeout:a=we("OPENAI_EMBED_TIMEOUT")!=null?Number(we("OPENAI_EMBED_TIMEOUT")):void 0,retries:o=Number(we("OPENAI_EMBED_RETRIES")??0),retryDelay:c=Number(we("OPENAI_EMBED_RETRY_DELAY")??1000),headers:l={},fetch:d=globalThis.fetch}={}){super();if(!t)throw Error("OpenAIEmbeddingAdapter requires an apiKey");this.apiKey=t,this.model=i,this.baseUrl=r,this.dimensions=s,this.organization=n,this.timeout=a,this.retries=o,this.retryDelay=c,this.headers=l,this._fetch=d}async embed(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,...this.organization&&{"OpenAI-Organization":this.organization},...this.headers},body:JSON.stringify({input:t,model:this.model,...this.dimensions!==void 0&&{dimensions:this.dimensions}}),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`OpenAI embedding API error ${a.status}: ${o}`)}return(await a.json()).data[0].embedding}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}var mt=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class Xs extends Xi{constructor({model:t=mt("OLLAMA_EMBED_MODEL")??"nomic-embed-text",host:i=mt("OLLAMA_HOST")??"http://localhost:11434",timeout:r=mt("OLLAMA_EMBED_TIMEOUT")!=null?Number(mt("OLLAMA_EMBED_TIMEOUT")):void 0,retries:s=Number(mt("OLLAMA_EMBED_RETRIES")??0),retryDelay:n=Number(mt("OLLAMA_EMBED_RETRY_DELAY")??1000),headers:a={},fetch:o=globalThis.fetch}={}){super();this.model=t,this.host=i,this.timeout=r,this.retries=s,this.retryDelay=n,this.headers=a,this._fetch=o}async embed(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(`${this.host}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json",...this.headers},body:JSON.stringify({model:this.model,prompt:t}),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`Ollama embedding API error ${a.status}: ${o}`)}return(await a.json()).embedding}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}class ai{async generate(t,i){throw Error("LLMAdapter.generate() not implemented")}async summarize(t){throw Error("LLMAdapter.summarize() not implemented")}}var Vi=`You are a database query assistant. Convert the user's natural language request into a JSON filter object for a document database.
|
|
4
|
+
`)}if(typeof this._ctx.fs.writeRaw!=="function")throw new be("ERR_SKALEX_ADAPTER_NO_RAW_WRITE","export() requires a file-system adapter (FsAdapter). The current adapter does not support raw file writes.");let c=r||`${this._ctx.dataDirectory}/exports`,l=`${s||this.name}.${n}`,d=this._ctx.fs.join(c,l);this._ctx.fs.ensureDir(c),await this._ctx.fs.writeRaw(d,o)}catch(a){throw this._ctx.logger(`Error exporting "${this.name}": ${a.message}`,"error"),a}}_txSnapshotIfNeeded(){let t=this._ctx.txManager;if(!t.active)return;if(this._activeTxId!==t.context?.id)return;t.snapshotIfNeeded(this.name,this._store,(i)=>this._ctx.snapshotCollection(i))}async _saveIfNeeded(t){let i=this._ctx.txManager;if(i.active&&this._activeTxId===i.context?.id)return;if(t??this._ctx.autoSave)await this._ctx.saveCollection(this.name)}_applyValidation(t){if(!this._schema)return t;let i=jr(t,this._schema,this._strict);if(!i.length)return t;switch(this._onSchemaError){case"warn":return this._ctx.logger(`[${this.name}] Validation warning: ${i.join("; ")}`,"warn"),t;case"strip":return qr(t,this._schema);default:throw new D("ERR_SKALEX_VALIDATION_FAILED",`Validation failed: ${i.join("; ")}`,{errors:i})}}_enforceCapAfterInsert(){let t=this._maxDocs;if(!t||this._data.length<=t)return;let i=this._data.splice(0,this._data.length-t);for(let r of i)this._index.delete(r._id),this._removeFromIndex(r)}_findRaw(t,{includeDeleted:i=!1}={}){if(typeof t==="function"){for(let r of this._data){if(this._softDelete&&r._deletedAt&&!i)continue;if(t(r))return r}return null}if(t._id){let r=this._index.get(t._id)||null;if(!r)return null;if(this._softDelete&&r._deletedAt&&!i)return null;if(Object.keys(t).length>1)return ie(r,t)?r:null;return r}if(this._fieldIndex)for(let r in t){if(r==="$or"||r==="$and"||r==="$not")continue;let s=t[r];if(typeof s!=="object"||s===null){let n=this._fieldIndex._lookupIterable(r,s);if(n!==null){for(let a of n){if(this._softDelete&&a._deletedAt&&!i)continue;if(ie(a,t))return a}return null}}}for(let r of this._data){if(this._softDelete&&r._deletedAt&&!i)continue;if(ie(r,t))return r}return null}_findAllRaw(t,{includeDeleted:i=!1}={}){if(t&&typeof t!=="function"&&t._id){let s=this._index.get(t._id);if(!s)return[];if(this._softDelete&&s._deletedAt&&!i)return[];return ie(s,t)?[s]:[]}let r=[];for(let s of this._getCandidates(t)){if(this._softDelete&&s._deletedAt&&!i)continue;if(ie(s,t))r.push(s)}return r}_getCandidates(t){if(!this._fieldIndex)return this._data;if(this._fieldIndex._compoundIndexes.size>0){let i={};for(let r in t){if(r==="$or"||r==="$and"||r==="$not")continue;let s=t[r];if(typeof s!=="object"||s===null)i[r]=s}if(Object.keys(i).length>=2){let r=this._fieldIndex.lookupCompound(i);if(r!==null)return r}}for(let i in t){if(i==="$or"||i==="$and"||i==="$not")continue;let r=t[i];if(typeof r!=="object"||r===null){let s=this._fieldIndex._lookupIterable(i,r);if(s!==null)return s}}return this._data}_findIndex(t){for(let i=0;i<this._data.length;i++)if(ie(this._data[i],t))return i;return-1}_addToIndex(t){if(this._fieldIndex)this._fieldIndex.add(t)}_removeFromIndex(t){if(this._fieldIndex)this._fieldIndex.remove(t)}_updateInIndex(t,i){if(this._fieldIndex)this._fieldIndex.update(t,i)}async _buildDoc(t,{ttl:i,embed:r}={}){let s={...t,_id:t._id??(this._ctx.idGenerator??Mo)(),createdAt:new Date,updatedAt:new Date},n=i??this._defaultTtl;if(n)s._expiresAt=Fo(n);let a=r??this._defaultEmbed;if(a){let o=typeof a==="function"?a(s):s[a];s._vector=await this._ctx.embed(String(o))}if(this._versioning)s._version=1;return s}_projectDoc(t,i){if(i){let s={};for(let n of i){if(n==="_vector")continue;s[n]=t[n]}return s}let r={...t};return delete r._vector,r}async _populateDoc(t,i,r){for(let s of r){let n=await this._ctx.getCollection(s).findOne({_id:i[s]});if(n)t[s]=n}}}class Fi{async read(t){throw Error("StorageAdapter.read() not implemented")}async write(t,i){throw Error("StorageAdapter.write() not implemented")}async delete(t){throw Error("StorageAdapter.delete() not implemented")}async list(){throw Error("StorageAdapter.list() not implemented")}async writeAll(t){for(let{name:i,data:r}of t)await this.write(i,r)}}class Us extends Fi{constructor({dir:t,format:i="gz"}){super();this.dir=it.resolve(t),this.format=i,this._ensureDir(this.dir)}_ensureDir(t){if(!G.existsSync(t))G.mkdirSync(t,{recursive:!0})}_filePath(t){return it.join(this.dir,`${t}.${this.format}`)}async read(t){let i=this._filePath(t);try{let r=await G.promises.readFile(i);if(this.format==="gz")r=Ai.inflateSync(r);return r.toString("utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}}async write(t,i){let r=this._filePath(t),s=it.join(this.dir,`${t}_${globalThis.crypto.randomUUID()}.tmp.${this.format}`);if(this.format==="gz"){let n=Ai.deflateSync(i);await G.promises.writeFile(s,n)}else await G.promises.writeFile(s,i,"utf8");await G.promises.rename(s,r)}async writeAll(t){let i=[];try{for(let{name:r,data:s}of t){let n=this._filePath(r),a=it.join(this.dir,`${r}_${globalThis.crypto.randomUUID()}.tmp.${this.format}`);if(this.format==="gz"){let o=Ai.deflateSync(s);await G.promises.writeFile(a,o)}else await G.promises.writeFile(a,s,"utf8");i.push({tmp:a,fp:n})}for(let{tmp:r,fp:s}of i)await G.promises.rename(r,s)}catch(r){for(let{tmp:s}of i)try{await G.promises.unlink(s)}catch{}throw r}}async delete(t){let i=this._filePath(t);try{await G.promises.unlink(i)}catch(r){if(r.code!=="ENOENT")throw r}}async list(){try{let t=await G.promises.readdir(this.dir),i=`.${this.format}`;return t.filter((r)=>r.endsWith(i)&&!r.includes(".tmp.")).map((r)=>r.slice(0,-i.length))}catch(t){if(t.code==="ENOENT")return[];throw t}}join(...t){return it.join(...t)}ensureDir(t){this._ensureDir(t)}async writeRaw(t,i){this._ensureDir(it.dirname(t)),await G.promises.writeFile(t,i,"utf8")}async readRaw(t){return G.promises.readFile(it.resolve(t),"utf8")}}class Fs{constructor(){this._migrations=[]}add(t){let{version:i,up:r}=t;if(typeof i!=="number"||i<1)throw new D("ERR_SKALEX_VALIDATION_MIGRATION",`Migration version must be a positive integer, got ${i}`,{version:i});if(typeof r!=="function")throw new D("ERR_SKALEX_VALIDATION_MIGRATION",`Migration version ${i} must have an "up" function`,{version:i});if(this._migrations.some((s)=>s.version===i))throw new D("ERR_SKALEX_VALIDATION_MIGRATION_DUPLICATE",`Migration version ${i} is already registered`,{version:i});this._migrations.push({...t}),this._migrations.sort((s,n)=>s.version-n.version)}async run(t,i=[]){let r=new Set(i),s=this._migrations.filter((n)=>!r.has(n.version));for(let n of s){let a=t(n.version);await n.up(a),r.add(n.version)}return[...r].sort((n,a)=>n-a)}status(t=[]){let i=new Set(t),r=this._migrations.map((s)=>s.version).filter((s)=>!i.has(s));return{current:t.length?Math.max(...t):0,applied:[...i].sort((s,n)=>s-n),pending:r}}}var Fr={[Symbol.iterator](){return{next(){return{done:!0}}}},size:0};function Kr(t){return{[Symbol.iterator](){return t[Symbol.iterator]()},get size(){return t.size}}}function Si(t){return t.map((i)=>{if(i===null||i===void 0)return"\x00";if(typeof i==="boolean")return i?"\x01T":"\x01F";if(typeof i==="number")return`\x02${i}`;return`\x03${String(i)}`}).join("\x1F")}class Yt{constructor(t=[],i=[]){this._fields=new Set,this._compoundFields=[];for(let r of t)if(Array.isArray(r)){for(let s of r)this._validateFieldName(s);this._compoundFields.push(r)}else this._validateFieldName(r),this._fields.add(r);for(let r of i)this._validateFieldName(r);this._uniqueFields=new Set(i),this._indexedFields=new Set([...this._fields,...this._uniqueFields]),this._fieldIndexes=new Map,this._uniqueIndexes=new Map;for(let r of this._fields)this._fieldIndexes.set(r,new Map);for(let r of this._uniqueFields)if(this._uniqueIndexes.set(r,new Map),!this._fieldIndexes.has(r))this._fieldIndexes.set(r,new Map);this._compoundIndexes=new Map;for(let r of this._compoundFields)this._compoundIndexes.set(r.join("\x00"),{fields:r,map:new Map})}get indexedFields(){return this._indexedFields}buildFromData(t){for(let[,i]of this._fieldIndexes)i.clear();for(let[,i]of this._uniqueIndexes)i.clear();for(let[,i]of this._compoundIndexes)i.map.clear();for(let i of t)this._indexDoc(i)}add(t){this._checkUnique(t,null),this._indexDoc(t)}remove(t){for(let[i,r]of this._fieldIndexes){let s=t[i];if(s!==void 0){let n=r.get(s);if(n){if(n.delete(t),n.size===0)r.delete(s)}}}for(let[i,r]of this._uniqueIndexes){let s=t[i];if(s!==void 0)r.delete(s)}for(let[,i]of this._compoundIndexes){let r=Si(i.fields.map((n)=>t[n])),s=i.map.get(r);if(s){if(s.delete(t),s.size===0)i.map.delete(r)}}}update(t,i){this._checkUnique(i,t),this.remove(t);try{this._indexDoc(i)}catch(r){try{this._indexDoc(t)}catch{}throw r}}lookup(t,i){let r=this._fieldIndexes.get(t);if(!r)return null;let s=r.get(i);return s?[...s]:[]}_lookupIterable(t,i){let r=this._fieldIndexes.get(t);if(!r)return null;let s=r.get(i);return s?Kr(s):Fr}lookupCompound(t){let i=Object.keys(t).sort();for(let[,r]of this._compoundIndexes){let s=[...r.fields].sort();if(s.length!==i.length)continue;if(s.every((n,a)=>n===i[a])){let n=Si(r.fields.map((o)=>t[o])),a=r.map.get(n);return a?Kr(a):Fr}}return null}isUniqueTaken(t,i){let r=this._uniqueIndexes.get(t);if(!r)return!1;return r.has(i)}assertUniqueCandidates(t,i){if(this._uniqueFields.size===0)return;let r=new Set(t.map((s)=>s._id));for(let s of this._uniqueFields){let n=new Set,a=this._uniqueIndexes.get(s);if(a){for(let[c,l]of a.entries())if(!r.has(l._id))n.add(c)}let o=new Map;for(let c=0;c<i.length;c++){let l=i[c][s];if(l===void 0)continue;if(n.has(l))throw new De("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${s}" value "${l}" already exists`,{field:s,value:l});let d=o.get(l);if(d&&d!==t[c]._id)throw new De("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${s}" value "${l}" already exists`,{field:s,value:l});o.set(l,t[c]._id)}}}assertUniqueBatch(t){if(this._uniqueFields.size===0)return;for(let i of this._uniqueFields){let r=this._uniqueIndexes.get(i),s=new Set;for(let n of t){let a=n[i];if(a===void 0)continue;if(r&&r.has(a))throw new De("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${i}" value "${a}" already exists`,{field:i,value:a});if(s.has(a))throw new De("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: duplicate "${i}" value "${a}" within batch`,{field:i,value:a});s.add(a)}}}_validateFieldName(t){if(t.includes("."))throw new D("ERR_SKALEX_VALIDATION_INDEX_DOT_PATH",`Index fields cannot use dot-notation: "${t}". Use a flat field name.`,{field:t})}_indexDoc(t){for(let[i,r]of this._fieldIndexes){let s=t[i];if(s!==void 0){if(!r.has(s))r.set(s,new Set);r.get(s).add(t)}}for(let[i,r]of this._uniqueIndexes){let s=t[i];if(s!==void 0)r.set(s,t)}for(let[,i]of this._compoundIndexes){for(let s of i.fields){let n=t[s];if(n!==void 0&&n!==null&&typeof n==="object")throw new D("ERR_SKALEX_VALIDATION_COMPOUND_INDEX",`Compound index field "${s}" must be a scalar value (string, number, or boolean), got ${Array.isArray(n)?"array":typeof n}`,{field:s})}let r=Si(i.fields.map((s)=>t[s]));if(!i.map.has(r))i.map.set(r,new Set);i.map.get(r).add(t)}}_checkUnique(t,i){for(let r of this._uniqueFields){let s=t[r];if(s===void 0)continue;let n=this._uniqueIndexes.get(r);if(!n)continue;let a=n.get(s);if(a&&a._id!==i?._id)throw new De("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${r}" value "${s}" already exists`,{field:r,value:s})}}}var jt="_flush",qt="migrations";class Ks{constructor({adapter:t,serializer:i,deserializer:r,logger:s,debug:n=!1,lenientLoad:a=!1}){this._adapter=t,this._serializer=i,this._deserializer=r,this._logger=s,this._debug=n,this._lenientLoad=a,this._saveLock=Promise.resolve()}_withSaveLock(t){let i=this._saveLock.then(t);return this._saveLock=i.catch(()=>{}),i}async loadAll(t,{parseSchema:i,buildIndex:r,IndexEngine:s}){try{let n=await this._adapter.list();await Promise.all(n.map(async(a)=>{try{let o=await this._adapter.read(a);if(!o)return;let c=this._deserializer(o),{collectionName:l,data:d}=c;if(!l)return;let u=t[l],f=u?.rawSchema??c.rawSchema??null,h=u?.schema??(f?i(f):null),_=u?.changelog??c.changelog??!1,p=u?.softDelete??c.softDelete??!1,g=u?.versioning??c.versioning??!1,m=u?.strict??c.strict??!1,w=u?.onSchemaError??c.onSchemaError??"throw",v=u?.defaultTtl??c.defaultTtl??null,q=u?.defaultEmbed??c.defaultEmbed??null,E=u?.maxDocs??c.maxDocs??null,A=u?u.fieldIndex:null;if(!A&&h?.uniqueFields?.length)A=new s([],h.uniqueFields);let tt=r(d,"_id");if(A)A.buildFromData(d);t[l]={collectionName:l,data:d,index:tt,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:h,rawSchema:f,fieldIndex:A,changelog:_,softDelete:p,versioning:g,strict:m,onSchemaError:w,defaultTtl:v,defaultEmbed:q,maxDocs:E}}catch(o){if(o.code==="ENOENT")return;if(this._lenientLoad){this._logger(`WARNING: Could not load collection "${a}": ${o.message}. Collection will be empty.`,"error");return}throw new Ve("ERR_SKALEX_PERSISTENCE_CORRUPT",`Failed to load collection "${a}": ${o.message}`,{collection:a})}})),this._detectIncompleteFlush(t),await this._cleanOrphanTempFiles()}catch(n){if(n.code!=="ENOENT")throw this._logger(`Error loading data: ${n}`,"error"),n}}async save(t,i){if(i)await this._saveOne(t,i);else await Promise.all(Object.keys(t).map((r)=>this._saveOne(t,r)))}async saveDirty(t){let i=Object.keys(t).filter((r)=>t[r]._dirty);if(i.length===0)return;await Promise.all(i.map((r)=>this._saveOne(t,r)))}saveAtomic(t,i){return this._withSaveLock(async()=>{if(i.length===0)return;this._writeFlushSentinel(t,i);let r=new Set(i);r.add("_meta");let s=[...r].filter((n)=>t[n]).map((n)=>({name:n,data:this._serializeCollection(t[n])}));try{await this._adapter.writeAll(s)}catch(n){throw new Ve("ERR_SKALEX_PERSISTENCE_FLUSH_FAILED",`Batch save failed during writeAll: ${n.message}`,{collections:i})}for(let n of i)if(t[n])t[n]._dirty=!1;try{this._clearFlushSentinel(t),await this._adapter.write("_meta",this._serializeCollection(t._meta))}catch(n){this._logger(`WARNING: Batch data committed but sentinel clear failed: ${n.message}. Next load will report an incomplete flush (false positive).`,"error")}})}markDirty(t,i){let r=t[i];if(r)r._dirty=!0}_serializeCollection(t){let i={collectionName:t.collectionName,data:t.data};if(t.rawSchema)i.rawSchema=t.rawSchema;if(t.changelog)i.changelog=t.changelog;if(t.softDelete)i.softDelete=t.softDelete;if(t.versioning)i.versioning=t.versioning;if(t.strict)i.strict=t.strict;if(t.onSchemaError!=="throw")i.onSchemaError=t.onSchemaError;if(t.defaultTtl)i.defaultTtl=t.defaultTtl;if(t.defaultEmbed)i.defaultEmbed=t.defaultEmbed;if(t.maxDocs)i.maxDocs=t.maxDocs;return this._serializer(i)}async _saveOne(t,i){let r=t[i];if(!r)return;if(r.isSaving)return r._pendingSave=!0,new Promise((s,n)=>{(r._saveWaiters??=[]).push({resolve:s,reject:n})});r.isSaving=!0,r._pendingSave=!1;try{await this._writeCollection(i,r);while(r._pendingSave)r._pendingSave=!1,await this._writeCollection(i,r);this._resolveSaveWaiters(r)}catch(s){throw this._rejectSaveWaiters(r,s),s}finally{r.isSaving=!1}}async _writeCollection(t,i){try{await this._adapter.write(t,this._serializeCollection(i)),i._dirty=!1}catch(r){throw this._logger(`Error saving "${t}": ${r.message}`,"error"),r}}_resolveSaveWaiters(t){let i=t._saveWaiters?.splice(0)??[];for(let r of i)r.resolve()}_rejectSaveWaiters(t,i){let r=t._saveWaiters?.splice(0)??[];for(let s of r)s.reject(i)}_writeFlushSentinel(t,i){let r=this._getOrCreateMeta(t);r[jt]={startedAt:new Date().toISOString(),collections:i,completedAt:null}}_clearFlushSentinel(t){let i=this._getOrCreateMeta(t);if(i[jt])i[jt].completedAt=new Date().toISOString()}_detectIncompleteFlush(t){let i=t._meta;if(!i)return;let r=i.index.get(qt);if(!r)return;let s=r[jt];if(!s)return;if(s.startedAt&&!s.completedAt)this._logger(`WARNING: Incomplete flush detected (started ${s.startedAt}, collections: ${s.collections?.join(", ")}). Data may be inconsistent.`,"error")}async _cleanOrphanTempFiles(){if(typeof this._adapter.join!=="function")return;if(typeof this._adapter.list!=="function")return;try{let t=await import("fs"),i=await import("path"),r=this._adapter.dir;if(!r)return;let s=(await t.default.promises.readdir(r)).filter((n)=>n.includes(".tmp."));for(let n of s){let a=i.default.join(r,n);try{await t.default.promises.unlink(a),this._log(`Cleaned orphan temp file: ${n}`)}catch{}}}catch{}}_getOrCreateMeta(t){if(!t._meta)t._meta={collectionName:"_meta",data:[],index:new Map,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:null,rawSchema:null,fieldIndex:null,changelog:!1,softDelete:!1,versioning:!1,strict:!1,onSchemaError:"throw",defaultTtl:null,defaultEmbed:null,maxDocs:null};let i=t._meta,r=i.index.get(qt);if(!r)r={_id:qt},i.data.push(r),i.index.set(qt,r);return r}_log(t){if(this._debug)this._logger(t,"info")}}var Ho=0;class zs{constructor(){this._txLock=Promise.resolve(),this._ctx=null,this._abortedIds=new Set}get active(){return this._ctx!==null&&!this._ctx.aborted}get context(){return this._ctx}async run(t,i,{timeout:r=0}={}){let s=async()=>{await i._ensureConnected();let a=new Set(Object.keys(i.collections)),o={id:++Ho,startedAt:Date.now(),aborted:!1,preExisting:a,touchedCollections:new Set,snapshots:new Map,deferredEffects:[],timeout:r};this._ctx=o;let c=null,l=r>0?new Promise((f,h)=>{c=setTimeout(()=>{o.aborted=!0,h(new Ce("ERR_SKALEX_TX_TIMEOUT",`Transaction ${o.id} timed out after ${r}ms`))},r)}):null,d=this,u=new Proxy(i,{get(f,h){if(h==="_txId")return o.id;if(o!==d._ctx)throw new Ce("ERR_SKALEX_TX_STALE_PROXY",`Transaction ${o.id} has ended. This proxy is no longer usable.`);if(h==="collections")throw new Ce("ERR_SKALEX_TX_DIRECT_ACCESS","Direct access to db.collections inside transaction() is not covered by rollback. Use the collection API (db.useCollection) instead.");if(h==="useCollection")return(p)=>{let g=f.useCollection(p);return g._activeTxId=o.id,g};let _=Reflect.get(f,h);return typeof _==="function"?_.bind(f):_}});try{let f=t(u),h=l?await Promise.race([f,l]):await f;if(o.aborted)throw new Ce("ERR_SKALEX_TX_ABORTED",`Transaction ${o.id} was aborted`);let _=[...o.touchedCollections];if(_.length>0)await i._persistence.saveAtomic(i.collections,_);for(let p of o.deferredEffects)await p();return h}catch(f){for(let[h,_]of o.snapshots)if(o.preExisting.has(h)){if(i._applySnapshot(h,_),i.collections[h])i.collections[h]._dirty=_._dirty}for(let h in i.collections)if(!o.preExisting.has(h))delete i.collections[h],delete i._collectionInstances[h];throw f}finally{if(c)clearTimeout(c);if(o.aborted)this._abortedIds.add(o.id);this._ctx=null;for(let f in i._collectionInstances){let h=i._collectionInstances[f];if(h._createdInTxId===o.id)h._createdInTxId=null;if(h._activeTxId===o.id)h._activeTxId=null}}},n=this._txLock.then(s);return this._txLock=n.catch(()=>{}),n}snapshotIfNeeded(t,i,r){let s=this._ctx;if(!s)return;if(this._assertCtxNotAborted(s),!s.snapshots.has(t)){let n=r(i);n._dirty=i._dirty??!1,s.snapshots.set(t,n)}s.touchedCollections.add(t)}assertNotAborted(){let t=this._ctx;if(t)this._assertCtxNotAborted(t)}_assertCtxNotAborted(t){if(t.aborted)throw new Ce("ERR_SKALEX_TX_ABORTED",`Transaction ${t.id} was aborted. No further mutations allowed.`)}defer(t){if(this._ctx)return this._ctx.deferredEffects.push(t),!0;return!1}}class Bs{constructor(t){this._CollectionClass=t,this.stores={},this._instances={}}get(t,i){if(this._instances[t])return this._instances[t];if(!this.stores[t])this.createStore(t);let r=new this._CollectionClass(this.stores[t],i);return this._instances[t]=r,r}create(t,i={},r){this.createStore(t,i);let s=new this._CollectionClass(this.stores[t],r);return this._instances[t]=s,s}createStore(t,{schema:i,indexes:r=[],changelog:s=!1,softDelete:n=!1,versioning:a=!1,strict:o=!1,onSchemaError:c="throw",defaultTtl:l=null,defaultEmbed:d=null,maxDocs:u=null}={}){let f=null,h=null;if(i){f=Ls(i);let _=f.uniqueFields;if(r.length||_.length)h=new Yt(r,_)}else if(r.length)h=new Yt(r,[]);this.stores[t]={collectionName:t,data:[],index:new Map,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:f,rawSchema:i||null,fieldIndex:h,changelog:s,softDelete:n,versioning:a,strict:o,onSchemaError:c,defaultTtl:l,defaultEmbed:d,maxDocs:u}}rename(t,i){if(!this.stores[t])throw new Ve("ERR_SKALEX_PERSISTENCE_COLLECTION_NOT_FOUND",`Collection "${t}" not found`,{collection:t});if(this.stores[i])throw new Ve("ERR_SKALEX_PERSISTENCE_COLLECTION_EXISTS",`Collection "${i}" already exists`,{collection:i});let r=this.stores[t];if(r.collectionName=i,this.stores[i]=r,delete this.stores[t],this._instances[t]){let s=this._instances[t];s.name=i,this._instances[i]=s,delete this._instances[t]}}buildIndex(t,i){let r=new Map;for(let s of t)r.set(s[i],s);return r}inspect(t){if(t){let r=this.stores[t];if(!r)return null;return{name:t,count:r.data.length,schema:r.schema?Object.fromEntries(r.schema.fields):null,indexes:r.fieldIndex?[...r.fieldIndex.indexedFields]:[],softDelete:r.softDelete??!1,versioning:r.versioning??!1,strict:r.strict??!1,onSchemaError:r.onSchemaError??"throw",maxDocs:r.maxDocs??null}}let i={};for(let r in this.stores)i[r]=this.inspect(r);return i}dump(){let t={};for(let i in this.stores)if(!i.startsWith("_"))t[i]=structuredClone(this.stores[i].data);return t}schema(t){let i=this.stores[t];if(!i)return null;if(i.schema)return Object.fromEntries([...i.schema.fields.entries()].map(([r,s])=>[r,s.type]));if(i.data.length>0)return qo(i.data[0]);return null}stats(t){let i=(r)=>{let s=this.stores[r];if(!s)return null;let n=s.data.length,a=0;for(let o of s.data)try{a+=JSON.stringify(o).length}catch(c){}return{collection:r,count:n,estimatedSize:a,avgDocSize:n>0?Math.round(a/n):0}};if(t)return i(t);return Object.keys(this.stores).map(i)}clear(){this.stores={},this._instances={}}}class Ki{async embed(t){throw Error("EmbeddingAdapter.embed() not implemented")}}var ye=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class Xs extends Ki{constructor({apiKey:t=ye("OPENAI_API_KEY"),model:i=ye("OPENAI_EMBED_MODEL")??"text-embedding-3-small",baseUrl:r=ye("OPENAI_EMBED_BASE_URL")??"https://api.openai.com/v1/embeddings",dimensions:s=ye("OPENAI_EMBED_DIMENSIONS")!=null?Number(ye("OPENAI_EMBED_DIMENSIONS")):void 0,organization:n=ye("OPENAI_ORGANIZATION")??void 0,timeout:a=ye("OPENAI_EMBED_TIMEOUT")!=null?Number(ye("OPENAI_EMBED_TIMEOUT")):void 0,retries:o=Number(ye("OPENAI_EMBED_RETRIES")??0),retryDelay:c=Number(ye("OPENAI_EMBED_RETRY_DELAY")??1000),headers:l={},fetch:d=globalThis.fetch}={}){super();if(!t)throw Error("OpenAIEmbeddingAdapter requires an apiKey");this.apiKey=t,this.model=i,this.baseUrl=r,this.dimensions=s,this.organization=n,this.timeout=a,this.retries=o,this.retryDelay=c,this.headers=l,this._fetch=d}async embed(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,...this.organization&&{"OpenAI-Organization":this.organization},...this.headers},body:JSON.stringify({input:t,model:this.model,...this.dimensions!==void 0&&{dimensions:this.dimensions}}),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`OpenAI embedding API error ${a.status}: ${o}`)}return(await a.json()).data[0].embedding}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}var mt=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class Vs extends Ki{constructor({model:t=mt("OLLAMA_EMBED_MODEL")??"nomic-embed-text",host:i=mt("OLLAMA_HOST")??"http://localhost:11434",timeout:r=mt("OLLAMA_EMBED_TIMEOUT")!=null?Number(mt("OLLAMA_EMBED_TIMEOUT")):void 0,retries:s=Number(mt("OLLAMA_EMBED_RETRIES")??0),retryDelay:n=Number(mt("OLLAMA_EMBED_RETRY_DELAY")??1000),headers:a={},fetch:o=globalThis.fetch}={}){super();this.model=t,this.host=i,this.timeout=r,this.retries=s,this.retryDelay=n,this.headers=a,this._fetch=o}async embed(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(`${this.host}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json",...this.headers},body:JSON.stringify({model:this.model,prompt:t}),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`Ollama embedding API error ${a.status}: ${o}`)}return(await a.json()).embedding}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}class ii{async generate(t,i){throw Error("LLMAdapter.generate() not implemented")}async summarize(t){throw Error("LLMAdapter.summarize() not implemented")}}var zi=`You are a database query assistant. Convert the user's natural language request into a JSON filter object for a document database.
|
|
5
5
|
|
|
6
6
|
Rules:
|
|
7
7
|
- Return ONLY a valid JSON object, nothing else
|
|
@@ -10,24 +10,24 @@ Rules:
|
|
|
10
10
|
- For numeric comparisons use operators: {"age": {"$gt": 18}}
|
|
11
11
|
- For text search use $regex: {"name": {"$regex": "pattern"}}
|
|
12
12
|
- Return {} to match all documents
|
|
13
|
-
- No explanations, no markdown, no code fences`,
|
|
14
|
-
Schema: ${JSON.stringify(t)}`},{role:"user",content:i}],response_format:{type:"json_object"},temperature:0,...this.maxTokens!==void 0&&{max_tokens:this.maxTokens},...this.seed!==void 0&&{seed:this.seed}});return JSON.parse(r.choices[0].message.content)}async summarize(t){return(await this._post({model:this.model,messages:[{role:"system",content:this.summarizePrompt},{role:"user",content:t}],temperature:this.temperature,...this.maxTokens!==void 0&&{max_tokens:this.maxTokens},...this.topP!==void 0&&{top_p:this.topP},...this.seed!==void 0&&{seed:this.seed}})).choices[0].message.content.trim()}async _post(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,...this.organization&&{"OpenAI-Organization":this.organization},...this.headers},body:JSON.stringify(t),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`OpenAI API error ${a.status}: ${o}`)}return a.json()}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}var ae=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class
|
|
15
|
-
Schema: ${JSON.stringify(t)}`,messages:[{role:"user",content:i}]})).content[0].text.trim().replace(/^```(?:json)?\n?/,"").replace(/\n?```$/,"");return JSON.parse(r)}async summarize(t){return(await this._post({model:this.model,max_tokens:this.maxTokens,temperature:this.temperature,...this.topP!==void 0&&{top_p:this.topP},...this.topK!==void 0&&{top_k:this.topK},system:this.summarizePrompt,messages:[{role:"user",content:t}]})).content[0].text.trim()}async _post(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.apiKey,"anthropic-version":this.apiVersion,...this.headers},body:JSON.stringify(t),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`Anthropic API error ${a.status}: ${o}`)}return a.json()}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}var
|
|
13
|
+
- No explanations, no markdown, no code fences`,Bi="Summarise the following memory entries into one concise paragraph. Preserve all important facts.",U=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class Gs extends ii{constructor({apiKey:t=U("OPENAI_API_KEY"),model:i=U("OPENAI_MODEL")??"gpt-4o-mini",baseUrl:r=U("OPENAI_BASE_URL")??"https://api.openai.com/v1/chat/completions",maxTokens:s=U("OPENAI_MAX_TOKENS")!=null?Number(U("OPENAI_MAX_TOKENS")):void 0,temperature:n=Number(U("OPENAI_TEMPERATURE")??0.3),topP:a=U("OPENAI_TOP_P")!=null?Number(U("OPENAI_TOP_P")):void 0,organization:o=U("OPENAI_ORGANIZATION")??void 0,timeout:c=U("OPENAI_TIMEOUT")!=null?Number(U("OPENAI_TIMEOUT")):void 0,retries:l=Number(U("OPENAI_RETRIES")??0),retryDelay:d=Number(U("OPENAI_RETRY_DELAY")??1000),headers:u={},fetch:f=globalThis.fetch,seed:h=U("OPENAI_SEED")!=null?Number(U("OPENAI_SEED")):void 0,generatePrompt:_=zi,summarizePrompt:p=Bi}={}){super();if(!t)throw Error("OpenAILLMAdapter requires an apiKey");this.apiKey=t,this.model=i,this.baseUrl=r,this.maxTokens=s,this.temperature=n,this.topP=a,this.organization=o,this.timeout=c,this.retries=l,this.retryDelay=d,this.headers=u,this._fetch=f,this.seed=h,this.generatePrompt=_,this.summarizePrompt=p}async generate(t,i){let r=await this._post({model:this.model,messages:[{role:"system",content:`${this.generatePrompt}
|
|
14
|
+
Schema: ${JSON.stringify(t)}`},{role:"user",content:i}],response_format:{type:"json_object"},temperature:0,...this.maxTokens!==void 0&&{max_tokens:this.maxTokens},...this.seed!==void 0&&{seed:this.seed}});return JSON.parse(r.choices[0].message.content)}async summarize(t){return(await this._post({model:this.model,messages:[{role:"system",content:this.summarizePrompt},{role:"user",content:t}],temperature:this.temperature,...this.maxTokens!==void 0&&{max_tokens:this.maxTokens},...this.topP!==void 0&&{top_p:this.topP},...this.seed!==void 0&&{seed:this.seed}})).choices[0].message.content.trim()}async _post(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,...this.organization&&{"OpenAI-Organization":this.organization},...this.headers},body:JSON.stringify(t),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`OpenAI API error ${a.status}: ${o}`)}return a.json()}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}var ae=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class Hs extends ii{constructor({apiKey:t=ae("ANTHROPIC_API_KEY"),model:i=ae("ANTHROPIC_MODEL")??"claude-haiku-4-5",baseUrl:r=ae("ANTHROPIC_BASE_URL")??"https://api.anthropic.com/v1/messages",apiVersion:s="2023-06-01",maxTokens:n=Number(ae("ANTHROPIC_MAX_TOKENS")??1024),temperature:a=Number(ae("ANTHROPIC_TEMPERATURE")??0.3),topP:o=ae("ANTHROPIC_TOP_P")!=null?Number(ae("ANTHROPIC_TOP_P")):void 0,topK:c=ae("ANTHROPIC_TOP_K")!=null?Number(ae("ANTHROPIC_TOP_K")):void 0,timeout:l=ae("ANTHROPIC_TIMEOUT")!=null?Number(ae("ANTHROPIC_TIMEOUT")):void 0,retries:d=Number(ae("ANTHROPIC_RETRIES")??0),retryDelay:u=Number(ae("ANTHROPIC_RETRY_DELAY")??1000),headers:f={},fetch:h=globalThis.fetch,generatePrompt:_=zi,summarizePrompt:p=Bi}={}){super();if(!t)throw Error("AnthropicLLMAdapter requires an apiKey");this.apiKey=t,this.model=i,this.baseUrl=r,this.apiVersion=s,this.maxTokens=n,this.temperature=a,this.topP=o,this.topK=c,this.timeout=l,this.retries=d,this.retryDelay=u,this.headers=f,this._fetch=h,this.generatePrompt=_,this.summarizePrompt=p}async generate(t,i){let r=(await this._post({model:this.model,max_tokens:this.maxTokens,temperature:0,system:`${this.generatePrompt}
|
|
15
|
+
Schema: ${JSON.stringify(t)}`,messages:[{role:"user",content:i}]})).content[0].text.trim().replace(/^```(?:json)?\n?/,"").replace(/\n?```$/,"");return JSON.parse(r)}async summarize(t){return(await this._post({model:this.model,max_tokens:this.maxTokens,temperature:this.temperature,...this.topP!==void 0&&{top_p:this.topP},...this.topK!==void 0&&{top_k:this.topK},system:this.summarizePrompt,messages:[{role:"user",content:t}]})).content[0].text.trim()}async _post(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.apiKey,"anthropic-version":this.apiVersion,...this.headers},body:JSON.stringify(t),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`Anthropic API error ${a.status}: ${o}`)}return a.json()}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}var _e=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class Ws extends ii{constructor({model:t=_e("OLLAMA_MODEL")??"llama3.2",host:i=_e("OLLAMA_HOST")??"http://localhost:11434",temperature:r=Number(_e("OLLAMA_TEMPERATURE")??0.3),topP:s=_e("OLLAMA_TOP_P")!=null?Number(_e("OLLAMA_TOP_P")):void 0,topK:n=_e("OLLAMA_TOP_K")!=null?Number(_e("OLLAMA_TOP_K")):void 0,timeout:a=_e("OLLAMA_TIMEOUT")!=null?Number(_e("OLLAMA_TIMEOUT")):void 0,retries:o=Number(_e("OLLAMA_RETRIES")??0),retryDelay:c=Number(_e("OLLAMA_RETRY_DELAY")??1000),headers:l={},fetch:d=globalThis.fetch,generatePrompt:u=zi,summarizePrompt:f=Bi}={}){super();this.model=t,this.host=i,this.temperature=r,this.topP=s,this.topK=n,this.timeout=a,this.retries=o,this.retryDelay=c,this.headers=l,this._fetch=d,this.generatePrompt=u,this.summarizePrompt=f}async generate(t,i){let r=`${this.generatePrompt}
|
|
16
16
|
Schema: ${JSON.stringify(t)}
|
|
17
17
|
Query: ${i}`,s=await this._post({model:this.model,prompt:r,format:"json",options:{temperature:0},stream:!1});return JSON.parse(s.response)}async summarize(t){return(await this._post({model:this.model,prompt:`${this.summarizePrompt}
|
|
18
18
|
|
|
19
|
-
${t}`,options:{temperature:this.temperature,...this.topP!==void 0&&{top_p:this.topP},...this.topK!==void 0&&{top_k:this.topK}},stream:!1})).response.trim()}async _post(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(`${this.host}/api/generate`,{method:"POST",headers:{"Content-Type":"application/json",...this.headers},body:JSON.stringify(t),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`Ollama API error ${a.status}: ${o}`)}return a.json()}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}function
|
|
19
|
+
${t}`,options:{temperature:this.temperature,...this.topP!==void 0&&{top_p:this.topP},...this.topK!==void 0&&{top_k:this.topK}},stream:!1})).response.trim()}async _post(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(`${this.host}/api/generate`,{method:"POST",headers:{"Content-Type":"application/json",...this.headers},body:JSON.stringify(t),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`Ollama API error ${a.status}: ${o}`)}return a.json()}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}function Wo({provider:t,apiKey:i,embedModel:r,model:s,host:n,embedBaseUrl:a,dimensions:o,organization:c,embedTimeout:l,embedRetries:d,embedRetryDelay:u}){let f=r||s;switch(t){case"openai":return new Xs({apiKey:i,model:f,baseUrl:a,...o!==void 0&&{dimensions:o},...c!==void 0&&{organization:c},...l!==void 0&&{timeout:l},...d!==void 0&&{retries:d},...u!==void 0&&{retryDelay:u}});case"ollama":return new Vs({model:f,host:n,...l!==void 0&&{timeout:l},...d!==void 0&&{retries:d},...u!==void 0&&{retryDelay:u}});default:throw new be("ERR_SKALEX_ADAPTER_UNKNOWN_PROVIDER",`Unknown AI provider: "${t}". Supported: "openai", "ollama".`,{provider:t})}}function Jo({provider:t,apiKey:i,model:r,host:s,baseUrl:n,apiVersion:a,temperature:o,maxTokens:c,topP:l,topK:d,organization:u,timeout:f,retries:h,retryDelay:_,seed:p,generatePrompt:g,summarizePrompt:m}){if(!r)return null;switch(t){case"openai":return new Gs({apiKey:i,model:r,baseUrl:n,...c!==void 0&&{maxTokens:c},...o!==void 0&&{temperature:o},...l!==void 0&&{topP:l},...u!==void 0&&{organization:u},...f!==void 0&&{timeout:f},...h!==void 0&&{retries:h},..._!==void 0&&{retryDelay:_},...p!==void 0&&{seed:p},...g!==void 0&&{generatePrompt:g},...m!==void 0&&{summarizePrompt:m}});case"anthropic":return new Hs({apiKey:i,model:r,baseUrl:n,apiVersion:a,...c!==void 0&&{maxTokens:c},...o!==void 0&&{temperature:o},...l!==void 0&&{topP:l},...d!==void 0&&{topK:d},...f!==void 0&&{timeout:f},...h!==void 0&&{retries:h},..._!==void 0&&{retryDelay:_},...g!==void 0&&{generatePrompt:g},...m!==void 0&&{summarizePrompt:m}});case"ollama":return new Ws({model:r,host:s,...o!==void 0&&{temperature:o},...l!==void 0&&{topP:l},...d!==void 0&&{topK:d},...f!==void 0&&{timeout:f},...h!==void 0&&{retries:h},..._!==void 0&&{retryDelay:_},...g!==void 0&&{generatePrompt:g},...m!==void 0&&{summarizePrompt:m}});default:return null}}var Ii="AES-GCM",$t=12,Le=32,Yo=new TextEncoder,Qo=new TextDecoder;class Js extends Fi{constructor(t,i){super();if(this._adapter=t,this._rawKey=typeof i==="string"?Zo(i):Uint8Array.from(i),this._rawKey.length!==Le)throw new be("ERR_SKALEX_ADAPTER_INVALID_KEY",`EncryptedAdapter: key must be ${Le} bytes (${Le*2} hex chars), got ${this._rawKey.length}`);this._cryptoKey=null}async read(t){let i=await this._adapter.read(t);if(!i)return null;return this._decrypt(i)}async write(t,i){return this._adapter.write(t,await this._encrypt(i))}async delete(t){return this._adapter.delete(t)}async list(){return this._adapter.list()}async writeAll(t){let i=[];for(let{name:r,data:s}of t)i.push({name:r,data:await this._encrypt(s)});return this._adapter.writeAll(i)}join(...t){return this._adapter.join?.(...t)}ensureDir(t){return this._adapter.ensureDir?.(t)}async writeRaw(t,i){return this._adapter.writeRaw?.(t,await this._encrypt(i))}async readRaw(t){let i=await this._adapter.readRaw?.(t);if(!i)return null;return this._decrypt(i)}async _getKey(){if(!this._cryptoKey)this._cryptoKey=await globalThis.crypto.subtle.importKey("raw",this._rawKey,{name:Ii},!1,["encrypt","decrypt"]);return this._cryptoKey}async _encrypt(t){let i=await this._getKey(),r=globalThis.crypto.getRandomValues(new Uint8Array($t)),s=Yo.encode(t),n=await globalThis.crypto.subtle.encrypt({name:Ii,iv:r,tagLength:128},i,s),a=new Uint8Array($t+n.byteLength);return a.set(r,0),a.set(new Uint8Array(n),$t),el(a)}async _decrypt(t){let i=await this._getKey(),r=tl(t),s=r.slice(0,$t),n=r.slice($t),a=await globalThis.crypto.subtle.decrypt({name:Ii,iv:s,tagLength:128},i,n);return Qo.decode(a)}}function Zo(t){if(t.length!==Le*2)throw new be("ERR_SKALEX_ADAPTER_INVALID_KEY",`EncryptedAdapter: hex key must be ${Le*2} characters (${Le} bytes)`);if(!/^[0-9a-fA-F]+$/.test(t))throw new be("ERR_SKALEX_ADAPTER_INVALID_KEY","EncryptedAdapter: hex key contains invalid characters");let i=new Uint8Array(Le);for(let r=0;r<Le;r++)i[r]=parseInt(t.slice(r*2,r*2+2),16);return i}function el(t){let i="";for(let r=0;r<t.length;r++)i+=String.fromCharCode(t[r]);return globalThis.btoa(i)}function tl(t){let i=globalThis.atob(t),r=new Uint8Array(i.length);for(let s=0;s<i.length;s++)r[s]=i.charCodeAt(s);return r}var il=4;class Ys{constructor(t,i){this.sessionId=t,this._db=i,this._col=i.useCollection(`_memory_${t}`)}async remember(t){let i=await this._col.insertOne({text:t,sessionId:this.sessionId},{embed:"text"}),r=this._db._memoryConfig?.maxEntries;if(r&&this._col._data.length>r)await this.compress({threshold:0});return i}async recall(t,{limit:i=10,minScore:r=0}={}){return this._col.search(t,{limit:i,minScore:r})}async history({since:t,limit:i}={}){let r=t?{createdAt:{$gte:new Date(t)}}:{},s={sort:{createdAt:1}};if(i)s.limit=i;let{docs:n}=await this._col.find(r,s);return n}async forget(t){return this._col.deleteOne({_id:t})}tokenCount(){let t=this._col._data;return{tokens:t.reduce((i,r)=>i+this._docTokens(r),0),count:t.length}}context({tokens:t=this._db._memoryConfig?.contextTokens??4000}={}){let i=this._sortedData("desc"),r=[],s=0;for(let n of i){let a=this._docTokens(n);if(s+a>t)break;r.push(n.text),s+=a}return r.reverse().join(`
|
|
20
20
|
`)}async compress({threshold:t=this._db._memoryConfig?.compressionThreshold??8000,keepRecent:i=this._db._memoryConfig?.keepRecent??10}={}){let{tokens:r}=this.tokenCount();if(r<=t)return;if(!this._db._aiAdapter)throw Error('memory.compress() requires a language model adapter. Configure { ai: { model: "..." } }.');let s=this._sortedData("asc"),n=Math.max(0,s.length-i),a=s.slice(0,n);if(a.length===0)return;let o=a.map((l)=>l.text).join(`
|
|
21
|
-
`),c=await this._db._aiAdapter.summarize(o);await this._col.deleteMany({_id:{$in:a.map((l)=>l._id)}}),await this._col.insertOne({text:c,sessionId:this.sessionId,compressed:!0})}_docTokens(t){return Math.ceil((t.text||"").length/tl)}_sortedData(t){return[...this._col._data].sort(t==="asc"?(i,r)=>new Date(i.createdAt)-new Date(r.createdAt):(i,r)=>new Date(r.createdAt)-new Date(i.createdAt))}}class Ys{constructor(t){this._db=t,this._restoring=!1}get _col(){return this._db.useCollection("_changelog")}async log(t,i,r,s=null,n=null){if(this._restoring)return;let a={op:t,collection:i,docId:r._id,doc:{...r},timestamp:new Date};if(s)a.prev={...s};if(n)a.session=n;await this._col.insertOne(a)}async query(t,{since:i,limit:r,session:s}={}){let n={collection:t};if(i)n.timestamp={$gte:new Date(i)};if(s)n.session=s;let a={sort:{timestamp:1}};if(r)a.limit=r;let{docs:o}=await this._col.find(n,a);return o}async restore(t,i,{_id:r}={}){let s=new Date(i),n=this._db.useCollection(t),a=(await this.query(t,{})).filter((c)=>new Date(c.timestamp)<=s);if(r){let c=a.filter((d)=>d.docId===r);if(c.length===0)return;let l=c[c.length-1];this._restoring=!0;try{if(l.op==="delete"){if(await n.findOne({_id:r}))await n.deleteOne({_id:r});return}if(await n.findOne({_id:r})){let{_id:d,createdAt:u,updatedAt:f,...h}=l.doc;await n.updateOne({_id:r},h)}else await n.insertOne({...l.doc})}finally{this._restoring=!1}await this._db.saveData(t);return}let o=new Map;for(let c of a)if(c.op==="insert"||c.op==="update")o.set(c.docId,{doc:c.doc,deleted:!1});else if(c.op==="delete")o.set(c.docId,{doc:null,deleted:!0});this._restoring=!0;try{await n.deleteMany({});for(let[,{doc:c,deleted:l}]of o)if(!l&&c)await n.insertOne({...c})}finally{this._restoring=!1}await this._db.saveData(t)}}function il(t){let i=5381;for(let r=0;r<t.length;r++)i=(i<<5)+i+t.charCodeAt(r)|0;return(i>>>0).toString(16).padStart(8,"0")}class Qs{constructor({maxSize:t=500,ttl:i=0}={}){this._cache=new Map,this._maxSize=t,this._ttl=i}_key(t,i,r){return il(JSON.stringify({collectionName:t,schema:i,query:r}))}get(t,i,r){let s=this._key(t,i,r),n=this._cache.get(s);if(!n)return;if(this._ttl>0&&Date.now()-n.ts>this._ttl){this._cache.delete(s);return}return n.filter}set(t,i,r,s){let n=this._key(t,i,r);if(this._cache.size>=this._maxSize&&!this._cache.has(n))this._cache.delete(this._cache.keys().next().value);this._cache.set(n,{filter:s,ts:Date.now()})}toJSON(){return Object.fromEntries([...this._cache.entries()].map(([t,i])=>[t,i]))}fromJSON(t){if(!t||typeof t!=="object")return;for(let[i,r]of Object.entries(t))this._cache.set(i,r)}get size(){return this._cache.size}}function rl(t,{regexMaxLength:i=500}={}){if(typeof t!=="object"||t===null)return t;let r={};for(let s of Object.keys(t)){let n=t[s];if(n&&typeof n==="object"&&!Array.isArray(n)){let a={};for(let o of Object.keys(n))if(o==="$regex"&&typeof n.$regex==="string"){if(n.$regex.length>i)throw Error(`$regex pattern too long (max ${i} characters)`);if(/\([^)]*[+*][^)]*\)[+*{]/.test(n.$regex))throw Error("$regex pattern rejected: nested quantifiers risk ReDoS");try{a.$regex=new RegExp(n.$regex)}catch{throw Error(`invalid $regex pattern: "${n.$regex}"`)}}else if(["$gt","$gte","$lt","$lte"].includes(o)&&sl(n[o]))a[o]=new Date(n[o]);else a[o]=n[o];r[s]=a}else r[s]=n}return r}function sl(t){if(typeof t!=="string")return!1;return/\d{4}-\d{2}-\d{2}/.test(t)&&!isNaN(Date.parse(t))}function nl(t,i){let r=[];if(!i||typeof t!=="object"||t===null)return r;for(let s of Object.keys(t)){if(s.startsWith("$"))continue;if(!(s.split(".")[0]in i))r.push(`Unknown field referenced in generated filter: "${s}"`)}return r}class Zs{constructor(){this._listeners=new Map}on(t,i){if(!this._listeners.has(t))this._listeners.set(t,new Set);return this._listeners.get(t).add(i),()=>this._listeners.get(t)?.delete(i)}off(t,i){this._listeners.get(t)?.delete(i)}emit(t,i){for(let r of[t,"*"]){let s=this._listeners.get(r);if(!s)continue;for(let n of s)try{n(i)}catch(a){}}}removeAll(t){if(t)this._listeners.delete(t);else this._listeners.clear()}listenerCount(t){return this._listeners.get(t)?.size??0}}class en{constructor({threshold:t=100,maxEntries:i=500}={}){this._threshold=t,this._maxEntries=i,this._entries=[]}record({collection:t,op:i,filter:r,query:s,duration:n,resultCount:a}){if(n<this._threshold)return;let o={collection:t,op:i,duration:n,resultCount:a,timestamp:new Date};if(r!==void 0)o.filter=r;if(s!==void 0)o.query=s;if(this._entries.push(o),this._entries.length>this._maxEntries)this._entries.shift()}entries({limit:t,minDuration:i,collection:r}={}){let s=this._entries;if(r)s=s.filter((n)=>n.collection===r);if(i)s=s.filter((n)=>n.duration>=i);if(t)s=s.slice(-t);return s}get size(){return this._entries.length}clear(){this._entries=[]}}class tn{constructor(){this._sessions=new Map}_ensure(t){if(!this._sessions.has(t))this._sessions.set(t,{reads:0,writes:0,lastActive:null});return this._sessions.get(t)}recordRead(t){if(!t)return;let i=this._ensure(t);i.reads++,i.lastActive=new Date}recordWrite(t){if(!t)return;let i=this._ensure(t);i.writes++,i.lastActive=new Date}get(t){let i=this._sessions.get(t);if(!i)return null;return{sessionId:t,...i}}all(){return[...this._sessions.entries()].map(([t,i])=>({sessionId:t,...i}))}clear(t){if(t)this._sessions.delete(t);else this._sessions.clear()}}class rn{constructor(){this._plugins=[]}register(t){if(typeof t!=="object"||t===null)throw TypeError("Plugin must be a non-null object.");this._plugins.push(t)}async run(t,i){for(let r of this._plugins)if(typeof r[t]==="function")await r[t](i)}get size(){return this._plugins.length}}function ot(t){if(typeof t!=="string"||!t.trim())throw Error("collection name must be a non-empty string");if(/[/\\]/.test(t)||t.includes("..")||t.includes("\x00"))throw Error(`invalid collection name: "${t}"`);if(t.trim().startsWith("_"))throw Error(`access to system collection "${t}" is not permitted`);return t.trim()}var Kr=[{name:"skalex_collections",description:"List all collection names in the database.",inputSchema:{type:"object",properties:{}},scope:"read"},{name:"skalex_schema",description:"Return the schema for a collection as a { field: type } map. Returns null if the collection is empty.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."}},required:["collection"]},scope:"read"},{name:"skalex_find",description:"Find documents in a collection that match a filter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},filter:{type:"object",description:"Query filter (MongoDB-style operators supported)."},limit:{type:"number",description:"Maximum number of results. Default: 20."},sort:{type:"object",description:"Sort descriptor: { field: 1 } for ascending, { field: -1 } for descending."}},required:["collection"]},scope:"read"},{name:"skalex_insert",description:"Insert a single document into a collection.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},doc:{type:"object",description:"Document to insert."}},required:["collection","doc"]},scope:"write"},{name:"skalex_update",description:"Update the first document matching a filter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},filter:{type:"object",description:"Query filter to identify the document."},update:{type:"object",description:"Fields to update (direct assignment, $inc, $push supported)."},many:{type:"boolean",description:"If true, update all matching documents. Default: false."}},required:["collection","filter","update"]},scope:"write"},{name:"skalex_delete",description:"Delete the first document matching a filter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},filter:{type:"object",description:"Query filter to identify the document."},many:{type:"boolean",description:"If true, delete all matching documents. Default: false."}},required:["collection","filter"]},scope:"write"},{name:"skalex_search",description:"Semantic similarity search. Requires an embedding adapter to be configured.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},query:{type:"string",description:"Natural-language query string to embed and compare."},limit:{type:"number",description:"Maximum number of results. Default: 10."},minScore:{type:"number",description:"Minimum cosine similarity score [0, 1]. Default: 0."},filter:{type:"object",description:"Optional structured pre-filter (hybrid search)."}},required:["collection","query"]},scope:"read"},{name:"skalex_ask",description:"Translate a natural-language question into a filter and query a collection. Requires a language model adapter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},question:{type:"string",description:"Natural-language question about the data."},limit:{type:"number",description:"Maximum number of results. Default: 20."}},required:["collection","question"]},scope:"read"}];async function al(t,i,r){switch(t){case"skalex_collections":return Object.keys(r.collections).filter((s)=>!s.startsWith("_"));case"skalex_schema":return r.schema(ot(i.collection))??null;case"skalex_find":{let s=r.useCollection(ot(i.collection)),n={};if(i.limit)n.limit=i.limit;if(i.sort)n.sort=i.sort;return s.find(i.filter||{},n)}case"skalex_insert":return r.useCollection(ot(i.collection)).insertOne(i.doc||{});case"skalex_update":{let s=r.useCollection(ot(i.collection));if(i.many)return s.updateMany(i.filter||{},i.update||{});return s.updateOne(i.filter||{},i.update||{})}case"skalex_delete":{let s=r.useCollection(ot(i.collection));if(i.many)return s.deleteMany(i.filter||{});return s.deleteOne(i.filter||{})}case"skalex_search":return r.useCollection(ot(i.collection)).search(i.query,{limit:i.limit??10,minScore:i.minScore??0,filter:i.filter});case"skalex_ask":return r.ask(ot(i.collection),i.question,{limit:i.limit??20});default:throw Object.assign(Error(`Unknown tool: ${t}`),{code:"NOT_FOUND"})}}var Hi="2.0",Wi=-32700,ol=-32600,zr=-32601,ll=-32602,cl=-32603;function yt(t,i){return{jsonrpc:Hi,id:t,result:i}}function Ke(t,i,r,s){return{jsonrpc:Hi,id:t,error:{code:i,message:r}}}function dl(t){try{let i=JSON.parse(t);if(typeof i!=="object"||i===null||i.jsonrpc!==Hi)return{parseError:Ke(null,ol,"Invalid JSON-RPC request")};return{msg:i}}catch(i){return{parseError:Ke(null,Wi,"Parse error")}}}function ul(t){return{content:[{type:"text",text:t}]}}function Br(t){return{content:[{type:"text",text:t}],isError:!0}}class sn{constructor({port:t=3000,host:i="127.0.0.1",allowedOrigin:r=null,maxBodySize:s=1048576}={}){this._port=t,this._host=i,this._allowedOrigin=r,this._maxBodySize=s,this._clients=new Set,this._onMessage=null,this._server=null}onMessage(t){this._onMessage=t}send(t){let i=`data: ${JSON.stringify(t)}
|
|
21
|
+
`),c=await this._db._aiAdapter.summarize(o);await this._col.deleteMany({_id:{$in:a.map((l)=>l._id)}}),await this._col.insertOne({text:c,sessionId:this.sessionId,compressed:!0})}_docTokens(t){return Math.ceil((t.text||"").length/il)}_sortedData(t){return[...this._col._data].sort(t==="asc"?(i,r)=>new Date(i.createdAt)-new Date(r.createdAt):(i,r)=>new Date(r.createdAt)-new Date(i.createdAt))}}class Qs{constructor(t){this._db=t,this._restoring=!1}get _col(){return this._db.useCollection("_changelog")}async log(t,i,r,s=null,n=null){if(this._restoring)return;let a={op:t,collection:i,docId:r._id,doc:{...r},timestamp:new Date};if(s)a.prev={...s};if(n)a.session=n;await this._col.insertOne(a)}async query(t,{since:i,limit:r,session:s}={}){let n={collection:t};if(i)n.timestamp={$gte:new Date(i)};if(s)n.session=s;let a={sort:{timestamp:1}};if(r)a.limit=r;let{docs:o}=await this._col.find(n,a);return o}async restore(t,i,{_id:r}={}){let s=new Date(i),n=this._db.useCollection(t),a=(await this.query(t,{})).filter((c)=>new Date(c.timestamp)<=s);if(r){let c=a.filter((d)=>d.docId===r);if(c.length===0)return;let l=c[c.length-1];this._restoring=!0;try{if(l.op==="delete"){if(await n.findOne({_id:r}))await n.deleteOne({_id:r});return}if(await n.findOne({_id:r})){let{_id:d,createdAt:u,updatedAt:f,...h}=l.doc;await n.updateOne({_id:r},h)}else await n.insertOne({...l.doc})}finally{this._restoring=!1}await this._db.saveData(t);return}let o=new Map;for(let c of a)if(c.op==="insert"||c.op==="update")o.set(c.docId,{doc:c.doc,deleted:!1});else if(c.op==="delete")o.set(c.docId,{doc:null,deleted:!0});this._restoring=!0;try{await n.deleteMany({});for(let[,{doc:c,deleted:l}]of o)if(!l&&c)await n.insertOne({...c})}finally{this._restoring=!1}await this._db.saveData(t)}}function rl(t){let i=5381;for(let r=0;r<t.length;r++)i=(i<<5)+i+t.charCodeAt(r)|0;return(i>>>0).toString(16).padStart(8,"0")}class Zs{constructor({maxSize:t=500,ttl:i=0}={}){this._cache=new Map,this._maxSize=t,this._ttl=i}_key(t,i,r){return rl(JSON.stringify({collectionName:t,schema:i,query:r}))}get(t,i,r){let s=this._key(t,i,r),n=this._cache.get(s);if(!n)return;if(this._ttl>0&&Date.now()-n.ts>this._ttl){this._cache.delete(s);return}return n.filter}set(t,i,r,s){let n=this._key(t,i,r);if(this._cache.size>=this._maxSize&&!this._cache.has(n))this._cache.delete(this._cache.keys().next().value);this._cache.set(n,{filter:s,ts:Date.now()})}toJSON(){return Object.fromEntries([...this._cache.entries()].map(([t,i])=>[t,i]))}fromJSON(t){if(!t||typeof t!=="object")return;for(let[i,r]of Object.entries(t))this._cache.set(i,r)}get size(){return this._cache.size}}function sl(t,{regexMaxLength:i=500}={}){if(typeof t!=="object"||t===null)return t;let r={};for(let s of Object.keys(t)){let n=t[s];if(n&&typeof n==="object"&&!Array.isArray(n)){let a={};for(let o of Object.keys(n))if(o==="$regex"&&typeof n.$regex==="string"){if(n.$regex.length>i)throw Error(`$regex pattern too long (max ${i} characters)`);if(/\([^)]*[+*][^)]*\)[+*{]/.test(n.$regex))throw Error("$regex pattern rejected: nested quantifiers risk ReDoS");try{a.$regex=new RegExp(n.$regex)}catch{throw Error(`invalid $regex pattern: "${n.$regex}"`)}}else if(["$gt","$gte","$lt","$lte"].includes(o)&&nl(n[o]))a[o]=new Date(n[o]);else a[o]=n[o];r[s]=a}else r[s]=n}return r}function nl(t){if(typeof t!=="string")return!1;return/\d{4}-\d{2}-\d{2}/.test(t)&&!isNaN(Date.parse(t))}function al(t,i){let r=[];if(!i||typeof t!=="object"||t===null)return r;for(let s of Object.keys(t)){if(s.startsWith("$"))continue;if(!(s.split(".")[0]in i))r.push(`Unknown field referenced in generated filter: "${s}"`)}return r}class en{constructor(){this._listeners=new Map}on(t,i){if(!this._listeners.has(t))this._listeners.set(t,new Set);return this._listeners.get(t).add(i),()=>this._listeners.get(t)?.delete(i)}off(t,i){this._listeners.get(t)?.delete(i)}emit(t,i){for(let r of[t,"*"]){let s=this._listeners.get(r);if(!s)continue;for(let n of s)try{n(i)}catch(a){}}}removeAll(t){if(t)this._listeners.delete(t);else this._listeners.clear()}listenerCount(t){return this._listeners.get(t)?.size??0}}class tn{constructor({threshold:t=100,maxEntries:i=500}={}){this._threshold=t,this._maxEntries=i,this._entries=[]}record({collection:t,op:i,filter:r,query:s,duration:n,resultCount:a}){if(n<this._threshold)return;let o={collection:t,op:i,duration:n,resultCount:a,timestamp:new Date};if(r!==void 0)o.filter=r;if(s!==void 0)o.query=s;if(this._entries.push(o),this._entries.length>this._maxEntries)this._entries.shift()}entries({limit:t,minDuration:i,collection:r}={}){let s=this._entries;if(r)s=s.filter((n)=>n.collection===r);if(i)s=s.filter((n)=>n.duration>=i);if(t)s=s.slice(-t);return s}get size(){return this._entries.length}clear(){this._entries=[]}}class rn{constructor(){this._sessions=new Map}_ensure(t){if(!this._sessions.has(t))this._sessions.set(t,{reads:0,writes:0,lastActive:null});return this._sessions.get(t)}recordRead(t){if(!t)return;let i=this._ensure(t);i.reads++,i.lastActive=new Date}recordWrite(t){if(!t)return;let i=this._ensure(t);i.writes++,i.lastActive=new Date}get(t){let i=this._sessions.get(t);if(!i)return null;return{sessionId:t,...i}}all(){return[...this._sessions.entries()].map(([t,i])=>({sessionId:t,...i}))}clear(t){if(t)this._sessions.delete(t);else this._sessions.clear()}}class sn{constructor(){this._plugins=[]}register(t){if(typeof t!=="object"||t===null)throw TypeError("Plugin must be a non-null object.");this._plugins.push(t)}async run(t,i){for(let r of this._plugins)if(typeof r[t]==="function")await r[t](i)}get size(){return this._plugins.length}}function ot(t){if(typeof t!=="string"||!t.trim())throw Error("collection name must be a non-empty string");if(/[/\\]/.test(t)||t.includes("..")||t.includes("\x00"))throw Error(`invalid collection name: "${t}"`);if(t.trim().startsWith("_"))throw Error(`access to system collection "${t}" is not permitted`);return t.trim()}var zr=[{name:"skalex_collections",description:"List all collection names in the database.",inputSchema:{type:"object",properties:{}},scope:"read"},{name:"skalex_schema",description:"Return the schema for a collection as a { field: type } map. Returns null if the collection is empty.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."}},required:["collection"]},scope:"read"},{name:"skalex_find",description:"Find documents in a collection that match a filter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},filter:{type:"object",description:"Query filter (MongoDB-style operators supported)."},limit:{type:"number",description:"Maximum number of results. Default: 20."},sort:{type:"object",description:"Sort descriptor: { field: 1 } for ascending, { field: -1 } for descending."}},required:["collection"]},scope:"read"},{name:"skalex_insert",description:"Insert a single document into a collection.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},doc:{type:"object",description:"Document to insert."}},required:["collection","doc"]},scope:"write"},{name:"skalex_update",description:"Update the first document matching a filter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},filter:{type:"object",description:"Query filter to identify the document."},update:{type:"object",description:"Fields to update (direct assignment, $inc, $push supported)."},many:{type:"boolean",description:"If true, update all matching documents. Default: false."}},required:["collection","filter","update"]},scope:"write"},{name:"skalex_delete",description:"Delete the first document matching a filter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},filter:{type:"object",description:"Query filter to identify the document."},many:{type:"boolean",description:"If true, delete all matching documents. Default: false."}},required:["collection","filter"]},scope:"write"},{name:"skalex_search",description:"Semantic similarity search. Requires an embedding adapter to be configured.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},query:{type:"string",description:"Natural-language query string to embed and compare."},limit:{type:"number",description:"Maximum number of results. Default: 10."},minScore:{type:"number",description:"Minimum cosine similarity score [0, 1]. Default: 0."},filter:{type:"object",description:"Optional structured pre-filter (hybrid search)."}},required:["collection","query"]},scope:"read"},{name:"skalex_ask",description:"Translate a natural-language question into a filter and query a collection. Requires a language model adapter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},question:{type:"string",description:"Natural-language question about the data."},limit:{type:"number",description:"Maximum number of results. Default: 20."}},required:["collection","question"]},scope:"read"}];async function ol(t,i,r){switch(t){case"skalex_collections":return Object.keys(r.collections).filter((s)=>!s.startsWith("_"));case"skalex_schema":return r.schema(ot(i.collection))??null;case"skalex_find":{let s=r.useCollection(ot(i.collection)),n={};if(i.limit)n.limit=i.limit;if(i.sort)n.sort=i.sort;return s.find(i.filter||{},n)}case"skalex_insert":return r.useCollection(ot(i.collection)).insertOne(i.doc||{});case"skalex_update":{let s=r.useCollection(ot(i.collection));if(i.many)return s.updateMany(i.filter||{},i.update||{});return s.updateOne(i.filter||{},i.update||{})}case"skalex_delete":{let s=r.useCollection(ot(i.collection));if(i.many)return s.deleteMany(i.filter||{});return s.deleteOne(i.filter||{})}case"skalex_search":return r.useCollection(ot(i.collection)).search(i.query,{limit:i.limit??10,minScore:i.minScore??0,filter:i.filter});case"skalex_ask":return r.ask(ot(i.collection),i.question,{limit:i.limit??20});default:throw Object.assign(Error(`Unknown tool: ${t}`),{code:"NOT_FOUND"})}}var Xi="2.0",Vi=-32700,ll=-32600,Br=-32601,cl=-32602,dl=-32603;function yt(t,i){return{jsonrpc:Xi,id:t,result:i}}function Ke(t,i,r,s){return{jsonrpc:Xi,id:t,error:{code:i,message:r}}}function ul(t){try{let i=JSON.parse(t);if(typeof i!=="object"||i===null||i.jsonrpc!==Xi)return{parseError:Ke(null,ll,"Invalid JSON-RPC request")};return{msg:i}}catch(i){return{parseError:Ke(null,Vi,"Parse error")}}}function hl(t){return{content:[{type:"text",text:t}]}}function Xr(t){return{content:[{type:"text",text:t}],isError:!0}}class nn{constructor({port:t=3000,host:i="127.0.0.1",allowedOrigin:r=null,maxBodySize:s=1048576}={}){this._port=t,this._host=i,this._allowedOrigin=r,this._maxBodySize=s,this._clients=new Set,this._onMessage=null,this._server=null}onMessage(t){this._onMessage=t}send(t){let i=`data: ${JSON.stringify(t)}
|
|
22
22
|
|
|
23
|
-
`;for(let r of this._clients)try{r.write(i)}catch(s){this._clients.delete(r)}}start(){return new Promise((t,i)=>{this._server=
|
|
23
|
+
`;for(let r of this._clients)try{r.write(i)}catch(s){this._clients.delete(r)}}start(){return new Promise((t,i)=>{this._server=lo.createServer((r,s)=>{if(this._allowedOrigin)s.setHeader("Access-Control-Allow-Origin",this._allowedOrigin),s.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),s.setHeader("Access-Control-Allow-Headers","Content-Type");if(r.method==="OPTIONS"){s.writeHead(204),s.end();return}if(r.method==="GET"&&r.url==="/sse")this._handleSSE(r,s);else if(r.method==="POST"&&r.url==="/message")this._handleMessage(r,s);else s.writeHead(404,{"Content-Type":"text/plain"}),s.end("Not Found")}),this._server.on("error",i),this._server.listen(this._port,this._host,()=>t())})}stop(){return new Promise((t)=>{if(!this._server){t();return}for(let i of this._clients)try{i.end()}catch(r){}this._clients.clear(),this._server.close(()=>t()),this._server=null})}_handleSSE(t,i){i.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),i.write(`event: endpoint
|
|
24
24
|
data: /message
|
|
25
25
|
|
|
26
|
-
`),this._clients.add(i),t.on("close",()=>{this._clients.delete(i)})}async _handleMessage(t,i){let r="";t.setEncoding("utf8"),t.on("data",(s)=>{if(r+=s,r.length>this._maxBodySize)t.destroy(),i.writeHead(413,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Request body too large"}))}),t.on("end",async()=>{i.writeHead(202,{"Content-Type":"application/json"}),i.end("{}");let s;try{s=JSON.parse(r)}catch(n){this.send(Ke(null,
|
|
26
|
+
`),this._clients.add(i),t.on("close",()=>{this._clients.delete(i)})}async _handleMessage(t,i){let r="";t.setEncoding("utf8"),t.on("data",(s)=>{if(r+=s,r.length>this._maxBodySize)t.destroy(),i.writeHead(413,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Request body too large"}))}),t.on("end",async()=>{i.writeHead(202,{"Content-Type":"application/json"}),i.end("{}");let s;try{s=JSON.parse(r)}catch(n){this.send(Ke(null,Vi,"Parse error"));return}if(this._onMessage)await this._onMessage(s).catch(()=>{})})}get port(){return this._port}get host(){return this._host}get url(){return`http://${this._host}:${this._port}`}get sseUrl(){return`${this.url}/sse`}}class an{constructor(){this._onMessage=null,this._buffer="",this._started=!1}onMessage(t){this._onMessage=t}send(t){process.stdout.write(JSON.stringify(t)+`
|
|
27
27
|
`)}start(){if(this._started)return;this._started=!0,process.stdin.setEncoding("utf8"),process.stdin.on("data",(t)=>{this._buffer+=t;let i;while((i=this._buffer.indexOf(`
|
|
28
|
-
`))!==-1){let r=this._buffer.slice(0,i).trim();if(this._buffer=this._buffer.slice(i+1),r&&this._onMessage){let s;try{s=JSON.parse(r)}catch(n){this.send(Ke(null,Wi,"Parse error"));continue}this._onMessage(s).catch(()=>{})}}}),process.stdin.on("end",()=>{process.exit(0)})}stop(){process.stdin.removeAllListeners("data"),process.stdin.removeAllListeners("end"),this._started=!1}}var hl={name:"skalex",version:"4.0.0-alpha"},fl="2024-11-05";class an{constructor(t,i={}){this._db=t,this._transport=i.transport||"stdio",this._port=i.port||3000,this._host=i.host||"127.0.0.1",this._allowedOrigin=i.allowedOrigin??null,this._maxBodySize=i.maxBodySize??1048576,this._scopes=i.scopes||{"*":["read"]},this._t=null}async listen(){if(this._transport==="http")this._t=new sn({port:this._port,host:this._host,allowedOrigin:this._allowedOrigin,maxBodySize:this._maxBodySize});else this._t=new nn;this._t.onMessage((t)=>this._handleMessage(t)),await this._t.start()}async connect(t){if(this._t=t,this._t.onMessage((i)=>this._handleMessage(i)),typeof this._t.start==="function")await this._t.start()}async close(){if(this._t&&typeof this._t.stop==="function")await this._t.stop();this._t=null}get transport(){return this._transport}get url(){return this._t?.url}async _handleMessage(t){let{msg:i,parseError:r}=typeof t==="string"?dl(t):{msg:t};if(r){this._send(r);return}let{id:s,method:n,params:a}=i;if(s===void 0){if(n==="notifications/initialized")return;return}try{switch(n){case"initialize":this._send(yt(s,{protocolVersion:fl,capabilities:{tools:{}},serverInfo:hl}));break;case"tools/list":this._send(yt(s,{tools:this._visibleTools()}));break;case"tools/call":await this._handleToolCall(s,a);break;case"ping":this._send(yt(s,{}));break;default:this._send(Ke(s,zr,`Method not found: ${n}`))}}catch(o){this._send(Ke(s,cl,o.message||"Internal error"))}}async _handleToolCall(t,i){let r=i?.name,s=i?.arguments??{};if(!r){this._send(Ke(t,ll,"tools/call requires params.name"));return}let n=Kr.find((o)=>o.name===r);if(!n){this._send(Ke(t,zr,`Unknown tool: ${r}`));return}let a=s.collection||s.collection_name||null;if(!this._hasScope(a,n.scope)){this._send(yt(t,Br(`Access denied: "${r}" requires "${n.scope}" scope on collection "${a}".`)));return}try{let o=await al(r,s,this._db);this._send(yt(t,ul(JSON.stringify(o,null,2))))}catch(o){this._send(yt(t,Br(o.message||String(o))))}}_visibleTools(){return Kr.filter((t)=>{let i=this._scopes["*"];if(i&&(i.includes(t.scope)||i.includes("admin")))return!0;for(let[,r]of Object.entries(this._scopes))if(r.includes(t.scope)||r.includes("admin"))return!0;return!1})}_hasScope(t,i){let r=(s)=>s.includes("admin")||s.includes(i);if(t&&this._scopes[t])return r(this._scopes[t]);if(this._scopes["*"])return r(this._scopes["*"]);return!1}_send(t){this._t?.send(t)}}var Ut="migrations",Xr=(t)=>JSON.stringify(t,function(i,r){let s=this[i];if(s instanceof Date)return{__skalex_date__:s.toISOString()};if(typeof r==="bigint")return{__skalex_bigint__:r.toString()};return r}),Vr=(t)=>JSON.parse(t,(i,r)=>{if(r&&typeof r==="object"){if("__skalex_bigint__"in r)return BigInt(r.__skalex_bigint__);if("__skalex_date__"in r)return new Date(r.__skalex_date__)}return r});class de{constructor({path:t="./.db",format:i="gz",debug:r=!1,adapter:s,ai:n,encrypt:a,slowQueryLog:o,queryCache:c,memory:l,logger:d,plugins:u,llmAdapter:f,embeddingAdapter:h,regexMaxLength:_,idGenerator:p,serializer:g,deserializer:m,autoSave:w,ttlSweepInterval:v,lenientLoad:q}={}){if(this.dataDirectory=t,this.dataFormat=i,this.debug=r,!de._errorsAttached)de.SkalexError=Je,de.ValidationError=D,de.UniqueConstraintError=De,de.TransactionError=Re,de.PersistenceError=Ve,de.AdapterError=Se,de.QueryError=ut,de._errorsAttached=!0;this._adapterConfig=s??null;let E=s||new qs({dir:t,format:i});if(a)E=new Ws(E,a.key);if(this.fs=E,this._registry=new zs(js),this.collections=this._registry.stores,this._collectionInstances=this._registry._instances,this._migrations=new Us,this._connectPromise=null,this.isConnected=!1,this._aiConfig=n||null,this._encryptConfig=a||null,this._pluginsConfig=Array.isArray(u)?u:null,this._memoryConfig=l||null,this._regexMaxLength=_??500,this._idGenerator=p??null,this._serializer=g??Xr,this._deserializer=m??Vr,this._autoSave=w??!1,this._txManager=new Ks,this._ttlSweepInterval=v??0,this._ttlTimer=null,this._logger=d??Lr,this._embeddingAdapter=h??(n?Ho(n):null),this._aiAdapter=f??(n?Wo(n):null),this._persistence=new Fs({adapter:this.fs,serializer:this._serializer,deserializer:this._deserializer,logger:this._logger,debug:this.debug,lenientLoad:q??!1}),this._changeLog=new Ys(this),this._queryCache=new Qs(c||{}),this._eventBus=new Zs,this._queryLog=o?new en(o):null,this._sessionStats=new tn,this._plugins=new rn,Array.isArray(u))for(let A of u)this._plugins.register(A)}async connect(){if(this._connectPromise)return this._connectPromise;return this._connectPromise=this._doConnect(),this._connectPromise}async _doConnect(){try{await this.loadData();let t=this._getMeta();if(t.queryCache)this._queryCache.fromJSON(t.queryCache);if(this._migrations._migrations.length>0){let i=t.appliedVersions||[],r=await this._migrations.run((s)=>this.useCollection(`_migration_${s}`),i);this._saveMeta({appliedVersions:r})}if(this._sweepTtl(),this._ttlSweepInterval>0){if(this._ttlTimer=setInterval(()=>this._sweepTtl(),this._ttlSweepInterval),this._ttlTimer?.unref)this._ttlTimer.unref()}this.isConnected=!0,this._log("> - Connected to the database (\u221A)")}catch(t){throw this._logger(`Error connecting to the database: ${t}`,"error"),t}}async disconnect(){try{if(this._ttlTimer)clearInterval(this._ttlTimer),this._ttlTimer=null;await this.saveData(),this._registry.clear(),this.collections=this._registry.stores,this._collectionInstances=this._registry._instances,this._connectPromise=null,this.isConnected=!1,this._log("> - Disconnected from the database (\u221A)")}catch(t){throw this._logger(`Error disconnecting from the database: ${t}`,"error"),t}}async _ensureConnected(){if(this.isConnected)return;return this.connect()}useCollection(t){return this._registry.get(t,this)}createCollection(t,i={}){return this._registry.create(t,i,this)}_createCollectionStore(t,i={}){this._registry.createStore(t,i)}async renameCollection(t,i){this._registry.rename(t,i),await this.saveData(i),await this.fs.delete(t)}async loadData(){await this._persistence.loadAll(this.collections,{parseSchema:Ds,buildIndex:this._registry.buildIndex,IndexEngine:ei});for(let t in this._collectionInstances){let i=this.collections[t];if(i&&this._collectionInstances[t]._store!==i)this._collectionInstances[t]._store=i}}async saveData(t){await this._persistence.save(this.collections,t)}buildIndex(t,i){return this._registry.buildIndex(t,i)}addMigration(t){this._migrations.add(t)}migrationStatus(){let t=this._getMeta();return this._migrations.status(t.appliedVersions||[])}namespace(t){if(this._adapterConfig)throw new Se("ERR_SKALEX_ADAPTER_NAMESPACE_REQUIRES_FS","namespace() requires the default FsAdapter. When a custom storage adapter is configured, create a separate Skalex instance with your adapter instead.");let i=String(t).replace(/[^a-zA-Z0-9_-]/g,"_");if(!i)throw new D("ERR_SKALEX_VALIDATION_NAMESPACE_ID","namespace: id must contain at least one alphanumeric character",{id:t});return new de({path:`${this.dataDirectory}/${i}`,format:this.dataFormat,debug:this.debug,ai:this._aiConfig||void 0,encrypt:this._encryptConfig||void 0,slowQueryLog:this._queryLog?{threshold:this._queryLog._threshold,maxEntries:this._queryLog._maxEntries}:void 0,queryCache:this._queryCache?{maxSize:this._queryCache._maxSize,ttl:this._queryCache._ttl}:void 0,plugins:this._pluginsConfig||void 0,memory:this._memoryConfig||void 0,logger:this._logger!==Lr?this._logger:void 0,llmAdapter:this._aiAdapter&&!this._aiConfig?this._aiAdapter:void 0,embeddingAdapter:this._embeddingAdapter&&!this._aiConfig?this._embeddingAdapter:void 0,regexMaxLength:this._regexMaxLength!==500?this._regexMaxLength:void 0,idGenerator:this._idGenerator||void 0,serializer:this._serializer!==Xr?this._serializer:void 0,deserializer:this._deserializer!==Vr?this._deserializer:void 0,autoSave:this._autoSave||void 0,ttlSweepInterval:this._ttlSweepInterval||void 0})}use(t){this._plugins.register(t)}watch(t){return this._eventBus.on("*",t)}sessionStats(t){if(t!==void 0)return this._sessionStats.get(t);return this._sessionStats.all()}get _inTransaction(){return this._txManager.active}_emitEvent(t,i){if(!this._txManager.defer(()=>this._eventBus.emit(t,i)))this._eventBus.emit(t,i)}async _runAfterHook(t,i){if(!this._txManager.defer(()=>this._plugins.run(t,i)))await this._plugins.run(t,i)}async _logChange(t,i,r,s,n){if(!this._txManager.defer(()=>this._changeLog.log(t,i,r,s,n)))await this._changeLog.log(t,i,r,s,n)}async transaction(t,i={}){return this._txManager.run(t,this,i)}async seed(t,{reset:i=!1}={}){for(let[r,s]of Object.entries(t)){if(i&&this.collections[r])this._applySnapshot(r,{data:[],index:new Map}),delete this._collectionInstances[r];await this.useCollection(r).insertMany(s)}await this.saveData()}dump(){return this._registry.dump()}inspect(t){return this._registry.inspect(t)}async import(t){let i=await this.fs.readRaw(t),r;try{r=JSON.parse(i)}catch{throw new Ve("ERR_SKALEX_PERSISTENCE_INVALID_JSON",`import: invalid JSON in file "${t}"`,{filePath:t})}let s=t.split("/").pop().replace(/\.[^.]+$/,"");return this.useCollection(s).insertMany(Array.isArray(r)?r:[r],{save:!0})}async embed(t){if(!this._embeddingAdapter)throw new Se("ERR_SKALEX_ADAPTER_EMBEDDING_REQUIRED","db.embed() requires an AI adapter. Pass { ai: { provider, apiKey } } to the Skalex constructor.");return this._embeddingAdapter.embed(t)}async ask(t,i,{limit:r=20}={}){if(!this._aiAdapter)throw new Se("ERR_SKALEX_ADAPTER_LLM_REQUIRED",'db.ask() requires a language model adapter. Configure { ai: { provider, model: "..." } }.');let s=this.useCollection(t),n=this.schema(t),a=this._queryCache.get(t,n,i);if(!a){a=await this._aiAdapter.generate(n,i);let o=nl(a,n);if(o.length)o.forEach((c)=>this._log(`[ask] ${c}`));this._queryCache.set(t,n,i,a),this._saveMeta({queryCache:this._queryCache.toJSON()})}return s.find(rl(a,{regexMaxLength:this._regexMaxLength}),{limit:r})}schema(t){return this._registry.schema(t)}useMemory(t){return new Js(t,this)}changelog(){return this._changeLog}async restore(t,i,r={}){return this._changeLog.restore(t,i,r)}stats(t){return this._registry.stats(t)}slowQueries(t={}){if(!this._queryLog)return[];return this._queryLog.entries(t)}slowQueryCount(){return this._queryLog?this._queryLog.size:0}clearSlowQueries(){this._queryLog?.clear()}mcp(t={}){return new an(this,t)}_getMeta(){let t=this.collections._meta;if(!t)return{};return t.index.get(Ut)||{}}_saveMeta(t){if(!this.collections._meta)this._createCollectionStore("_meta");let i=this.collections._meta,r=i.index.get(Ut);if(r)Object.assign(r,t);else{let s={_id:Ut,...t};i.data.push(s),i.index.set(Ut,s)}this._persistence.markDirty(this.collections,"_meta")}_sweepTtl(){for(let t in this.collections){let i=this.collections[t],r=Fo(i.data,i.index,i.fieldIndex?(s)=>i.fieldIndex.remove(s):null);if(r>0)this._persistence.markDirty(this.collections,t),this._log(`TTL sweep: removed ${r} expired docs from "${t}"`)}}_buildCollectionContext(){let t=this;return{ensureConnected:()=>t._ensureConnected(),get txManager(){return t._txManager},get plugins(){return t._plugins},get eventBus(){return t._eventBus},get sessionStats(){return t._sessionStats},get queryLog(){return t._queryLog},get logger(){return t._logger},get persistence(){return t._persistence},get collections(){return t.collections},embed:(i)=>t.embed(i),get idGenerator(){return t._idGenerator},get autoSave(){return t._autoSave},saveCollection:(i)=>t.saveData(i),snapshotCollection:(i)=>t._snapshotCollection(i),getCollection:(i)=>t.useCollection(i),emitEvent:(i,r)=>t._emitEvent(i,r),runAfterHook:(i,r)=>t._runAfterHook(i,r),logChange:(i,r,s,n,a)=>t._logChange(i,r,s,n,a),get fs(){return t.fs},get dataDirectory(){return t.dataDirectory}}}_log(t){if(this.debug)this._logger(t,"info")}_snapshotCollection(t){return{data:structuredClone(t.data)}}_applySnapshot(t,i){let r=this.collections[t];if(!r)return;if(r.data=i.data,r.index=this.buildIndex(i.data,"_id"),r.fieldIndex)r.fieldIndex.buildFromData(i.data)}}function _l(){let t=Date.now().toString(16),i;try{i=go.randomBytes(8).toString("hex")}catch{let r=new Uint8Array(8);crypto.getRandomValues(r),i=Array.from(r).map((s)=>s.toString(16).padStart(2,"0")).join("")}return`${t}${i}`}function Gr(t,i){let r=t instanceof Error?t.message:t;if(i==="error")console.error(r);else console.log(r)}var Hr=new Set(["__proto__","constructor","prototype"]);function oi(t,i){if(!i.includes(".")){if(Hr.has(i))return;return t[i]}let r=t;for(let s of i.split(".")){if(Hr.has(s))return;if(r==null)return;r=r[s]}return r}class Ye extends Error{constructor(t,i,r={}){super(i);this.name=this.constructor.name,this.code=t,this.details=r}}class L extends Ye{}class Pe extends Ye{}class Ce extends Ye{}class Ge extends Ye{}class Ie extends Ye{}class ht extends Ye{}function Mi(t,i){if(t===i)return!0;if(t==null||i==null)return!1;if(typeof t!==typeof i)return!1;if(t instanceof Date&&i instanceof Date)return t.getTime()===i.getTime();if(t instanceof RegExp&&i instanceof RegExp)return t.source===i.source&&t.flags===i.flags;if(Array.isArray(t)){if(!Array.isArray(i)||t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Mi(t[r],i[r]))return!1;return!0}if(typeof t==="object"){if(Array.isArray(i))return!1;let r=Object.keys(t);if(r.length!==Object.keys(i).length)return!1;for(let s of r){if(!Object.prototype.hasOwnProperty.call(i,s))return!1;if(!Mi(t[s],i[s]))return!1}return!0}return!1}function re(t,i){if(typeof i==="function")return i(t);if(i==null)return!0;if(typeof i==="object"&&Object.keys(i).length===0)return!0;if("$or"in i){let r=i.$or;if(!Array.isArray(r))throw new ht("ERR_SKALEX_QUERY_INVALID_OPERATOR","$or must be an array of filters",{operator:"$or"});if(!r.some((s)=>re(t,s)))return!1}if("$and"in i){let r=i.$and;if(!Array.isArray(r))throw new ht("ERR_SKALEX_QUERY_INVALID_OPERATOR","$and must be an array of filters",{operator:"$and"});if(!r.every((s)=>re(t,s)))return!1}if("$not"in i){if(re(t,i.$not))return!1}for(let r in i){if(r==="$or"||r==="$and"||r==="$not")continue;let s=i[r],n;try{n=oi(t,r)}catch{return!1}if(s instanceof RegExp){if(!s.test(String(n)))return!1}else if(typeof s==="object"&&s!==null){if(Object.keys(s).some((a)=>a.startsWith("$"))){if("$eq"in s&&n!==s.$eq)return!1;if("$ne"in s&&n===s.$ne)return!1;if("$gt"in s&&!(n>s.$gt))return!1;if("$lt"in s&&!(n<s.$lt))return!1;if("$gte"in s&&!(n>=s.$gte))return!1;if("$lte"in s&&!(n<=s.$lte))return!1;if("$in"in s&&!s.$in.includes(n))return!1;if("$nin"in s&&s.$nin.includes(n))return!1;if("$regex"in s){if(!(s.$regex instanceof RegExp?s.$regex:new RegExp(s.$regex)).test(String(n)))return!1}if("$fn"in s&&!s.$fn(n))return!1}else if(!Mi(n,s))return!1}else if(n!==s)return!1}return!0}function pl(t,i=new Set){if(typeof t!=="object"||t===null||typeof t==="function")return t;let r=[],s=[],n=[],a=[],o=[];for(let l in t){if(l==="$or"||l==="$and"||l==="$not"){o.push(l);continue}let d=t[l];if(i.has(l))r.push(l);else if(d instanceof RegExp||typeof d==="object"&&d!==null&&(("$regex"in d)||("$fn"in d))||typeof d==="function")a.push(l);else if(typeof d==="object"&&d!==null&&(("$gt"in d)||("$lt"in d)||("$gte"in d)||("$lte"in d)||("$ne"in d)||("$in"in d)||("$nin"in d)))n.push(l);else s.push(l)}let c={};for(let l of[...r,...s,...n,...a,...o])c[l]=t[l];return c}var ji=new Set(["string","number","boolean","object","array","date","any"]);function Ji(t){if(Array.isArray(t))return"array";if(t instanceof Date)return"date";return typeof t}function on(t){let i=new Map,r=[];for(let[s,n]of Object.entries(t)){let a;if(typeof n==="string"){if(!ji.has(n))throw new L("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${n}" for field "${s}"`,{field:s,type:n});a={type:n,required:!1,unique:!1}}else if(typeof n==="object"&&n!==null){let{type:o="any",required:c=!1,unique:l=!1,enum:d}=n;if(!ji.has(o))throw new L("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${o}" for field "${s}"`,{field:s,type:o});if(a={type:o,required:c,unique:l,enum:d},l)r.push(s)}else throw new L("ERR_SKALEX_VALIDATION_INVALID_SCHEMA",`Invalid schema definition for field "${s}"`,{field:s});i.set(s,a)}return{fields:i,uniqueFields:r}}function Wr(t,i,r=!1){let s=[];for(let[n,a]of i){let o=t[n],c=o===void 0||o===null;if(a.required&&c){s.push(`Field "${n}" is required`);continue}if(c)continue;if(a.type!=="any"){let l=Ji(o);if(l!==a.type)s.push(`Field "${n}" must be of type "${a.type}", got "${l}"`)}if(a.enum&&!a.enum.includes(o))s.push(`Field "${n}" must be one of [${a.enum.map((l)=>JSON.stringify(l)).join(", ")}], got ${JSON.stringify(o)}`)}if(r){for(let n of Object.keys(t))if(!n.startsWith("_")&&!i.has(n))s.push(`Unknown field "${n}" (strict mode)`)}return s}function Jr(t,i){let r={};for(let[s,n]of Object.entries(t)){if(s.startsWith("_")){r[s]=n;continue}if(!i.has(s))continue;let a=i.get(s);if(a.type!=="any"){if(Ji(n)!==a.type)continue}if(a.enum&&!a.enum.includes(n))continue;r[s]=n}return r}function gl(t){let i={};for(let[r,s]of Object.entries(t)){if(r.startsWith("_"))continue;let n=Ji(s);i[r]=ji.has(n)?n:"any"}return i}function ml(t){if(typeof t==="number"){if(t<=0)throw new L("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got ${t}`,{ttl:t});return t*1000}if(typeof t!=="string")throw new L("ERR_SKALEX_VALIDATION_TTL",`Invalid TTL value: ${t}`,{ttl:t});let i=t.match(/^(\d+(?:\.\d+)?)(ms|s|m|h|d)$/);if(!i)throw new L("ERR_SKALEX_VALIDATION_TTL_FORMAT",`Invalid TTL format: "${t}". Use e.g. 300 (seconds), "30m", "24h", "7d"`,{ttl:t});let r=parseFloat(i[1]);if(r<=0)throw new L("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got "${t}"`,{ttl:t});let s=i[2],n=r*{ms:1,s:1000,m:60000,h:3600000,d:86400000}[s];if(!isFinite(n))throw new L("ERR_SKALEX_VALIDATION_TTL",`TTL value "${t}" is too large`,{ttl:t});return n}function yl(t){return new Date(Date.now()+ml(t))}function wl(t,i,r=null){let s=Date.now(),n=0,a=t.length;while(a--){let o=t[a];if(o._expiresAt&&new Date(o._expiresAt).getTime()<=s){if(t.splice(a,1),i.delete(o._id),r)r(o);n++}}return n}function Yr(t,i){if(t.length!==i.length)throw new ht("ERR_SKALEX_QUERY_VECTOR_MISMATCH",`Vector dimension mismatch: ${t.length} vs ${i.length}`,{expected:t.length,got:i.length});let r=0,s=0,n=0;for(let o=0;o<t.length;o++)r+=t[o]*i[o],s+=t[o]*t[o],n+=i[o]*i[o];let a=Math.sqrt(s*n);return a===0?0:r/a}function Z(t){if(!("_vector"in t))return{...t};let{_vector:i,...r}=t;return r}function Al(t){return t.length}function vl(t,i){let r=0;for(let s of t){let n=oi(s,i);if(typeof n==="number"&&!isNaN(n))r+=n}return r}function El(t,i){let r=0,s=0;for(let n of t){let a=oi(n,i);if(typeof a==="number"&&!isNaN(a))r+=a,s++}return s===0?null:r/s}function xl(t,i){let r=Object.create(null);for(let s of t){let n=String(oi(s,i)??"__null__");if(!r[n])r[n]=[];r[n].push(s)}return r}class ln{constructor(t){this._col=t}get _ctx(){return this._col._ctx}async execute({op:t,beforeHook:i,afterHook:r,hookPayload:s,mutate:n,afterHookPayload:a,save:o,session:c}){let l=this._ctx;await l.ensureConnected(),this._col._txSnapshotIfNeeded();let d=l.txManager,u=d.active&&this._col._activeTxId===d.context?.id,f=u?d.context.id:null,h=this._col._createdInTxId,_=()=>{if(f!==null&&d._abortedIds.has(f))throw new Ce("ERR_SKALEX_TX_ABORTED",`Transaction ${f} was aborted. No further mutations allowed.`);if(h!==null&&d._abortedIds.has(h))throw new Ce("ERR_SKALEX_TX_ABORTED",`Transaction ${h} was aborted. Collection obtained inside that transaction cannot be used for further mutations.`)};if(u||h!==null)_();if(i)await l.plugins.run(i,s);let{docs:p,prevDocs:g=[]}=await n(_);if(l.persistence.markDirty(l.collections,this._col.name),await this._col._saveIfNeeded(o),this._col._changelogEnabled)for(let m=0;m<p.length;m++)await l.logChange(t,this._col.name,p[m],g[m]??null,c||null);if(!u||!d.defer(()=>l.sessionStats.recordWrite(c)))l.sessionStats.recordWrite(c);for(let m of p)l.emitEvent(this._col.name,{op:t,collection:this._col.name,doc:Z(m)});if(r)if(a)await l.runAfterHook(r,a(p));else for(let m of p)await l.runAfterHook(r,{collection:this._col.name,doc:Z(m)});return{docs:p,prevDocs:g}}}function Sl(t){let i={};for(let r in t){if(r.startsWith("$"))continue;let s=t[r];if(s&&typeof s==="object"&&!Array.isArray(s)){let n=Object.keys(s);if(n.length===1&&n[0]==="$eq")i[r]=s.$eq}else i[r]=s}return i}var cn=new Set(["__proto__","constructor","prototype"]);function dn(t){if(typeof t!=="object"||t===null||Array.isArray(t))return t;let i={};for(let r of Object.keys(t)){if(cn.has(r))continue;i[r]=dn(t[r])}return i}class un{constructor(t,i){this.name=t.collectionName,this.database=i,this._ctx=i._buildCollectionContext(),this._store=t,this._pipeline=new ln(this),this._createdInTxId=i._txManager.context?.id??null,this._activeTxId=null}get _data(){return this._store.data}set _data(t){this._store.data=t}get _index(){return this._store.index}get _fieldIndex(){return this._store.fieldIndex||null}get _schema(){return this._store.schema?this._store.schema.fields:null}get _changelogEnabled(){return this._store.changelog===!0}get _softDelete(){return this._store.softDelete===!0}get _versioning(){return this._store.versioning===!0}get _strict(){return this._store.strict===!0}get _onSchemaError(){return this._store.onSchemaError??"throw"}get _defaultTtl(){return this._store.defaultTtl||null}get _defaultEmbed(){return this._store.defaultEmbed||null}get _maxDocs(){return this._store.maxDocs||null}async insertOne(t,i={}){let{save:r,ifNotExists:s,ttl:n,embed:a,session:o}=i;if(s){await this._ctx.ensureConnected();let l=this._findRaw(t);if(l)return Z({...l})}let{docs:c}=await this._insertCore([t],{ttl:n,embed:a,session:o,save:r});return Z(c[0])}async insertMany(t,i={}){let{save:r,ttl:s,embed:n,session:a}=i,{docs:o}=await this._insertCore(t,{ttl:s,embed:n,session:a,save:r});return o.map(Z)}async _insertCore(t,{ttl:i,embed:r,session:s,save:n}){return this._pipeline.execute({op:"insert",beforeHook:null,afterHook:"afterInsert",hookPayload:null,save:n,session:s,mutate:async(a)=>{let o=[],c=new Set;for(let l of t){let d=this._applyValidation(l);await this._ctx.plugins.run("beforeInsert",{collection:this.name,doc:d});let u=await this._buildDoc(d,{ttl:i,embed:r});if(this._index.has(u._id)||c.has(u._id))throw new Pe("ERR_SKALEX_UNIQUE_DUPLICATE_ID",`Duplicate _id "${u._id}" in collection "${this.name}"`,{id:u._id,collection:this.name});c.add(u._id),o.push(u)}if(a(),this._fieldIndex)this._fieldIndex.assertUniqueBatch(o);for(let l of o)this._addToIndex(l);this._data.push(...o);for(let l of o)this._index.set(l._id,l);return this._enforceCapAfterInsert(),{docs:o}}})}async updateOne(t,i,r={}){await this._ctx.ensureConnected();let s=this._findRaw(t);if(!s)return null;let{save:n,session:a}=r,{docs:o}=await this._updateCore([s],t,i,{save:n,session:a});return Z(o[0])}async updateMany(t,i,r={}){await this._ctx.ensureConnected();let s=this._findAllRaw(t);if(s.length===0)return[];let{save:n,session:a}=r,{docs:o}=await this._updateCore(s,t,i,{save:n,session:a});return o.map(Z)}async _updateCore(t,i,r,{save:s,session:n}){return this._pipeline.execute({op:"update",beforeHook:"beforeUpdate",afterHook:"afterUpdate",hookPayload:{collection:this.name,filter:i,update:r},save:s,session:n,afterHookPayload:(a)=>({collection:this.name,filter:i,update:r,result:a.length===1?a[0]:a}),mutate:async(a)=>{let o=this._changelogEnabled?t.map((u)=>structuredClone(u)):t.map(()=>null),c=t.map((u)=>this._prepareUpdatedDoc(u,r));this._assertUniqueCandidates(t,c),a();let l=new Set(t),d=new Map;for(let u=0;u<this._data.length;u++)if(l.has(this._data[u]))d.set(this._data[u],u);for(let u=0;u<t.length;u++)this._commitUpdatedDoc(t[u],c[u],d);return{docs:c,prevDocs:o}}})}applyUpdate(t,i){for(let r in i){if(cn.has(r))continue;if(r==="_id"||r==="createdAt")continue;let s=i[r];if(Array.isArray(s))t[r]=s;else if(typeof s==="object"&&s!==null){let n=Object.keys(s);if(n.some((a)=>a.startsWith("$"))){for(let a of n)if(a==="$inc"&&typeof t[r]==="number")t[r]+=s[a];else if(a==="$push"){if(!Array.isArray(t[r]))t[r]=[];t[r].push(s[a])}}else t[r]=dn(s)}else t[r]=s}if(t.updatedAt=new Date,this._versioning)t._version=(t._version??0)+1;return t}_prepareUpdatedDoc(t,i){let r=structuredClone(t),s=structuredClone(t);if(this.applyUpdate(s,i),!this._schema)return s;let n=Wr(s,this._schema,this._strict);if(!n.length)return s;switch(this._onSchemaError){case"throw":throw new L("ERR_SKALEX_VALIDATION_UPDATE",`Update validation failed on doc "${t._id}": ${n.join("; ")}`,{id:t._id,errors:n});case"strip":return this._stripCandidateToValid(s,r);default:return this._ctx.logger(`[${this.name}] Update validation warning: ${n.join("; ")}`,"warn"),s}}_stripCandidateToValid(t,i){let r=Jr(t,this._schema),s=structuredClone(i);for(let[n,a]of Object.entries(r)){if(n.startsWith("_"))continue;s[n]=a}if(s.updatedAt=t.updatedAt,this._versioning)s._version=t._version;return s}_commitUpdatedDoc(t,i,r){let s=r?r.get(t):this._data.indexOf(t);if(s===void 0||s===-1)throw new Ge("ERR_SKALEX_PERSISTENCE_DOC_MISSING",`Document "${t._id}" no longer exists in collection "${this.name}"`,{id:t._id,collection:this.name});this._data[s]=i,this._index.set(i._id,i),this._updateInIndex(t,i)}_assertUniqueCandidates(t,i){this._fieldIndex?.assertUniqueCandidates(t,i)}async upsert(t,i,r={}){if(await this._ctx.ensureConnected(),this._findRaw(t))return this.updateOne(t,i,r);return this.insertOne({...Sl(t),...i},r)}async upsertMany(t,i,r={}){await this._ctx.ensureConnected();let{save:s,...n}=r,a=[];for(let o of t)a.push(await this.upsert({[i]:o[i]},o,{...n,save:!1}));return await this._saveIfNeeded(s),a}async restore(t,i={}){if(!this._softDelete)throw new ht("ERR_SKALEX_QUERY_SOFT_DELETE_REQUIRED",`restore() requires softDelete on "${this.name}"`,{collection:this.name});await this._ctx.ensureConnected();let{save:r,session:s}=i,n=this._findRaw(t,{includeDeleted:!0});if(!n||!n._deletedAt)return null;let{docs:a}=await this._pipeline.execute({op:"restore",beforeHook:null,afterHook:null,hookPayload:null,save:r,session:s,mutate:async(o)=>(o(),delete n._deletedAt,n.updatedAt=new Date,this._index.set(n._id,n),{docs:[n]})});return Z(a[0])}watch(t,i){if(typeof t==="function")i=t,t=null;if(i)return this._ctx.eventBus.on(this.name,(r)=>{if(!t||re(r.doc,t))i(r)});return this._watchIterator(t)}_watchIterator(t){let i=[],r=null,s=!1,n=this._ctx.eventBus.on(this.name,(a)=>{if(t&&!re(a.doc,t))return;if(r){let o=r;r=null,o({value:a,done:!1})}else i.push(a)});return{[Symbol.asyncIterator](){return this},next(){if(i.length>0)return Promise.resolve({value:i.shift(),done:!1});if(s)return Promise.resolve({value:void 0,done:!0});return new Promise((a)=>{r=a})},return(){if(s=!0,n(),r){let a=r;r=null,a({value:void 0,done:!0})}return Promise.resolve({value:void 0,done:!0})}}}async count(t={}){return await this._ctx.ensureConnected(),Al(this._findAllRaw(t))}async sum(t,i={}){return await this._ctx.ensureConnected(),vl(this._findAllRaw(i),t)}async avg(t,i={}){return await this._ctx.ensureConnected(),El(this._findAllRaw(i),t)}async groupBy(t,i={}){return await this._ctx.ensureConnected(),xl(this._findAllRaw(i),t)}async findOne(t,i={}){await this._ctx.ensureConnected();let{populate:r,select:s,includeDeleted:n=!1}=i,a=this._findRaw(t,{includeDeleted:n});if(!a)return null;let o=this._projectDoc(a,s);if(r)await this._populateDoc(o,a,r);return o}async find(t,i={}){await this._ctx.ensureConnected();let r=Date.now(),{populate:s,select:n,sort:a,page:o=1,limit:c,session:l,includeDeleted:d=!1}=i;await this._ctx.plugins.run("beforeFind",{collection:this.name,filter:t,options:i});let u=this._getCandidates(t),f=pl(t,this._fieldIndex?this._fieldIndex.indexedFields:new Set),h=[];for(let p of u){if(this._softDelete&&p._deletedAt&&!d)continue;if(!re(p,f))continue;let g=this._projectDoc(p,n);if(s)await this._populateDoc(g,p,s);h.push(g)}if(a){let p=Object.keys(a);h.sort((g,m)=>{for(let w of p){let v=a[w];if(g[w]<m[w])return-v;if(g[w]>m[w])return v}return 0})}let _;if(c){let p=h.length,g=Math.ceil(p/c),m=(o-1)*c;h=h.slice(m,m+c),_={page:o,totalDocs:p,totalPages:g}}return this._ctx.queryLog?.record({collection:this.name,op:"find",filter:t,duration:Date.now()-r,resultCount:h.length}),this._ctx.sessionStats.recordRead(l),await this._ctx.plugins.run("afterFind",{collection:this.name,filter:t,options:i,docs:h}),_?{docs:h,..._}:{docs:h}}async search(t,{filter:i,limit:r=10,minScore:s=0,session:n}={}){await this._ctx.ensureConnected();let a=Date.now();await this._ctx.plugins.run("beforeSearch",{collection:this.name,query:t,options:{filter:i,limit:r,minScore:s}});let o=await this._ctx.embed(t),c=i?this._findAllRaw(i):this._data,l=[];for(let h of c){if(!h._vector)continue;let _=Yr(o,h._vector);if(_>=s)l.push({doc:h,score:_})}l.sort((h,_)=>_.score-h.score);let d=l.slice(0,r);this._ctx.queryLog?.record({collection:this.name,op:"search",query:t,duration:Date.now()-a,resultCount:d.length}),this._ctx.sessionStats.recordRead(n);let u=d.map((h)=>Z(h.doc)),f=d.map((h)=>h.score);return await this._ctx.plugins.run("afterSearch",{collection:this.name,query:t,options:{filter:i,limit:r,minScore:s},docs:u,scores:f}),{docs:u,scores:f}}async similar(t,{limit:i=10,minScore:r=0}={}){await this._ctx.ensureConnected();let s=this._index.get(t);if(!s||!s._vector)return{docs:[],scores:[]};let n=[];for(let o of this._data){if(o._id===t||!o._vector)continue;let c=Yr(s._vector,o._vector);if(c>=r)n.push({doc:o,score:c})}n.sort((o,c)=>c.score-o.score);let a=n.slice(0,i);return{docs:a.map((o)=>Z(o.doc)),scores:a.map((o)=>o.score)}}async deleteOne(t,i={}){await this._ctx.ensureConnected();let{save:r,session:s}=i;if(this._softDelete){let a=this._findRaw(t);if(!a)return null;let{docs:o}=await this._deleteCore("soft",[a],t,{save:r,session:s});return Z(o[0])}let{docs:n}=await this._deleteCore("hard",null,t,{save:r,session:s});if(n.length===0)return null;return Z(n[0])}async deleteMany(t,i={}){await this._ctx.ensureConnected();let{save:r,session:s}=i;if(this._softDelete){let a=this._findAllRaw(t);if(a.length===0)return[];let{docs:o}=await this._deleteCore("soft",a,t,{save:r,session:s});return o.map(Z)}let{docs:n}=await this._deleteCore("hardMany",null,t,{save:r,session:s});return n.map(Z)}async _deleteCore(t,i,r,{save:s,session:n}){return this._pipeline.execute({op:"delete",beforeHook:"beforeDelete",afterHook:"afterDelete",hookPayload:{collection:this.name,filter:r},save:s,session:n,afterHookPayload:(a)=>({collection:this.name,filter:r,result:a.length===1?a[0]:a}),mutate:async(a)=>{if(a(),t==="soft"){let l=new Date;for(let d of i)d._deletedAt=l,d.updatedAt=l,this._index.set(d._id,d);return{docs:i}}if(t==="hard"){let l=this._findIndex(r);if(l===-1)return{docs:[]};let d=this._data.splice(l,1)[0];return this._index.delete(d._id),this._removeFromIndex(d),{docs:[d]}}let o=[],c=[];for(let l of this._data)if(re(l,r))o.push(l),this._index.delete(l._id),this._removeFromIndex(l);else c.push(l);return this._data=c,{docs:o}}})}async export(t={},i={}){let{dir:r,name:s,format:n="json"}=i;try{let a=this._data.filter((u)=>re(u,t));if(a.length===0)throw new ht("ERR_SKALEX_QUERY_EXPORT_EMPTY",`export(): no documents matched the filter in "${this.name}"`,{collection:this.name});let o;if(n==="json")o=JSON.stringify(a,null,2);else{let u=(_)=>{if(_==null)return"";let p=typeof _==="object"?JSON.stringify(_):String(_);return p.includes(",")||p.includes('"')||p.includes(`
|
|
28
|
+
`))!==-1){let r=this._buffer.slice(0,i).trim();if(this._buffer=this._buffer.slice(i+1),r&&this._onMessage){let s;try{s=JSON.parse(r)}catch(n){this.send(Ke(null,Vi,"Parse error"));continue}this._onMessage(s).catch(()=>{})}}}),process.stdin.on("end",()=>{process.exit(0)})}stop(){process.stdin.removeAllListeners("data"),process.stdin.removeAllListeners("end"),this._started=!1}}var fl={name:"skalex",version:"4.0.0-alpha"},_l="2024-11-05";class on{constructor(t,i={}){this._db=t,this._transport=i.transport||"stdio",this._port=i.port||3000,this._host=i.host||"127.0.0.1",this._allowedOrigin=i.allowedOrigin??null,this._maxBodySize=i.maxBodySize??1048576,this._scopes=i.scopes||{"*":["read"]},this._t=null}async listen(){if(this._transport==="http")this._t=new nn({port:this._port,host:this._host,allowedOrigin:this._allowedOrigin,maxBodySize:this._maxBodySize});else this._t=new an;this._t.onMessage((t)=>this._handleMessage(t)),await this._t.start()}async connect(t){if(this._t=t,this._t.onMessage((i)=>this._handleMessage(i)),typeof this._t.start==="function")await this._t.start()}async close(){if(this._t&&typeof this._t.stop==="function")await this._t.stop();this._t=null}get transport(){return this._transport}get url(){return this._t?.url}async _handleMessage(t){let{msg:i,parseError:r}=typeof t==="string"?ul(t):{msg:t};if(r){this._send(r);return}let{id:s,method:n,params:a}=i;if(s===void 0){if(n==="notifications/initialized")return;return}try{switch(n){case"initialize":this._send(yt(s,{protocolVersion:_l,capabilities:{tools:{}},serverInfo:fl}));break;case"tools/list":this._send(yt(s,{tools:this._visibleTools()}));break;case"tools/call":await this._handleToolCall(s,a);break;case"ping":this._send(yt(s,{}));break;default:this._send(Ke(s,Br,`Method not found: ${n}`))}}catch(o){this._send(Ke(s,dl,o.message||"Internal error"))}}async _handleToolCall(t,i){let r=i?.name,s=i?.arguments??{};if(!r){this._send(Ke(t,cl,"tools/call requires params.name"));return}let n=zr.find((o)=>o.name===r);if(!n){this._send(Ke(t,Br,`Unknown tool: ${r}`));return}let a=s.collection||s.collection_name||null;if(!this._hasScope(a,n.scope)){this._send(yt(t,Xr(`Access denied: "${r}" requires "${n.scope}" scope on collection "${a}".`)));return}try{let o=await ol(r,s,this._db);this._send(yt(t,hl(JSON.stringify(o,null,2))))}catch(o){this._send(yt(t,Xr(o.message||String(o))))}}_visibleTools(){return zr.filter((t)=>{let i=this._scopes["*"];if(i&&(i.includes(t.scope)||i.includes("admin")))return!0;for(let[,r]of Object.entries(this._scopes))if(r.includes(t.scope)||r.includes("admin"))return!0;return!1})}_hasScope(t,i){let r=(s)=>s.includes("admin")||s.includes(i);if(t&&this._scopes[t])return r(this._scopes[t]);if(this._scopes["*"])return r(this._scopes["*"]);return!1}_send(t){this._t?.send(t)}}var Ut="migrations",Vr=(t)=>JSON.stringify(t,function(i,r){let s=this[i];if(s instanceof Date)return{__skalex_date__:s.toISOString()};if(typeof r==="bigint")return{__skalex_bigint__:r.toString()};return r}),Gr=(t)=>JSON.parse(t,(i,r)=>{if(r&&typeof r==="object"){if("__skalex_bigint__"in r)return BigInt(r.__skalex_bigint__);if("__skalex_date__"in r)return new Date(r.__skalex_date__)}return r});class de{constructor({path:t="./.db",format:i="gz",debug:r=!1,adapter:s,ai:n,encrypt:a,slowQueryLog:o,queryCache:c,memory:l,logger:d,plugins:u,llmAdapter:f,embeddingAdapter:h,regexMaxLength:_,idGenerator:p,serializer:g,deserializer:m,autoSave:w,ttlSweepInterval:v,lenientLoad:q}={}){if(this.dataDirectory=t,this.dataFormat=i,this.debug=r,!de._errorsAttached)de.SkalexError=Je,de.ValidationError=D,de.UniqueConstraintError=De,de.TransactionError=Ce,de.PersistenceError=Ve,de.AdapterError=be,de.QueryError=ut,de._errorsAttached=!0;this._adapterConfig=s??null;let E=s||new Us({dir:t,format:i});if(a)E=new Js(E,a.key);if(this.fs=E,this._registry=new Bs(qs),this.collections=this._registry.stores,this._collectionInstances=this._registry._instances,this._migrations=new Fs,this._connectPromise=null,this.isConnected=!1,this._aiConfig=n||null,this._encryptConfig=a||null,this._pluginsConfig=Array.isArray(u)?u:null,this._memoryConfig=l||null,this._regexMaxLength=_??500,this._idGenerator=p??null,this._serializer=g??Vr,this._deserializer=m??Gr,this._autoSave=w??!1,this._txManager=new zs,this._ttlSweepInterval=v??0,this._ttlTimer=null,this._logger=d??Pr,this._embeddingAdapter=h??(n?Wo(n):null),this._aiAdapter=f??(n?Jo(n):null),this._persistence=new Ks({adapter:this.fs,serializer:this._serializer,deserializer:this._deserializer,logger:this._logger,debug:this.debug,lenientLoad:q??!1}),this._changeLog=new Qs(this),this._queryCache=new Zs(c||{}),this._eventBus=new en,this._queryLog=o?new tn(o):null,this._sessionStats=new rn,this._plugins=new sn,Array.isArray(u))for(let A of u)this._plugins.register(A)}async connect(){if(this._connectPromise)return this._connectPromise;return this._connectPromise=this._doConnect(),this._connectPromise}async _doConnect(){try{await this.loadData();let t=this._getMeta();if(t.queryCache)this._queryCache.fromJSON(t.queryCache);if(this._migrations._migrations.length>0){let i=t.appliedVersions||[],r=await this._migrations.run((s)=>this.useCollection(`_migration_${s}`),i);this._saveMeta({appliedVersions:r})}if(this._sweepTtl(),this._ttlSweepInterval>0){if(this._ttlTimer=setInterval(()=>this._sweepTtl(),this._ttlSweepInterval),this._ttlTimer?.unref)this._ttlTimer.unref()}this.isConnected=!0,this._log("> - Connected to the database (\u221A)")}catch(t){throw this._logger(`Error connecting to the database: ${t}`,"error"),t}}async disconnect(){try{if(this._ttlTimer)clearInterval(this._ttlTimer),this._ttlTimer=null;await this.saveData(),this._registry.clear(),this.collections=this._registry.stores,this._collectionInstances=this._registry._instances,this._connectPromise=null,this.isConnected=!1,this._log("> - Disconnected from the database (\u221A)")}catch(t){throw this._logger(`Error disconnecting from the database: ${t}`,"error"),t}}async _ensureConnected(){if(this.isConnected)return;return this.connect()}useCollection(t){return this._registry.get(t,this)}createCollection(t,i={}){return this._registry.create(t,i,this)}_createCollectionStore(t,i={}){this._registry.createStore(t,i)}async renameCollection(t,i){this._registry.rename(t,i),await this.saveData(i),await this.fs.delete(t)}async loadData(){await this._persistence.loadAll(this.collections,{parseSchema:Ls,buildIndex:this._registry.buildIndex,IndexEngine:Yt});for(let t in this._collectionInstances){let i=this.collections[t];if(i&&this._collectionInstances[t]._store!==i)this._collectionInstances[t]._store=i}}async saveData(t){await this._persistence.save(this.collections,t)}buildIndex(t,i){return this._registry.buildIndex(t,i)}addMigration(t){this._migrations.add(t)}migrationStatus(){let t=this._getMeta();return this._migrations.status(t.appliedVersions||[])}namespace(t){if(this._adapterConfig)throw new be("ERR_SKALEX_ADAPTER_NAMESPACE_REQUIRES_FS","namespace() requires the default FsAdapter. When a custom storage adapter is configured, create a separate Skalex instance with your adapter instead.");let i=String(t).replace(/[^a-zA-Z0-9_-]/g,"_");if(!i)throw new D("ERR_SKALEX_VALIDATION_NAMESPACE_ID","namespace: id must contain at least one alphanumeric character",{id:t});return new de({path:`${this.dataDirectory}/${i}`,format:this.dataFormat,debug:this.debug,ai:this._aiConfig||void 0,encrypt:this._encryptConfig||void 0,slowQueryLog:this._queryLog?{threshold:this._queryLog._threshold,maxEntries:this._queryLog._maxEntries}:void 0,queryCache:this._queryCache?{maxSize:this._queryCache._maxSize,ttl:this._queryCache._ttl}:void 0,plugins:this._pluginsConfig||void 0,memory:this._memoryConfig||void 0,logger:this._logger!==Pr?this._logger:void 0,llmAdapter:this._aiAdapter&&!this._aiConfig?this._aiAdapter:void 0,embeddingAdapter:this._embeddingAdapter&&!this._aiConfig?this._embeddingAdapter:void 0,regexMaxLength:this._regexMaxLength!==500?this._regexMaxLength:void 0,idGenerator:this._idGenerator||void 0,serializer:this._serializer!==Vr?this._serializer:void 0,deserializer:this._deserializer!==Gr?this._deserializer:void 0,autoSave:this._autoSave||void 0,ttlSweepInterval:this._ttlSweepInterval||void 0})}use(t){this._plugins.register(t)}watch(t){return this._eventBus.on("*",t)}sessionStats(t){if(t!==void 0)return this._sessionStats.get(t);return this._sessionStats.all()}get _inTransaction(){return this._txManager.active}_emitEvent(t,i){if(!this._txManager.defer(()=>this._eventBus.emit(t,i)))this._eventBus.emit(t,i)}async _runAfterHook(t,i){if(!this._txManager.defer(()=>this._plugins.run(t,i)))await this._plugins.run(t,i)}async _logChange(t,i,r,s,n){if(!this._txManager.defer(()=>this._changeLog.log(t,i,r,s,n)))await this._changeLog.log(t,i,r,s,n)}async transaction(t,i={}){return this._txManager.run(t,this,i)}async seed(t,{reset:i=!1}={}){for(let[r,s]of Object.entries(t)){if(i&&this.collections[r])this._applySnapshot(r,{data:[],index:new Map}),delete this._collectionInstances[r];await this.useCollection(r).insertMany(s)}await this.saveData()}dump(){return this._registry.dump()}inspect(t){return this._registry.inspect(t)}async import(t){let i=await this.fs.readRaw(t),r;try{r=JSON.parse(i)}catch{throw new Ve("ERR_SKALEX_PERSISTENCE_INVALID_JSON",`import: invalid JSON in file "${t}"`,{filePath:t})}let s=t.split("/").pop().replace(/\.[^.]+$/,"");return this.useCollection(s).insertMany(Array.isArray(r)?r:[r],{save:!0})}async embed(t){if(!this._embeddingAdapter)throw new be("ERR_SKALEX_ADAPTER_EMBEDDING_REQUIRED","db.embed() requires an AI adapter. Pass { ai: { provider, apiKey } } to the Skalex constructor.");return this._embeddingAdapter.embed(t)}async ask(t,i,{limit:r=20}={}){if(!this._aiAdapter)throw new be("ERR_SKALEX_ADAPTER_LLM_REQUIRED",'db.ask() requires a language model adapter. Configure { ai: { provider, model: "..." } }.');let s=this.useCollection(t),n=this.schema(t),a=this._queryCache.get(t,n,i);if(!a){a=await this._aiAdapter.generate(n,i);let o=al(a,n);if(o.length)o.forEach((c)=>this._log(`[ask] ${c}`));this._queryCache.set(t,n,i,a),this._saveMeta({queryCache:this._queryCache.toJSON()})}return s.find(sl(a,{regexMaxLength:this._regexMaxLength}),{limit:r})}schema(t){return this._registry.schema(t)}useMemory(t){return new Ys(t,this)}changelog(){return this._changeLog}async restore(t,i,r={}){return this._changeLog.restore(t,i,r)}stats(t){return this._registry.stats(t)}slowQueries(t={}){if(!this._queryLog)return[];return this._queryLog.entries(t)}slowQueryCount(){return this._queryLog?this._queryLog.size:0}clearSlowQueries(){this._queryLog?.clear()}mcp(t={}){return new on(this,t)}_getMeta(){let t=this.collections._meta;if(!t)return{};return t.index.get(Ut)||{}}_saveMeta(t){if(!this.collections._meta)this._createCollectionStore("_meta");let i=this.collections._meta,r=i.index.get(Ut);if(r)Object.assign(r,t);else{let s={_id:Ut,...t};i.data.push(s),i.index.set(Ut,s)}this._persistence.markDirty(this.collections,"_meta")}_sweepTtl(){for(let t in this.collections){let i=this.collections[t],r=Ko(i.data,i.index,i.fieldIndex?(s)=>i.fieldIndex.remove(s):null);if(r>0)this._persistence.markDirty(this.collections,t),this._log(`TTL sweep: removed ${r} expired docs from "${t}"`)}}_buildCollectionContext(){let t=this;return{ensureConnected:()=>t._ensureConnected(),get txManager(){return t._txManager},get plugins(){return t._plugins},get eventBus(){return t._eventBus},get sessionStats(){return t._sessionStats},get queryLog(){return t._queryLog},get logger(){return t._logger},get persistence(){return t._persistence},get collections(){return t.collections},embed:(i)=>t.embed(i),get idGenerator(){return t._idGenerator},get autoSave(){return t._autoSave},saveCollection:(i)=>t.saveData(i),snapshotCollection:(i)=>t._snapshotCollection(i),getCollection:(i)=>t.useCollection(i),emitEvent:(i,r)=>t._emitEvent(i,r),runAfterHook:(i,r)=>t._runAfterHook(i,r),logChange:(i,r,s,n,a)=>t._logChange(i,r,s,n,a),get fs(){return t.fs},get dataDirectory(){return t.dataDirectory}}}_log(t){if(this.debug)this._logger(t,"info")}_snapshotCollection(t){return{data:structuredClone(t.data)}}_applySnapshot(t,i){let r=this.collections[t];if(!r)return;if(r.data=i.data,r.index=this.buildIndex(i.data,"_id"),r.fieldIndex)r.fieldIndex.buildFromData(i.data)}}function pl(){let t=Date.now().toString(16),i;try{i=mo.randomBytes(8).toString("hex")}catch{let r=new Uint8Array(8);crypto.getRandomValues(r),i=Array.from(r).map((s)=>s.toString(16).padStart(2,"0")).join("")}return`${t}${i}`}function Hr(t,i){let r=t instanceof Error?t.message:t;if(i==="error")console.error(r);else console.log(r)}var Wr=new Set(["__proto__","constructor","prototype"]);function ri(t,i){if(!i.includes(".")){if(Wr.has(i))return;return t[i]}let r=t;for(let s of i.split(".")){if(Wr.has(s))return;if(r==null)return;r=r[s]}return r}class Ye extends Error{constructor(t,i,r={}){super(i);this.name=this.constructor.name,this.code=t,this.details=r}}class L extends Ye{}class Pe extends Ye{}class Ne extends Ye{}class Ge extends Ye{}class Te extends Ye{}class ht extends Ye{}function Di(t,i){if(t===i)return!0;if(t==null||i==null)return!1;if(typeof t!==typeof i)return!1;if(t instanceof Date&&i instanceof Date)return t.getTime()===i.getTime();if(t instanceof RegExp&&i instanceof RegExp)return t.source===i.source&&t.flags===i.flags;if(Array.isArray(t)){if(!Array.isArray(i)||t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Di(t[r],i[r]))return!1;return!0}if(typeof t==="object"){if(Array.isArray(i))return!1;let r=Object.keys(t);if(r.length!==Object.keys(i).length)return!1;for(let s of r){if(!Object.prototype.hasOwnProperty.call(i,s))return!1;if(!Di(t[s],i[s]))return!1}return!0}return!1}function re(t,i){if(typeof i==="function")return i(t);if(i==null)return!0;if(typeof i==="object"&&Object.keys(i).length===0)return!0;if("$or"in i){let r=i.$or;if(!Array.isArray(r))throw new ht("ERR_SKALEX_QUERY_INVALID_OPERATOR","$or must be an array of filters",{operator:"$or"});if(!r.some((s)=>re(t,s)))return!1}if("$and"in i){let r=i.$and;if(!Array.isArray(r))throw new ht("ERR_SKALEX_QUERY_INVALID_OPERATOR","$and must be an array of filters",{operator:"$and"});if(!r.every((s)=>re(t,s)))return!1}if("$not"in i){if(re(t,i.$not))return!1}for(let r in i){if(r==="$or"||r==="$and"||r==="$not")continue;let s=i[r],n;try{n=ri(t,r)}catch{return!1}if(s instanceof RegExp){if(!s.test(String(n)))return!1}else if(typeof s==="object"&&s!==null){if(Object.keys(s).some((a)=>a.startsWith("$"))){if("$eq"in s&&n!==s.$eq)return!1;if("$ne"in s&&n===s.$ne)return!1;if("$gt"in s&&!(n>s.$gt))return!1;if("$lt"in s&&!(n<s.$lt))return!1;if("$gte"in s&&!(n>=s.$gte))return!1;if("$lte"in s&&!(n<=s.$lte))return!1;if("$in"in s&&!s.$in.includes(n))return!1;if("$nin"in s&&s.$nin.includes(n))return!1;if("$regex"in s){if(!(s.$regex instanceof RegExp?s.$regex:new RegExp(s.$regex)).test(String(n)))return!1}if("$fn"in s&&!s.$fn(n))return!1}else if(!Di(n,s))return!1}else if(n!==s)return!1}return!0}function gl(t,i=new Set){if(typeof t!=="object"||t===null||typeof t==="function")return t;let r=[],s=[],n=[],a=[],o=[];for(let l in t){if(l==="$or"||l==="$and"||l==="$not"){o.push(l);continue}let d=t[l];if(i.has(l))r.push(l);else if(d instanceof RegExp||typeof d==="object"&&d!==null&&(("$regex"in d)||("$fn"in d))||typeof d==="function")a.push(l);else if(typeof d==="object"&&d!==null&&(("$gt"in d)||("$lt"in d)||("$gte"in d)||("$lte"in d)||("$ne"in d)||("$in"in d)||("$nin"in d)))n.push(l);else s.push(l)}let c={};for(let l of[...r,...s,...n,...a,...o])c[l]=t[l];return c}var Li=new Set(["string","number","boolean","object","array","date","any"]);function Gi(t){if(Array.isArray(t))return"array";if(t instanceof Date)return"date";return typeof t}function ln(t){let i=new Map,r=[];for(let[s,n]of Object.entries(t)){let a;if(typeof n==="string"){if(!Li.has(n))throw new L("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${n}" for field "${s}"`,{field:s,type:n});a={type:n,required:!1,unique:!1}}else if(typeof n==="object"&&n!==null){let{type:o="any",required:c=!1,unique:l=!1,enum:d}=n;if(!Li.has(o))throw new L("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${o}" for field "${s}"`,{field:s,type:o});if(a={type:o,required:c,unique:l,enum:d},l)r.push(s)}else throw new L("ERR_SKALEX_VALIDATION_INVALID_SCHEMA",`Invalid schema definition for field "${s}"`,{field:s});i.set(s,a)}return{fields:i,uniqueFields:r}}function Jr(t,i,r=!1){let s=[];for(let[n,a]of i){let o=t[n],c=o===void 0||o===null;if(a.required&&c){s.push(`Field "${n}" is required`);continue}if(c)continue;if(a.type!=="any"){let l=Gi(o);if(l!==a.type)s.push(`Field "${n}" must be of type "${a.type}", got "${l}"`)}if(a.enum&&!a.enum.includes(o))s.push(`Field "${n}" must be one of [${a.enum.map((l)=>JSON.stringify(l)).join(", ")}], got ${JSON.stringify(o)}`)}if(r){for(let n of Object.keys(t))if(!n.startsWith("_")&&!i.has(n))s.push(`Unknown field "${n}" (strict mode)`)}return s}function Yr(t,i){let r={};for(let[s,n]of Object.entries(t)){if(s.startsWith("_")){r[s]=n;continue}if(!i.has(s))continue;let a=i.get(s);if(a.type!=="any"){if(Gi(n)!==a.type)continue}if(a.enum&&!a.enum.includes(n))continue;r[s]=n}return r}function ml(t){let i={};for(let[r,s]of Object.entries(t)){if(r.startsWith("_"))continue;let n=Gi(s);i[r]=Li.has(n)?n:"any"}return i}function yl(t){if(typeof t==="number"){if(t<=0)throw new L("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got ${t}`,{ttl:t});return t*1000}if(typeof t!=="string")throw new L("ERR_SKALEX_VALIDATION_TTL",`Invalid TTL value: ${t}`,{ttl:t});let i=t.match(/^(\d+(?:\.\d+)?)(ms|s|m|h|d)$/);if(!i)throw new L("ERR_SKALEX_VALIDATION_TTL_FORMAT",`Invalid TTL format: "${t}". Use e.g. 300 (seconds), "30m", "24h", "7d"`,{ttl:t});let r=parseFloat(i[1]);if(r<=0)throw new L("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got "${t}"`,{ttl:t});let s=i[2],n=r*{ms:1,s:1000,m:60000,h:3600000,d:86400000}[s];if(!isFinite(n))throw new L("ERR_SKALEX_VALIDATION_TTL",`TTL value "${t}" is too large`,{ttl:t});return n}function wl(t){return new Date(Date.now()+yl(t))}function Al(t,i,r=null){let s=Date.now(),n=0,a=t.length;while(a--){let o=t[a];if(o._expiresAt&&new Date(o._expiresAt).getTime()<=s){if(t.splice(a,1),i.delete(o._id),r)r(o);n++}}return n}function Qr(t,i){if(t.length!==i.length)throw new ht("ERR_SKALEX_QUERY_VECTOR_MISMATCH",`Vector dimension mismatch: ${t.length} vs ${i.length}`,{expected:t.length,got:i.length});let r=0,s=0,n=0;for(let o=0;o<t.length;o++)r+=t[o]*i[o],s+=t[o]*t[o],n+=i[o]*i[o];let a=Math.sqrt(s*n);return a===0?0:r/a}function Z(t){if(!("_vector"in t))return{...t};let{_vector:i,...r}=t;return r}function vl(t){return t.length}function El(t,i){let r=0;for(let s of t){let n=ri(s,i);if(typeof n==="number"&&!isNaN(n))r+=n}return r}function xl(t,i){let r=0,s=0;for(let n of t){let a=ri(n,i);if(typeof a==="number"&&!isNaN(a))r+=a,s++}return s===0?null:r/s}function Sl(t,i){let r=Object.create(null);for(let s of t){let n=String(ri(s,i)??"__null__");if(!r[n])r[n]=[];r[n].push(s)}return r}class cn{constructor(t){this._col=t}get _ctx(){return this._col._ctx}async execute({op:t,beforeHook:i,afterHook:r,hookPayload:s,mutate:n,afterHookPayload:a,save:o,session:c}){let l=this._ctx;await l.ensureConnected(),this._col._txSnapshotIfNeeded();let d=l.txManager,u=d.active&&this._col._activeTxId===d.context?.id,f=u?d.context.id:null,h=this._col._createdInTxId,_=()=>{if(f!==null&&d._abortedIds.has(f))throw new Ne("ERR_SKALEX_TX_ABORTED",`Transaction ${f} was aborted. No further mutations allowed.`);if(h!==null&&d._abortedIds.has(h))throw new Ne("ERR_SKALEX_TX_ABORTED",`Transaction ${h} was aborted. Collection obtained inside that transaction cannot be used for further mutations.`)};if(u||h!==null)_();if(i)await l.plugins.run(i,s);let{docs:p,prevDocs:g=[]}=await n(_);if(l.persistence.markDirty(l.collections,this._col.name),await this._col._saveIfNeeded(o),this._col._changelogEnabled)for(let m=0;m<p.length;m++)await l.logChange(t,this._col.name,p[m],g[m]??null,c||null);if(!u||!d.defer(()=>l.sessionStats.recordWrite(c)))l.sessionStats.recordWrite(c);for(let m of p)l.emitEvent(this._col.name,{op:t,collection:this._col.name,doc:Z(m)});if(r)if(a)await l.runAfterHook(r,a(p));else for(let m of p)await l.runAfterHook(r,{collection:this._col.name,doc:Z(m)});return{docs:p,prevDocs:g}}}function Il(t){let i={};for(let r in t){if(r.startsWith("$"))continue;let s=t[r];if(s&&typeof s==="object"&&!Array.isArray(s)){let n=Object.keys(s);if(n.length===1&&n[0]==="$eq")i[r]=s.$eq}else i[r]=s}return i}var dn=new Set(["__proto__","constructor","prototype"]);function un(t){if(typeof t!=="object"||t===null||Array.isArray(t))return t;let i={};for(let r of Object.keys(t)){if(dn.has(r))continue;i[r]=un(t[r])}return i}class hn{constructor(t,i){this.name=t.collectionName,this.database=i,this._ctx=i._buildCollectionContext(),this._store=t,this._pipeline=new cn(this),this._createdInTxId=i._txManager.context?.id??null,this._activeTxId=null}get _data(){return this._store.data}set _data(t){this._store.data=t}get _index(){return this._store.index}get _fieldIndex(){return this._store.fieldIndex||null}get _schema(){return this._store.schema?this._store.schema.fields:null}get _changelogEnabled(){return this._store.changelog===!0}get _softDelete(){return this._store.softDelete===!0}get _versioning(){return this._store.versioning===!0}get _strict(){return this._store.strict===!0}get _onSchemaError(){return this._store.onSchemaError??"throw"}get _defaultTtl(){return this._store.defaultTtl||null}get _defaultEmbed(){return this._store.defaultEmbed||null}get _maxDocs(){return this._store.maxDocs||null}async insertOne(t,i={}){let{save:r,ifNotExists:s,ttl:n,embed:a,session:o}=i;if(s){await this._ctx.ensureConnected();let l=this._findRaw(t);if(l)return Z({...l})}let{docs:c}=await this._insertCore([t],{ttl:n,embed:a,session:o,save:r});return Z(c[0])}async insertMany(t,i={}){let{save:r,ttl:s,embed:n,session:a}=i,{docs:o}=await this._insertCore(t,{ttl:s,embed:n,session:a,save:r});return o.map(Z)}async _insertCore(t,{ttl:i,embed:r,session:s,save:n}){return this._pipeline.execute({op:"insert",beforeHook:null,afterHook:"afterInsert",hookPayload:null,save:n,session:s,mutate:async(a)=>{let o=[],c=new Set;for(let l of t){let d=this._applyValidation(l);await this._ctx.plugins.run("beforeInsert",{collection:this.name,doc:d});let u=await this._buildDoc(d,{ttl:i,embed:r});if(this._index.has(u._id)||c.has(u._id))throw new Pe("ERR_SKALEX_UNIQUE_DUPLICATE_ID",`Duplicate _id "${u._id}" in collection "${this.name}"`,{id:u._id,collection:this.name});c.add(u._id),o.push(u)}if(a(),this._fieldIndex)this._fieldIndex.assertUniqueBatch(o);for(let l of o)this._addToIndex(l);this._data.push(...o);for(let l of o)this._index.set(l._id,l);return this._enforceCapAfterInsert(),{docs:o}}})}async updateOne(t,i,r={}){await this._ctx.ensureConnected();let s=this._findRaw(t);if(!s)return null;let{save:n,session:a}=r,{docs:o}=await this._updateCore([s],t,i,{save:n,session:a});return Z(o[0])}async updateMany(t,i,r={}){await this._ctx.ensureConnected();let s=this._findAllRaw(t);if(s.length===0)return[];let{save:n,session:a}=r,{docs:o}=await this._updateCore(s,t,i,{save:n,session:a});return o.map(Z)}async _updateCore(t,i,r,{save:s,session:n}){return this._pipeline.execute({op:"update",beforeHook:"beforeUpdate",afterHook:"afterUpdate",hookPayload:{collection:this.name,filter:i,update:r},save:s,session:n,afterHookPayload:(a)=>({collection:this.name,filter:i,update:r,result:a.length===1?a[0]:a}),mutate:async(a)=>{let o=this._changelogEnabled?t.map((u)=>structuredClone(u)):t.map(()=>null),c=t.map((u)=>this._prepareUpdatedDoc(u,r));this._assertUniqueCandidates(t,c),a();let l=new Set(t),d=new Map;for(let u=0;u<this._data.length;u++)if(l.has(this._data[u]))d.set(this._data[u],u);for(let u=0;u<t.length;u++)this._commitUpdatedDoc(t[u],c[u],d);return{docs:c,prevDocs:o}}})}applyUpdate(t,i){for(let r in i){if(dn.has(r))continue;if(r==="_id"||r==="createdAt")continue;let s=i[r];if(Array.isArray(s))t[r]=s;else if(typeof s==="object"&&s!==null){let n=Object.keys(s);if(n.some((a)=>a.startsWith("$"))){for(let a of n)if(a==="$inc"&&typeof t[r]==="number")t[r]+=s[a];else if(a==="$push"){if(!Array.isArray(t[r]))t[r]=[];t[r].push(s[a])}}else t[r]=un(s)}else t[r]=s}if(t.updatedAt=new Date,this._versioning)t._version=(t._version??0)+1;return t}_prepareUpdatedDoc(t,i){let r=structuredClone(t),s=structuredClone(t);if(this.applyUpdate(s,i),!this._schema)return s;let n=Jr(s,this._schema,this._strict);if(!n.length)return s;switch(this._onSchemaError){case"throw":throw new L("ERR_SKALEX_VALIDATION_UPDATE",`Update validation failed on doc "${t._id}": ${n.join("; ")}`,{id:t._id,errors:n});case"strip":return this._stripCandidateToValid(s,r);default:return this._ctx.logger(`[${this.name}] Update validation warning: ${n.join("; ")}`,"warn"),s}}_stripCandidateToValid(t,i){let r=Yr(t,this._schema),s=structuredClone(i);for(let[n,a]of Object.entries(r)){if(n.startsWith("_"))continue;s[n]=a}if(s.updatedAt=t.updatedAt,this._versioning)s._version=t._version;return s}_commitUpdatedDoc(t,i,r){let s=r?r.get(t):this._data.indexOf(t);if(s===void 0||s===-1)throw new Ge("ERR_SKALEX_PERSISTENCE_DOC_MISSING",`Document "${t._id}" no longer exists in collection "${this.name}"`,{id:t._id,collection:this.name});this._data[s]=i,this._index.set(i._id,i),this._updateInIndex(t,i)}_assertUniqueCandidates(t,i){this._fieldIndex?.assertUniqueCandidates(t,i)}async upsert(t,i,r={}){if(await this._ctx.ensureConnected(),this._findRaw(t))return this.updateOne(t,i,r);return this.insertOne({...Il(t),...i},r)}async upsertMany(t,i,r={}){await this._ctx.ensureConnected();let{save:s,...n}=r,a=[];for(let o of t)a.push(await this.upsert({[i]:o[i]},o,{...n,save:!1}));return await this._saveIfNeeded(s),a}async restore(t,i={}){if(!this._softDelete)throw new ht("ERR_SKALEX_QUERY_SOFT_DELETE_REQUIRED",`restore() requires softDelete on "${this.name}"`,{collection:this.name});await this._ctx.ensureConnected();let{save:r,session:s}=i,n=this._findRaw(t,{includeDeleted:!0});if(!n||!n._deletedAt)return null;let{docs:a}=await this._pipeline.execute({op:"restore",beforeHook:null,afterHook:null,hookPayload:null,save:r,session:s,mutate:async(o)=>(o(),delete n._deletedAt,n.updatedAt=new Date,this._index.set(n._id,n),{docs:[n]})});return Z(a[0])}watch(t,i){if(typeof t==="function")i=t,t=null;if(i)return this._ctx.eventBus.on(this.name,(r)=>{if(!t||re(r.doc,t))i(r)});return this._watchIterator(t)}_watchIterator(t){let i=[],r=null,s=!1,n=this._ctx.eventBus.on(this.name,(a)=>{if(t&&!re(a.doc,t))return;if(r){let o=r;r=null,o({value:a,done:!1})}else i.push(a)});return{[Symbol.asyncIterator](){return this},next(){if(i.length>0)return Promise.resolve({value:i.shift(),done:!1});if(s)return Promise.resolve({value:void 0,done:!0});return new Promise((a)=>{r=a})},return(){if(s=!0,n(),r){let a=r;r=null,a({value:void 0,done:!0})}return Promise.resolve({value:void 0,done:!0})}}}async count(t={}){return await this._ctx.ensureConnected(),vl(this._findAllRaw(t))}async sum(t,i={}){return await this._ctx.ensureConnected(),El(this._findAllRaw(i),t)}async avg(t,i={}){return await this._ctx.ensureConnected(),xl(this._findAllRaw(i),t)}async groupBy(t,i={}){return await this._ctx.ensureConnected(),Sl(this._findAllRaw(i),t)}async findOne(t,i={}){await this._ctx.ensureConnected();let{populate:r,select:s,includeDeleted:n=!1}=i,a=this._findRaw(t,{includeDeleted:n});if(!a)return null;let o=this._projectDoc(a,s);if(r)await this._populateDoc(o,a,r);return o}async find(t,i={}){await this._ctx.ensureConnected();let r=Date.now(),{populate:s,select:n,sort:a,page:o=1,limit:c,session:l,includeDeleted:d=!1}=i;await this._ctx.plugins.run("beforeFind",{collection:this.name,filter:t,options:i});let u=this._getCandidates(t),f=gl(t,this._fieldIndex?this._fieldIndex.indexedFields:new Set),h=[];for(let p of u){if(this._softDelete&&p._deletedAt&&!d)continue;if(!re(p,f))continue;let g=this._projectDoc(p,n);if(s)await this._populateDoc(g,p,s);h.push(g)}if(a){let p=Object.keys(a);h.sort((g,m)=>{for(let w of p){let v=a[w];if(g[w]<m[w])return-v;if(g[w]>m[w])return v}return 0})}let _;if(c){let p=h.length,g=Math.ceil(p/c),m=(o-1)*c;h=h.slice(m,m+c),_={page:o,totalDocs:p,totalPages:g}}return this._ctx.queryLog?.record({collection:this.name,op:"find",filter:t,duration:Date.now()-r,resultCount:h.length}),this._ctx.sessionStats.recordRead(l),await this._ctx.plugins.run("afterFind",{collection:this.name,filter:t,options:i,docs:h}),_?{docs:h,..._}:{docs:h}}async search(t,{filter:i,limit:r=10,minScore:s=0,session:n}={}){await this._ctx.ensureConnected();let a=Date.now();await this._ctx.plugins.run("beforeSearch",{collection:this.name,query:t,options:{filter:i,limit:r,minScore:s}});let o=await this._ctx.embed(t),c=i?this._findAllRaw(i):this._data,l=[];for(let h of c){if(!h._vector)continue;let _=Qr(o,h._vector);if(_>=s)l.push({doc:h,score:_})}l.sort((h,_)=>_.score-h.score);let d=l.slice(0,r);this._ctx.queryLog?.record({collection:this.name,op:"search",query:t,duration:Date.now()-a,resultCount:d.length}),this._ctx.sessionStats.recordRead(n);let u=d.map((h)=>Z(h.doc)),f=d.map((h)=>h.score);return await this._ctx.plugins.run("afterSearch",{collection:this.name,query:t,options:{filter:i,limit:r,minScore:s},docs:u,scores:f}),{docs:u,scores:f}}async similar(t,{limit:i=10,minScore:r=0}={}){await this._ctx.ensureConnected();let s=this._index.get(t);if(!s||!s._vector)return{docs:[],scores:[]};let n=[];for(let o of this._data){if(o._id===t||!o._vector)continue;let c=Qr(s._vector,o._vector);if(c>=r)n.push({doc:o,score:c})}n.sort((o,c)=>c.score-o.score);let a=n.slice(0,i);return{docs:a.map((o)=>Z(o.doc)),scores:a.map((o)=>o.score)}}async deleteOne(t,i={}){await this._ctx.ensureConnected();let{save:r,session:s}=i;if(this._softDelete){let a=this._findRaw(t);if(!a)return null;let{docs:o}=await this._deleteCore("soft",[a],t,{save:r,session:s});return Z(o[0])}let{docs:n}=await this._deleteCore("hard",null,t,{save:r,session:s});if(n.length===0)return null;return Z(n[0])}async deleteMany(t,i={}){await this._ctx.ensureConnected();let{save:r,session:s}=i;if(this._softDelete){let a=this._findAllRaw(t);if(a.length===0)return[];let{docs:o}=await this._deleteCore("soft",a,t,{save:r,session:s});return o.map(Z)}let{docs:n}=await this._deleteCore("hardMany",null,t,{save:r,session:s});return n.map(Z)}async _deleteCore(t,i,r,{save:s,session:n}){return this._pipeline.execute({op:"delete",beforeHook:"beforeDelete",afterHook:"afterDelete",hookPayload:{collection:this.name,filter:r},save:s,session:n,afterHookPayload:(a)=>({collection:this.name,filter:r,result:a.length===1?a[0]:a}),mutate:async(a)=>{if(a(),t==="soft"){let l=new Date;for(let d of i)d._deletedAt=l,d.updatedAt=l,this._index.set(d._id,d);return{docs:i}}if(t==="hard"){let l=this._findIndex(r);if(l===-1)return{docs:[]};let d=this._data.splice(l,1)[0];return this._index.delete(d._id),this._removeFromIndex(d),{docs:[d]}}let o=[],c=[];for(let l of this._data)if(re(l,r))o.push(l),this._index.delete(l._id),this._removeFromIndex(l);else c.push(l);return this._data=c,{docs:o}}})}async export(t={},i={}){let{dir:r,name:s,format:n="json"}=i;try{let a=this._data.filter((u)=>re(u,t));if(a.length===0)throw new ht("ERR_SKALEX_QUERY_EXPORT_EMPTY",`export(): no documents matched the filter in "${this.name}"`,{collection:this.name});let o;if(n==="json")o=JSON.stringify(a,null,2);else{let u=(_)=>{if(_==null)return"";let p=typeof _==="object"?JSON.stringify(_):String(_);return p.includes(",")||p.includes('"')||p.includes(`
|
|
29
29
|
`)||p.includes("\r")?`"${p.replace(/"/g,'""')}"`:p},f=Object.keys(a[0]).map(u).join(","),h=a.map((_)=>Object.values(_).map(u).join(","));o=[f,...h].join(`
|
|
30
|
-
`)}if(typeof this._ctx.fs.writeRaw!=="function")throw new Ie("ERR_SKALEX_ADAPTER_NO_RAW_WRITE","export() requires a file-system adapter (FsAdapter). The current adapter does not support raw file writes.");let c=r||`${this._ctx.dataDirectory}/exports`,l=`${s||this.name}.${n}`,d=this._ctx.fs.join(c,l);this._ctx.fs.ensureDir(c),await this._ctx.fs.writeRaw(d,o)}catch(a){throw this._ctx.logger(`Error exporting "${this.name}": ${a.message}`,"error"),a}}_txSnapshotIfNeeded(){let t=this._ctx.txManager;if(!t.active)return;if(this._activeTxId!==t.context?.id)return;t.snapshotIfNeeded(this.name,this._store,(i)=>this._ctx.snapshotCollection(i))}async _saveIfNeeded(t){let i=this._ctx.txManager;if(i.active&&this._activeTxId===i.context?.id)return;if(t??this._ctx.autoSave)await this._ctx.saveCollection(this.name)}_applyValidation(t){if(!this._schema)return t;let i=Wr(t,this._schema,this._strict);if(!i.length)return t;switch(this._onSchemaError){case"warn":return this._ctx.logger(`[${this.name}] Validation warning: ${i.join("; ")}`,"warn"),t;case"strip":return Jr(t,this._schema);default:throw new L("ERR_SKALEX_VALIDATION_FAILED",`Validation failed: ${i.join("; ")}`,{errors:i})}}_enforceCapAfterInsert(){let t=this._maxDocs;if(!t||this._data.length<=t)return;let i=this._data.splice(0,this._data.length-t);for(let r of i)this._index.delete(r._id),this._removeFromIndex(r)}_findRaw(t,{includeDeleted:i=!1}={}){if(typeof t==="function"){for(let r of this._data){if(this._softDelete&&r._deletedAt&&!i)continue;if(t(r))return r}return null}if(t._id){let r=this._index.get(t._id)||null;if(!r)return null;if(this._softDelete&&r._deletedAt&&!i)return null;if(Object.keys(t).length>1)return re(r,t)?r:null;return r}if(this._fieldIndex)for(let r in t){if(r==="$or"||r==="$and"||r==="$not")continue;let s=t[r];if(typeof s!=="object"||s===null){let n=this._fieldIndex._lookupIterable(r,s);if(n!==null){for(let a of n){if(this._softDelete&&a._deletedAt&&!i)continue;if(re(a,t))return a}return null}}}for(let r of this._data){if(this._softDelete&&r._deletedAt&&!i)continue;if(re(r,t))return r}return null}_findAllRaw(t,{includeDeleted:i=!1}={}){if(t&&typeof t!=="function"&&t._id){let s=this._index.get(t._id);if(!s)return[];if(this._softDelete&&s._deletedAt&&!i)return[];return re(s,t)?[s]:[]}let r=[];for(let s of this._getCandidates(t)){if(this._softDelete&&s._deletedAt&&!i)continue;if(re(s,t))r.push(s)}return r}_getCandidates(t){if(!this._fieldIndex)return this._data;if(this._fieldIndex._compoundIndexes.size>0){let i={};for(let r in t){if(r==="$or"||r==="$and"||r==="$not")continue;let s=t[r];if(typeof s!=="object"||s===null)i[r]=s}if(Object.keys(i).length>=2){let r=this._fieldIndex.lookupCompound(i);if(r!==null)return r}}for(let i in t){if(i==="$or"||i==="$and"||i==="$not")continue;let r=t[i];if(typeof r!=="object"||r===null){let s=this._fieldIndex._lookupIterable(i,r);if(s!==null)return s}}return this._data}_findIndex(t){for(let i=0;i<this._data.length;i++)if(re(this._data[i],t))return i;return-1}_addToIndex(t){if(this._fieldIndex)this._fieldIndex.add(t)}_removeFromIndex(t){if(this._fieldIndex)this._fieldIndex.remove(t)}_updateInIndex(t,i){if(this._fieldIndex)this._fieldIndex.update(t,i)}async _buildDoc(t,{ttl:i,embed:r}={}){let s={...t,_id:t._id??(this._ctx.idGenerator??_l)(),createdAt:new Date,updatedAt:new Date},n=i??this._defaultTtl;if(n)s._expiresAt=yl(n);let a=r??this._defaultEmbed;if(a){let o=typeof a==="function"?a(s):s[a];s._vector=await this._ctx.embed(String(o))}if(this._versioning)s._version=1;return s}_projectDoc(t,i){if(i){let s={};for(let n of i){if(n==="_vector")continue;s[n]=t[n]}return s}let r={...t};return delete r._vector,r}async _populateDoc(t,i,r){for(let s of r){let n=await this._ctx.getCollection(s).findOne({_id:i[s]});if(n)t[s]=n}}}class Yi{async read(t){throw Error("StorageAdapter.read() not implemented")}async write(t,i){throw Error("StorageAdapter.write() not implemented")}async delete(t){throw Error("StorageAdapter.delete() not implemented")}async list(){throw Error("StorageAdapter.list() not implemented")}async writeAll(t){for(let{name:i,data:r}of t)await this.write(i,r)}}class hn extends Yi{constructor({dir:t,format:i="gz"}){super();this.dir=st.resolve(t),this.format=i,this._ensureDir(this.dir)}_ensureDir(t){if(!H.existsSync(t))H.mkdirSync(t,{recursive:!0})}_filePath(t){return st.join(this.dir,`${t}.${this.format}`)}async read(t){let i=this._filePath(t);try{let r=await H.promises.readFile(i);if(this.format==="gz")r=Si.inflateSync(r);return r.toString("utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}}async write(t,i){let r=this._filePath(t),s=st.join(this.dir,`${t}_${globalThis.crypto.randomUUID()}.tmp.${this.format}`);if(this.format==="gz"){let n=Si.deflateSync(i);await H.promises.writeFile(s,n)}else await H.promises.writeFile(s,i,"utf8");await H.promises.rename(s,r)}async writeAll(t){let i=[];try{for(let{name:r,data:s}of t){let n=this._filePath(r),a=st.join(this.dir,`${r}_${globalThis.crypto.randomUUID()}.tmp.${this.format}`);if(this.format==="gz"){let o=Si.deflateSync(s);await H.promises.writeFile(a,o)}else await H.promises.writeFile(a,s,"utf8");i.push({tmp:a,fp:n})}for(let{tmp:r,fp:s}of i)await H.promises.rename(r,s)}catch(r){for(let{tmp:s}of i)try{await H.promises.unlink(s)}catch{}throw r}}async delete(t){let i=this._filePath(t);try{await H.promises.unlink(i)}catch(r){if(r.code!=="ENOENT")throw r}}async list(){try{let t=await H.promises.readdir(this.dir),i=`.${this.format}`;return t.filter((r)=>r.endsWith(i)&&!r.includes(".tmp.")).map((r)=>r.slice(0,-i.length))}catch(t){if(t.code==="ENOENT")return[];throw t}}join(...t){return st.join(...t)}ensureDir(t){this._ensureDir(t)}async writeRaw(t,i){this._ensureDir(st.dirname(t)),await H.promises.writeFile(t,i,"utf8")}async readRaw(t){return H.promises.readFile(st.resolve(t),"utf8")}}class fn{constructor(){this._migrations=[]}add(t){let{version:i,up:r}=t;if(typeof i!=="number"||i<1)throw new L("ERR_SKALEX_VALIDATION_MIGRATION",`Migration version must be a positive integer, got ${i}`,{version:i});if(typeof r!=="function")throw new L("ERR_SKALEX_VALIDATION_MIGRATION",`Migration version ${i} must have an "up" function`,{version:i});if(this._migrations.some((s)=>s.version===i))throw new L("ERR_SKALEX_VALIDATION_MIGRATION_DUPLICATE",`Migration version ${i} is already registered`,{version:i});this._migrations.push({...t}),this._migrations.sort((s,n)=>s.version-n.version)}async run(t,i=[]){let r=new Set(i),s=this._migrations.filter((n)=>!r.has(n.version));for(let n of s){let a=t(n.version);await n.up(a),r.add(n.version)}return[...r].sort((n,a)=>n-a)}status(t=[]){let i=new Set(t),r=this._migrations.map((s)=>s.version).filter((s)=>!i.has(s));return{current:t.length?Math.max(...t):0,applied:[...i].sort((s,n)=>s-n),pending:r}}}var Qr={[Symbol.iterator](){return{next(){return{done:!0}}}},size:0};function Zr(t){return{[Symbol.iterator](){return t[Symbol.iterator]()},get size(){return t.size}}}function Ri(t){return t.map((i)=>{if(i===null||i===void 0)return"\x00";if(typeof i==="boolean")return i?"\x01T":"\x01F";if(typeof i==="number")return`\x02${i}`;return`\x03${String(i)}`}).join("\x1F")}class ti{constructor(t=[],i=[]){this._fields=new Set,this._compoundFields=[];for(let r of t)if(Array.isArray(r)){for(let s of r)this._validateFieldName(s);this._compoundFields.push(r)}else this._validateFieldName(r),this._fields.add(r);for(let r of i)this._validateFieldName(r);this._uniqueFields=new Set(i),this._indexedFields=new Set([...this._fields,...this._uniqueFields]),this._fieldIndexes=new Map,this._uniqueIndexes=new Map;for(let r of this._fields)this._fieldIndexes.set(r,new Map);for(let r of this._uniqueFields)if(this._uniqueIndexes.set(r,new Map),!this._fieldIndexes.has(r))this._fieldIndexes.set(r,new Map);this._compoundIndexes=new Map;for(let r of this._compoundFields)this._compoundIndexes.set(r.join("\x00"),{fields:r,map:new Map})}get indexedFields(){return this._indexedFields}buildFromData(t){for(let[,i]of this._fieldIndexes)i.clear();for(let[,i]of this._uniqueIndexes)i.clear();for(let[,i]of this._compoundIndexes)i.map.clear();for(let i of t)this._indexDoc(i)}add(t){this._checkUnique(t,null),this._indexDoc(t)}remove(t){for(let[i,r]of this._fieldIndexes){let s=t[i];if(s!==void 0){let n=r.get(s);if(n){if(n.delete(t),n.size===0)r.delete(s)}}}for(let[i,r]of this._uniqueIndexes){let s=t[i];if(s!==void 0)r.delete(s)}for(let[,i]of this._compoundIndexes){let r=Ri(i.fields.map((n)=>t[n])),s=i.map.get(r);if(s){if(s.delete(t),s.size===0)i.map.delete(r)}}}update(t,i){this._checkUnique(i,t),this.remove(t);try{this._indexDoc(i)}catch(r){try{this._indexDoc(t)}catch{}throw r}}lookup(t,i){let r=this._fieldIndexes.get(t);if(!r)return null;let s=r.get(i);return s?[...s]:[]}_lookupIterable(t,i){let r=this._fieldIndexes.get(t);if(!r)return null;let s=r.get(i);return s?Zr(s):Qr}lookupCompound(t){let i=Object.keys(t).sort();for(let[,r]of this._compoundIndexes){let s=[...r.fields].sort();if(s.length!==i.length)continue;if(s.every((n,a)=>n===i[a])){let n=Ri(r.fields.map((o)=>t[o])),a=r.map.get(n);return a?Zr(a):Qr}}return null}isUniqueTaken(t,i){let r=this._uniqueIndexes.get(t);if(!r)return!1;return r.has(i)}assertUniqueCandidates(t,i){if(this._uniqueFields.size===0)return;let r=new Set(t.map((s)=>s._id));for(let s of this._uniqueFields){let n=new Set,a=this._uniqueIndexes.get(s);if(a){for(let[c,l]of a.entries())if(!r.has(l._id))n.add(c)}let o=new Map;for(let c=0;c<i.length;c++){let l=i[c][s];if(l===void 0)continue;if(n.has(l))throw new Pe("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${s}" value "${l}" already exists`,{field:s,value:l});let d=o.get(l);if(d&&d!==t[c]._id)throw new Pe("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${s}" value "${l}" already exists`,{field:s,value:l});o.set(l,t[c]._id)}}}assertUniqueBatch(t){if(this._uniqueFields.size===0)return;for(let i of this._uniqueFields){let r=this._uniqueIndexes.get(i),s=new Set;for(let n of t){let a=n[i];if(a===void 0)continue;if(r&&r.has(a))throw new Pe("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${i}" value "${a}" already exists`,{field:i,value:a});if(s.has(a))throw new Pe("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: duplicate "${i}" value "${a}" within batch`,{field:i,value:a});s.add(a)}}}_validateFieldName(t){if(t.includes("."))throw new L("ERR_SKALEX_VALIDATION_INDEX_DOT_PATH",`Index fields cannot use dot-notation: "${t}". Use a flat field name.`,{field:t})}_indexDoc(t){for(let[i,r]of this._fieldIndexes){let s=t[i];if(s!==void 0){if(!r.has(s))r.set(s,new Set);r.get(s).add(t)}}for(let[i,r]of this._uniqueIndexes){let s=t[i];if(s!==void 0)r.set(s,t)}for(let[,i]of this._compoundIndexes){for(let s of i.fields){let n=t[s];if(n!==void 0&&n!==null&&typeof n==="object")throw new L("ERR_SKALEX_VALIDATION_COMPOUND_INDEX",`Compound index field "${s}" must be a scalar value (string, number, or boolean), got ${Array.isArray(n)?"array":typeof n}`,{field:s})}let r=Ri(i.fields.map((s)=>t[s]));if(!i.map.has(r))i.map.set(r,new Set);i.map.get(r).add(t)}}_checkUnique(t,i){for(let r of this._uniqueFields){let s=t[r];if(s===void 0)continue;let n=this._uniqueIndexes.get(r);if(!n)continue;let a=n.get(s);if(a&&a._id!==i?._id)throw new Pe("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${r}" value "${s}" already exists`,{field:r,value:s})}}}var Ft="_flush",Kt="migrations";class _n{constructor({adapter:t,serializer:i,deserializer:r,logger:s,debug:n=!1,lenientLoad:a=!1}){this._adapter=t,this._serializer=i,this._deserializer=r,this._logger=s,this._debug=n,this._lenientLoad=a,this._saveLock=Promise.resolve()}_withSaveLock(t){let i=this._saveLock.then(t);return this._saveLock=i.catch(()=>{}),i}async loadAll(t,{parseSchema:i,buildIndex:r,IndexEngine:s}){try{let n=await this._adapter.list();await Promise.all(n.map(async(a)=>{try{let o=await this._adapter.read(a);if(!o)return;let c=this._deserializer(o),{collectionName:l,data:d}=c;if(!l)return;let u=t[l],f=u?.rawSchema??c.rawSchema??null,h=u?.schema??(f?i(f):null),_=u?.changelog??c.changelog??!1,p=u?.softDelete??c.softDelete??!1,g=u?.versioning??c.versioning??!1,m=u?.strict??c.strict??!1,w=u?.onSchemaError??c.onSchemaError??"throw",v=u?.defaultTtl??c.defaultTtl??null,q=u?.defaultEmbed??c.defaultEmbed??null,E=u?.maxDocs??c.maxDocs??null,A=u?u.fieldIndex:null;if(!A&&h?.uniqueFields?.length)A=new s([],h.uniqueFields);let tt=r(d,"_id");if(A)A.buildFromData(d);t[l]={collectionName:l,data:d,index:tt,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:h,rawSchema:f,fieldIndex:A,changelog:_,softDelete:p,versioning:g,strict:m,onSchemaError:w,defaultTtl:v,defaultEmbed:q,maxDocs:E}}catch(o){if(o.code==="ENOENT")return;if(this._lenientLoad){this._logger(`WARNING: Could not load collection "${a}": ${o.message}. Collection will be empty.`,"error");return}throw new Ge("ERR_SKALEX_PERSISTENCE_CORRUPT",`Failed to load collection "${a}": ${o.message}`,{collection:a})}})),this._detectIncompleteFlush(t),await this._cleanOrphanTempFiles()}catch(n){if(n.code!=="ENOENT")throw this._logger(`Error loading data: ${n}`,"error"),n}}async save(t,i){if(i)await this._saveOne(t,i);else await Promise.all(Object.keys(t).map((r)=>this._saveOne(t,r)))}async saveDirty(t){let i=Object.keys(t).filter((r)=>t[r]._dirty);if(i.length===0)return;await Promise.all(i.map((r)=>this._saveOne(t,r)))}saveAtomic(t,i){return this._withSaveLock(async()=>{if(i.length===0)return;this._writeFlushSentinel(t,i);let r=new Set(i);r.add("_meta");let s=[...r].filter((n)=>t[n]).map((n)=>({name:n,data:this._serializeCollection(t[n])}));try{await this._adapter.writeAll(s)}catch(n){throw new Ge("ERR_SKALEX_PERSISTENCE_FLUSH_FAILED",`Batch save failed during writeAll: ${n.message}`,{collections:i})}for(let n of i)if(t[n])t[n]._dirty=!1;try{this._clearFlushSentinel(t),await this._adapter.write("_meta",this._serializeCollection(t._meta))}catch(n){this._logger(`WARNING: Batch data committed but sentinel clear failed: ${n.message}. Next load will report an incomplete flush (false positive).`,"error")}})}markDirty(t,i){let r=t[i];if(r)r._dirty=!0}_serializeCollection(t){let i={collectionName:t.collectionName,data:t.data};if(t.rawSchema)i.rawSchema=t.rawSchema;if(t.changelog)i.changelog=t.changelog;if(t.softDelete)i.softDelete=t.softDelete;if(t.versioning)i.versioning=t.versioning;if(t.strict)i.strict=t.strict;if(t.onSchemaError!=="throw")i.onSchemaError=t.onSchemaError;if(t.defaultTtl)i.defaultTtl=t.defaultTtl;if(t.defaultEmbed)i.defaultEmbed=t.defaultEmbed;if(t.maxDocs)i.maxDocs=t.maxDocs;return this._serializer(i)}async _saveOne(t,i){let r=t[i];if(!r)return;if(r.isSaving)return r._pendingSave=!0,new Promise((s,n)=>{(r._saveWaiters??=[]).push({resolve:s,reject:n})});r.isSaving=!0,r._pendingSave=!1;try{await this._writeCollection(i,r);while(r._pendingSave)r._pendingSave=!1,await this._writeCollection(i,r);this._resolveSaveWaiters(r)}catch(s){throw this._rejectSaveWaiters(r,s),s}finally{r.isSaving=!1}}async _writeCollection(t,i){try{await this._adapter.write(t,this._serializeCollection(i)),i._dirty=!1}catch(r){throw this._logger(`Error saving "${t}": ${r.message}`,"error"),r}}_resolveSaveWaiters(t){let i=t._saveWaiters?.splice(0)??[];for(let r of i)r.resolve()}_rejectSaveWaiters(t,i){let r=t._saveWaiters?.splice(0)??[];for(let s of r)s.reject(i)}_writeFlushSentinel(t,i){let r=this._getOrCreateMeta(t);r[Ft]={startedAt:new Date().toISOString(),collections:i,completedAt:null}}_clearFlushSentinel(t){let i=this._getOrCreateMeta(t);if(i[Ft])i[Ft].completedAt=new Date().toISOString()}_detectIncompleteFlush(t){let i=t._meta;if(!i)return;let r=i.index.get(Kt);if(!r)return;let s=r[Ft];if(!s)return;if(s.startedAt&&!s.completedAt)this._logger(`WARNING: Incomplete flush detected (started ${s.startedAt}, collections: ${s.collections?.join(", ")}). Data may be inconsistent.`,"error")}async _cleanOrphanTempFiles(){if(typeof this._adapter.join!=="function")return;if(typeof this._adapter.list!=="function")return;try{let t=await import("fs"),i=await import("path"),r=this._adapter.dir;if(!r)return;let s=(await t.default.promises.readdir(r)).filter((n)=>n.includes(".tmp."));for(let n of s){let a=i.default.join(r,n);try{await t.default.promises.unlink(a),this._log(`Cleaned orphan temp file: ${n}`)}catch{}}}catch{}}_getOrCreateMeta(t){if(!t._meta)t._meta={collectionName:"_meta",data:[],index:new Map,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:null,rawSchema:null,fieldIndex:null,changelog:!1,softDelete:!1,versioning:!1,strict:!1,onSchemaError:"throw",defaultTtl:null,defaultEmbed:null,maxDocs:null};let i=t._meta,r=i.index.get(Kt);if(!r)r={_id:Kt},i.data.push(r),i.index.set(Kt,r);return r}_log(t){if(this._debug)this._logger(t,"info")}}var Il=0;class pn{constructor(){this._txLock=Promise.resolve(),this._ctx=null,this._abortedIds=new Set}get active(){return this._ctx!==null&&!this._ctx.aborted}get context(){return this._ctx}async run(t,i,{timeout:r=0}={}){let s=async()=>{await i._ensureConnected();let a=new Set(Object.keys(i.collections)),o={id:++Il,startedAt:Date.now(),aborted:!1,preExisting:a,touchedCollections:new Set,snapshots:new Map,deferredEffects:[],timeout:r};this._ctx=o;let c=null,l=r>0?new Promise((f,h)=>{c=setTimeout(()=>{o.aborted=!0,h(new Ce("ERR_SKALEX_TX_TIMEOUT",`Transaction ${o.id} timed out after ${r}ms`))},r)}):null,d=this,u=new Proxy(i,{get(f,h){if(h==="_txId")return o.id;if(o!==d._ctx)throw new Ce("ERR_SKALEX_TX_STALE_PROXY",`Transaction ${o.id} has ended. This proxy is no longer usable.`);if(h==="collections")throw new Ce("ERR_SKALEX_TX_DIRECT_ACCESS","Direct access to db.collections inside transaction() is not covered by rollback. Use the collection API (db.useCollection) instead.");if(h==="useCollection")return(p)=>{let g=f.useCollection(p);return g._activeTxId=o.id,g};let _=Reflect.get(f,h);return typeof _==="function"?_.bind(f):_}});try{let f=t(u),h=l?await Promise.race([f,l]):await f;if(o.aborted)throw new Ce("ERR_SKALEX_TX_ABORTED",`Transaction ${o.id} was aborted`);let _=[...o.touchedCollections];if(_.length>0)await i._persistence.saveAtomic(i.collections,_);for(let p of o.deferredEffects)await p();return h}catch(f){for(let[h,_]of o.snapshots)if(o.preExisting.has(h)){if(i._applySnapshot(h,_),i.collections[h])i.collections[h]._dirty=_._dirty}for(let h in i.collections)if(!o.preExisting.has(h))delete i.collections[h],delete i._collectionInstances[h];throw f}finally{if(c)clearTimeout(c);if(o.aborted)this._abortedIds.add(o.id);this._ctx=null;for(let f in i._collectionInstances){let h=i._collectionInstances[f];if(h._createdInTxId===o.id)h._createdInTxId=null;if(h._activeTxId===o.id)h._activeTxId=null}}},n=this._txLock.then(s);return this._txLock=n.catch(()=>{}),n}snapshotIfNeeded(t,i,r){let s=this._ctx;if(!s)return;if(this._assertCtxNotAborted(s),!s.snapshots.has(t)){let n=r(i);n._dirty=i._dirty??!1,s.snapshots.set(t,n)}s.touchedCollections.add(t)}assertNotAborted(){let t=this._ctx;if(t)this._assertCtxNotAborted(t)}_assertCtxNotAborted(t){if(t.aborted)throw new Ce("ERR_SKALEX_TX_ABORTED",`Transaction ${t.id} was aborted. No further mutations allowed.`)}defer(t){if(this._ctx)return this._ctx.deferredEffects.push(t),!0;return!1}}class gn{constructor(t){this._CollectionClass=t,this.stores={},this._instances={}}get(t,i){if(this._instances[t])return this._instances[t];if(!this.stores[t])this.createStore(t);let r=new this._CollectionClass(this.stores[t],i);return this._instances[t]=r,r}create(t,i={},r){this.createStore(t,i);let s=new this._CollectionClass(this.stores[t],r);return this._instances[t]=s,s}createStore(t,{schema:i,indexes:r=[],changelog:s=!1,softDelete:n=!1,versioning:a=!1,strict:o=!1,onSchemaError:c="throw",defaultTtl:l=null,defaultEmbed:d=null,maxDocs:u=null}={}){let f=null,h=null;if(i){f=on(i);let _=f.uniqueFields;if(r.length||_.length)h=new ti(r,_)}else if(r.length)h=new ti(r,[]);this.stores[t]={collectionName:t,data:[],index:new Map,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:f,rawSchema:i||null,fieldIndex:h,changelog:s,softDelete:n,versioning:a,strict:o,onSchemaError:c,defaultTtl:l,defaultEmbed:d,maxDocs:u}}rename(t,i){if(!this.stores[t])throw new Ge("ERR_SKALEX_PERSISTENCE_COLLECTION_NOT_FOUND",`Collection "${t}" not found`,{collection:t});if(this.stores[i])throw new Ge("ERR_SKALEX_PERSISTENCE_COLLECTION_EXISTS",`Collection "${i}" already exists`,{collection:i});let r=this.stores[t];if(r.collectionName=i,this.stores[i]=r,delete this.stores[t],this._instances[t]){let s=this._instances[t];s.name=i,this._instances[i]=s,delete this._instances[t]}}buildIndex(t,i){let r=new Map;for(let s of t)r.set(s[i],s);return r}inspect(t){if(t){let r=this.stores[t];if(!r)return null;return{name:t,count:r.data.length,schema:r.schema?Object.fromEntries(r.schema.fields):null,indexes:r.fieldIndex?[...r.fieldIndex.indexedFields]:[],softDelete:r.softDelete??!1,versioning:r.versioning??!1,strict:r.strict??!1,onSchemaError:r.onSchemaError??"throw",maxDocs:r.maxDocs??null}}let i={};for(let r in this.stores)i[r]=this.inspect(r);return i}dump(){let t={};for(let i in this.stores)if(!i.startsWith("_"))t[i]=structuredClone(this.stores[i].data);return t}schema(t){let i=this.stores[t];if(!i)return null;if(i.schema)return Object.fromEntries([...i.schema.fields.entries()].map(([r,s])=>[r,s.type]));if(i.data.length>0)return gl(i.data[0]);return null}stats(t){let i=(r)=>{let s=this.stores[r];if(!s)return null;let n=s.data.length,a=0;for(let o of s.data)try{a+=JSON.stringify(o).length}catch(c){}return{collection:r,count:n,estimatedSize:a,avgDocSize:n>0?Math.round(a/n):0}};if(t)return i(t);return Object.keys(this.stores).map(i)}clear(){this.stores={},this._instances={}}}class Qi{async embed(t){throw Error("EmbeddingAdapter.embed() not implemented")}}var Ae=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class mn extends Qi{constructor({apiKey:t=Ae("OPENAI_API_KEY"),model:i=Ae("OPENAI_EMBED_MODEL")??"text-embedding-3-small",baseUrl:r=Ae("OPENAI_EMBED_BASE_URL")??"https://api.openai.com/v1/embeddings",dimensions:s=Ae("OPENAI_EMBED_DIMENSIONS")!=null?Number(Ae("OPENAI_EMBED_DIMENSIONS")):void 0,organization:n=Ae("OPENAI_ORGANIZATION")??void 0,timeout:a=Ae("OPENAI_EMBED_TIMEOUT")!=null?Number(Ae("OPENAI_EMBED_TIMEOUT")):void 0,retries:o=Number(Ae("OPENAI_EMBED_RETRIES")??0),retryDelay:c=Number(Ae("OPENAI_EMBED_RETRY_DELAY")??1000),headers:l={},fetch:d=globalThis.fetch}={}){super();if(!t)throw Error("OpenAIEmbeddingAdapter requires an apiKey");this.apiKey=t,this.model=i,this.baseUrl=r,this.dimensions=s,this.organization=n,this.timeout=a,this.retries=o,this.retryDelay=c,this.headers=l,this._fetch=d}async embed(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,...this.organization&&{"OpenAI-Organization":this.organization},...this.headers},body:JSON.stringify({input:t,model:this.model,...this.dimensions!==void 0&&{dimensions:this.dimensions}}),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`OpenAI embedding API error ${a.status}: ${o}`)}return(await a.json()).data[0].embedding}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}var wt=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class yn extends Qi{constructor({model:t=wt("OLLAMA_EMBED_MODEL")??"nomic-embed-text",host:i=wt("OLLAMA_HOST")??"http://localhost:11434",timeout:r=wt("OLLAMA_EMBED_TIMEOUT")!=null?Number(wt("OLLAMA_EMBED_TIMEOUT")):void 0,retries:s=Number(wt("OLLAMA_EMBED_RETRIES")??0),retryDelay:n=Number(wt("OLLAMA_EMBED_RETRY_DELAY")??1000),headers:a={},fetch:o=globalThis.fetch}={}){super();this.model=t,this.host=i,this.timeout=r,this.retries=s,this.retryDelay=n,this.headers=a,this._fetch=o}async embed(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(`${this.host}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json",...this.headers},body:JSON.stringify({model:this.model,prompt:t}),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`Ollama embedding API error ${a.status}: ${o}`)}return(await a.json()).embedding}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}class di{async generate(t,i){throw Error("LLMAdapter.generate() not implemented")}async summarize(t){throw Error("LLMAdapter.summarize() not implemented")}}var Zi=`You are a database query assistant. Convert the user's natural language request into a JSON filter object for a document database.
|
|
30
|
+
`)}if(typeof this._ctx.fs.writeRaw!=="function")throw new Te("ERR_SKALEX_ADAPTER_NO_RAW_WRITE","export() requires a file-system adapter (FsAdapter). The current adapter does not support raw file writes.");let c=r||`${this._ctx.dataDirectory}/exports`,l=`${s||this.name}.${n}`,d=this._ctx.fs.join(c,l);this._ctx.fs.ensureDir(c),await this._ctx.fs.writeRaw(d,o)}catch(a){throw this._ctx.logger(`Error exporting "${this.name}": ${a.message}`,"error"),a}}_txSnapshotIfNeeded(){let t=this._ctx.txManager;if(!t.active)return;if(this._activeTxId!==t.context?.id)return;t.snapshotIfNeeded(this.name,this._store,(i)=>this._ctx.snapshotCollection(i))}async _saveIfNeeded(t){let i=this._ctx.txManager;if(i.active&&this._activeTxId===i.context?.id)return;if(t??this._ctx.autoSave)await this._ctx.saveCollection(this.name)}_applyValidation(t){if(!this._schema)return t;let i=Jr(t,this._schema,this._strict);if(!i.length)return t;switch(this._onSchemaError){case"warn":return this._ctx.logger(`[${this.name}] Validation warning: ${i.join("; ")}`,"warn"),t;case"strip":return Yr(t,this._schema);default:throw new L("ERR_SKALEX_VALIDATION_FAILED",`Validation failed: ${i.join("; ")}`,{errors:i})}}_enforceCapAfterInsert(){let t=this._maxDocs;if(!t||this._data.length<=t)return;let i=this._data.splice(0,this._data.length-t);for(let r of i)this._index.delete(r._id),this._removeFromIndex(r)}_findRaw(t,{includeDeleted:i=!1}={}){if(typeof t==="function"){for(let r of this._data){if(this._softDelete&&r._deletedAt&&!i)continue;if(t(r))return r}return null}if(t._id){let r=this._index.get(t._id)||null;if(!r)return null;if(this._softDelete&&r._deletedAt&&!i)return null;if(Object.keys(t).length>1)return re(r,t)?r:null;return r}if(this._fieldIndex)for(let r in t){if(r==="$or"||r==="$and"||r==="$not")continue;let s=t[r];if(typeof s!=="object"||s===null){let n=this._fieldIndex._lookupIterable(r,s);if(n!==null){for(let a of n){if(this._softDelete&&a._deletedAt&&!i)continue;if(re(a,t))return a}return null}}}for(let r of this._data){if(this._softDelete&&r._deletedAt&&!i)continue;if(re(r,t))return r}return null}_findAllRaw(t,{includeDeleted:i=!1}={}){if(t&&typeof t!=="function"&&t._id){let s=this._index.get(t._id);if(!s)return[];if(this._softDelete&&s._deletedAt&&!i)return[];return re(s,t)?[s]:[]}let r=[];for(let s of this._getCandidates(t)){if(this._softDelete&&s._deletedAt&&!i)continue;if(re(s,t))r.push(s)}return r}_getCandidates(t){if(!this._fieldIndex)return this._data;if(this._fieldIndex._compoundIndexes.size>0){let i={};for(let r in t){if(r==="$or"||r==="$and"||r==="$not")continue;let s=t[r];if(typeof s!=="object"||s===null)i[r]=s}if(Object.keys(i).length>=2){let r=this._fieldIndex.lookupCompound(i);if(r!==null)return r}}for(let i in t){if(i==="$or"||i==="$and"||i==="$not")continue;let r=t[i];if(typeof r!=="object"||r===null){let s=this._fieldIndex._lookupIterable(i,r);if(s!==null)return s}}return this._data}_findIndex(t){for(let i=0;i<this._data.length;i++)if(re(this._data[i],t))return i;return-1}_addToIndex(t){if(this._fieldIndex)this._fieldIndex.add(t)}_removeFromIndex(t){if(this._fieldIndex)this._fieldIndex.remove(t)}_updateInIndex(t,i){if(this._fieldIndex)this._fieldIndex.update(t,i)}async _buildDoc(t,{ttl:i,embed:r}={}){let s={...t,_id:t._id??(this._ctx.idGenerator??pl)(),createdAt:new Date,updatedAt:new Date},n=i??this._defaultTtl;if(n)s._expiresAt=wl(n);let a=r??this._defaultEmbed;if(a){let o=typeof a==="function"?a(s):s[a];s._vector=await this._ctx.embed(String(o))}if(this._versioning)s._version=1;return s}_projectDoc(t,i){if(i){let s={};for(let n of i){if(n==="_vector")continue;s[n]=t[n]}return s}let r={...t};return delete r._vector,r}async _populateDoc(t,i,r){for(let s of r){let n=await this._ctx.getCollection(s).findOne({_id:i[s]});if(n)t[s]=n}}}class Hi{async read(t){throw Error("StorageAdapter.read() not implemented")}async write(t,i){throw Error("StorageAdapter.write() not implemented")}async delete(t){throw Error("StorageAdapter.delete() not implemented")}async list(){throw Error("StorageAdapter.list() not implemented")}async writeAll(t){for(let{name:i,data:r}of t)await this.write(i,r)}}class fn extends Hi{constructor({dir:t,format:i="gz"}){super();this.dir=rt.resolve(t),this.format=i,this._ensureDir(this.dir)}_ensureDir(t){if(!H.existsSync(t))H.mkdirSync(t,{recursive:!0})}_filePath(t){return rt.join(this.dir,`${t}.${this.format}`)}async read(t){let i=this._filePath(t);try{let r=await H.promises.readFile(i);if(this.format==="gz")r=vi.inflateSync(r);return r.toString("utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}}async write(t,i){let r=this._filePath(t),s=rt.join(this.dir,`${t}_${globalThis.crypto.randomUUID()}.tmp.${this.format}`);if(this.format==="gz"){let n=vi.deflateSync(i);await H.promises.writeFile(s,n)}else await H.promises.writeFile(s,i,"utf8");await H.promises.rename(s,r)}async writeAll(t){let i=[];try{for(let{name:r,data:s}of t){let n=this._filePath(r),a=rt.join(this.dir,`${r}_${globalThis.crypto.randomUUID()}.tmp.${this.format}`);if(this.format==="gz"){let o=vi.deflateSync(s);await H.promises.writeFile(a,o)}else await H.promises.writeFile(a,s,"utf8");i.push({tmp:a,fp:n})}for(let{tmp:r,fp:s}of i)await H.promises.rename(r,s)}catch(r){for(let{tmp:s}of i)try{await H.promises.unlink(s)}catch{}throw r}}async delete(t){let i=this._filePath(t);try{await H.promises.unlink(i)}catch(r){if(r.code!=="ENOENT")throw r}}async list(){try{let t=await H.promises.readdir(this.dir),i=`.${this.format}`;return t.filter((r)=>r.endsWith(i)&&!r.includes(".tmp.")).map((r)=>r.slice(0,-i.length))}catch(t){if(t.code==="ENOENT")return[];throw t}}join(...t){return rt.join(...t)}ensureDir(t){this._ensureDir(t)}async writeRaw(t,i){this._ensureDir(rt.dirname(t)),await H.promises.writeFile(t,i,"utf8")}async readRaw(t){return H.promises.readFile(rt.resolve(t),"utf8")}}class _n{constructor(){this._migrations=[]}add(t){let{version:i,up:r}=t;if(typeof i!=="number"||i<1)throw new L("ERR_SKALEX_VALIDATION_MIGRATION",`Migration version must be a positive integer, got ${i}`,{version:i});if(typeof r!=="function")throw new L("ERR_SKALEX_VALIDATION_MIGRATION",`Migration version ${i} must have an "up" function`,{version:i});if(this._migrations.some((s)=>s.version===i))throw new L("ERR_SKALEX_VALIDATION_MIGRATION_DUPLICATE",`Migration version ${i} is already registered`,{version:i});this._migrations.push({...t}),this._migrations.sort((s,n)=>s.version-n.version)}async run(t,i=[]){let r=new Set(i),s=this._migrations.filter((n)=>!r.has(n.version));for(let n of s){let a=t(n.version);await n.up(a),r.add(n.version)}return[...r].sort((n,a)=>n-a)}status(t=[]){let i=new Set(t),r=this._migrations.map((s)=>s.version).filter((s)=>!i.has(s));return{current:t.length?Math.max(...t):0,applied:[...i].sort((s,n)=>s-n),pending:r}}}var Zr={[Symbol.iterator](){return{next(){return{done:!0}}}},size:0};function es(t){return{[Symbol.iterator](){return t[Symbol.iterator]()},get size(){return t.size}}}function bi(t){return t.map((i)=>{if(i===null||i===void 0)return"\x00";if(typeof i==="boolean")return i?"\x01T":"\x01F";if(typeof i==="number")return`\x02${i}`;return`\x03${String(i)}`}).join("\x1F")}class Qt{constructor(t=[],i=[]){this._fields=new Set,this._compoundFields=[];for(let r of t)if(Array.isArray(r)){for(let s of r)this._validateFieldName(s);this._compoundFields.push(r)}else this._validateFieldName(r),this._fields.add(r);for(let r of i)this._validateFieldName(r);this._uniqueFields=new Set(i),this._indexedFields=new Set([...this._fields,...this._uniqueFields]),this._fieldIndexes=new Map,this._uniqueIndexes=new Map;for(let r of this._fields)this._fieldIndexes.set(r,new Map);for(let r of this._uniqueFields)if(this._uniqueIndexes.set(r,new Map),!this._fieldIndexes.has(r))this._fieldIndexes.set(r,new Map);this._compoundIndexes=new Map;for(let r of this._compoundFields)this._compoundIndexes.set(r.join("\x00"),{fields:r,map:new Map})}get indexedFields(){return this._indexedFields}buildFromData(t){for(let[,i]of this._fieldIndexes)i.clear();for(let[,i]of this._uniqueIndexes)i.clear();for(let[,i]of this._compoundIndexes)i.map.clear();for(let i of t)this._indexDoc(i)}add(t){this._checkUnique(t,null),this._indexDoc(t)}remove(t){for(let[i,r]of this._fieldIndexes){let s=t[i];if(s!==void 0){let n=r.get(s);if(n){if(n.delete(t),n.size===0)r.delete(s)}}}for(let[i,r]of this._uniqueIndexes){let s=t[i];if(s!==void 0)r.delete(s)}for(let[,i]of this._compoundIndexes){let r=bi(i.fields.map((n)=>t[n])),s=i.map.get(r);if(s){if(s.delete(t),s.size===0)i.map.delete(r)}}}update(t,i){this._checkUnique(i,t),this.remove(t);try{this._indexDoc(i)}catch(r){try{this._indexDoc(t)}catch{}throw r}}lookup(t,i){let r=this._fieldIndexes.get(t);if(!r)return null;let s=r.get(i);return s?[...s]:[]}_lookupIterable(t,i){let r=this._fieldIndexes.get(t);if(!r)return null;let s=r.get(i);return s?es(s):Zr}lookupCompound(t){let i=Object.keys(t).sort();for(let[,r]of this._compoundIndexes){let s=[...r.fields].sort();if(s.length!==i.length)continue;if(s.every((n,a)=>n===i[a])){let n=bi(r.fields.map((o)=>t[o])),a=r.map.get(n);return a?es(a):Zr}}return null}isUniqueTaken(t,i){let r=this._uniqueIndexes.get(t);if(!r)return!1;return r.has(i)}assertUniqueCandidates(t,i){if(this._uniqueFields.size===0)return;let r=new Set(t.map((s)=>s._id));for(let s of this._uniqueFields){let n=new Set,a=this._uniqueIndexes.get(s);if(a){for(let[c,l]of a.entries())if(!r.has(l._id))n.add(c)}let o=new Map;for(let c=0;c<i.length;c++){let l=i[c][s];if(l===void 0)continue;if(n.has(l))throw new Pe("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${s}" value "${l}" already exists`,{field:s,value:l});let d=o.get(l);if(d&&d!==t[c]._id)throw new Pe("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${s}" value "${l}" already exists`,{field:s,value:l});o.set(l,t[c]._id)}}}assertUniqueBatch(t){if(this._uniqueFields.size===0)return;for(let i of this._uniqueFields){let r=this._uniqueIndexes.get(i),s=new Set;for(let n of t){let a=n[i];if(a===void 0)continue;if(r&&r.has(a))throw new Pe("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${i}" value "${a}" already exists`,{field:i,value:a});if(s.has(a))throw new Pe("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: duplicate "${i}" value "${a}" within batch`,{field:i,value:a});s.add(a)}}}_validateFieldName(t){if(t.includes("."))throw new L("ERR_SKALEX_VALIDATION_INDEX_DOT_PATH",`Index fields cannot use dot-notation: "${t}". Use a flat field name.`,{field:t})}_indexDoc(t){for(let[i,r]of this._fieldIndexes){let s=t[i];if(s!==void 0){if(!r.has(s))r.set(s,new Set);r.get(s).add(t)}}for(let[i,r]of this._uniqueIndexes){let s=t[i];if(s!==void 0)r.set(s,t)}for(let[,i]of this._compoundIndexes){for(let s of i.fields){let n=t[s];if(n!==void 0&&n!==null&&typeof n==="object")throw new L("ERR_SKALEX_VALIDATION_COMPOUND_INDEX",`Compound index field "${s}" must be a scalar value (string, number, or boolean), got ${Array.isArray(n)?"array":typeof n}`,{field:s})}let r=bi(i.fields.map((s)=>t[s]));if(!i.map.has(r))i.map.set(r,new Set);i.map.get(r).add(t)}}_checkUnique(t,i){for(let r of this._uniqueFields){let s=t[r];if(s===void 0)continue;let n=this._uniqueIndexes.get(r);if(!n)continue;let a=n.get(s);if(a&&a._id!==i?._id)throw new Pe("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${r}" value "${s}" already exists`,{field:r,value:s})}}}var Ft="_flush",Kt="migrations";class pn{constructor({adapter:t,serializer:i,deserializer:r,logger:s,debug:n=!1,lenientLoad:a=!1}){this._adapter=t,this._serializer=i,this._deserializer=r,this._logger=s,this._debug=n,this._lenientLoad=a,this._saveLock=Promise.resolve()}_withSaveLock(t){let i=this._saveLock.then(t);return this._saveLock=i.catch(()=>{}),i}async loadAll(t,{parseSchema:i,buildIndex:r,IndexEngine:s}){try{let n=await this._adapter.list();await Promise.all(n.map(async(a)=>{try{let o=await this._adapter.read(a);if(!o)return;let c=this._deserializer(o),{collectionName:l,data:d}=c;if(!l)return;let u=t[l],f=u?.rawSchema??c.rawSchema??null,h=u?.schema??(f?i(f):null),_=u?.changelog??c.changelog??!1,p=u?.softDelete??c.softDelete??!1,g=u?.versioning??c.versioning??!1,m=u?.strict??c.strict??!1,w=u?.onSchemaError??c.onSchemaError??"throw",v=u?.defaultTtl??c.defaultTtl??null,q=u?.defaultEmbed??c.defaultEmbed??null,E=u?.maxDocs??c.maxDocs??null,A=u?u.fieldIndex:null;if(!A&&h?.uniqueFields?.length)A=new s([],h.uniqueFields);let tt=r(d,"_id");if(A)A.buildFromData(d);t[l]={collectionName:l,data:d,index:tt,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:h,rawSchema:f,fieldIndex:A,changelog:_,softDelete:p,versioning:g,strict:m,onSchemaError:w,defaultTtl:v,defaultEmbed:q,maxDocs:E}}catch(o){if(o.code==="ENOENT")return;if(this._lenientLoad){this._logger(`WARNING: Could not load collection "${a}": ${o.message}. Collection will be empty.`,"error");return}throw new Ge("ERR_SKALEX_PERSISTENCE_CORRUPT",`Failed to load collection "${a}": ${o.message}`,{collection:a})}})),this._detectIncompleteFlush(t),await this._cleanOrphanTempFiles()}catch(n){if(n.code!=="ENOENT")throw this._logger(`Error loading data: ${n}`,"error"),n}}async save(t,i){if(i)await this._saveOne(t,i);else await Promise.all(Object.keys(t).map((r)=>this._saveOne(t,r)))}async saveDirty(t){let i=Object.keys(t).filter((r)=>t[r]._dirty);if(i.length===0)return;await Promise.all(i.map((r)=>this._saveOne(t,r)))}saveAtomic(t,i){return this._withSaveLock(async()=>{if(i.length===0)return;this._writeFlushSentinel(t,i);let r=new Set(i);r.add("_meta");let s=[...r].filter((n)=>t[n]).map((n)=>({name:n,data:this._serializeCollection(t[n])}));try{await this._adapter.writeAll(s)}catch(n){throw new Ge("ERR_SKALEX_PERSISTENCE_FLUSH_FAILED",`Batch save failed during writeAll: ${n.message}`,{collections:i})}for(let n of i)if(t[n])t[n]._dirty=!1;try{this._clearFlushSentinel(t),await this._adapter.write("_meta",this._serializeCollection(t._meta))}catch(n){this._logger(`WARNING: Batch data committed but sentinel clear failed: ${n.message}. Next load will report an incomplete flush (false positive).`,"error")}})}markDirty(t,i){let r=t[i];if(r)r._dirty=!0}_serializeCollection(t){let i={collectionName:t.collectionName,data:t.data};if(t.rawSchema)i.rawSchema=t.rawSchema;if(t.changelog)i.changelog=t.changelog;if(t.softDelete)i.softDelete=t.softDelete;if(t.versioning)i.versioning=t.versioning;if(t.strict)i.strict=t.strict;if(t.onSchemaError!=="throw")i.onSchemaError=t.onSchemaError;if(t.defaultTtl)i.defaultTtl=t.defaultTtl;if(t.defaultEmbed)i.defaultEmbed=t.defaultEmbed;if(t.maxDocs)i.maxDocs=t.maxDocs;return this._serializer(i)}async _saveOne(t,i){let r=t[i];if(!r)return;if(r.isSaving)return r._pendingSave=!0,new Promise((s,n)=>{(r._saveWaiters??=[]).push({resolve:s,reject:n})});r.isSaving=!0,r._pendingSave=!1;try{await this._writeCollection(i,r);while(r._pendingSave)r._pendingSave=!1,await this._writeCollection(i,r);this._resolveSaveWaiters(r)}catch(s){throw this._rejectSaveWaiters(r,s),s}finally{r.isSaving=!1}}async _writeCollection(t,i){try{await this._adapter.write(t,this._serializeCollection(i)),i._dirty=!1}catch(r){throw this._logger(`Error saving "${t}": ${r.message}`,"error"),r}}_resolveSaveWaiters(t){let i=t._saveWaiters?.splice(0)??[];for(let r of i)r.resolve()}_rejectSaveWaiters(t,i){let r=t._saveWaiters?.splice(0)??[];for(let s of r)s.reject(i)}_writeFlushSentinel(t,i){let r=this._getOrCreateMeta(t);r[Ft]={startedAt:new Date().toISOString(),collections:i,completedAt:null}}_clearFlushSentinel(t){let i=this._getOrCreateMeta(t);if(i[Ft])i[Ft].completedAt=new Date().toISOString()}_detectIncompleteFlush(t){let i=t._meta;if(!i)return;let r=i.index.get(Kt);if(!r)return;let s=r[Ft];if(!s)return;if(s.startedAt&&!s.completedAt)this._logger(`WARNING: Incomplete flush detected (started ${s.startedAt}, collections: ${s.collections?.join(", ")}). Data may be inconsistent.`,"error")}async _cleanOrphanTempFiles(){if(typeof this._adapter.join!=="function")return;if(typeof this._adapter.list!=="function")return;try{let t=await import("fs"),i=await import("path"),r=this._adapter.dir;if(!r)return;let s=(await t.default.promises.readdir(r)).filter((n)=>n.includes(".tmp."));for(let n of s){let a=i.default.join(r,n);try{await t.default.promises.unlink(a),this._log(`Cleaned orphan temp file: ${n}`)}catch{}}}catch{}}_getOrCreateMeta(t){if(!t._meta)t._meta={collectionName:"_meta",data:[],index:new Map,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:null,rawSchema:null,fieldIndex:null,changelog:!1,softDelete:!1,versioning:!1,strict:!1,onSchemaError:"throw",defaultTtl:null,defaultEmbed:null,maxDocs:null};let i=t._meta,r=i.index.get(Kt);if(!r)r={_id:Kt},i.data.push(r),i.index.set(Kt,r);return r}_log(t){if(this._debug)this._logger(t,"info")}}var bl=0;class gn{constructor(){this._txLock=Promise.resolve(),this._ctx=null,this._abortedIds=new Set}get active(){return this._ctx!==null&&!this._ctx.aborted}get context(){return this._ctx}async run(t,i,{timeout:r=0}={}){let s=async()=>{await i._ensureConnected();let a=new Set(Object.keys(i.collections)),o={id:++bl,startedAt:Date.now(),aborted:!1,preExisting:a,touchedCollections:new Set,snapshots:new Map,deferredEffects:[],timeout:r};this._ctx=o;let c=null,l=r>0?new Promise((f,h)=>{c=setTimeout(()=>{o.aborted=!0,h(new Ne("ERR_SKALEX_TX_TIMEOUT",`Transaction ${o.id} timed out after ${r}ms`))},r)}):null,d=this,u=new Proxy(i,{get(f,h){if(h==="_txId")return o.id;if(o!==d._ctx)throw new Ne("ERR_SKALEX_TX_STALE_PROXY",`Transaction ${o.id} has ended. This proxy is no longer usable.`);if(h==="collections")throw new Ne("ERR_SKALEX_TX_DIRECT_ACCESS","Direct access to db.collections inside transaction() is not covered by rollback. Use the collection API (db.useCollection) instead.");if(h==="useCollection")return(p)=>{let g=f.useCollection(p);return g._activeTxId=o.id,g};let _=Reflect.get(f,h);return typeof _==="function"?_.bind(f):_}});try{let f=t(u),h=l?await Promise.race([f,l]):await f;if(o.aborted)throw new Ne("ERR_SKALEX_TX_ABORTED",`Transaction ${o.id} was aborted`);let _=[...o.touchedCollections];if(_.length>0)await i._persistence.saveAtomic(i.collections,_);for(let p of o.deferredEffects)await p();return h}catch(f){for(let[h,_]of o.snapshots)if(o.preExisting.has(h)){if(i._applySnapshot(h,_),i.collections[h])i.collections[h]._dirty=_._dirty}for(let h in i.collections)if(!o.preExisting.has(h))delete i.collections[h],delete i._collectionInstances[h];throw f}finally{if(c)clearTimeout(c);if(o.aborted)this._abortedIds.add(o.id);this._ctx=null;for(let f in i._collectionInstances){let h=i._collectionInstances[f];if(h._createdInTxId===o.id)h._createdInTxId=null;if(h._activeTxId===o.id)h._activeTxId=null}}},n=this._txLock.then(s);return this._txLock=n.catch(()=>{}),n}snapshotIfNeeded(t,i,r){let s=this._ctx;if(!s)return;if(this._assertCtxNotAborted(s),!s.snapshots.has(t)){let n=r(i);n._dirty=i._dirty??!1,s.snapshots.set(t,n)}s.touchedCollections.add(t)}assertNotAborted(){let t=this._ctx;if(t)this._assertCtxNotAborted(t)}_assertCtxNotAborted(t){if(t.aborted)throw new Ne("ERR_SKALEX_TX_ABORTED",`Transaction ${t.id} was aborted. No further mutations allowed.`)}defer(t){if(this._ctx)return this._ctx.deferredEffects.push(t),!0;return!1}}class mn{constructor(t){this._CollectionClass=t,this.stores={},this._instances={}}get(t,i){if(this._instances[t])return this._instances[t];if(!this.stores[t])this.createStore(t);let r=new this._CollectionClass(this.stores[t],i);return this._instances[t]=r,r}create(t,i={},r){this.createStore(t,i);let s=new this._CollectionClass(this.stores[t],r);return this._instances[t]=s,s}createStore(t,{schema:i,indexes:r=[],changelog:s=!1,softDelete:n=!1,versioning:a=!1,strict:o=!1,onSchemaError:c="throw",defaultTtl:l=null,defaultEmbed:d=null,maxDocs:u=null}={}){let f=null,h=null;if(i){f=ln(i);let _=f.uniqueFields;if(r.length||_.length)h=new Qt(r,_)}else if(r.length)h=new Qt(r,[]);this.stores[t]={collectionName:t,data:[],index:new Map,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:f,rawSchema:i||null,fieldIndex:h,changelog:s,softDelete:n,versioning:a,strict:o,onSchemaError:c,defaultTtl:l,defaultEmbed:d,maxDocs:u}}rename(t,i){if(!this.stores[t])throw new Ge("ERR_SKALEX_PERSISTENCE_COLLECTION_NOT_FOUND",`Collection "${t}" not found`,{collection:t});if(this.stores[i])throw new Ge("ERR_SKALEX_PERSISTENCE_COLLECTION_EXISTS",`Collection "${i}" already exists`,{collection:i});let r=this.stores[t];if(r.collectionName=i,this.stores[i]=r,delete this.stores[t],this._instances[t]){let s=this._instances[t];s.name=i,this._instances[i]=s,delete this._instances[t]}}buildIndex(t,i){let r=new Map;for(let s of t)r.set(s[i],s);return r}inspect(t){if(t){let r=this.stores[t];if(!r)return null;return{name:t,count:r.data.length,schema:r.schema?Object.fromEntries(r.schema.fields):null,indexes:r.fieldIndex?[...r.fieldIndex.indexedFields]:[],softDelete:r.softDelete??!1,versioning:r.versioning??!1,strict:r.strict??!1,onSchemaError:r.onSchemaError??"throw",maxDocs:r.maxDocs??null}}let i={};for(let r in this.stores)i[r]=this.inspect(r);return i}dump(){let t={};for(let i in this.stores)if(!i.startsWith("_"))t[i]=structuredClone(this.stores[i].data);return t}schema(t){let i=this.stores[t];if(!i)return null;if(i.schema)return Object.fromEntries([...i.schema.fields.entries()].map(([r,s])=>[r,s.type]));if(i.data.length>0)return ml(i.data[0]);return null}stats(t){let i=(r)=>{let s=this.stores[r];if(!s)return null;let n=s.data.length,a=0;for(let o of s.data)try{a+=JSON.stringify(o).length}catch(c){}return{collection:r,count:n,estimatedSize:a,avgDocSize:n>0?Math.round(a/n):0}};if(t)return i(t);return Object.keys(this.stores).map(i)}clear(){this.stores={},this._instances={}}}class Wi{async embed(t){throw Error("EmbeddingAdapter.embed() not implemented")}}var we=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class yn extends Wi{constructor({apiKey:t=we("OPENAI_API_KEY"),model:i=we("OPENAI_EMBED_MODEL")??"text-embedding-3-small",baseUrl:r=we("OPENAI_EMBED_BASE_URL")??"https://api.openai.com/v1/embeddings",dimensions:s=we("OPENAI_EMBED_DIMENSIONS")!=null?Number(we("OPENAI_EMBED_DIMENSIONS")):void 0,organization:n=we("OPENAI_ORGANIZATION")??void 0,timeout:a=we("OPENAI_EMBED_TIMEOUT")!=null?Number(we("OPENAI_EMBED_TIMEOUT")):void 0,retries:o=Number(we("OPENAI_EMBED_RETRIES")??0),retryDelay:c=Number(we("OPENAI_EMBED_RETRY_DELAY")??1000),headers:l={},fetch:d=globalThis.fetch}={}){super();if(!t)throw Error("OpenAIEmbeddingAdapter requires an apiKey");this.apiKey=t,this.model=i,this.baseUrl=r,this.dimensions=s,this.organization=n,this.timeout=a,this.retries=o,this.retryDelay=c,this.headers=l,this._fetch=d}async embed(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,...this.organization&&{"OpenAI-Organization":this.organization},...this.headers},body:JSON.stringify({input:t,model:this.model,...this.dimensions!==void 0&&{dimensions:this.dimensions}}),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`OpenAI embedding API error ${a.status}: ${o}`)}return(await a.json()).data[0].embedding}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}var wt=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class wn extends Wi{constructor({model:t=wt("OLLAMA_EMBED_MODEL")??"nomic-embed-text",host:i=wt("OLLAMA_HOST")??"http://localhost:11434",timeout:r=wt("OLLAMA_EMBED_TIMEOUT")!=null?Number(wt("OLLAMA_EMBED_TIMEOUT")):void 0,retries:s=Number(wt("OLLAMA_EMBED_RETRIES")??0),retryDelay:n=Number(wt("OLLAMA_EMBED_RETRY_DELAY")??1000),headers:a={},fetch:o=globalThis.fetch}={}){super();this.model=t,this.host=i,this.timeout=r,this.retries=s,this.retryDelay=n,this.headers=a,this._fetch=o}async embed(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(`${this.host}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json",...this.headers},body:JSON.stringify({model:this.model,prompt:t}),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`Ollama embedding API error ${a.status}: ${o}`)}return(await a.json()).embedding}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}class si{async generate(t,i){throw Error("LLMAdapter.generate() not implemented")}async summarize(t){throw Error("LLMAdapter.summarize() not implemented")}}var Ji=`You are a database query assistant. Convert the user's natural language request into a JSON filter object for a document database.
|
|
31
31
|
|
|
32
32
|
Rules:
|
|
33
33
|
- Return ONLY a valid JSON object, nothing else
|
|
@@ -36,24 +36,24 @@ Rules:
|
|
|
36
36
|
- For numeric comparisons use operators: {"age": {"$gt": 18}}
|
|
37
37
|
- For text search use $regex: {"name": {"$regex": "pattern"}}
|
|
38
38
|
- Return {} to match all documents
|
|
39
|
-
- No explanations, no markdown, no code fences`,
|
|
40
|
-
Schema: ${JSON.stringify(t)}`},{role:"user",content:i}],response_format:{type:"json_object"},temperature:0,...this.maxTokens!==void 0&&{max_tokens:this.maxTokens},...this.seed!==void 0&&{seed:this.seed}});return JSON.parse(r.choices[0].message.content)}async summarize(t){return(await this._post({model:this.model,messages:[{role:"system",content:this.summarizePrompt},{role:"user",content:t}],temperature:this.temperature,...this.maxTokens!==void 0&&{max_tokens:this.maxTokens},...this.topP!==void 0&&{top_p:this.topP},...this.seed!==void 0&&{seed:this.seed}})).choices[0].message.content.trim()}async _post(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,...this.organization&&{"OpenAI-Organization":this.organization},...this.headers},body:JSON.stringify(t),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`OpenAI API error ${a.status}: ${o}`)}return a.json()}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}var oe=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class
|
|
41
|
-
Schema: ${JSON.stringify(t)}`,messages:[{role:"user",content:i}]})).content[0].text.trim().replace(/^```(?:json)?\n?/,"").replace(/\n?```$/,"");return JSON.parse(r)}async summarize(t){return(await this._post({model:this.model,max_tokens:this.maxTokens,temperature:this.temperature,...this.topP!==void 0&&{top_p:this.topP},...this.topK!==void 0&&{top_k:this.topK},system:this.summarizePrompt,messages:[{role:"user",content:t}]})).content[0].text.trim()}async _post(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.apiKey,"anthropic-version":this.apiVersion,...this.headers},body:JSON.stringify(t),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`Anthropic API error ${a.status}: ${o}`)}return a.json()}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}var
|
|
39
|
+
- No explanations, no markdown, no code fences`,Yi="Summarise the following memory entries into one concise paragraph. Preserve all important facts.",F=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class An extends si{constructor({apiKey:t=F("OPENAI_API_KEY"),model:i=F("OPENAI_MODEL")??"gpt-4o-mini",baseUrl:r=F("OPENAI_BASE_URL")??"https://api.openai.com/v1/chat/completions",maxTokens:s=F("OPENAI_MAX_TOKENS")!=null?Number(F("OPENAI_MAX_TOKENS")):void 0,temperature:n=Number(F("OPENAI_TEMPERATURE")??0.3),topP:a=F("OPENAI_TOP_P")!=null?Number(F("OPENAI_TOP_P")):void 0,organization:o=F("OPENAI_ORGANIZATION")??void 0,timeout:c=F("OPENAI_TIMEOUT")!=null?Number(F("OPENAI_TIMEOUT")):void 0,retries:l=Number(F("OPENAI_RETRIES")??0),retryDelay:d=Number(F("OPENAI_RETRY_DELAY")??1000),headers:u={},fetch:f=globalThis.fetch,seed:h=F("OPENAI_SEED")!=null?Number(F("OPENAI_SEED")):void 0,generatePrompt:_=Ji,summarizePrompt:p=Yi}={}){super();if(!t)throw Error("OpenAILLMAdapter requires an apiKey");this.apiKey=t,this.model=i,this.baseUrl=r,this.maxTokens=s,this.temperature=n,this.topP=a,this.organization=o,this.timeout=c,this.retries=l,this.retryDelay=d,this.headers=u,this._fetch=f,this.seed=h,this.generatePrompt=_,this.summarizePrompt=p}async generate(t,i){let r=await this._post({model:this.model,messages:[{role:"system",content:`${this.generatePrompt}
|
|
40
|
+
Schema: ${JSON.stringify(t)}`},{role:"user",content:i}],response_format:{type:"json_object"},temperature:0,...this.maxTokens!==void 0&&{max_tokens:this.maxTokens},...this.seed!==void 0&&{seed:this.seed}});return JSON.parse(r.choices[0].message.content)}async summarize(t){return(await this._post({model:this.model,messages:[{role:"system",content:this.summarizePrompt},{role:"user",content:t}],temperature:this.temperature,...this.maxTokens!==void 0&&{max_tokens:this.maxTokens},...this.topP!==void 0&&{top_p:this.topP},...this.seed!==void 0&&{seed:this.seed}})).choices[0].message.content.trim()}async _post(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,...this.organization&&{"OpenAI-Organization":this.organization},...this.headers},body:JSON.stringify(t),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`OpenAI API error ${a.status}: ${o}`)}return a.json()}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}var oe=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class vn extends si{constructor({apiKey:t=oe("ANTHROPIC_API_KEY"),model:i=oe("ANTHROPIC_MODEL")??"claude-haiku-4-5",baseUrl:r=oe("ANTHROPIC_BASE_URL")??"https://api.anthropic.com/v1/messages",apiVersion:s="2023-06-01",maxTokens:n=Number(oe("ANTHROPIC_MAX_TOKENS")??1024),temperature:a=Number(oe("ANTHROPIC_TEMPERATURE")??0.3),topP:o=oe("ANTHROPIC_TOP_P")!=null?Number(oe("ANTHROPIC_TOP_P")):void 0,topK:c=oe("ANTHROPIC_TOP_K")!=null?Number(oe("ANTHROPIC_TOP_K")):void 0,timeout:l=oe("ANTHROPIC_TIMEOUT")!=null?Number(oe("ANTHROPIC_TIMEOUT")):void 0,retries:d=Number(oe("ANTHROPIC_RETRIES")??0),retryDelay:u=Number(oe("ANTHROPIC_RETRY_DELAY")??1000),headers:f={},fetch:h=globalThis.fetch,generatePrompt:_=Ji,summarizePrompt:p=Yi}={}){super();if(!t)throw Error("AnthropicLLMAdapter requires an apiKey");this.apiKey=t,this.model=i,this.baseUrl=r,this.apiVersion=s,this.maxTokens=n,this.temperature=a,this.topP=o,this.topK=c,this.timeout=l,this.retries=d,this.retryDelay=u,this.headers=f,this._fetch=h,this.generatePrompt=_,this.summarizePrompt=p}async generate(t,i){let r=(await this._post({model:this.model,max_tokens:this.maxTokens,temperature:0,system:`${this.generatePrompt}
|
|
41
|
+
Schema: ${JSON.stringify(t)}`,messages:[{role:"user",content:i}]})).content[0].text.trim().replace(/^```(?:json)?\n?/,"").replace(/\n?```$/,"");return JSON.parse(r)}async summarize(t){return(await this._post({model:this.model,max_tokens:this.maxTokens,temperature:this.temperature,...this.topP!==void 0&&{top_p:this.topP},...this.topK!==void 0&&{top_k:this.topK},system:this.summarizePrompt,messages:[{role:"user",content:t}]})).content[0].text.trim()}async _post(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.apiKey,"anthropic-version":this.apiVersion,...this.headers},body:JSON.stringify(t),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`Anthropic API error ${a.status}: ${o}`)}return a.json()}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}var pe=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class En extends si{constructor({model:t=pe("OLLAMA_MODEL")??"llama3.2",host:i=pe("OLLAMA_HOST")??"http://localhost:11434",temperature:r=Number(pe("OLLAMA_TEMPERATURE")??0.3),topP:s=pe("OLLAMA_TOP_P")!=null?Number(pe("OLLAMA_TOP_P")):void 0,topK:n=pe("OLLAMA_TOP_K")!=null?Number(pe("OLLAMA_TOP_K")):void 0,timeout:a=pe("OLLAMA_TIMEOUT")!=null?Number(pe("OLLAMA_TIMEOUT")):void 0,retries:o=Number(pe("OLLAMA_RETRIES")??0),retryDelay:c=Number(pe("OLLAMA_RETRY_DELAY")??1000),headers:l={},fetch:d=globalThis.fetch,generatePrompt:u=Ji,summarizePrompt:f=Yi}={}){super();this.model=t,this.host=i,this.temperature=r,this.topP=s,this.topK=n,this.timeout=a,this.retries=o,this.retryDelay=c,this.headers=l,this._fetch=d,this.generatePrompt=u,this.summarizePrompt=f}async generate(t,i){let r=`${this.generatePrompt}
|
|
42
42
|
Schema: ${JSON.stringify(t)}
|
|
43
43
|
Query: ${i}`,s=await this._post({model:this.model,prompt:r,format:"json",options:{temperature:0},stream:!1});return JSON.parse(s.response)}async summarize(t){return(await this._post({model:this.model,prompt:`${this.summarizePrompt}
|
|
44
44
|
|
|
45
|
-
${t}`,options:{temperature:this.temperature,...this.topP!==void 0&&{top_p:this.topP},...this.topK!==void 0&&{top_k:this.topK}},stream:!1})).response.trim()}async _post(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(`${this.host}/api/generate`,{method:"POST",headers:{"Content-Type":"application/json",...this.headers},body:JSON.stringify(t),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`Ollama API error ${a.status}: ${o}`)}return a.json()}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}function
|
|
45
|
+
${t}`,options:{temperature:this.temperature,...this.topP!==void 0&&{top_p:this.topP},...this.topK!==void 0&&{top_k:this.topK}},stream:!1})).response.trim()}async _post(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(`${this.host}/api/generate`,{method:"POST",headers:{"Content-Type":"application/json",...this.headers},body:JSON.stringify(t),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`Ollama API error ${a.status}: ${o}`)}return a.json()}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}function Tl({provider:t,apiKey:i,embedModel:r,model:s,host:n,embedBaseUrl:a,dimensions:o,organization:c,embedTimeout:l,embedRetries:d,embedRetryDelay:u}){let f=r||s;switch(t){case"openai":return new yn({apiKey:i,model:f,baseUrl:a,...o!==void 0&&{dimensions:o},...c!==void 0&&{organization:c},...l!==void 0&&{timeout:l},...d!==void 0&&{retries:d},...u!==void 0&&{retryDelay:u}});case"ollama":return new wn({model:f,host:n,...l!==void 0&&{timeout:l},...d!==void 0&&{retries:d},...u!==void 0&&{retryDelay:u}});default:throw new Te("ERR_SKALEX_ADAPTER_UNKNOWN_PROVIDER",`Unknown AI provider: "${t}". Supported: "openai", "ollama".`,{provider:t})}}function Ol({provider:t,apiKey:i,model:r,host:s,baseUrl:n,apiVersion:a,temperature:o,maxTokens:c,topP:l,topK:d,organization:u,timeout:f,retries:h,retryDelay:_,seed:p,generatePrompt:g,summarizePrompt:m}){if(!r)return null;switch(t){case"openai":return new An({apiKey:i,model:r,baseUrl:n,...c!==void 0&&{maxTokens:c},...o!==void 0&&{temperature:o},...l!==void 0&&{topP:l},...u!==void 0&&{organization:u},...f!==void 0&&{timeout:f},...h!==void 0&&{retries:h},..._!==void 0&&{retryDelay:_},...p!==void 0&&{seed:p},...g!==void 0&&{generatePrompt:g},...m!==void 0&&{summarizePrompt:m}});case"anthropic":return new vn({apiKey:i,model:r,baseUrl:n,apiVersion:a,...c!==void 0&&{maxTokens:c},...o!==void 0&&{temperature:o},...l!==void 0&&{topP:l},...d!==void 0&&{topK:d},...f!==void 0&&{timeout:f},...h!==void 0&&{retries:h},..._!==void 0&&{retryDelay:_},...g!==void 0&&{generatePrompt:g},...m!==void 0&&{summarizePrompt:m}});case"ollama":return new En({model:r,host:s,...o!==void 0&&{temperature:o},...l!==void 0&&{topP:l},...d!==void 0&&{topK:d},...f!==void 0&&{timeout:f},...h!==void 0&&{retries:h},..._!==void 0&&{retryDelay:_},...g!==void 0&&{generatePrompt:g},...m!==void 0&&{summarizePrompt:m}});default:return null}}var Ti="AES-GCM",kt=12,Me=32,Rl=new TextEncoder,Cl=new TextDecoder;class xn extends Hi{constructor(t,i){super();if(this._adapter=t,this._rawKey=typeof i==="string"?Nl(i):Uint8Array.from(i),this._rawKey.length!==Me)throw new Te("ERR_SKALEX_ADAPTER_INVALID_KEY",`EncryptedAdapter: key must be ${Me} bytes (${Me*2} hex chars), got ${this._rawKey.length}`);this._cryptoKey=null}async read(t){let i=await this._adapter.read(t);if(!i)return null;return this._decrypt(i)}async write(t,i){return this._adapter.write(t,await this._encrypt(i))}async delete(t){return this._adapter.delete(t)}async list(){return this._adapter.list()}async writeAll(t){let i=[];for(let{name:r,data:s}of t)i.push({name:r,data:await this._encrypt(s)});return this._adapter.writeAll(i)}join(...t){return this._adapter.join?.(...t)}ensureDir(t){return this._adapter.ensureDir?.(t)}async writeRaw(t,i){return this._adapter.writeRaw?.(t,await this._encrypt(i))}async readRaw(t){let i=await this._adapter.readRaw?.(t);if(!i)return null;return this._decrypt(i)}async _getKey(){if(!this._cryptoKey)this._cryptoKey=await globalThis.crypto.subtle.importKey("raw",this._rawKey,{name:Ti},!1,["encrypt","decrypt"]);return this._cryptoKey}async _encrypt(t){let i=await this._getKey(),r=globalThis.crypto.getRandomValues(new Uint8Array(kt)),s=Rl.encode(t),n=await globalThis.crypto.subtle.encrypt({name:Ti,iv:r,tagLength:128},i,s),a=new Uint8Array(kt+n.byteLength);return a.set(r,0),a.set(new Uint8Array(n),kt),$l(a)}async _decrypt(t){let i=await this._getKey(),r=kl(t),s=r.slice(0,kt),n=r.slice(kt),a=await globalThis.crypto.subtle.decrypt({name:Ti,iv:s,tagLength:128},i,n);return Cl.decode(a)}}function Nl(t){if(t.length!==Me*2)throw new Te("ERR_SKALEX_ADAPTER_INVALID_KEY",`EncryptedAdapter: hex key must be ${Me*2} characters (${Me} bytes)`);if(!/^[0-9a-fA-F]+$/.test(t))throw new Te("ERR_SKALEX_ADAPTER_INVALID_KEY","EncryptedAdapter: hex key contains invalid characters");let i=new Uint8Array(Me);for(let r=0;r<Me;r++)i[r]=parseInt(t.slice(r*2,r*2+2),16);return i}function $l(t){let i="";for(let r=0;r<t.length;r++)i+=String.fromCharCode(t[r]);return globalThis.btoa(i)}function kl(t){let i=globalThis.atob(t),r=new Uint8Array(i.length);for(let s=0;s<i.length;s++)r[s]=i.charCodeAt(s);return r}var Dl=4;class Sn{constructor(t,i){this.sessionId=t,this._db=i,this._col=i.useCollection(`_memory_${t}`)}async remember(t){let i=await this._col.insertOne({text:t,sessionId:this.sessionId},{embed:"text"}),r=this._db._memoryConfig?.maxEntries;if(r&&this._col._data.length>r)await this.compress({threshold:0});return i}async recall(t,{limit:i=10,minScore:r=0}={}){return this._col.search(t,{limit:i,minScore:r})}async history({since:t,limit:i}={}){let r=t?{createdAt:{$gte:new Date(t)}}:{},s={sort:{createdAt:1}};if(i)s.limit=i;let{docs:n}=await this._col.find(r,s);return n}async forget(t){return this._col.deleteOne({_id:t})}tokenCount(){let t=this._col._data;return{tokens:t.reduce((i,r)=>i+this._docTokens(r),0),count:t.length}}context({tokens:t=this._db._memoryConfig?.contextTokens??4000}={}){let i=this._sortedData("desc"),r=[],s=0;for(let n of i){let a=this._docTokens(n);if(s+a>t)break;r.push(n.text),s+=a}return r.reverse().join(`
|
|
46
46
|
`)}async compress({threshold:t=this._db._memoryConfig?.compressionThreshold??8000,keepRecent:i=this._db._memoryConfig?.keepRecent??10}={}){let{tokens:r}=this.tokenCount();if(r<=t)return;if(!this._db._aiAdapter)throw Error('memory.compress() requires a language model adapter. Configure { ai: { model: "..." } }.');let s=this._sortedData("asc"),n=Math.max(0,s.length-i),a=s.slice(0,n);if(a.length===0)return;let o=a.map((l)=>l.text).join(`
|
|
47
|
-
`),c=await this._db._aiAdapter.summarize(o);await this._col.deleteMany({_id:{$in:a.map((l)=>l._id)}}),await this._col.insertOne({text:c,sessionId:this.sessionId,compressed:!0})}_docTokens(t){return Math.ceil((t.text||"").length/kl)}_sortedData(t){return[...this._col._data].sort(t==="asc"?(i,r)=>new Date(i.createdAt)-new Date(r.createdAt):(i,r)=>new Date(r.createdAt)-new Date(i.createdAt))}}class Sn{constructor(t){this._db=t,this._restoring=!1}get _col(){return this._db.useCollection("_changelog")}async log(t,i,r,s=null,n=null){if(this._restoring)return;let a={op:t,collection:i,docId:r._id,doc:{...r},timestamp:new Date};if(s)a.prev={...s};if(n)a.session=n;await this._col.insertOne(a)}async query(t,{since:i,limit:r,session:s}={}){let n={collection:t};if(i)n.timestamp={$gte:new Date(i)};if(s)n.session=s;let a={sort:{timestamp:1}};if(r)a.limit=r;let{docs:o}=await this._col.find(n,a);return o}async restore(t,i,{_id:r}={}){let s=new Date(i),n=this._db.useCollection(t),a=(await this.query(t,{})).filter((c)=>new Date(c.timestamp)<=s);if(r){let c=a.filter((d)=>d.docId===r);if(c.length===0)return;let l=c[c.length-1];this._restoring=!0;try{if(l.op==="delete"){if(await n.findOne({_id:r}))await n.deleteOne({_id:r});return}if(await n.findOne({_id:r})){let{_id:d,createdAt:u,updatedAt:f,...h}=l.doc;await n.updateOne({_id:r},h)}else await n.insertOne({...l.doc})}finally{this._restoring=!1}await this._db.saveData(t);return}let o=new Map;for(let c of a)if(c.op==="insert"||c.op==="update")o.set(c.docId,{doc:c.doc,deleted:!1});else if(c.op==="delete")o.set(c.docId,{doc:null,deleted:!0});this._restoring=!0;try{await n.deleteMany({});for(let[,{doc:c,deleted:l}]of o)if(!l&&c)await n.insertOne({...c})}finally{this._restoring=!1}await this._db.saveData(t)}}function Dl(t){let i=5381;for(let r=0;r<t.length;r++)i=(i<<5)+i+t.charCodeAt(r)|0;return(i>>>0).toString(16).padStart(8,"0")}class In{constructor({maxSize:t=500,ttl:i=0}={}){this._cache=new Map,this._maxSize=t,this._ttl=i}_key(t,i,r){return Dl(JSON.stringify({collectionName:t,schema:i,query:r}))}get(t,i,r){let s=this._key(t,i,r),n=this._cache.get(s);if(!n)return;if(this._ttl>0&&Date.now()-n.ts>this._ttl){this._cache.delete(s);return}return n.filter}set(t,i,r,s){let n=this._key(t,i,r);if(this._cache.size>=this._maxSize&&!this._cache.has(n))this._cache.delete(this._cache.keys().next().value);this._cache.set(n,{filter:s,ts:Date.now()})}toJSON(){return Object.fromEntries([...this._cache.entries()].map(([t,i])=>[t,i]))}fromJSON(t){if(!t||typeof t!=="object")return;for(let[i,r]of Object.entries(t))this._cache.set(i,r)}get size(){return this._cache.size}}function Ll(t,{regexMaxLength:i=500}={}){if(typeof t!=="object"||t===null)return t;let r={};for(let s of Object.keys(t)){let n=t[s];if(n&&typeof n==="object"&&!Array.isArray(n)){let a={};for(let o of Object.keys(n))if(o==="$regex"&&typeof n.$regex==="string"){if(n.$regex.length>i)throw Error(`$regex pattern too long (max ${i} characters)`);if(/\([^)]*[+*][^)]*\)[+*{]/.test(n.$regex))throw Error("$regex pattern rejected: nested quantifiers risk ReDoS");try{a.$regex=new RegExp(n.$regex)}catch{throw Error(`invalid $regex pattern: "${n.$regex}"`)}}else if(["$gt","$gte","$lt","$lte"].includes(o)&&Pl(n[o]))a[o]=new Date(n[o]);else a[o]=n[o];r[s]=a}else r[s]=n}return r}function Pl(t){if(typeof t!=="string")return!1;return/\d{4}-\d{2}-\d{2}/.test(t)&&!isNaN(Date.parse(t))}function Ml(t,i){let r=[];if(!i||typeof t!=="object"||t===null)return r;for(let s of Object.keys(t)){if(s.startsWith("$"))continue;if(!(s.split(".")[0]in i))r.push(`Unknown field referenced in generated filter: "${s}"`)}return r}class bn{constructor(){this._listeners=new Map}on(t,i){if(!this._listeners.has(t))this._listeners.set(t,new Set);return this._listeners.get(t).add(i),()=>this._listeners.get(t)?.delete(i)}off(t,i){this._listeners.get(t)?.delete(i)}emit(t,i){for(let r of[t,"*"]){let s=this._listeners.get(r);if(!s)continue;for(let n of s)try{n(i)}catch(a){}}}removeAll(t){if(t)this._listeners.delete(t);else this._listeners.clear()}listenerCount(t){return this._listeners.get(t)?.size??0}}class Tn{constructor({threshold:t=100,maxEntries:i=500}={}){this._threshold=t,this._maxEntries=i,this._entries=[]}record({collection:t,op:i,filter:r,query:s,duration:n,resultCount:a}){if(n<this._threshold)return;let o={collection:t,op:i,duration:n,resultCount:a,timestamp:new Date};if(r!==void 0)o.filter=r;if(s!==void 0)o.query=s;if(this._entries.push(o),this._entries.length>this._maxEntries)this._entries.shift()}entries({limit:t,minDuration:i,collection:r}={}){let s=this._entries;if(r)s=s.filter((n)=>n.collection===r);if(i)s=s.filter((n)=>n.duration>=i);if(t)s=s.slice(-t);return s}get size(){return this._entries.length}clear(){this._entries=[]}}class On{constructor(){this._sessions=new Map}_ensure(t){if(!this._sessions.has(t))this._sessions.set(t,{reads:0,writes:0,lastActive:null});return this._sessions.get(t)}recordRead(t){if(!t)return;let i=this._ensure(t);i.reads++,i.lastActive=new Date}recordWrite(t){if(!t)return;let i=this._ensure(t);i.writes++,i.lastActive=new Date}get(t){let i=this._sessions.get(t);if(!i)return null;return{sessionId:t,...i}}all(){return[...this._sessions.entries()].map(([t,i])=>({sessionId:t,...i}))}clear(t){if(t)this._sessions.delete(t);else this._sessions.clear()}}class Rn{constructor(){this._plugins=[]}register(t){if(typeof t!=="object"||t===null)throw TypeError("Plugin must be a non-null object.");this._plugins.push(t)}async run(t,i){for(let r of this._plugins)if(typeof r[t]==="function")await r[t](i)}get size(){return this._plugins.length}}function lt(t){if(typeof t!=="string"||!t.trim())throw Error("collection name must be a non-empty string");if(/[/\\]/.test(t)||t.includes("..")||t.includes("\x00"))throw Error(`invalid collection name: "${t}"`);if(t.trim().startsWith("_"))throw Error(`access to system collection "${t}" is not permitted`);return t.trim()}var es=[{name:"skalex_collections",description:"List all collection names in the database.",inputSchema:{type:"object",properties:{}},scope:"read"},{name:"skalex_schema",description:"Return the schema for a collection as a { field: type } map. Returns null if the collection is empty.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."}},required:["collection"]},scope:"read"},{name:"skalex_find",description:"Find documents in a collection that match a filter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},filter:{type:"object",description:"Query filter (MongoDB-style operators supported)."},limit:{type:"number",description:"Maximum number of results. Default: 20."},sort:{type:"object",description:"Sort descriptor: { field: 1 } for ascending, { field: -1 } for descending."}},required:["collection"]},scope:"read"},{name:"skalex_insert",description:"Insert a single document into a collection.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},doc:{type:"object",description:"Document to insert."}},required:["collection","doc"]},scope:"write"},{name:"skalex_update",description:"Update the first document matching a filter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},filter:{type:"object",description:"Query filter to identify the document."},update:{type:"object",description:"Fields to update (direct assignment, $inc, $push supported)."},many:{type:"boolean",description:"If true, update all matching documents. Default: false."}},required:["collection","filter","update"]},scope:"write"},{name:"skalex_delete",description:"Delete the first document matching a filter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},filter:{type:"object",description:"Query filter to identify the document."},many:{type:"boolean",description:"If true, delete all matching documents. Default: false."}},required:["collection","filter"]},scope:"write"},{name:"skalex_search",description:"Semantic similarity search. Requires an embedding adapter to be configured.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},query:{type:"string",description:"Natural-language query string to embed and compare."},limit:{type:"number",description:"Maximum number of results. Default: 10."},minScore:{type:"number",description:"Minimum cosine similarity score [0, 1]. Default: 0."},filter:{type:"object",description:"Optional structured pre-filter (hybrid search)."}},required:["collection","query"]},scope:"read"},{name:"skalex_ask",description:"Translate a natural-language question into a filter and query a collection. Requires a language model adapter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},question:{type:"string",description:"Natural-language question about the data."},limit:{type:"number",description:"Maximum number of results. Default: 20."}},required:["collection","question"]},scope:"read"}];async function jl(t,i,r){switch(t){case"skalex_collections":return Object.keys(r.collections).filter((s)=>!s.startsWith("_"));case"skalex_schema":return r.schema(lt(i.collection))??null;case"skalex_find":{let s=r.useCollection(lt(i.collection)),n={};if(i.limit)n.limit=i.limit;if(i.sort)n.sort=i.sort;return s.find(i.filter||{},n)}case"skalex_insert":return r.useCollection(lt(i.collection)).insertOne(i.doc||{});case"skalex_update":{let s=r.useCollection(lt(i.collection));if(i.many)return s.updateMany(i.filter||{},i.update||{});return s.updateOne(i.filter||{},i.update||{})}case"skalex_delete":{let s=r.useCollection(lt(i.collection));if(i.many)return s.deleteMany(i.filter||{});return s.deleteOne(i.filter||{})}case"skalex_search":return r.useCollection(lt(i.collection)).search(i.query,{limit:i.limit??10,minScore:i.minScore??0,filter:i.filter});case"skalex_ask":return r.ask(lt(i.collection),i.question,{limit:i.limit??20});default:throw Object.assign(Error(`Unknown tool: ${t}`),{code:"NOT_FOUND"})}}var tr="2.0",ir=-32700,ql=-32600,ts=-32601,Ul=-32602,Fl=-32603;function At(t,i){return{jsonrpc:tr,id:t,result:i}}function ze(t,i,r,s){return{jsonrpc:tr,id:t,error:{code:i,message:r}}}function Kl(t){try{let i=JSON.parse(t);if(typeof i!=="object"||i===null||i.jsonrpc!==tr)return{parseError:ze(null,ql,"Invalid JSON-RPC request")};return{msg:i}}catch(i){return{parseError:ze(null,ir,"Parse error")}}}function zl(t){return{content:[{type:"text",text:t}]}}function is(t){return{content:[{type:"text",text:t}],isError:!0}}class Cn{constructor({port:t=3000,host:i="127.0.0.1",allowedOrigin:r=null,maxBodySize:s=1048576}={}){this._port=t,this._host=i,this._allowedOrigin=r,this._maxBodySize=s,this._clients=new Set,this._onMessage=null,this._server=null}onMessage(t){this._onMessage=t}send(t){let i=`data: ${JSON.stringify(t)}
|
|
47
|
+
`),c=await this._db._aiAdapter.summarize(o);await this._col.deleteMany({_id:{$in:a.map((l)=>l._id)}}),await this._col.insertOne({text:c,sessionId:this.sessionId,compressed:!0})}_docTokens(t){return Math.ceil((t.text||"").length/Dl)}_sortedData(t){return[...this._col._data].sort(t==="asc"?(i,r)=>new Date(i.createdAt)-new Date(r.createdAt):(i,r)=>new Date(r.createdAt)-new Date(i.createdAt))}}class In{constructor(t){this._db=t,this._restoring=!1}get _col(){return this._db.useCollection("_changelog")}async log(t,i,r,s=null,n=null){if(this._restoring)return;let a={op:t,collection:i,docId:r._id,doc:{...r},timestamp:new Date};if(s)a.prev={...s};if(n)a.session=n;await this._col.insertOne(a)}async query(t,{since:i,limit:r,session:s}={}){let n={collection:t};if(i)n.timestamp={$gte:new Date(i)};if(s)n.session=s;let a={sort:{timestamp:1}};if(r)a.limit=r;let{docs:o}=await this._col.find(n,a);return o}async restore(t,i,{_id:r}={}){let s=new Date(i),n=this._db.useCollection(t),a=(await this.query(t,{})).filter((c)=>new Date(c.timestamp)<=s);if(r){let c=a.filter((d)=>d.docId===r);if(c.length===0)return;let l=c[c.length-1];this._restoring=!0;try{if(l.op==="delete"){if(await n.findOne({_id:r}))await n.deleteOne({_id:r});return}if(await n.findOne({_id:r})){let{_id:d,createdAt:u,updatedAt:f,...h}=l.doc;await n.updateOne({_id:r},h)}else await n.insertOne({...l.doc})}finally{this._restoring=!1}await this._db.saveData(t);return}let o=new Map;for(let c of a)if(c.op==="insert"||c.op==="update")o.set(c.docId,{doc:c.doc,deleted:!1});else if(c.op==="delete")o.set(c.docId,{doc:null,deleted:!0});this._restoring=!0;try{await n.deleteMany({});for(let[,{doc:c,deleted:l}]of o)if(!l&&c)await n.insertOne({...c})}finally{this._restoring=!1}await this._db.saveData(t)}}function Ll(t){let i=5381;for(let r=0;r<t.length;r++)i=(i<<5)+i+t.charCodeAt(r)|0;return(i>>>0).toString(16).padStart(8,"0")}class bn{constructor({maxSize:t=500,ttl:i=0}={}){this._cache=new Map,this._maxSize=t,this._ttl=i}_key(t,i,r){return Ll(JSON.stringify({collectionName:t,schema:i,query:r}))}get(t,i,r){let s=this._key(t,i,r),n=this._cache.get(s);if(!n)return;if(this._ttl>0&&Date.now()-n.ts>this._ttl){this._cache.delete(s);return}return n.filter}set(t,i,r,s){let n=this._key(t,i,r);if(this._cache.size>=this._maxSize&&!this._cache.has(n))this._cache.delete(this._cache.keys().next().value);this._cache.set(n,{filter:s,ts:Date.now()})}toJSON(){return Object.fromEntries([...this._cache.entries()].map(([t,i])=>[t,i]))}fromJSON(t){if(!t||typeof t!=="object")return;for(let[i,r]of Object.entries(t))this._cache.set(i,r)}get size(){return this._cache.size}}function Pl(t,{regexMaxLength:i=500}={}){if(typeof t!=="object"||t===null)return t;let r={};for(let s of Object.keys(t)){let n=t[s];if(n&&typeof n==="object"&&!Array.isArray(n)){let a={};for(let o of Object.keys(n))if(o==="$regex"&&typeof n.$regex==="string"){if(n.$regex.length>i)throw Error(`$regex pattern too long (max ${i} characters)`);if(/\([^)]*[+*][^)]*\)[+*{]/.test(n.$regex))throw Error("$regex pattern rejected: nested quantifiers risk ReDoS");try{a.$regex=new RegExp(n.$regex)}catch{throw Error(`invalid $regex pattern: "${n.$regex}"`)}}else if(["$gt","$gte","$lt","$lte"].includes(o)&&Ml(n[o]))a[o]=new Date(n[o]);else a[o]=n[o];r[s]=a}else r[s]=n}return r}function Ml(t){if(typeof t!=="string")return!1;return/\d{4}-\d{2}-\d{2}/.test(t)&&!isNaN(Date.parse(t))}function jl(t,i){let r=[];if(!i||typeof t!=="object"||t===null)return r;for(let s of Object.keys(t)){if(s.startsWith("$"))continue;if(!(s.split(".")[0]in i))r.push(`Unknown field referenced in generated filter: "${s}"`)}return r}class Tn{constructor(){this._listeners=new Map}on(t,i){if(!this._listeners.has(t))this._listeners.set(t,new Set);return this._listeners.get(t).add(i),()=>this._listeners.get(t)?.delete(i)}off(t,i){this._listeners.get(t)?.delete(i)}emit(t,i){for(let r of[t,"*"]){let s=this._listeners.get(r);if(!s)continue;for(let n of s)try{n(i)}catch(a){}}}removeAll(t){if(t)this._listeners.delete(t);else this._listeners.clear()}listenerCount(t){return this._listeners.get(t)?.size??0}}class On{constructor({threshold:t=100,maxEntries:i=500}={}){this._threshold=t,this._maxEntries=i,this._entries=[]}record({collection:t,op:i,filter:r,query:s,duration:n,resultCount:a}){if(n<this._threshold)return;let o={collection:t,op:i,duration:n,resultCount:a,timestamp:new Date};if(r!==void 0)o.filter=r;if(s!==void 0)o.query=s;if(this._entries.push(o),this._entries.length>this._maxEntries)this._entries.shift()}entries({limit:t,minDuration:i,collection:r}={}){let s=this._entries;if(r)s=s.filter((n)=>n.collection===r);if(i)s=s.filter((n)=>n.duration>=i);if(t)s=s.slice(-t);return s}get size(){return this._entries.length}clear(){this._entries=[]}}class Rn{constructor(){this._sessions=new Map}_ensure(t){if(!this._sessions.has(t))this._sessions.set(t,{reads:0,writes:0,lastActive:null});return this._sessions.get(t)}recordRead(t){if(!t)return;let i=this._ensure(t);i.reads++,i.lastActive=new Date}recordWrite(t){if(!t)return;let i=this._ensure(t);i.writes++,i.lastActive=new Date}get(t){let i=this._sessions.get(t);if(!i)return null;return{sessionId:t,...i}}all(){return[...this._sessions.entries()].map(([t,i])=>({sessionId:t,...i}))}clear(t){if(t)this._sessions.delete(t);else this._sessions.clear()}}class Cn{constructor(){this._plugins=[]}register(t){if(typeof t!=="object"||t===null)throw TypeError("Plugin must be a non-null object.");this._plugins.push(t)}async run(t,i){for(let r of this._plugins)if(typeof r[t]==="function")await r[t](i)}get size(){return this._plugins.length}}function lt(t){if(typeof t!=="string"||!t.trim())throw Error("collection name must be a non-empty string");if(/[/\\]/.test(t)||t.includes("..")||t.includes("\x00"))throw Error(`invalid collection name: "${t}"`);if(t.trim().startsWith("_"))throw Error(`access to system collection "${t}" is not permitted`);return t.trim()}var ts=[{name:"skalex_collections",description:"List all collection names in the database.",inputSchema:{type:"object",properties:{}},scope:"read"},{name:"skalex_schema",description:"Return the schema for a collection as a { field: type } map. Returns null if the collection is empty.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."}},required:["collection"]},scope:"read"},{name:"skalex_find",description:"Find documents in a collection that match a filter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},filter:{type:"object",description:"Query filter (MongoDB-style operators supported)."},limit:{type:"number",description:"Maximum number of results. Default: 20."},sort:{type:"object",description:"Sort descriptor: { field: 1 } for ascending, { field: -1 } for descending."}},required:["collection"]},scope:"read"},{name:"skalex_insert",description:"Insert a single document into a collection.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},doc:{type:"object",description:"Document to insert."}},required:["collection","doc"]},scope:"write"},{name:"skalex_update",description:"Update the first document matching a filter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},filter:{type:"object",description:"Query filter to identify the document."},update:{type:"object",description:"Fields to update (direct assignment, $inc, $push supported)."},many:{type:"boolean",description:"If true, update all matching documents. Default: false."}},required:["collection","filter","update"]},scope:"write"},{name:"skalex_delete",description:"Delete the first document matching a filter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},filter:{type:"object",description:"Query filter to identify the document."},many:{type:"boolean",description:"If true, delete all matching documents. Default: false."}},required:["collection","filter"]},scope:"write"},{name:"skalex_search",description:"Semantic similarity search. Requires an embedding adapter to be configured.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},query:{type:"string",description:"Natural-language query string to embed and compare."},limit:{type:"number",description:"Maximum number of results. Default: 10."},minScore:{type:"number",description:"Minimum cosine similarity score [0, 1]. Default: 0."},filter:{type:"object",description:"Optional structured pre-filter (hybrid search)."}},required:["collection","query"]},scope:"read"},{name:"skalex_ask",description:"Translate a natural-language question into a filter and query a collection. Requires a language model adapter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},question:{type:"string",description:"Natural-language question about the data."},limit:{type:"number",description:"Maximum number of results. Default: 20."}},required:["collection","question"]},scope:"read"}];async function ql(t,i,r){switch(t){case"skalex_collections":return Object.keys(r.collections).filter((s)=>!s.startsWith("_"));case"skalex_schema":return r.schema(lt(i.collection))??null;case"skalex_find":{let s=r.useCollection(lt(i.collection)),n={};if(i.limit)n.limit=i.limit;if(i.sort)n.sort=i.sort;return s.find(i.filter||{},n)}case"skalex_insert":return r.useCollection(lt(i.collection)).insertOne(i.doc||{});case"skalex_update":{let s=r.useCollection(lt(i.collection));if(i.many)return s.updateMany(i.filter||{},i.update||{});return s.updateOne(i.filter||{},i.update||{})}case"skalex_delete":{let s=r.useCollection(lt(i.collection));if(i.many)return s.deleteMany(i.filter||{});return s.deleteOne(i.filter||{})}case"skalex_search":return r.useCollection(lt(i.collection)).search(i.query,{limit:i.limit??10,minScore:i.minScore??0,filter:i.filter});case"skalex_ask":return r.ask(lt(i.collection),i.question,{limit:i.limit??20});default:throw Object.assign(Error(`Unknown tool: ${t}`),{code:"NOT_FOUND"})}}var Qi="2.0",Zi=-32700,Ul=-32600,is=-32601,Fl=-32602,Kl=-32603;function At(t,i){return{jsonrpc:Qi,id:t,result:i}}function ze(t,i,r,s){return{jsonrpc:Qi,id:t,error:{code:i,message:r}}}function zl(t){try{let i=JSON.parse(t);if(typeof i!=="object"||i===null||i.jsonrpc!==Qi)return{parseError:ze(null,Ul,"Invalid JSON-RPC request")};return{msg:i}}catch(i){return{parseError:ze(null,Zi,"Parse error")}}}function Bl(t){return{content:[{type:"text",text:t}]}}function rs(t){return{content:[{type:"text",text:t}],isError:!0}}class Nn{constructor({port:t=3000,host:i="127.0.0.1",allowedOrigin:r=null,maxBodySize:s=1048576}={}){this._port=t,this._host=i,this._allowedOrigin=r,this._maxBodySize=s,this._clients=new Set,this._onMessage=null,this._server=null}onMessage(t){this._onMessage=t}send(t){let i=`data: ${JSON.stringify(t)}
|
|
48
48
|
|
|
49
|
-
`;for(let r of this._clients)try{r.write(i)}catch(s){this._clients.delete(r)}}start(){return new Promise((t,i)=>{this._server=
|
|
49
|
+
`;for(let r of this._clients)try{r.write(i)}catch(s){this._clients.delete(r)}}start(){return new Promise((t,i)=>{this._server=yo.createServer((r,s)=>{if(this._allowedOrigin)s.setHeader("Access-Control-Allow-Origin",this._allowedOrigin),s.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),s.setHeader("Access-Control-Allow-Headers","Content-Type");if(r.method==="OPTIONS"){s.writeHead(204),s.end();return}if(r.method==="GET"&&r.url==="/sse")this._handleSSE(r,s);else if(r.method==="POST"&&r.url==="/message")this._handleMessage(r,s);else s.writeHead(404,{"Content-Type":"text/plain"}),s.end("Not Found")}),this._server.on("error",i),this._server.listen(this._port,this._host,()=>t())})}stop(){return new Promise((t)=>{if(!this._server){t();return}for(let i of this._clients)try{i.end()}catch(r){}this._clients.clear(),this._server.close(()=>t()),this._server=null})}_handleSSE(t,i){i.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),i.write(`event: endpoint
|
|
50
50
|
data: /message
|
|
51
51
|
|
|
52
|
-
`),this._clients.add(i),t.on("close",()=>{this._clients.delete(i)})}async _handleMessage(t,i){let r="";t.setEncoding("utf8"),t.on("data",(s)=>{if(r+=s,r.length>this._maxBodySize)t.destroy(),i.writeHead(413,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Request body too large"}))}),t.on("end",async()=>{i.writeHead(202,{"Content-Type":"application/json"}),i.end("{}");let s;try{s=JSON.parse(r)}catch(n){this.send(ze(null,
|
|
52
|
+
`),this._clients.add(i),t.on("close",()=>{this._clients.delete(i)})}async _handleMessage(t,i){let r="";t.setEncoding("utf8"),t.on("data",(s)=>{if(r+=s,r.length>this._maxBodySize)t.destroy(),i.writeHead(413,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Request body too large"}))}),t.on("end",async()=>{i.writeHead(202,{"Content-Type":"application/json"}),i.end("{}");let s;try{s=JSON.parse(r)}catch(n){this.send(ze(null,Zi,"Parse error"));return}if(this._onMessage)await this._onMessage(s).catch(()=>{})})}get port(){return this._port}get host(){return this._host}get url(){return`http://${this._host}:${this._port}`}get sseUrl(){return`${this.url}/sse`}}class $n{constructor(){this._onMessage=null,this._buffer="",this._started=!1}onMessage(t){this._onMessage=t}send(t){process.stdout.write(JSON.stringify(t)+`
|
|
53
53
|
`)}start(){if(this._started)return;this._started=!0,process.stdin.setEncoding("utf8"),process.stdin.on("data",(t)=>{this._buffer+=t;let i;while((i=this._buffer.indexOf(`
|
|
54
|
-
`))!==-1){let r=this._buffer.slice(0,i).trim();if(this._buffer=this._buffer.slice(i+1),r&&this._onMessage){let s;try{s=JSON.parse(r)}catch(n){this.send(ze(null,ir,"Parse error"));continue}this._onMessage(s).catch(()=>{})}}}),process.stdin.on("end",()=>{process.exit(0)})}stop(){process.stdin.removeAllListeners("data"),process.stdin.removeAllListeners("end"),this._started=!1}}var Bl={name:"skalex",version:"4.0.0-alpha"},Xl="2024-11-05";class $n{constructor(t,i={}){this._db=t,this._transport=i.transport||"stdio",this._port=i.port||3000,this._host=i.host||"127.0.0.1",this._allowedOrigin=i.allowedOrigin??null,this._maxBodySize=i.maxBodySize??1048576,this._scopes=i.scopes||{"*":["read"]},this._t=null}async listen(){if(this._transport==="http")this._t=new Cn({port:this._port,host:this._host,allowedOrigin:this._allowedOrigin,maxBodySize:this._maxBodySize});else this._t=new Nn;this._t.onMessage((t)=>this._handleMessage(t)),await this._t.start()}async connect(t){if(this._t=t,this._t.onMessage((i)=>this._handleMessage(i)),typeof this._t.start==="function")await this._t.start()}async close(){if(this._t&&typeof this._t.stop==="function")await this._t.stop();this._t=null}get transport(){return this._transport}get url(){return this._t?.url}async _handleMessage(t){let{msg:i,parseError:r}=typeof t==="string"?Kl(t):{msg:t};if(r){this._send(r);return}let{id:s,method:n,params:a}=i;if(s===void 0){if(n==="notifications/initialized")return;return}try{switch(n){case"initialize":this._send(At(s,{protocolVersion:Xl,capabilities:{tools:{}},serverInfo:Bl}));break;case"tools/list":this._send(At(s,{tools:this._visibleTools()}));break;case"tools/call":await this._handleToolCall(s,a);break;case"ping":this._send(At(s,{}));break;default:this._send(ze(s,ts,`Method not found: ${n}`))}}catch(o){this._send(ze(s,Fl,o.message||"Internal error"))}}async _handleToolCall(t,i){let r=i?.name,s=i?.arguments??{};if(!r){this._send(ze(t,Ul,"tools/call requires params.name"));return}let n=es.find((o)=>o.name===r);if(!n){this._send(ze(t,ts,`Unknown tool: ${r}`));return}let a=s.collection||s.collection_name||null;if(!this._hasScope(a,n.scope)){this._send(At(t,is(`Access denied: "${r}" requires "${n.scope}" scope on collection "${a}".`)));return}try{let o=await jl(r,s,this._db);this._send(At(t,zl(JSON.stringify(o,null,2))))}catch(o){this._send(At(t,is(o.message||String(o))))}}_visibleTools(){return es.filter((t)=>{let i=this._scopes["*"];if(i&&(i.includes(t.scope)||i.includes("admin")))return!0;for(let[,r]of Object.entries(this._scopes))if(r.includes(t.scope)||r.includes("admin"))return!0;return!1})}_hasScope(t,i){let r=(s)=>s.includes("admin")||s.includes(i);if(t&&this._scopes[t])return r(this._scopes[t]);if(this._scopes["*"])return r(this._scopes["*"]);return!1}_send(t){this._t?.send(t)}}var zt="migrations",rs=(t)=>JSON.stringify(t,function(i,r){let s=this[i];if(s instanceof Date)return{__skalex_date__:s.toISOString()};if(typeof r==="bigint")return{__skalex_bigint__:r.toString()};return r}),ss=(t)=>JSON.parse(t,(i,r)=>{if(r&&typeof r==="object"){if("__skalex_bigint__"in r)return BigInt(r.__skalex_bigint__);if("__skalex_date__"in r)return new Date(r.__skalex_date__)}return r});class ue{constructor({path:t="./.db",format:i="gz",debug:r=!1,adapter:s,ai:n,encrypt:a,slowQueryLog:o,queryCache:c,memory:l,logger:d,plugins:u,llmAdapter:f,embeddingAdapter:h,regexMaxLength:_,idGenerator:p,serializer:g,deserializer:m,autoSave:w,ttlSweepInterval:v,lenientLoad:q}={}){if(this.dataDirectory=t,this.dataFormat=i,this.debug=r,!ue._errorsAttached)ue.SkalexError=Ye,ue.ValidationError=L,ue.UniqueConstraintError=Pe,ue.TransactionError=Ce,ue.PersistenceError=Ge,ue.AdapterError=Ie,ue.QueryError=ht,ue._errorsAttached=!0;this._adapterConfig=s??null;let E=s||new hn({dir:t,format:i});if(a)E=new En(E,a.key);if(this.fs=E,this._registry=new gn(un),this.collections=this._registry.stores,this._collectionInstances=this._registry._instances,this._migrations=new fn,this._connectPromise=null,this.isConnected=!1,this._aiConfig=n||null,this._encryptConfig=a||null,this._pluginsConfig=Array.isArray(u)?u:null,this._memoryConfig=l||null,this._regexMaxLength=_??500,this._idGenerator=p??null,this._serializer=g??rs,this._deserializer=m??ss,this._autoSave=w??!1,this._txManager=new pn,this._ttlSweepInterval=v??0,this._ttlTimer=null,this._logger=d??Gr,this._embeddingAdapter=h??(n?bl(n):null),this._aiAdapter=f??(n?Tl(n):null),this._persistence=new _n({adapter:this.fs,serializer:this._serializer,deserializer:this._deserializer,logger:this._logger,debug:this.debug,lenientLoad:q??!1}),this._changeLog=new Sn(this),this._queryCache=new In(c||{}),this._eventBus=new bn,this._queryLog=o?new Tn(o):null,this._sessionStats=new On,this._plugins=new Rn,Array.isArray(u))for(let A of u)this._plugins.register(A)}async connect(){if(this._connectPromise)return this._connectPromise;return this._connectPromise=this._doConnect(),this._connectPromise}async _doConnect(){try{await this.loadData();let t=this._getMeta();if(t.queryCache)this._queryCache.fromJSON(t.queryCache);if(this._migrations._migrations.length>0){let i=t.appliedVersions||[],r=await this._migrations.run((s)=>this.useCollection(`_migration_${s}`),i);this._saveMeta({appliedVersions:r})}if(this._sweepTtl(),this._ttlSweepInterval>0){if(this._ttlTimer=setInterval(()=>this._sweepTtl(),this._ttlSweepInterval),this._ttlTimer?.unref)this._ttlTimer.unref()}this.isConnected=!0,this._log("> - Connected to the database (\u221A)")}catch(t){throw this._logger(`Error connecting to the database: ${t}`,"error"),t}}async disconnect(){try{if(this._ttlTimer)clearInterval(this._ttlTimer),this._ttlTimer=null;await this.saveData(),this._registry.clear(),this.collections=this._registry.stores,this._collectionInstances=this._registry._instances,this._connectPromise=null,this.isConnected=!1,this._log("> - Disconnected from the database (\u221A)")}catch(t){throw this._logger(`Error disconnecting from the database: ${t}`,"error"),t}}async _ensureConnected(){if(this.isConnected)return;return this.connect()}useCollection(t){return this._registry.get(t,this)}createCollection(t,i={}){return this._registry.create(t,i,this)}_createCollectionStore(t,i={}){this._registry.createStore(t,i)}async renameCollection(t,i){this._registry.rename(t,i),await this.saveData(i),await this.fs.delete(t)}async loadData(){await this._persistence.loadAll(this.collections,{parseSchema:on,buildIndex:this._registry.buildIndex,IndexEngine:ti});for(let t in this._collectionInstances){let i=this.collections[t];if(i&&this._collectionInstances[t]._store!==i)this._collectionInstances[t]._store=i}}async saveData(t){await this._persistence.save(this.collections,t)}buildIndex(t,i){return this._registry.buildIndex(t,i)}addMigration(t){this._migrations.add(t)}migrationStatus(){let t=this._getMeta();return this._migrations.status(t.appliedVersions||[])}namespace(t){if(this._adapterConfig)throw new Ie("ERR_SKALEX_ADAPTER_NAMESPACE_REQUIRES_FS","namespace() requires the default FsAdapter. When a custom storage adapter is configured, create a separate Skalex instance with your adapter instead.");let i=String(t).replace(/[^a-zA-Z0-9_-]/g,"_");if(!i)throw new L("ERR_SKALEX_VALIDATION_NAMESPACE_ID","namespace: id must contain at least one alphanumeric character",{id:t});return new ue({path:`${this.dataDirectory}/${i}`,format:this.dataFormat,debug:this.debug,ai:this._aiConfig||void 0,encrypt:this._encryptConfig||void 0,slowQueryLog:this._queryLog?{threshold:this._queryLog._threshold,maxEntries:this._queryLog._maxEntries}:void 0,queryCache:this._queryCache?{maxSize:this._queryCache._maxSize,ttl:this._queryCache._ttl}:void 0,plugins:this._pluginsConfig||void 0,memory:this._memoryConfig||void 0,logger:this._logger!==Gr?this._logger:void 0,llmAdapter:this._aiAdapter&&!this._aiConfig?this._aiAdapter:void 0,embeddingAdapter:this._embeddingAdapter&&!this._aiConfig?this._embeddingAdapter:void 0,regexMaxLength:this._regexMaxLength!==500?this._regexMaxLength:void 0,idGenerator:this._idGenerator||void 0,serializer:this._serializer!==rs?this._serializer:void 0,deserializer:this._deserializer!==ss?this._deserializer:void 0,autoSave:this._autoSave||void 0,ttlSweepInterval:this._ttlSweepInterval||void 0})}use(t){this._plugins.register(t)}watch(t){return this._eventBus.on("*",t)}sessionStats(t){if(t!==void 0)return this._sessionStats.get(t);return this._sessionStats.all()}get _inTransaction(){return this._txManager.active}_emitEvent(t,i){if(!this._txManager.defer(()=>this._eventBus.emit(t,i)))this._eventBus.emit(t,i)}async _runAfterHook(t,i){if(!this._txManager.defer(()=>this._plugins.run(t,i)))await this._plugins.run(t,i)}async _logChange(t,i,r,s,n){if(!this._txManager.defer(()=>this._changeLog.log(t,i,r,s,n)))await this._changeLog.log(t,i,r,s,n)}async transaction(t,i={}){return this._txManager.run(t,this,i)}async seed(t,{reset:i=!1}={}){for(let[r,s]of Object.entries(t)){if(i&&this.collections[r])this._applySnapshot(r,{data:[],index:new Map}),delete this._collectionInstances[r];await this.useCollection(r).insertMany(s)}await this.saveData()}dump(){return this._registry.dump()}inspect(t){return this._registry.inspect(t)}async import(t){let i=await this.fs.readRaw(t),r;try{r=JSON.parse(i)}catch{throw new Ge("ERR_SKALEX_PERSISTENCE_INVALID_JSON",`import: invalid JSON in file "${t}"`,{filePath:t})}let s=t.split("/").pop().replace(/\.[^.]+$/,"");return this.useCollection(s).insertMany(Array.isArray(r)?r:[r],{save:!0})}async embed(t){if(!this._embeddingAdapter)throw new Ie("ERR_SKALEX_ADAPTER_EMBEDDING_REQUIRED","db.embed() requires an AI adapter. Pass { ai: { provider, apiKey } } to the Skalex constructor.");return this._embeddingAdapter.embed(t)}async ask(t,i,{limit:r=20}={}){if(!this._aiAdapter)throw new Ie("ERR_SKALEX_ADAPTER_LLM_REQUIRED",'db.ask() requires a language model adapter. Configure { ai: { provider, model: "..." } }.');let s=this.useCollection(t),n=this.schema(t),a=this._queryCache.get(t,n,i);if(!a){a=await this._aiAdapter.generate(n,i);let o=Ml(a,n);if(o.length)o.forEach((c)=>this._log(`[ask] ${c}`));this._queryCache.set(t,n,i,a),this._saveMeta({queryCache:this._queryCache.toJSON()})}return s.find(Ll(a,{regexMaxLength:this._regexMaxLength}),{limit:r})}schema(t){return this._registry.schema(t)}useMemory(t){return new xn(t,this)}changelog(){return this._changeLog}async restore(t,i,r={}){return this._changeLog.restore(t,i,r)}stats(t){return this._registry.stats(t)}slowQueries(t={}){if(!this._queryLog)return[];return this._queryLog.entries(t)}slowQueryCount(){return this._queryLog?this._queryLog.size:0}clearSlowQueries(){this._queryLog?.clear()}mcp(t={}){return new $n(this,t)}_getMeta(){let t=this.collections._meta;if(!t)return{};return t.index.get(zt)||{}}_saveMeta(t){if(!this.collections._meta)this._createCollectionStore("_meta");let i=this.collections._meta,r=i.index.get(zt);if(r)Object.assign(r,t);else{let s={_id:zt,...t};i.data.push(s),i.index.set(zt,s)}this._persistence.markDirty(this.collections,"_meta")}_sweepTtl(){for(let t in this.collections){let i=this.collections[t],r=wl(i.data,i.index,i.fieldIndex?(s)=>i.fieldIndex.remove(s):null);if(r>0)this._persistence.markDirty(this.collections,t),this._log(`TTL sweep: removed ${r} expired docs from "${t}"`)}}_buildCollectionContext(){let t=this;return{ensureConnected:()=>t._ensureConnected(),get txManager(){return t._txManager},get plugins(){return t._plugins},get eventBus(){return t._eventBus},get sessionStats(){return t._sessionStats},get queryLog(){return t._queryLog},get logger(){return t._logger},get persistence(){return t._persistence},get collections(){return t.collections},embed:(i)=>t.embed(i),get idGenerator(){return t._idGenerator},get autoSave(){return t._autoSave},saveCollection:(i)=>t.saveData(i),snapshotCollection:(i)=>t._snapshotCollection(i),getCollection:(i)=>t.useCollection(i),emitEvent:(i,r)=>t._emitEvent(i,r),runAfterHook:(i,r)=>t._runAfterHook(i,r),logChange:(i,r,s,n,a)=>t._logChange(i,r,s,n,a),get fs(){return t.fs},get dataDirectory(){return t.dataDirectory}}}_log(t){if(this.debug)this._logger(t,"info")}_snapshotCollection(t){return{data:structuredClone(t.data)}}_applySnapshot(t,i){let r=this.collections[t];if(!r)return;if(r.data=i.data,r.index=this.buildIndex(i.data,"_id"),r.fieldIndex)r.fieldIndex.buildFromData(i.data)}}function Vl(){let t=Date.now().toString(16),i;try{i=Io.randomBytes(8).toString("hex")}catch{let r=new Uint8Array(8);crypto.getRandomValues(r),i=Array.from(r).map((s)=>s.toString(16).padStart(2,"0")).join("")}return`${t}${i}`}function ns(t,i){let r=t instanceof Error?t.message:t;if(i==="error")console.error(r);else console.log(r)}var as=new Set(["__proto__","constructor","prototype"]);function hi(t,i){if(!i.includes(".")){if(as.has(i))return;return t[i]}let r=t;for(let s of i.split(".")){if(as.has(s))return;if(r==null)return;r=r[s]}return r}class Qe extends Error{constructor(t,i,r={}){super(i);this.name=this.constructor.name,this.code=t,this.details=r}}class P extends Qe{}class je extends Qe{}class Ne extends Qe{}class He extends Qe{}class be extends Qe{}class ft extends Qe{}function qi(t,i){if(t===i)return!0;if(t==null||i==null)return!1;if(typeof t!==typeof i)return!1;if(t instanceof Date&&i instanceof Date)return t.getTime()===i.getTime();if(t instanceof RegExp&&i instanceof RegExp)return t.source===i.source&&t.flags===i.flags;if(Array.isArray(t)){if(!Array.isArray(i)||t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!qi(t[r],i[r]))return!1;return!0}if(typeof t==="object"){if(Array.isArray(i))return!1;let r=Object.keys(t);if(r.length!==Object.keys(i).length)return!1;for(let s of r){if(!Object.prototype.hasOwnProperty.call(i,s))return!1;if(!qi(t[s],i[s]))return!1}return!0}return!1}function se(t,i){if(typeof i==="function")return i(t);if(i==null)return!0;if(typeof i==="object"&&Object.keys(i).length===0)return!0;if("$or"in i){let r=i.$or;if(!Array.isArray(r))throw new ft("ERR_SKALEX_QUERY_INVALID_OPERATOR","$or must be an array of filters",{operator:"$or"});if(!r.some((s)=>se(t,s)))return!1}if("$and"in i){let r=i.$and;if(!Array.isArray(r))throw new ft("ERR_SKALEX_QUERY_INVALID_OPERATOR","$and must be an array of filters",{operator:"$and"});if(!r.every((s)=>se(t,s)))return!1}if("$not"in i){if(se(t,i.$not))return!1}for(let r in i){if(r==="$or"||r==="$and"||r==="$not")continue;let s=i[r],n;try{n=hi(t,r)}catch{return!1}if(s instanceof RegExp){if(!s.test(String(n)))return!1}else if(typeof s==="object"&&s!==null){if(Object.keys(s).some((a)=>a.startsWith("$"))){if("$eq"in s&&n!==s.$eq)return!1;if("$ne"in s&&n===s.$ne)return!1;if("$gt"in s&&!(n>s.$gt))return!1;if("$lt"in s&&!(n<s.$lt))return!1;if("$gte"in s&&!(n>=s.$gte))return!1;if("$lte"in s&&!(n<=s.$lte))return!1;if("$in"in s&&!s.$in.includes(n))return!1;if("$nin"in s&&s.$nin.includes(n))return!1;if("$regex"in s){if(!(s.$regex instanceof RegExp?s.$regex:new RegExp(s.$regex)).test(String(n)))return!1}if("$fn"in s&&!s.$fn(n))return!1}else if(!qi(n,s))return!1}else if(n!==s)return!1}return!0}function Gl(t,i=new Set){if(typeof t!=="object"||t===null||typeof t==="function")return t;let r=[],s=[],n=[],a=[],o=[];for(let l in t){if(l==="$or"||l==="$and"||l==="$not"){o.push(l);continue}let d=t[l];if(i.has(l))r.push(l);else if(d instanceof RegExp||typeof d==="object"&&d!==null&&(("$regex"in d)||("$fn"in d))||typeof d==="function")a.push(l);else if(typeof d==="object"&&d!==null&&(("$gt"in d)||("$lt"in d)||("$gte"in d)||("$lte"in d)||("$ne"in d)||("$in"in d)||("$nin"in d)))n.push(l);else s.push(l)}let c={};for(let l of[...r,...s,...n,...a,...o])c[l]=t[l];return c}var Ui=new Set(["string","number","boolean","object","array","date","any"]);function rr(t){if(Array.isArray(t))return"array";if(t instanceof Date)return"date";return typeof t}function kn(t){let i=new Map,r=[];for(let[s,n]of Object.entries(t)){let a;if(typeof n==="string"){if(!Ui.has(n))throw new P("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${n}" for field "${s}"`,{field:s,type:n});a={type:n,required:!1,unique:!1}}else if(typeof n==="object"&&n!==null){let{type:o="any",required:c=!1,unique:l=!1,enum:d}=n;if(!Ui.has(o))throw new P("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${o}" for field "${s}"`,{field:s,type:o});if(a={type:o,required:c,unique:l,enum:d},l)r.push(s)}else throw new P("ERR_SKALEX_VALIDATION_INVALID_SCHEMA",`Invalid schema definition for field "${s}"`,{field:s});i.set(s,a)}return{fields:i,uniqueFields:r}}function os(t,i,r=!1){let s=[];for(let[n,a]of i){let o=t[n],c=o===void 0||o===null;if(a.required&&c){s.push(`Field "${n}" is required`);continue}if(c)continue;if(a.type!=="any"){let l=rr(o);if(l!==a.type)s.push(`Field "${n}" must be of type "${a.type}", got "${l}"`)}if(a.enum&&!a.enum.includes(o))s.push(`Field "${n}" must be one of [${a.enum.map((l)=>JSON.stringify(l)).join(", ")}], got ${JSON.stringify(o)}`)}if(r){for(let n of Object.keys(t))if(!n.startsWith("_")&&!i.has(n))s.push(`Unknown field "${n}" (strict mode)`)}return s}function ls(t,i){let r={};for(let[s,n]of Object.entries(t)){if(s.startsWith("_")){r[s]=n;continue}if(!i.has(s))continue;let a=i.get(s);if(a.type!=="any"){if(rr(n)!==a.type)continue}if(a.enum&&!a.enum.includes(n))continue;r[s]=n}return r}function Hl(t){let i={};for(let[r,s]of Object.entries(t)){if(r.startsWith("_"))continue;let n=rr(s);i[r]=Ui.has(n)?n:"any"}return i}function Wl(t){if(typeof t==="number"){if(t<=0)throw new P("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got ${t}`,{ttl:t});return t*1000}if(typeof t!=="string")throw new P("ERR_SKALEX_VALIDATION_TTL",`Invalid TTL value: ${t}`,{ttl:t});let i=t.match(/^(\d+(?:\.\d+)?)(ms|s|m|h|d)$/);if(!i)throw new P("ERR_SKALEX_VALIDATION_TTL_FORMAT",`Invalid TTL format: "${t}". Use e.g. 300 (seconds), "30m", "24h", "7d"`,{ttl:t});let r=parseFloat(i[1]);if(r<=0)throw new P("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got "${t}"`,{ttl:t});let s=i[2],n=r*{ms:1,s:1000,m:60000,h:3600000,d:86400000}[s];if(!isFinite(n))throw new P("ERR_SKALEX_VALIDATION_TTL",`TTL value "${t}" is too large`,{ttl:t});return n}function Jl(t){return new Date(Date.now()+Wl(t))}function Yl(t,i,r=null){let s=Date.now(),n=0,a=t.length;while(a--){let o=t[a];if(o._expiresAt&&new Date(o._expiresAt).getTime()<=s){if(t.splice(a,1),i.delete(o._id),r)r(o);n++}}return n}function cs(t,i){if(t.length!==i.length)throw new ft("ERR_SKALEX_QUERY_VECTOR_MISMATCH",`Vector dimension mismatch: ${t.length} vs ${i.length}`,{expected:t.length,got:i.length});let r=0,s=0,n=0;for(let o=0;o<t.length;o++)r+=t[o]*i[o],s+=t[o]*t[o],n+=i[o]*i[o];let a=Math.sqrt(s*n);return a===0?0:r/a}function ee(t){if(!("_vector"in t))return{...t};let{_vector:i,...r}=t;return r}function Ql(t){return t.length}function Zl(t,i){let r=0;for(let s of t){let n=hi(s,i);if(typeof n==="number"&&!isNaN(n))r+=n}return r}function ec(t,i){let r=0,s=0;for(let n of t){let a=hi(n,i);if(typeof a==="number"&&!isNaN(a))r+=a,s++}return s===0?null:r/s}function tc(t,i){let r=Object.create(null);for(let s of t){let n=String(hi(s,i)??"__null__");if(!r[n])r[n]=[];r[n].push(s)}return r}class Dn{constructor(t){this._col=t}get _ctx(){return this._col._ctx}async execute({op:t,beforeHook:i,afterHook:r,hookPayload:s,mutate:n,afterHookPayload:a,save:o,session:c}){let l=this._ctx;await l.ensureConnected(),this._col._txSnapshotIfNeeded();let d=l.txManager,u=d.active&&this._col._activeTxId===d.context?.id,f=u?d.context.id:null,h=this._col._createdInTxId,_=()=>{if(f!==null&&d._abortedIds.has(f))throw new Ne("ERR_SKALEX_TX_ABORTED",`Transaction ${f} was aborted. No further mutations allowed.`);if(h!==null&&d._abortedIds.has(h))throw new Ne("ERR_SKALEX_TX_ABORTED",`Transaction ${h} was aborted. Collection obtained inside that transaction cannot be used for further mutations.`)};if(u||h!==null)_();if(i)await l.plugins.run(i,s);let{docs:p,prevDocs:g=[]}=await n(_);if(l.persistence.markDirty(l.collections,this._col.name),await this._col._saveIfNeeded(o),this._col._changelogEnabled)for(let m=0;m<p.length;m++)await l.logChange(t,this._col.name,p[m],g[m]??null,c||null);if(!u||!d.defer(()=>l.sessionStats.recordWrite(c)))l.sessionStats.recordWrite(c);for(let m of p)l.emitEvent(this._col.name,{op:t,collection:this._col.name,doc:ee(m)});if(r)if(a)await l.runAfterHook(r,a(p));else for(let m of p)await l.runAfterHook(r,{collection:this._col.name,doc:ee(m)});return{docs:p,prevDocs:g}}}function ic(t){let i={};for(let r in t){if(r.startsWith("$"))continue;let s=t[r];if(s&&typeof s==="object"&&!Array.isArray(s)){let n=Object.keys(s);if(n.length===1&&n[0]==="$eq")i[r]=s.$eq}else i[r]=s}return i}var Ln=new Set(["__proto__","constructor","prototype"]);function Pn(t){if(typeof t!=="object"||t===null||Array.isArray(t))return t;let i={};for(let r of Object.keys(t)){if(Ln.has(r))continue;i[r]=Pn(t[r])}return i}class Mn{constructor(t,i){this.name=t.collectionName,this.database=i,this._ctx=i._buildCollectionContext(),this._store=t,this._pipeline=new Dn(this),this._createdInTxId=i._txManager.context?.id??null,this._activeTxId=null}get _data(){return this._store.data}set _data(t){this._store.data=t}get _index(){return this._store.index}get _fieldIndex(){return this._store.fieldIndex||null}get _schema(){return this._store.schema?this._store.schema.fields:null}get _changelogEnabled(){return this._store.changelog===!0}get _softDelete(){return this._store.softDelete===!0}get _versioning(){return this._store.versioning===!0}get _strict(){return this._store.strict===!0}get _onSchemaError(){return this._store.onSchemaError??"throw"}get _defaultTtl(){return this._store.defaultTtl||null}get _defaultEmbed(){return this._store.defaultEmbed||null}get _maxDocs(){return this._store.maxDocs||null}async insertOne(t,i={}){let{save:r,ifNotExists:s,ttl:n,embed:a,session:o}=i;if(s){await this._ctx.ensureConnected();let l=this._findRaw(t);if(l)return ee({...l})}let{docs:c}=await this._insertCore([t],{ttl:n,embed:a,session:o,save:r});return ee(c[0])}async insertMany(t,i={}){let{save:r,ttl:s,embed:n,session:a}=i,{docs:o}=await this._insertCore(t,{ttl:s,embed:n,session:a,save:r});return o.map(ee)}async _insertCore(t,{ttl:i,embed:r,session:s,save:n}){return this._pipeline.execute({op:"insert",beforeHook:null,afterHook:"afterInsert",hookPayload:null,save:n,session:s,mutate:async(a)=>{let o=[],c=new Set;for(let l of t){let d=this._applyValidation(l);await this._ctx.plugins.run("beforeInsert",{collection:this.name,doc:d});let u=await this._buildDoc(d,{ttl:i,embed:r});if(this._index.has(u._id)||c.has(u._id))throw new je("ERR_SKALEX_UNIQUE_DUPLICATE_ID",`Duplicate _id "${u._id}" in collection "${this.name}"`,{id:u._id,collection:this.name});c.add(u._id),o.push(u)}if(a(),this._fieldIndex)this._fieldIndex.assertUniqueBatch(o);for(let l of o)this._addToIndex(l);this._data.push(...o);for(let l of o)this._index.set(l._id,l);return this._enforceCapAfterInsert(),{docs:o}}})}async updateOne(t,i,r={}){await this._ctx.ensureConnected();let s=this._findRaw(t);if(!s)return null;let{save:n,session:a}=r,{docs:o}=await this._updateCore([s],t,i,{save:n,session:a});return ee(o[0])}async updateMany(t,i,r={}){await this._ctx.ensureConnected();let s=this._findAllRaw(t);if(s.length===0)return[];let{save:n,session:a}=r,{docs:o}=await this._updateCore(s,t,i,{save:n,session:a});return o.map(ee)}async _updateCore(t,i,r,{save:s,session:n}){return this._pipeline.execute({op:"update",beforeHook:"beforeUpdate",afterHook:"afterUpdate",hookPayload:{collection:this.name,filter:i,update:r},save:s,session:n,afterHookPayload:(a)=>({collection:this.name,filter:i,update:r,result:a.length===1?a[0]:a}),mutate:async(a)=>{let o=this._changelogEnabled?t.map((u)=>structuredClone(u)):t.map(()=>null),c=t.map((u)=>this._prepareUpdatedDoc(u,r));this._assertUniqueCandidates(t,c),a();let l=new Set(t),d=new Map;for(let u=0;u<this._data.length;u++)if(l.has(this._data[u]))d.set(this._data[u],u);for(let u=0;u<t.length;u++)this._commitUpdatedDoc(t[u],c[u],d);return{docs:c,prevDocs:o}}})}applyUpdate(t,i){for(let r in i){if(Ln.has(r))continue;if(r==="_id"||r==="createdAt")continue;let s=i[r];if(Array.isArray(s))t[r]=s;else if(typeof s==="object"&&s!==null){let n=Object.keys(s);if(n.some((a)=>a.startsWith("$"))){for(let a of n)if(a==="$inc"&&typeof t[r]==="number")t[r]+=s[a];else if(a==="$push"){if(!Array.isArray(t[r]))t[r]=[];t[r].push(s[a])}}else t[r]=Pn(s)}else t[r]=s}if(t.updatedAt=new Date,this._versioning)t._version=(t._version??0)+1;return t}_prepareUpdatedDoc(t,i){let r=structuredClone(t),s=structuredClone(t);if(this.applyUpdate(s,i),!this._schema)return s;let n=os(s,this._schema,this._strict);if(!n.length)return s;switch(this._onSchemaError){case"throw":throw new P("ERR_SKALEX_VALIDATION_UPDATE",`Update validation failed on doc "${t._id}": ${n.join("; ")}`,{id:t._id,errors:n});case"strip":return this._stripCandidateToValid(s,r);default:return this._ctx.logger(`[${this.name}] Update validation warning: ${n.join("; ")}`,"warn"),s}}_stripCandidateToValid(t,i){let r=ls(t,this._schema),s=structuredClone(i);for(let[n,a]of Object.entries(r)){if(n.startsWith("_"))continue;s[n]=a}if(s.updatedAt=t.updatedAt,this._versioning)s._version=t._version;return s}_commitUpdatedDoc(t,i,r){let s=r?r.get(t):this._data.indexOf(t);if(s===void 0||s===-1)throw new He("ERR_SKALEX_PERSISTENCE_DOC_MISSING",`Document "${t._id}" no longer exists in collection "${this.name}"`,{id:t._id,collection:this.name});this._data[s]=i,this._index.set(i._id,i),this._updateInIndex(t,i)}_assertUniqueCandidates(t,i){this._fieldIndex?.assertUniqueCandidates(t,i)}async upsert(t,i,r={}){if(await this._ctx.ensureConnected(),this._findRaw(t))return this.updateOne(t,i,r);return this.insertOne({...ic(t),...i},r)}async upsertMany(t,i,r={}){await this._ctx.ensureConnected();let{save:s,...n}=r,a=[];for(let o of t)a.push(await this.upsert({[i]:o[i]},o,{...n,save:!1}));return await this._saveIfNeeded(s),a}async restore(t,i={}){if(!this._softDelete)throw new ft("ERR_SKALEX_QUERY_SOFT_DELETE_REQUIRED",`restore() requires softDelete on "${this.name}"`,{collection:this.name});await this._ctx.ensureConnected();let{save:r,session:s}=i,n=this._findRaw(t,{includeDeleted:!0});if(!n||!n._deletedAt)return null;let{docs:a}=await this._pipeline.execute({op:"restore",beforeHook:null,afterHook:null,hookPayload:null,save:r,session:s,mutate:async(o)=>(o(),delete n._deletedAt,n.updatedAt=new Date,this._index.set(n._id,n),{docs:[n]})});return ee(a[0])}watch(t,i){if(typeof t==="function")i=t,t=null;if(i)return this._ctx.eventBus.on(this.name,(r)=>{if(!t||se(r.doc,t))i(r)});return this._watchIterator(t)}_watchIterator(t){let i=[],r=null,s=!1,n=this._ctx.eventBus.on(this.name,(a)=>{if(t&&!se(a.doc,t))return;if(r){let o=r;r=null,o({value:a,done:!1})}else i.push(a)});return{[Symbol.asyncIterator](){return this},next(){if(i.length>0)return Promise.resolve({value:i.shift(),done:!1});if(s)return Promise.resolve({value:void 0,done:!0});return new Promise((a)=>{r=a})},return(){if(s=!0,n(),r){let a=r;r=null,a({value:void 0,done:!0})}return Promise.resolve({value:void 0,done:!0})}}}async count(t={}){return await this._ctx.ensureConnected(),Ql(this._findAllRaw(t))}async sum(t,i={}){return await this._ctx.ensureConnected(),Zl(this._findAllRaw(i),t)}async avg(t,i={}){return await this._ctx.ensureConnected(),ec(this._findAllRaw(i),t)}async groupBy(t,i={}){return await this._ctx.ensureConnected(),tc(this._findAllRaw(i),t)}async findOne(t,i={}){await this._ctx.ensureConnected();let{populate:r,select:s,includeDeleted:n=!1}=i,a=this._findRaw(t,{includeDeleted:n});if(!a)return null;let o=this._projectDoc(a,s);if(r)await this._populateDoc(o,a,r);return o}async find(t,i={}){await this._ctx.ensureConnected();let r=Date.now(),{populate:s,select:n,sort:a,page:o=1,limit:c,session:l,includeDeleted:d=!1}=i;await this._ctx.plugins.run("beforeFind",{collection:this.name,filter:t,options:i});let u=this._getCandidates(t),f=Gl(t,this._fieldIndex?this._fieldIndex.indexedFields:new Set),h=[];for(let p of u){if(this._softDelete&&p._deletedAt&&!d)continue;if(!se(p,f))continue;let g=this._projectDoc(p,n);if(s)await this._populateDoc(g,p,s);h.push(g)}if(a){let p=Object.keys(a);h.sort((g,m)=>{for(let w of p){let v=a[w];if(g[w]<m[w])return-v;if(g[w]>m[w])return v}return 0})}let _;if(c){let p=h.length,g=Math.ceil(p/c),m=(o-1)*c;h=h.slice(m,m+c),_={page:o,totalDocs:p,totalPages:g}}return this._ctx.queryLog?.record({collection:this.name,op:"find",filter:t,duration:Date.now()-r,resultCount:h.length}),this._ctx.sessionStats.recordRead(l),await this._ctx.plugins.run("afterFind",{collection:this.name,filter:t,options:i,docs:h}),_?{docs:h,..._}:{docs:h}}async search(t,{filter:i,limit:r=10,minScore:s=0,session:n}={}){await this._ctx.ensureConnected();let a=Date.now();await this._ctx.plugins.run("beforeSearch",{collection:this.name,query:t,options:{filter:i,limit:r,minScore:s}});let o=await this._ctx.embed(t),c=i?this._findAllRaw(i):this._data,l=[];for(let h of c){if(!h._vector)continue;let _=cs(o,h._vector);if(_>=s)l.push({doc:h,score:_})}l.sort((h,_)=>_.score-h.score);let d=l.slice(0,r);this._ctx.queryLog?.record({collection:this.name,op:"search",query:t,duration:Date.now()-a,resultCount:d.length}),this._ctx.sessionStats.recordRead(n);let u=d.map((h)=>ee(h.doc)),f=d.map((h)=>h.score);return await this._ctx.plugins.run("afterSearch",{collection:this.name,query:t,options:{filter:i,limit:r,minScore:s},docs:u,scores:f}),{docs:u,scores:f}}async similar(t,{limit:i=10,minScore:r=0}={}){await this._ctx.ensureConnected();let s=this._index.get(t);if(!s||!s._vector)return{docs:[],scores:[]};let n=[];for(let o of this._data){if(o._id===t||!o._vector)continue;let c=cs(s._vector,o._vector);if(c>=r)n.push({doc:o,score:c})}n.sort((o,c)=>c.score-o.score);let a=n.slice(0,i);return{docs:a.map((o)=>ee(o.doc)),scores:a.map((o)=>o.score)}}async deleteOne(t,i={}){await this._ctx.ensureConnected();let{save:r,session:s}=i;if(this._softDelete){let a=this._findRaw(t);if(!a)return null;let{docs:o}=await this._deleteCore("soft",[a],t,{save:r,session:s});return ee(o[0])}let{docs:n}=await this._deleteCore("hard",null,t,{save:r,session:s});if(n.length===0)return null;return ee(n[0])}async deleteMany(t,i={}){await this._ctx.ensureConnected();let{save:r,session:s}=i;if(this._softDelete){let a=this._findAllRaw(t);if(a.length===0)return[];let{docs:o}=await this._deleteCore("soft",a,t,{save:r,session:s});return o.map(ee)}let{docs:n}=await this._deleteCore("hardMany",null,t,{save:r,session:s});return n.map(ee)}async _deleteCore(t,i,r,{save:s,session:n}){return this._pipeline.execute({op:"delete",beforeHook:"beforeDelete",afterHook:"afterDelete",hookPayload:{collection:this.name,filter:r},save:s,session:n,afterHookPayload:(a)=>({collection:this.name,filter:r,result:a.length===1?a[0]:a}),mutate:async(a)=>{if(a(),t==="soft"){let l=new Date;for(let d of i)d._deletedAt=l,d.updatedAt=l,this._index.set(d._id,d);return{docs:i}}if(t==="hard"){let l=this._findIndex(r);if(l===-1)return{docs:[]};let d=this._data.splice(l,1)[0];return this._index.delete(d._id),this._removeFromIndex(d),{docs:[d]}}let o=[],c=[];for(let l of this._data)if(se(l,r))o.push(l),this._index.delete(l._id),this._removeFromIndex(l);else c.push(l);return this._data=c,{docs:o}}})}async export(t={},i={}){let{dir:r,name:s,format:n="json"}=i;try{let a=this._data.filter((u)=>se(u,t));if(a.length===0)throw new ft("ERR_SKALEX_QUERY_EXPORT_EMPTY",`export(): no documents matched the filter in "${this.name}"`,{collection:this.name});let o;if(n==="json")o=JSON.stringify(a,null,2);else{let u=(_)=>{if(_==null)return"";let p=typeof _==="object"?JSON.stringify(_):String(_);return p.includes(",")||p.includes('"')||p.includes(`
|
|
54
|
+
`))!==-1){let r=this._buffer.slice(0,i).trim();if(this._buffer=this._buffer.slice(i+1),r&&this._onMessage){let s;try{s=JSON.parse(r)}catch(n){this.send(ze(null,Zi,"Parse error"));continue}this._onMessage(s).catch(()=>{})}}}),process.stdin.on("end",()=>{process.exit(0)})}stop(){process.stdin.removeAllListeners("data"),process.stdin.removeAllListeners("end"),this._started=!1}}var Xl={name:"skalex",version:"4.0.0-alpha"},Vl="2024-11-05";class kn{constructor(t,i={}){this._db=t,this._transport=i.transport||"stdio",this._port=i.port||3000,this._host=i.host||"127.0.0.1",this._allowedOrigin=i.allowedOrigin??null,this._maxBodySize=i.maxBodySize??1048576,this._scopes=i.scopes||{"*":["read"]},this._t=null}async listen(){if(this._transport==="http")this._t=new Nn({port:this._port,host:this._host,allowedOrigin:this._allowedOrigin,maxBodySize:this._maxBodySize});else this._t=new $n;this._t.onMessage((t)=>this._handleMessage(t)),await this._t.start()}async connect(t){if(this._t=t,this._t.onMessage((i)=>this._handleMessage(i)),typeof this._t.start==="function")await this._t.start()}async close(){if(this._t&&typeof this._t.stop==="function")await this._t.stop();this._t=null}get transport(){return this._transport}get url(){return this._t?.url}async _handleMessage(t){let{msg:i,parseError:r}=typeof t==="string"?zl(t):{msg:t};if(r){this._send(r);return}let{id:s,method:n,params:a}=i;if(s===void 0){if(n==="notifications/initialized")return;return}try{switch(n){case"initialize":this._send(At(s,{protocolVersion:Vl,capabilities:{tools:{}},serverInfo:Xl}));break;case"tools/list":this._send(At(s,{tools:this._visibleTools()}));break;case"tools/call":await this._handleToolCall(s,a);break;case"ping":this._send(At(s,{}));break;default:this._send(ze(s,is,`Method not found: ${n}`))}}catch(o){this._send(ze(s,Kl,o.message||"Internal error"))}}async _handleToolCall(t,i){let r=i?.name,s=i?.arguments??{};if(!r){this._send(ze(t,Fl,"tools/call requires params.name"));return}let n=ts.find((o)=>o.name===r);if(!n){this._send(ze(t,is,`Unknown tool: ${r}`));return}let a=s.collection||s.collection_name||null;if(!this._hasScope(a,n.scope)){this._send(At(t,rs(`Access denied: "${r}" requires "${n.scope}" scope on collection "${a}".`)));return}try{let o=await ql(r,s,this._db);this._send(At(t,Bl(JSON.stringify(o,null,2))))}catch(o){this._send(At(t,rs(o.message||String(o))))}}_visibleTools(){return ts.filter((t)=>{let i=this._scopes["*"];if(i&&(i.includes(t.scope)||i.includes("admin")))return!0;for(let[,r]of Object.entries(this._scopes))if(r.includes(t.scope)||r.includes("admin"))return!0;return!1})}_hasScope(t,i){let r=(s)=>s.includes("admin")||s.includes(i);if(t&&this._scopes[t])return r(this._scopes[t]);if(this._scopes["*"])return r(this._scopes["*"]);return!1}_send(t){this._t?.send(t)}}var zt="migrations",ss=(t)=>JSON.stringify(t,function(i,r){let s=this[i];if(s instanceof Date)return{__skalex_date__:s.toISOString()};if(typeof r==="bigint")return{__skalex_bigint__:r.toString()};return r}),ns=(t)=>JSON.parse(t,(i,r)=>{if(r&&typeof r==="object"){if("__skalex_bigint__"in r)return BigInt(r.__skalex_bigint__);if("__skalex_date__"in r)return new Date(r.__skalex_date__)}return r});class ue{constructor({path:t="./.db",format:i="gz",debug:r=!1,adapter:s,ai:n,encrypt:a,slowQueryLog:o,queryCache:c,memory:l,logger:d,plugins:u,llmAdapter:f,embeddingAdapter:h,regexMaxLength:_,idGenerator:p,serializer:g,deserializer:m,autoSave:w,ttlSweepInterval:v,lenientLoad:q}={}){if(this.dataDirectory=t,this.dataFormat=i,this.debug=r,!ue._errorsAttached)ue.SkalexError=Ye,ue.ValidationError=L,ue.UniqueConstraintError=Pe,ue.TransactionError=Ne,ue.PersistenceError=Ge,ue.AdapterError=Te,ue.QueryError=ht,ue._errorsAttached=!0;this._adapterConfig=s??null;let E=s||new fn({dir:t,format:i});if(a)E=new xn(E,a.key);if(this.fs=E,this._registry=new mn(hn),this.collections=this._registry.stores,this._collectionInstances=this._registry._instances,this._migrations=new _n,this._connectPromise=null,this.isConnected=!1,this._aiConfig=n||null,this._encryptConfig=a||null,this._pluginsConfig=Array.isArray(u)?u:null,this._memoryConfig=l||null,this._regexMaxLength=_??500,this._idGenerator=p??null,this._serializer=g??ss,this._deserializer=m??ns,this._autoSave=w??!1,this._txManager=new gn,this._ttlSweepInterval=v??0,this._ttlTimer=null,this._logger=d??Hr,this._embeddingAdapter=h??(n?Tl(n):null),this._aiAdapter=f??(n?Ol(n):null),this._persistence=new pn({adapter:this.fs,serializer:this._serializer,deserializer:this._deserializer,logger:this._logger,debug:this.debug,lenientLoad:q??!1}),this._changeLog=new In(this),this._queryCache=new bn(c||{}),this._eventBus=new Tn,this._queryLog=o?new On(o):null,this._sessionStats=new Rn,this._plugins=new Cn,Array.isArray(u))for(let A of u)this._plugins.register(A)}async connect(){if(this._connectPromise)return this._connectPromise;return this._connectPromise=this._doConnect(),this._connectPromise}async _doConnect(){try{await this.loadData();let t=this._getMeta();if(t.queryCache)this._queryCache.fromJSON(t.queryCache);if(this._migrations._migrations.length>0){let i=t.appliedVersions||[],r=await this._migrations.run((s)=>this.useCollection(`_migration_${s}`),i);this._saveMeta({appliedVersions:r})}if(this._sweepTtl(),this._ttlSweepInterval>0){if(this._ttlTimer=setInterval(()=>this._sweepTtl(),this._ttlSweepInterval),this._ttlTimer?.unref)this._ttlTimer.unref()}this.isConnected=!0,this._log("> - Connected to the database (\u221A)")}catch(t){throw this._logger(`Error connecting to the database: ${t}`,"error"),t}}async disconnect(){try{if(this._ttlTimer)clearInterval(this._ttlTimer),this._ttlTimer=null;await this.saveData(),this._registry.clear(),this.collections=this._registry.stores,this._collectionInstances=this._registry._instances,this._connectPromise=null,this.isConnected=!1,this._log("> - Disconnected from the database (\u221A)")}catch(t){throw this._logger(`Error disconnecting from the database: ${t}`,"error"),t}}async _ensureConnected(){if(this.isConnected)return;return this.connect()}useCollection(t){return this._registry.get(t,this)}createCollection(t,i={}){return this._registry.create(t,i,this)}_createCollectionStore(t,i={}){this._registry.createStore(t,i)}async renameCollection(t,i){this._registry.rename(t,i),await this.saveData(i),await this.fs.delete(t)}async loadData(){await this._persistence.loadAll(this.collections,{parseSchema:ln,buildIndex:this._registry.buildIndex,IndexEngine:Qt});for(let t in this._collectionInstances){let i=this.collections[t];if(i&&this._collectionInstances[t]._store!==i)this._collectionInstances[t]._store=i}}async saveData(t){await this._persistence.save(this.collections,t)}buildIndex(t,i){return this._registry.buildIndex(t,i)}addMigration(t){this._migrations.add(t)}migrationStatus(){let t=this._getMeta();return this._migrations.status(t.appliedVersions||[])}namespace(t){if(this._adapterConfig)throw new Te("ERR_SKALEX_ADAPTER_NAMESPACE_REQUIRES_FS","namespace() requires the default FsAdapter. When a custom storage adapter is configured, create a separate Skalex instance with your adapter instead.");let i=String(t).replace(/[^a-zA-Z0-9_-]/g,"_");if(!i)throw new L("ERR_SKALEX_VALIDATION_NAMESPACE_ID","namespace: id must contain at least one alphanumeric character",{id:t});return new ue({path:`${this.dataDirectory}/${i}`,format:this.dataFormat,debug:this.debug,ai:this._aiConfig||void 0,encrypt:this._encryptConfig||void 0,slowQueryLog:this._queryLog?{threshold:this._queryLog._threshold,maxEntries:this._queryLog._maxEntries}:void 0,queryCache:this._queryCache?{maxSize:this._queryCache._maxSize,ttl:this._queryCache._ttl}:void 0,plugins:this._pluginsConfig||void 0,memory:this._memoryConfig||void 0,logger:this._logger!==Hr?this._logger:void 0,llmAdapter:this._aiAdapter&&!this._aiConfig?this._aiAdapter:void 0,embeddingAdapter:this._embeddingAdapter&&!this._aiConfig?this._embeddingAdapter:void 0,regexMaxLength:this._regexMaxLength!==500?this._regexMaxLength:void 0,idGenerator:this._idGenerator||void 0,serializer:this._serializer!==ss?this._serializer:void 0,deserializer:this._deserializer!==ns?this._deserializer:void 0,autoSave:this._autoSave||void 0,ttlSweepInterval:this._ttlSweepInterval||void 0})}use(t){this._plugins.register(t)}watch(t){return this._eventBus.on("*",t)}sessionStats(t){if(t!==void 0)return this._sessionStats.get(t);return this._sessionStats.all()}get _inTransaction(){return this._txManager.active}_emitEvent(t,i){if(!this._txManager.defer(()=>this._eventBus.emit(t,i)))this._eventBus.emit(t,i)}async _runAfterHook(t,i){if(!this._txManager.defer(()=>this._plugins.run(t,i)))await this._plugins.run(t,i)}async _logChange(t,i,r,s,n){if(!this._txManager.defer(()=>this._changeLog.log(t,i,r,s,n)))await this._changeLog.log(t,i,r,s,n)}async transaction(t,i={}){return this._txManager.run(t,this,i)}async seed(t,{reset:i=!1}={}){for(let[r,s]of Object.entries(t)){if(i&&this.collections[r])this._applySnapshot(r,{data:[],index:new Map}),delete this._collectionInstances[r];await this.useCollection(r).insertMany(s)}await this.saveData()}dump(){return this._registry.dump()}inspect(t){return this._registry.inspect(t)}async import(t){let i=await this.fs.readRaw(t),r;try{r=JSON.parse(i)}catch{throw new Ge("ERR_SKALEX_PERSISTENCE_INVALID_JSON",`import: invalid JSON in file "${t}"`,{filePath:t})}let s=t.split("/").pop().replace(/\.[^.]+$/,"");return this.useCollection(s).insertMany(Array.isArray(r)?r:[r],{save:!0})}async embed(t){if(!this._embeddingAdapter)throw new Te("ERR_SKALEX_ADAPTER_EMBEDDING_REQUIRED","db.embed() requires an AI adapter. Pass { ai: { provider, apiKey } } to the Skalex constructor.");return this._embeddingAdapter.embed(t)}async ask(t,i,{limit:r=20}={}){if(!this._aiAdapter)throw new Te("ERR_SKALEX_ADAPTER_LLM_REQUIRED",'db.ask() requires a language model adapter. Configure { ai: { provider, model: "..." } }.');let s=this.useCollection(t),n=this.schema(t),a=this._queryCache.get(t,n,i);if(!a){a=await this._aiAdapter.generate(n,i);let o=jl(a,n);if(o.length)o.forEach((c)=>this._log(`[ask] ${c}`));this._queryCache.set(t,n,i,a),this._saveMeta({queryCache:this._queryCache.toJSON()})}return s.find(Pl(a,{regexMaxLength:this._regexMaxLength}),{limit:r})}schema(t){return this._registry.schema(t)}useMemory(t){return new Sn(t,this)}changelog(){return this._changeLog}async restore(t,i,r={}){return this._changeLog.restore(t,i,r)}stats(t){return this._registry.stats(t)}slowQueries(t={}){if(!this._queryLog)return[];return this._queryLog.entries(t)}slowQueryCount(){return this._queryLog?this._queryLog.size:0}clearSlowQueries(){this._queryLog?.clear()}mcp(t={}){return new kn(this,t)}_getMeta(){let t=this.collections._meta;if(!t)return{};return t.index.get(zt)||{}}_saveMeta(t){if(!this.collections._meta)this._createCollectionStore("_meta");let i=this.collections._meta,r=i.index.get(zt);if(r)Object.assign(r,t);else{let s={_id:zt,...t};i.data.push(s),i.index.set(zt,s)}this._persistence.markDirty(this.collections,"_meta")}_sweepTtl(){for(let t in this.collections){let i=this.collections[t],r=Al(i.data,i.index,i.fieldIndex?(s)=>i.fieldIndex.remove(s):null);if(r>0)this._persistence.markDirty(this.collections,t),this._log(`TTL sweep: removed ${r} expired docs from "${t}"`)}}_buildCollectionContext(){let t=this;return{ensureConnected:()=>t._ensureConnected(),get txManager(){return t._txManager},get plugins(){return t._plugins},get eventBus(){return t._eventBus},get sessionStats(){return t._sessionStats},get queryLog(){return t._queryLog},get logger(){return t._logger},get persistence(){return t._persistence},get collections(){return t.collections},embed:(i)=>t.embed(i),get idGenerator(){return t._idGenerator},get autoSave(){return t._autoSave},saveCollection:(i)=>t.saveData(i),snapshotCollection:(i)=>t._snapshotCollection(i),getCollection:(i)=>t.useCollection(i),emitEvent:(i,r)=>t._emitEvent(i,r),runAfterHook:(i,r)=>t._runAfterHook(i,r),logChange:(i,r,s,n,a)=>t._logChange(i,r,s,n,a),get fs(){return t.fs},get dataDirectory(){return t.dataDirectory}}}_log(t){if(this.debug)this._logger(t,"info")}_snapshotCollection(t){return{data:structuredClone(t.data)}}_applySnapshot(t,i){let r=this.collections[t];if(!r)return;if(r.data=i.data,r.index=this.buildIndex(i.data,"_id"),r.fieldIndex)r.fieldIndex.buildFromData(i.data)}}function Gl(){let t=Date.now().toString(16),i;try{i=bo.randomBytes(8).toString("hex")}catch{let r=new Uint8Array(8);crypto.getRandomValues(r),i=Array.from(r).map((s)=>s.toString(16).padStart(2,"0")).join("")}return`${t}${i}`}function as(t,i){let r=t instanceof Error?t.message:t;if(i==="error")console.error(r);else console.log(r)}var os=new Set(["__proto__","constructor","prototype"]);function ni(t,i){if(!i.includes(".")){if(os.has(i))return;return t[i]}let r=t;for(let s of i.split(".")){if(os.has(s))return;if(r==null)return;r=r[s]}return r}class Qe extends Error{constructor(t,i,r={}){super(i);this.name=this.constructor.name,this.code=t,this.details=r}}class P extends Qe{}class je extends Qe{}class $e extends Qe{}class He extends Qe{}class Oe extends Qe{}class ft extends Qe{}function Pi(t,i){if(t===i)return!0;if(t==null||i==null)return!1;if(typeof t!==typeof i)return!1;if(t instanceof Date&&i instanceof Date)return t.getTime()===i.getTime();if(t instanceof RegExp&&i instanceof RegExp)return t.source===i.source&&t.flags===i.flags;if(Array.isArray(t)){if(!Array.isArray(i)||t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Pi(t[r],i[r]))return!1;return!0}if(typeof t==="object"){if(Array.isArray(i))return!1;let r=Object.keys(t);if(r.length!==Object.keys(i).length)return!1;for(let s of r){if(!Object.prototype.hasOwnProperty.call(i,s))return!1;if(!Pi(t[s],i[s]))return!1}return!0}return!1}function se(t,i){if(typeof i==="function")return i(t);if(i==null)return!0;if(typeof i==="object"&&Object.keys(i).length===0)return!0;if("$or"in i){let r=i.$or;if(!Array.isArray(r))throw new ft("ERR_SKALEX_QUERY_INVALID_OPERATOR","$or must be an array of filters",{operator:"$or"});if(!r.some((s)=>se(t,s)))return!1}if("$and"in i){let r=i.$and;if(!Array.isArray(r))throw new ft("ERR_SKALEX_QUERY_INVALID_OPERATOR","$and must be an array of filters",{operator:"$and"});if(!r.every((s)=>se(t,s)))return!1}if("$not"in i){if(se(t,i.$not))return!1}for(let r in i){if(r==="$or"||r==="$and"||r==="$not")continue;let s=i[r],n;try{n=ni(t,r)}catch{return!1}if(s instanceof RegExp){if(!s.test(String(n)))return!1}else if(typeof s==="object"&&s!==null){if(Object.keys(s).some((a)=>a.startsWith("$"))){if("$eq"in s&&n!==s.$eq)return!1;if("$ne"in s&&n===s.$ne)return!1;if("$gt"in s&&!(n>s.$gt))return!1;if("$lt"in s&&!(n<s.$lt))return!1;if("$gte"in s&&!(n>=s.$gte))return!1;if("$lte"in s&&!(n<=s.$lte))return!1;if("$in"in s&&!s.$in.includes(n))return!1;if("$nin"in s&&s.$nin.includes(n))return!1;if("$regex"in s){if(!(s.$regex instanceof RegExp?s.$regex:new RegExp(s.$regex)).test(String(n)))return!1}if("$fn"in s&&!s.$fn(n))return!1}else if(!Pi(n,s))return!1}else if(n!==s)return!1}return!0}function Hl(t,i=new Set){if(typeof t!=="object"||t===null||typeof t==="function")return t;let r=[],s=[],n=[],a=[],o=[];for(let l in t){if(l==="$or"||l==="$and"||l==="$not"){o.push(l);continue}let d=t[l];if(i.has(l))r.push(l);else if(d instanceof RegExp||typeof d==="object"&&d!==null&&(("$regex"in d)||("$fn"in d))||typeof d==="function")a.push(l);else if(typeof d==="object"&&d!==null&&(("$gt"in d)||("$lt"in d)||("$gte"in d)||("$lte"in d)||("$ne"in d)||("$in"in d)||("$nin"in d)))n.push(l);else s.push(l)}let c={};for(let l of[...r,...s,...n,...a,...o])c[l]=t[l];return c}var Mi=new Set(["string","number","boolean","object","array","date","any"]);function ir(t){if(Array.isArray(t))return"array";if(t instanceof Date)return"date";return typeof t}function Dn(t){let i=new Map,r=[];for(let[s,n]of Object.entries(t)){let a;if(typeof n==="string"){if(!Mi.has(n))throw new P("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${n}" for field "${s}"`,{field:s,type:n});a={type:n,required:!1,unique:!1}}else if(typeof n==="object"&&n!==null){let{type:o="any",required:c=!1,unique:l=!1,enum:d}=n;if(!Mi.has(o))throw new P("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${o}" for field "${s}"`,{field:s,type:o});if(a={type:o,required:c,unique:l,enum:d},l)r.push(s)}else throw new P("ERR_SKALEX_VALIDATION_INVALID_SCHEMA",`Invalid schema definition for field "${s}"`,{field:s});i.set(s,a)}return{fields:i,uniqueFields:r}}function ls(t,i,r=!1){let s=[];for(let[n,a]of i){let o=t[n],c=o===void 0||o===null;if(a.required&&c){s.push(`Field "${n}" is required`);continue}if(c)continue;if(a.type!=="any"){let l=ir(o);if(l!==a.type)s.push(`Field "${n}" must be of type "${a.type}", got "${l}"`)}if(a.enum&&!a.enum.includes(o))s.push(`Field "${n}" must be one of [${a.enum.map((l)=>JSON.stringify(l)).join(", ")}], got ${JSON.stringify(o)}`)}if(r){for(let n of Object.keys(t))if(!n.startsWith("_")&&!i.has(n))s.push(`Unknown field "${n}" (strict mode)`)}return s}function cs(t,i){let r={};for(let[s,n]of Object.entries(t)){if(s.startsWith("_")){r[s]=n;continue}if(!i.has(s))continue;let a=i.get(s);if(a.type!=="any"){if(ir(n)!==a.type)continue}if(a.enum&&!a.enum.includes(n))continue;r[s]=n}return r}function Wl(t){let i={};for(let[r,s]of Object.entries(t)){if(r.startsWith("_"))continue;let n=ir(s);i[r]=Mi.has(n)?n:"any"}return i}function Jl(t){if(typeof t==="number"){if(t<=0)throw new P("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got ${t}`,{ttl:t});return t*1000}if(typeof t!=="string")throw new P("ERR_SKALEX_VALIDATION_TTL",`Invalid TTL value: ${t}`,{ttl:t});let i=t.match(/^(\d+(?:\.\d+)?)(ms|s|m|h|d)$/);if(!i)throw new P("ERR_SKALEX_VALIDATION_TTL_FORMAT",`Invalid TTL format: "${t}". Use e.g. 300 (seconds), "30m", "24h", "7d"`,{ttl:t});let r=parseFloat(i[1]);if(r<=0)throw new P("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got "${t}"`,{ttl:t});let s=i[2],n=r*{ms:1,s:1000,m:60000,h:3600000,d:86400000}[s];if(!isFinite(n))throw new P("ERR_SKALEX_VALIDATION_TTL",`TTL value "${t}" is too large`,{ttl:t});return n}function Yl(t){return new Date(Date.now()+Jl(t))}function Ql(t,i,r=null){let s=Date.now(),n=0,a=t.length;while(a--){let o=t[a];if(o._expiresAt&&new Date(o._expiresAt).getTime()<=s){if(t.splice(a,1),i.delete(o._id),r)r(o);n++}}return n}function ds(t,i){if(t.length!==i.length)throw new ft("ERR_SKALEX_QUERY_VECTOR_MISMATCH",`Vector dimension mismatch: ${t.length} vs ${i.length}`,{expected:t.length,got:i.length});let r=0,s=0,n=0;for(let o=0;o<t.length;o++)r+=t[o]*i[o],s+=t[o]*t[o],n+=i[o]*i[o];let a=Math.sqrt(s*n);return a===0?0:r/a}function ee(t){if(!("_vector"in t))return{...t};let{_vector:i,...r}=t;return r}function Zl(t){return t.length}function ec(t,i){let r=0;for(let s of t){let n=ni(s,i);if(typeof n==="number"&&!isNaN(n))r+=n}return r}function tc(t,i){let r=0,s=0;for(let n of t){let a=ni(n,i);if(typeof a==="number"&&!isNaN(a))r+=a,s++}return s===0?null:r/s}function ic(t,i){let r=Object.create(null);for(let s of t){let n=String(ni(s,i)??"__null__");if(!r[n])r[n]=[];r[n].push(s)}return r}class Ln{constructor(t){this._col=t}get _ctx(){return this._col._ctx}async execute({op:t,beforeHook:i,afterHook:r,hookPayload:s,mutate:n,afterHookPayload:a,save:o,session:c}){let l=this._ctx;await l.ensureConnected(),this._col._txSnapshotIfNeeded();let d=l.txManager,u=d.active&&this._col._activeTxId===d.context?.id,f=u?d.context.id:null,h=this._col._createdInTxId,_=()=>{if(f!==null&&d._abortedIds.has(f))throw new $e("ERR_SKALEX_TX_ABORTED",`Transaction ${f} was aborted. No further mutations allowed.`);if(h!==null&&d._abortedIds.has(h))throw new $e("ERR_SKALEX_TX_ABORTED",`Transaction ${h} was aborted. Collection obtained inside that transaction cannot be used for further mutations.`)};if(u||h!==null)_();if(i)await l.plugins.run(i,s);let{docs:p,prevDocs:g=[]}=await n(_);if(l.persistence.markDirty(l.collections,this._col.name),await this._col._saveIfNeeded(o),this._col._changelogEnabled)for(let m=0;m<p.length;m++)await l.logChange(t,this._col.name,p[m],g[m]??null,c||null);if(!u||!d.defer(()=>l.sessionStats.recordWrite(c)))l.sessionStats.recordWrite(c);for(let m of p)l.emitEvent(this._col.name,{op:t,collection:this._col.name,doc:ee(m)});if(r)if(a)await l.runAfterHook(r,a(p));else for(let m of p)await l.runAfterHook(r,{collection:this._col.name,doc:ee(m)});return{docs:p,prevDocs:g}}}function rc(t){let i={};for(let r in t){if(r.startsWith("$"))continue;let s=t[r];if(s&&typeof s==="object"&&!Array.isArray(s)){let n=Object.keys(s);if(n.length===1&&n[0]==="$eq")i[r]=s.$eq}else i[r]=s}return i}var Pn=new Set(["__proto__","constructor","prototype"]);function Mn(t){if(typeof t!=="object"||t===null||Array.isArray(t))return t;let i={};for(let r of Object.keys(t)){if(Pn.has(r))continue;i[r]=Mn(t[r])}return i}class jn{constructor(t,i){this.name=t.collectionName,this.database=i,this._ctx=i._buildCollectionContext(),this._store=t,this._pipeline=new Ln(this),this._createdInTxId=i._txManager.context?.id??null,this._activeTxId=null}get _data(){return this._store.data}set _data(t){this._store.data=t}get _index(){return this._store.index}get _fieldIndex(){return this._store.fieldIndex||null}get _schema(){return this._store.schema?this._store.schema.fields:null}get _changelogEnabled(){return this._store.changelog===!0}get _softDelete(){return this._store.softDelete===!0}get _versioning(){return this._store.versioning===!0}get _strict(){return this._store.strict===!0}get _onSchemaError(){return this._store.onSchemaError??"throw"}get _defaultTtl(){return this._store.defaultTtl||null}get _defaultEmbed(){return this._store.defaultEmbed||null}get _maxDocs(){return this._store.maxDocs||null}async insertOne(t,i={}){let{save:r,ifNotExists:s,ttl:n,embed:a,session:o}=i;if(s){await this._ctx.ensureConnected();let l=this._findRaw(t);if(l)return ee({...l})}let{docs:c}=await this._insertCore([t],{ttl:n,embed:a,session:o,save:r});return ee(c[0])}async insertMany(t,i={}){let{save:r,ttl:s,embed:n,session:a}=i,{docs:o}=await this._insertCore(t,{ttl:s,embed:n,session:a,save:r});return o.map(ee)}async _insertCore(t,{ttl:i,embed:r,session:s,save:n}){return this._pipeline.execute({op:"insert",beforeHook:null,afterHook:"afterInsert",hookPayload:null,save:n,session:s,mutate:async(a)=>{let o=[],c=new Set;for(let l of t){let d=this._applyValidation(l);await this._ctx.plugins.run("beforeInsert",{collection:this.name,doc:d});let u=await this._buildDoc(d,{ttl:i,embed:r});if(this._index.has(u._id)||c.has(u._id))throw new je("ERR_SKALEX_UNIQUE_DUPLICATE_ID",`Duplicate _id "${u._id}" in collection "${this.name}"`,{id:u._id,collection:this.name});c.add(u._id),o.push(u)}if(a(),this._fieldIndex)this._fieldIndex.assertUniqueBatch(o);for(let l of o)this._addToIndex(l);this._data.push(...o);for(let l of o)this._index.set(l._id,l);return this._enforceCapAfterInsert(),{docs:o}}})}async updateOne(t,i,r={}){await this._ctx.ensureConnected();let s=this._findRaw(t);if(!s)return null;let{save:n,session:a}=r,{docs:o}=await this._updateCore([s],t,i,{save:n,session:a});return ee(o[0])}async updateMany(t,i,r={}){await this._ctx.ensureConnected();let s=this._findAllRaw(t);if(s.length===0)return[];let{save:n,session:a}=r,{docs:o}=await this._updateCore(s,t,i,{save:n,session:a});return o.map(ee)}async _updateCore(t,i,r,{save:s,session:n}){return this._pipeline.execute({op:"update",beforeHook:"beforeUpdate",afterHook:"afterUpdate",hookPayload:{collection:this.name,filter:i,update:r},save:s,session:n,afterHookPayload:(a)=>({collection:this.name,filter:i,update:r,result:a.length===1?a[0]:a}),mutate:async(a)=>{let o=this._changelogEnabled?t.map((u)=>structuredClone(u)):t.map(()=>null),c=t.map((u)=>this._prepareUpdatedDoc(u,r));this._assertUniqueCandidates(t,c),a();let l=new Set(t),d=new Map;for(let u=0;u<this._data.length;u++)if(l.has(this._data[u]))d.set(this._data[u],u);for(let u=0;u<t.length;u++)this._commitUpdatedDoc(t[u],c[u],d);return{docs:c,prevDocs:o}}})}applyUpdate(t,i){for(let r in i){if(Pn.has(r))continue;if(r==="_id"||r==="createdAt")continue;let s=i[r];if(Array.isArray(s))t[r]=s;else if(typeof s==="object"&&s!==null){let n=Object.keys(s);if(n.some((a)=>a.startsWith("$"))){for(let a of n)if(a==="$inc"&&typeof t[r]==="number")t[r]+=s[a];else if(a==="$push"){if(!Array.isArray(t[r]))t[r]=[];t[r].push(s[a])}}else t[r]=Mn(s)}else t[r]=s}if(t.updatedAt=new Date,this._versioning)t._version=(t._version??0)+1;return t}_prepareUpdatedDoc(t,i){let r=structuredClone(t),s=structuredClone(t);if(this.applyUpdate(s,i),!this._schema)return s;let n=ls(s,this._schema,this._strict);if(!n.length)return s;switch(this._onSchemaError){case"throw":throw new P("ERR_SKALEX_VALIDATION_UPDATE",`Update validation failed on doc "${t._id}": ${n.join("; ")}`,{id:t._id,errors:n});case"strip":return this._stripCandidateToValid(s,r);default:return this._ctx.logger(`[${this.name}] Update validation warning: ${n.join("; ")}`,"warn"),s}}_stripCandidateToValid(t,i){let r=cs(t,this._schema),s=structuredClone(i);for(let[n,a]of Object.entries(r)){if(n.startsWith("_"))continue;s[n]=a}if(s.updatedAt=t.updatedAt,this._versioning)s._version=t._version;return s}_commitUpdatedDoc(t,i,r){let s=r?r.get(t):this._data.indexOf(t);if(s===void 0||s===-1)throw new He("ERR_SKALEX_PERSISTENCE_DOC_MISSING",`Document "${t._id}" no longer exists in collection "${this.name}"`,{id:t._id,collection:this.name});this._data[s]=i,this._index.set(i._id,i),this._updateInIndex(t,i)}_assertUniqueCandidates(t,i){this._fieldIndex?.assertUniqueCandidates(t,i)}async upsert(t,i,r={}){if(await this._ctx.ensureConnected(),this._findRaw(t))return this.updateOne(t,i,r);return this.insertOne({...rc(t),...i},r)}async upsertMany(t,i,r={}){await this._ctx.ensureConnected();let{save:s,...n}=r,a=[];for(let o of t)a.push(await this.upsert({[i]:o[i]},o,{...n,save:!1}));return await this._saveIfNeeded(s),a}async restore(t,i={}){if(!this._softDelete)throw new ft("ERR_SKALEX_QUERY_SOFT_DELETE_REQUIRED",`restore() requires softDelete on "${this.name}"`,{collection:this.name});await this._ctx.ensureConnected();let{save:r,session:s}=i,n=this._findRaw(t,{includeDeleted:!0});if(!n||!n._deletedAt)return null;let{docs:a}=await this._pipeline.execute({op:"restore",beforeHook:null,afterHook:null,hookPayload:null,save:r,session:s,mutate:async(o)=>(o(),delete n._deletedAt,n.updatedAt=new Date,this._index.set(n._id,n),{docs:[n]})});return ee(a[0])}watch(t,i){if(typeof t==="function")i=t,t=null;if(i)return this._ctx.eventBus.on(this.name,(r)=>{if(!t||se(r.doc,t))i(r)});return this._watchIterator(t)}_watchIterator(t){let i=[],r=null,s=!1,n=this._ctx.eventBus.on(this.name,(a)=>{if(t&&!se(a.doc,t))return;if(r){let o=r;r=null,o({value:a,done:!1})}else i.push(a)});return{[Symbol.asyncIterator](){return this},next(){if(i.length>0)return Promise.resolve({value:i.shift(),done:!1});if(s)return Promise.resolve({value:void 0,done:!0});return new Promise((a)=>{r=a})},return(){if(s=!0,n(),r){let a=r;r=null,a({value:void 0,done:!0})}return Promise.resolve({value:void 0,done:!0})}}}async count(t={}){return await this._ctx.ensureConnected(),Zl(this._findAllRaw(t))}async sum(t,i={}){return await this._ctx.ensureConnected(),ec(this._findAllRaw(i),t)}async avg(t,i={}){return await this._ctx.ensureConnected(),tc(this._findAllRaw(i),t)}async groupBy(t,i={}){return await this._ctx.ensureConnected(),ic(this._findAllRaw(i),t)}async findOne(t,i={}){await this._ctx.ensureConnected();let{populate:r,select:s,includeDeleted:n=!1}=i,a=this._findRaw(t,{includeDeleted:n});if(!a)return null;let o=this._projectDoc(a,s);if(r)await this._populateDoc(o,a,r);return o}async find(t,i={}){await this._ctx.ensureConnected();let r=Date.now(),{populate:s,select:n,sort:a,page:o=1,limit:c,session:l,includeDeleted:d=!1}=i;await this._ctx.plugins.run("beforeFind",{collection:this.name,filter:t,options:i});let u=this._getCandidates(t),f=Hl(t,this._fieldIndex?this._fieldIndex.indexedFields:new Set),h=[];for(let p of u){if(this._softDelete&&p._deletedAt&&!d)continue;if(!se(p,f))continue;let g=this._projectDoc(p,n);if(s)await this._populateDoc(g,p,s);h.push(g)}if(a){let p=Object.keys(a);h.sort((g,m)=>{for(let w of p){let v=a[w];if(g[w]<m[w])return-v;if(g[w]>m[w])return v}return 0})}let _;if(c){let p=h.length,g=Math.ceil(p/c),m=(o-1)*c;h=h.slice(m,m+c),_={page:o,totalDocs:p,totalPages:g}}return this._ctx.queryLog?.record({collection:this.name,op:"find",filter:t,duration:Date.now()-r,resultCount:h.length}),this._ctx.sessionStats.recordRead(l),await this._ctx.plugins.run("afterFind",{collection:this.name,filter:t,options:i,docs:h}),_?{docs:h,..._}:{docs:h}}async search(t,{filter:i,limit:r=10,minScore:s=0,session:n}={}){await this._ctx.ensureConnected();let a=Date.now();await this._ctx.plugins.run("beforeSearch",{collection:this.name,query:t,options:{filter:i,limit:r,minScore:s}});let o=await this._ctx.embed(t),c=i?this._findAllRaw(i):this._data,l=[];for(let h of c){if(!h._vector)continue;let _=ds(o,h._vector);if(_>=s)l.push({doc:h,score:_})}l.sort((h,_)=>_.score-h.score);let d=l.slice(0,r);this._ctx.queryLog?.record({collection:this.name,op:"search",query:t,duration:Date.now()-a,resultCount:d.length}),this._ctx.sessionStats.recordRead(n);let u=d.map((h)=>ee(h.doc)),f=d.map((h)=>h.score);return await this._ctx.plugins.run("afterSearch",{collection:this.name,query:t,options:{filter:i,limit:r,minScore:s},docs:u,scores:f}),{docs:u,scores:f}}async similar(t,{limit:i=10,minScore:r=0}={}){await this._ctx.ensureConnected();let s=this._index.get(t);if(!s||!s._vector)return{docs:[],scores:[]};let n=[];for(let o of this._data){if(o._id===t||!o._vector)continue;let c=ds(s._vector,o._vector);if(c>=r)n.push({doc:o,score:c})}n.sort((o,c)=>c.score-o.score);let a=n.slice(0,i);return{docs:a.map((o)=>ee(o.doc)),scores:a.map((o)=>o.score)}}async deleteOne(t,i={}){await this._ctx.ensureConnected();let{save:r,session:s}=i;if(this._softDelete){let a=this._findRaw(t);if(!a)return null;let{docs:o}=await this._deleteCore("soft",[a],t,{save:r,session:s});return ee(o[0])}let{docs:n}=await this._deleteCore("hard",null,t,{save:r,session:s});if(n.length===0)return null;return ee(n[0])}async deleteMany(t,i={}){await this._ctx.ensureConnected();let{save:r,session:s}=i;if(this._softDelete){let a=this._findAllRaw(t);if(a.length===0)return[];let{docs:o}=await this._deleteCore("soft",a,t,{save:r,session:s});return o.map(ee)}let{docs:n}=await this._deleteCore("hardMany",null,t,{save:r,session:s});return n.map(ee)}async _deleteCore(t,i,r,{save:s,session:n}){return this._pipeline.execute({op:"delete",beforeHook:"beforeDelete",afterHook:"afterDelete",hookPayload:{collection:this.name,filter:r},save:s,session:n,afterHookPayload:(a)=>({collection:this.name,filter:r,result:a.length===1?a[0]:a}),mutate:async(a)=>{if(a(),t==="soft"){let l=new Date;for(let d of i)d._deletedAt=l,d.updatedAt=l,this._index.set(d._id,d);return{docs:i}}if(t==="hard"){let l=this._findIndex(r);if(l===-1)return{docs:[]};let d=this._data.splice(l,1)[0];return this._index.delete(d._id),this._removeFromIndex(d),{docs:[d]}}let o=[],c=[];for(let l of this._data)if(se(l,r))o.push(l),this._index.delete(l._id),this._removeFromIndex(l);else c.push(l);return this._data=c,{docs:o}}})}async export(t={},i={}){let{dir:r,name:s,format:n="json"}=i;try{let a=this._data.filter((u)=>se(u,t));if(a.length===0)throw new ft("ERR_SKALEX_QUERY_EXPORT_EMPTY",`export(): no documents matched the filter in "${this.name}"`,{collection:this.name});let o;if(n==="json")o=JSON.stringify(a,null,2);else{let u=(_)=>{if(_==null)return"";let p=typeof _==="object"?JSON.stringify(_):String(_);return p.includes(",")||p.includes('"')||p.includes(`
|
|
55
55
|
`)||p.includes("\r")?`"${p.replace(/"/g,'""')}"`:p},f=Object.keys(a[0]).map(u).join(","),h=a.map((_)=>Object.values(_).map(u).join(","));o=[f,...h].join(`
|
|
56
|
-
`)}if(typeof this._ctx.fs.writeRaw!=="function")throw new be("ERR_SKALEX_ADAPTER_NO_RAW_WRITE","export() requires a file-system adapter (FsAdapter). The current adapter does not support raw file writes.");let c=r||`${this._ctx.dataDirectory}/exports`,l=`${s||this.name}.${n}`,d=this._ctx.fs.join(c,l);this._ctx.fs.ensureDir(c),await this._ctx.fs.writeRaw(d,o)}catch(a){throw this._ctx.logger(`Error exporting "${this.name}": ${a.message}`,"error"),a}}_txSnapshotIfNeeded(){let t=this._ctx.txManager;if(!t.active)return;if(this._activeTxId!==t.context?.id)return;t.snapshotIfNeeded(this.name,this._store,(i)=>this._ctx.snapshotCollection(i))}async _saveIfNeeded(t){let i=this._ctx.txManager;if(i.active&&this._activeTxId===i.context?.id)return;if(t??this._ctx.autoSave)await this._ctx.saveCollection(this.name)}_applyValidation(t){if(!this._schema)return t;let i=os(t,this._schema,this._strict);if(!i.length)return t;switch(this._onSchemaError){case"warn":return this._ctx.logger(`[${this.name}] Validation warning: ${i.join("; ")}`,"warn"),t;case"strip":return ls(t,this._schema);default:throw new P("ERR_SKALEX_VALIDATION_FAILED",`Validation failed: ${i.join("; ")}`,{errors:i})}}_enforceCapAfterInsert(){let t=this._maxDocs;if(!t||this._data.length<=t)return;let i=this._data.splice(0,this._data.length-t);for(let r of i)this._index.delete(r._id),this._removeFromIndex(r)}_findRaw(t,{includeDeleted:i=!1}={}){if(typeof t==="function"){for(let r of this._data){if(this._softDelete&&r._deletedAt&&!i)continue;if(t(r))return r}return null}if(t._id){let r=this._index.get(t._id)||null;if(!r)return null;if(this._softDelete&&r._deletedAt&&!i)return null;if(Object.keys(t).length>1)return se(r,t)?r:null;return r}if(this._fieldIndex)for(let r in t){if(r==="$or"||r==="$and"||r==="$not")continue;let s=t[r];if(typeof s!=="object"||s===null){let n=this._fieldIndex._lookupIterable(r,s);if(n!==null){for(let a of n){if(this._softDelete&&a._deletedAt&&!i)continue;if(se(a,t))return a}return null}}}for(let r of this._data){if(this._softDelete&&r._deletedAt&&!i)continue;if(se(r,t))return r}return null}_findAllRaw(t,{includeDeleted:i=!1}={}){if(t&&typeof t!=="function"&&t._id){let s=this._index.get(t._id);if(!s)return[];if(this._softDelete&&s._deletedAt&&!i)return[];return se(s,t)?[s]:[]}let r=[];for(let s of this._getCandidates(t)){if(this._softDelete&&s._deletedAt&&!i)continue;if(se(s,t))r.push(s)}return r}_getCandidates(t){if(!this._fieldIndex)return this._data;if(this._fieldIndex._compoundIndexes.size>0){let i={};for(let r in t){if(r==="$or"||r==="$and"||r==="$not")continue;let s=t[r];if(typeof s!=="object"||s===null)i[r]=s}if(Object.keys(i).length>=2){let r=this._fieldIndex.lookupCompound(i);if(r!==null)return r}}for(let i in t){if(i==="$or"||i==="$and"||i==="$not")continue;let r=t[i];if(typeof r!=="object"||r===null){let s=this._fieldIndex._lookupIterable(i,r);if(s!==null)return s}}return this._data}_findIndex(t){for(let i=0;i<this._data.length;i++)if(se(this._data[i],t))return i;return-1}_addToIndex(t){if(this._fieldIndex)this._fieldIndex.add(t)}_removeFromIndex(t){if(this._fieldIndex)this._fieldIndex.remove(t)}_updateInIndex(t,i){if(this._fieldIndex)this._fieldIndex.update(t,i)}async _buildDoc(t,{ttl:i,embed:r}={}){let s={...t,_id:t._id??(this._ctx.idGenerator??Vl)(),createdAt:new Date,updatedAt:new Date},n=i??this._defaultTtl;if(n)s._expiresAt=Jl(n);let a=r??this._defaultEmbed;if(a){let o=typeof a==="function"?a(s):s[a];s._vector=await this._ctx.embed(String(o))}if(this._versioning)s._version=1;return s}_projectDoc(t,i){if(i){let s={};for(let n of i){if(n==="_vector")continue;s[n]=t[n]}return s}let r={...t};return delete r._vector,r}async _populateDoc(t,i,r){for(let s of r){let n=await this._ctx.getCollection(s).findOne({_id:i[s]});if(n)t[s]=n}}}class sr{async read(t){throw Error("StorageAdapter.read() not implemented")}async write(t,i){throw Error("StorageAdapter.write() not implemented")}async delete(t){throw Error("StorageAdapter.delete() not implemented")}async list(){throw Error("StorageAdapter.list() not implemented")}async writeAll(t){for(let{name:i,data:r}of t)await this.write(i,r)}}class jn extends sr{constructor({dir:t,format:i="gz"}){super();this.dir=nt.resolve(t),this.format=i,this._ensureDir(this.dir)}_ensureDir(t){if(!J.existsSync(t))J.mkdirSync(t,{recursive:!0})}_filePath(t){return nt.join(this.dir,`${t}.${this.format}`)}async read(t){let i=this._filePath(t);try{let r=await J.promises.readFile(i);if(this.format==="gz")r=Ii.inflateSync(r);return r.toString("utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}}async write(t,i){let r=this._filePath(t),s=nt.join(this.dir,`${t}_${globalThis.crypto.randomUUID()}.tmp.${this.format}`);if(this.format==="gz"){let n=Ii.deflateSync(i);await J.promises.writeFile(s,n)}else await J.promises.writeFile(s,i,"utf8");await J.promises.rename(s,r)}async writeAll(t){let i=[];try{for(let{name:r,data:s}of t){let n=this._filePath(r),a=nt.join(this.dir,`${r}_${globalThis.crypto.randomUUID()}.tmp.${this.format}`);if(this.format==="gz"){let o=Ii.deflateSync(s);await J.promises.writeFile(a,o)}else await J.promises.writeFile(a,s,"utf8");i.push({tmp:a,fp:n})}for(let{tmp:r,fp:s}of i)await J.promises.rename(r,s)}catch(r){for(let{tmp:s}of i)try{await J.promises.unlink(s)}catch{}throw r}}async delete(t){let i=this._filePath(t);try{await J.promises.unlink(i)}catch(r){if(r.code!=="ENOENT")throw r}}async list(){try{let t=await J.promises.readdir(this.dir),i=`.${this.format}`;return t.filter((r)=>r.endsWith(i)&&!r.includes(".tmp.")).map((r)=>r.slice(0,-i.length))}catch(t){if(t.code==="ENOENT")return[];throw t}}join(...t){return nt.join(...t)}ensureDir(t){this._ensureDir(t)}async writeRaw(t,i){this._ensureDir(nt.dirname(t)),await J.promises.writeFile(t,i,"utf8")}async readRaw(t){return J.promises.readFile(nt.resolve(t),"utf8")}}class qn{constructor(){this._migrations=[]}add(t){let{version:i,up:r}=t;if(typeof i!=="number"||i<1)throw new P("ERR_SKALEX_VALIDATION_MIGRATION",`Migration version must be a positive integer, got ${i}`,{version:i});if(typeof r!=="function")throw new P("ERR_SKALEX_VALIDATION_MIGRATION",`Migration version ${i} must have an "up" function`,{version:i});if(this._migrations.some((s)=>s.version===i))throw new P("ERR_SKALEX_VALIDATION_MIGRATION_DUPLICATE",`Migration version ${i} is already registered`,{version:i});this._migrations.push({...t}),this._migrations.sort((s,n)=>s.version-n.version)}async run(t,i=[]){let r=new Set(i),s=this._migrations.filter((n)=>!r.has(n.version));for(let n of s){let a=t(n.version);await n.up(a),r.add(n.version)}return[...r].sort((n,a)=>n-a)}status(t=[]){let i=new Set(t),r=this._migrations.map((s)=>s.version).filter((s)=>!i.has(s));return{current:t.length?Math.max(...t):0,applied:[...i].sort((s,n)=>s-n),pending:r}}}var ds={[Symbol.iterator](){return{next(){return{done:!0}}}},size:0};function us(t){return{[Symbol.iterator](){return t[Symbol.iterator]()},get size(){return t.size}}}function Ni(t){return t.map((i)=>{if(i===null||i===void 0)return"\x00";if(typeof i==="boolean")return i?"\x01T":"\x01F";if(typeof i==="number")return`\x02${i}`;return`\x03${String(i)}`}).join("\x1F")}class ri{constructor(t=[],i=[]){this._fields=new Set,this._compoundFields=[];for(let r of t)if(Array.isArray(r)){for(let s of r)this._validateFieldName(s);this._compoundFields.push(r)}else this._validateFieldName(r),this._fields.add(r);for(let r of i)this._validateFieldName(r);this._uniqueFields=new Set(i),this._indexedFields=new Set([...this._fields,...this._uniqueFields]),this._fieldIndexes=new Map,this._uniqueIndexes=new Map;for(let r of this._fields)this._fieldIndexes.set(r,new Map);for(let r of this._uniqueFields)if(this._uniqueIndexes.set(r,new Map),!this._fieldIndexes.has(r))this._fieldIndexes.set(r,new Map);this._compoundIndexes=new Map;for(let r of this._compoundFields)this._compoundIndexes.set(r.join("\x00"),{fields:r,map:new Map})}get indexedFields(){return this._indexedFields}buildFromData(t){for(let[,i]of this._fieldIndexes)i.clear();for(let[,i]of this._uniqueIndexes)i.clear();for(let[,i]of this._compoundIndexes)i.map.clear();for(let i of t)this._indexDoc(i)}add(t){this._checkUnique(t,null),this._indexDoc(t)}remove(t){for(let[i,r]of this._fieldIndexes){let s=t[i];if(s!==void 0){let n=r.get(s);if(n){if(n.delete(t),n.size===0)r.delete(s)}}}for(let[i,r]of this._uniqueIndexes){let s=t[i];if(s!==void 0)r.delete(s)}for(let[,i]of this._compoundIndexes){let r=Ni(i.fields.map((n)=>t[n])),s=i.map.get(r);if(s){if(s.delete(t),s.size===0)i.map.delete(r)}}}update(t,i){this._checkUnique(i,t),this.remove(t);try{this._indexDoc(i)}catch(r){try{this._indexDoc(t)}catch{}throw r}}lookup(t,i){let r=this._fieldIndexes.get(t);if(!r)return null;let s=r.get(i);return s?[...s]:[]}_lookupIterable(t,i){let r=this._fieldIndexes.get(t);if(!r)return null;let s=r.get(i);return s?us(s):ds}lookupCompound(t){let i=Object.keys(t).sort();for(let[,r]of this._compoundIndexes){let s=[...r.fields].sort();if(s.length!==i.length)continue;if(s.every((n,a)=>n===i[a])){let n=Ni(r.fields.map((o)=>t[o])),a=r.map.get(n);return a?us(a):ds}}return null}isUniqueTaken(t,i){let r=this._uniqueIndexes.get(t);if(!r)return!1;return r.has(i)}assertUniqueCandidates(t,i){if(this._uniqueFields.size===0)return;let r=new Set(t.map((s)=>s._id));for(let s of this._uniqueFields){let n=new Set,a=this._uniqueIndexes.get(s);if(a){for(let[c,l]of a.entries())if(!r.has(l._id))n.add(c)}let o=new Map;for(let c=0;c<i.length;c++){let l=i[c][s];if(l===void 0)continue;if(n.has(l))throw new je("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${s}" value "${l}" already exists`,{field:s,value:l});let d=o.get(l);if(d&&d!==t[c]._id)throw new je("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${s}" value "${l}" already exists`,{field:s,value:l});o.set(l,t[c]._id)}}}assertUniqueBatch(t){if(this._uniqueFields.size===0)return;for(let i of this._uniqueFields){let r=this._uniqueIndexes.get(i),s=new Set;for(let n of t){let a=n[i];if(a===void 0)continue;if(r&&r.has(a))throw new je("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${i}" value "${a}" already exists`,{field:i,value:a});if(s.has(a))throw new je("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: duplicate "${i}" value "${a}" within batch`,{field:i,value:a});s.add(a)}}}_validateFieldName(t){if(t.includes("."))throw new P("ERR_SKALEX_VALIDATION_INDEX_DOT_PATH",`Index fields cannot use dot-notation: "${t}". Use a flat field name.`,{field:t})}_indexDoc(t){for(let[i,r]of this._fieldIndexes){let s=t[i];if(s!==void 0){if(!r.has(s))r.set(s,new Set);r.get(s).add(t)}}for(let[i,r]of this._uniqueIndexes){let s=t[i];if(s!==void 0)r.set(s,t)}for(let[,i]of this._compoundIndexes){for(let s of i.fields){let n=t[s];if(n!==void 0&&n!==null&&typeof n==="object")throw new P("ERR_SKALEX_VALIDATION_COMPOUND_INDEX",`Compound index field "${s}" must be a scalar value (string, number, or boolean), got ${Array.isArray(n)?"array":typeof n}`,{field:s})}let r=Ni(i.fields.map((s)=>t[s]));if(!i.map.has(r))i.map.set(r,new Set);i.map.get(r).add(t)}}_checkUnique(t,i){for(let r of this._uniqueFields){let s=t[r];if(s===void 0)continue;let n=this._uniqueIndexes.get(r);if(!n)continue;let a=n.get(s);if(a&&a._id!==i?._id)throw new je("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${r}" value "${s}" already exists`,{field:r,value:s})}}}var Bt="_flush",Gt="migrations";class Un{constructor({adapter:t,serializer:i,deserializer:r,logger:s,debug:n=!1,lenientLoad:a=!1}){this._adapter=t,this._serializer=i,this._deserializer=r,this._logger=s,this._debug=n,this._lenientLoad=a,this._saveLock=Promise.resolve()}_withSaveLock(t){let i=this._saveLock.then(t);return this._saveLock=i.catch(()=>{}),i}async loadAll(t,{parseSchema:i,buildIndex:r,IndexEngine:s}){try{let n=await this._adapter.list();await Promise.all(n.map(async(a)=>{try{let o=await this._adapter.read(a);if(!o)return;let c=this._deserializer(o),{collectionName:l,data:d}=c;if(!l)return;let u=t[l],f=u?.rawSchema??c.rawSchema??null,h=u?.schema??(f?i(f):null),_=u?.changelog??c.changelog??!1,p=u?.softDelete??c.softDelete??!1,g=u?.versioning??c.versioning??!1,m=u?.strict??c.strict??!1,w=u?.onSchemaError??c.onSchemaError??"throw",v=u?.defaultTtl??c.defaultTtl??null,q=u?.defaultEmbed??c.defaultEmbed??null,E=u?.maxDocs??c.maxDocs??null,A=u?u.fieldIndex:null;if(!A&&h?.uniqueFields?.length)A=new s([],h.uniqueFields);let tt=r(d,"_id");if(A)A.buildFromData(d);t[l]={collectionName:l,data:d,index:tt,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:h,rawSchema:f,fieldIndex:A,changelog:_,softDelete:p,versioning:g,strict:m,onSchemaError:w,defaultTtl:v,defaultEmbed:q,maxDocs:E}}catch(o){if(o.code==="ENOENT")return;if(this._lenientLoad){this._logger(`WARNING: Could not load collection "${a}": ${o.message}. Collection will be empty.`,"error");return}throw new He("ERR_SKALEX_PERSISTENCE_CORRUPT",`Failed to load collection "${a}": ${o.message}`,{collection:a})}})),this._detectIncompleteFlush(t),await this._cleanOrphanTempFiles()}catch(n){if(n.code!=="ENOENT")throw this._logger(`Error loading data: ${n}`,"error"),n}}async save(t,i){if(i)await this._saveOne(t,i);else await Promise.all(Object.keys(t).map((r)=>this._saveOne(t,r)))}async saveDirty(t){let i=Object.keys(t).filter((r)=>t[r]._dirty);if(i.length===0)return;await Promise.all(i.map((r)=>this._saveOne(t,r)))}saveAtomic(t,i){return this._withSaveLock(async()=>{if(i.length===0)return;this._writeFlushSentinel(t,i);let r=new Set(i);r.add("_meta");let s=[...r].filter((n)=>t[n]).map((n)=>({name:n,data:this._serializeCollection(t[n])}));try{await this._adapter.writeAll(s)}catch(n){throw new He("ERR_SKALEX_PERSISTENCE_FLUSH_FAILED",`Batch save failed during writeAll: ${n.message}`,{collections:i})}for(let n of i)if(t[n])t[n]._dirty=!1;try{this._clearFlushSentinel(t),await this._adapter.write("_meta",this._serializeCollection(t._meta))}catch(n){this._logger(`WARNING: Batch data committed but sentinel clear failed: ${n.message}. Next load will report an incomplete flush (false positive).`,"error")}})}markDirty(t,i){let r=t[i];if(r)r._dirty=!0}_serializeCollection(t){let i={collectionName:t.collectionName,data:t.data};if(t.rawSchema)i.rawSchema=t.rawSchema;if(t.changelog)i.changelog=t.changelog;if(t.softDelete)i.softDelete=t.softDelete;if(t.versioning)i.versioning=t.versioning;if(t.strict)i.strict=t.strict;if(t.onSchemaError!=="throw")i.onSchemaError=t.onSchemaError;if(t.defaultTtl)i.defaultTtl=t.defaultTtl;if(t.defaultEmbed)i.defaultEmbed=t.defaultEmbed;if(t.maxDocs)i.maxDocs=t.maxDocs;return this._serializer(i)}async _saveOne(t,i){let r=t[i];if(!r)return;if(r.isSaving)return r._pendingSave=!0,new Promise((s,n)=>{(r._saveWaiters??=[]).push({resolve:s,reject:n})});r.isSaving=!0,r._pendingSave=!1;try{await this._writeCollection(i,r);while(r._pendingSave)r._pendingSave=!1,await this._writeCollection(i,r);this._resolveSaveWaiters(r)}catch(s){throw this._rejectSaveWaiters(r,s),s}finally{r.isSaving=!1}}async _writeCollection(t,i){try{await this._adapter.write(t,this._serializeCollection(i)),i._dirty=!1}catch(r){throw this._logger(`Error saving "${t}": ${r.message}`,"error"),r}}_resolveSaveWaiters(t){let i=t._saveWaiters?.splice(0)??[];for(let r of i)r.resolve()}_rejectSaveWaiters(t,i){let r=t._saveWaiters?.splice(0)??[];for(let s of r)s.reject(i)}_writeFlushSentinel(t,i){let r=this._getOrCreateMeta(t);r[Bt]={startedAt:new Date().toISOString(),collections:i,completedAt:null}}_clearFlushSentinel(t){let i=this._getOrCreateMeta(t);if(i[Bt])i[Bt].completedAt=new Date().toISOString()}_detectIncompleteFlush(t){let i=t._meta;if(!i)return;let r=i.index.get(Gt);if(!r)return;let s=r[Bt];if(!s)return;if(s.startedAt&&!s.completedAt)this._logger(`WARNING: Incomplete flush detected (started ${s.startedAt}, collections: ${s.collections?.join(", ")}). Data may be inconsistent.`,"error")}async _cleanOrphanTempFiles(){if(typeof this._adapter.join!=="function")return;if(typeof this._adapter.list!=="function")return;try{let t=await import("fs"),i=await import("path"),r=this._adapter.dir;if(!r)return;let s=(await t.default.promises.readdir(r)).filter((n)=>n.includes(".tmp."));for(let n of s){let a=i.default.join(r,n);try{await t.default.promises.unlink(a),this._log(`Cleaned orphan temp file: ${n}`)}catch{}}}catch{}}_getOrCreateMeta(t){if(!t._meta)t._meta={collectionName:"_meta",data:[],index:new Map,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:null,rawSchema:null,fieldIndex:null,changelog:!1,softDelete:!1,versioning:!1,strict:!1,onSchemaError:"throw",defaultTtl:null,defaultEmbed:null,maxDocs:null};let i=t._meta,r=i.index.get(Gt);if(!r)r={_id:Gt},i.data.push(r),i.index.set(Gt,r);return r}_log(t){if(this._debug)this._logger(t,"info")}}var rc=0;class Fn{constructor(){this._txLock=Promise.resolve(),this._ctx=null,this._abortedIds=new Set}get active(){return this._ctx!==null&&!this._ctx.aborted}get context(){return this._ctx}async run(t,i,{timeout:r=0}={}){let s=async()=>{await i._ensureConnected();let a=new Set(Object.keys(i.collections)),o={id:++rc,startedAt:Date.now(),aborted:!1,preExisting:a,touchedCollections:new Set,snapshots:new Map,deferredEffects:[],timeout:r};this._ctx=o;let c=null,l=r>0?new Promise((f,h)=>{c=setTimeout(()=>{o.aborted=!0,h(new Ne("ERR_SKALEX_TX_TIMEOUT",`Transaction ${o.id} timed out after ${r}ms`))},r)}):null,d=this,u=new Proxy(i,{get(f,h){if(h==="_txId")return o.id;if(o!==d._ctx)throw new Ne("ERR_SKALEX_TX_STALE_PROXY",`Transaction ${o.id} has ended. This proxy is no longer usable.`);if(h==="collections")throw new Ne("ERR_SKALEX_TX_DIRECT_ACCESS","Direct access to db.collections inside transaction() is not covered by rollback. Use the collection API (db.useCollection) instead.");if(h==="useCollection")return(p)=>{let g=f.useCollection(p);return g._activeTxId=o.id,g};let _=Reflect.get(f,h);return typeof _==="function"?_.bind(f):_}});try{let f=t(u),h=l?await Promise.race([f,l]):await f;if(o.aborted)throw new Ne("ERR_SKALEX_TX_ABORTED",`Transaction ${o.id} was aborted`);let _=[...o.touchedCollections];if(_.length>0)await i._persistence.saveAtomic(i.collections,_);for(let p of o.deferredEffects)await p();return h}catch(f){for(let[h,_]of o.snapshots)if(o.preExisting.has(h)){if(i._applySnapshot(h,_),i.collections[h])i.collections[h]._dirty=_._dirty}for(let h in i.collections)if(!o.preExisting.has(h))delete i.collections[h],delete i._collectionInstances[h];throw f}finally{if(c)clearTimeout(c);if(o.aborted)this._abortedIds.add(o.id);this._ctx=null;for(let f in i._collectionInstances){let h=i._collectionInstances[f];if(h._createdInTxId===o.id)h._createdInTxId=null;if(h._activeTxId===o.id)h._activeTxId=null}}},n=this._txLock.then(s);return this._txLock=n.catch(()=>{}),n}snapshotIfNeeded(t,i,r){let s=this._ctx;if(!s)return;if(this._assertCtxNotAborted(s),!s.snapshots.has(t)){let n=r(i);n._dirty=i._dirty??!1,s.snapshots.set(t,n)}s.touchedCollections.add(t)}assertNotAborted(){let t=this._ctx;if(t)this._assertCtxNotAborted(t)}_assertCtxNotAborted(t){if(t.aborted)throw new Ne("ERR_SKALEX_TX_ABORTED",`Transaction ${t.id} was aborted. No further mutations allowed.`)}defer(t){if(this._ctx)return this._ctx.deferredEffects.push(t),!0;return!1}}class Kn{constructor(t){this._CollectionClass=t,this.stores={},this._instances={}}get(t,i){if(this._instances[t])return this._instances[t];if(!this.stores[t])this.createStore(t);let r=new this._CollectionClass(this.stores[t],i);return this._instances[t]=r,r}create(t,i={},r){this.createStore(t,i);let s=new this._CollectionClass(this.stores[t],r);return this._instances[t]=s,s}createStore(t,{schema:i,indexes:r=[],changelog:s=!1,softDelete:n=!1,versioning:a=!1,strict:o=!1,onSchemaError:c="throw",defaultTtl:l=null,defaultEmbed:d=null,maxDocs:u=null}={}){let f=null,h=null;if(i){f=kn(i);let _=f.uniqueFields;if(r.length||_.length)h=new ri(r,_)}else if(r.length)h=new ri(r,[]);this.stores[t]={collectionName:t,data:[],index:new Map,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:f,rawSchema:i||null,fieldIndex:h,changelog:s,softDelete:n,versioning:a,strict:o,onSchemaError:c,defaultTtl:l,defaultEmbed:d,maxDocs:u}}rename(t,i){if(!this.stores[t])throw new He("ERR_SKALEX_PERSISTENCE_COLLECTION_NOT_FOUND",`Collection "${t}" not found`,{collection:t});if(this.stores[i])throw new He("ERR_SKALEX_PERSISTENCE_COLLECTION_EXISTS",`Collection "${i}" already exists`,{collection:i});let r=this.stores[t];if(r.collectionName=i,this.stores[i]=r,delete this.stores[t],this._instances[t]){let s=this._instances[t];s.name=i,this._instances[i]=s,delete this._instances[t]}}buildIndex(t,i){let r=new Map;for(let s of t)r.set(s[i],s);return r}inspect(t){if(t){let r=this.stores[t];if(!r)return null;return{name:t,count:r.data.length,schema:r.schema?Object.fromEntries(r.schema.fields):null,indexes:r.fieldIndex?[...r.fieldIndex.indexedFields]:[],softDelete:r.softDelete??!1,versioning:r.versioning??!1,strict:r.strict??!1,onSchemaError:r.onSchemaError??"throw",maxDocs:r.maxDocs??null}}let i={};for(let r in this.stores)i[r]=this.inspect(r);return i}dump(){let t={};for(let i in this.stores)if(!i.startsWith("_"))t[i]=structuredClone(this.stores[i].data);return t}schema(t){let i=this.stores[t];if(!i)return null;if(i.schema)return Object.fromEntries([...i.schema.fields.entries()].map(([r,s])=>[r,s.type]));if(i.data.length>0)return Hl(i.data[0]);return null}stats(t){let i=(r)=>{let s=this.stores[r];if(!s)return null;let n=s.data.length,a=0;for(let o of s.data)try{a+=JSON.stringify(o).length}catch(c){}return{collection:r,count:n,estimatedSize:a,avgDocSize:n>0?Math.round(a/n):0}};if(t)return i(t);return Object.keys(this.stores).map(i)}clear(){this.stores={},this._instances={}}}class nr{async embed(t){throw Error("EmbeddingAdapter.embed() not implemented")}}var ve=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class zn extends nr{constructor({apiKey:t=ve("OPENAI_API_KEY"),model:i=ve("OPENAI_EMBED_MODEL")??"text-embedding-3-small",baseUrl:r=ve("OPENAI_EMBED_BASE_URL")??"https://api.openai.com/v1/embeddings",dimensions:s=ve("OPENAI_EMBED_DIMENSIONS")!=null?Number(ve("OPENAI_EMBED_DIMENSIONS")):void 0,organization:n=ve("OPENAI_ORGANIZATION")??void 0,timeout:a=ve("OPENAI_EMBED_TIMEOUT")!=null?Number(ve("OPENAI_EMBED_TIMEOUT")):void 0,retries:o=Number(ve("OPENAI_EMBED_RETRIES")??0),retryDelay:c=Number(ve("OPENAI_EMBED_RETRY_DELAY")??1000),headers:l={},fetch:d=globalThis.fetch}={}){super();if(!t)throw Error("OpenAIEmbeddingAdapter requires an apiKey");this.apiKey=t,this.model=i,this.baseUrl=r,this.dimensions=s,this.organization=n,this.timeout=a,this.retries=o,this.retryDelay=c,this.headers=l,this._fetch=d}async embed(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,...this.organization&&{"OpenAI-Organization":this.organization},...this.headers},body:JSON.stringify({input:t,model:this.model,...this.dimensions!==void 0&&{dimensions:this.dimensions}}),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`OpenAI embedding API error ${a.status}: ${o}`)}return(await a.json()).data[0].embedding}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}var vt=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class Bn extends nr{constructor({model:t=vt("OLLAMA_EMBED_MODEL")??"nomic-embed-text",host:i=vt("OLLAMA_HOST")??"http://localhost:11434",timeout:r=vt("OLLAMA_EMBED_TIMEOUT")!=null?Number(vt("OLLAMA_EMBED_TIMEOUT")):void 0,retries:s=Number(vt("OLLAMA_EMBED_RETRIES")??0),retryDelay:n=Number(vt("OLLAMA_EMBED_RETRY_DELAY")??1000),headers:a={},fetch:o=globalThis.fetch}={}){super();this.model=t,this.host=i,this.timeout=r,this.retries=s,this.retryDelay=n,this.headers=a,this._fetch=o}async embed(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(`${this.host}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json",...this.headers},body:JSON.stringify({model:this.model,prompt:t}),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`Ollama embedding API error ${a.status}: ${o}`)}return(await a.json()).embedding}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}class fi{async generate(t,i){throw Error("LLMAdapter.generate() not implemented")}async summarize(t){throw Error("LLMAdapter.summarize() not implemented")}}var ar=`You are a database query assistant. Convert the user's natural language request into a JSON filter object for a document database.
|
|
56
|
+
`)}if(typeof this._ctx.fs.writeRaw!=="function")throw new Oe("ERR_SKALEX_ADAPTER_NO_RAW_WRITE","export() requires a file-system adapter (FsAdapter). The current adapter does not support raw file writes.");let c=r||`${this._ctx.dataDirectory}/exports`,l=`${s||this.name}.${n}`,d=this._ctx.fs.join(c,l);this._ctx.fs.ensureDir(c),await this._ctx.fs.writeRaw(d,o)}catch(a){throw this._ctx.logger(`Error exporting "${this.name}": ${a.message}`,"error"),a}}_txSnapshotIfNeeded(){let t=this._ctx.txManager;if(!t.active)return;if(this._activeTxId!==t.context?.id)return;t.snapshotIfNeeded(this.name,this._store,(i)=>this._ctx.snapshotCollection(i))}async _saveIfNeeded(t){let i=this._ctx.txManager;if(i.active&&this._activeTxId===i.context?.id)return;if(t??this._ctx.autoSave)await this._ctx.saveCollection(this.name)}_applyValidation(t){if(!this._schema)return t;let i=ls(t,this._schema,this._strict);if(!i.length)return t;switch(this._onSchemaError){case"warn":return this._ctx.logger(`[${this.name}] Validation warning: ${i.join("; ")}`,"warn"),t;case"strip":return cs(t,this._schema);default:throw new P("ERR_SKALEX_VALIDATION_FAILED",`Validation failed: ${i.join("; ")}`,{errors:i})}}_enforceCapAfterInsert(){let t=this._maxDocs;if(!t||this._data.length<=t)return;let i=this._data.splice(0,this._data.length-t);for(let r of i)this._index.delete(r._id),this._removeFromIndex(r)}_findRaw(t,{includeDeleted:i=!1}={}){if(typeof t==="function"){for(let r of this._data){if(this._softDelete&&r._deletedAt&&!i)continue;if(t(r))return r}return null}if(t._id){let r=this._index.get(t._id)||null;if(!r)return null;if(this._softDelete&&r._deletedAt&&!i)return null;if(Object.keys(t).length>1)return se(r,t)?r:null;return r}if(this._fieldIndex)for(let r in t){if(r==="$or"||r==="$and"||r==="$not")continue;let s=t[r];if(typeof s!=="object"||s===null){let n=this._fieldIndex._lookupIterable(r,s);if(n!==null){for(let a of n){if(this._softDelete&&a._deletedAt&&!i)continue;if(se(a,t))return a}return null}}}for(let r of this._data){if(this._softDelete&&r._deletedAt&&!i)continue;if(se(r,t))return r}return null}_findAllRaw(t,{includeDeleted:i=!1}={}){if(t&&typeof t!=="function"&&t._id){let s=this._index.get(t._id);if(!s)return[];if(this._softDelete&&s._deletedAt&&!i)return[];return se(s,t)?[s]:[]}let r=[];for(let s of this._getCandidates(t)){if(this._softDelete&&s._deletedAt&&!i)continue;if(se(s,t))r.push(s)}return r}_getCandidates(t){if(!this._fieldIndex)return this._data;if(this._fieldIndex._compoundIndexes.size>0){let i={};for(let r in t){if(r==="$or"||r==="$and"||r==="$not")continue;let s=t[r];if(typeof s!=="object"||s===null)i[r]=s}if(Object.keys(i).length>=2){let r=this._fieldIndex.lookupCompound(i);if(r!==null)return r}}for(let i in t){if(i==="$or"||i==="$and"||i==="$not")continue;let r=t[i];if(typeof r!=="object"||r===null){let s=this._fieldIndex._lookupIterable(i,r);if(s!==null)return s}}return this._data}_findIndex(t){for(let i=0;i<this._data.length;i++)if(se(this._data[i],t))return i;return-1}_addToIndex(t){if(this._fieldIndex)this._fieldIndex.add(t)}_removeFromIndex(t){if(this._fieldIndex)this._fieldIndex.remove(t)}_updateInIndex(t,i){if(this._fieldIndex)this._fieldIndex.update(t,i)}async _buildDoc(t,{ttl:i,embed:r}={}){let s={...t,_id:t._id??(this._ctx.idGenerator??Gl)(),createdAt:new Date,updatedAt:new Date},n=i??this._defaultTtl;if(n)s._expiresAt=Yl(n);let a=r??this._defaultEmbed;if(a){let o=typeof a==="function"?a(s):s[a];s._vector=await this._ctx.embed(String(o))}if(this._versioning)s._version=1;return s}_projectDoc(t,i){if(i){let s={};for(let n of i){if(n==="_vector")continue;s[n]=t[n]}return s}let r={...t};return delete r._vector,r}async _populateDoc(t,i,r){for(let s of r){let n=await this._ctx.getCollection(s).findOne({_id:i[s]});if(n)t[s]=n}}}class sr{async read(t){throw Error("StorageAdapter.read() not implemented")}async write(t,i){throw Error("StorageAdapter.write() not implemented")}async delete(t){throw Error("StorageAdapter.delete() not implemented")}async list(){throw Error("StorageAdapter.list() not implemented")}async writeAll(t){for(let{name:i,data:r}of t)await this.write(i,r)}}class qn extends sr{constructor({dir:t,format:i="gz"}){super();this.dir=st.resolve(t),this.format=i,this._ensureDir(this.dir)}_ensureDir(t){if(!J.existsSync(t))J.mkdirSync(t,{recursive:!0})}_filePath(t){return st.join(this.dir,`${t}.${this.format}`)}async read(t){let i=this._filePath(t);try{let r=await J.promises.readFile(i);if(this.format==="gz")r=Ei.inflateSync(r);return r.toString("utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}}async write(t,i){let r=this._filePath(t),s=st.join(this.dir,`${t}_${globalThis.crypto.randomUUID()}.tmp.${this.format}`);if(this.format==="gz"){let n=Ei.deflateSync(i);await J.promises.writeFile(s,n)}else await J.promises.writeFile(s,i,"utf8");await J.promises.rename(s,r)}async writeAll(t){let i=[];try{for(let{name:r,data:s}of t){let n=this._filePath(r),a=st.join(this.dir,`${r}_${globalThis.crypto.randomUUID()}.tmp.${this.format}`);if(this.format==="gz"){let o=Ei.deflateSync(s);await J.promises.writeFile(a,o)}else await J.promises.writeFile(a,s,"utf8");i.push({tmp:a,fp:n})}for(let{tmp:r,fp:s}of i)await J.promises.rename(r,s)}catch(r){for(let{tmp:s}of i)try{await J.promises.unlink(s)}catch{}throw r}}async delete(t){let i=this._filePath(t);try{await J.promises.unlink(i)}catch(r){if(r.code!=="ENOENT")throw r}}async list(){try{let t=await J.promises.readdir(this.dir),i=`.${this.format}`;return t.filter((r)=>r.endsWith(i)&&!r.includes(".tmp.")).map((r)=>r.slice(0,-i.length))}catch(t){if(t.code==="ENOENT")return[];throw t}}join(...t){return st.join(...t)}ensureDir(t){this._ensureDir(t)}async writeRaw(t,i){this._ensureDir(st.dirname(t)),await J.promises.writeFile(t,i,"utf8")}async readRaw(t){return J.promises.readFile(st.resolve(t),"utf8")}}class Un{constructor(){this._migrations=[]}add(t){let{version:i,up:r}=t;if(typeof i!=="number"||i<1)throw new P("ERR_SKALEX_VALIDATION_MIGRATION",`Migration version must be a positive integer, got ${i}`,{version:i});if(typeof r!=="function")throw new P("ERR_SKALEX_VALIDATION_MIGRATION",`Migration version ${i} must have an "up" function`,{version:i});if(this._migrations.some((s)=>s.version===i))throw new P("ERR_SKALEX_VALIDATION_MIGRATION_DUPLICATE",`Migration version ${i} is already registered`,{version:i});this._migrations.push({...t}),this._migrations.sort((s,n)=>s.version-n.version)}async run(t,i=[]){let r=new Set(i),s=this._migrations.filter((n)=>!r.has(n.version));for(let n of s){let a=t(n.version);await n.up(a),r.add(n.version)}return[...r].sort((n,a)=>n-a)}status(t=[]){let i=new Set(t),r=this._migrations.map((s)=>s.version).filter((s)=>!i.has(s));return{current:t.length?Math.max(...t):0,applied:[...i].sort((s,n)=>s-n),pending:r}}}var us={[Symbol.iterator](){return{next(){return{done:!0}}}},size:0};function hs(t){return{[Symbol.iterator](){return t[Symbol.iterator]()},get size(){return t.size}}}function Oi(t){return t.map((i)=>{if(i===null||i===void 0)return"\x00";if(typeof i==="boolean")return i?"\x01T":"\x01F";if(typeof i==="number")return`\x02${i}`;return`\x03${String(i)}`}).join("\x1F")}class Zt{constructor(t=[],i=[]){this._fields=new Set,this._compoundFields=[];for(let r of t)if(Array.isArray(r)){for(let s of r)this._validateFieldName(s);this._compoundFields.push(r)}else this._validateFieldName(r),this._fields.add(r);for(let r of i)this._validateFieldName(r);this._uniqueFields=new Set(i),this._indexedFields=new Set([...this._fields,...this._uniqueFields]),this._fieldIndexes=new Map,this._uniqueIndexes=new Map;for(let r of this._fields)this._fieldIndexes.set(r,new Map);for(let r of this._uniqueFields)if(this._uniqueIndexes.set(r,new Map),!this._fieldIndexes.has(r))this._fieldIndexes.set(r,new Map);this._compoundIndexes=new Map;for(let r of this._compoundFields)this._compoundIndexes.set(r.join("\x00"),{fields:r,map:new Map})}get indexedFields(){return this._indexedFields}buildFromData(t){for(let[,i]of this._fieldIndexes)i.clear();for(let[,i]of this._uniqueIndexes)i.clear();for(let[,i]of this._compoundIndexes)i.map.clear();for(let i of t)this._indexDoc(i)}add(t){this._checkUnique(t,null),this._indexDoc(t)}remove(t){for(let[i,r]of this._fieldIndexes){let s=t[i];if(s!==void 0){let n=r.get(s);if(n){if(n.delete(t),n.size===0)r.delete(s)}}}for(let[i,r]of this._uniqueIndexes){let s=t[i];if(s!==void 0)r.delete(s)}for(let[,i]of this._compoundIndexes){let r=Oi(i.fields.map((n)=>t[n])),s=i.map.get(r);if(s){if(s.delete(t),s.size===0)i.map.delete(r)}}}update(t,i){this._checkUnique(i,t),this.remove(t);try{this._indexDoc(i)}catch(r){try{this._indexDoc(t)}catch{}throw r}}lookup(t,i){let r=this._fieldIndexes.get(t);if(!r)return null;let s=r.get(i);return s?[...s]:[]}_lookupIterable(t,i){let r=this._fieldIndexes.get(t);if(!r)return null;let s=r.get(i);return s?hs(s):us}lookupCompound(t){let i=Object.keys(t).sort();for(let[,r]of this._compoundIndexes){let s=[...r.fields].sort();if(s.length!==i.length)continue;if(s.every((n,a)=>n===i[a])){let n=Oi(r.fields.map((o)=>t[o])),a=r.map.get(n);return a?hs(a):us}}return null}isUniqueTaken(t,i){let r=this._uniqueIndexes.get(t);if(!r)return!1;return r.has(i)}assertUniqueCandidates(t,i){if(this._uniqueFields.size===0)return;let r=new Set(t.map((s)=>s._id));for(let s of this._uniqueFields){let n=new Set,a=this._uniqueIndexes.get(s);if(a){for(let[c,l]of a.entries())if(!r.has(l._id))n.add(c)}let o=new Map;for(let c=0;c<i.length;c++){let l=i[c][s];if(l===void 0)continue;if(n.has(l))throw new je("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${s}" value "${l}" already exists`,{field:s,value:l});let d=o.get(l);if(d&&d!==t[c]._id)throw new je("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${s}" value "${l}" already exists`,{field:s,value:l});o.set(l,t[c]._id)}}}assertUniqueBatch(t){if(this._uniqueFields.size===0)return;for(let i of this._uniqueFields){let r=this._uniqueIndexes.get(i),s=new Set;for(let n of t){let a=n[i];if(a===void 0)continue;if(r&&r.has(a))throw new je("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${i}" value "${a}" already exists`,{field:i,value:a});if(s.has(a))throw new je("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: duplicate "${i}" value "${a}" within batch`,{field:i,value:a});s.add(a)}}}_validateFieldName(t){if(t.includes("."))throw new P("ERR_SKALEX_VALIDATION_INDEX_DOT_PATH",`Index fields cannot use dot-notation: "${t}". Use a flat field name.`,{field:t})}_indexDoc(t){for(let[i,r]of this._fieldIndexes){let s=t[i];if(s!==void 0){if(!r.has(s))r.set(s,new Set);r.get(s).add(t)}}for(let[i,r]of this._uniqueIndexes){let s=t[i];if(s!==void 0)r.set(s,t)}for(let[,i]of this._compoundIndexes){for(let s of i.fields){let n=t[s];if(n!==void 0&&n!==null&&typeof n==="object")throw new P("ERR_SKALEX_VALIDATION_COMPOUND_INDEX",`Compound index field "${s}" must be a scalar value (string, number, or boolean), got ${Array.isArray(n)?"array":typeof n}`,{field:s})}let r=Oi(i.fields.map((s)=>t[s]));if(!i.map.has(r))i.map.set(r,new Set);i.map.get(r).add(t)}}_checkUnique(t,i){for(let r of this._uniqueFields){let s=t[r];if(s===void 0)continue;let n=this._uniqueIndexes.get(r);if(!n)continue;let a=n.get(s);if(a&&a._id!==i?._id)throw new je("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${r}" value "${s}" already exists`,{field:r,value:s})}}}var Bt="_flush",Xt="migrations";class Fn{constructor({adapter:t,serializer:i,deserializer:r,logger:s,debug:n=!1,lenientLoad:a=!1}){this._adapter=t,this._serializer=i,this._deserializer=r,this._logger=s,this._debug=n,this._lenientLoad=a,this._saveLock=Promise.resolve()}_withSaveLock(t){let i=this._saveLock.then(t);return this._saveLock=i.catch(()=>{}),i}async loadAll(t,{parseSchema:i,buildIndex:r,IndexEngine:s}){try{let n=await this._adapter.list();await Promise.all(n.map(async(a)=>{try{let o=await this._adapter.read(a);if(!o)return;let c=this._deserializer(o),{collectionName:l,data:d}=c;if(!l)return;let u=t[l],f=u?.rawSchema??c.rawSchema??null,h=u?.schema??(f?i(f):null),_=u?.changelog??c.changelog??!1,p=u?.softDelete??c.softDelete??!1,g=u?.versioning??c.versioning??!1,m=u?.strict??c.strict??!1,w=u?.onSchemaError??c.onSchemaError??"throw",v=u?.defaultTtl??c.defaultTtl??null,q=u?.defaultEmbed??c.defaultEmbed??null,E=u?.maxDocs??c.maxDocs??null,A=u?u.fieldIndex:null;if(!A&&h?.uniqueFields?.length)A=new s([],h.uniqueFields);let tt=r(d,"_id");if(A)A.buildFromData(d);t[l]={collectionName:l,data:d,index:tt,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:h,rawSchema:f,fieldIndex:A,changelog:_,softDelete:p,versioning:g,strict:m,onSchemaError:w,defaultTtl:v,defaultEmbed:q,maxDocs:E}}catch(o){if(o.code==="ENOENT")return;if(this._lenientLoad){this._logger(`WARNING: Could not load collection "${a}": ${o.message}. Collection will be empty.`,"error");return}throw new He("ERR_SKALEX_PERSISTENCE_CORRUPT",`Failed to load collection "${a}": ${o.message}`,{collection:a})}})),this._detectIncompleteFlush(t),await this._cleanOrphanTempFiles()}catch(n){if(n.code!=="ENOENT")throw this._logger(`Error loading data: ${n}`,"error"),n}}async save(t,i){if(i)await this._saveOne(t,i);else await Promise.all(Object.keys(t).map((r)=>this._saveOne(t,r)))}async saveDirty(t){let i=Object.keys(t).filter((r)=>t[r]._dirty);if(i.length===0)return;await Promise.all(i.map((r)=>this._saveOne(t,r)))}saveAtomic(t,i){return this._withSaveLock(async()=>{if(i.length===0)return;this._writeFlushSentinel(t,i);let r=new Set(i);r.add("_meta");let s=[...r].filter((n)=>t[n]).map((n)=>({name:n,data:this._serializeCollection(t[n])}));try{await this._adapter.writeAll(s)}catch(n){throw new He("ERR_SKALEX_PERSISTENCE_FLUSH_FAILED",`Batch save failed during writeAll: ${n.message}`,{collections:i})}for(let n of i)if(t[n])t[n]._dirty=!1;try{this._clearFlushSentinel(t),await this._adapter.write("_meta",this._serializeCollection(t._meta))}catch(n){this._logger(`WARNING: Batch data committed but sentinel clear failed: ${n.message}. Next load will report an incomplete flush (false positive).`,"error")}})}markDirty(t,i){let r=t[i];if(r)r._dirty=!0}_serializeCollection(t){let i={collectionName:t.collectionName,data:t.data};if(t.rawSchema)i.rawSchema=t.rawSchema;if(t.changelog)i.changelog=t.changelog;if(t.softDelete)i.softDelete=t.softDelete;if(t.versioning)i.versioning=t.versioning;if(t.strict)i.strict=t.strict;if(t.onSchemaError!=="throw")i.onSchemaError=t.onSchemaError;if(t.defaultTtl)i.defaultTtl=t.defaultTtl;if(t.defaultEmbed)i.defaultEmbed=t.defaultEmbed;if(t.maxDocs)i.maxDocs=t.maxDocs;return this._serializer(i)}async _saveOne(t,i){let r=t[i];if(!r)return;if(r.isSaving)return r._pendingSave=!0,new Promise((s,n)=>{(r._saveWaiters??=[]).push({resolve:s,reject:n})});r.isSaving=!0,r._pendingSave=!1;try{await this._writeCollection(i,r);while(r._pendingSave)r._pendingSave=!1,await this._writeCollection(i,r);this._resolveSaveWaiters(r)}catch(s){throw this._rejectSaveWaiters(r,s),s}finally{r.isSaving=!1}}async _writeCollection(t,i){try{await this._adapter.write(t,this._serializeCollection(i)),i._dirty=!1}catch(r){throw this._logger(`Error saving "${t}": ${r.message}`,"error"),r}}_resolveSaveWaiters(t){let i=t._saveWaiters?.splice(0)??[];for(let r of i)r.resolve()}_rejectSaveWaiters(t,i){let r=t._saveWaiters?.splice(0)??[];for(let s of r)s.reject(i)}_writeFlushSentinel(t,i){let r=this._getOrCreateMeta(t);r[Bt]={startedAt:new Date().toISOString(),collections:i,completedAt:null}}_clearFlushSentinel(t){let i=this._getOrCreateMeta(t);if(i[Bt])i[Bt].completedAt=new Date().toISOString()}_detectIncompleteFlush(t){let i=t._meta;if(!i)return;let r=i.index.get(Xt);if(!r)return;let s=r[Bt];if(!s)return;if(s.startedAt&&!s.completedAt)this._logger(`WARNING: Incomplete flush detected (started ${s.startedAt}, collections: ${s.collections?.join(", ")}). Data may be inconsistent.`,"error")}async _cleanOrphanTempFiles(){if(typeof this._adapter.join!=="function")return;if(typeof this._adapter.list!=="function")return;try{let t=await import("fs"),i=await import("path"),r=this._adapter.dir;if(!r)return;let s=(await t.default.promises.readdir(r)).filter((n)=>n.includes(".tmp."));for(let n of s){let a=i.default.join(r,n);try{await t.default.promises.unlink(a),this._log(`Cleaned orphan temp file: ${n}`)}catch{}}}catch{}}_getOrCreateMeta(t){if(!t._meta)t._meta={collectionName:"_meta",data:[],index:new Map,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:null,rawSchema:null,fieldIndex:null,changelog:!1,softDelete:!1,versioning:!1,strict:!1,onSchemaError:"throw",defaultTtl:null,defaultEmbed:null,maxDocs:null};let i=t._meta,r=i.index.get(Xt);if(!r)r={_id:Xt},i.data.push(r),i.index.set(Xt,r);return r}_log(t){if(this._debug)this._logger(t,"info")}}var sc=0;class Kn{constructor(){this._txLock=Promise.resolve(),this._ctx=null,this._abortedIds=new Set}get active(){return this._ctx!==null&&!this._ctx.aborted}get context(){return this._ctx}async run(t,i,{timeout:r=0}={}){let s=async()=>{await i._ensureConnected();let a=new Set(Object.keys(i.collections)),o={id:++sc,startedAt:Date.now(),aborted:!1,preExisting:a,touchedCollections:new Set,snapshots:new Map,deferredEffects:[],timeout:r};this._ctx=o;let c=null,l=r>0?new Promise((f,h)=>{c=setTimeout(()=>{o.aborted=!0,h(new $e("ERR_SKALEX_TX_TIMEOUT",`Transaction ${o.id} timed out after ${r}ms`))},r)}):null,d=this,u=new Proxy(i,{get(f,h){if(h==="_txId")return o.id;if(o!==d._ctx)throw new $e("ERR_SKALEX_TX_STALE_PROXY",`Transaction ${o.id} has ended. This proxy is no longer usable.`);if(h==="collections")throw new $e("ERR_SKALEX_TX_DIRECT_ACCESS","Direct access to db.collections inside transaction() is not covered by rollback. Use the collection API (db.useCollection) instead.");if(h==="useCollection")return(p)=>{let g=f.useCollection(p);return g._activeTxId=o.id,g};let _=Reflect.get(f,h);return typeof _==="function"?_.bind(f):_}});try{let f=t(u),h=l?await Promise.race([f,l]):await f;if(o.aborted)throw new $e("ERR_SKALEX_TX_ABORTED",`Transaction ${o.id} was aborted`);let _=[...o.touchedCollections];if(_.length>0)await i._persistence.saveAtomic(i.collections,_);for(let p of o.deferredEffects)await p();return h}catch(f){for(let[h,_]of o.snapshots)if(o.preExisting.has(h)){if(i._applySnapshot(h,_),i.collections[h])i.collections[h]._dirty=_._dirty}for(let h in i.collections)if(!o.preExisting.has(h))delete i.collections[h],delete i._collectionInstances[h];throw f}finally{if(c)clearTimeout(c);if(o.aborted)this._abortedIds.add(o.id);this._ctx=null;for(let f in i._collectionInstances){let h=i._collectionInstances[f];if(h._createdInTxId===o.id)h._createdInTxId=null;if(h._activeTxId===o.id)h._activeTxId=null}}},n=this._txLock.then(s);return this._txLock=n.catch(()=>{}),n}snapshotIfNeeded(t,i,r){let s=this._ctx;if(!s)return;if(this._assertCtxNotAborted(s),!s.snapshots.has(t)){let n=r(i);n._dirty=i._dirty??!1,s.snapshots.set(t,n)}s.touchedCollections.add(t)}assertNotAborted(){let t=this._ctx;if(t)this._assertCtxNotAborted(t)}_assertCtxNotAborted(t){if(t.aborted)throw new $e("ERR_SKALEX_TX_ABORTED",`Transaction ${t.id} was aborted. No further mutations allowed.`)}defer(t){if(this._ctx)return this._ctx.deferredEffects.push(t),!0;return!1}}class zn{constructor(t){this._CollectionClass=t,this.stores={},this._instances={}}get(t,i){if(this._instances[t])return this._instances[t];if(!this.stores[t])this.createStore(t);let r=new this._CollectionClass(this.stores[t],i);return this._instances[t]=r,r}create(t,i={},r){this.createStore(t,i);let s=new this._CollectionClass(this.stores[t],r);return this._instances[t]=s,s}createStore(t,{schema:i,indexes:r=[],changelog:s=!1,softDelete:n=!1,versioning:a=!1,strict:o=!1,onSchemaError:c="throw",defaultTtl:l=null,defaultEmbed:d=null,maxDocs:u=null}={}){let f=null,h=null;if(i){f=Dn(i);let _=f.uniqueFields;if(r.length||_.length)h=new Zt(r,_)}else if(r.length)h=new Zt(r,[]);this.stores[t]={collectionName:t,data:[],index:new Map,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:f,rawSchema:i||null,fieldIndex:h,changelog:s,softDelete:n,versioning:a,strict:o,onSchemaError:c,defaultTtl:l,defaultEmbed:d,maxDocs:u}}rename(t,i){if(!this.stores[t])throw new He("ERR_SKALEX_PERSISTENCE_COLLECTION_NOT_FOUND",`Collection "${t}" not found`,{collection:t});if(this.stores[i])throw new He("ERR_SKALEX_PERSISTENCE_COLLECTION_EXISTS",`Collection "${i}" already exists`,{collection:i});let r=this.stores[t];if(r.collectionName=i,this.stores[i]=r,delete this.stores[t],this._instances[t]){let s=this._instances[t];s.name=i,this._instances[i]=s,delete this._instances[t]}}buildIndex(t,i){let r=new Map;for(let s of t)r.set(s[i],s);return r}inspect(t){if(t){let r=this.stores[t];if(!r)return null;return{name:t,count:r.data.length,schema:r.schema?Object.fromEntries(r.schema.fields):null,indexes:r.fieldIndex?[...r.fieldIndex.indexedFields]:[],softDelete:r.softDelete??!1,versioning:r.versioning??!1,strict:r.strict??!1,onSchemaError:r.onSchemaError??"throw",maxDocs:r.maxDocs??null}}let i={};for(let r in this.stores)i[r]=this.inspect(r);return i}dump(){let t={};for(let i in this.stores)if(!i.startsWith("_"))t[i]=structuredClone(this.stores[i].data);return t}schema(t){let i=this.stores[t];if(!i)return null;if(i.schema)return Object.fromEntries([...i.schema.fields.entries()].map(([r,s])=>[r,s.type]));if(i.data.length>0)return Wl(i.data[0]);return null}stats(t){let i=(r)=>{let s=this.stores[r];if(!s)return null;let n=s.data.length,a=0;for(let o of s.data)try{a+=JSON.stringify(o).length}catch(c){}return{collection:r,count:n,estimatedSize:a,avgDocSize:n>0?Math.round(a/n):0}};if(t)return i(t);return Object.keys(this.stores).map(i)}clear(){this.stores={},this._instances={}}}class nr{async embed(t){throw Error("EmbeddingAdapter.embed() not implemented")}}var Ee=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class Bn extends nr{constructor({apiKey:t=Ee("OPENAI_API_KEY"),model:i=Ee("OPENAI_EMBED_MODEL")??"text-embedding-3-small",baseUrl:r=Ee("OPENAI_EMBED_BASE_URL")??"https://api.openai.com/v1/embeddings",dimensions:s=Ee("OPENAI_EMBED_DIMENSIONS")!=null?Number(Ee("OPENAI_EMBED_DIMENSIONS")):void 0,organization:n=Ee("OPENAI_ORGANIZATION")??void 0,timeout:a=Ee("OPENAI_EMBED_TIMEOUT")!=null?Number(Ee("OPENAI_EMBED_TIMEOUT")):void 0,retries:o=Number(Ee("OPENAI_EMBED_RETRIES")??0),retryDelay:c=Number(Ee("OPENAI_EMBED_RETRY_DELAY")??1000),headers:l={},fetch:d=globalThis.fetch}={}){super();if(!t)throw Error("OpenAIEmbeddingAdapter requires an apiKey");this.apiKey=t,this.model=i,this.baseUrl=r,this.dimensions=s,this.organization=n,this.timeout=a,this.retries=o,this.retryDelay=c,this.headers=l,this._fetch=d}async embed(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,...this.organization&&{"OpenAI-Organization":this.organization},...this.headers},body:JSON.stringify({input:t,model:this.model,...this.dimensions!==void 0&&{dimensions:this.dimensions}}),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`OpenAI embedding API error ${a.status}: ${o}`)}return(await a.json()).data[0].embedding}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}var vt=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class Xn extends nr{constructor({model:t=vt("OLLAMA_EMBED_MODEL")??"nomic-embed-text",host:i=vt("OLLAMA_HOST")??"http://localhost:11434",timeout:r=vt("OLLAMA_EMBED_TIMEOUT")!=null?Number(vt("OLLAMA_EMBED_TIMEOUT")):void 0,retries:s=Number(vt("OLLAMA_EMBED_RETRIES")??0),retryDelay:n=Number(vt("OLLAMA_EMBED_RETRY_DELAY")??1000),headers:a={},fetch:o=globalThis.fetch}={}){super();this.model=t,this.host=i,this.timeout=r,this.retries=s,this.retryDelay=n,this.headers=a,this._fetch=o}async embed(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(`${this.host}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json",...this.headers},body:JSON.stringify({model:this.model,prompt:t}),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`Ollama embedding API error ${a.status}: ${o}`)}return(await a.json()).embedding}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}class ai{async generate(t,i){throw Error("LLMAdapter.generate() not implemented")}async summarize(t){throw Error("LLMAdapter.summarize() not implemented")}}var ar=`You are a database query assistant. Convert the user's natural language request into a JSON filter object for a document database.
|
|
57
57
|
|
|
58
58
|
Rules:
|
|
59
59
|
- Return ONLY a valid JSON object, nothing else
|
|
@@ -62,24 +62,24 @@ Rules:
|
|
|
62
62
|
- For numeric comparisons use operators: {"age": {"$gt": 18}}
|
|
63
63
|
- For text search use $regex: {"name": {"$regex": "pattern"}}
|
|
64
64
|
- Return {} to match all documents
|
|
65
|
-
- No explanations, no markdown, no code fences`,or="Summarise the following memory entries into one concise paragraph. Preserve all important facts.",B=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class
|
|
66
|
-
Schema: ${JSON.stringify(t)}`},{role:"user",content:i}],response_format:{type:"json_object"},temperature:0,...this.maxTokens!==void 0&&{max_tokens:this.maxTokens},...this.seed!==void 0&&{seed:this.seed}});return JSON.parse(r.choices[0].message.content)}async summarize(t){return(await this._post({model:this.model,messages:[{role:"system",content:this.summarizePrompt},{role:"user",content:t}],temperature:this.temperature,...this.maxTokens!==void 0&&{max_tokens:this.maxTokens},...this.topP!==void 0&&{top_p:this.topP},...this.seed!==void 0&&{seed:this.seed}})).choices[0].message.content.trim()}async _post(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,...this.organization&&{"OpenAI-Organization":this.organization},...this.headers},body:JSON.stringify(t),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`OpenAI API error ${a.status}: ${o}`)}return a.json()}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}var le=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class
|
|
67
|
-
Schema: ${JSON.stringify(t)}`,messages:[{role:"user",content:i}]})).content[0].text.trim().replace(/^```(?:json)?\n?/,"").replace(/\n?```$/,"");return JSON.parse(r)}async summarize(t){return(await this._post({model:this.model,max_tokens:this.maxTokens,temperature:this.temperature,...this.topP!==void 0&&{top_p:this.topP},...this.topK!==void 0&&{top_k:this.topK},system:this.summarizePrompt,messages:[{role:"user",content:t}]})).content[0].text.trim()}async _post(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.apiKey,"anthropic-version":this.apiVersion,...this.headers},body:JSON.stringify(t),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`Anthropic API error ${a.status}: ${o}`)}return a.json()}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}var
|
|
65
|
+
- No explanations, no markdown, no code fences`,or="Summarise the following memory entries into one concise paragraph. Preserve all important facts.",B=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class Vn extends ai{constructor({apiKey:t=B("OPENAI_API_KEY"),model:i=B("OPENAI_MODEL")??"gpt-4o-mini",baseUrl:r=B("OPENAI_BASE_URL")??"https://api.openai.com/v1/chat/completions",maxTokens:s=B("OPENAI_MAX_TOKENS")!=null?Number(B("OPENAI_MAX_TOKENS")):void 0,temperature:n=Number(B("OPENAI_TEMPERATURE")??0.3),topP:a=B("OPENAI_TOP_P")!=null?Number(B("OPENAI_TOP_P")):void 0,organization:o=B("OPENAI_ORGANIZATION")??void 0,timeout:c=B("OPENAI_TIMEOUT")!=null?Number(B("OPENAI_TIMEOUT")):void 0,retries:l=Number(B("OPENAI_RETRIES")??0),retryDelay:d=Number(B("OPENAI_RETRY_DELAY")??1000),headers:u={},fetch:f=globalThis.fetch,seed:h=B("OPENAI_SEED")!=null?Number(B("OPENAI_SEED")):void 0,generatePrompt:_=ar,summarizePrompt:p=or}={}){super();if(!t)throw Error("OpenAILLMAdapter requires an apiKey");this.apiKey=t,this.model=i,this.baseUrl=r,this.maxTokens=s,this.temperature=n,this.topP=a,this.organization=o,this.timeout=c,this.retries=l,this.retryDelay=d,this.headers=u,this._fetch=f,this.seed=h,this.generatePrompt=_,this.summarizePrompt=p}async generate(t,i){let r=await this._post({model:this.model,messages:[{role:"system",content:`${this.generatePrompt}
|
|
66
|
+
Schema: ${JSON.stringify(t)}`},{role:"user",content:i}],response_format:{type:"json_object"},temperature:0,...this.maxTokens!==void 0&&{max_tokens:this.maxTokens},...this.seed!==void 0&&{seed:this.seed}});return JSON.parse(r.choices[0].message.content)}async summarize(t){return(await this._post({model:this.model,messages:[{role:"system",content:this.summarizePrompt},{role:"user",content:t}],temperature:this.temperature,...this.maxTokens!==void 0&&{max_tokens:this.maxTokens},...this.topP!==void 0&&{top_p:this.topP},...this.seed!==void 0&&{seed:this.seed}})).choices[0].message.content.trim()}async _post(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,...this.organization&&{"OpenAI-Organization":this.organization},...this.headers},body:JSON.stringify(t),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`OpenAI API error ${a.status}: ${o}`)}return a.json()}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}var le=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class Gn extends ai{constructor({apiKey:t=le("ANTHROPIC_API_KEY"),model:i=le("ANTHROPIC_MODEL")??"claude-haiku-4-5",baseUrl:r=le("ANTHROPIC_BASE_URL")??"https://api.anthropic.com/v1/messages",apiVersion:s="2023-06-01",maxTokens:n=Number(le("ANTHROPIC_MAX_TOKENS")??1024),temperature:a=Number(le("ANTHROPIC_TEMPERATURE")??0.3),topP:o=le("ANTHROPIC_TOP_P")!=null?Number(le("ANTHROPIC_TOP_P")):void 0,topK:c=le("ANTHROPIC_TOP_K")!=null?Number(le("ANTHROPIC_TOP_K")):void 0,timeout:l=le("ANTHROPIC_TIMEOUT")!=null?Number(le("ANTHROPIC_TIMEOUT")):void 0,retries:d=Number(le("ANTHROPIC_RETRIES")??0),retryDelay:u=Number(le("ANTHROPIC_RETRY_DELAY")??1000),headers:f={},fetch:h=globalThis.fetch,generatePrompt:_=ar,summarizePrompt:p=or}={}){super();if(!t)throw Error("AnthropicLLMAdapter requires an apiKey");this.apiKey=t,this.model=i,this.baseUrl=r,this.apiVersion=s,this.maxTokens=n,this.temperature=a,this.topP=o,this.topK=c,this.timeout=l,this.retries=d,this.retryDelay=u,this.headers=f,this._fetch=h,this.generatePrompt=_,this.summarizePrompt=p}async generate(t,i){let r=(await this._post({model:this.model,max_tokens:this.maxTokens,temperature:0,system:`${this.generatePrompt}
|
|
67
|
+
Schema: ${JSON.stringify(t)}`,messages:[{role:"user",content:i}]})).content[0].text.trim().replace(/^```(?:json)?\n?/,"").replace(/\n?```$/,"");return JSON.parse(r)}async summarize(t){return(await this._post({model:this.model,max_tokens:this.maxTokens,temperature:this.temperature,...this.topP!==void 0&&{top_p:this.topP},...this.topK!==void 0&&{top_k:this.topK},system:this.summarizePrompt,messages:[{role:"user",content:t}]})).content[0].text.trim()}async _post(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.apiKey,"anthropic-version":this.apiVersion,...this.headers},body:JSON.stringify(t),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`Anthropic API error ${a.status}: ${o}`)}return a.json()}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}var ge=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class Hn extends ai{constructor({model:t=ge("OLLAMA_MODEL")??"llama3.2",host:i=ge("OLLAMA_HOST")??"http://localhost:11434",temperature:r=Number(ge("OLLAMA_TEMPERATURE")??0.3),topP:s=ge("OLLAMA_TOP_P")!=null?Number(ge("OLLAMA_TOP_P")):void 0,topK:n=ge("OLLAMA_TOP_K")!=null?Number(ge("OLLAMA_TOP_K")):void 0,timeout:a=ge("OLLAMA_TIMEOUT")!=null?Number(ge("OLLAMA_TIMEOUT")):void 0,retries:o=Number(ge("OLLAMA_RETRIES")??0),retryDelay:c=Number(ge("OLLAMA_RETRY_DELAY")??1000),headers:l={},fetch:d=globalThis.fetch,generatePrompt:u=ar,summarizePrompt:f=or}={}){super();this.model=t,this.host=i,this.temperature=r,this.topP=s,this.topK=n,this.timeout=a,this.retries=o,this.retryDelay=c,this.headers=l,this._fetch=d,this.generatePrompt=u,this.summarizePrompt=f}async generate(t,i){let r=`${this.generatePrompt}
|
|
68
68
|
Schema: ${JSON.stringify(t)}
|
|
69
69
|
Query: ${i}`,s=await this._post({model:this.model,prompt:r,format:"json",options:{temperature:0},stream:!1});return JSON.parse(s.response)}async summarize(t){return(await this._post({model:this.model,prompt:`${this.summarizePrompt}
|
|
70
70
|
|
|
71
|
-
${t}`,options:{temperature:this.temperature,...this.topP!==void 0&&{top_p:this.topP},...this.topK!==void 0&&{top_k:this.topK}},stream:!1})).response.trim()}async _post(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(`${this.host}/api/generate`,{method:"POST",headers:{"Content-Type":"application/json",...this.headers},body:JSON.stringify(t),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`Ollama API error ${a.status}: ${o}`)}return a.json()}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}function
|
|
71
|
+
${t}`,options:{temperature:this.temperature,...this.topP!==void 0&&{top_p:this.topP},...this.topK!==void 0&&{top_k:this.topK}},stream:!1})).response.trim()}async _post(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(`${this.host}/api/generate`,{method:"POST",headers:{"Content-Type":"application/json",...this.headers},body:JSON.stringify(t),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`Ollama API error ${a.status}: ${o}`)}return a.json()}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}function nc({provider:t,apiKey:i,embedModel:r,model:s,host:n,embedBaseUrl:a,dimensions:o,organization:c,embedTimeout:l,embedRetries:d,embedRetryDelay:u}){let f=r||s;switch(t){case"openai":return new Bn({apiKey:i,model:f,baseUrl:a,...o!==void 0&&{dimensions:o},...c!==void 0&&{organization:c},...l!==void 0&&{timeout:l},...d!==void 0&&{retries:d},...u!==void 0&&{retryDelay:u}});case"ollama":return new Xn({model:f,host:n,...l!==void 0&&{timeout:l},...d!==void 0&&{retries:d},...u!==void 0&&{retryDelay:u}});default:throw new Oe("ERR_SKALEX_ADAPTER_UNKNOWN_PROVIDER",`Unknown AI provider: "${t}". Supported: "openai", "ollama".`,{provider:t})}}function ac({provider:t,apiKey:i,model:r,host:s,baseUrl:n,apiVersion:a,temperature:o,maxTokens:c,topP:l,topK:d,organization:u,timeout:f,retries:h,retryDelay:_,seed:p,generatePrompt:g,summarizePrompt:m}){if(!r)return null;switch(t){case"openai":return new Vn({apiKey:i,model:r,baseUrl:n,...c!==void 0&&{maxTokens:c},...o!==void 0&&{temperature:o},...l!==void 0&&{topP:l},...u!==void 0&&{organization:u},...f!==void 0&&{timeout:f},...h!==void 0&&{retries:h},..._!==void 0&&{retryDelay:_},...p!==void 0&&{seed:p},...g!==void 0&&{generatePrompt:g},...m!==void 0&&{summarizePrompt:m}});case"anthropic":return new Gn({apiKey:i,model:r,baseUrl:n,apiVersion:a,...c!==void 0&&{maxTokens:c},...o!==void 0&&{temperature:o},...l!==void 0&&{topP:l},...d!==void 0&&{topK:d},...f!==void 0&&{timeout:f},...h!==void 0&&{retries:h},..._!==void 0&&{retryDelay:_},...g!==void 0&&{generatePrompt:g},...m!==void 0&&{summarizePrompt:m}});case"ollama":return new Hn({model:r,host:s,...o!==void 0&&{temperature:o},...l!==void 0&&{topP:l},...d!==void 0&&{topK:d},...f!==void 0&&{timeout:f},...h!==void 0&&{retries:h},..._!==void 0&&{retryDelay:_},...g!==void 0&&{generatePrompt:g},...m!==void 0&&{summarizePrompt:m}});default:return null}}var Ri="AES-GCM",Dt=12,qe=32,oc=new TextEncoder,lc=new TextDecoder;class Wn extends sr{constructor(t,i){super();if(this._adapter=t,this._rawKey=typeof i==="string"?cc(i):Uint8Array.from(i),this._rawKey.length!==qe)throw new Oe("ERR_SKALEX_ADAPTER_INVALID_KEY",`EncryptedAdapter: key must be ${qe} bytes (${qe*2} hex chars), got ${this._rawKey.length}`);this._cryptoKey=null}async read(t){let i=await this._adapter.read(t);if(!i)return null;return this._decrypt(i)}async write(t,i){return this._adapter.write(t,await this._encrypt(i))}async delete(t){return this._adapter.delete(t)}async list(){return this._adapter.list()}async writeAll(t){let i=[];for(let{name:r,data:s}of t)i.push({name:r,data:await this._encrypt(s)});return this._adapter.writeAll(i)}join(...t){return this._adapter.join?.(...t)}ensureDir(t){return this._adapter.ensureDir?.(t)}async writeRaw(t,i){return this._adapter.writeRaw?.(t,await this._encrypt(i))}async readRaw(t){let i=await this._adapter.readRaw?.(t);if(!i)return null;return this._decrypt(i)}async _getKey(){if(!this._cryptoKey)this._cryptoKey=await globalThis.crypto.subtle.importKey("raw",this._rawKey,{name:Ri},!1,["encrypt","decrypt"]);return this._cryptoKey}async _encrypt(t){let i=await this._getKey(),r=globalThis.crypto.getRandomValues(new Uint8Array(Dt)),s=oc.encode(t),n=await globalThis.crypto.subtle.encrypt({name:Ri,iv:r,tagLength:128},i,s),a=new Uint8Array(Dt+n.byteLength);return a.set(r,0),a.set(new Uint8Array(n),Dt),dc(a)}async _decrypt(t){let i=await this._getKey(),r=uc(t),s=r.slice(0,Dt),n=r.slice(Dt),a=await globalThis.crypto.subtle.decrypt({name:Ri,iv:s,tagLength:128},i,n);return lc.decode(a)}}function cc(t){if(t.length!==qe*2)throw new Oe("ERR_SKALEX_ADAPTER_INVALID_KEY",`EncryptedAdapter: hex key must be ${qe*2} characters (${qe} bytes)`);if(!/^[0-9a-fA-F]+$/.test(t))throw new Oe("ERR_SKALEX_ADAPTER_INVALID_KEY","EncryptedAdapter: hex key contains invalid characters");let i=new Uint8Array(qe);for(let r=0;r<qe;r++)i[r]=parseInt(t.slice(r*2,r*2+2),16);return i}function dc(t){let i="";for(let r=0;r<t.length;r++)i+=String.fromCharCode(t[r]);return globalThis.btoa(i)}function uc(t){let i=globalThis.atob(t),r=new Uint8Array(i.length);for(let s=0;s<i.length;s++)r[s]=i.charCodeAt(s);return r}var hc=4;class Jn{constructor(t,i){this.sessionId=t,this._db=i,this._col=i.useCollection(`_memory_${t}`)}async remember(t){let i=await this._col.insertOne({text:t,sessionId:this.sessionId},{embed:"text"}),r=this._db._memoryConfig?.maxEntries;if(r&&this._col._data.length>r)await this.compress({threshold:0});return i}async recall(t,{limit:i=10,minScore:r=0}={}){return this._col.search(t,{limit:i,minScore:r})}async history({since:t,limit:i}={}){let r=t?{createdAt:{$gte:new Date(t)}}:{},s={sort:{createdAt:1}};if(i)s.limit=i;let{docs:n}=await this._col.find(r,s);return n}async forget(t){return this._col.deleteOne({_id:t})}tokenCount(){let t=this._col._data;return{tokens:t.reduce((i,r)=>i+this._docTokens(r),0),count:t.length}}context({tokens:t=this._db._memoryConfig?.contextTokens??4000}={}){let i=this._sortedData("desc"),r=[],s=0;for(let n of i){let a=this._docTokens(n);if(s+a>t)break;r.push(n.text),s+=a}return r.reverse().join(`
|
|
72
72
|
`)}async compress({threshold:t=this._db._memoryConfig?.compressionThreshold??8000,keepRecent:i=this._db._memoryConfig?.keepRecent??10}={}){let{tokens:r}=this.tokenCount();if(r<=t)return;if(!this._db._aiAdapter)throw Error('memory.compress() requires a language model adapter. Configure { ai: { model: "..." } }.');let s=this._sortedData("asc"),n=Math.max(0,s.length-i),a=s.slice(0,n);if(a.length===0)return;let o=a.map((l)=>l.text).join(`
|
|
73
|
-
`),c=await this._db._aiAdapter.summarize(o);await this._col.deleteMany({_id:{$in:a.map((l)=>l._id)}}),await this._col.insertOne({text:c,sessionId:this.sessionId,compressed:!0})}_docTokens(t){return Math.ceil((t.text||"").length/uc)}_sortedData(t){return[...this._col._data].sort(t==="asc"?(i,r)=>new Date(i.createdAt)-new Date(r.createdAt):(i,r)=>new Date(r.createdAt)-new Date(i.createdAt))}}class Jn{constructor(t){this._db=t,this._restoring=!1}get _col(){return this._db.useCollection("_changelog")}async log(t,i,r,s=null,n=null){if(this._restoring)return;let a={op:t,collection:i,docId:r._id,doc:{...r},timestamp:new Date};if(s)a.prev={...s};if(n)a.session=n;await this._col.insertOne(a)}async query(t,{since:i,limit:r,session:s}={}){let n={collection:t};if(i)n.timestamp={$gte:new Date(i)};if(s)n.session=s;let a={sort:{timestamp:1}};if(r)a.limit=r;let{docs:o}=await this._col.find(n,a);return o}async restore(t,i,{_id:r}={}){let s=new Date(i),n=this._db.useCollection(t),a=(await this.query(t,{})).filter((c)=>new Date(c.timestamp)<=s);if(r){let c=a.filter((d)=>d.docId===r);if(c.length===0)return;let l=c[c.length-1];this._restoring=!0;try{if(l.op==="delete"){if(await n.findOne({_id:r}))await n.deleteOne({_id:r});return}if(await n.findOne({_id:r})){let{_id:d,createdAt:u,updatedAt:f,...h}=l.doc;await n.updateOne({_id:r},h)}else await n.insertOne({...l.doc})}finally{this._restoring=!1}await this._db.saveData(t);return}let o=new Map;for(let c of a)if(c.op==="insert"||c.op==="update")o.set(c.docId,{doc:c.doc,deleted:!1});else if(c.op==="delete")o.set(c.docId,{doc:null,deleted:!0});this._restoring=!0;try{await n.deleteMany({});for(let[,{doc:c,deleted:l}]of o)if(!l&&c)await n.insertOne({...c})}finally{this._restoring=!1}await this._db.saveData(t)}}function hc(t){let i=5381;for(let r=0;r<t.length;r++)i=(i<<5)+i+t.charCodeAt(r)|0;return(i>>>0).toString(16).padStart(8,"0")}class Yn{constructor({maxSize:t=500,ttl:i=0}={}){this._cache=new Map,this._maxSize=t,this._ttl=i}_key(t,i,r){return hc(JSON.stringify({collectionName:t,schema:i,query:r}))}get(t,i,r){let s=this._key(t,i,r),n=this._cache.get(s);if(!n)return;if(this._ttl>0&&Date.now()-n.ts>this._ttl){this._cache.delete(s);return}return n.filter}set(t,i,r,s){let n=this._key(t,i,r);if(this._cache.size>=this._maxSize&&!this._cache.has(n))this._cache.delete(this._cache.keys().next().value);this._cache.set(n,{filter:s,ts:Date.now()})}toJSON(){return Object.fromEntries([...this._cache.entries()].map(([t,i])=>[t,i]))}fromJSON(t){if(!t||typeof t!=="object")return;for(let[i,r]of Object.entries(t))this._cache.set(i,r)}get size(){return this._cache.size}}function fc(t,{regexMaxLength:i=500}={}){if(typeof t!=="object"||t===null)return t;let r={};for(let s of Object.keys(t)){let n=t[s];if(n&&typeof n==="object"&&!Array.isArray(n)){let a={};for(let o of Object.keys(n))if(o==="$regex"&&typeof n.$regex==="string"){if(n.$regex.length>i)throw Error(`$regex pattern too long (max ${i} characters)`);if(/\([^)]*[+*][^)]*\)[+*{]/.test(n.$regex))throw Error("$regex pattern rejected: nested quantifiers risk ReDoS");try{a.$regex=new RegExp(n.$regex)}catch{throw Error(`invalid $regex pattern: "${n.$regex}"`)}}else if(["$gt","$gte","$lt","$lte"].includes(o)&&_c(n[o]))a[o]=new Date(n[o]);else a[o]=n[o];r[s]=a}else r[s]=n}return r}function _c(t){if(typeof t!=="string")return!1;return/\d{4}-\d{2}-\d{2}/.test(t)&&!isNaN(Date.parse(t))}function pc(t,i){let r=[];if(!i||typeof t!=="object"||t===null)return r;for(let s of Object.keys(t)){if(s.startsWith("$"))continue;if(!(s.split(".")[0]in i))r.push(`Unknown field referenced in generated filter: "${s}"`)}return r}class Qn{constructor(){this._listeners=new Map}on(t,i){if(!this._listeners.has(t))this._listeners.set(t,new Set);return this._listeners.get(t).add(i),()=>this._listeners.get(t)?.delete(i)}off(t,i){this._listeners.get(t)?.delete(i)}emit(t,i){for(let r of[t,"*"]){let s=this._listeners.get(r);if(!s)continue;for(let n of s)try{n(i)}catch(a){}}}removeAll(t){if(t)this._listeners.delete(t);else this._listeners.clear()}listenerCount(t){return this._listeners.get(t)?.size??0}}class Zn{constructor({threshold:t=100,maxEntries:i=500}={}){this._threshold=t,this._maxEntries=i,this._entries=[]}record({collection:t,op:i,filter:r,query:s,duration:n,resultCount:a}){if(n<this._threshold)return;let o={collection:t,op:i,duration:n,resultCount:a,timestamp:new Date};if(r!==void 0)o.filter=r;if(s!==void 0)o.query=s;if(this._entries.push(o),this._entries.length>this._maxEntries)this._entries.shift()}entries({limit:t,minDuration:i,collection:r}={}){let s=this._entries;if(r)s=s.filter((n)=>n.collection===r);if(i)s=s.filter((n)=>n.duration>=i);if(t)s=s.slice(-t);return s}get size(){return this._entries.length}clear(){this._entries=[]}}class ea{constructor(){this._sessions=new Map}_ensure(t){if(!this._sessions.has(t))this._sessions.set(t,{reads:0,writes:0,lastActive:null});return this._sessions.get(t)}recordRead(t){if(!t)return;let i=this._ensure(t);i.reads++,i.lastActive=new Date}recordWrite(t){if(!t)return;let i=this._ensure(t);i.writes++,i.lastActive=new Date}get(t){let i=this._sessions.get(t);if(!i)return null;return{sessionId:t,...i}}all(){return[...this._sessions.entries()].map(([t,i])=>({sessionId:t,...i}))}clear(t){if(t)this._sessions.delete(t);else this._sessions.clear()}}class ta{constructor(){this._plugins=[]}register(t){if(typeof t!=="object"||t===null)throw TypeError("Plugin must be a non-null object.");this._plugins.push(t)}async run(t,i){for(let r of this._plugins)if(typeof r[t]==="function")await r[t](i)}get size(){return this._plugins.length}}function ct(t){if(typeof t!=="string"||!t.trim())throw Error("collection name must be a non-empty string");if(/[/\\]/.test(t)||t.includes("..")||t.includes("\x00"))throw Error(`invalid collection name: "${t}"`);if(t.trim().startsWith("_"))throw Error(`access to system collection "${t}" is not permitted`);return t.trim()}var hs=[{name:"skalex_collections",description:"List all collection names in the database.",inputSchema:{type:"object",properties:{}},scope:"read"},{name:"skalex_schema",description:"Return the schema for a collection as a { field: type } map. Returns null if the collection is empty.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."}},required:["collection"]},scope:"read"},{name:"skalex_find",description:"Find documents in a collection that match a filter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},filter:{type:"object",description:"Query filter (MongoDB-style operators supported)."},limit:{type:"number",description:"Maximum number of results. Default: 20."},sort:{type:"object",description:"Sort descriptor: { field: 1 } for ascending, { field: -1 } for descending."}},required:["collection"]},scope:"read"},{name:"skalex_insert",description:"Insert a single document into a collection.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},doc:{type:"object",description:"Document to insert."}},required:["collection","doc"]},scope:"write"},{name:"skalex_update",description:"Update the first document matching a filter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},filter:{type:"object",description:"Query filter to identify the document."},update:{type:"object",description:"Fields to update (direct assignment, $inc, $push supported)."},many:{type:"boolean",description:"If true, update all matching documents. Default: false."}},required:["collection","filter","update"]},scope:"write"},{name:"skalex_delete",description:"Delete the first document matching a filter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},filter:{type:"object",description:"Query filter to identify the document."},many:{type:"boolean",description:"If true, delete all matching documents. Default: false."}},required:["collection","filter"]},scope:"write"},{name:"skalex_search",description:"Semantic similarity search. Requires an embedding adapter to be configured.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},query:{type:"string",description:"Natural-language query string to embed and compare."},limit:{type:"number",description:"Maximum number of results. Default: 10."},minScore:{type:"number",description:"Minimum cosine similarity score [0, 1]. Default: 0."},filter:{type:"object",description:"Optional structured pre-filter (hybrid search)."}},required:["collection","query"]},scope:"read"},{name:"skalex_ask",description:"Translate a natural-language question into a filter and query a collection. Requires a language model adapter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},question:{type:"string",description:"Natural-language question about the data."},limit:{type:"number",description:"Maximum number of results. Default: 20."}},required:["collection","question"]},scope:"read"}];async function gc(t,i,r){switch(t){case"skalex_collections":return Object.keys(r.collections).filter((s)=>!s.startsWith("_"));case"skalex_schema":return r.schema(ct(i.collection))??null;case"skalex_find":{let s=r.useCollection(ct(i.collection)),n={};if(i.limit)n.limit=i.limit;if(i.sort)n.sort=i.sort;return s.find(i.filter||{},n)}case"skalex_insert":return r.useCollection(ct(i.collection)).insertOne(i.doc||{});case"skalex_update":{let s=r.useCollection(ct(i.collection));if(i.many)return s.updateMany(i.filter||{},i.update||{});return s.updateOne(i.filter||{},i.update||{})}case"skalex_delete":{let s=r.useCollection(ct(i.collection));if(i.many)return s.deleteMany(i.filter||{});return s.deleteOne(i.filter||{})}case"skalex_search":return r.useCollection(ct(i.collection)).search(i.query,{limit:i.limit??10,minScore:i.minScore??0,filter:i.filter});case"skalex_ask":return r.ask(ct(i.collection),i.question,{limit:i.limit??20});default:throw Object.assign(Error(`Unknown tool: ${t}`),{code:"NOT_FOUND"})}}var lr="2.0",cr=-32700,mc=-32600,fs=-32601,yc=-32602,wc=-32603;function Et(t,i){return{jsonrpc:lr,id:t,result:i}}function Be(t,i,r,s){return{jsonrpc:lr,id:t,error:{code:i,message:r}}}function Ac(t){try{let i=JSON.parse(t);if(typeof i!=="object"||i===null||i.jsonrpc!==lr)return{parseError:Be(null,mc,"Invalid JSON-RPC request")};return{msg:i}}catch(i){return{parseError:Be(null,cr,"Parse error")}}}function vc(t){return{content:[{type:"text",text:t}]}}function _s(t){return{content:[{type:"text",text:t}],isError:!0}}class ia{constructor({port:t=3000,host:i="127.0.0.1",allowedOrigin:r=null,maxBodySize:s=1048576}={}){this._port=t,this._host=i,this._allowedOrigin=r,this._maxBodySize=s,this._clients=new Set,this._onMessage=null,this._server=null}onMessage(t){this._onMessage=t}send(t){let i=`data: ${JSON.stringify(t)}
|
|
73
|
+
`),c=await this._db._aiAdapter.summarize(o);await this._col.deleteMany({_id:{$in:a.map((l)=>l._id)}}),await this._col.insertOne({text:c,sessionId:this.sessionId,compressed:!0})}_docTokens(t){return Math.ceil((t.text||"").length/hc)}_sortedData(t){return[...this._col._data].sort(t==="asc"?(i,r)=>new Date(i.createdAt)-new Date(r.createdAt):(i,r)=>new Date(r.createdAt)-new Date(i.createdAt))}}class Yn{constructor(t){this._db=t,this._restoring=!1}get _col(){return this._db.useCollection("_changelog")}async log(t,i,r,s=null,n=null){if(this._restoring)return;let a={op:t,collection:i,docId:r._id,doc:{...r},timestamp:new Date};if(s)a.prev={...s};if(n)a.session=n;await this._col.insertOne(a)}async query(t,{since:i,limit:r,session:s}={}){let n={collection:t};if(i)n.timestamp={$gte:new Date(i)};if(s)n.session=s;let a={sort:{timestamp:1}};if(r)a.limit=r;let{docs:o}=await this._col.find(n,a);return o}async restore(t,i,{_id:r}={}){let s=new Date(i),n=this._db.useCollection(t),a=(await this.query(t,{})).filter((c)=>new Date(c.timestamp)<=s);if(r){let c=a.filter((d)=>d.docId===r);if(c.length===0)return;let l=c[c.length-1];this._restoring=!0;try{if(l.op==="delete"){if(await n.findOne({_id:r}))await n.deleteOne({_id:r});return}if(await n.findOne({_id:r})){let{_id:d,createdAt:u,updatedAt:f,...h}=l.doc;await n.updateOne({_id:r},h)}else await n.insertOne({...l.doc})}finally{this._restoring=!1}await this._db.saveData(t);return}let o=new Map;for(let c of a)if(c.op==="insert"||c.op==="update")o.set(c.docId,{doc:c.doc,deleted:!1});else if(c.op==="delete")o.set(c.docId,{doc:null,deleted:!0});this._restoring=!0;try{await n.deleteMany({});for(let[,{doc:c,deleted:l}]of o)if(!l&&c)await n.insertOne({...c})}finally{this._restoring=!1}await this._db.saveData(t)}}function fc(t){let i=5381;for(let r=0;r<t.length;r++)i=(i<<5)+i+t.charCodeAt(r)|0;return(i>>>0).toString(16).padStart(8,"0")}class Qn{constructor({maxSize:t=500,ttl:i=0}={}){this._cache=new Map,this._maxSize=t,this._ttl=i}_key(t,i,r){return fc(JSON.stringify({collectionName:t,schema:i,query:r}))}get(t,i,r){let s=this._key(t,i,r),n=this._cache.get(s);if(!n)return;if(this._ttl>0&&Date.now()-n.ts>this._ttl){this._cache.delete(s);return}return n.filter}set(t,i,r,s){let n=this._key(t,i,r);if(this._cache.size>=this._maxSize&&!this._cache.has(n))this._cache.delete(this._cache.keys().next().value);this._cache.set(n,{filter:s,ts:Date.now()})}toJSON(){return Object.fromEntries([...this._cache.entries()].map(([t,i])=>[t,i]))}fromJSON(t){if(!t||typeof t!=="object")return;for(let[i,r]of Object.entries(t))this._cache.set(i,r)}get size(){return this._cache.size}}function _c(t,{regexMaxLength:i=500}={}){if(typeof t!=="object"||t===null)return t;let r={};for(let s of Object.keys(t)){let n=t[s];if(n&&typeof n==="object"&&!Array.isArray(n)){let a={};for(let o of Object.keys(n))if(o==="$regex"&&typeof n.$regex==="string"){if(n.$regex.length>i)throw Error(`$regex pattern too long (max ${i} characters)`);if(/\([^)]*[+*][^)]*\)[+*{]/.test(n.$regex))throw Error("$regex pattern rejected: nested quantifiers risk ReDoS");try{a.$regex=new RegExp(n.$regex)}catch{throw Error(`invalid $regex pattern: "${n.$regex}"`)}}else if(["$gt","$gte","$lt","$lte"].includes(o)&&pc(n[o]))a[o]=new Date(n[o]);else a[o]=n[o];r[s]=a}else r[s]=n}return r}function pc(t){if(typeof t!=="string")return!1;return/\d{4}-\d{2}-\d{2}/.test(t)&&!isNaN(Date.parse(t))}function gc(t,i){let r=[];if(!i||typeof t!=="object"||t===null)return r;for(let s of Object.keys(t)){if(s.startsWith("$"))continue;if(!(s.split(".")[0]in i))r.push(`Unknown field referenced in generated filter: "${s}"`)}return r}class Zn{constructor(){this._listeners=new Map}on(t,i){if(!this._listeners.has(t))this._listeners.set(t,new Set);return this._listeners.get(t).add(i),()=>this._listeners.get(t)?.delete(i)}off(t,i){this._listeners.get(t)?.delete(i)}emit(t,i){for(let r of[t,"*"]){let s=this._listeners.get(r);if(!s)continue;for(let n of s)try{n(i)}catch(a){}}}removeAll(t){if(t)this._listeners.delete(t);else this._listeners.clear()}listenerCount(t){return this._listeners.get(t)?.size??0}}class ea{constructor({threshold:t=100,maxEntries:i=500}={}){this._threshold=t,this._maxEntries=i,this._entries=[]}record({collection:t,op:i,filter:r,query:s,duration:n,resultCount:a}){if(n<this._threshold)return;let o={collection:t,op:i,duration:n,resultCount:a,timestamp:new Date};if(r!==void 0)o.filter=r;if(s!==void 0)o.query=s;if(this._entries.push(o),this._entries.length>this._maxEntries)this._entries.shift()}entries({limit:t,minDuration:i,collection:r}={}){let s=this._entries;if(r)s=s.filter((n)=>n.collection===r);if(i)s=s.filter((n)=>n.duration>=i);if(t)s=s.slice(-t);return s}get size(){return this._entries.length}clear(){this._entries=[]}}class ta{constructor(){this._sessions=new Map}_ensure(t){if(!this._sessions.has(t))this._sessions.set(t,{reads:0,writes:0,lastActive:null});return this._sessions.get(t)}recordRead(t){if(!t)return;let i=this._ensure(t);i.reads++,i.lastActive=new Date}recordWrite(t){if(!t)return;let i=this._ensure(t);i.writes++,i.lastActive=new Date}get(t){let i=this._sessions.get(t);if(!i)return null;return{sessionId:t,...i}}all(){return[...this._sessions.entries()].map(([t,i])=>({sessionId:t,...i}))}clear(t){if(t)this._sessions.delete(t);else this._sessions.clear()}}class ia{constructor(){this._plugins=[]}register(t){if(typeof t!=="object"||t===null)throw TypeError("Plugin must be a non-null object.");this._plugins.push(t)}async run(t,i){for(let r of this._plugins)if(typeof r[t]==="function")await r[t](i)}get size(){return this._plugins.length}}function ct(t){if(typeof t!=="string"||!t.trim())throw Error("collection name must be a non-empty string");if(/[/\\]/.test(t)||t.includes("..")||t.includes("\x00"))throw Error(`invalid collection name: "${t}"`);if(t.trim().startsWith("_"))throw Error(`access to system collection "${t}" is not permitted`);return t.trim()}var fs=[{name:"skalex_collections",description:"List all collection names in the database.",inputSchema:{type:"object",properties:{}},scope:"read"},{name:"skalex_schema",description:"Return the schema for a collection as a { field: type } map. Returns null if the collection is empty.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."}},required:["collection"]},scope:"read"},{name:"skalex_find",description:"Find documents in a collection that match a filter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},filter:{type:"object",description:"Query filter (MongoDB-style operators supported)."},limit:{type:"number",description:"Maximum number of results. Default: 20."},sort:{type:"object",description:"Sort descriptor: { field: 1 } for ascending, { field: -1 } for descending."}},required:["collection"]},scope:"read"},{name:"skalex_insert",description:"Insert a single document into a collection.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},doc:{type:"object",description:"Document to insert."}},required:["collection","doc"]},scope:"write"},{name:"skalex_update",description:"Update the first document matching a filter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},filter:{type:"object",description:"Query filter to identify the document."},update:{type:"object",description:"Fields to update (direct assignment, $inc, $push supported)."},many:{type:"boolean",description:"If true, update all matching documents. Default: false."}},required:["collection","filter","update"]},scope:"write"},{name:"skalex_delete",description:"Delete the first document matching a filter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},filter:{type:"object",description:"Query filter to identify the document."},many:{type:"boolean",description:"If true, delete all matching documents. Default: false."}},required:["collection","filter"]},scope:"write"},{name:"skalex_search",description:"Semantic similarity search. Requires an embedding adapter to be configured.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},query:{type:"string",description:"Natural-language query string to embed and compare."},limit:{type:"number",description:"Maximum number of results. Default: 10."},minScore:{type:"number",description:"Minimum cosine similarity score [0, 1]. Default: 0."},filter:{type:"object",description:"Optional structured pre-filter (hybrid search)."}},required:["collection","query"]},scope:"read"},{name:"skalex_ask",description:"Translate a natural-language question into a filter and query a collection. Requires a language model adapter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},question:{type:"string",description:"Natural-language question about the data."},limit:{type:"number",description:"Maximum number of results. Default: 20."}},required:["collection","question"]},scope:"read"}];async function mc(t,i,r){switch(t){case"skalex_collections":return Object.keys(r.collections).filter((s)=>!s.startsWith("_"));case"skalex_schema":return r.schema(ct(i.collection))??null;case"skalex_find":{let s=r.useCollection(ct(i.collection)),n={};if(i.limit)n.limit=i.limit;if(i.sort)n.sort=i.sort;return s.find(i.filter||{},n)}case"skalex_insert":return r.useCollection(ct(i.collection)).insertOne(i.doc||{});case"skalex_update":{let s=r.useCollection(ct(i.collection));if(i.many)return s.updateMany(i.filter||{},i.update||{});return s.updateOne(i.filter||{},i.update||{})}case"skalex_delete":{let s=r.useCollection(ct(i.collection));if(i.many)return s.deleteMany(i.filter||{});return s.deleteOne(i.filter||{})}case"skalex_search":return r.useCollection(ct(i.collection)).search(i.query,{limit:i.limit??10,minScore:i.minScore??0,filter:i.filter});case"skalex_ask":return r.ask(ct(i.collection),i.question,{limit:i.limit??20});default:throw Object.assign(Error(`Unknown tool: ${t}`),{code:"NOT_FOUND"})}}var lr="2.0",cr=-32700,yc=-32600,_s=-32601,wc=-32602,Ac=-32603;function Et(t,i){return{jsonrpc:lr,id:t,result:i}}function Be(t,i,r,s){return{jsonrpc:lr,id:t,error:{code:i,message:r}}}function vc(t){try{let i=JSON.parse(t);if(typeof i!=="object"||i===null||i.jsonrpc!==lr)return{parseError:Be(null,yc,"Invalid JSON-RPC request")};return{msg:i}}catch(i){return{parseError:Be(null,cr,"Parse error")}}}function Ec(t){return{content:[{type:"text",text:t}]}}function ps(t){return{content:[{type:"text",text:t}],isError:!0}}class ra{constructor({port:t=3000,host:i="127.0.0.1",allowedOrigin:r=null,maxBodySize:s=1048576}={}){this._port=t,this._host=i,this._allowedOrigin=r,this._maxBodySize=s,this._clients=new Set,this._onMessage=null,this._server=null}onMessage(t){this._onMessage=t}send(t){let i=`data: ${JSON.stringify(t)}
|
|
74
74
|
|
|
75
|
-
`;for(let r of this._clients)try{r.write(i)}catch(s){this._clients.delete(r)}}start(){return new Promise((t,i)=>{this._server=
|
|
75
|
+
`;for(let r of this._clients)try{r.write(i)}catch(s){this._clients.delete(r)}}start(){return new Promise((t,i)=>{this._server=To.createServer((r,s)=>{if(this._allowedOrigin)s.setHeader("Access-Control-Allow-Origin",this._allowedOrigin),s.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),s.setHeader("Access-Control-Allow-Headers","Content-Type");if(r.method==="OPTIONS"){s.writeHead(204),s.end();return}if(r.method==="GET"&&r.url==="/sse")this._handleSSE(r,s);else if(r.method==="POST"&&r.url==="/message")this._handleMessage(r,s);else s.writeHead(404,{"Content-Type":"text/plain"}),s.end("Not Found")}),this._server.on("error",i),this._server.listen(this._port,this._host,()=>t())})}stop(){return new Promise((t)=>{if(!this._server){t();return}for(let i of this._clients)try{i.end()}catch(r){}this._clients.clear(),this._server.close(()=>t()),this._server=null})}_handleSSE(t,i){i.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),i.write(`event: endpoint
|
|
76
76
|
data: /message
|
|
77
77
|
|
|
78
|
-
`),this._clients.add(i),t.on("close",()=>{this._clients.delete(i)})}async _handleMessage(t,i){let r="";t.setEncoding("utf8"),t.on("data",(s)=>{if(r+=s,r.length>this._maxBodySize)t.destroy(),i.writeHead(413,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Request body too large"}))}),t.on("end",async()=>{i.writeHead(202,{"Content-Type":"application/json"}),i.end("{}");let s;try{s=JSON.parse(r)}catch(n){this.send(Be(null,cr,"Parse error"));return}if(this._onMessage)await this._onMessage(s).catch(()=>{})})}get port(){return this._port}get host(){return this._host}get url(){return`http://${this._host}:${this._port}`}get sseUrl(){return`${this.url}/sse`}}class
|
|
78
|
+
`),this._clients.add(i),t.on("close",()=>{this._clients.delete(i)})}async _handleMessage(t,i){let r="";t.setEncoding("utf8"),t.on("data",(s)=>{if(r+=s,r.length>this._maxBodySize)t.destroy(),i.writeHead(413,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Request body too large"}))}),t.on("end",async()=>{i.writeHead(202,{"Content-Type":"application/json"}),i.end("{}");let s;try{s=JSON.parse(r)}catch(n){this.send(Be(null,cr,"Parse error"));return}if(this._onMessage)await this._onMessage(s).catch(()=>{})})}get port(){return this._port}get host(){return this._host}get url(){return`http://${this._host}:${this._port}`}get sseUrl(){return`${this.url}/sse`}}class sa{constructor(){this._onMessage=null,this._buffer="",this._started=!1}onMessage(t){this._onMessage=t}send(t){process.stdout.write(JSON.stringify(t)+`
|
|
79
79
|
`)}start(){if(this._started)return;this._started=!0,process.stdin.setEncoding("utf8"),process.stdin.on("data",(t)=>{this._buffer+=t;let i;while((i=this._buffer.indexOf(`
|
|
80
|
-
`))!==-1){let r=this._buffer.slice(0,i).trim();if(this._buffer=this._buffer.slice(i+1),r&&this._onMessage){let s;try{s=JSON.parse(r)}catch(n){this.send(Be(null,cr,"Parse error"));continue}this._onMessage(s).catch(()=>{})}}}),process.stdin.on("end",()=>{process.exit(0)})}stop(){process.stdin.removeAllListeners("data"),process.stdin.removeAllListeners("end"),this._started=!1}}var Ec={name:"skalex",version:"4.0.0-alpha"},xc="2024-11-05";class sa{constructor(t,i={}){this._db=t,this._transport=i.transport||"stdio",this._port=i.port||3000,this._host=i.host||"127.0.0.1",this._allowedOrigin=i.allowedOrigin??null,this._maxBodySize=i.maxBodySize??1048576,this._scopes=i.scopes||{"*":["read"]},this._t=null}async listen(){if(this._transport==="http")this._t=new ia({port:this._port,host:this._host,allowedOrigin:this._allowedOrigin,maxBodySize:this._maxBodySize});else this._t=new ra;this._t.onMessage((t)=>this._handleMessage(t)),await this._t.start()}async connect(t){if(this._t=t,this._t.onMessage((i)=>this._handleMessage(i)),typeof this._t.start==="function")await this._t.start()}async close(){if(this._t&&typeof this._t.stop==="function")await this._t.stop();this._t=null}get transport(){return this._transport}get url(){return this._t?.url}async _handleMessage(t){let{msg:i,parseError:r}=typeof t==="string"?Ac(t):{msg:t};if(r){this._send(r);return}let{id:s,method:n,params:a}=i;if(s===void 0){if(n==="notifications/initialized")return;return}try{switch(n){case"initialize":this._send(Et(s,{protocolVersion:xc,capabilities:{tools:{}},serverInfo:Ec}));break;case"tools/list":this._send(Et(s,{tools:this._visibleTools()}));break;case"tools/call":await this._handleToolCall(s,a);break;case"ping":this._send(Et(s,{}));break;default:this._send(Be(s,fs,`Method not found: ${n}`))}}catch(o){this._send(Be(s,wc,o.message||"Internal error"))}}async _handleToolCall(t,i){let r=i?.name,s=i?.arguments??{};if(!r){this._send(Be(t,yc,"tools/call requires params.name"));return}let n=hs.find((o)=>o.name===r);if(!n){this._send(Be(t,fs,`Unknown tool: ${r}`));return}let a=s.collection||s.collection_name||null;if(!this._hasScope(a,n.scope)){this._send(Et(t,_s(`Access denied: "${r}" requires "${n.scope}" scope on collection "${a}".`)));return}try{let o=await gc(r,s,this._db);this._send(Et(t,vc(JSON.stringify(o,null,2))))}catch(o){this._send(Et(t,_s(o.message||String(o))))}}_visibleTools(){return hs.filter((t)=>{let i=this._scopes["*"];if(i&&(i.includes(t.scope)||i.includes("admin")))return!0;for(let[,r]of Object.entries(this._scopes))if(r.includes(t.scope)||r.includes("admin"))return!0;return!1})}_hasScope(t,i){let r=(s)=>s.includes("admin")||s.includes(i);if(t&&this._scopes[t])return r(this._scopes[t]);if(this._scopes["*"])return r(this._scopes["*"]);return!1}_send(t){this._t?.send(t)}}var Ht="migrations",ps=(t)=>JSON.stringify(t,function(i,r){let s=this[i];if(s instanceof Date)return{__skalex_date__:s.toISOString()};if(typeof r==="bigint")return{__skalex_bigint__:r.toString()};return r}),gs=(t)=>JSON.parse(t,(i,r)=>{if(r&&typeof r==="object"){if("__skalex_bigint__"in r)return BigInt(r.__skalex_bigint__);if("__skalex_date__"in r)return new Date(r.__skalex_date__)}return r});class he{constructor({path:t="./.db",format:i="gz",debug:r=!1,adapter:s,ai:n,encrypt:a,slowQueryLog:o,queryCache:c,memory:l,logger:d,plugins:u,llmAdapter:f,embeddingAdapter:h,regexMaxLength:_,idGenerator:p,serializer:g,deserializer:m,autoSave:w,ttlSweepInterval:v,lenientLoad:q}={}){if(this.dataDirectory=t,this.dataFormat=i,this.debug=r,!he._errorsAttached)he.SkalexError=Qe,he.ValidationError=P,he.UniqueConstraintError=je,he.TransactionError=Ne,he.PersistenceError=He,he.AdapterError=be,he.QueryError=ft,he._errorsAttached=!0;this._adapterConfig=s??null;let E=s||new jn({dir:t,format:i});if(a)E=new Hn(E,a.key);if(this.fs=E,this._registry=new Kn(Mn),this.collections=this._registry.stores,this._collectionInstances=this._registry._instances,this._migrations=new qn,this._connectPromise=null,this.isConnected=!1,this._aiConfig=n||null,this._encryptConfig=a||null,this._pluginsConfig=Array.isArray(u)?u:null,this._memoryConfig=l||null,this._regexMaxLength=_??500,this._idGenerator=p??null,this._serializer=g??ps,this._deserializer=m??gs,this._autoSave=w??!1,this._txManager=new Fn,this._ttlSweepInterval=v??0,this._ttlTimer=null,this._logger=d??ns,this._embeddingAdapter=h??(n?sc(n):null),this._aiAdapter=f??(n?nc(n):null),this._persistence=new Un({adapter:this.fs,serializer:this._serializer,deserializer:this._deserializer,logger:this._logger,debug:this.debug,lenientLoad:q??!1}),this._changeLog=new Jn(this),this._queryCache=new Yn(c||{}),this._eventBus=new Qn,this._queryLog=o?new Zn(o):null,this._sessionStats=new ea,this._plugins=new ta,Array.isArray(u))for(let A of u)this._plugins.register(A)}async connect(){if(this._connectPromise)return this._connectPromise;return this._connectPromise=this._doConnect(),this._connectPromise}async _doConnect(){try{await this.loadData();let t=this._getMeta();if(t.queryCache)this._queryCache.fromJSON(t.queryCache);if(this._migrations._migrations.length>0){let i=t.appliedVersions||[],r=await this._migrations.run((s)=>this.useCollection(`_migration_${s}`),i);this._saveMeta({appliedVersions:r})}if(this._sweepTtl(),this._ttlSweepInterval>0){if(this._ttlTimer=setInterval(()=>this._sweepTtl(),this._ttlSweepInterval),this._ttlTimer?.unref)this._ttlTimer.unref()}this.isConnected=!0,this._log("> - Connected to the database (\u221A)")}catch(t){throw this._logger(`Error connecting to the database: ${t}`,"error"),t}}async disconnect(){try{if(this._ttlTimer)clearInterval(this._ttlTimer),this._ttlTimer=null;await this.saveData(),this._registry.clear(),this.collections=this._registry.stores,this._collectionInstances=this._registry._instances,this._connectPromise=null,this.isConnected=!1,this._log("> - Disconnected from the database (\u221A)")}catch(t){throw this._logger(`Error disconnecting from the database: ${t}`,"error"),t}}async _ensureConnected(){if(this.isConnected)return;return this.connect()}useCollection(t){return this._registry.get(t,this)}createCollection(t,i={}){return this._registry.create(t,i,this)}_createCollectionStore(t,i={}){this._registry.createStore(t,i)}async renameCollection(t,i){this._registry.rename(t,i),await this.saveData(i),await this.fs.delete(t)}async loadData(){await this._persistence.loadAll(this.collections,{parseSchema:kn,buildIndex:this._registry.buildIndex,IndexEngine:ri});for(let t in this._collectionInstances){let i=this.collections[t];if(i&&this._collectionInstances[t]._store!==i)this._collectionInstances[t]._store=i}}async saveData(t){await this._persistence.save(this.collections,t)}buildIndex(t,i){return this._registry.buildIndex(t,i)}addMigration(t){this._migrations.add(t)}migrationStatus(){let t=this._getMeta();return this._migrations.status(t.appliedVersions||[])}namespace(t){if(this._adapterConfig)throw new be("ERR_SKALEX_ADAPTER_NAMESPACE_REQUIRES_FS","namespace() requires the default FsAdapter. When a custom storage adapter is configured, create a separate Skalex instance with your adapter instead.");let i=String(t).replace(/[^a-zA-Z0-9_-]/g,"_");if(!i)throw new P("ERR_SKALEX_VALIDATION_NAMESPACE_ID","namespace: id must contain at least one alphanumeric character",{id:t});return new he({path:`${this.dataDirectory}/${i}`,format:this.dataFormat,debug:this.debug,ai:this._aiConfig||void 0,encrypt:this._encryptConfig||void 0,slowQueryLog:this._queryLog?{threshold:this._queryLog._threshold,maxEntries:this._queryLog._maxEntries}:void 0,queryCache:this._queryCache?{maxSize:this._queryCache._maxSize,ttl:this._queryCache._ttl}:void 0,plugins:this._pluginsConfig||void 0,memory:this._memoryConfig||void 0,logger:this._logger!==ns?this._logger:void 0,llmAdapter:this._aiAdapter&&!this._aiConfig?this._aiAdapter:void 0,embeddingAdapter:this._embeddingAdapter&&!this._aiConfig?this._embeddingAdapter:void 0,regexMaxLength:this._regexMaxLength!==500?this._regexMaxLength:void 0,idGenerator:this._idGenerator||void 0,serializer:this._serializer!==ps?this._serializer:void 0,deserializer:this._deserializer!==gs?this._deserializer:void 0,autoSave:this._autoSave||void 0,ttlSweepInterval:this._ttlSweepInterval||void 0})}use(t){this._plugins.register(t)}watch(t){return this._eventBus.on("*",t)}sessionStats(t){if(t!==void 0)return this._sessionStats.get(t);return this._sessionStats.all()}get _inTransaction(){return this._txManager.active}_emitEvent(t,i){if(!this._txManager.defer(()=>this._eventBus.emit(t,i)))this._eventBus.emit(t,i)}async _runAfterHook(t,i){if(!this._txManager.defer(()=>this._plugins.run(t,i)))await this._plugins.run(t,i)}async _logChange(t,i,r,s,n){if(!this._txManager.defer(()=>this._changeLog.log(t,i,r,s,n)))await this._changeLog.log(t,i,r,s,n)}async transaction(t,i={}){return this._txManager.run(t,this,i)}async seed(t,{reset:i=!1}={}){for(let[r,s]of Object.entries(t)){if(i&&this.collections[r])this._applySnapshot(r,{data:[],index:new Map}),delete this._collectionInstances[r];await this.useCollection(r).insertMany(s)}await this.saveData()}dump(){return this._registry.dump()}inspect(t){return this._registry.inspect(t)}async import(t){let i=await this.fs.readRaw(t),r;try{r=JSON.parse(i)}catch{throw new He("ERR_SKALEX_PERSISTENCE_INVALID_JSON",`import: invalid JSON in file "${t}"`,{filePath:t})}let s=t.split("/").pop().replace(/\.[^.]+$/,"");return this.useCollection(s).insertMany(Array.isArray(r)?r:[r],{save:!0})}async embed(t){if(!this._embeddingAdapter)throw new be("ERR_SKALEX_ADAPTER_EMBEDDING_REQUIRED","db.embed() requires an AI adapter. Pass { ai: { provider, apiKey } } to the Skalex constructor.");return this._embeddingAdapter.embed(t)}async ask(t,i,{limit:r=20}={}){if(!this._aiAdapter)throw new be("ERR_SKALEX_ADAPTER_LLM_REQUIRED",'db.ask() requires a language model adapter. Configure { ai: { provider, model: "..." } }.');let s=this.useCollection(t),n=this.schema(t),a=this._queryCache.get(t,n,i);if(!a){a=await this._aiAdapter.generate(n,i);let o=pc(a,n);if(o.length)o.forEach((c)=>this._log(`[ask] ${c}`));this._queryCache.set(t,n,i,a),this._saveMeta({queryCache:this._queryCache.toJSON()})}return s.find(fc(a,{regexMaxLength:this._regexMaxLength}),{limit:r})}schema(t){return this._registry.schema(t)}useMemory(t){return new Wn(t,this)}changelog(){return this._changeLog}async restore(t,i,r={}){return this._changeLog.restore(t,i,r)}stats(t){return this._registry.stats(t)}slowQueries(t={}){if(!this._queryLog)return[];return this._queryLog.entries(t)}slowQueryCount(){return this._queryLog?this._queryLog.size:0}clearSlowQueries(){this._queryLog?.clear()}mcp(t={}){return new sa(this,t)}_getMeta(){let t=this.collections._meta;if(!t)return{};return t.index.get(Ht)||{}}_saveMeta(t){if(!this.collections._meta)this._createCollectionStore("_meta");let i=this.collections._meta,r=i.index.get(Ht);if(r)Object.assign(r,t);else{let s={_id:Ht,...t};i.data.push(s),i.index.set(Ht,s)}this._persistence.markDirty(this.collections,"_meta")}_sweepTtl(){for(let t in this.collections){let i=this.collections[t],r=Yl(i.data,i.index,i.fieldIndex?(s)=>i.fieldIndex.remove(s):null);if(r>0)this._persistence.markDirty(this.collections,t),this._log(`TTL sweep: removed ${r} expired docs from "${t}"`)}}_buildCollectionContext(){let t=this;return{ensureConnected:()=>t._ensureConnected(),get txManager(){return t._txManager},get plugins(){return t._plugins},get eventBus(){return t._eventBus},get sessionStats(){return t._sessionStats},get queryLog(){return t._queryLog},get logger(){return t._logger},get persistence(){return t._persistence},get collections(){return t.collections},embed:(i)=>t.embed(i),get idGenerator(){return t._idGenerator},get autoSave(){return t._autoSave},saveCollection:(i)=>t.saveData(i),snapshotCollection:(i)=>t._snapshotCollection(i),getCollection:(i)=>t.useCollection(i),emitEvent:(i,r)=>t._emitEvent(i,r),runAfterHook:(i,r)=>t._runAfterHook(i,r),logChange:(i,r,s,n,a)=>t._logChange(i,r,s,n,a),get fs(){return t.fs},get dataDirectory(){return t.dataDirectory}}}_log(t){if(this.debug)this._logger(t,"info")}_snapshotCollection(t){return{data:structuredClone(t.data)}}_applySnapshot(t,i){let r=this.collections[t];if(!r)return;if(r.data=i.data,r.index=this.buildIndex(i.data,"_id"),r.fieldIndex)r.fieldIndex.buildFromData(i.data)}}function Sc(){let t=Date.now().toString(16),i;try{i=Do.randomBytes(8).toString("hex")}catch{let r=new Uint8Array(8);crypto.getRandomValues(r),i=Array.from(r).map((s)=>s.toString(16).padStart(2,"0")).join("")}return`${t}${i}`}function ms(t,i){let r=t instanceof Error?t.message:t;if(i==="error")console.error(r);else console.log(r)}var ys=new Set(["__proto__","constructor","prototype"]);function _i(t,i){if(!i.includes(".")){if(ys.has(i))return;return t[i]}let r=t;for(let s of i.split(".")){if(ys.has(s))return;if(r==null)return;r=r[s]}return r}class Ze extends Error{constructor(t,i,r={}){super(i);this.name=this.constructor.name,this.code=t,this.details=r}}class j extends Ze{}class Ue extends Ze{}class $e extends Ze{}class We extends Ze{}class Oe extends Ze{}class _t extends Ze{}function Fi(t,i){if(t===i)return!0;if(t==null||i==null)return!1;if(typeof t!==typeof i)return!1;if(t instanceof Date&&i instanceof Date)return t.getTime()===i.getTime();if(t instanceof RegExp&&i instanceof RegExp)return t.source===i.source&&t.flags===i.flags;if(Array.isArray(t)){if(!Array.isArray(i)||t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!Fi(t[r],i[r]))return!1;return!0}if(typeof t==="object"){if(Array.isArray(i))return!1;let r=Object.keys(t);if(r.length!==Object.keys(i).length)return!1;for(let s of r){if(!Object.prototype.hasOwnProperty.call(i,s))return!1;if(!Fi(t[s],i[s]))return!1}return!0}return!1}function ne(t,i){if(typeof i==="function")return i(t);if(i==null)return!0;if(typeof i==="object"&&Object.keys(i).length===0)return!0;if("$or"in i){let r=i.$or;if(!Array.isArray(r))throw new _t("ERR_SKALEX_QUERY_INVALID_OPERATOR","$or must be an array of filters",{operator:"$or"});if(!r.some((s)=>ne(t,s)))return!1}if("$and"in i){let r=i.$and;if(!Array.isArray(r))throw new _t("ERR_SKALEX_QUERY_INVALID_OPERATOR","$and must be an array of filters",{operator:"$and"});if(!r.every((s)=>ne(t,s)))return!1}if("$not"in i){if(ne(t,i.$not))return!1}for(let r in i){if(r==="$or"||r==="$and"||r==="$not")continue;let s=i[r],n;try{n=_i(t,r)}catch{return!1}if(s instanceof RegExp){if(!s.test(String(n)))return!1}else if(typeof s==="object"&&s!==null){if(Object.keys(s).some((a)=>a.startsWith("$"))){if("$eq"in s&&n!==s.$eq)return!1;if("$ne"in s&&n===s.$ne)return!1;if("$gt"in s&&!(n>s.$gt))return!1;if("$lt"in s&&!(n<s.$lt))return!1;if("$gte"in s&&!(n>=s.$gte))return!1;if("$lte"in s&&!(n<=s.$lte))return!1;if("$in"in s&&!s.$in.includes(n))return!1;if("$nin"in s&&s.$nin.includes(n))return!1;if("$regex"in s){if(!(s.$regex instanceof RegExp?s.$regex:new RegExp(s.$regex)).test(String(n)))return!1}if("$fn"in s&&!s.$fn(n))return!1}else if(!Fi(n,s))return!1}else if(n!==s)return!1}return!0}function Ic(t,i=new Set){if(typeof t!=="object"||t===null||typeof t==="function")return t;let r=[],s=[],n=[],a=[],o=[];for(let l in t){if(l==="$or"||l==="$and"||l==="$not"){o.push(l);continue}let d=t[l];if(i.has(l))r.push(l);else if(d instanceof RegExp||typeof d==="object"&&d!==null&&(("$regex"in d)||("$fn"in d))||typeof d==="function")a.push(l);else if(typeof d==="object"&&d!==null&&(("$gt"in d)||("$lt"in d)||("$gte"in d)||("$lte"in d)||("$ne"in d)||("$in"in d)||("$nin"in d)))n.push(l);else s.push(l)}let c={};for(let l of[...r,...s,...n,...a,...o])c[l]=t[l];return c}var Ki=new Set(["string","number","boolean","object","array","date","any"]);function dr(t){if(Array.isArray(t))return"array";if(t instanceof Date)return"date";return typeof t}function na(t){let i=new Map,r=[];for(let[s,n]of Object.entries(t)){let a;if(typeof n==="string"){if(!Ki.has(n))throw new j("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${n}" for field "${s}"`,{field:s,type:n});a={type:n,required:!1,unique:!1}}else if(typeof n==="object"&&n!==null){let{type:o="any",required:c=!1,unique:l=!1,enum:d}=n;if(!Ki.has(o))throw new j("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${o}" for field "${s}"`,{field:s,type:o});if(a={type:o,required:c,unique:l,enum:d},l)r.push(s)}else throw new j("ERR_SKALEX_VALIDATION_INVALID_SCHEMA",`Invalid schema definition for field "${s}"`,{field:s});i.set(s,a)}return{fields:i,uniqueFields:r}}function ws(t,i,r=!1){let s=[];for(let[n,a]of i){let o=t[n],c=o===void 0||o===null;if(a.required&&c){s.push(`Field "${n}" is required`);continue}if(c)continue;if(a.type!=="any"){let l=dr(o);if(l!==a.type)s.push(`Field "${n}" must be of type "${a.type}", got "${l}"`)}if(a.enum&&!a.enum.includes(o))s.push(`Field "${n}" must be one of [${a.enum.map((l)=>JSON.stringify(l)).join(", ")}], got ${JSON.stringify(o)}`)}if(r){for(let n of Object.keys(t))if(!n.startsWith("_")&&!i.has(n))s.push(`Unknown field "${n}" (strict mode)`)}return s}function As(t,i){let r={};for(let[s,n]of Object.entries(t)){if(s.startsWith("_")){r[s]=n;continue}if(!i.has(s))continue;let a=i.get(s);if(a.type!=="any"){if(dr(n)!==a.type)continue}if(a.enum&&!a.enum.includes(n))continue;r[s]=n}return r}function bc(t){let i={};for(let[r,s]of Object.entries(t)){if(r.startsWith("_"))continue;let n=dr(s);i[r]=Ki.has(n)?n:"any"}return i}function Tc(t){if(typeof t==="number"){if(t<=0)throw new j("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got ${t}`,{ttl:t});return t*1000}if(typeof t!=="string")throw new j("ERR_SKALEX_VALIDATION_TTL",`Invalid TTL value: ${t}`,{ttl:t});let i=t.match(/^(\d+(?:\.\d+)?)(ms|s|m|h|d)$/);if(!i)throw new j("ERR_SKALEX_VALIDATION_TTL_FORMAT",`Invalid TTL format: "${t}". Use e.g. 300 (seconds), "30m", "24h", "7d"`,{ttl:t});let r=parseFloat(i[1]);if(r<=0)throw new j("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got "${t}"`,{ttl:t});let s=i[2],n=r*{ms:1,s:1000,m:60000,h:3600000,d:86400000}[s];if(!isFinite(n))throw new j("ERR_SKALEX_VALIDATION_TTL",`TTL value "${t}" is too large`,{ttl:t});return n}function Oc(t){return new Date(Date.now()+Tc(t))}function Rc(t,i,r=null){let s=Date.now(),n=0,a=t.length;while(a--){let o=t[a];if(o._expiresAt&&new Date(o._expiresAt).getTime()<=s){if(t.splice(a,1),i.delete(o._id),r)r(o);n++}}return n}function vs(t,i){if(t.length!==i.length)throw new _t("ERR_SKALEX_QUERY_VECTOR_MISMATCH",`Vector dimension mismatch: ${t.length} vs ${i.length}`,{expected:t.length,got:i.length});let r=0,s=0,n=0;for(let o=0;o<t.length;o++)r+=t[o]*i[o],s+=t[o]*t[o],n+=i[o]*i[o];let a=Math.sqrt(s*n);return a===0?0:r/a}function te(t){if(!("_vector"in t))return{...t};let{_vector:i,...r}=t;return r}function Cc(t){return t.length}function Nc(t,i){let r=0;for(let s of t){let n=_i(s,i);if(typeof n==="number"&&!isNaN(n))r+=n}return r}function $c(t,i){let r=0,s=0;for(let n of t){let a=_i(n,i);if(typeof a==="number"&&!isNaN(a))r+=a,s++}return s===0?null:r/s}function kc(t,i){let r=Object.create(null);for(let s of t){let n=String(_i(s,i)??"__null__");if(!r[n])r[n]=[];r[n].push(s)}return r}class aa{constructor(t){this._col=t}get _ctx(){return this._col._ctx}async execute({op:t,beforeHook:i,afterHook:r,hookPayload:s,mutate:n,afterHookPayload:a,save:o,session:c}){let l=this._ctx;await l.ensureConnected(),this._col._txSnapshotIfNeeded();let d=l.txManager,u=d.active&&this._col._activeTxId===d.context?.id,f=u?d.context.id:null,h=this._col._createdInTxId,_=()=>{if(f!==null&&d._abortedIds.has(f))throw new $e("ERR_SKALEX_TX_ABORTED",`Transaction ${f} was aborted. No further mutations allowed.`);if(h!==null&&d._abortedIds.has(h))throw new $e("ERR_SKALEX_TX_ABORTED",`Transaction ${h} was aborted. Collection obtained inside that transaction cannot be used for further mutations.`)};if(u||h!==null)_();if(i)await l.plugins.run(i,s);let{docs:p,prevDocs:g=[]}=await n(_);if(l.persistence.markDirty(l.collections,this._col.name),await this._col._saveIfNeeded(o),this._col._changelogEnabled)for(let m=0;m<p.length;m++)await l.logChange(t,this._col.name,p[m],g[m]??null,c||null);if(!u||!d.defer(()=>l.sessionStats.recordWrite(c)))l.sessionStats.recordWrite(c);for(let m of p)l.emitEvent(this._col.name,{op:t,collection:this._col.name,doc:te(m)});if(r)if(a)await l.runAfterHook(r,a(p));else for(let m of p)await l.runAfterHook(r,{collection:this._col.name,doc:te(m)});return{docs:p,prevDocs:g}}}function Dc(t){let i={};for(let r in t){if(r.startsWith("$"))continue;let s=t[r];if(s&&typeof s==="object"&&!Array.isArray(s)){let n=Object.keys(s);if(n.length===1&&n[0]==="$eq")i[r]=s.$eq}else i[r]=s}return i}var oa=new Set(["__proto__","constructor","prototype"]);function la(t){if(typeof t!=="object"||t===null||Array.isArray(t))return t;let i={};for(let r of Object.keys(t)){if(oa.has(r))continue;i[r]=la(t[r])}return i}class ca{constructor(t,i){this.name=t.collectionName,this.database=i,this._ctx=i._buildCollectionContext(),this._store=t,this._pipeline=new aa(this),this._createdInTxId=i._txManager.context?.id??null,this._activeTxId=null}get _data(){return this._store.data}set _data(t){this._store.data=t}get _index(){return this._store.index}get _fieldIndex(){return this._store.fieldIndex||null}get _schema(){return this._store.schema?this._store.schema.fields:null}get _changelogEnabled(){return this._store.changelog===!0}get _softDelete(){return this._store.softDelete===!0}get _versioning(){return this._store.versioning===!0}get _strict(){return this._store.strict===!0}get _onSchemaError(){return this._store.onSchemaError??"throw"}get _defaultTtl(){return this._store.defaultTtl||null}get _defaultEmbed(){return this._store.defaultEmbed||null}get _maxDocs(){return this._store.maxDocs||null}async insertOne(t,i={}){let{save:r,ifNotExists:s,ttl:n,embed:a,session:o}=i;if(s){await this._ctx.ensureConnected();let l=this._findRaw(t);if(l)return te({...l})}let{docs:c}=await this._insertCore([t],{ttl:n,embed:a,session:o,save:r});return te(c[0])}async insertMany(t,i={}){let{save:r,ttl:s,embed:n,session:a}=i,{docs:o}=await this._insertCore(t,{ttl:s,embed:n,session:a,save:r});return o.map(te)}async _insertCore(t,{ttl:i,embed:r,session:s,save:n}){return this._pipeline.execute({op:"insert",beforeHook:null,afterHook:"afterInsert",hookPayload:null,save:n,session:s,mutate:async(a)=>{let o=[],c=new Set;for(let l of t){let d=this._applyValidation(l);await this._ctx.plugins.run("beforeInsert",{collection:this.name,doc:d});let u=await this._buildDoc(d,{ttl:i,embed:r});if(this._index.has(u._id)||c.has(u._id))throw new Ue("ERR_SKALEX_UNIQUE_DUPLICATE_ID",`Duplicate _id "${u._id}" in collection "${this.name}"`,{id:u._id,collection:this.name});c.add(u._id),o.push(u)}if(a(),this._fieldIndex)this._fieldIndex.assertUniqueBatch(o);for(let l of o)this._addToIndex(l);this._data.push(...o);for(let l of o)this._index.set(l._id,l);return this._enforceCapAfterInsert(),{docs:o}}})}async updateOne(t,i,r={}){await this._ctx.ensureConnected();let s=this._findRaw(t);if(!s)return null;let{save:n,session:a}=r,{docs:o}=await this._updateCore([s],t,i,{save:n,session:a});return te(o[0])}async updateMany(t,i,r={}){await this._ctx.ensureConnected();let s=this._findAllRaw(t);if(s.length===0)return[];let{save:n,session:a}=r,{docs:o}=await this._updateCore(s,t,i,{save:n,session:a});return o.map(te)}async _updateCore(t,i,r,{save:s,session:n}){return this._pipeline.execute({op:"update",beforeHook:"beforeUpdate",afterHook:"afterUpdate",hookPayload:{collection:this.name,filter:i,update:r},save:s,session:n,afterHookPayload:(a)=>({collection:this.name,filter:i,update:r,result:a.length===1?a[0]:a}),mutate:async(a)=>{let o=this._changelogEnabled?t.map((u)=>structuredClone(u)):t.map(()=>null),c=t.map((u)=>this._prepareUpdatedDoc(u,r));this._assertUniqueCandidates(t,c),a();let l=new Set(t),d=new Map;for(let u=0;u<this._data.length;u++)if(l.has(this._data[u]))d.set(this._data[u],u);for(let u=0;u<t.length;u++)this._commitUpdatedDoc(t[u],c[u],d);return{docs:c,prevDocs:o}}})}applyUpdate(t,i){for(let r in i){if(oa.has(r))continue;if(r==="_id"||r==="createdAt")continue;let s=i[r];if(Array.isArray(s))t[r]=s;else if(typeof s==="object"&&s!==null){let n=Object.keys(s);if(n.some((a)=>a.startsWith("$"))){for(let a of n)if(a==="$inc"&&typeof t[r]==="number")t[r]+=s[a];else if(a==="$push"){if(!Array.isArray(t[r]))t[r]=[];t[r].push(s[a])}}else t[r]=la(s)}else t[r]=s}if(t.updatedAt=new Date,this._versioning)t._version=(t._version??0)+1;return t}_prepareUpdatedDoc(t,i){let r=structuredClone(t),s=structuredClone(t);if(this.applyUpdate(s,i),!this._schema)return s;let n=ws(s,this._schema,this._strict);if(!n.length)return s;switch(this._onSchemaError){case"throw":throw new j("ERR_SKALEX_VALIDATION_UPDATE",`Update validation failed on doc "${t._id}": ${n.join("; ")}`,{id:t._id,errors:n});case"strip":return this._stripCandidateToValid(s,r);default:return this._ctx.logger(`[${this.name}] Update validation warning: ${n.join("; ")}`,"warn"),s}}_stripCandidateToValid(t,i){let r=As(t,this._schema),s=structuredClone(i);for(let[n,a]of Object.entries(r)){if(n.startsWith("_"))continue;s[n]=a}if(s.updatedAt=t.updatedAt,this._versioning)s._version=t._version;return s}_commitUpdatedDoc(t,i,r){let s=r?r.get(t):this._data.indexOf(t);if(s===void 0||s===-1)throw new We("ERR_SKALEX_PERSISTENCE_DOC_MISSING",`Document "${t._id}" no longer exists in collection "${this.name}"`,{id:t._id,collection:this.name});this._data[s]=i,this._index.set(i._id,i),this._updateInIndex(t,i)}_assertUniqueCandidates(t,i){this._fieldIndex?.assertUniqueCandidates(t,i)}async upsert(t,i,r={}){if(await this._ctx.ensureConnected(),this._findRaw(t))return this.updateOne(t,i,r);return this.insertOne({...Dc(t),...i},r)}async upsertMany(t,i,r={}){await this._ctx.ensureConnected();let{save:s,...n}=r,a=[];for(let o of t)a.push(await this.upsert({[i]:o[i]},o,{...n,save:!1}));return await this._saveIfNeeded(s),a}async restore(t,i={}){if(!this._softDelete)throw new _t("ERR_SKALEX_QUERY_SOFT_DELETE_REQUIRED",`restore() requires softDelete on "${this.name}"`,{collection:this.name});await this._ctx.ensureConnected();let{save:r,session:s}=i,n=this._findRaw(t,{includeDeleted:!0});if(!n||!n._deletedAt)return null;let{docs:a}=await this._pipeline.execute({op:"restore",beforeHook:null,afterHook:null,hookPayload:null,save:r,session:s,mutate:async(o)=>(o(),delete n._deletedAt,n.updatedAt=new Date,this._index.set(n._id,n),{docs:[n]})});return te(a[0])}watch(t,i){if(typeof t==="function")i=t,t=null;if(i)return this._ctx.eventBus.on(this.name,(r)=>{if(!t||ne(r.doc,t))i(r)});return this._watchIterator(t)}_watchIterator(t){let i=[],r=null,s=!1,n=this._ctx.eventBus.on(this.name,(a)=>{if(t&&!ne(a.doc,t))return;if(r){let o=r;r=null,o({value:a,done:!1})}else i.push(a)});return{[Symbol.asyncIterator](){return this},next(){if(i.length>0)return Promise.resolve({value:i.shift(),done:!1});if(s)return Promise.resolve({value:void 0,done:!0});return new Promise((a)=>{r=a})},return(){if(s=!0,n(),r){let a=r;r=null,a({value:void 0,done:!0})}return Promise.resolve({value:void 0,done:!0})}}}async count(t={}){return await this._ctx.ensureConnected(),Cc(this._findAllRaw(t))}async sum(t,i={}){return await this._ctx.ensureConnected(),Nc(this._findAllRaw(i),t)}async avg(t,i={}){return await this._ctx.ensureConnected(),$c(this._findAllRaw(i),t)}async groupBy(t,i={}){return await this._ctx.ensureConnected(),kc(this._findAllRaw(i),t)}async findOne(t,i={}){await this._ctx.ensureConnected();let{populate:r,select:s,includeDeleted:n=!1}=i,a=this._findRaw(t,{includeDeleted:n});if(!a)return null;let o=this._projectDoc(a,s);if(r)await this._populateDoc(o,a,r);return o}async find(t,i={}){await this._ctx.ensureConnected();let r=Date.now(),{populate:s,select:n,sort:a,page:o=1,limit:c,session:l,includeDeleted:d=!1}=i;await this._ctx.plugins.run("beforeFind",{collection:this.name,filter:t,options:i});let u=this._getCandidates(t),f=Ic(t,this._fieldIndex?this._fieldIndex.indexedFields:new Set),h=[];for(let p of u){if(this._softDelete&&p._deletedAt&&!d)continue;if(!ne(p,f))continue;let g=this._projectDoc(p,n);if(s)await this._populateDoc(g,p,s);h.push(g)}if(a){let p=Object.keys(a);h.sort((g,m)=>{for(let w of p){let v=a[w];if(g[w]<m[w])return-v;if(g[w]>m[w])return v}return 0})}let _;if(c){let p=h.length,g=Math.ceil(p/c),m=(o-1)*c;h=h.slice(m,m+c),_={page:o,totalDocs:p,totalPages:g}}return this._ctx.queryLog?.record({collection:this.name,op:"find",filter:t,duration:Date.now()-r,resultCount:h.length}),this._ctx.sessionStats.recordRead(l),await this._ctx.plugins.run("afterFind",{collection:this.name,filter:t,options:i,docs:h}),_?{docs:h,..._}:{docs:h}}async search(t,{filter:i,limit:r=10,minScore:s=0,session:n}={}){await this._ctx.ensureConnected();let a=Date.now();await this._ctx.plugins.run("beforeSearch",{collection:this.name,query:t,options:{filter:i,limit:r,minScore:s}});let o=await this._ctx.embed(t),c=i?this._findAllRaw(i):this._data,l=[];for(let h of c){if(!h._vector)continue;let _=vs(o,h._vector);if(_>=s)l.push({doc:h,score:_})}l.sort((h,_)=>_.score-h.score);let d=l.slice(0,r);this._ctx.queryLog?.record({collection:this.name,op:"search",query:t,duration:Date.now()-a,resultCount:d.length}),this._ctx.sessionStats.recordRead(n);let u=d.map((h)=>te(h.doc)),f=d.map((h)=>h.score);return await this._ctx.plugins.run("afterSearch",{collection:this.name,query:t,options:{filter:i,limit:r,minScore:s},docs:u,scores:f}),{docs:u,scores:f}}async similar(t,{limit:i=10,minScore:r=0}={}){await this._ctx.ensureConnected();let s=this._index.get(t);if(!s||!s._vector)return{docs:[],scores:[]};let n=[];for(let o of this._data){if(o._id===t||!o._vector)continue;let c=vs(s._vector,o._vector);if(c>=r)n.push({doc:o,score:c})}n.sort((o,c)=>c.score-o.score);let a=n.slice(0,i);return{docs:a.map((o)=>te(o.doc)),scores:a.map((o)=>o.score)}}async deleteOne(t,i={}){await this._ctx.ensureConnected();let{save:r,session:s}=i;if(this._softDelete){let a=this._findRaw(t);if(!a)return null;let{docs:o}=await this._deleteCore("soft",[a],t,{save:r,session:s});return te(o[0])}let{docs:n}=await this._deleteCore("hard",null,t,{save:r,session:s});if(n.length===0)return null;return te(n[0])}async deleteMany(t,i={}){await this._ctx.ensureConnected();let{save:r,session:s}=i;if(this._softDelete){let a=this._findAllRaw(t);if(a.length===0)return[];let{docs:o}=await this._deleteCore("soft",a,t,{save:r,session:s});return o.map(te)}let{docs:n}=await this._deleteCore("hardMany",null,t,{save:r,session:s});return n.map(te)}async _deleteCore(t,i,r,{save:s,session:n}){return this._pipeline.execute({op:"delete",beforeHook:"beforeDelete",afterHook:"afterDelete",hookPayload:{collection:this.name,filter:r},save:s,session:n,afterHookPayload:(a)=>({collection:this.name,filter:r,result:a.length===1?a[0]:a}),mutate:async(a)=>{if(a(),t==="soft"){let l=new Date;for(let d of i)d._deletedAt=l,d.updatedAt=l,this._index.set(d._id,d);return{docs:i}}if(t==="hard"){let l=this._findIndex(r);if(l===-1)return{docs:[]};let d=this._data.splice(l,1)[0];return this._index.delete(d._id),this._removeFromIndex(d),{docs:[d]}}let o=[],c=[];for(let l of this._data)if(ne(l,r))o.push(l),this._index.delete(l._id),this._removeFromIndex(l);else c.push(l);return this._data=c,{docs:o}}})}async export(t={},i={}){let{dir:r,name:s,format:n="json"}=i;try{let a=this._data.filter((u)=>ne(u,t));if(a.length===0)throw new _t("ERR_SKALEX_QUERY_EXPORT_EMPTY",`export(): no documents matched the filter in "${this.name}"`,{collection:this.name});let o;if(n==="json")o=JSON.stringify(a,null,2);else{let u=(_)=>{if(_==null)return"";let p=typeof _==="object"?JSON.stringify(_):String(_);return p.includes(",")||p.includes('"')||p.includes(`
|
|
80
|
+
`))!==-1){let r=this._buffer.slice(0,i).trim();if(this._buffer=this._buffer.slice(i+1),r&&this._onMessage){let s;try{s=JSON.parse(r)}catch(n){this.send(Be(null,cr,"Parse error"));continue}this._onMessage(s).catch(()=>{})}}}),process.stdin.on("end",()=>{process.exit(0)})}stop(){process.stdin.removeAllListeners("data"),process.stdin.removeAllListeners("end"),this._started=!1}}var xc={name:"skalex",version:"4.0.0-alpha"},Sc="2024-11-05";class na{constructor(t,i={}){this._db=t,this._transport=i.transport||"stdio",this._port=i.port||3000,this._host=i.host||"127.0.0.1",this._allowedOrigin=i.allowedOrigin??null,this._maxBodySize=i.maxBodySize??1048576,this._scopes=i.scopes||{"*":["read"]},this._t=null}async listen(){if(this._transport==="http")this._t=new ra({port:this._port,host:this._host,allowedOrigin:this._allowedOrigin,maxBodySize:this._maxBodySize});else this._t=new sa;this._t.onMessage((t)=>this._handleMessage(t)),await this._t.start()}async connect(t){if(this._t=t,this._t.onMessage((i)=>this._handleMessage(i)),typeof this._t.start==="function")await this._t.start()}async close(){if(this._t&&typeof this._t.stop==="function")await this._t.stop();this._t=null}get transport(){return this._transport}get url(){return this._t?.url}async _handleMessage(t){let{msg:i,parseError:r}=typeof t==="string"?vc(t):{msg:t};if(r){this._send(r);return}let{id:s,method:n,params:a}=i;if(s===void 0){if(n==="notifications/initialized")return;return}try{switch(n){case"initialize":this._send(Et(s,{protocolVersion:Sc,capabilities:{tools:{}},serverInfo:xc}));break;case"tools/list":this._send(Et(s,{tools:this._visibleTools()}));break;case"tools/call":await this._handleToolCall(s,a);break;case"ping":this._send(Et(s,{}));break;default:this._send(Be(s,_s,`Method not found: ${n}`))}}catch(o){this._send(Be(s,Ac,o.message||"Internal error"))}}async _handleToolCall(t,i){let r=i?.name,s=i?.arguments??{};if(!r){this._send(Be(t,wc,"tools/call requires params.name"));return}let n=fs.find((o)=>o.name===r);if(!n){this._send(Be(t,_s,`Unknown tool: ${r}`));return}let a=s.collection||s.collection_name||null;if(!this._hasScope(a,n.scope)){this._send(Et(t,ps(`Access denied: "${r}" requires "${n.scope}" scope on collection "${a}".`)));return}try{let o=await mc(r,s,this._db);this._send(Et(t,Ec(JSON.stringify(o,null,2))))}catch(o){this._send(Et(t,ps(o.message||String(o))))}}_visibleTools(){return fs.filter((t)=>{let i=this._scopes["*"];if(i&&(i.includes(t.scope)||i.includes("admin")))return!0;for(let[,r]of Object.entries(this._scopes))if(r.includes(t.scope)||r.includes("admin"))return!0;return!1})}_hasScope(t,i){let r=(s)=>s.includes("admin")||s.includes(i);if(t&&this._scopes[t])return r(this._scopes[t]);if(this._scopes["*"])return r(this._scopes["*"]);return!1}_send(t){this._t?.send(t)}}var Vt="migrations",gs=(t)=>JSON.stringify(t,function(i,r){let s=this[i];if(s instanceof Date)return{__skalex_date__:s.toISOString()};if(typeof r==="bigint")return{__skalex_bigint__:r.toString()};return r}),ms=(t)=>JSON.parse(t,(i,r)=>{if(r&&typeof r==="object"){if("__skalex_bigint__"in r)return BigInt(r.__skalex_bigint__);if("__skalex_date__"in r)return new Date(r.__skalex_date__)}return r});class he{constructor({path:t="./.db",format:i="gz",debug:r=!1,adapter:s,ai:n,encrypt:a,slowQueryLog:o,queryCache:c,memory:l,logger:d,plugins:u,llmAdapter:f,embeddingAdapter:h,regexMaxLength:_,idGenerator:p,serializer:g,deserializer:m,autoSave:w,ttlSweepInterval:v,lenientLoad:q}={}){if(this.dataDirectory=t,this.dataFormat=i,this.debug=r,!he._errorsAttached)he.SkalexError=Qe,he.ValidationError=P,he.UniqueConstraintError=je,he.TransactionError=$e,he.PersistenceError=He,he.AdapterError=Oe,he.QueryError=ft,he._errorsAttached=!0;this._adapterConfig=s??null;let E=s||new qn({dir:t,format:i});if(a)E=new Wn(E,a.key);if(this.fs=E,this._registry=new zn(jn),this.collections=this._registry.stores,this._collectionInstances=this._registry._instances,this._migrations=new Un,this._connectPromise=null,this.isConnected=!1,this._aiConfig=n||null,this._encryptConfig=a||null,this._pluginsConfig=Array.isArray(u)?u:null,this._memoryConfig=l||null,this._regexMaxLength=_??500,this._idGenerator=p??null,this._serializer=g??gs,this._deserializer=m??ms,this._autoSave=w??!1,this._txManager=new Kn,this._ttlSweepInterval=v??0,this._ttlTimer=null,this._logger=d??as,this._embeddingAdapter=h??(n?nc(n):null),this._aiAdapter=f??(n?ac(n):null),this._persistence=new Fn({adapter:this.fs,serializer:this._serializer,deserializer:this._deserializer,logger:this._logger,debug:this.debug,lenientLoad:q??!1}),this._changeLog=new Yn(this),this._queryCache=new Qn(c||{}),this._eventBus=new Zn,this._queryLog=o?new ea(o):null,this._sessionStats=new ta,this._plugins=new ia,Array.isArray(u))for(let A of u)this._plugins.register(A)}async connect(){if(this._connectPromise)return this._connectPromise;return this._connectPromise=this._doConnect(),this._connectPromise}async _doConnect(){try{await this.loadData();let t=this._getMeta();if(t.queryCache)this._queryCache.fromJSON(t.queryCache);if(this._migrations._migrations.length>0){let i=t.appliedVersions||[],r=await this._migrations.run((s)=>this.useCollection(`_migration_${s}`),i);this._saveMeta({appliedVersions:r})}if(this._sweepTtl(),this._ttlSweepInterval>0){if(this._ttlTimer=setInterval(()=>this._sweepTtl(),this._ttlSweepInterval),this._ttlTimer?.unref)this._ttlTimer.unref()}this.isConnected=!0,this._log("> - Connected to the database (\u221A)")}catch(t){throw this._logger(`Error connecting to the database: ${t}`,"error"),t}}async disconnect(){try{if(this._ttlTimer)clearInterval(this._ttlTimer),this._ttlTimer=null;await this.saveData(),this._registry.clear(),this.collections=this._registry.stores,this._collectionInstances=this._registry._instances,this._connectPromise=null,this.isConnected=!1,this._log("> - Disconnected from the database (\u221A)")}catch(t){throw this._logger(`Error disconnecting from the database: ${t}`,"error"),t}}async _ensureConnected(){if(this.isConnected)return;return this.connect()}useCollection(t){return this._registry.get(t,this)}createCollection(t,i={}){return this._registry.create(t,i,this)}_createCollectionStore(t,i={}){this._registry.createStore(t,i)}async renameCollection(t,i){this._registry.rename(t,i),await this.saveData(i),await this.fs.delete(t)}async loadData(){await this._persistence.loadAll(this.collections,{parseSchema:Dn,buildIndex:this._registry.buildIndex,IndexEngine:Zt});for(let t in this._collectionInstances){let i=this.collections[t];if(i&&this._collectionInstances[t]._store!==i)this._collectionInstances[t]._store=i}}async saveData(t){await this._persistence.save(this.collections,t)}buildIndex(t,i){return this._registry.buildIndex(t,i)}addMigration(t){this._migrations.add(t)}migrationStatus(){let t=this._getMeta();return this._migrations.status(t.appliedVersions||[])}namespace(t){if(this._adapterConfig)throw new Oe("ERR_SKALEX_ADAPTER_NAMESPACE_REQUIRES_FS","namespace() requires the default FsAdapter. When a custom storage adapter is configured, create a separate Skalex instance with your adapter instead.");let i=String(t).replace(/[^a-zA-Z0-9_-]/g,"_");if(!i)throw new P("ERR_SKALEX_VALIDATION_NAMESPACE_ID","namespace: id must contain at least one alphanumeric character",{id:t});return new he({path:`${this.dataDirectory}/${i}`,format:this.dataFormat,debug:this.debug,ai:this._aiConfig||void 0,encrypt:this._encryptConfig||void 0,slowQueryLog:this._queryLog?{threshold:this._queryLog._threshold,maxEntries:this._queryLog._maxEntries}:void 0,queryCache:this._queryCache?{maxSize:this._queryCache._maxSize,ttl:this._queryCache._ttl}:void 0,plugins:this._pluginsConfig||void 0,memory:this._memoryConfig||void 0,logger:this._logger!==as?this._logger:void 0,llmAdapter:this._aiAdapter&&!this._aiConfig?this._aiAdapter:void 0,embeddingAdapter:this._embeddingAdapter&&!this._aiConfig?this._embeddingAdapter:void 0,regexMaxLength:this._regexMaxLength!==500?this._regexMaxLength:void 0,idGenerator:this._idGenerator||void 0,serializer:this._serializer!==gs?this._serializer:void 0,deserializer:this._deserializer!==ms?this._deserializer:void 0,autoSave:this._autoSave||void 0,ttlSweepInterval:this._ttlSweepInterval||void 0})}use(t){this._plugins.register(t)}watch(t){return this._eventBus.on("*",t)}sessionStats(t){if(t!==void 0)return this._sessionStats.get(t);return this._sessionStats.all()}get _inTransaction(){return this._txManager.active}_emitEvent(t,i){if(!this._txManager.defer(()=>this._eventBus.emit(t,i)))this._eventBus.emit(t,i)}async _runAfterHook(t,i){if(!this._txManager.defer(()=>this._plugins.run(t,i)))await this._plugins.run(t,i)}async _logChange(t,i,r,s,n){if(!this._txManager.defer(()=>this._changeLog.log(t,i,r,s,n)))await this._changeLog.log(t,i,r,s,n)}async transaction(t,i={}){return this._txManager.run(t,this,i)}async seed(t,{reset:i=!1}={}){for(let[r,s]of Object.entries(t)){if(i&&this.collections[r])this._applySnapshot(r,{data:[],index:new Map}),delete this._collectionInstances[r];await this.useCollection(r).insertMany(s)}await this.saveData()}dump(){return this._registry.dump()}inspect(t){return this._registry.inspect(t)}async import(t){let i=await this.fs.readRaw(t),r;try{r=JSON.parse(i)}catch{throw new He("ERR_SKALEX_PERSISTENCE_INVALID_JSON",`import: invalid JSON in file "${t}"`,{filePath:t})}let s=t.split("/").pop().replace(/\.[^.]+$/,"");return this.useCollection(s).insertMany(Array.isArray(r)?r:[r],{save:!0})}async embed(t){if(!this._embeddingAdapter)throw new Oe("ERR_SKALEX_ADAPTER_EMBEDDING_REQUIRED","db.embed() requires an AI adapter. Pass { ai: { provider, apiKey } } to the Skalex constructor.");return this._embeddingAdapter.embed(t)}async ask(t,i,{limit:r=20}={}){if(!this._aiAdapter)throw new Oe("ERR_SKALEX_ADAPTER_LLM_REQUIRED",'db.ask() requires a language model adapter. Configure { ai: { provider, model: "..." } }.');let s=this.useCollection(t),n=this.schema(t),a=this._queryCache.get(t,n,i);if(!a){a=await this._aiAdapter.generate(n,i);let o=gc(a,n);if(o.length)o.forEach((c)=>this._log(`[ask] ${c}`));this._queryCache.set(t,n,i,a),this._saveMeta({queryCache:this._queryCache.toJSON()})}return s.find(_c(a,{regexMaxLength:this._regexMaxLength}),{limit:r})}schema(t){return this._registry.schema(t)}useMemory(t){return new Jn(t,this)}changelog(){return this._changeLog}async restore(t,i,r={}){return this._changeLog.restore(t,i,r)}stats(t){return this._registry.stats(t)}slowQueries(t={}){if(!this._queryLog)return[];return this._queryLog.entries(t)}slowQueryCount(){return this._queryLog?this._queryLog.size:0}clearSlowQueries(){this._queryLog?.clear()}mcp(t={}){return new na(this,t)}_getMeta(){let t=this.collections._meta;if(!t)return{};return t.index.get(Vt)||{}}_saveMeta(t){if(!this.collections._meta)this._createCollectionStore("_meta");let i=this.collections._meta,r=i.index.get(Vt);if(r)Object.assign(r,t);else{let s={_id:Vt,...t};i.data.push(s),i.index.set(Vt,s)}this._persistence.markDirty(this.collections,"_meta")}_sweepTtl(){for(let t in this.collections){let i=this.collections[t],r=Ql(i.data,i.index,i.fieldIndex?(s)=>i.fieldIndex.remove(s):null);if(r>0)this._persistence.markDirty(this.collections,t),this._log(`TTL sweep: removed ${r} expired docs from "${t}"`)}}_buildCollectionContext(){let t=this;return{ensureConnected:()=>t._ensureConnected(),get txManager(){return t._txManager},get plugins(){return t._plugins},get eventBus(){return t._eventBus},get sessionStats(){return t._sessionStats},get queryLog(){return t._queryLog},get logger(){return t._logger},get persistence(){return t._persistence},get collections(){return t.collections},embed:(i)=>t.embed(i),get idGenerator(){return t._idGenerator},get autoSave(){return t._autoSave},saveCollection:(i)=>t.saveData(i),snapshotCollection:(i)=>t._snapshotCollection(i),getCollection:(i)=>t.useCollection(i),emitEvent:(i,r)=>t._emitEvent(i,r),runAfterHook:(i,r)=>t._runAfterHook(i,r),logChange:(i,r,s,n,a)=>t._logChange(i,r,s,n,a),get fs(){return t.fs},get dataDirectory(){return t.dataDirectory}}}_log(t){if(this.debug)this._logger(t,"info")}_snapshotCollection(t){return{data:structuredClone(t.data)}}_applySnapshot(t,i){let r=this.collections[t];if(!r)return;if(r.data=i.data,r.index=this.buildIndex(i.data,"_id"),r.fieldIndex)r.fieldIndex.buildFromData(i.data)}}function Ic(){let t=Date.now().toString(16),i;try{i=Lo.randomBytes(8).toString("hex")}catch{let r=new Uint8Array(8);crypto.getRandomValues(r),i=Array.from(r).map((s)=>s.toString(16).padStart(2,"0")).join("")}return`${t}${i}`}function ys(t,i){let r=t instanceof Error?t.message:t;if(i==="error")console.error(r);else console.log(r)}var ws=new Set(["__proto__","constructor","prototype"]);function oi(t,i){if(!i.includes(".")){if(ws.has(i))return;return t[i]}let r=t;for(let s of i.split(".")){if(ws.has(s))return;if(r==null)return;r=r[s]}return r}class Ze extends Error{constructor(t,i,r={}){super(i);this.name=this.constructor.name,this.code=t,this.details=r}}class j extends Ze{}class Ue extends Ze{}class ke extends Ze{}class We extends Ze{}class Re extends Ze{}class pt extends Ze{}function ji(t,i){if(t===i)return!0;if(t==null||i==null)return!1;if(typeof t!==typeof i)return!1;if(t instanceof Date&&i instanceof Date)return t.getTime()===i.getTime();if(t instanceof RegExp&&i instanceof RegExp)return t.source===i.source&&t.flags===i.flags;if(Array.isArray(t)){if(!Array.isArray(i)||t.length!==i.length)return!1;for(let r=0;r<t.length;r++)if(!ji(t[r],i[r]))return!1;return!0}if(typeof t==="object"){if(Array.isArray(i))return!1;let r=Object.keys(t);if(r.length!==Object.keys(i).length)return!1;for(let s of r){if(!Object.prototype.hasOwnProperty.call(i,s))return!1;if(!ji(t[s],i[s]))return!1}return!0}return!1}function ne(t,i){if(typeof i==="function")return i(t);if(i==null)return!0;if(typeof i==="object"&&Object.keys(i).length===0)return!0;if("$or"in i){let r=i.$or;if(!Array.isArray(r))throw new pt("ERR_SKALEX_QUERY_INVALID_OPERATOR","$or must be an array of filters",{operator:"$or"});if(!r.some((s)=>ne(t,s)))return!1}if("$and"in i){let r=i.$and;if(!Array.isArray(r))throw new pt("ERR_SKALEX_QUERY_INVALID_OPERATOR","$and must be an array of filters",{operator:"$and"});if(!r.every((s)=>ne(t,s)))return!1}if("$not"in i){if(ne(t,i.$not))return!1}for(let r in i){if(r==="$or"||r==="$and"||r==="$not")continue;let s=i[r],n;try{n=oi(t,r)}catch{return!1}if(s instanceof RegExp){if(!s.test(String(n)))return!1}else if(typeof s==="object"&&s!==null){if(Object.keys(s).some((a)=>a.startsWith("$"))){if("$eq"in s&&n!==s.$eq)return!1;if("$ne"in s&&n===s.$ne)return!1;if("$gt"in s&&!(n>s.$gt))return!1;if("$lt"in s&&!(n<s.$lt))return!1;if("$gte"in s&&!(n>=s.$gte))return!1;if("$lte"in s&&!(n<=s.$lte))return!1;if("$in"in s&&!s.$in.includes(n))return!1;if("$nin"in s&&s.$nin.includes(n))return!1;if("$regex"in s){if(!(s.$regex instanceof RegExp?s.$regex:new RegExp(s.$regex)).test(String(n)))return!1}if("$fn"in s&&!s.$fn(n))return!1}else if(!ji(n,s))return!1}else if(n!==s)return!1}return!0}function bc(t,i=new Set){if(typeof t!=="object"||t===null||typeof t==="function")return t;let r=[],s=[],n=[],a=[],o=[];for(let l in t){if(l==="$or"||l==="$and"||l==="$not"){o.push(l);continue}let d=t[l];if(i.has(l))r.push(l);else if(d instanceof RegExp||typeof d==="object"&&d!==null&&(("$regex"in d)||("$fn"in d))||typeof d==="function")a.push(l);else if(typeof d==="object"&&d!==null&&(("$gt"in d)||("$lt"in d)||("$gte"in d)||("$lte"in d)||("$ne"in d)||("$in"in d)||("$nin"in d)))n.push(l);else s.push(l)}let c={};for(let l of[...r,...s,...n,...a,...o])c[l]=t[l];return c}var qi=new Set(["string","number","boolean","object","array","date","any"]);function dr(t){if(Array.isArray(t))return"array";if(t instanceof Date)return"date";return typeof t}function aa(t){let i=new Map,r=[];for(let[s,n]of Object.entries(t)){let a;if(typeof n==="string"){if(!qi.has(n))throw new j("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${n}" for field "${s}"`,{field:s,type:n});a={type:n,required:!1,unique:!1}}else if(typeof n==="object"&&n!==null){let{type:o="any",required:c=!1,unique:l=!1,enum:d}=n;if(!qi.has(o))throw new j("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${o}" for field "${s}"`,{field:s,type:o});if(a={type:o,required:c,unique:l,enum:d},l)r.push(s)}else throw new j("ERR_SKALEX_VALIDATION_INVALID_SCHEMA",`Invalid schema definition for field "${s}"`,{field:s});i.set(s,a)}return{fields:i,uniqueFields:r}}function As(t,i,r=!1){let s=[];for(let[n,a]of i){let o=t[n],c=o===void 0||o===null;if(a.required&&c){s.push(`Field "${n}" is required`);continue}if(c)continue;if(a.type!=="any"){let l=dr(o);if(l!==a.type)s.push(`Field "${n}" must be of type "${a.type}", got "${l}"`)}if(a.enum&&!a.enum.includes(o))s.push(`Field "${n}" must be one of [${a.enum.map((l)=>JSON.stringify(l)).join(", ")}], got ${JSON.stringify(o)}`)}if(r){for(let n of Object.keys(t))if(!n.startsWith("_")&&!i.has(n))s.push(`Unknown field "${n}" (strict mode)`)}return s}function vs(t,i){let r={};for(let[s,n]of Object.entries(t)){if(s.startsWith("_")){r[s]=n;continue}if(!i.has(s))continue;let a=i.get(s);if(a.type!=="any"){if(dr(n)!==a.type)continue}if(a.enum&&!a.enum.includes(n))continue;r[s]=n}return r}function Tc(t){let i={};for(let[r,s]of Object.entries(t)){if(r.startsWith("_"))continue;let n=dr(s);i[r]=qi.has(n)?n:"any"}return i}function Oc(t){if(typeof t==="number"){if(t<=0)throw new j("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got ${t}`,{ttl:t});return t*1000}if(typeof t!=="string")throw new j("ERR_SKALEX_VALIDATION_TTL",`Invalid TTL value: ${t}`,{ttl:t});let i=t.match(/^(\d+(?:\.\d+)?)(ms|s|m|h|d)$/);if(!i)throw new j("ERR_SKALEX_VALIDATION_TTL_FORMAT",`Invalid TTL format: "${t}". Use e.g. 300 (seconds), "30m", "24h", "7d"`,{ttl:t});let r=parseFloat(i[1]);if(r<=0)throw new j("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got "${t}"`,{ttl:t});let s=i[2],n=r*{ms:1,s:1000,m:60000,h:3600000,d:86400000}[s];if(!isFinite(n))throw new j("ERR_SKALEX_VALIDATION_TTL",`TTL value "${t}" is too large`,{ttl:t});return n}function Rc(t){return new Date(Date.now()+Oc(t))}function Cc(t,i,r=null){let s=Date.now(),n=0,a=t.length;while(a--){let o=t[a];if(o._expiresAt&&new Date(o._expiresAt).getTime()<=s){if(t.splice(a,1),i.delete(o._id),r)r(o);n++}}return n}function Es(t,i){if(t.length!==i.length)throw new pt("ERR_SKALEX_QUERY_VECTOR_MISMATCH",`Vector dimension mismatch: ${t.length} vs ${i.length}`,{expected:t.length,got:i.length});let r=0,s=0,n=0;for(let o=0;o<t.length;o++)r+=t[o]*i[o],s+=t[o]*t[o],n+=i[o]*i[o];let a=Math.sqrt(s*n);return a===0?0:r/a}function te(t){if(!("_vector"in t))return{...t};let{_vector:i,...r}=t;return r}function Nc(t){return t.length}function $c(t,i){let r=0;for(let s of t){let n=oi(s,i);if(typeof n==="number"&&!isNaN(n))r+=n}return r}function kc(t,i){let r=0,s=0;for(let n of t){let a=oi(n,i);if(typeof a==="number"&&!isNaN(a))r+=a,s++}return s===0?null:r/s}function Dc(t,i){let r=Object.create(null);for(let s of t){let n=String(oi(s,i)??"__null__");if(!r[n])r[n]=[];r[n].push(s)}return r}class oa{constructor(t){this._col=t}get _ctx(){return this._col._ctx}async execute({op:t,beforeHook:i,afterHook:r,hookPayload:s,mutate:n,afterHookPayload:a,save:o,session:c}){let l=this._ctx;await l.ensureConnected(),this._col._txSnapshotIfNeeded();let d=l.txManager,u=d.active&&this._col._activeTxId===d.context?.id,f=u?d.context.id:null,h=this._col._createdInTxId,_=()=>{if(f!==null&&d._abortedIds.has(f))throw new ke("ERR_SKALEX_TX_ABORTED",`Transaction ${f} was aborted. No further mutations allowed.`);if(h!==null&&d._abortedIds.has(h))throw new ke("ERR_SKALEX_TX_ABORTED",`Transaction ${h} was aborted. Collection obtained inside that transaction cannot be used for further mutations.`)};if(u||h!==null)_();if(i)await l.plugins.run(i,s);let{docs:p,prevDocs:g=[]}=await n(_);if(l.persistence.markDirty(l.collections,this._col.name),await this._col._saveIfNeeded(o),this._col._changelogEnabled)for(let m=0;m<p.length;m++)await l.logChange(t,this._col.name,p[m],g[m]??null,c||null);if(!u||!d.defer(()=>l.sessionStats.recordWrite(c)))l.sessionStats.recordWrite(c);for(let m of p)l.emitEvent(this._col.name,{op:t,collection:this._col.name,doc:te(m)});if(r)if(a)await l.runAfterHook(r,a(p));else for(let m of p)await l.runAfterHook(r,{collection:this._col.name,doc:te(m)});return{docs:p,prevDocs:g}}}function Lc(t){let i={};for(let r in t){if(r.startsWith("$"))continue;let s=t[r];if(s&&typeof s==="object"&&!Array.isArray(s)){let n=Object.keys(s);if(n.length===1&&n[0]==="$eq")i[r]=s.$eq}else i[r]=s}return i}var la=new Set(["__proto__","constructor","prototype"]);function ca(t){if(typeof t!=="object"||t===null||Array.isArray(t))return t;let i={};for(let r of Object.keys(t)){if(la.has(r))continue;i[r]=ca(t[r])}return i}class da{constructor(t,i){this.name=t.collectionName,this.database=i,this._ctx=i._buildCollectionContext(),this._store=t,this._pipeline=new oa(this),this._createdInTxId=i._txManager.context?.id??null,this._activeTxId=null}get _data(){return this._store.data}set _data(t){this._store.data=t}get _index(){return this._store.index}get _fieldIndex(){return this._store.fieldIndex||null}get _schema(){return this._store.schema?this._store.schema.fields:null}get _changelogEnabled(){return this._store.changelog===!0}get _softDelete(){return this._store.softDelete===!0}get _versioning(){return this._store.versioning===!0}get _strict(){return this._store.strict===!0}get _onSchemaError(){return this._store.onSchemaError??"throw"}get _defaultTtl(){return this._store.defaultTtl||null}get _defaultEmbed(){return this._store.defaultEmbed||null}get _maxDocs(){return this._store.maxDocs||null}async insertOne(t,i={}){let{save:r,ifNotExists:s,ttl:n,embed:a,session:o}=i;if(s){await this._ctx.ensureConnected();let l=this._findRaw(t);if(l)return te({...l})}let{docs:c}=await this._insertCore([t],{ttl:n,embed:a,session:o,save:r});return te(c[0])}async insertMany(t,i={}){let{save:r,ttl:s,embed:n,session:a}=i,{docs:o}=await this._insertCore(t,{ttl:s,embed:n,session:a,save:r});return o.map(te)}async _insertCore(t,{ttl:i,embed:r,session:s,save:n}){return this._pipeline.execute({op:"insert",beforeHook:null,afterHook:"afterInsert",hookPayload:null,save:n,session:s,mutate:async(a)=>{let o=[],c=new Set;for(let l of t){let d=this._applyValidation(l);await this._ctx.plugins.run("beforeInsert",{collection:this.name,doc:d});let u=await this._buildDoc(d,{ttl:i,embed:r});if(this._index.has(u._id)||c.has(u._id))throw new Ue("ERR_SKALEX_UNIQUE_DUPLICATE_ID",`Duplicate _id "${u._id}" in collection "${this.name}"`,{id:u._id,collection:this.name});c.add(u._id),o.push(u)}if(a(),this._fieldIndex)this._fieldIndex.assertUniqueBatch(o);for(let l of o)this._addToIndex(l);this._data.push(...o);for(let l of o)this._index.set(l._id,l);return this._enforceCapAfterInsert(),{docs:o}}})}async updateOne(t,i,r={}){await this._ctx.ensureConnected();let s=this._findRaw(t);if(!s)return null;let{save:n,session:a}=r,{docs:o}=await this._updateCore([s],t,i,{save:n,session:a});return te(o[0])}async updateMany(t,i,r={}){await this._ctx.ensureConnected();let s=this._findAllRaw(t);if(s.length===0)return[];let{save:n,session:a}=r,{docs:o}=await this._updateCore(s,t,i,{save:n,session:a});return o.map(te)}async _updateCore(t,i,r,{save:s,session:n}){return this._pipeline.execute({op:"update",beforeHook:"beforeUpdate",afterHook:"afterUpdate",hookPayload:{collection:this.name,filter:i,update:r},save:s,session:n,afterHookPayload:(a)=>({collection:this.name,filter:i,update:r,result:a.length===1?a[0]:a}),mutate:async(a)=>{let o=this._changelogEnabled?t.map((u)=>structuredClone(u)):t.map(()=>null),c=t.map((u)=>this._prepareUpdatedDoc(u,r));this._assertUniqueCandidates(t,c),a();let l=new Set(t),d=new Map;for(let u=0;u<this._data.length;u++)if(l.has(this._data[u]))d.set(this._data[u],u);for(let u=0;u<t.length;u++)this._commitUpdatedDoc(t[u],c[u],d);return{docs:c,prevDocs:o}}})}applyUpdate(t,i){for(let r in i){if(la.has(r))continue;if(r==="_id"||r==="createdAt")continue;let s=i[r];if(Array.isArray(s))t[r]=s;else if(typeof s==="object"&&s!==null){let n=Object.keys(s);if(n.some((a)=>a.startsWith("$"))){for(let a of n)if(a==="$inc"&&typeof t[r]==="number")t[r]+=s[a];else if(a==="$push"){if(!Array.isArray(t[r]))t[r]=[];t[r].push(s[a])}}else t[r]=ca(s)}else t[r]=s}if(t.updatedAt=new Date,this._versioning)t._version=(t._version??0)+1;return t}_prepareUpdatedDoc(t,i){let r=structuredClone(t),s=structuredClone(t);if(this.applyUpdate(s,i),!this._schema)return s;let n=As(s,this._schema,this._strict);if(!n.length)return s;switch(this._onSchemaError){case"throw":throw new j("ERR_SKALEX_VALIDATION_UPDATE",`Update validation failed on doc "${t._id}": ${n.join("; ")}`,{id:t._id,errors:n});case"strip":return this._stripCandidateToValid(s,r);default:return this._ctx.logger(`[${this.name}] Update validation warning: ${n.join("; ")}`,"warn"),s}}_stripCandidateToValid(t,i){let r=vs(t,this._schema),s=structuredClone(i);for(let[n,a]of Object.entries(r)){if(n.startsWith("_"))continue;s[n]=a}if(s.updatedAt=t.updatedAt,this._versioning)s._version=t._version;return s}_commitUpdatedDoc(t,i,r){let s=r?r.get(t):this._data.indexOf(t);if(s===void 0||s===-1)throw new We("ERR_SKALEX_PERSISTENCE_DOC_MISSING",`Document "${t._id}" no longer exists in collection "${this.name}"`,{id:t._id,collection:this.name});this._data[s]=i,this._index.set(i._id,i),this._updateInIndex(t,i)}_assertUniqueCandidates(t,i){this._fieldIndex?.assertUniqueCandidates(t,i)}async upsert(t,i,r={}){if(await this._ctx.ensureConnected(),this._findRaw(t))return this.updateOne(t,i,r);return this.insertOne({...Lc(t),...i},r)}async upsertMany(t,i,r={}){await this._ctx.ensureConnected();let{save:s,...n}=r,a=[];for(let o of t)a.push(await this.upsert({[i]:o[i]},o,{...n,save:!1}));return await this._saveIfNeeded(s),a}async restore(t,i={}){if(!this._softDelete)throw new pt("ERR_SKALEX_QUERY_SOFT_DELETE_REQUIRED",`restore() requires softDelete on "${this.name}"`,{collection:this.name});await this._ctx.ensureConnected();let{save:r,session:s}=i,n=this._findRaw(t,{includeDeleted:!0});if(!n||!n._deletedAt)return null;let{docs:a}=await this._pipeline.execute({op:"restore",beforeHook:null,afterHook:null,hookPayload:null,save:r,session:s,mutate:async(o)=>(o(),delete n._deletedAt,n.updatedAt=new Date,this._index.set(n._id,n),{docs:[n]})});return te(a[0])}watch(t,i){if(typeof t==="function")i=t,t=null;if(i)return this._ctx.eventBus.on(this.name,(r)=>{if(!t||ne(r.doc,t))i(r)});return this._watchIterator(t)}_watchIterator(t){let i=[],r=null,s=!1,n=this._ctx.eventBus.on(this.name,(a)=>{if(t&&!ne(a.doc,t))return;if(r){let o=r;r=null,o({value:a,done:!1})}else i.push(a)});return{[Symbol.asyncIterator](){return this},next(){if(i.length>0)return Promise.resolve({value:i.shift(),done:!1});if(s)return Promise.resolve({value:void 0,done:!0});return new Promise((a)=>{r=a})},return(){if(s=!0,n(),r){let a=r;r=null,a({value:void 0,done:!0})}return Promise.resolve({value:void 0,done:!0})}}}async count(t={}){return await this._ctx.ensureConnected(),Nc(this._findAllRaw(t))}async sum(t,i={}){return await this._ctx.ensureConnected(),$c(this._findAllRaw(i),t)}async avg(t,i={}){return await this._ctx.ensureConnected(),kc(this._findAllRaw(i),t)}async groupBy(t,i={}){return await this._ctx.ensureConnected(),Dc(this._findAllRaw(i),t)}async findOne(t,i={}){await this._ctx.ensureConnected();let{populate:r,select:s,includeDeleted:n=!1}=i,a=this._findRaw(t,{includeDeleted:n});if(!a)return null;let o=this._projectDoc(a,s);if(r)await this._populateDoc(o,a,r);return o}async find(t,i={}){await this._ctx.ensureConnected();let r=Date.now(),{populate:s,select:n,sort:a,page:o=1,limit:c,session:l,includeDeleted:d=!1}=i;await this._ctx.plugins.run("beforeFind",{collection:this.name,filter:t,options:i});let u=this._getCandidates(t),f=bc(t,this._fieldIndex?this._fieldIndex.indexedFields:new Set),h=[];for(let p of u){if(this._softDelete&&p._deletedAt&&!d)continue;if(!ne(p,f))continue;let g=this._projectDoc(p,n);if(s)await this._populateDoc(g,p,s);h.push(g)}if(a){let p=Object.keys(a);h.sort((g,m)=>{for(let w of p){let v=a[w];if(g[w]<m[w])return-v;if(g[w]>m[w])return v}return 0})}let _;if(c){let p=h.length,g=Math.ceil(p/c),m=(o-1)*c;h=h.slice(m,m+c),_={page:o,totalDocs:p,totalPages:g}}return this._ctx.queryLog?.record({collection:this.name,op:"find",filter:t,duration:Date.now()-r,resultCount:h.length}),this._ctx.sessionStats.recordRead(l),await this._ctx.plugins.run("afterFind",{collection:this.name,filter:t,options:i,docs:h}),_?{docs:h,..._}:{docs:h}}async search(t,{filter:i,limit:r=10,minScore:s=0,session:n}={}){await this._ctx.ensureConnected();let a=Date.now();await this._ctx.plugins.run("beforeSearch",{collection:this.name,query:t,options:{filter:i,limit:r,minScore:s}});let o=await this._ctx.embed(t),c=i?this._findAllRaw(i):this._data,l=[];for(let h of c){if(!h._vector)continue;let _=Es(o,h._vector);if(_>=s)l.push({doc:h,score:_})}l.sort((h,_)=>_.score-h.score);let d=l.slice(0,r);this._ctx.queryLog?.record({collection:this.name,op:"search",query:t,duration:Date.now()-a,resultCount:d.length}),this._ctx.sessionStats.recordRead(n);let u=d.map((h)=>te(h.doc)),f=d.map((h)=>h.score);return await this._ctx.plugins.run("afterSearch",{collection:this.name,query:t,options:{filter:i,limit:r,minScore:s},docs:u,scores:f}),{docs:u,scores:f}}async similar(t,{limit:i=10,minScore:r=0}={}){await this._ctx.ensureConnected();let s=this._index.get(t);if(!s||!s._vector)return{docs:[],scores:[]};let n=[];for(let o of this._data){if(o._id===t||!o._vector)continue;let c=Es(s._vector,o._vector);if(c>=r)n.push({doc:o,score:c})}n.sort((o,c)=>c.score-o.score);let a=n.slice(0,i);return{docs:a.map((o)=>te(o.doc)),scores:a.map((o)=>o.score)}}async deleteOne(t,i={}){await this._ctx.ensureConnected();let{save:r,session:s}=i;if(this._softDelete){let a=this._findRaw(t);if(!a)return null;let{docs:o}=await this._deleteCore("soft",[a],t,{save:r,session:s});return te(o[0])}let{docs:n}=await this._deleteCore("hard",null,t,{save:r,session:s});if(n.length===0)return null;return te(n[0])}async deleteMany(t,i={}){await this._ctx.ensureConnected();let{save:r,session:s}=i;if(this._softDelete){let a=this._findAllRaw(t);if(a.length===0)return[];let{docs:o}=await this._deleteCore("soft",a,t,{save:r,session:s});return o.map(te)}let{docs:n}=await this._deleteCore("hardMany",null,t,{save:r,session:s});return n.map(te)}async _deleteCore(t,i,r,{save:s,session:n}){return this._pipeline.execute({op:"delete",beforeHook:"beforeDelete",afterHook:"afterDelete",hookPayload:{collection:this.name,filter:r},save:s,session:n,afterHookPayload:(a)=>({collection:this.name,filter:r,result:a.length===1?a[0]:a}),mutate:async(a)=>{if(a(),t==="soft"){let l=new Date;for(let d of i)d._deletedAt=l,d.updatedAt=l,this._index.set(d._id,d);return{docs:i}}if(t==="hard"){let l=this._findIndex(r);if(l===-1)return{docs:[]};let d=this._data.splice(l,1)[0];return this._index.delete(d._id),this._removeFromIndex(d),{docs:[d]}}let o=[],c=[];for(let l of this._data)if(ne(l,r))o.push(l),this._index.delete(l._id),this._removeFromIndex(l);else c.push(l);return this._data=c,{docs:o}}})}async export(t={},i={}){let{dir:r,name:s,format:n="json"}=i;try{let a=this._data.filter((u)=>ne(u,t));if(a.length===0)throw new pt("ERR_SKALEX_QUERY_EXPORT_EMPTY",`export(): no documents matched the filter in "${this.name}"`,{collection:this.name});let o;if(n==="json")o=JSON.stringify(a,null,2);else{let u=(_)=>{if(_==null)return"";let p=typeof _==="object"?JSON.stringify(_):String(_);return p.includes(",")||p.includes('"')||p.includes(`
|
|
81
81
|
`)||p.includes("\r")?`"${p.replace(/"/g,'""')}"`:p},f=Object.keys(a[0]).map(u).join(","),h=a.map((_)=>Object.values(_).map(u).join(","));o=[f,...h].join(`
|
|
82
|
-
`)}if(typeof this._ctx.fs.writeRaw!=="function")throw new Oe("ERR_SKALEX_ADAPTER_NO_RAW_WRITE","export() requires a file-system adapter (FsAdapter). The current adapter does not support raw file writes.");let c=r||`${this._ctx.dataDirectory}/exports`,l=`${s||this.name}.${n}`,d=this._ctx.fs.join(c,l);this._ctx.fs.ensureDir(c),await this._ctx.fs.writeRaw(d,o)}catch(a){throw this._ctx.logger(`Error exporting "${this.name}": ${a.message}`,"error"),a}}_txSnapshotIfNeeded(){let t=this._ctx.txManager;if(!t.active)return;if(this._activeTxId!==t.context?.id)return;t.snapshotIfNeeded(this.name,this._store,(i)=>this._ctx.snapshotCollection(i))}async _saveIfNeeded(t){let i=this._ctx.txManager;if(i.active&&this._activeTxId===i.context?.id)return;if(t??this._ctx.autoSave)await this._ctx.saveCollection(this.name)}_applyValidation(t){if(!this._schema)return t;let i=ws(t,this._schema,this._strict);if(!i.length)return t;switch(this._onSchemaError){case"warn":return this._ctx.logger(`[${this.name}] Validation warning: ${i.join("; ")}`,"warn"),t;case"strip":return As(t,this._schema);default:throw new j("ERR_SKALEX_VALIDATION_FAILED",`Validation failed: ${i.join("; ")}`,{errors:i})}}_enforceCapAfterInsert(){let t=this._maxDocs;if(!t||this._data.length<=t)return;let i=this._data.splice(0,this._data.length-t);for(let r of i)this._index.delete(r._id),this._removeFromIndex(r)}_findRaw(t,{includeDeleted:i=!1}={}){if(typeof t==="function"){for(let r of this._data){if(this._softDelete&&r._deletedAt&&!i)continue;if(t(r))return r}return null}if(t._id){let r=this._index.get(t._id)||null;if(!r)return null;if(this._softDelete&&r._deletedAt&&!i)return null;if(Object.keys(t).length>1)return ne(r,t)?r:null;return r}if(this._fieldIndex)for(let r in t){if(r==="$or"||r==="$and"||r==="$not")continue;let s=t[r];if(typeof s!=="object"||s===null){let n=this._fieldIndex._lookupIterable(r,s);if(n!==null){for(let a of n){if(this._softDelete&&a._deletedAt&&!i)continue;if(ne(a,t))return a}return null}}}for(let r of this._data){if(this._softDelete&&r._deletedAt&&!i)continue;if(ne(r,t))return r}return null}_findAllRaw(t,{includeDeleted:i=!1}={}){if(t&&typeof t!=="function"&&t._id){let s=this._index.get(t._id);if(!s)return[];if(this._softDelete&&s._deletedAt&&!i)return[];return ne(s,t)?[s]:[]}let r=[];for(let s of this._getCandidates(t)){if(this._softDelete&&s._deletedAt&&!i)continue;if(ne(s,t))r.push(s)}return r}_getCandidates(t){if(!this._fieldIndex)return this._data;if(this._fieldIndex._compoundIndexes.size>0){let i={};for(let r in t){if(r==="$or"||r==="$and"||r==="$not")continue;let s=t[r];if(typeof s!=="object"||s===null)i[r]=s}if(Object.keys(i).length>=2){let r=this._fieldIndex.lookupCompound(i);if(r!==null)return r}}for(let i in t){if(i==="$or"||i==="$and"||i==="$not")continue;let r=t[i];if(typeof r!=="object"||r===null){let s=this._fieldIndex._lookupIterable(i,r);if(s!==null)return s}}return this._data}_findIndex(t){for(let i=0;i<this._data.length;i++)if(ne(this._data[i],t))return i;return-1}_addToIndex(t){if(this._fieldIndex)this._fieldIndex.add(t)}_removeFromIndex(t){if(this._fieldIndex)this._fieldIndex.remove(t)}_updateInIndex(t,i){if(this._fieldIndex)this._fieldIndex.update(t,i)}async _buildDoc(t,{ttl:i,embed:r}={}){let s={...t,_id:t._id??(this._ctx.idGenerator??Sc)(),createdAt:new Date,updatedAt:new Date},n=i??this._defaultTtl;if(n)s._expiresAt=Oc(n);let a=r??this._defaultEmbed;if(a){let o=typeof a==="function"?a(s):s[a];s._vector=await this._ctx.embed(String(o))}if(this._versioning)s._version=1;return s}_projectDoc(t,i){if(i){let s={};for(let n of i){if(n==="_vector")continue;s[n]=t[n]}return s}let r={...t};return delete r._vector,r}async _populateDoc(t,i,r){for(let s of r){let n=await this._ctx.getCollection(s).findOne({_id:i[s]});if(n)t[s]=n}}}class ur{async read(t){throw Error("StorageAdapter.read() not implemented")}async write(t,i){throw Error("StorageAdapter.write() not implemented")}async delete(t){throw Error("StorageAdapter.delete() not implemented")}async list(){throw Error("StorageAdapter.list() not implemented")}async writeAll(t){for(let{name:i,data:r}of t)await this.write(i,r)}}class da extends ur{constructor({dir:t,format:i="gz"}){super();this.dir=at.resolve(t),this.format=i,this._ensureDir(this.dir)}_ensureDir(t){if(!Y.existsSync(t))Y.mkdirSync(t,{recursive:!0})}_filePath(t){return at.join(this.dir,`${t}.${this.format}`)}async read(t){let i=this._filePath(t);try{let r=await Y.promises.readFile(i);if(this.format==="gz")r=bi.inflateSync(r);return r.toString("utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}}async write(t,i){let r=this._filePath(t),s=at.join(this.dir,`${t}_${globalThis.crypto.randomUUID()}.tmp.${this.format}`);if(this.format==="gz"){let n=bi.deflateSync(i);await Y.promises.writeFile(s,n)}else await Y.promises.writeFile(s,i,"utf8");await Y.promises.rename(s,r)}async writeAll(t){let i=[];try{for(let{name:r,data:s}of t){let n=this._filePath(r),a=at.join(this.dir,`${r}_${globalThis.crypto.randomUUID()}.tmp.${this.format}`);if(this.format==="gz"){let o=bi.deflateSync(s);await Y.promises.writeFile(a,o)}else await Y.promises.writeFile(a,s,"utf8");i.push({tmp:a,fp:n})}for(let{tmp:r,fp:s}of i)await Y.promises.rename(r,s)}catch(r){for(let{tmp:s}of i)try{await Y.promises.unlink(s)}catch{}throw r}}async delete(t){let i=this._filePath(t);try{await Y.promises.unlink(i)}catch(r){if(r.code!=="ENOENT")throw r}}async list(){try{let t=await Y.promises.readdir(this.dir),i=`.${this.format}`;return t.filter((r)=>r.endsWith(i)&&!r.includes(".tmp.")).map((r)=>r.slice(0,-i.length))}catch(t){if(t.code==="ENOENT")return[];throw t}}join(...t){return at.join(...t)}ensureDir(t){this._ensureDir(t)}async writeRaw(t,i){this._ensureDir(at.dirname(t)),await Y.promises.writeFile(t,i,"utf8")}async readRaw(t){return Y.promises.readFile(at.resolve(t),"utf8")}}class ua{constructor(){this._migrations=[]}add(t){let{version:i,up:r}=t;if(typeof i!=="number"||i<1)throw new j("ERR_SKALEX_VALIDATION_MIGRATION",`Migration version must be a positive integer, got ${i}`,{version:i});if(typeof r!=="function")throw new j("ERR_SKALEX_VALIDATION_MIGRATION",`Migration version ${i} must have an "up" function`,{version:i});if(this._migrations.some((s)=>s.version===i))throw new j("ERR_SKALEX_VALIDATION_MIGRATION_DUPLICATE",`Migration version ${i} is already registered`,{version:i});this._migrations.push({...t}),this._migrations.sort((s,n)=>s.version-n.version)}async run(t,i=[]){let r=new Set(i),s=this._migrations.filter((n)=>!r.has(n.version));for(let n of s){let a=t(n.version);await n.up(a),r.add(n.version)}return[...r].sort((n,a)=>n-a)}status(t=[]){let i=new Set(t),r=this._migrations.map((s)=>s.version).filter((s)=>!i.has(s));return{current:t.length?Math.max(...t):0,applied:[...i].sort((s,n)=>s-n),pending:r}}}var Es={[Symbol.iterator](){return{next(){return{done:!0}}}},size:0};function xs(t){return{[Symbol.iterator](){return t[Symbol.iterator]()},get size(){return t.size}}}function ki(t){return t.map((i)=>{if(i===null||i===void 0)return"\x00";if(typeof i==="boolean")return i?"\x01T":"\x01F";if(typeof i==="number")return`\x02${i}`;return`\x03${String(i)}`}).join("\x1F")}class si{constructor(t=[],i=[]){this._fields=new Set,this._compoundFields=[];for(let r of t)if(Array.isArray(r)){for(let s of r)this._validateFieldName(s);this._compoundFields.push(r)}else this._validateFieldName(r),this._fields.add(r);for(let r of i)this._validateFieldName(r);this._uniqueFields=new Set(i),this._indexedFields=new Set([...this._fields,...this._uniqueFields]),this._fieldIndexes=new Map,this._uniqueIndexes=new Map;for(let r of this._fields)this._fieldIndexes.set(r,new Map);for(let r of this._uniqueFields)if(this._uniqueIndexes.set(r,new Map),!this._fieldIndexes.has(r))this._fieldIndexes.set(r,new Map);this._compoundIndexes=new Map;for(let r of this._compoundFields)this._compoundIndexes.set(r.join("\x00"),{fields:r,map:new Map})}get indexedFields(){return this._indexedFields}buildFromData(t){for(let[,i]of this._fieldIndexes)i.clear();for(let[,i]of this._uniqueIndexes)i.clear();for(let[,i]of this._compoundIndexes)i.map.clear();for(let i of t)this._indexDoc(i)}add(t){this._checkUnique(t,null),this._indexDoc(t)}remove(t){for(let[i,r]of this._fieldIndexes){let s=t[i];if(s!==void 0){let n=r.get(s);if(n){if(n.delete(t),n.size===0)r.delete(s)}}}for(let[i,r]of this._uniqueIndexes){let s=t[i];if(s!==void 0)r.delete(s)}for(let[,i]of this._compoundIndexes){let r=ki(i.fields.map((n)=>t[n])),s=i.map.get(r);if(s){if(s.delete(t),s.size===0)i.map.delete(r)}}}update(t,i){this._checkUnique(i,t),this.remove(t);try{this._indexDoc(i)}catch(r){try{this._indexDoc(t)}catch{}throw r}}lookup(t,i){let r=this._fieldIndexes.get(t);if(!r)return null;let s=r.get(i);return s?[...s]:[]}_lookupIterable(t,i){let r=this._fieldIndexes.get(t);if(!r)return null;let s=r.get(i);return s?xs(s):Es}lookupCompound(t){let i=Object.keys(t).sort();for(let[,r]of this._compoundIndexes){let s=[...r.fields].sort();if(s.length!==i.length)continue;if(s.every((n,a)=>n===i[a])){let n=ki(r.fields.map((o)=>t[o])),a=r.map.get(n);return a?xs(a):Es}}return null}isUniqueTaken(t,i){let r=this._uniqueIndexes.get(t);if(!r)return!1;return r.has(i)}assertUniqueCandidates(t,i){if(this._uniqueFields.size===0)return;let r=new Set(t.map((s)=>s._id));for(let s of this._uniqueFields){let n=new Set,a=this._uniqueIndexes.get(s);if(a){for(let[c,l]of a.entries())if(!r.has(l._id))n.add(c)}let o=new Map;for(let c=0;c<i.length;c++){let l=i[c][s];if(l===void 0)continue;if(n.has(l))throw new Ue("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${s}" value "${l}" already exists`,{field:s,value:l});let d=o.get(l);if(d&&d!==t[c]._id)throw new Ue("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${s}" value "${l}" already exists`,{field:s,value:l});o.set(l,t[c]._id)}}}assertUniqueBatch(t){if(this._uniqueFields.size===0)return;for(let i of this._uniqueFields){let r=this._uniqueIndexes.get(i),s=new Set;for(let n of t){let a=n[i];if(a===void 0)continue;if(r&&r.has(a))throw new Ue("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${i}" value "${a}" already exists`,{field:i,value:a});if(s.has(a))throw new Ue("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: duplicate "${i}" value "${a}" within batch`,{field:i,value:a});s.add(a)}}}_validateFieldName(t){if(t.includes("."))throw new j("ERR_SKALEX_VALIDATION_INDEX_DOT_PATH",`Index fields cannot use dot-notation: "${t}". Use a flat field name.`,{field:t})}_indexDoc(t){for(let[i,r]of this._fieldIndexes){let s=t[i];if(s!==void 0){if(!r.has(s))r.set(s,new Set);r.get(s).add(t)}}for(let[i,r]of this._uniqueIndexes){let s=t[i];if(s!==void 0)r.set(s,t)}for(let[,i]of this._compoundIndexes){for(let s of i.fields){let n=t[s];if(n!==void 0&&n!==null&&typeof n==="object")throw new j("ERR_SKALEX_VALIDATION_COMPOUND_INDEX",`Compound index field "${s}" must be a scalar value (string, number, or boolean), got ${Array.isArray(n)?"array":typeof n}`,{field:s})}let r=ki(i.fields.map((s)=>t[s]));if(!i.map.has(r))i.map.set(r,new Set);i.map.get(r).add(t)}}_checkUnique(t,i){for(let r of this._uniqueFields){let s=t[r];if(s===void 0)continue;let n=this._uniqueIndexes.get(r);if(!n)continue;let a=n.get(s);if(a&&a._id!==i?._id)throw new Ue("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${r}" value "${s}" already exists`,{field:r,value:s})}}}var Yt="_flush",Qt="migrations";class ha{constructor({adapter:t,serializer:i,deserializer:r,logger:s,debug:n=!1,lenientLoad:a=!1}){this._adapter=t,this._serializer=i,this._deserializer=r,this._logger=s,this._debug=n,this._lenientLoad=a,this._saveLock=Promise.resolve()}_withSaveLock(t){let i=this._saveLock.then(t);return this._saveLock=i.catch(()=>{}),i}async loadAll(t,{parseSchema:i,buildIndex:r,IndexEngine:s}){try{let n=await this._adapter.list();await Promise.all(n.map(async(a)=>{try{let o=await this._adapter.read(a);if(!o)return;let c=this._deserializer(o),{collectionName:l,data:d}=c;if(!l)return;let u=t[l],f=u?.rawSchema??c.rawSchema??null,h=u?.schema??(f?i(f):null),_=u?.changelog??c.changelog??!1,p=u?.softDelete??c.softDelete??!1,g=u?.versioning??c.versioning??!1,m=u?.strict??c.strict??!1,w=u?.onSchemaError??c.onSchemaError??"throw",v=u?.defaultTtl??c.defaultTtl??null,q=u?.defaultEmbed??c.defaultEmbed??null,E=u?.maxDocs??c.maxDocs??null,A=u?u.fieldIndex:null;if(!A&&h?.uniqueFields?.length)A=new s([],h.uniqueFields);let tt=r(d,"_id");if(A)A.buildFromData(d);t[l]={collectionName:l,data:d,index:tt,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:h,rawSchema:f,fieldIndex:A,changelog:_,softDelete:p,versioning:g,strict:m,onSchemaError:w,defaultTtl:v,defaultEmbed:q,maxDocs:E}}catch(o){if(o.code==="ENOENT")return;if(this._lenientLoad){this._logger(`WARNING: Could not load collection "${a}": ${o.message}. Collection will be empty.`,"error");return}throw new We("ERR_SKALEX_PERSISTENCE_CORRUPT",`Failed to load collection "${a}": ${o.message}`,{collection:a})}})),this._detectIncompleteFlush(t),await this._cleanOrphanTempFiles()}catch(n){if(n.code!=="ENOENT")throw this._logger(`Error loading data: ${n}`,"error"),n}}async save(t,i){if(i)await this._saveOne(t,i);else await Promise.all(Object.keys(t).map((r)=>this._saveOne(t,r)))}async saveDirty(t){let i=Object.keys(t).filter((r)=>t[r]._dirty);if(i.length===0)return;await Promise.all(i.map((r)=>this._saveOne(t,r)))}saveAtomic(t,i){return this._withSaveLock(async()=>{if(i.length===0)return;this._writeFlushSentinel(t,i);let r=new Set(i);r.add("_meta");let s=[...r].filter((n)=>t[n]).map((n)=>({name:n,data:this._serializeCollection(t[n])}));try{await this._adapter.writeAll(s)}catch(n){throw new We("ERR_SKALEX_PERSISTENCE_FLUSH_FAILED",`Batch save failed during writeAll: ${n.message}`,{collections:i})}for(let n of i)if(t[n])t[n]._dirty=!1;try{this._clearFlushSentinel(t),await this._adapter.write("_meta",this._serializeCollection(t._meta))}catch(n){this._logger(`WARNING: Batch data committed but sentinel clear failed: ${n.message}. Next load will report an incomplete flush (false positive).`,"error")}})}markDirty(t,i){let r=t[i];if(r)r._dirty=!0}_serializeCollection(t){let i={collectionName:t.collectionName,data:t.data};if(t.rawSchema)i.rawSchema=t.rawSchema;if(t.changelog)i.changelog=t.changelog;if(t.softDelete)i.softDelete=t.softDelete;if(t.versioning)i.versioning=t.versioning;if(t.strict)i.strict=t.strict;if(t.onSchemaError!=="throw")i.onSchemaError=t.onSchemaError;if(t.defaultTtl)i.defaultTtl=t.defaultTtl;if(t.defaultEmbed)i.defaultEmbed=t.defaultEmbed;if(t.maxDocs)i.maxDocs=t.maxDocs;return this._serializer(i)}async _saveOne(t,i){let r=t[i];if(!r)return;if(r.isSaving)return r._pendingSave=!0,new Promise((s,n)=>{(r._saveWaiters??=[]).push({resolve:s,reject:n})});r.isSaving=!0,r._pendingSave=!1;try{await this._writeCollection(i,r);while(r._pendingSave)r._pendingSave=!1,await this._writeCollection(i,r);this._resolveSaveWaiters(r)}catch(s){throw this._rejectSaveWaiters(r,s),s}finally{r.isSaving=!1}}async _writeCollection(t,i){try{await this._adapter.write(t,this._serializeCollection(i)),i._dirty=!1}catch(r){throw this._logger(`Error saving "${t}": ${r.message}`,"error"),r}}_resolveSaveWaiters(t){let i=t._saveWaiters?.splice(0)??[];for(let r of i)r.resolve()}_rejectSaveWaiters(t,i){let r=t._saveWaiters?.splice(0)??[];for(let s of r)s.reject(i)}_writeFlushSentinel(t,i){let r=this._getOrCreateMeta(t);r[Yt]={startedAt:new Date().toISOString(),collections:i,completedAt:null}}_clearFlushSentinel(t){let i=this._getOrCreateMeta(t);if(i[Yt])i[Yt].completedAt=new Date().toISOString()}_detectIncompleteFlush(t){let i=t._meta;if(!i)return;let r=i.index.get(Qt);if(!r)return;let s=r[Yt];if(!s)return;if(s.startedAt&&!s.completedAt)this._logger(`WARNING: Incomplete flush detected (started ${s.startedAt}, collections: ${s.collections?.join(", ")}). Data may be inconsistent.`,"error")}async _cleanOrphanTempFiles(){if(typeof this._adapter.join!=="function")return;if(typeof this._adapter.list!=="function")return;try{let t=await import("fs"),i=await import("path"),r=this._adapter.dir;if(!r)return;let s=(await t.default.promises.readdir(r)).filter((n)=>n.includes(".tmp."));for(let n of s){let a=i.default.join(r,n);try{await t.default.promises.unlink(a),this._log(`Cleaned orphan temp file: ${n}`)}catch{}}}catch{}}_getOrCreateMeta(t){if(!t._meta)t._meta={collectionName:"_meta",data:[],index:new Map,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:null,rawSchema:null,fieldIndex:null,changelog:!1,softDelete:!1,versioning:!1,strict:!1,onSchemaError:"throw",defaultTtl:null,defaultEmbed:null,maxDocs:null};let i=t._meta,r=i.index.get(Qt);if(!r)r={_id:Qt},i.data.push(r),i.index.set(Qt,r);return r}_log(t){if(this._debug)this._logger(t,"info")}}var Lc=0;class fa{constructor(){this._txLock=Promise.resolve(),this._ctx=null,this._abortedIds=new Set}get active(){return this._ctx!==null&&!this._ctx.aborted}get context(){return this._ctx}async run(t,i,{timeout:r=0}={}){let s=async()=>{await i._ensureConnected();let a=new Set(Object.keys(i.collections)),o={id:++Lc,startedAt:Date.now(),aborted:!1,preExisting:a,touchedCollections:new Set,snapshots:new Map,deferredEffects:[],timeout:r};this._ctx=o;let c=null,l=r>0?new Promise((f,h)=>{c=setTimeout(()=>{o.aborted=!0,h(new $e("ERR_SKALEX_TX_TIMEOUT",`Transaction ${o.id} timed out after ${r}ms`))},r)}):null,d=this,u=new Proxy(i,{get(f,h){if(h==="_txId")return o.id;if(o!==d._ctx)throw new $e("ERR_SKALEX_TX_STALE_PROXY",`Transaction ${o.id} has ended. This proxy is no longer usable.`);if(h==="collections")throw new $e("ERR_SKALEX_TX_DIRECT_ACCESS","Direct access to db.collections inside transaction() is not covered by rollback. Use the collection API (db.useCollection) instead.");if(h==="useCollection")return(p)=>{let g=f.useCollection(p);return g._activeTxId=o.id,g};let _=Reflect.get(f,h);return typeof _==="function"?_.bind(f):_}});try{let f=t(u),h=l?await Promise.race([f,l]):await f;if(o.aborted)throw new $e("ERR_SKALEX_TX_ABORTED",`Transaction ${o.id} was aborted`);let _=[...o.touchedCollections];if(_.length>0)await i._persistence.saveAtomic(i.collections,_);for(let p of o.deferredEffects)await p();return h}catch(f){for(let[h,_]of o.snapshots)if(o.preExisting.has(h)){if(i._applySnapshot(h,_),i.collections[h])i.collections[h]._dirty=_._dirty}for(let h in i.collections)if(!o.preExisting.has(h))delete i.collections[h],delete i._collectionInstances[h];throw f}finally{if(c)clearTimeout(c);if(o.aborted)this._abortedIds.add(o.id);this._ctx=null;for(let f in i._collectionInstances){let h=i._collectionInstances[f];if(h._createdInTxId===o.id)h._createdInTxId=null;if(h._activeTxId===o.id)h._activeTxId=null}}},n=this._txLock.then(s);return this._txLock=n.catch(()=>{}),n}snapshotIfNeeded(t,i,r){let s=this._ctx;if(!s)return;if(this._assertCtxNotAborted(s),!s.snapshots.has(t)){let n=r(i);n._dirty=i._dirty??!1,s.snapshots.set(t,n)}s.touchedCollections.add(t)}assertNotAborted(){let t=this._ctx;if(t)this._assertCtxNotAborted(t)}_assertCtxNotAborted(t){if(t.aborted)throw new $e("ERR_SKALEX_TX_ABORTED",`Transaction ${t.id} was aborted. No further mutations allowed.`)}defer(t){if(this._ctx)return this._ctx.deferredEffects.push(t),!0;return!1}}class _a{constructor(t){this._CollectionClass=t,this.stores={},this._instances={}}get(t,i){if(this._instances[t])return this._instances[t];if(!this.stores[t])this.createStore(t);let r=new this._CollectionClass(this.stores[t],i);return this._instances[t]=r,r}create(t,i={},r){this.createStore(t,i);let s=new this._CollectionClass(this.stores[t],r);return this._instances[t]=s,s}createStore(t,{schema:i,indexes:r=[],changelog:s=!1,softDelete:n=!1,versioning:a=!1,strict:o=!1,onSchemaError:c="throw",defaultTtl:l=null,defaultEmbed:d=null,maxDocs:u=null}={}){let f=null,h=null;if(i){f=na(i);let _=f.uniqueFields;if(r.length||_.length)h=new si(r,_)}else if(r.length)h=new si(r,[]);this.stores[t]={collectionName:t,data:[],index:new Map,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:f,rawSchema:i||null,fieldIndex:h,changelog:s,softDelete:n,versioning:a,strict:o,onSchemaError:c,defaultTtl:l,defaultEmbed:d,maxDocs:u}}rename(t,i){if(!this.stores[t])throw new We("ERR_SKALEX_PERSISTENCE_COLLECTION_NOT_FOUND",`Collection "${t}" not found`,{collection:t});if(this.stores[i])throw new We("ERR_SKALEX_PERSISTENCE_COLLECTION_EXISTS",`Collection "${i}" already exists`,{collection:i});let r=this.stores[t];if(r.collectionName=i,this.stores[i]=r,delete this.stores[t],this._instances[t]){let s=this._instances[t];s.name=i,this._instances[i]=s,delete this._instances[t]}}buildIndex(t,i){let r=new Map;for(let s of t)r.set(s[i],s);return r}inspect(t){if(t){let r=this.stores[t];if(!r)return null;return{name:t,count:r.data.length,schema:r.schema?Object.fromEntries(r.schema.fields):null,indexes:r.fieldIndex?[...r.fieldIndex.indexedFields]:[],softDelete:r.softDelete??!1,versioning:r.versioning??!1,strict:r.strict??!1,onSchemaError:r.onSchemaError??"throw",maxDocs:r.maxDocs??null}}let i={};for(let r in this.stores)i[r]=this.inspect(r);return i}dump(){let t={};for(let i in this.stores)if(!i.startsWith("_"))t[i]=structuredClone(this.stores[i].data);return t}schema(t){let i=this.stores[t];if(!i)return null;if(i.schema)return Object.fromEntries([...i.schema.fields.entries()].map(([r,s])=>[r,s.type]));if(i.data.length>0)return bc(i.data[0]);return null}stats(t){let i=(r)=>{let s=this.stores[r];if(!s)return null;let n=s.data.length,a=0;for(let o of s.data)try{a+=JSON.stringify(o).length}catch(c){}return{collection:r,count:n,estimatedSize:a,avgDocSize:n>0?Math.round(a/n):0}};if(t)return i(t);return Object.keys(this.stores).map(i)}clear(){this.stores={},this._instances={}}}class hr{async embed(t){throw Error("EmbeddingAdapter.embed() not implemented")}}var xe=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class pa extends hr{constructor({apiKey:t=xe("OPENAI_API_KEY"),model:i=xe("OPENAI_EMBED_MODEL")??"text-embedding-3-small",baseUrl:r=xe("OPENAI_EMBED_BASE_URL")??"https://api.openai.com/v1/embeddings",dimensions:s=xe("OPENAI_EMBED_DIMENSIONS")!=null?Number(xe("OPENAI_EMBED_DIMENSIONS")):void 0,organization:n=xe("OPENAI_ORGANIZATION")??void 0,timeout:a=xe("OPENAI_EMBED_TIMEOUT")!=null?Number(xe("OPENAI_EMBED_TIMEOUT")):void 0,retries:o=Number(xe("OPENAI_EMBED_RETRIES")??0),retryDelay:c=Number(xe("OPENAI_EMBED_RETRY_DELAY")??1000),headers:l={},fetch:d=globalThis.fetch}={}){super();if(!t)throw Error("OpenAIEmbeddingAdapter requires an apiKey");this.apiKey=t,this.model=i,this.baseUrl=r,this.dimensions=s,this.organization=n,this.timeout=a,this.retries=o,this.retryDelay=c,this.headers=l,this._fetch=d}async embed(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,...this.organization&&{"OpenAI-Organization":this.organization},...this.headers},body:JSON.stringify({input:t,model:this.model,...this.dimensions!==void 0&&{dimensions:this.dimensions}}),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`OpenAI embedding API error ${a.status}: ${o}`)}return(await a.json()).data[0].embedding}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}var xt=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class ga extends hr{constructor({model:t=xt("OLLAMA_EMBED_MODEL")??"nomic-embed-text",host:i=xt("OLLAMA_HOST")??"http://localhost:11434",timeout:r=xt("OLLAMA_EMBED_TIMEOUT")!=null?Number(xt("OLLAMA_EMBED_TIMEOUT")):void 0,retries:s=Number(xt("OLLAMA_EMBED_RETRIES")??0),retryDelay:n=Number(xt("OLLAMA_EMBED_RETRY_DELAY")??1000),headers:a={},fetch:o=globalThis.fetch}={}){super();this.model=t,this.host=i,this.timeout=r,this.retries=s,this.retryDelay=n,this.headers=a,this._fetch=o}async embed(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(`${this.host}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json",...this.headers},body:JSON.stringify({model:this.model,prompt:t}),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`Ollama embedding API error ${a.status}: ${o}`)}return(await a.json()).embedding}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}class pi{async generate(t,i){throw Error("LLMAdapter.generate() not implemented")}async summarize(t){throw Error("LLMAdapter.summarize() not implemented")}}var fr=`You are a database query assistant. Convert the user's natural language request into a JSON filter object for a document database.
|
|
82
|
+
`)}if(typeof this._ctx.fs.writeRaw!=="function")throw new Re("ERR_SKALEX_ADAPTER_NO_RAW_WRITE","export() requires a file-system adapter (FsAdapter). The current adapter does not support raw file writes.");let c=r||`${this._ctx.dataDirectory}/exports`,l=`${s||this.name}.${n}`,d=this._ctx.fs.join(c,l);this._ctx.fs.ensureDir(c),await this._ctx.fs.writeRaw(d,o)}catch(a){throw this._ctx.logger(`Error exporting "${this.name}": ${a.message}`,"error"),a}}_txSnapshotIfNeeded(){let t=this._ctx.txManager;if(!t.active)return;if(this._activeTxId!==t.context?.id)return;t.snapshotIfNeeded(this.name,this._store,(i)=>this._ctx.snapshotCollection(i))}async _saveIfNeeded(t){let i=this._ctx.txManager;if(i.active&&this._activeTxId===i.context?.id)return;if(t??this._ctx.autoSave)await this._ctx.saveCollection(this.name)}_applyValidation(t){if(!this._schema)return t;let i=As(t,this._schema,this._strict);if(!i.length)return t;switch(this._onSchemaError){case"warn":return this._ctx.logger(`[${this.name}] Validation warning: ${i.join("; ")}`,"warn"),t;case"strip":return vs(t,this._schema);default:throw new j("ERR_SKALEX_VALIDATION_FAILED",`Validation failed: ${i.join("; ")}`,{errors:i})}}_enforceCapAfterInsert(){let t=this._maxDocs;if(!t||this._data.length<=t)return;let i=this._data.splice(0,this._data.length-t);for(let r of i)this._index.delete(r._id),this._removeFromIndex(r)}_findRaw(t,{includeDeleted:i=!1}={}){if(typeof t==="function"){for(let r of this._data){if(this._softDelete&&r._deletedAt&&!i)continue;if(t(r))return r}return null}if(t._id){let r=this._index.get(t._id)||null;if(!r)return null;if(this._softDelete&&r._deletedAt&&!i)return null;if(Object.keys(t).length>1)return ne(r,t)?r:null;return r}if(this._fieldIndex)for(let r in t){if(r==="$or"||r==="$and"||r==="$not")continue;let s=t[r];if(typeof s!=="object"||s===null){let n=this._fieldIndex._lookupIterable(r,s);if(n!==null){for(let a of n){if(this._softDelete&&a._deletedAt&&!i)continue;if(ne(a,t))return a}return null}}}for(let r of this._data){if(this._softDelete&&r._deletedAt&&!i)continue;if(ne(r,t))return r}return null}_findAllRaw(t,{includeDeleted:i=!1}={}){if(t&&typeof t!=="function"&&t._id){let s=this._index.get(t._id);if(!s)return[];if(this._softDelete&&s._deletedAt&&!i)return[];return ne(s,t)?[s]:[]}let r=[];for(let s of this._getCandidates(t)){if(this._softDelete&&s._deletedAt&&!i)continue;if(ne(s,t))r.push(s)}return r}_getCandidates(t){if(!this._fieldIndex)return this._data;if(this._fieldIndex._compoundIndexes.size>0){let i={};for(let r in t){if(r==="$or"||r==="$and"||r==="$not")continue;let s=t[r];if(typeof s!=="object"||s===null)i[r]=s}if(Object.keys(i).length>=2){let r=this._fieldIndex.lookupCompound(i);if(r!==null)return r}}for(let i in t){if(i==="$or"||i==="$and"||i==="$not")continue;let r=t[i];if(typeof r!=="object"||r===null){let s=this._fieldIndex._lookupIterable(i,r);if(s!==null)return s}}return this._data}_findIndex(t){for(let i=0;i<this._data.length;i++)if(ne(this._data[i],t))return i;return-1}_addToIndex(t){if(this._fieldIndex)this._fieldIndex.add(t)}_removeFromIndex(t){if(this._fieldIndex)this._fieldIndex.remove(t)}_updateInIndex(t,i){if(this._fieldIndex)this._fieldIndex.update(t,i)}async _buildDoc(t,{ttl:i,embed:r}={}){let s={...t,_id:t._id??(this._ctx.idGenerator??Ic)(),createdAt:new Date,updatedAt:new Date},n=i??this._defaultTtl;if(n)s._expiresAt=Rc(n);let a=r??this._defaultEmbed;if(a){let o=typeof a==="function"?a(s):s[a];s._vector=await this._ctx.embed(String(o))}if(this._versioning)s._version=1;return s}_projectDoc(t,i){if(i){let s={};for(let n of i){if(n==="_vector")continue;s[n]=t[n]}return s}let r={...t};return delete r._vector,r}async _populateDoc(t,i,r){for(let s of r){let n=await this._ctx.getCollection(s).findOne({_id:i[s]});if(n)t[s]=n}}}class ur{async read(t){throw Error("StorageAdapter.read() not implemented")}async write(t,i){throw Error("StorageAdapter.write() not implemented")}async delete(t){throw Error("StorageAdapter.delete() not implemented")}async list(){throw Error("StorageAdapter.list() not implemented")}async writeAll(t){for(let{name:i,data:r}of t)await this.write(i,r)}}class ua extends ur{constructor({dir:t,format:i="gz"}){super();this.dir=nt.resolve(t),this.format=i,this._ensureDir(this.dir)}_ensureDir(t){if(!Y.existsSync(t))Y.mkdirSync(t,{recursive:!0})}_filePath(t){return nt.join(this.dir,`${t}.${this.format}`)}async read(t){let i=this._filePath(t);try{let r=await Y.promises.readFile(i);if(this.format==="gz")r=xi.inflateSync(r);return r.toString("utf8")}catch(r){if(r.code==="ENOENT")return null;throw r}}async write(t,i){let r=this._filePath(t),s=nt.join(this.dir,`${t}_${globalThis.crypto.randomUUID()}.tmp.${this.format}`);if(this.format==="gz"){let n=xi.deflateSync(i);await Y.promises.writeFile(s,n)}else await Y.promises.writeFile(s,i,"utf8");await Y.promises.rename(s,r)}async writeAll(t){let i=[];try{for(let{name:r,data:s}of t){let n=this._filePath(r),a=nt.join(this.dir,`${r}_${globalThis.crypto.randomUUID()}.tmp.${this.format}`);if(this.format==="gz"){let o=xi.deflateSync(s);await Y.promises.writeFile(a,o)}else await Y.promises.writeFile(a,s,"utf8");i.push({tmp:a,fp:n})}for(let{tmp:r,fp:s}of i)await Y.promises.rename(r,s)}catch(r){for(let{tmp:s}of i)try{await Y.promises.unlink(s)}catch{}throw r}}async delete(t){let i=this._filePath(t);try{await Y.promises.unlink(i)}catch(r){if(r.code!=="ENOENT")throw r}}async list(){try{let t=await Y.promises.readdir(this.dir),i=`.${this.format}`;return t.filter((r)=>r.endsWith(i)&&!r.includes(".tmp.")).map((r)=>r.slice(0,-i.length))}catch(t){if(t.code==="ENOENT")return[];throw t}}join(...t){return nt.join(...t)}ensureDir(t){this._ensureDir(t)}async writeRaw(t,i){this._ensureDir(nt.dirname(t)),await Y.promises.writeFile(t,i,"utf8")}async readRaw(t){return Y.promises.readFile(nt.resolve(t),"utf8")}}class ha{constructor(){this._migrations=[]}add(t){let{version:i,up:r}=t;if(typeof i!=="number"||i<1)throw new j("ERR_SKALEX_VALIDATION_MIGRATION",`Migration version must be a positive integer, got ${i}`,{version:i});if(typeof r!=="function")throw new j("ERR_SKALEX_VALIDATION_MIGRATION",`Migration version ${i} must have an "up" function`,{version:i});if(this._migrations.some((s)=>s.version===i))throw new j("ERR_SKALEX_VALIDATION_MIGRATION_DUPLICATE",`Migration version ${i} is already registered`,{version:i});this._migrations.push({...t}),this._migrations.sort((s,n)=>s.version-n.version)}async run(t,i=[]){let r=new Set(i),s=this._migrations.filter((n)=>!r.has(n.version));for(let n of s){let a=t(n.version);await n.up(a),r.add(n.version)}return[...r].sort((n,a)=>n-a)}status(t=[]){let i=new Set(t),r=this._migrations.map((s)=>s.version).filter((s)=>!i.has(s));return{current:t.length?Math.max(...t):0,applied:[...i].sort((s,n)=>s-n),pending:r}}}var xs={[Symbol.iterator](){return{next(){return{done:!0}}}},size:0};function Ss(t){return{[Symbol.iterator](){return t[Symbol.iterator]()},get size(){return t.size}}}function Ci(t){return t.map((i)=>{if(i===null||i===void 0)return"\x00";if(typeof i==="boolean")return i?"\x01T":"\x01F";if(typeof i==="number")return`\x02${i}`;return`\x03${String(i)}`}).join("\x1F")}class ei{constructor(t=[],i=[]){this._fields=new Set,this._compoundFields=[];for(let r of t)if(Array.isArray(r)){for(let s of r)this._validateFieldName(s);this._compoundFields.push(r)}else this._validateFieldName(r),this._fields.add(r);for(let r of i)this._validateFieldName(r);this._uniqueFields=new Set(i),this._indexedFields=new Set([...this._fields,...this._uniqueFields]),this._fieldIndexes=new Map,this._uniqueIndexes=new Map;for(let r of this._fields)this._fieldIndexes.set(r,new Map);for(let r of this._uniqueFields)if(this._uniqueIndexes.set(r,new Map),!this._fieldIndexes.has(r))this._fieldIndexes.set(r,new Map);this._compoundIndexes=new Map;for(let r of this._compoundFields)this._compoundIndexes.set(r.join("\x00"),{fields:r,map:new Map})}get indexedFields(){return this._indexedFields}buildFromData(t){for(let[,i]of this._fieldIndexes)i.clear();for(let[,i]of this._uniqueIndexes)i.clear();for(let[,i]of this._compoundIndexes)i.map.clear();for(let i of t)this._indexDoc(i)}add(t){this._checkUnique(t,null),this._indexDoc(t)}remove(t){for(let[i,r]of this._fieldIndexes){let s=t[i];if(s!==void 0){let n=r.get(s);if(n){if(n.delete(t),n.size===0)r.delete(s)}}}for(let[i,r]of this._uniqueIndexes){let s=t[i];if(s!==void 0)r.delete(s)}for(let[,i]of this._compoundIndexes){let r=Ci(i.fields.map((n)=>t[n])),s=i.map.get(r);if(s){if(s.delete(t),s.size===0)i.map.delete(r)}}}update(t,i){this._checkUnique(i,t),this.remove(t);try{this._indexDoc(i)}catch(r){try{this._indexDoc(t)}catch{}throw r}}lookup(t,i){let r=this._fieldIndexes.get(t);if(!r)return null;let s=r.get(i);return s?[...s]:[]}_lookupIterable(t,i){let r=this._fieldIndexes.get(t);if(!r)return null;let s=r.get(i);return s?Ss(s):xs}lookupCompound(t){let i=Object.keys(t).sort();for(let[,r]of this._compoundIndexes){let s=[...r.fields].sort();if(s.length!==i.length)continue;if(s.every((n,a)=>n===i[a])){let n=Ci(r.fields.map((o)=>t[o])),a=r.map.get(n);return a?Ss(a):xs}}return null}isUniqueTaken(t,i){let r=this._uniqueIndexes.get(t);if(!r)return!1;return r.has(i)}assertUniqueCandidates(t,i){if(this._uniqueFields.size===0)return;let r=new Set(t.map((s)=>s._id));for(let s of this._uniqueFields){let n=new Set,a=this._uniqueIndexes.get(s);if(a){for(let[c,l]of a.entries())if(!r.has(l._id))n.add(c)}let o=new Map;for(let c=0;c<i.length;c++){let l=i[c][s];if(l===void 0)continue;if(n.has(l))throw new Ue("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${s}" value "${l}" already exists`,{field:s,value:l});let d=o.get(l);if(d&&d!==t[c]._id)throw new Ue("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${s}" value "${l}" already exists`,{field:s,value:l});o.set(l,t[c]._id)}}}assertUniqueBatch(t){if(this._uniqueFields.size===0)return;for(let i of this._uniqueFields){let r=this._uniqueIndexes.get(i),s=new Set;for(let n of t){let a=n[i];if(a===void 0)continue;if(r&&r.has(a))throw new Ue("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${i}" value "${a}" already exists`,{field:i,value:a});if(s.has(a))throw new Ue("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: duplicate "${i}" value "${a}" within batch`,{field:i,value:a});s.add(a)}}}_validateFieldName(t){if(t.includes("."))throw new j("ERR_SKALEX_VALIDATION_INDEX_DOT_PATH",`Index fields cannot use dot-notation: "${t}". Use a flat field name.`,{field:t})}_indexDoc(t){for(let[i,r]of this._fieldIndexes){let s=t[i];if(s!==void 0){if(!r.has(s))r.set(s,new Set);r.get(s).add(t)}}for(let[i,r]of this._uniqueIndexes){let s=t[i];if(s!==void 0)r.set(s,t)}for(let[,i]of this._compoundIndexes){for(let s of i.fields){let n=t[s];if(n!==void 0&&n!==null&&typeof n==="object")throw new j("ERR_SKALEX_VALIDATION_COMPOUND_INDEX",`Compound index field "${s}" must be a scalar value (string, number, or boolean), got ${Array.isArray(n)?"array":typeof n}`,{field:s})}let r=Ci(i.fields.map((s)=>t[s]));if(!i.map.has(r))i.map.set(r,new Set);i.map.get(r).add(t)}}_checkUnique(t,i){for(let r of this._uniqueFields){let s=t[r];if(s===void 0)continue;let n=this._uniqueIndexes.get(r);if(!n)continue;let a=n.get(s);if(a&&a._id!==i?._id)throw new Ue("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${r}" value "${s}" already exists`,{field:r,value:s})}}}var Gt="_flush",Ht="migrations";class fa{constructor({adapter:t,serializer:i,deserializer:r,logger:s,debug:n=!1,lenientLoad:a=!1}){this._adapter=t,this._serializer=i,this._deserializer=r,this._logger=s,this._debug=n,this._lenientLoad=a,this._saveLock=Promise.resolve()}_withSaveLock(t){let i=this._saveLock.then(t);return this._saveLock=i.catch(()=>{}),i}async loadAll(t,{parseSchema:i,buildIndex:r,IndexEngine:s}){try{let n=await this._adapter.list();await Promise.all(n.map(async(a)=>{try{let o=await this._adapter.read(a);if(!o)return;let c=this._deserializer(o),{collectionName:l,data:d}=c;if(!l)return;let u=t[l],f=u?.rawSchema??c.rawSchema??null,h=u?.schema??(f?i(f):null),_=u?.changelog??c.changelog??!1,p=u?.softDelete??c.softDelete??!1,g=u?.versioning??c.versioning??!1,m=u?.strict??c.strict??!1,w=u?.onSchemaError??c.onSchemaError??"throw",v=u?.defaultTtl??c.defaultTtl??null,q=u?.defaultEmbed??c.defaultEmbed??null,E=u?.maxDocs??c.maxDocs??null,A=u?u.fieldIndex:null;if(!A&&h?.uniqueFields?.length)A=new s([],h.uniqueFields);let tt=r(d,"_id");if(A)A.buildFromData(d);t[l]={collectionName:l,data:d,index:tt,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:h,rawSchema:f,fieldIndex:A,changelog:_,softDelete:p,versioning:g,strict:m,onSchemaError:w,defaultTtl:v,defaultEmbed:q,maxDocs:E}}catch(o){if(o.code==="ENOENT")return;if(this._lenientLoad){this._logger(`WARNING: Could not load collection "${a}": ${o.message}. Collection will be empty.`,"error");return}throw new We("ERR_SKALEX_PERSISTENCE_CORRUPT",`Failed to load collection "${a}": ${o.message}`,{collection:a})}})),this._detectIncompleteFlush(t),await this._cleanOrphanTempFiles()}catch(n){if(n.code!=="ENOENT")throw this._logger(`Error loading data: ${n}`,"error"),n}}async save(t,i){if(i)await this._saveOne(t,i);else await Promise.all(Object.keys(t).map((r)=>this._saveOne(t,r)))}async saveDirty(t){let i=Object.keys(t).filter((r)=>t[r]._dirty);if(i.length===0)return;await Promise.all(i.map((r)=>this._saveOne(t,r)))}saveAtomic(t,i){return this._withSaveLock(async()=>{if(i.length===0)return;this._writeFlushSentinel(t,i);let r=new Set(i);r.add("_meta");let s=[...r].filter((n)=>t[n]).map((n)=>({name:n,data:this._serializeCollection(t[n])}));try{await this._adapter.writeAll(s)}catch(n){throw new We("ERR_SKALEX_PERSISTENCE_FLUSH_FAILED",`Batch save failed during writeAll: ${n.message}`,{collections:i})}for(let n of i)if(t[n])t[n]._dirty=!1;try{this._clearFlushSentinel(t),await this._adapter.write("_meta",this._serializeCollection(t._meta))}catch(n){this._logger(`WARNING: Batch data committed but sentinel clear failed: ${n.message}. Next load will report an incomplete flush (false positive).`,"error")}})}markDirty(t,i){let r=t[i];if(r)r._dirty=!0}_serializeCollection(t){let i={collectionName:t.collectionName,data:t.data};if(t.rawSchema)i.rawSchema=t.rawSchema;if(t.changelog)i.changelog=t.changelog;if(t.softDelete)i.softDelete=t.softDelete;if(t.versioning)i.versioning=t.versioning;if(t.strict)i.strict=t.strict;if(t.onSchemaError!=="throw")i.onSchemaError=t.onSchemaError;if(t.defaultTtl)i.defaultTtl=t.defaultTtl;if(t.defaultEmbed)i.defaultEmbed=t.defaultEmbed;if(t.maxDocs)i.maxDocs=t.maxDocs;return this._serializer(i)}async _saveOne(t,i){let r=t[i];if(!r)return;if(r.isSaving)return r._pendingSave=!0,new Promise((s,n)=>{(r._saveWaiters??=[]).push({resolve:s,reject:n})});r.isSaving=!0,r._pendingSave=!1;try{await this._writeCollection(i,r);while(r._pendingSave)r._pendingSave=!1,await this._writeCollection(i,r);this._resolveSaveWaiters(r)}catch(s){throw this._rejectSaveWaiters(r,s),s}finally{r.isSaving=!1}}async _writeCollection(t,i){try{await this._adapter.write(t,this._serializeCollection(i)),i._dirty=!1}catch(r){throw this._logger(`Error saving "${t}": ${r.message}`,"error"),r}}_resolveSaveWaiters(t){let i=t._saveWaiters?.splice(0)??[];for(let r of i)r.resolve()}_rejectSaveWaiters(t,i){let r=t._saveWaiters?.splice(0)??[];for(let s of r)s.reject(i)}_writeFlushSentinel(t,i){let r=this._getOrCreateMeta(t);r[Gt]={startedAt:new Date().toISOString(),collections:i,completedAt:null}}_clearFlushSentinel(t){let i=this._getOrCreateMeta(t);if(i[Gt])i[Gt].completedAt=new Date().toISOString()}_detectIncompleteFlush(t){let i=t._meta;if(!i)return;let r=i.index.get(Ht);if(!r)return;let s=r[Gt];if(!s)return;if(s.startedAt&&!s.completedAt)this._logger(`WARNING: Incomplete flush detected (started ${s.startedAt}, collections: ${s.collections?.join(", ")}). Data may be inconsistent.`,"error")}async _cleanOrphanTempFiles(){if(typeof this._adapter.join!=="function")return;if(typeof this._adapter.list!=="function")return;try{let t=await import("fs"),i=await import("path"),r=this._adapter.dir;if(!r)return;let s=(await t.default.promises.readdir(r)).filter((n)=>n.includes(".tmp."));for(let n of s){let a=i.default.join(r,n);try{await t.default.promises.unlink(a),this._log(`Cleaned orphan temp file: ${n}`)}catch{}}}catch{}}_getOrCreateMeta(t){if(!t._meta)t._meta={collectionName:"_meta",data:[],index:new Map,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:null,rawSchema:null,fieldIndex:null,changelog:!1,softDelete:!1,versioning:!1,strict:!1,onSchemaError:"throw",defaultTtl:null,defaultEmbed:null,maxDocs:null};let i=t._meta,r=i.index.get(Ht);if(!r)r={_id:Ht},i.data.push(r),i.index.set(Ht,r);return r}_log(t){if(this._debug)this._logger(t,"info")}}var Pc=0;class _a{constructor(){this._txLock=Promise.resolve(),this._ctx=null,this._abortedIds=new Set}get active(){return this._ctx!==null&&!this._ctx.aborted}get context(){return this._ctx}async run(t,i,{timeout:r=0}={}){let s=async()=>{await i._ensureConnected();let a=new Set(Object.keys(i.collections)),o={id:++Pc,startedAt:Date.now(),aborted:!1,preExisting:a,touchedCollections:new Set,snapshots:new Map,deferredEffects:[],timeout:r};this._ctx=o;let c=null,l=r>0?new Promise((f,h)=>{c=setTimeout(()=>{o.aborted=!0,h(new ke("ERR_SKALEX_TX_TIMEOUT",`Transaction ${o.id} timed out after ${r}ms`))},r)}):null,d=this,u=new Proxy(i,{get(f,h){if(h==="_txId")return o.id;if(o!==d._ctx)throw new ke("ERR_SKALEX_TX_STALE_PROXY",`Transaction ${o.id} has ended. This proxy is no longer usable.`);if(h==="collections")throw new ke("ERR_SKALEX_TX_DIRECT_ACCESS","Direct access to db.collections inside transaction() is not covered by rollback. Use the collection API (db.useCollection) instead.");if(h==="useCollection")return(p)=>{let g=f.useCollection(p);return g._activeTxId=o.id,g};let _=Reflect.get(f,h);return typeof _==="function"?_.bind(f):_}});try{let f=t(u),h=l?await Promise.race([f,l]):await f;if(o.aborted)throw new ke("ERR_SKALEX_TX_ABORTED",`Transaction ${o.id} was aborted`);let _=[...o.touchedCollections];if(_.length>0)await i._persistence.saveAtomic(i.collections,_);for(let p of o.deferredEffects)await p();return h}catch(f){for(let[h,_]of o.snapshots)if(o.preExisting.has(h)){if(i._applySnapshot(h,_),i.collections[h])i.collections[h]._dirty=_._dirty}for(let h in i.collections)if(!o.preExisting.has(h))delete i.collections[h],delete i._collectionInstances[h];throw f}finally{if(c)clearTimeout(c);if(o.aborted)this._abortedIds.add(o.id);this._ctx=null;for(let f in i._collectionInstances){let h=i._collectionInstances[f];if(h._createdInTxId===o.id)h._createdInTxId=null;if(h._activeTxId===o.id)h._activeTxId=null}}},n=this._txLock.then(s);return this._txLock=n.catch(()=>{}),n}snapshotIfNeeded(t,i,r){let s=this._ctx;if(!s)return;if(this._assertCtxNotAborted(s),!s.snapshots.has(t)){let n=r(i);n._dirty=i._dirty??!1,s.snapshots.set(t,n)}s.touchedCollections.add(t)}assertNotAborted(){let t=this._ctx;if(t)this._assertCtxNotAborted(t)}_assertCtxNotAborted(t){if(t.aborted)throw new ke("ERR_SKALEX_TX_ABORTED",`Transaction ${t.id} was aborted. No further mutations allowed.`)}defer(t){if(this._ctx)return this._ctx.deferredEffects.push(t),!0;return!1}}class pa{constructor(t){this._CollectionClass=t,this.stores={},this._instances={}}get(t,i){if(this._instances[t])return this._instances[t];if(!this.stores[t])this.createStore(t);let r=new this._CollectionClass(this.stores[t],i);return this._instances[t]=r,r}create(t,i={},r){this.createStore(t,i);let s=new this._CollectionClass(this.stores[t],r);return this._instances[t]=s,s}createStore(t,{schema:i,indexes:r=[],changelog:s=!1,softDelete:n=!1,versioning:a=!1,strict:o=!1,onSchemaError:c="throw",defaultTtl:l=null,defaultEmbed:d=null,maxDocs:u=null}={}){let f=null,h=null;if(i){f=aa(i);let _=f.uniqueFields;if(r.length||_.length)h=new ei(r,_)}else if(r.length)h=new ei(r,[]);this.stores[t]={collectionName:t,data:[],index:new Map,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:f,rawSchema:i||null,fieldIndex:h,changelog:s,softDelete:n,versioning:a,strict:o,onSchemaError:c,defaultTtl:l,defaultEmbed:d,maxDocs:u}}rename(t,i){if(!this.stores[t])throw new We("ERR_SKALEX_PERSISTENCE_COLLECTION_NOT_FOUND",`Collection "${t}" not found`,{collection:t});if(this.stores[i])throw new We("ERR_SKALEX_PERSISTENCE_COLLECTION_EXISTS",`Collection "${i}" already exists`,{collection:i});let r=this.stores[t];if(r.collectionName=i,this.stores[i]=r,delete this.stores[t],this._instances[t]){let s=this._instances[t];s.name=i,this._instances[i]=s,delete this._instances[t]}}buildIndex(t,i){let r=new Map;for(let s of t)r.set(s[i],s);return r}inspect(t){if(t){let r=this.stores[t];if(!r)return null;return{name:t,count:r.data.length,schema:r.schema?Object.fromEntries(r.schema.fields):null,indexes:r.fieldIndex?[...r.fieldIndex.indexedFields]:[],softDelete:r.softDelete??!1,versioning:r.versioning??!1,strict:r.strict??!1,onSchemaError:r.onSchemaError??"throw",maxDocs:r.maxDocs??null}}let i={};for(let r in this.stores)i[r]=this.inspect(r);return i}dump(){let t={};for(let i in this.stores)if(!i.startsWith("_"))t[i]=structuredClone(this.stores[i].data);return t}schema(t){let i=this.stores[t];if(!i)return null;if(i.schema)return Object.fromEntries([...i.schema.fields.entries()].map(([r,s])=>[r,s.type]));if(i.data.length>0)return Tc(i.data[0]);return null}stats(t){let i=(r)=>{let s=this.stores[r];if(!s)return null;let n=s.data.length,a=0;for(let o of s.data)try{a+=JSON.stringify(o).length}catch(c){}return{collection:r,count:n,estimatedSize:a,avgDocSize:n>0?Math.round(a/n):0}};if(t)return i(t);return Object.keys(this.stores).map(i)}clear(){this.stores={},this._instances={}}}class hr{async embed(t){throw Error("EmbeddingAdapter.embed() not implemented")}}var Se=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class ga extends hr{constructor({apiKey:t=Se("OPENAI_API_KEY"),model:i=Se("OPENAI_EMBED_MODEL")??"text-embedding-3-small",baseUrl:r=Se("OPENAI_EMBED_BASE_URL")??"https://api.openai.com/v1/embeddings",dimensions:s=Se("OPENAI_EMBED_DIMENSIONS")!=null?Number(Se("OPENAI_EMBED_DIMENSIONS")):void 0,organization:n=Se("OPENAI_ORGANIZATION")??void 0,timeout:a=Se("OPENAI_EMBED_TIMEOUT")!=null?Number(Se("OPENAI_EMBED_TIMEOUT")):void 0,retries:o=Number(Se("OPENAI_EMBED_RETRIES")??0),retryDelay:c=Number(Se("OPENAI_EMBED_RETRY_DELAY")??1000),headers:l={},fetch:d=globalThis.fetch}={}){super();if(!t)throw Error("OpenAIEmbeddingAdapter requires an apiKey");this.apiKey=t,this.model=i,this.baseUrl=r,this.dimensions=s,this.organization=n,this.timeout=a,this.retries=o,this.retryDelay=c,this.headers=l,this._fetch=d}async embed(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,...this.organization&&{"OpenAI-Organization":this.organization},...this.headers},body:JSON.stringify({input:t,model:this.model,...this.dimensions!==void 0&&{dimensions:this.dimensions}}),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`OpenAI embedding API error ${a.status}: ${o}`)}return(await a.json()).data[0].embedding}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}var St=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class ma extends hr{constructor({model:t=St("OLLAMA_EMBED_MODEL")??"nomic-embed-text",host:i=St("OLLAMA_HOST")??"http://localhost:11434",timeout:r=St("OLLAMA_EMBED_TIMEOUT")!=null?Number(St("OLLAMA_EMBED_TIMEOUT")):void 0,retries:s=Number(St("OLLAMA_EMBED_RETRIES")??0),retryDelay:n=Number(St("OLLAMA_EMBED_RETRY_DELAY")??1000),headers:a={},fetch:o=globalThis.fetch}={}){super();this.model=t,this.host=i,this.timeout=r,this.retries=s,this.retryDelay=n,this.headers=a,this._fetch=o}async embed(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(`${this.host}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json",...this.headers},body:JSON.stringify({model:this.model,prompt:t}),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`Ollama embedding API error ${a.status}: ${o}`)}return(await a.json()).embedding}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}class li{async generate(t,i){throw Error("LLMAdapter.generate() not implemented")}async summarize(t){throw Error("LLMAdapter.summarize() not implemented")}}var fr=`You are a database query assistant. Convert the user's natural language request into a JSON filter object for a document database.
|
|
83
83
|
|
|
84
84
|
Rules:
|
|
85
85
|
- Return ONLY a valid JSON object, nothing else
|
|
@@ -88,33 +88,33 @@ Rules:
|
|
|
88
88
|
- For numeric comparisons use operators: {"age": {"$gt": 18}}
|
|
89
89
|
- For text search use $regex: {"name": {"$regex": "pattern"}}
|
|
90
90
|
- Return {} to match all documents
|
|
91
|
-
- No explanations, no markdown, no code fences`,_r="Summarise the following memory entries into one concise paragraph. Preserve all important facts.",V=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class
|
|
92
|
-
Schema: ${JSON.stringify(t)}`},{role:"user",content:i}],response_format:{type:"json_object"},temperature:0,...this.maxTokens!==void 0&&{max_tokens:this.maxTokens},...this.seed!==void 0&&{seed:this.seed}});return JSON.parse(r.choices[0].message.content)}async summarize(t){return(await this._post({model:this.model,messages:[{role:"system",content:this.summarizePrompt},{role:"user",content:t}],temperature:this.temperature,...this.maxTokens!==void 0&&{max_tokens:this.maxTokens},...this.topP!==void 0&&{top_p:this.topP},...this.seed!==void 0&&{seed:this.seed}})).choices[0].message.content.trim()}async _post(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,...this.organization&&{"OpenAI-Organization":this.organization},...this.headers},body:JSON.stringify(t),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`OpenAI API error ${a.status}: ${o}`)}return a.json()}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}var ce=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class
|
|
93
|
-
Schema: ${JSON.stringify(t)}`,messages:[{role:"user",content:i}]})).content[0].text.trim().replace(/^```(?:json)?\n?/,"").replace(/\n?```$/,"");return JSON.parse(r)}async summarize(t){return(await this._post({model:this.model,max_tokens:this.maxTokens,temperature:this.temperature,...this.topP!==void 0&&{top_p:this.topP},...this.topK!==void 0&&{top_k:this.topK},system:this.summarizePrompt,messages:[{role:"user",content:t}]})).content[0].text.trim()}async _post(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.apiKey,"anthropic-version":this.apiVersion,...this.headers},body:JSON.stringify(t),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`Anthropic API error ${a.status}: ${o}`)}return a.json()}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}var
|
|
91
|
+
- No explanations, no markdown, no code fences`,_r="Summarise the following memory entries into one concise paragraph. Preserve all important facts.",V=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class ya extends li{constructor({apiKey:t=V("OPENAI_API_KEY"),model:i=V("OPENAI_MODEL")??"gpt-4o-mini",baseUrl:r=V("OPENAI_BASE_URL")??"https://api.openai.com/v1/chat/completions",maxTokens:s=V("OPENAI_MAX_TOKENS")!=null?Number(V("OPENAI_MAX_TOKENS")):void 0,temperature:n=Number(V("OPENAI_TEMPERATURE")??0.3),topP:a=V("OPENAI_TOP_P")!=null?Number(V("OPENAI_TOP_P")):void 0,organization:o=V("OPENAI_ORGANIZATION")??void 0,timeout:c=V("OPENAI_TIMEOUT")!=null?Number(V("OPENAI_TIMEOUT")):void 0,retries:l=Number(V("OPENAI_RETRIES")??0),retryDelay:d=Number(V("OPENAI_RETRY_DELAY")??1000),headers:u={},fetch:f=globalThis.fetch,seed:h=V("OPENAI_SEED")!=null?Number(V("OPENAI_SEED")):void 0,generatePrompt:_=fr,summarizePrompt:p=_r}={}){super();if(!t)throw Error("OpenAILLMAdapter requires an apiKey");this.apiKey=t,this.model=i,this.baseUrl=r,this.maxTokens=s,this.temperature=n,this.topP=a,this.organization=o,this.timeout=c,this.retries=l,this.retryDelay=d,this.headers=u,this._fetch=f,this.seed=h,this.generatePrompt=_,this.summarizePrompt=p}async generate(t,i){let r=await this._post({model:this.model,messages:[{role:"system",content:`${this.generatePrompt}
|
|
92
|
+
Schema: ${JSON.stringify(t)}`},{role:"user",content:i}],response_format:{type:"json_object"},temperature:0,...this.maxTokens!==void 0&&{max_tokens:this.maxTokens},...this.seed!==void 0&&{seed:this.seed}});return JSON.parse(r.choices[0].message.content)}async summarize(t){return(await this._post({model:this.model,messages:[{role:"system",content:this.summarizePrompt},{role:"user",content:t}],temperature:this.temperature,...this.maxTokens!==void 0&&{max_tokens:this.maxTokens},...this.topP!==void 0&&{top_p:this.topP},...this.seed!==void 0&&{seed:this.seed}})).choices[0].message.content.trim()}async _post(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json",Authorization:`Bearer ${this.apiKey}`,...this.organization&&{"OpenAI-Organization":this.organization},...this.headers},body:JSON.stringify(t),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`OpenAI API error ${a.status}: ${o}`)}return a.json()}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}var ce=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class wa extends li{constructor({apiKey:t=ce("ANTHROPIC_API_KEY"),model:i=ce("ANTHROPIC_MODEL")??"claude-haiku-4-5",baseUrl:r=ce("ANTHROPIC_BASE_URL")??"https://api.anthropic.com/v1/messages",apiVersion:s="2023-06-01",maxTokens:n=Number(ce("ANTHROPIC_MAX_TOKENS")??1024),temperature:a=Number(ce("ANTHROPIC_TEMPERATURE")??0.3),topP:o=ce("ANTHROPIC_TOP_P")!=null?Number(ce("ANTHROPIC_TOP_P")):void 0,topK:c=ce("ANTHROPIC_TOP_K")!=null?Number(ce("ANTHROPIC_TOP_K")):void 0,timeout:l=ce("ANTHROPIC_TIMEOUT")!=null?Number(ce("ANTHROPIC_TIMEOUT")):void 0,retries:d=Number(ce("ANTHROPIC_RETRIES")??0),retryDelay:u=Number(ce("ANTHROPIC_RETRY_DELAY")??1000),headers:f={},fetch:h=globalThis.fetch,generatePrompt:_=fr,summarizePrompt:p=_r}={}){super();if(!t)throw Error("AnthropicLLMAdapter requires an apiKey");this.apiKey=t,this.model=i,this.baseUrl=r,this.apiVersion=s,this.maxTokens=n,this.temperature=a,this.topP=o,this.topK=c,this.timeout=l,this.retries=d,this.retryDelay=u,this.headers=f,this._fetch=h,this.generatePrompt=_,this.summarizePrompt=p}async generate(t,i){let r=(await this._post({model:this.model,max_tokens:this.maxTokens,temperature:0,system:`${this.generatePrompt}
|
|
93
|
+
Schema: ${JSON.stringify(t)}`,messages:[{role:"user",content:i}]})).content[0].text.trim().replace(/^```(?:json)?\n?/,"").replace(/\n?```$/,"");return JSON.parse(r)}async summarize(t){return(await this._post({model:this.model,max_tokens:this.maxTokens,temperature:this.temperature,...this.topP!==void 0&&{top_p:this.topP},...this.topK!==void 0&&{top_k:this.topK},system:this.summarizePrompt,messages:[{role:"user",content:t}]})).content[0].text.trim()}async _post(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(this.baseUrl,{method:"POST",headers:{"Content-Type":"application/json","x-api-key":this.apiKey,"anthropic-version":this.apiVersion,...this.headers},body:JSON.stringify(t),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`Anthropic API error ${a.status}: ${o}`)}return a.json()}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}var me=(t)=>globalThis.process?.env?.[t]??globalThis.Deno?.env?.get(t);class Aa extends li{constructor({model:t=me("OLLAMA_MODEL")??"llama3.2",host:i=me("OLLAMA_HOST")??"http://localhost:11434",temperature:r=Number(me("OLLAMA_TEMPERATURE")??0.3),topP:s=me("OLLAMA_TOP_P")!=null?Number(me("OLLAMA_TOP_P")):void 0,topK:n=me("OLLAMA_TOP_K")!=null?Number(me("OLLAMA_TOP_K")):void 0,timeout:a=me("OLLAMA_TIMEOUT")!=null?Number(me("OLLAMA_TIMEOUT")):void 0,retries:o=Number(me("OLLAMA_RETRIES")??0),retryDelay:c=Number(me("OLLAMA_RETRY_DELAY")??1000),headers:l={},fetch:d=globalThis.fetch,generatePrompt:u=fr,summarizePrompt:f=_r}={}){super();this.model=t,this.host=i,this.temperature=r,this.topP=s,this.topK=n,this.timeout=a,this.retries=o,this.retryDelay=c,this.headers=l,this._fetch=d,this.generatePrompt=u,this.summarizePrompt=f}async generate(t,i){let r=`${this.generatePrompt}
|
|
94
94
|
Schema: ${JSON.stringify(t)}
|
|
95
95
|
Query: ${i}`,s=await this._post({model:this.model,prompt:r,format:"json",options:{temperature:0},stream:!1});return JSON.parse(s.response)}async summarize(t){return(await this._post({model:this.model,prompt:`${this.summarizePrompt}
|
|
96
96
|
|
|
97
|
-
${t}`,options:{temperature:this.temperature,...this.topP!==void 0&&{top_p:this.topP},...this.topK!==void 0&&{top_k:this.topK}},stream:!1})).response.trim()}async _post(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(`${this.host}/api/generate`,{method:"POST",headers:{"Content-Type":"application/json",...this.headers},body:JSON.stringify(t),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`Ollama API error ${a.status}: ${o}`)}return a.json()}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}function
|
|
97
|
+
${t}`,options:{temperature:this.temperature,...this.topP!==void 0&&{top_p:this.topP},...this.topK!==void 0&&{top_k:this.topK}},stream:!1})).response.trim()}async _post(t){let i;for(let r=0;r<=this.retries;r++){let s=this.timeout!=null?new AbortController:null,n=s?setTimeout(()=>s.abort(),this.timeout):null;try{let a=await this._fetch(`${this.host}/api/generate`,{method:"POST",headers:{"Content-Type":"application/json",...this.headers},body:JSON.stringify(t),...s&&{signal:s.signal}});if(!a.ok){let o=(await a.text()).slice(0,200);throw Error(`Ollama API error ${a.status}: ${o}`)}return a.json()}catch(a){if(i=a,r<this.retries)await new Promise((o)=>setTimeout(o,this.retryDelay*2**r))}finally{if(n!==null)clearTimeout(n)}}throw i}}function Mc({provider:t,apiKey:i,embedModel:r,model:s,host:n,embedBaseUrl:a,dimensions:o,organization:c,embedTimeout:l,embedRetries:d,embedRetryDelay:u}){let f=r||s;switch(t){case"openai":return new ga({apiKey:i,model:f,baseUrl:a,...o!==void 0&&{dimensions:o},...c!==void 0&&{organization:c},...l!==void 0&&{timeout:l},...d!==void 0&&{retries:d},...u!==void 0&&{retryDelay:u}});case"ollama":return new ma({model:f,host:n,...l!==void 0&&{timeout:l},...d!==void 0&&{retries:d},...u!==void 0&&{retryDelay:u}});default:throw new Re("ERR_SKALEX_ADAPTER_UNKNOWN_PROVIDER",`Unknown AI provider: "${t}". Supported: "openai", "ollama".`,{provider:t})}}function jc({provider:t,apiKey:i,model:r,host:s,baseUrl:n,apiVersion:a,temperature:o,maxTokens:c,topP:l,topK:d,organization:u,timeout:f,retries:h,retryDelay:_,seed:p,generatePrompt:g,summarizePrompt:m}){if(!r)return null;switch(t){case"openai":return new ya({apiKey:i,model:r,baseUrl:n,...c!==void 0&&{maxTokens:c},...o!==void 0&&{temperature:o},...l!==void 0&&{topP:l},...u!==void 0&&{organization:u},...f!==void 0&&{timeout:f},...h!==void 0&&{retries:h},..._!==void 0&&{retryDelay:_},...p!==void 0&&{seed:p},...g!==void 0&&{generatePrompt:g},...m!==void 0&&{summarizePrompt:m}});case"anthropic":return new wa({apiKey:i,model:r,baseUrl:n,apiVersion:a,...c!==void 0&&{maxTokens:c},...o!==void 0&&{temperature:o},...l!==void 0&&{topP:l},...d!==void 0&&{topK:d},...f!==void 0&&{timeout:f},...h!==void 0&&{retries:h},..._!==void 0&&{retryDelay:_},...g!==void 0&&{generatePrompt:g},...m!==void 0&&{summarizePrompt:m}});case"ollama":return new Aa({model:r,host:s,...o!==void 0&&{temperature:o},...l!==void 0&&{topP:l},...d!==void 0&&{topK:d},...f!==void 0&&{timeout:f},...h!==void 0&&{retries:h},..._!==void 0&&{retryDelay:_},...g!==void 0&&{generatePrompt:g},...m!==void 0&&{summarizePrompt:m}});default:return null}}var Ni="AES-GCM",Lt=12,Fe=32,qc=new TextEncoder,Uc=new TextDecoder;class va extends ur{constructor(t,i){super();if(this._adapter=t,this._rawKey=typeof i==="string"?Fc(i):Uint8Array.from(i),this._rawKey.length!==Fe)throw new Re("ERR_SKALEX_ADAPTER_INVALID_KEY",`EncryptedAdapter: key must be ${Fe} bytes (${Fe*2} hex chars), got ${this._rawKey.length}`);this._cryptoKey=null}async read(t){let i=await this._adapter.read(t);if(!i)return null;return this._decrypt(i)}async write(t,i){return this._adapter.write(t,await this._encrypt(i))}async delete(t){return this._adapter.delete(t)}async list(){return this._adapter.list()}async writeAll(t){let i=[];for(let{name:r,data:s}of t)i.push({name:r,data:await this._encrypt(s)});return this._adapter.writeAll(i)}join(...t){return this._adapter.join?.(...t)}ensureDir(t){return this._adapter.ensureDir?.(t)}async writeRaw(t,i){return this._adapter.writeRaw?.(t,await this._encrypt(i))}async readRaw(t){let i=await this._adapter.readRaw?.(t);if(!i)return null;return this._decrypt(i)}async _getKey(){if(!this._cryptoKey)this._cryptoKey=await globalThis.crypto.subtle.importKey("raw",this._rawKey,{name:Ni},!1,["encrypt","decrypt"]);return this._cryptoKey}async _encrypt(t){let i=await this._getKey(),r=globalThis.crypto.getRandomValues(new Uint8Array(Lt)),s=qc.encode(t),n=await globalThis.crypto.subtle.encrypt({name:Ni,iv:r,tagLength:128},i,s),a=new Uint8Array(Lt+n.byteLength);return a.set(r,0),a.set(new Uint8Array(n),Lt),Kc(a)}async _decrypt(t){let i=await this._getKey(),r=zc(t),s=r.slice(0,Lt),n=r.slice(Lt),a=await globalThis.crypto.subtle.decrypt({name:Ni,iv:s,tagLength:128},i,n);return Uc.decode(a)}}function Fc(t){if(t.length!==Fe*2)throw new Re("ERR_SKALEX_ADAPTER_INVALID_KEY",`EncryptedAdapter: hex key must be ${Fe*2} characters (${Fe} bytes)`);if(!/^[0-9a-fA-F]+$/.test(t))throw new Re("ERR_SKALEX_ADAPTER_INVALID_KEY","EncryptedAdapter: hex key contains invalid characters");let i=new Uint8Array(Fe);for(let r=0;r<Fe;r++)i[r]=parseInt(t.slice(r*2,r*2+2),16);return i}function Kc(t){let i="";for(let r=0;r<t.length;r++)i+=String.fromCharCode(t[r]);return globalThis.btoa(i)}function zc(t){let i=globalThis.atob(t),r=new Uint8Array(i.length);for(let s=0;s<i.length;s++)r[s]=i.charCodeAt(s);return r}var Bc=4;class Ea{constructor(t,i){this.sessionId=t,this._db=i,this._col=i.useCollection(`_memory_${t}`)}async remember(t){let i=await this._col.insertOne({text:t,sessionId:this.sessionId},{embed:"text"}),r=this._db._memoryConfig?.maxEntries;if(r&&this._col._data.length>r)await this.compress({threshold:0});return i}async recall(t,{limit:i=10,minScore:r=0}={}){return this._col.search(t,{limit:i,minScore:r})}async history({since:t,limit:i}={}){let r=t?{createdAt:{$gte:new Date(t)}}:{},s={sort:{createdAt:1}};if(i)s.limit=i;let{docs:n}=await this._col.find(r,s);return n}async forget(t){return this._col.deleteOne({_id:t})}tokenCount(){let t=this._col._data;return{tokens:t.reduce((i,r)=>i+this._docTokens(r),0),count:t.length}}context({tokens:t=this._db._memoryConfig?.contextTokens??4000}={}){let i=this._sortedData("desc"),r=[],s=0;for(let n of i){let a=this._docTokens(n);if(s+a>t)break;r.push(n.text),s+=a}return r.reverse().join(`
|
|
98
98
|
`)}async compress({threshold:t=this._db._memoryConfig?.compressionThreshold??8000,keepRecent:i=this._db._memoryConfig?.keepRecent??10}={}){let{tokens:r}=this.tokenCount();if(r<=t)return;if(!this._db._aiAdapter)throw Error('memory.compress() requires a language model adapter. Configure { ai: { model: "..." } }.');let s=this._sortedData("asc"),n=Math.max(0,s.length-i),a=s.slice(0,n);if(a.length===0)return;let o=a.map((l)=>l.text).join(`
|
|
99
|
-
`),c=await this._db._aiAdapter.summarize(o);await this._col.deleteMany({_id:{$in:a.map((l)=>l._id)}}),await this._col.insertOne({text:c,sessionId:this.sessionId,compressed:!0})}_docTokens(t){return Math.ceil((t.text||"").length/zc)}_sortedData(t){return[...this._col._data].sort(t==="asc"?(i,r)=>new Date(i.createdAt)-new Date(r.createdAt):(i,r)=>new Date(r.createdAt)-new Date(i.createdAt))}}class Ea{constructor(t){this._db=t,this._restoring=!1}get _col(){return this._db.useCollection("_changelog")}async log(t,i,r,s=null,n=null){if(this._restoring)return;let a={op:t,collection:i,docId:r._id,doc:{...r},timestamp:new Date};if(s)a.prev={...s};if(n)a.session=n;await this._col.insertOne(a)}async query(t,{since:i,limit:r,session:s}={}){let n={collection:t};if(i)n.timestamp={$gte:new Date(i)};if(s)n.session=s;let a={sort:{timestamp:1}};if(r)a.limit=r;let{docs:o}=await this._col.find(n,a);return o}async restore(t,i,{_id:r}={}){let s=new Date(i),n=this._db.useCollection(t),a=(await this.query(t,{})).filter((c)=>new Date(c.timestamp)<=s);if(r){let c=a.filter((d)=>d.docId===r);if(c.length===0)return;let l=c[c.length-1];this._restoring=!0;try{if(l.op==="delete"){if(await n.findOne({_id:r}))await n.deleteOne({_id:r});return}if(await n.findOne({_id:r})){let{_id:d,createdAt:u,updatedAt:f,...h}=l.doc;await n.updateOne({_id:r},h)}else await n.insertOne({...l.doc})}finally{this._restoring=!1}await this._db.saveData(t);return}let o=new Map;for(let c of a)if(c.op==="insert"||c.op==="update")o.set(c.docId,{doc:c.doc,deleted:!1});else if(c.op==="delete")o.set(c.docId,{doc:null,deleted:!0});this._restoring=!0;try{await n.deleteMany({});for(let[,{doc:c,deleted:l}]of o)if(!l&&c)await n.insertOne({...c})}finally{this._restoring=!1}await this._db.saveData(t)}}function Bc(t){let i=5381;for(let r=0;r<t.length;r++)i=(i<<5)+i+t.charCodeAt(r)|0;return(i>>>0).toString(16).padStart(8,"0")}class xa{constructor({maxSize:t=500,ttl:i=0}={}){this._cache=new Map,this._maxSize=t,this._ttl=i}_key(t,i,r){return Bc(JSON.stringify({collectionName:t,schema:i,query:r}))}get(t,i,r){let s=this._key(t,i,r),n=this._cache.get(s);if(!n)return;if(this._ttl>0&&Date.now()-n.ts>this._ttl){this._cache.delete(s);return}return n.filter}set(t,i,r,s){let n=this._key(t,i,r);if(this._cache.size>=this._maxSize&&!this._cache.has(n))this._cache.delete(this._cache.keys().next().value);this._cache.set(n,{filter:s,ts:Date.now()})}toJSON(){return Object.fromEntries([...this._cache.entries()].map(([t,i])=>[t,i]))}fromJSON(t){if(!t||typeof t!=="object")return;for(let[i,r]of Object.entries(t))this._cache.set(i,r)}get size(){return this._cache.size}}function Xc(t,{regexMaxLength:i=500}={}){if(typeof t!=="object"||t===null)return t;let r={};for(let s of Object.keys(t)){let n=t[s];if(n&&typeof n==="object"&&!Array.isArray(n)){let a={};for(let o of Object.keys(n))if(o==="$regex"&&typeof n.$regex==="string"){if(n.$regex.length>i)throw Error(`$regex pattern too long (max ${i} characters)`);if(/\([^)]*[+*][^)]*\)[+*{]/.test(n.$regex))throw Error("$regex pattern rejected: nested quantifiers risk ReDoS");try{a.$regex=new RegExp(n.$regex)}catch{throw Error(`invalid $regex pattern: "${n.$regex}"`)}}else if(["$gt","$gte","$lt","$lte"].includes(o)&&Vc(n[o]))a[o]=new Date(n[o]);else a[o]=n[o];r[s]=a}else r[s]=n}return r}function Vc(t){if(typeof t!=="string")return!1;return/\d{4}-\d{2}-\d{2}/.test(t)&&!isNaN(Date.parse(t))}function Gc(t,i){let r=[];if(!i||typeof t!=="object"||t===null)return r;for(let s of Object.keys(t)){if(s.startsWith("$"))continue;if(!(s.split(".")[0]in i))r.push(`Unknown field referenced in generated filter: "${s}"`)}return r}class Sa{constructor(){this._listeners=new Map}on(t,i){if(!this._listeners.has(t))this._listeners.set(t,new Set);return this._listeners.get(t).add(i),()=>this._listeners.get(t)?.delete(i)}off(t,i){this._listeners.get(t)?.delete(i)}emit(t,i){for(let r of[t,"*"]){let s=this._listeners.get(r);if(!s)continue;for(let n of s)try{n(i)}catch(a){}}}removeAll(t){if(t)this._listeners.delete(t);else this._listeners.clear()}listenerCount(t){return this._listeners.get(t)?.size??0}}class Ia{constructor({threshold:t=100,maxEntries:i=500}={}){this._threshold=t,this._maxEntries=i,this._entries=[]}record({collection:t,op:i,filter:r,query:s,duration:n,resultCount:a}){if(n<this._threshold)return;let o={collection:t,op:i,duration:n,resultCount:a,timestamp:new Date};if(r!==void 0)o.filter=r;if(s!==void 0)o.query=s;if(this._entries.push(o),this._entries.length>this._maxEntries)this._entries.shift()}entries({limit:t,minDuration:i,collection:r}={}){let s=this._entries;if(r)s=s.filter((n)=>n.collection===r);if(i)s=s.filter((n)=>n.duration>=i);if(t)s=s.slice(-t);return s}get size(){return this._entries.length}clear(){this._entries=[]}}class ba{constructor(){this._sessions=new Map}_ensure(t){if(!this._sessions.has(t))this._sessions.set(t,{reads:0,writes:0,lastActive:null});return this._sessions.get(t)}recordRead(t){if(!t)return;let i=this._ensure(t);i.reads++,i.lastActive=new Date}recordWrite(t){if(!t)return;let i=this._ensure(t);i.writes++,i.lastActive=new Date}get(t){let i=this._sessions.get(t);if(!i)return null;return{sessionId:t,...i}}all(){return[...this._sessions.entries()].map(([t,i])=>({sessionId:t,...i}))}clear(t){if(t)this._sessions.delete(t);else this._sessions.clear()}}class Ta{constructor(){this._plugins=[]}register(t){if(typeof t!=="object"||t===null)throw TypeError("Plugin must be a non-null object.");this._plugins.push(t)}async run(t,i){for(let r of this._plugins)if(typeof r[t]==="function")await r[t](i)}get size(){return this._plugins.length}}function dt(t){if(typeof t!=="string"||!t.trim())throw Error("collection name must be a non-empty string");if(/[/\\]/.test(t)||t.includes("..")||t.includes("\x00"))throw Error(`invalid collection name: "${t}"`);if(t.trim().startsWith("_"))throw Error(`access to system collection "${t}" is not permitted`);return t.trim()}var Ss=[{name:"skalex_collections",description:"List all collection names in the database.",inputSchema:{type:"object",properties:{}},scope:"read"},{name:"skalex_schema",description:"Return the schema for a collection as a { field: type } map. Returns null if the collection is empty.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."}},required:["collection"]},scope:"read"},{name:"skalex_find",description:"Find documents in a collection that match a filter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},filter:{type:"object",description:"Query filter (MongoDB-style operators supported)."},limit:{type:"number",description:"Maximum number of results. Default: 20."},sort:{type:"object",description:"Sort descriptor: { field: 1 } for ascending, { field: -1 } for descending."}},required:["collection"]},scope:"read"},{name:"skalex_insert",description:"Insert a single document into a collection.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},doc:{type:"object",description:"Document to insert."}},required:["collection","doc"]},scope:"write"},{name:"skalex_update",description:"Update the first document matching a filter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},filter:{type:"object",description:"Query filter to identify the document."},update:{type:"object",description:"Fields to update (direct assignment, $inc, $push supported)."},many:{type:"boolean",description:"If true, update all matching documents. Default: false."}},required:["collection","filter","update"]},scope:"write"},{name:"skalex_delete",description:"Delete the first document matching a filter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},filter:{type:"object",description:"Query filter to identify the document."},many:{type:"boolean",description:"If true, delete all matching documents. Default: false."}},required:["collection","filter"]},scope:"write"},{name:"skalex_search",description:"Semantic similarity search. Requires an embedding adapter to be configured.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},query:{type:"string",description:"Natural-language query string to embed and compare."},limit:{type:"number",description:"Maximum number of results. Default: 10."},minScore:{type:"number",description:"Minimum cosine similarity score [0, 1]. Default: 0."},filter:{type:"object",description:"Optional structured pre-filter (hybrid search)."}},required:["collection","query"]},scope:"read"},{name:"skalex_ask",description:"Translate a natural-language question into a filter and query a collection. Requires a language model adapter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},question:{type:"string",description:"Natural-language question about the data."},limit:{type:"number",description:"Maximum number of results. Default: 20."}},required:["collection","question"]},scope:"read"}];async function Hc(t,i,r){switch(t){case"skalex_collections":return Object.keys(r.collections).filter((s)=>!s.startsWith("_"));case"skalex_schema":return r.schema(dt(i.collection))??null;case"skalex_find":{let s=r.useCollection(dt(i.collection)),n={};if(i.limit)n.limit=i.limit;if(i.sort)n.sort=i.sort;return s.find(i.filter||{},n)}case"skalex_insert":return r.useCollection(dt(i.collection)).insertOne(i.doc||{});case"skalex_update":{let s=r.useCollection(dt(i.collection));if(i.many)return s.updateMany(i.filter||{},i.update||{});return s.updateOne(i.filter||{},i.update||{})}case"skalex_delete":{let s=r.useCollection(dt(i.collection));if(i.many)return s.deleteMany(i.filter||{});return s.deleteOne(i.filter||{})}case"skalex_search":return r.useCollection(dt(i.collection)).search(i.query,{limit:i.limit??10,minScore:i.minScore??0,filter:i.filter});case"skalex_ask":return r.ask(dt(i.collection),i.question,{limit:i.limit??20});default:throw Object.assign(Error(`Unknown tool: ${t}`),{code:"NOT_FOUND"})}}var pr="2.0",gr=-32700,Wc=-32600,Is=-32601,Jc=-32602,Yc=-32603;function St(t,i){return{jsonrpc:pr,id:t,result:i}}function Xe(t,i,r,s){return{jsonrpc:pr,id:t,error:{code:i,message:r}}}function Qc(t){try{let i=JSON.parse(t);if(typeof i!=="object"||i===null||i.jsonrpc!==pr)return{parseError:Xe(null,Wc,"Invalid JSON-RPC request")};return{msg:i}}catch(i){return{parseError:Xe(null,gr,"Parse error")}}}function Zc(t){return{content:[{type:"text",text:t}]}}function bs(t){return{content:[{type:"text",text:t}],isError:!0}}class Oa{constructor({port:t=3000,host:i="127.0.0.1",allowedOrigin:r=null,maxBodySize:s=1048576}={}){this._port=t,this._host=i,this._allowedOrigin=r,this._maxBodySize=s,this._clients=new Set,this._onMessage=null,this._server=null}onMessage(t){this._onMessage=t}send(t){let i=`data: ${JSON.stringify(t)}
|
|
99
|
+
`),c=await this._db._aiAdapter.summarize(o);await this._col.deleteMany({_id:{$in:a.map((l)=>l._id)}}),await this._col.insertOne({text:c,sessionId:this.sessionId,compressed:!0})}_docTokens(t){return Math.ceil((t.text||"").length/Bc)}_sortedData(t){return[...this._col._data].sort(t==="asc"?(i,r)=>new Date(i.createdAt)-new Date(r.createdAt):(i,r)=>new Date(r.createdAt)-new Date(i.createdAt))}}class xa{constructor(t){this._db=t,this._restoring=!1}get _col(){return this._db.useCollection("_changelog")}async log(t,i,r,s=null,n=null){if(this._restoring)return;let a={op:t,collection:i,docId:r._id,doc:{...r},timestamp:new Date};if(s)a.prev={...s};if(n)a.session=n;await this._col.insertOne(a)}async query(t,{since:i,limit:r,session:s}={}){let n={collection:t};if(i)n.timestamp={$gte:new Date(i)};if(s)n.session=s;let a={sort:{timestamp:1}};if(r)a.limit=r;let{docs:o}=await this._col.find(n,a);return o}async restore(t,i,{_id:r}={}){let s=new Date(i),n=this._db.useCollection(t),a=(await this.query(t,{})).filter((c)=>new Date(c.timestamp)<=s);if(r){let c=a.filter((d)=>d.docId===r);if(c.length===0)return;let l=c[c.length-1];this._restoring=!0;try{if(l.op==="delete"){if(await n.findOne({_id:r}))await n.deleteOne({_id:r});return}if(await n.findOne({_id:r})){let{_id:d,createdAt:u,updatedAt:f,...h}=l.doc;await n.updateOne({_id:r},h)}else await n.insertOne({...l.doc})}finally{this._restoring=!1}await this._db.saveData(t);return}let o=new Map;for(let c of a)if(c.op==="insert"||c.op==="update")o.set(c.docId,{doc:c.doc,deleted:!1});else if(c.op==="delete")o.set(c.docId,{doc:null,deleted:!0});this._restoring=!0;try{await n.deleteMany({});for(let[,{doc:c,deleted:l}]of o)if(!l&&c)await n.insertOne({...c})}finally{this._restoring=!1}await this._db.saveData(t)}}function Xc(t){let i=5381;for(let r=0;r<t.length;r++)i=(i<<5)+i+t.charCodeAt(r)|0;return(i>>>0).toString(16).padStart(8,"0")}class Sa{constructor({maxSize:t=500,ttl:i=0}={}){this._cache=new Map,this._maxSize=t,this._ttl=i}_key(t,i,r){return Xc(JSON.stringify({collectionName:t,schema:i,query:r}))}get(t,i,r){let s=this._key(t,i,r),n=this._cache.get(s);if(!n)return;if(this._ttl>0&&Date.now()-n.ts>this._ttl){this._cache.delete(s);return}return n.filter}set(t,i,r,s){let n=this._key(t,i,r);if(this._cache.size>=this._maxSize&&!this._cache.has(n))this._cache.delete(this._cache.keys().next().value);this._cache.set(n,{filter:s,ts:Date.now()})}toJSON(){return Object.fromEntries([...this._cache.entries()].map(([t,i])=>[t,i]))}fromJSON(t){if(!t||typeof t!=="object")return;for(let[i,r]of Object.entries(t))this._cache.set(i,r)}get size(){return this._cache.size}}function Vc(t,{regexMaxLength:i=500}={}){if(typeof t!=="object"||t===null)return t;let r={};for(let s of Object.keys(t)){let n=t[s];if(n&&typeof n==="object"&&!Array.isArray(n)){let a={};for(let o of Object.keys(n))if(o==="$regex"&&typeof n.$regex==="string"){if(n.$regex.length>i)throw Error(`$regex pattern too long (max ${i} characters)`);if(/\([^)]*[+*][^)]*\)[+*{]/.test(n.$regex))throw Error("$regex pattern rejected: nested quantifiers risk ReDoS");try{a.$regex=new RegExp(n.$regex)}catch{throw Error(`invalid $regex pattern: "${n.$regex}"`)}}else if(["$gt","$gte","$lt","$lte"].includes(o)&&Gc(n[o]))a[o]=new Date(n[o]);else a[o]=n[o];r[s]=a}else r[s]=n}return r}function Gc(t){if(typeof t!=="string")return!1;return/\d{4}-\d{2}-\d{2}/.test(t)&&!isNaN(Date.parse(t))}function Hc(t,i){let r=[];if(!i||typeof t!=="object"||t===null)return r;for(let s of Object.keys(t)){if(s.startsWith("$"))continue;if(!(s.split(".")[0]in i))r.push(`Unknown field referenced in generated filter: "${s}"`)}return r}class Ia{constructor(){this._listeners=new Map}on(t,i){if(!this._listeners.has(t))this._listeners.set(t,new Set);return this._listeners.get(t).add(i),()=>this._listeners.get(t)?.delete(i)}off(t,i){this._listeners.get(t)?.delete(i)}emit(t,i){for(let r of[t,"*"]){let s=this._listeners.get(r);if(!s)continue;for(let n of s)try{n(i)}catch(a){}}}removeAll(t){if(t)this._listeners.delete(t);else this._listeners.clear()}listenerCount(t){return this._listeners.get(t)?.size??0}}class ba{constructor({threshold:t=100,maxEntries:i=500}={}){this._threshold=t,this._maxEntries=i,this._entries=[]}record({collection:t,op:i,filter:r,query:s,duration:n,resultCount:a}){if(n<this._threshold)return;let o={collection:t,op:i,duration:n,resultCount:a,timestamp:new Date};if(r!==void 0)o.filter=r;if(s!==void 0)o.query=s;if(this._entries.push(o),this._entries.length>this._maxEntries)this._entries.shift()}entries({limit:t,minDuration:i,collection:r}={}){let s=this._entries;if(r)s=s.filter((n)=>n.collection===r);if(i)s=s.filter((n)=>n.duration>=i);if(t)s=s.slice(-t);return s}get size(){return this._entries.length}clear(){this._entries=[]}}class Ta{constructor(){this._sessions=new Map}_ensure(t){if(!this._sessions.has(t))this._sessions.set(t,{reads:0,writes:0,lastActive:null});return this._sessions.get(t)}recordRead(t){if(!t)return;let i=this._ensure(t);i.reads++,i.lastActive=new Date}recordWrite(t){if(!t)return;let i=this._ensure(t);i.writes++,i.lastActive=new Date}get(t){let i=this._sessions.get(t);if(!i)return null;return{sessionId:t,...i}}all(){return[...this._sessions.entries()].map(([t,i])=>({sessionId:t,...i}))}clear(t){if(t)this._sessions.delete(t);else this._sessions.clear()}}class Oa{constructor(){this._plugins=[]}register(t){if(typeof t!=="object"||t===null)throw TypeError("Plugin must be a non-null object.");this._plugins.push(t)}async run(t,i){for(let r of this._plugins)if(typeof r[t]==="function")await r[t](i)}get size(){return this._plugins.length}}function dt(t){if(typeof t!=="string"||!t.trim())throw Error("collection name must be a non-empty string");if(/[/\\]/.test(t)||t.includes("..")||t.includes("\x00"))throw Error(`invalid collection name: "${t}"`);if(t.trim().startsWith("_"))throw Error(`access to system collection "${t}" is not permitted`);return t.trim()}var Is=[{name:"skalex_collections",description:"List all collection names in the database.",inputSchema:{type:"object",properties:{}},scope:"read"},{name:"skalex_schema",description:"Return the schema for a collection as a { field: type } map. Returns null if the collection is empty.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."}},required:["collection"]},scope:"read"},{name:"skalex_find",description:"Find documents in a collection that match a filter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},filter:{type:"object",description:"Query filter (MongoDB-style operators supported)."},limit:{type:"number",description:"Maximum number of results. Default: 20."},sort:{type:"object",description:"Sort descriptor: { field: 1 } for ascending, { field: -1 } for descending."}},required:["collection"]},scope:"read"},{name:"skalex_insert",description:"Insert a single document into a collection.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},doc:{type:"object",description:"Document to insert."}},required:["collection","doc"]},scope:"write"},{name:"skalex_update",description:"Update the first document matching a filter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},filter:{type:"object",description:"Query filter to identify the document."},update:{type:"object",description:"Fields to update (direct assignment, $inc, $push supported)."},many:{type:"boolean",description:"If true, update all matching documents. Default: false."}},required:["collection","filter","update"]},scope:"write"},{name:"skalex_delete",description:"Delete the first document matching a filter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},filter:{type:"object",description:"Query filter to identify the document."},many:{type:"boolean",description:"If true, delete all matching documents. Default: false."}},required:["collection","filter"]},scope:"write"},{name:"skalex_search",description:"Semantic similarity search. Requires an embedding adapter to be configured.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},query:{type:"string",description:"Natural-language query string to embed and compare."},limit:{type:"number",description:"Maximum number of results. Default: 10."},minScore:{type:"number",description:"Minimum cosine similarity score [0, 1]. Default: 0."},filter:{type:"object",description:"Optional structured pre-filter (hybrid search)."}},required:["collection","query"]},scope:"read"},{name:"skalex_ask",description:"Translate a natural-language question into a filter and query a collection. Requires a language model adapter.",inputSchema:{type:"object",properties:{collection:{type:"string",description:"Collection name."},question:{type:"string",description:"Natural-language question about the data."},limit:{type:"number",description:"Maximum number of results. Default: 20."}},required:["collection","question"]},scope:"read"}];async function Wc(t,i,r){switch(t){case"skalex_collections":return Object.keys(r.collections).filter((s)=>!s.startsWith("_"));case"skalex_schema":return r.schema(dt(i.collection))??null;case"skalex_find":{let s=r.useCollection(dt(i.collection)),n={};if(i.limit)n.limit=i.limit;if(i.sort)n.sort=i.sort;return s.find(i.filter||{},n)}case"skalex_insert":return r.useCollection(dt(i.collection)).insertOne(i.doc||{});case"skalex_update":{let s=r.useCollection(dt(i.collection));if(i.many)return s.updateMany(i.filter||{},i.update||{});return s.updateOne(i.filter||{},i.update||{})}case"skalex_delete":{let s=r.useCollection(dt(i.collection));if(i.many)return s.deleteMany(i.filter||{});return s.deleteOne(i.filter||{})}case"skalex_search":return r.useCollection(dt(i.collection)).search(i.query,{limit:i.limit??10,minScore:i.minScore??0,filter:i.filter});case"skalex_ask":return r.ask(dt(i.collection),i.question,{limit:i.limit??20});default:throw Object.assign(Error(`Unknown tool: ${t}`),{code:"NOT_FOUND"})}}var pr="2.0",gr=-32700,Jc=-32600,bs=-32601,Yc=-32602,Qc=-32603;function It(t,i){return{jsonrpc:pr,id:t,result:i}}function Xe(t,i,r,s){return{jsonrpc:pr,id:t,error:{code:i,message:r}}}function Zc(t){try{let i=JSON.parse(t);if(typeof i!=="object"||i===null||i.jsonrpc!==pr)return{parseError:Xe(null,Jc,"Invalid JSON-RPC request")};return{msg:i}}catch(i){return{parseError:Xe(null,gr,"Parse error")}}}function ed(t){return{content:[{type:"text",text:t}]}}function Ts(t){return{content:[{type:"text",text:t}],isError:!0}}class Ra{constructor({port:t=3000,host:i="127.0.0.1",allowedOrigin:r=null,maxBodySize:s=1048576}={}){this._port=t,this._host=i,this._allowedOrigin=r,this._maxBodySize=s,this._clients=new Set,this._onMessage=null,this._server=null}onMessage(t){this._onMessage=t}send(t){let i=`data: ${JSON.stringify(t)}
|
|
100
100
|
|
|
101
|
-
`;for(let r of this._clients)try{r.write(i)}catch(s){this._clients.delete(r)}}start(){return new Promise((t,i)=>{this._server=
|
|
101
|
+
`;for(let r of this._clients)try{r.write(i)}catch(s){this._clients.delete(r)}}start(){return new Promise((t,i)=>{this._server=Po.createServer((r,s)=>{if(this._allowedOrigin)s.setHeader("Access-Control-Allow-Origin",this._allowedOrigin),s.setHeader("Access-Control-Allow-Methods","GET, POST, OPTIONS"),s.setHeader("Access-Control-Allow-Headers","Content-Type");if(r.method==="OPTIONS"){s.writeHead(204),s.end();return}if(r.method==="GET"&&r.url==="/sse")this._handleSSE(r,s);else if(r.method==="POST"&&r.url==="/message")this._handleMessage(r,s);else s.writeHead(404,{"Content-Type":"text/plain"}),s.end("Not Found")}),this._server.on("error",i),this._server.listen(this._port,this._host,()=>t())})}stop(){return new Promise((t)=>{if(!this._server){t();return}for(let i of this._clients)try{i.end()}catch(r){}this._clients.clear(),this._server.close(()=>t()),this._server=null})}_handleSSE(t,i){i.writeHead(200,{"Content-Type":"text/event-stream","Cache-Control":"no-cache",Connection:"keep-alive"}),i.write(`event: endpoint
|
|
102
102
|
data: /message
|
|
103
103
|
|
|
104
|
-
`),this._clients.add(i),t.on("close",()=>{this._clients.delete(i)})}async _handleMessage(t,i){let r="";t.setEncoding("utf8"),t.on("data",(s)=>{if(r+=s,r.length>this._maxBodySize)t.destroy(),i.writeHead(413,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Request body too large"}))}),t.on("end",async()=>{i.writeHead(202,{"Content-Type":"application/json"}),i.end("{}");let s;try{s=JSON.parse(r)}catch(n){this.send(Xe(null,gr,"Parse error"));return}if(this._onMessage)await this._onMessage(s).catch(()=>{})})}get port(){return this._port}get host(){return this._host}get url(){return`http://${this._host}:${this._port}`}get sseUrl(){return`${this.url}/sse`}}class
|
|
104
|
+
`),this._clients.add(i),t.on("close",()=>{this._clients.delete(i)})}async _handleMessage(t,i){let r="";t.setEncoding("utf8"),t.on("data",(s)=>{if(r+=s,r.length>this._maxBodySize)t.destroy(),i.writeHead(413,{"Content-Type":"application/json"}),i.end(JSON.stringify({error:"Request body too large"}))}),t.on("end",async()=>{i.writeHead(202,{"Content-Type":"application/json"}),i.end("{}");let s;try{s=JSON.parse(r)}catch(n){this.send(Xe(null,gr,"Parse error"));return}if(this._onMessage)await this._onMessage(s).catch(()=>{})})}get port(){return this._port}get host(){return this._host}get url(){return`http://${this._host}:${this._port}`}get sseUrl(){return`${this.url}/sse`}}class Ca{constructor(){this._onMessage=null,this._buffer="",this._started=!1}onMessage(t){this._onMessage=t}send(t){process.stdout.write(JSON.stringify(t)+`
|
|
105
105
|
`)}start(){if(this._started)return;this._started=!0,process.stdin.setEncoding("utf8"),process.stdin.on("data",(t)=>{this._buffer+=t;let i;while((i=this._buffer.indexOf(`
|
|
106
|
-
`))!==-1){let r=this._buffer.slice(0,i).trim();if(this._buffer=this._buffer.slice(i+1),r&&this._onMessage){let s;try{s=JSON.parse(r)}catch(n){this.send(Xe(null,gr,"Parse error"));continue}this._onMessage(s).catch(()=>{})}}}),process.stdin.on("end",()=>{process.exit(0)})}stop(){process.stdin.removeAllListeners("data"),process.stdin.removeAllListeners("end"),this._started=!1}}var ed={name:"skalex",version:"4.0.0-alpha"},td="2024-11-05";class Ca{constructor(t,i={}){this._db=t,this._transport=i.transport||"stdio",this._port=i.port||3000,this._host=i.host||"127.0.0.1",this._allowedOrigin=i.allowedOrigin??null,this._maxBodySize=i.maxBodySize??1048576,this._scopes=i.scopes||{"*":["read"]},this._t=null}async listen(){if(this._transport==="http")this._t=new Oa({port:this._port,host:this._host,allowedOrigin:this._allowedOrigin,maxBodySize:this._maxBodySize});else this._t=new Ra;this._t.onMessage((t)=>this._handleMessage(t)),await this._t.start()}async connect(t){if(this._t=t,this._t.onMessage((i)=>this._handleMessage(i)),typeof this._t.start==="function")await this._t.start()}async close(){if(this._t&&typeof this._t.stop==="function")await this._t.stop();this._t=null}get transport(){return this._transport}get url(){return this._t?.url}async _handleMessage(t){let{msg:i,parseError:r}=typeof t==="string"?Qc(t):{msg:t};if(r){this._send(r);return}let{id:s,method:n,params:a}=i;if(s===void 0){if(n==="notifications/initialized")return;return}try{switch(n){case"initialize":this._send(St(s,{protocolVersion:td,capabilities:{tools:{}},serverInfo:ed}));break;case"tools/list":this._send(St(s,{tools:this._visibleTools()}));break;case"tools/call":await this._handleToolCall(s,a);break;case"ping":this._send(St(s,{}));break;default:this._send(Xe(s,Is,`Method not found: ${n}`))}}catch(o){this._send(Xe(s,Yc,o.message||"Internal error"))}}async _handleToolCall(t,i){let r=i?.name,s=i?.arguments??{};if(!r){this._send(Xe(t,Jc,"tools/call requires params.name"));return}let n=Ss.find((o)=>o.name===r);if(!n){this._send(Xe(t,Is,`Unknown tool: ${r}`));return}let a=s.collection||s.collection_name||null;if(!this._hasScope(a,n.scope)){this._send(St(t,bs(`Access denied: "${r}" requires "${n.scope}" scope on collection "${a}".`)));return}try{let o=await Hc(r,s,this._db);this._send(St(t,Zc(JSON.stringify(o,null,2))))}catch(o){this._send(St(t,bs(o.message||String(o))))}}_visibleTools(){return Ss.filter((t)=>{let i=this._scopes["*"];if(i&&(i.includes(t.scope)||i.includes("admin")))return!0;for(let[,r]of Object.entries(this._scopes))if(r.includes(t.scope)||r.includes("admin"))return!0;return!1})}_hasScope(t,i){let r=(s)=>s.includes("admin")||s.includes(i);if(t&&this._scopes[t])return r(this._scopes[t]);if(this._scopes["*"])return r(this._scopes["*"]);return!1}_send(t){this._t?.send(t)}}var Zt="migrations",Ts=(t)=>JSON.stringify(t,function(i,r){let s=this[i];if(s instanceof Date)return{__skalex_date__:s.toISOString()};if(typeof r==="bigint")return{__skalex_bigint__:r.toString()};return r}),Os=(t)=>JSON.parse(t,(i,r)=>{if(r&&typeof r==="object"){if("__skalex_bigint__"in r)return BigInt(r.__skalex_bigint__);if("__skalex_date__"in r)return new Date(r.__skalex_date__)}return r});class fe{constructor({path:t="./.db",format:i="gz",debug:r=!1,adapter:s,ai:n,encrypt:a,slowQueryLog:o,queryCache:c,memory:l,logger:d,plugins:u,llmAdapter:f,embeddingAdapter:h,regexMaxLength:_,idGenerator:p,serializer:g,deserializer:m,autoSave:w,ttlSweepInterval:v,lenientLoad:q}={}){if(this.dataDirectory=t,this.dataFormat=i,this.debug=r,!fe._errorsAttached)fe.SkalexError=Ze,fe.ValidationError=j,fe.UniqueConstraintError=Ue,fe.TransactionError=$e,fe.PersistenceError=We,fe.AdapterError=Oe,fe.QueryError=_t,fe._errorsAttached=!0;this._adapterConfig=s??null;let E=s||new da({dir:t,format:i});if(a)E=new Aa(E,a.key);if(this.fs=E,this._registry=new _a(ca),this.collections=this._registry.stores,this._collectionInstances=this._registry._instances,this._migrations=new ua,this._connectPromise=null,this.isConnected=!1,this._aiConfig=n||null,this._encryptConfig=a||null,this._pluginsConfig=Array.isArray(u)?u:null,this._memoryConfig=l||null,this._regexMaxLength=_??500,this._idGenerator=p??null,this._serializer=g??Ts,this._deserializer=m??Os,this._autoSave=w??!1,this._txManager=new fa,this._ttlSweepInterval=v??0,this._ttlTimer=null,this._logger=d??ms,this._embeddingAdapter=h??(n?Pc(n):null),this._aiAdapter=f??(n?Mc(n):null),this._persistence=new ha({adapter:this.fs,serializer:this._serializer,deserializer:this._deserializer,logger:this._logger,debug:this.debug,lenientLoad:q??!1}),this._changeLog=new Ea(this),this._queryCache=new xa(c||{}),this._eventBus=new Sa,this._queryLog=o?new Ia(o):null,this._sessionStats=new ba,this._plugins=new Ta,Array.isArray(u))for(let A of u)this._plugins.register(A)}async connect(){if(this._connectPromise)return this._connectPromise;return this._connectPromise=this._doConnect(),this._connectPromise}async _doConnect(){try{await this.loadData();let t=this._getMeta();if(t.queryCache)this._queryCache.fromJSON(t.queryCache);if(this._migrations._migrations.length>0){let i=t.appliedVersions||[],r=await this._migrations.run((s)=>this.useCollection(`_migration_${s}`),i);this._saveMeta({appliedVersions:r})}if(this._sweepTtl(),this._ttlSweepInterval>0){if(this._ttlTimer=setInterval(()=>this._sweepTtl(),this._ttlSweepInterval),this._ttlTimer?.unref)this._ttlTimer.unref()}this.isConnected=!0,this._log("> - Connected to the database (\u221A)")}catch(t){throw this._logger(`Error connecting to the database: ${t}`,"error"),t}}async disconnect(){try{if(this._ttlTimer)clearInterval(this._ttlTimer),this._ttlTimer=null;await this.saveData(),this._registry.clear(),this.collections=this._registry.stores,this._collectionInstances=this._registry._instances,this._connectPromise=null,this.isConnected=!1,this._log("> - Disconnected from the database (\u221A)")}catch(t){throw this._logger(`Error disconnecting from the database: ${t}`,"error"),t}}async _ensureConnected(){if(this.isConnected)return;return this.connect()}useCollection(t){return this._registry.get(t,this)}createCollection(t,i={}){return this._registry.create(t,i,this)}_createCollectionStore(t,i={}){this._registry.createStore(t,i)}async renameCollection(t,i){this._registry.rename(t,i),await this.saveData(i),await this.fs.delete(t)}async loadData(){await this._persistence.loadAll(this.collections,{parseSchema:na,buildIndex:this._registry.buildIndex,IndexEngine:si});for(let t in this._collectionInstances){let i=this.collections[t];if(i&&this._collectionInstances[t]._store!==i)this._collectionInstances[t]._store=i}}async saveData(t){await this._persistence.save(this.collections,t)}buildIndex(t,i){return this._registry.buildIndex(t,i)}addMigration(t){this._migrations.add(t)}migrationStatus(){let t=this._getMeta();return this._migrations.status(t.appliedVersions||[])}namespace(t){if(this._adapterConfig)throw new Oe("ERR_SKALEX_ADAPTER_NAMESPACE_REQUIRES_FS","namespace() requires the default FsAdapter. When a custom storage adapter is configured, create a separate Skalex instance with your adapter instead.");let i=String(t).replace(/[^a-zA-Z0-9_-]/g,"_");if(!i)throw new j("ERR_SKALEX_VALIDATION_NAMESPACE_ID","namespace: id must contain at least one alphanumeric character",{id:t});return new fe({path:`${this.dataDirectory}/${i}`,format:this.dataFormat,debug:this.debug,ai:this._aiConfig||void 0,encrypt:this._encryptConfig||void 0,slowQueryLog:this._queryLog?{threshold:this._queryLog._threshold,maxEntries:this._queryLog._maxEntries}:void 0,queryCache:this._queryCache?{maxSize:this._queryCache._maxSize,ttl:this._queryCache._ttl}:void 0,plugins:this._pluginsConfig||void 0,memory:this._memoryConfig||void 0,logger:this._logger!==ms?this._logger:void 0,llmAdapter:this._aiAdapter&&!this._aiConfig?this._aiAdapter:void 0,embeddingAdapter:this._embeddingAdapter&&!this._aiConfig?this._embeddingAdapter:void 0,regexMaxLength:this._regexMaxLength!==500?this._regexMaxLength:void 0,idGenerator:this._idGenerator||void 0,serializer:this._serializer!==Ts?this._serializer:void 0,deserializer:this._deserializer!==Os?this._deserializer:void 0,autoSave:this._autoSave||void 0,ttlSweepInterval:this._ttlSweepInterval||void 0})}use(t){this._plugins.register(t)}watch(t){return this._eventBus.on("*",t)}sessionStats(t){if(t!==void 0)return this._sessionStats.get(t);return this._sessionStats.all()}get _inTransaction(){return this._txManager.active}_emitEvent(t,i){if(!this._txManager.defer(()=>this._eventBus.emit(t,i)))this._eventBus.emit(t,i)}async _runAfterHook(t,i){if(!this._txManager.defer(()=>this._plugins.run(t,i)))await this._plugins.run(t,i)}async _logChange(t,i,r,s,n){if(!this._txManager.defer(()=>this._changeLog.log(t,i,r,s,n)))await this._changeLog.log(t,i,r,s,n)}async transaction(t,i={}){return this._txManager.run(t,this,i)}async seed(t,{reset:i=!1}={}){for(let[r,s]of Object.entries(t)){if(i&&this.collections[r])this._applySnapshot(r,{data:[],index:new Map}),delete this._collectionInstances[r];await this.useCollection(r).insertMany(s)}await this.saveData()}dump(){return this._registry.dump()}inspect(t){return this._registry.inspect(t)}async import(t){let i=await this.fs.readRaw(t),r;try{r=JSON.parse(i)}catch{throw new We("ERR_SKALEX_PERSISTENCE_INVALID_JSON",`import: invalid JSON in file "${t}"`,{filePath:t})}let s=t.split("/").pop().replace(/\.[^.]+$/,"");return this.useCollection(s).insertMany(Array.isArray(r)?r:[r],{save:!0})}async embed(t){if(!this._embeddingAdapter)throw new Oe("ERR_SKALEX_ADAPTER_EMBEDDING_REQUIRED","db.embed() requires an AI adapter. Pass { ai: { provider, apiKey } } to the Skalex constructor.");return this._embeddingAdapter.embed(t)}async ask(t,i,{limit:r=20}={}){if(!this._aiAdapter)throw new Oe("ERR_SKALEX_ADAPTER_LLM_REQUIRED",'db.ask() requires a language model adapter. Configure { ai: { provider, model: "..." } }.');let s=this.useCollection(t),n=this.schema(t),a=this._queryCache.get(t,n,i);if(!a){a=await this._aiAdapter.generate(n,i);let o=Gc(a,n);if(o.length)o.forEach((c)=>this._log(`[ask] ${c}`));this._queryCache.set(t,n,i,a),this._saveMeta({queryCache:this._queryCache.toJSON()})}return s.find(Xc(a,{regexMaxLength:this._regexMaxLength}),{limit:r})}schema(t){return this._registry.schema(t)}useMemory(t){return new va(t,this)}changelog(){return this._changeLog}async restore(t,i,r={}){return this._changeLog.restore(t,i,r)}stats(t){return this._registry.stats(t)}slowQueries(t={}){if(!this._queryLog)return[];return this._queryLog.entries(t)}slowQueryCount(){return this._queryLog?this._queryLog.size:0}clearSlowQueries(){this._queryLog?.clear()}mcp(t={}){return new Ca(this,t)}_getMeta(){let t=this.collections._meta;if(!t)return{};return t.index.get(Zt)||{}}_saveMeta(t){if(!this.collections._meta)this._createCollectionStore("_meta");let i=this.collections._meta,r=i.index.get(Zt);if(r)Object.assign(r,t);else{let s={_id:Zt,...t};i.data.push(s),i.index.set(Zt,s)}this._persistence.markDirty(this.collections,"_meta")}_sweepTtl(){for(let t in this.collections){let i=this.collections[t],r=Rc(i.data,i.index,i.fieldIndex?(s)=>i.fieldIndex.remove(s):null);if(r>0)this._persistence.markDirty(this.collections,t),this._log(`TTL sweep: removed ${r} expired docs from "${t}"`)}}_buildCollectionContext(){let t=this;return{ensureConnected:()=>t._ensureConnected(),get txManager(){return t._txManager},get plugins(){return t._plugins},get eventBus(){return t._eventBus},get sessionStats(){return t._sessionStats},get queryLog(){return t._queryLog},get logger(){return t._logger},get persistence(){return t._persistence},get collections(){return t.collections},embed:(i)=>t.embed(i),get idGenerator(){return t._idGenerator},get autoSave(){return t._autoSave},saveCollection:(i)=>t.saveData(i),snapshotCollection:(i)=>t._snapshotCollection(i),getCollection:(i)=>t.useCollection(i),emitEvent:(i,r)=>t._emitEvent(i,r),runAfterHook:(i,r)=>t._runAfterHook(i,r),logChange:(i,r,s,n,a)=>t._logChange(i,r,s,n,a),get fs(){return t.fs},get dataDirectory(){return t.dataDirectory}}}_log(t){if(this.debug)this._logger(t,"info")}_snapshotCollection(t){return{data:structuredClone(t.data)}}_applySnapshot(t,i){let r=this.collections[t];if(!r)return;if(r.data=i.data,r.index=this.buildIndex(i.data,"_id"),r.fieldIndex)r.fieldIndex.buildFromData(i.data)}}class Na{}var id=new Map;function rd(t,i){id.set(t,i)}var Rs=()=>new Date().toISOString();function S(t){if(!t)return t;let{_id:i,createdAt:r,updatedAt:s,_version:n,_expiresAt:a,...o}=t,c={...o};if(c.createdAt==null&&r!=null)c.createdAt=r instanceof Date?r.toISOString():String(r);if(c.updatedAt==null&&s!=null)c.updatedAt=s instanceof Date?s.toISOString():String(s);return c}class mr extends Na{dataDir;encryptionKey;lockPath;lockFd=null;db;tasks;config;gitRepos;bookmarks;notifications;pluginState;constructor(t){super();this.dataDir=t.dataDir,this.encryptionKey=t.encryptionKey,this.lockPath=ko(t.dataDir,".agent-db.lock")}static async create(t){if(!Oo(t.dataDir))Ro(t.dataDir,{recursive:!0});let i=new mr(t);i.acquireLock();try{await i.init()}catch(r){throw i.releaseLock(),r}return i}acquireLock(){try{this.lockFd=Co(this.lockPath,"wx",384),$o(this.lockFd,JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()}));return}catch(i){if(i.code!=="EEXIST")throw i}let t=!1;try{let i=JSON.parse(No(this.lockPath,"utf8"));if(!i.pid)t=!0;else try{process.kill(i.pid,0)}catch{t=!0}}catch{t=!0}if(t){try{Dr(this.lockPath)}catch{}this.acquireLock();return}throw Error(`Agent database is already open by another process (${this.lockPath})`)}releaseLock(){if(this.lockFd!==null){try{To(this.lockFd)}catch{}this.lockFd=null}try{Dr(this.lockPath)}catch{}}async init(){this.db=new fe({path:this.dataDir,encrypt:{key:this.encryptionKey},autoSave:!0,format:"gz",lenientLoad:!0}),this.tasks=this.db.createCollection("tasks",{schema:{id:{type:"string",required:!0,unique:!0},type:{type:"string",required:!0,enum:["command","script","file_operation"]},status:{type:"string",required:!0,enum:["pending","running","completed","failed"]},payload:{type:"string",required:!0},result:{type:"string"},error:{type:"string"},calendarTaskId:{type:"string"},exitCode:{type:"number"},timeout:{type:"number"}},indexes:["status","type"]}),this.config=this.db.createCollection("agent_config",{schema:{key:{type:"string",required:!0,unique:!0},value:{type:"string",required:!0}}}),this.gitRepos=this.db.createCollection("git_repositories",{schema:{id:{type:"string",required:!0,unique:!0},path:{type:"string",required:!0,unique:!0},name:{type:"string",required:!0},parentPath:{type:"string"},isSubmodule:{type:"boolean"},projectType:{type:"string"},vitePort:{type:"number"},lastScanned:{type:"string"}},indexes:["parentPath"]}),this.bookmarks=this.db.createCollection("bookmarked_commands",{schema:{id:{type:"string",required:!0,unique:!0},projectId:{type:"string"},command:{type:"string",required:!0},description:{type:"string"},category:{type:"string"}},indexes:["projectId","category"]}),this.notifications=this.db.createCollection("notifications",{schema:{id:{type:"string",required:!0,unique:!0},sessionName:{type:"string"},projectId:{type:"string"},type:{type:"string",required:!0,enum:["info","success","warning","error"]},title:{type:"string",required:!0},message:{type:"string",required:!0},status:{type:"string",required:!0,enum:["unread","read"]}},indexes:["status","projectId"]}),this.pluginState=this.db.createCollection("plugin_state",{schema:{pluginName:{type:"string",required:!0},key:{type:"string",required:!0},value:{type:"string",required:!0}},indexes:["pluginName"]}),await this.db.connect()}async close(){if(this.db?.isConnected)await this.db.disconnect();this.releaseLock()}getDbPath(){return this.dataDir}async createTask(t){let i={id:t.id,type:t.type,status:t.status,payload:t.payload};if(t.result!=null)i.result=t.result;if(t.error!=null)i.error=t.error;if(t.calendarTaskId!=null)i.calendarTaskId=t.calendarTaskId;if(t.exitCode!=null)i.exitCode=t.exitCode;if(t.timeout!=null)i.timeout=t.timeout;let r=await this.tasks.insertOne(i);return S(r)}async getTask(t){let i=await this.tasks.findOne({id:t});return i?S(i):void 0}async getAllTasks(){return(await this.tasks.find(void 0,{sort:{createdAt:-1}})).docs.map((t)=>S(t))}async getPendingTasks(){return(await this.tasks.find({status:"pending"},{sort:{createdAt:1}})).docs.map((t)=>S(t))}async updateTask(t,i){let r={};for(let[s,n]of Object.entries(i)){if(s==="id"||s==="createdAt"||s==="updatedAt")continue;r[s]=n??null}if(Object.keys(r).length===0)return;await this.tasks.updateOne({id:t},r)}async cancelTask(t){let i=await this.tasks.findOne({id:t});if(!i||i.status!=="pending"&&i.status!=="running")return!1;return await this.tasks.updateOne({id:t},{status:"failed",error:"Cancelled"}),!0}async getConfig(t){return(await this.config.findOne({key:t}))?.value}async setConfig(t,i){await this.config.upsert({key:t},{key:t,value:i})}async deleteConfig(t){return await this.config.deleteOne({key:t})!==null}async getAllConfig(){let t=await this.config.find(),i={};for(let r of t.docs)i[r.key]=r.value;return i}async bulkSetConfig(t){for(let[i,r]of Object.entries(t))await this.config.upsert({key:i},{key:i,value:r})}async getConfigStatus(){let t=await this.config.find(),i=null;for(let r of t.docs){let s=r.updatedAt,n=s instanceof Date?s.toISOString():typeof s==="string"?s:null;if(n&&(!i||n>i))i=n}return{totalKeys:t.docs.length,lastUpdated:i}}async createGitRepository(t){let i={id:t.id,path:t.path,name:t.name,isSubmodule:Boolean(t.isSubmodule),lastScanned:Rs()};if(t.parentPath!=null)i.parentPath=t.parentPath;if(t.projectType!=null)i.projectType=t.projectType;if(t.vitePort!=null)i.vitePort=t.vitePort;let r=await this.gitRepos.insertOne(i);return S(r)}async getGitRepository(t){let i=await this.gitRepos.findOne({id:t});return i?S(i):void 0}async getGitRepositoryByPath(t){let i=await this.gitRepos.findOne({path:t});return i?S(i):void 0}async getAllGitRepositories(){return(await this.gitRepos.find(void 0,{sort:{path:1}})).docs.map((t)=>S(t))}async updateGitRepository(t,i){let r={lastScanned:Rs()};for(let[s,n]of Object.entries(i)){if(s==="id"||s==="createdAt"||s==="updatedAt")continue;if(s==="isSubmodule"){r[s]=Boolean(n);continue}r[s]=n??null}await this.gitRepos.updateOne({id:t},r)}async deleteGitRepository(t){return await this.gitRepos.deleteOne({id:t})!==null}async fixGitHierarchy(){let t=await this.getAllGitRepositories(),i=0;for(let r of t){if(r.isSubmodule)continue;let s=t.find((n)=>n.id!==r.id&&r.path.startsWith(`${n.path}/`)&&!n.isSubmodule);if(s&&r.parentPath!==s.path)await this.updateGitRepository(r.id,{parentPath:s.path}),i++}return{fixed:i}}async createBookmarkedCommand(t){let i={id:t.id,command:t.command};if(t.projectId!=null)i.projectId=t.projectId;if(t.description!=null)i.description=t.description;if(t.category!=null)i.category=t.category;let r=await this.bookmarks.insertOne(i);return S(r)}async getBookmarkedCommand(t){let i=await this.bookmarks.findOne({id:t});return i?S(i):void 0}async getAllBookmarkedCommands(){return(await this.bookmarks.find(void 0,{sort:{createdAt:-1}})).docs.map((t)=>S(t))}async getBookmarkedCommandsByProject(t){let i=t===null?{projectId:{$fn:(r)=>r==null}}:{projectId:t};return(await this.bookmarks.find(i,{sort:{createdAt:-1}})).docs.map((r)=>S(r))}async getBookmarkedCommandsByCategory(t){return(await this.bookmarks.find({category:t},{sort:{createdAt:-1}})).docs.map((i)=>S(i))}async updateBookmarkedCommand(t,i){let r={};for(let[s,n]of Object.entries(i)){if(s==="id"||s==="createdAt"||s==="updatedAt")continue;r[s]=n??null}if(Object.keys(r).length===0)return;await this.bookmarks.updateOne({id:t},r)}async deleteBookmarkedCommand(t){return await this.bookmarks.deleteOne({id:t})!==null}async executeBookmarkedCommand(t){return this.getBookmarkedCommand(t)}async createNotification(t){let i={id:t.id,type:t.type,title:t.title,message:t.message,status:t.status};if(t.sessionName!=null)i.sessionName=t.sessionName;if(t.projectId!=null)i.projectId=t.projectId;let r=await this.notifications.insertOne(i);return S(r)}async getNotification(t){let i=await this.notifications.findOne({id:t});return i?S(i):void 0}async getAllNotifications(){return(await this.notifications.find(void 0,{sort:{createdAt:-1}})).docs.map((t)=>S(t))}async getNotificationsByProject(t){let i=t===null?{projectId:{$fn:(r)=>r==null}}:{projectId:t};return(await this.notifications.find(i,{sort:{createdAt:-1}})).docs.map((r)=>S(r))}async getGlobalNotifications(){return this.getNotificationsByProject(null)}async getUnreadNotifications(){return(await this.notifications.find({status:"unread"},{sort:{createdAt:-1}})).docs.map((t)=>S(t))}async updateNotificationStatus(t,i){await this.notifications.updateOne({id:t},{status:i})}async markAllNotificationsRead(){return(await this.notifications.updateMany({status:"unread"},{status:"read"})).length}async deleteNotification(t){return await this.notifications.deleteOne({id:t})!==null}async clearOldNotifications(t=30){let i=new Date(Date.now()-t*24*60*60*1000);return(await this.notifications.deleteMany({createdAt:{$fn:(r)=>r instanceof Date&&r<i}})).length}async getPluginState(t,i){return(await this.pluginState.findOne({$and:[{pluginName:t},{key:i}]}))?.value}async setPluginState(t,i,r){await this.pluginState.upsert({$and:[{pluginName:t},{key:i}]},{pluginName:t,key:i,value:r})}async deletePluginState(t,i){return await this.pluginState.deleteOne({$and:[{pluginName:t},{key:i}]})!==null}async getAllPluginState(t){return(await this.pluginState.find({pluginName:t},{sort:{key:1}})).docs.map((i)=>{let r=i.updatedAt,s=r instanceof Date?r.toISOString():typeof r==="string"?r:void 0;return{key:i.key,value:i.value,updatedAt:s}})}async deleteAllPluginState(t){return(await this.pluginState.deleteMany({pluginName:t})).length}}var $a=(t)=>mr.create(t);rd("skalex",$a);var sd=new Map;function ka(t,i){sd.set(t,i)}class Da{}ka("skalex",$a);var Cs=()=>new Date().toISOString();function I(t){if(!t)return t;let{_id:i,createdAt:r,updatedAt:s,_version:n,_expiresAt:a,...o}=t,c={...o};if(c.createdAt==null&&r!=null)c.createdAt=r instanceof Date?r.toISOString():String(r);if(c.updatedAt==null&&s!=null)c.updatedAt=s instanceof Date?s.toISOString():String(s);return c}class yr extends Da{dataDir;encryptionKey;lockPath;lockFd=null;db;tasks;config;gitRepos;bookmarks;notifications;pluginState;constructor(t){super();this.dataDir=t.dataDir,this.encryptionKey=t.encryptionKey,this.lockPath=So(t.dataDir,".agent-db.lock")}static async create(t){if(!wo(t.dataDir))Ao(t.dataDir,{recursive:!0});let i=new yr(t);i.acquireLock();try{await i.init()}catch(r){throw i.releaseLock(),r}return i}acquireLock(){try{this.lockFd=vo(this.lockPath,"wx",384),xo(this.lockFd,JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()}));return}catch(i){if(i.code!=="EEXIST")throw i}let t=!1;try{let i=JSON.parse(Eo(this.lockPath,"utf8"));if(!i.pid)t=!0;else try{process.kill(i.pid,0)}catch{t=!0}}catch{t=!0}if(t){try{kr(this.lockPath)}catch{}this.acquireLock();return}throw Error(`Agent database is already open by another process (${this.lockPath})`)}releaseLock(){if(this.lockFd!==null){try{yo(this.lockFd)}catch{}this.lockFd=null}try{kr(this.lockPath)}catch{}}async init(){this.db=new he({path:this.dataDir,encrypt:{key:this.encryptionKey},autoSave:!0,format:"gz",lenientLoad:!0}),this.tasks=this.db.createCollection("tasks",{schema:{id:{type:"string",required:!0,unique:!0},type:{type:"string",required:!0,enum:["command","script","file_operation"]},status:{type:"string",required:!0,enum:["pending","running","completed","failed"]},payload:{type:"string",required:!0},result:{type:"string"},error:{type:"string"},calendarTaskId:{type:"string"},exitCode:{type:"number"},timeout:{type:"number"}},indexes:["status","type"]}),this.config=this.db.createCollection("agent_config",{schema:{key:{type:"string",required:!0,unique:!0},value:{type:"string",required:!0}}}),this.gitRepos=this.db.createCollection("git_repositories",{schema:{id:{type:"string",required:!0,unique:!0},path:{type:"string",required:!0,unique:!0},name:{type:"string",required:!0},parentPath:{type:"string"},isSubmodule:{type:"boolean"},projectType:{type:"string"},vitePort:{type:"number"},lastScanned:{type:"string"}},indexes:["parentPath"]}),this.bookmarks=this.db.createCollection("bookmarked_commands",{schema:{id:{type:"string",required:!0,unique:!0},projectId:{type:"string"},command:{type:"string",required:!0},description:{type:"string"},category:{type:"string"}},indexes:["projectId","category"]}),this.notifications=this.db.createCollection("notifications",{schema:{id:{type:"string",required:!0,unique:!0},sessionName:{type:"string"},projectId:{type:"string"},type:{type:"string",required:!0,enum:["info","success","warning","error"]},title:{type:"string",required:!0},message:{type:"string",required:!0},status:{type:"string",required:!0,enum:["unread","read"]}},indexes:["status","projectId"]}),this.pluginState=this.db.createCollection("plugin_state",{schema:{pluginName:{type:"string",required:!0},key:{type:"string",required:!0},value:{type:"string",required:!0}},indexes:["pluginName"]}),await this.db.connect()}async close(){if(this.db?.isConnected)await this.db.disconnect();this.releaseLock()}getDbPath(){return this.dataDir}async createTask(t){let i={id:t.id,type:t.type,status:t.status,payload:t.payload};if(t.result!=null)i.result=t.result;if(t.error!=null)i.error=t.error;if(t.calendarTaskId!=null)i.calendarTaskId=t.calendarTaskId;if(t.exitCode!=null)i.exitCode=t.exitCode;if(t.timeout!=null)i.timeout=t.timeout;let r=await this.tasks.insertOne(i);return I(r)}async getTask(t){let i=await this.tasks.findOne({id:t});return i?I(i):void 0}async getAllTasks(){return(await this.tasks.find(void 0,{sort:{createdAt:-1}})).docs.map((t)=>I(t))}async getPendingTasks(){return(await this.tasks.find({status:"pending"},{sort:{createdAt:1}})).docs.map((t)=>I(t))}async updateTask(t,i){let r={};for(let[s,n]of Object.entries(i)){if(s==="id"||s==="createdAt"||s==="updatedAt")continue;r[s]=n??null}if(Object.keys(r).length===0)return;await this.tasks.updateOne({id:t},r)}async cancelTask(t){let i=await this.tasks.findOne({id:t});if(!i||i.status!=="pending"&&i.status!=="running")return!1;return await this.tasks.updateOne({id:t},{status:"failed",error:"Cancelled"}),!0}async getConfig(t){return(await this.config.findOne({key:t}))?.value}async setConfig(t,i){await this.config.upsert({key:t},{key:t,value:i})}async deleteConfig(t){return await this.config.deleteOne({key:t})!==null}async getAllConfig(){let t=await this.config.find(),i={};for(let r of t.docs)i[r.key]=r.value;return i}async bulkSetConfig(t){for(let[i,r]of Object.entries(t))await this.config.upsert({key:i},{key:i,value:r})}async getConfigStatus(){let t=await this.config.find(),i=null;for(let r of t.docs){let s=r.updatedAt,n=s instanceof Date?s.toISOString():typeof s==="string"?s:null;if(n&&(!i||n>i))i=n}return{totalKeys:t.docs.length,lastUpdated:i}}async createGitRepository(t){let i={id:t.id,path:t.path,name:t.name,isSubmodule:Boolean(t.isSubmodule),lastScanned:Cs()};if(t.parentPath!=null)i.parentPath=t.parentPath;if(t.projectType!=null)i.projectType=t.projectType;if(t.vitePort!=null)i.vitePort=t.vitePort;let r=await this.gitRepos.insertOne(i);return I(r)}async getGitRepository(t){let i=await this.gitRepos.findOne({id:t});return i?I(i):void 0}async getGitRepositoryByPath(t){let i=await this.gitRepos.findOne({path:t});return i?I(i):void 0}async getAllGitRepositories(){return(await this.gitRepos.find(void 0,{sort:{path:1}})).docs.map((t)=>I(t))}async updateGitRepository(t,i){let r={lastScanned:Cs()};for(let[s,n]of Object.entries(i)){if(s==="id"||s==="createdAt"||s==="updatedAt")continue;if(s==="isSubmodule"){r[s]=Boolean(n);continue}r[s]=n??null}await this.gitRepos.updateOne({id:t},r)}async deleteGitRepository(t){return await this.gitRepos.deleteOne({id:t})!==null}async fixGitHierarchy(){let t=await this.getAllGitRepositories(),i=0;for(let r of t){if(r.isSubmodule)continue;let s=t.find((n)=>n.id!==r.id&&r.path.startsWith(`${n.path}/`)&&!n.isSubmodule);if(s&&r.parentPath!==s.path)await this.updateGitRepository(r.id,{parentPath:s.path}),i++}return{fixed:i}}async createBookmarkedCommand(t){let i={id:t.id,command:t.command};if(t.projectId!=null)i.projectId=t.projectId;if(t.description!=null)i.description=t.description;if(t.category!=null)i.category=t.category;let r=await this.bookmarks.insertOne(i);return I(r)}async getBookmarkedCommand(t){let i=await this.bookmarks.findOne({id:t});return i?I(i):void 0}async getAllBookmarkedCommands(){return(await this.bookmarks.find(void 0,{sort:{createdAt:-1}})).docs.map((t)=>I(t))}async getBookmarkedCommandsByProject(t){let i=t===null?{projectId:{$fn:(r)=>r==null}}:{projectId:t};return(await this.bookmarks.find(i,{sort:{createdAt:-1}})).docs.map((r)=>I(r))}async getBookmarkedCommandsByCategory(t){return(await this.bookmarks.find({category:t},{sort:{createdAt:-1}})).docs.map((i)=>I(i))}async updateBookmarkedCommand(t,i){let r={};for(let[s,n]of Object.entries(i)){if(s==="id"||s==="createdAt"||s==="updatedAt")continue;r[s]=n??null}if(Object.keys(r).length===0)return;await this.bookmarks.updateOne({id:t},r)}async deleteBookmarkedCommand(t){return await this.bookmarks.deleteOne({id:t})!==null}async executeBookmarkedCommand(t){return this.getBookmarkedCommand(t)}async createNotification(t){let i={id:t.id,type:t.type,title:t.title,message:t.message,status:t.status};if(t.sessionName!=null)i.sessionName=t.sessionName;if(t.projectId!=null)i.projectId=t.projectId;let r=await this.notifications.insertOne(i);return I(r)}async getNotification(t){let i=await this.notifications.findOne({id:t});return i?I(i):void 0}async getAllNotifications(){return(await this.notifications.find(void 0,{sort:{createdAt:-1}})).docs.map((t)=>I(t))}async getNotificationsByProject(t){let i=t===null?{projectId:{$fn:(r)=>r==null}}:{projectId:t};return(await this.notifications.find(i,{sort:{createdAt:-1}})).docs.map((r)=>I(r))}async getGlobalNotifications(){return this.getNotificationsByProject(null)}async getUnreadNotifications(){return(await this.notifications.find({status:"unread"},{sort:{createdAt:-1}})).docs.map((t)=>I(t))}async updateNotificationStatus(t,i){await this.notifications.updateOne({id:t},{status:i})}async markAllNotificationsRead(){return(await this.notifications.updateMany({status:"unread"},{status:"read"})).length}async deleteNotification(t){return await this.notifications.deleteOne({id:t})!==null}async clearOldNotifications(t=30){let i=new Date(Date.now()-t*24*60*60*1000);return(await this.notifications.deleteMany({createdAt:{$fn:(r)=>r instanceof Date&&r<i}})).length}async getPluginState(t,i){return(await this.pluginState.findOne({$and:[{pluginName:t},{key:i}]}))?.value}async setPluginState(t,i,r){await this.pluginState.upsert({$and:[{pluginName:t},{key:i}]},{pluginName:t,key:i,value:r})}async deletePluginState(t,i){return await this.pluginState.deleteOne({$and:[{pluginName:t},{key:i}]})!==null}async getAllPluginState(t){return(await this.pluginState.find({pluginName:t},{sort:{key:1}})).docs.map((i)=>{let r=i.updatedAt,s=r instanceof Date?r.toISOString():typeof r==="string"?r:void 0;return{key:i.key,value:i.value,updatedAt:s}})}async deleteAllPluginState(t){return(await this.pluginState.deleteMany({pluginName:t})).length}}var La=(t)=>yr.create(t);ka("skalex",La);var nd=new Map;function Pa(t,i){nd.set(t,i)}class Ma{}Pa("skalex",La);var Ns=()=>new Date().toISOString();function R(t){if(!t)return t;let{_id:i,createdAt:r,updatedAt:s,_version:n,_expiresAt:a,...o}=t,c={...o};if(c.createdAt==null&&r!=null)c.createdAt=r instanceof Date?r.toISOString():String(r);if(c.updatedAt==null&&s!=null)c.updatedAt=s instanceof Date?s.toISOString():String(s);return c}class wr extends Ma{dataDir;encryptionKey;lockPath;lockFd=null;db;tasks;config;gitRepos;bookmarks;notifications;pluginState;constructor(t){super();this.dataDir=t.dataDir,this.encryptionKey=t.encryptionKey,this.lockPath=po(t.dataDir,".agent-db.lock")}static async create(t){if(!co(t.dataDir))uo(t.dataDir,{recursive:!0});let i=new wr(t);i.acquireLock();try{await i.init()}catch(r){throw i.releaseLock(),r}return i}acquireLock(){try{this.lockFd=ho(this.lockPath,"wx",384),_o(this.lockFd,JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()}));return}catch(i){if(i.code!=="EEXIST")throw i}let t=!1;try{let i=JSON.parse(fo(this.lockPath,"utf8"));if(!i.pid)t=!0;else try{process.kill(i.pid,0)}catch{t=!0}}catch{t=!0}if(t){try{$r(this.lockPath)}catch{}this.acquireLock();return}throw Error(`Agent database is already open by another process (${this.lockPath})`)}releaseLock(){if(this.lockFd!==null){try{lo(this.lockFd)}catch{}this.lockFd=null}try{$r(this.lockPath)}catch{}}async init(){this.db=new ue({path:this.dataDir,encrypt:{key:this.encryptionKey},autoSave:!0,format:"gz",lenientLoad:!0}),this.tasks=this.db.createCollection("tasks",{schema:{id:{type:"string",required:!0,unique:!0},type:{type:"string",required:!0,enum:["command","script","file_operation"]},status:{type:"string",required:!0,enum:["pending","running","completed","failed"]},payload:{type:"string",required:!0},result:{type:"string"},error:{type:"string"},calendarTaskId:{type:"string"},exitCode:{type:"number"},timeout:{type:"number"}},indexes:["status","type"]}),this.config=this.db.createCollection("agent_config",{schema:{key:{type:"string",required:!0,unique:!0},value:{type:"string",required:!0}}}),this.gitRepos=this.db.createCollection("git_repositories",{schema:{id:{type:"string",required:!0,unique:!0},path:{type:"string",required:!0,unique:!0},name:{type:"string",required:!0},parentPath:{type:"string"},isSubmodule:{type:"boolean"},projectType:{type:"string"},vitePort:{type:"number"},lastScanned:{type:"string"}},indexes:["parentPath"]}),this.bookmarks=this.db.createCollection("bookmarked_commands",{schema:{id:{type:"string",required:!0,unique:!0},projectId:{type:"string"},command:{type:"string",required:!0},description:{type:"string"},category:{type:"string"}},indexes:["projectId","category"]}),this.notifications=this.db.createCollection("notifications",{schema:{id:{type:"string",required:!0,unique:!0},sessionName:{type:"string"},projectId:{type:"string"},type:{type:"string",required:!0,enum:["info","success","warning","error"]},title:{type:"string",required:!0},message:{type:"string",required:!0},status:{type:"string",required:!0,enum:["unread","read"]}},indexes:["status","projectId"]}),this.pluginState=this.db.createCollection("plugin_state",{schema:{pluginName:{type:"string",required:!0},key:{type:"string",required:!0},value:{type:"string",required:!0}},indexes:["pluginName"]}),await this.db.connect()}async close(){if(this.db?.isConnected)await this.db.disconnect();this.releaseLock()}getDbPath(){return this.dataDir}async createTask(t){let i={id:t.id,type:t.type,status:t.status,payload:t.payload};if(t.result!=null)i.result=t.result;if(t.error!=null)i.error=t.error;if(t.calendarTaskId!=null)i.calendarTaskId=t.calendarTaskId;if(t.exitCode!=null)i.exitCode=t.exitCode;if(t.timeout!=null)i.timeout=t.timeout;let r=await this.tasks.insertOne(i);return R(r)}async getTask(t){let i=await this.tasks.findOne({id:t});return i?R(i):void 0}async getAllTasks(){return(await this.tasks.find(void 0,{sort:{createdAt:-1}})).docs.map((t)=>R(t))}async getPendingTasks(){return(await this.tasks.find({status:"pending"},{sort:{createdAt:1}})).docs.map((t)=>R(t))}async updateTask(t,i){let r={};for(let[s,n]of Object.entries(i)){if(s==="id"||s==="createdAt"||s==="updatedAt")continue;r[s]=n??null}if(Object.keys(r).length===0)return;await this.tasks.updateOne({id:t},r)}async cancelTask(t){let i=await this.tasks.findOne({id:t});if(!i||i.status!=="pending"&&i.status!=="running")return!1;return await this.tasks.updateOne({id:t},{status:"failed",error:"Cancelled"}),!0}async getConfig(t){return(await this.config.findOne({key:t}))?.value}async setConfig(t,i){await this.config.upsert({key:t},{key:t,value:i})}async deleteConfig(t){return await this.config.deleteOne({key:t})!==null}async getAllConfig(){let t=await this.config.find(),i={};for(let r of t.docs)i[r.key]=r.value;return i}async bulkSetConfig(t){for(let[i,r]of Object.entries(t))await this.config.upsert({key:i},{key:i,value:r})}async getConfigStatus(){let t=await this.config.find(),i=null;for(let r of t.docs){let s=r.updatedAt,n=s instanceof Date?s.toISOString():typeof s==="string"?s:null;if(n&&(!i||n>i))i=n}return{totalKeys:t.docs.length,lastUpdated:i}}async createGitRepository(t){let i={id:t.id,path:t.path,name:t.name,isSubmodule:Boolean(t.isSubmodule),lastScanned:Ns()};if(t.parentPath!=null)i.parentPath=t.parentPath;if(t.projectType!=null)i.projectType=t.projectType;if(t.vitePort!=null)i.vitePort=t.vitePort;let r=await this.gitRepos.insertOne(i);return R(r)}async getGitRepository(t){let i=await this.gitRepos.findOne({id:t});return i?R(i):void 0}async getGitRepositoryByPath(t){let i=await this.gitRepos.findOne({path:t});return i?R(i):void 0}async getAllGitRepositories(){return(await this.gitRepos.find(void 0,{sort:{path:1}})).docs.map((t)=>R(t))}async updateGitRepository(t,i){let r={lastScanned:Ns()};for(let[s,n]of Object.entries(i)){if(s==="id"||s==="createdAt"||s==="updatedAt")continue;if(s==="isSubmodule"){r[s]=Boolean(n);continue}r[s]=n??null}await this.gitRepos.updateOne({id:t},r)}async deleteGitRepository(t){return await this.gitRepos.deleteOne({id:t})!==null}async fixGitHierarchy(){let t=await this.getAllGitRepositories(),i=0;for(let r of t){if(r.isSubmodule)continue;let s=t.find((n)=>n.id!==r.id&&r.path.startsWith(`${n.path}/`)&&!n.isSubmodule);if(s&&r.parentPath!==s.path)await this.updateGitRepository(r.id,{parentPath:s.path}),i++}return{fixed:i}}async createBookmarkedCommand(t){let i={id:t.id,command:t.command};if(t.projectId!=null)i.projectId=t.projectId;if(t.description!=null)i.description=t.description;if(t.category!=null)i.category=t.category;let r=await this.bookmarks.insertOne(i);return R(r)}async getBookmarkedCommand(t){let i=await this.bookmarks.findOne({id:t});return i?R(i):void 0}async getAllBookmarkedCommands(){return(await this.bookmarks.find(void 0,{sort:{createdAt:-1}})).docs.map((t)=>R(t))}async getBookmarkedCommandsByProject(t){let i=t===null?{projectId:{$fn:(r)=>r==null}}:{projectId:t};return(await this.bookmarks.find(i,{sort:{createdAt:-1}})).docs.map((r)=>R(r))}async getBookmarkedCommandsByCategory(t){return(await this.bookmarks.find({category:t},{sort:{createdAt:-1}})).docs.map((i)=>R(i))}async updateBookmarkedCommand(t,i){let r={};for(let[s,n]of Object.entries(i)){if(s==="id"||s==="createdAt"||s==="updatedAt")continue;r[s]=n??null}if(Object.keys(r).length===0)return;await this.bookmarks.updateOne({id:t},r)}async deleteBookmarkedCommand(t){return await this.bookmarks.deleteOne({id:t})!==null}async executeBookmarkedCommand(t){return this.getBookmarkedCommand(t)}async createNotification(t){let i={id:t.id,type:t.type,title:t.title,message:t.message,status:t.status};if(t.sessionName!=null)i.sessionName=t.sessionName;if(t.projectId!=null)i.projectId=t.projectId;let r=await this.notifications.insertOne(i);return R(r)}async getNotification(t){let i=await this.notifications.findOne({id:t});return i?R(i):void 0}async getAllNotifications(){return(await this.notifications.find(void 0,{sort:{createdAt:-1}})).docs.map((t)=>R(t))}async getNotificationsByProject(t){let i=t===null?{projectId:{$fn:(r)=>r==null}}:{projectId:t};return(await this.notifications.find(i,{sort:{createdAt:-1}})).docs.map((r)=>R(r))}async getGlobalNotifications(){return this.getNotificationsByProject(null)}async getUnreadNotifications(){return(await this.notifications.find({status:"unread"},{sort:{createdAt:-1}})).docs.map((t)=>R(t))}async updateNotificationStatus(t,i){await this.notifications.updateOne({id:t},{status:i})}async markAllNotificationsRead(){return(await this.notifications.updateMany({status:"unread"},{status:"read"})).length}async deleteNotification(t){return await this.notifications.deleteOne({id:t})!==null}async clearOldNotifications(t=30){let i=new Date(Date.now()-t*24*60*60*1000);return(await this.notifications.deleteMany({createdAt:{$fn:(r)=>r instanceof Date&&r<i}})).length}async getPluginState(t,i){return(await this.pluginState.findOne({$and:[{pluginName:t},{key:i}]}))?.value}async setPluginState(t,i,r){await this.pluginState.upsert({$and:[{pluginName:t},{key:i}]},{pluginName:t,key:i,value:r})}async deletePluginState(t,i){return await this.pluginState.deleteOne({$and:[{pluginName:t},{key:i}]})!==null}async getAllPluginState(t){return(await this.pluginState.find({pluginName:t},{sort:{key:1}})).docs.map((i)=>{let r=i.updatedAt,s=r instanceof Date?r.toISOString():typeof r==="string"?r:void 0;return{key:i.key,value:i.value,updatedAt:s}})}async deleteAllPluginState(t){return(await this.pluginState.deleteMany({pluginName:t})).length}}var ja=(t)=>wr.create(t);Pa("skalex",ja);var ad=new Map;function qa(t,i){ad.set(t,i)}class Ua{}qa("skalex",ja);var $s=()=>new Date().toISOString();function k(t){if(!t)return t;let{_id:i,createdAt:r,updatedAt:s,_version:n,_expiresAt:a,...o}=t,c={...o};if(c.createdAt==null&&r!=null)c.createdAt=r instanceof Date?r.toISOString():String(r);if(c.updatedAt==null&&s!=null)c.updatedAt=s instanceof Date?s.toISOString():String(s);return c}class Ar extends Ua{dataDir;encryptionKey;lockPath;lockFd=null;db;tasks;config;gitRepos;bookmarks;notifications;pluginState;constructor(t){super();this.dataDir=t.dataDir,this.encryptionKey=t.encryptionKey,this.lockPath=no(t.dataDir,".agent-db.lock")}static async create(t){if(!eo(t.dataDir))to(t.dataDir,{recursive:!0});let i=new Ar(t);i.acquireLock();try{await i.init()}catch(r){throw i.releaseLock(),r}return i}acquireLock(){try{this.lockFd=io(this.lockPath,"wx",384),so(this.lockFd,JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()}));return}catch(i){if(i.code!=="EEXIST")throw i}let t=!1;try{let i=JSON.parse(ro(this.lockPath,"utf8"));if(!i.pid)t=!0;else try{process.kill(i.pid,0)}catch{t=!0}}catch{t=!0}if(t){try{Nr(this.lockPath)}catch{}this.acquireLock();return}throw Error(`Agent database is already open by another process (${this.lockPath})`)}releaseLock(){if(this.lockFd!==null){try{Za(this.lockFd)}catch{}this.lockFd=null}try{Nr(this.lockPath)}catch{}}async init(){this.db=new de({path:this.dataDir,encrypt:{key:this.encryptionKey},autoSave:!0,format:"gz",lenientLoad:!0}),this.tasks=this.db.createCollection("tasks",{schema:{id:{type:"string",required:!0,unique:!0},type:{type:"string",required:!0,enum:["command","script","file_operation"]},status:{type:"string",required:!0,enum:["pending","running","completed","failed"]},payload:{type:"string",required:!0},result:{type:"string"},error:{type:"string"},calendarTaskId:{type:"string"},exitCode:{type:"number"},timeout:{type:"number"}},indexes:["status","type"]}),this.config=this.db.createCollection("agent_config",{schema:{key:{type:"string",required:!0,unique:!0},value:{type:"string",required:!0}}}),this.gitRepos=this.db.createCollection("git_repositories",{schema:{id:{type:"string",required:!0,unique:!0},path:{type:"string",required:!0,unique:!0},name:{type:"string",required:!0},parentPath:{type:"string"},isSubmodule:{type:"boolean"},projectType:{type:"string"},vitePort:{type:"number"},lastScanned:{type:"string"}},indexes:["parentPath"]}),this.bookmarks=this.db.createCollection("bookmarked_commands",{schema:{id:{type:"string",required:!0,unique:!0},projectId:{type:"string"},command:{type:"string",required:!0},description:{type:"string"},category:{type:"string"}},indexes:["projectId","category"]}),this.notifications=this.db.createCollection("notifications",{schema:{id:{type:"string",required:!0,unique:!0},sessionName:{type:"string"},projectId:{type:"string"},type:{type:"string",required:!0,enum:["info","success","warning","error"]},title:{type:"string",required:!0},message:{type:"string",required:!0},status:{type:"string",required:!0,enum:["unread","read"]}},indexes:["status","projectId"]}),this.pluginState=this.db.createCollection("plugin_state",{schema:{pluginName:{type:"string",required:!0},key:{type:"string",required:!0},value:{type:"string",required:!0}},indexes:["pluginName"]}),await this.db.connect()}async close(){if(this.db?.isConnected)await this.db.disconnect();this.releaseLock()}getDbPath(){return this.dataDir}async createTask(t){let i={id:t.id,type:t.type,status:t.status,payload:t.payload};if(t.result!=null)i.result=t.result;if(t.error!=null)i.error=t.error;if(t.calendarTaskId!=null)i.calendarTaskId=t.calendarTaskId;if(t.exitCode!=null)i.exitCode=t.exitCode;if(t.timeout!=null)i.timeout=t.timeout;let r=await this.tasks.insertOne(i);return k(r)}async getTask(t){let i=await this.tasks.findOne({id:t});return i?k(i):void 0}async getAllTasks(){return(await this.tasks.find(void 0,{sort:{createdAt:-1}})).docs.map((t)=>k(t))}async getPendingTasks(){return(await this.tasks.find({status:"pending"},{sort:{createdAt:1}})).docs.map((t)=>k(t))}async updateTask(t,i){let r={};for(let[s,n]of Object.entries(i)){if(s==="id"||s==="createdAt"||s==="updatedAt")continue;r[s]=n??null}if(Object.keys(r).length===0)return;await this.tasks.updateOne({id:t},r)}async cancelTask(t){let i=await this.tasks.findOne({id:t});if(!i||i.status!=="pending"&&i.status!=="running")return!1;return await this.tasks.updateOne({id:t},{status:"failed",error:"Cancelled"}),!0}async getConfig(t){return(await this.config.findOne({key:t}))?.value}async setConfig(t,i){await this.config.upsert({key:t},{key:t,value:i})}async deleteConfig(t){return await this.config.deleteOne({key:t})!==null}async getAllConfig(){let t=await this.config.find(),i={};for(let r of t.docs)i[r.key]=r.value;return i}async bulkSetConfig(t){for(let[i,r]of Object.entries(t))await this.config.upsert({key:i},{key:i,value:r})}async getConfigStatus(){let t=await this.config.find(),i=null;for(let r of t.docs){let s=r.updatedAt,n=s instanceof Date?s.toISOString():typeof s==="string"?s:null;if(n&&(!i||n>i))i=n}return{totalKeys:t.docs.length,lastUpdated:i}}async createGitRepository(t){let i={id:t.id,path:t.path,name:t.name,isSubmodule:Boolean(t.isSubmodule),lastScanned:$s()};if(t.parentPath!=null)i.parentPath=t.parentPath;if(t.projectType!=null)i.projectType=t.projectType;if(t.vitePort!=null)i.vitePort=t.vitePort;let r=await this.gitRepos.insertOne(i);return k(r)}async getGitRepository(t){let i=await this.gitRepos.findOne({id:t});return i?k(i):void 0}async getGitRepositoryByPath(t){let i=await this.gitRepos.findOne({path:t});return i?k(i):void 0}async getAllGitRepositories(){return(await this.gitRepos.find(void 0,{sort:{path:1}})).docs.map((t)=>k(t))}async updateGitRepository(t,i){let r={lastScanned:$s()};for(let[s,n]of Object.entries(i)){if(s==="id"||s==="createdAt"||s==="updatedAt")continue;if(s==="isSubmodule"){r[s]=Boolean(n);continue}r[s]=n??null}await this.gitRepos.updateOne({id:t},r)}async deleteGitRepository(t){return await this.gitRepos.deleteOne({id:t})!==null}async fixGitHierarchy(){let t=await this.getAllGitRepositories(),i=0;for(let r of t){if(r.isSubmodule)continue;let s=t.find((n)=>n.id!==r.id&&r.path.startsWith(`${n.path}/`)&&!n.isSubmodule);if(s&&r.parentPath!==s.path)await this.updateGitRepository(r.id,{parentPath:s.path}),i++}return{fixed:i}}async createBookmarkedCommand(t){let i={id:t.id,command:t.command};if(t.projectId!=null)i.projectId=t.projectId;if(t.description!=null)i.description=t.description;if(t.category!=null)i.category=t.category;let r=await this.bookmarks.insertOne(i);return k(r)}async getBookmarkedCommand(t){let i=await this.bookmarks.findOne({id:t});return i?k(i):void 0}async getAllBookmarkedCommands(){return(await this.bookmarks.find(void 0,{sort:{createdAt:-1}})).docs.map((t)=>k(t))}async getBookmarkedCommandsByProject(t){let i=t===null?{projectId:{$fn:(r)=>r==null}}:{projectId:t};return(await this.bookmarks.find(i,{sort:{createdAt:-1}})).docs.map((r)=>k(r))}async getBookmarkedCommandsByCategory(t){return(await this.bookmarks.find({category:t},{sort:{createdAt:-1}})).docs.map((i)=>k(i))}async updateBookmarkedCommand(t,i){let r={};for(let[s,n]of Object.entries(i)){if(s==="id"||s==="createdAt"||s==="updatedAt")continue;r[s]=n??null}if(Object.keys(r).length===0)return;await this.bookmarks.updateOne({id:t},r)}async deleteBookmarkedCommand(t){return await this.bookmarks.deleteOne({id:t})!==null}async executeBookmarkedCommand(t){return this.getBookmarkedCommand(t)}async createNotification(t){let i={id:t.id,type:t.type,title:t.title,message:t.message,status:t.status};if(t.sessionName!=null)i.sessionName=t.sessionName;if(t.projectId!=null)i.projectId=t.projectId;let r=await this.notifications.insertOne(i);return k(r)}async getNotification(t){let i=await this.notifications.findOne({id:t});return i?k(i):void 0}async getAllNotifications(){return(await this.notifications.find(void 0,{sort:{createdAt:-1}})).docs.map((t)=>k(t))}async getNotificationsByProject(t){let i=t===null?{projectId:{$fn:(r)=>r==null}}:{projectId:t};return(await this.notifications.find(i,{sort:{createdAt:-1}})).docs.map((r)=>k(r))}async getGlobalNotifications(){return this.getNotificationsByProject(null)}async getUnreadNotifications(){return(await this.notifications.find({status:"unread"},{sort:{createdAt:-1}})).docs.map((t)=>k(t))}async updateNotificationStatus(t,i){await this.notifications.updateOne({id:t},{status:i})}async markAllNotificationsRead(){return(await this.notifications.updateMany({status:"unread"},{status:"read"})).length}async deleteNotification(t){return await this.notifications.deleteOne({id:t})!==null}async clearOldNotifications(t=30){let i=new Date(Date.now()-t*24*60*60*1000);return(await this.notifications.deleteMany({createdAt:{$fn:(r)=>r instanceof Date&&r<i}})).length}async getPluginState(t,i){return(await this.pluginState.findOne({$and:[{pluginName:t},{key:i}]}))?.value}async setPluginState(t,i,r){await this.pluginState.upsert({$and:[{pluginName:t},{key:i}]},{pluginName:t,key:i,value:r})}async deletePluginState(t,i){return await this.pluginState.deleteOne({$and:[{pluginName:t},{key:i}]})!==null}async getAllPluginState(t){return(await this.pluginState.find({pluginName:t},{sort:{key:1}})).docs.map((i)=>{let r=i.updatedAt,s=r instanceof Date?r.toISOString():typeof r==="string"?r:void 0;return{key:i.key,value:i.value,updatedAt:s}})}async deleteAllPluginState(t){return(await this.pluginState.deleteMany({pluginName:t})).length}}var Fa=(t)=>Ar.create(t);qa("skalex",Fa);var vr=new Map;function od(t,i){vr.set(t,i)}function ks(t){return vr.get(t)}function ld(){return Array.from(vr.keys())}async function cd(t){if(t.adapterFactory)return t.adapterFactory;let i=t.adapterName??process.env.VIBE_STORAGE_ADAPTER??"skalex";if(i.startsWith("custom:")){let s=i.slice(7);if(!s)throw Error("VIBE_STORAGE_ADAPTER=custom: requires a module path after the colon");let n=await import(s),a=n.default??n.createAdapter;if(typeof a!=="function")throw Error(`Custom storage adapter at ${s} must export a default function (or \`createAdapter\`) of type AgentStorageAdapterFactory`);return a}let r=ks(i);if(!r){let s={skalex:"@vibecontrols/vibe-plugin-storage-skalex",postgres:"@vibecontrols/vibe-plugin-storage-postgres",postgresql:"@vibecontrols/vibe-plugin-storage-postgres"}[i];if(s)try{await import(s),r=ks(i)}catch{}}if(!r)throw Error(`Unknown storage adapter: "${i}". Registered adapters: ${ld().join(", ")||`(none \u2014 did you install @vibecontrols/vibe-plugin-storage-${i})?`}`);return r}async function Jt(t){if(!t.encryptionKey)throw Error("createAgentDatabase(): encryptionKey is required. Storage is always encrypted at rest.");if(!t.dbPath)throw Error("createAgentDatabase(): dbPath is required.");return(await cd(t))({dataDir:t.dbPath,encryptionKey:t.encryptionKey,adapterOptions:t.adapterOptions})}od("skalex",Fa);var dd="@vibecontrols/vibe-plugin-storage",yu=ud();function ud(){try{let t=Ei(Qa(import.meta.url));for(let i=0;i<10&&t&&t!==Ei(t);i++){let r=Ya(t,"package.json");if(Wa(r))try{let s=JSON.parse(Ja(r,"utf8"));if(s.name===dd&&typeof s.version==="string")return s.version}catch{}t=Ei(t)}}catch{}return"0.0.0"}import mi from"os";import{mkdirSync as Id}from"fs";import{join as bd}from"path";var Er=[0,5000,15000,30000,60000],hd=2000,fd=5000,_d=120000,Ka=10,pd=1048576;class xr extends Error{resetAt;resource;constructor(t,i,r){super(t);this.name="RateLimitError",this.resource=i,this.resetAt=r}}function Sr(t,i){if(!t?.length)return null;let r=t.find((a)=>a.extensions?.code==="RATE_LIMITED");if(!r)return null;let s=r.extensions?.resetAt,n=null;if(s){let a=new Date(s);if(!Number.isNaN(a.getTime()))n=a}return new xr(`${i} rate limited${n?` until ${n.toISOString()}`:""}`,i,n)}function gd(t){if(!t.resetAt)return 60000;let i=t.resetAt.getTime()-Date.now()+hd;return Math.min(Math.max(i,fd),_d)}async function md(t,i){let r=t.headers.get("content-length");if(r){let l=Number.parseInt(r,10);if(Number.isInteger(l)&&l>i)throw Error(`Gateway response is too large (${l} bytes)`)}if(!t.body)return"";let s=t.body.getReader(),n=[],a=0;try{while(!0){let{done:l,value:d}=await s.read();if(l)break;if(!d)continue;if(a+=d.byteLength,a>i)throw await s.cancel().catch(()=>{return}),Error(`Gateway response exceeds ${i} bytes`);n.push(d)}}finally{s.releaseLock()}let o=new Uint8Array(a),c=0;for(let l of n)o.set(l,c),c+=l.byteLength;return new TextDecoder().decode(o)}async function Ir(t,i){let r=await md(t,pd),s;try{s=r?JSON.parse(r):{}}catch(n){let a=r.slice(0,240).replace(/\s+/g," ");throw Error(`${i} returned non-JSON response (${t.status} ${t.statusText})${a?`: ${a}`:""}`,{cause:n})}if(!t.ok){let n=r.slice(0,240).replace(/\s+/g," ");throw Error(`${i} failed (${t.status} ${t.statusText})${n?`: ${n}`:""}`)}return s}function br(t){return t.endsWith("/graphql")?t:`${t}/graphql`}function yd(t){let i;try{i=new URL(t).hostname.toLowerCase().replace(/^\[|\]$/g,"")}catch{return!1}if(i==="localhost"||i==="127.0.0.1"||i==="::1"||i==="0.0.0.0"||i==="host.docker.internal")return!0;return i.endsWith(".localhost")||i.endsWith(".local")||i.endsWith(".local.burdenoff.com")}function Tr(t){if(!(process.env.VIBE_DEV_INSECURE_TLS==="1"||process.env.NODE_TLS_REJECT_UNAUTHORIZED==="0")&&!yd(t))return{};return{tls:{rejectUnauthorized:!1}}}async function wd(t,i,r){let s=await fetch(br(t),{method:"POST",...Tr(t),headers:{"Content-Type":"application/json"},body:JSON.stringify({query:`mutation AuthenticateApp($input: AuthenticateAppInput!) {
|
|
106
|
+
`))!==-1){let r=this._buffer.slice(0,i).trim();if(this._buffer=this._buffer.slice(i+1),r&&this._onMessage){let s;try{s=JSON.parse(r)}catch(n){this.send(Xe(null,gr,"Parse error"));continue}this._onMessage(s).catch(()=>{})}}}),process.stdin.on("end",()=>{process.exit(0)})}stop(){process.stdin.removeAllListeners("data"),process.stdin.removeAllListeners("end"),this._started=!1}}var td={name:"skalex",version:"4.0.0-alpha"},id="2024-11-05";class Na{constructor(t,i={}){this._db=t,this._transport=i.transport||"stdio",this._port=i.port||3000,this._host=i.host||"127.0.0.1",this._allowedOrigin=i.allowedOrigin??null,this._maxBodySize=i.maxBodySize??1048576,this._scopes=i.scopes||{"*":["read"]},this._t=null}async listen(){if(this._transport==="http")this._t=new Ra({port:this._port,host:this._host,allowedOrigin:this._allowedOrigin,maxBodySize:this._maxBodySize});else this._t=new Ca;this._t.onMessage((t)=>this._handleMessage(t)),await this._t.start()}async connect(t){if(this._t=t,this._t.onMessage((i)=>this._handleMessage(i)),typeof this._t.start==="function")await this._t.start()}async close(){if(this._t&&typeof this._t.stop==="function")await this._t.stop();this._t=null}get transport(){return this._transport}get url(){return this._t?.url}async _handleMessage(t){let{msg:i,parseError:r}=typeof t==="string"?Zc(t):{msg:t};if(r){this._send(r);return}let{id:s,method:n,params:a}=i;if(s===void 0){if(n==="notifications/initialized")return;return}try{switch(n){case"initialize":this._send(It(s,{protocolVersion:id,capabilities:{tools:{}},serverInfo:td}));break;case"tools/list":this._send(It(s,{tools:this._visibleTools()}));break;case"tools/call":await this._handleToolCall(s,a);break;case"ping":this._send(It(s,{}));break;default:this._send(Xe(s,bs,`Method not found: ${n}`))}}catch(o){this._send(Xe(s,Qc,o.message||"Internal error"))}}async _handleToolCall(t,i){let r=i?.name,s=i?.arguments??{};if(!r){this._send(Xe(t,Yc,"tools/call requires params.name"));return}let n=Is.find((o)=>o.name===r);if(!n){this._send(Xe(t,bs,`Unknown tool: ${r}`));return}let a=s.collection||s.collection_name||null;if(!this._hasScope(a,n.scope)){this._send(It(t,Ts(`Access denied: "${r}" requires "${n.scope}" scope on collection "${a}".`)));return}try{let o=await Wc(r,s,this._db);this._send(It(t,ed(JSON.stringify(o,null,2))))}catch(o){this._send(It(t,Ts(o.message||String(o))))}}_visibleTools(){return Is.filter((t)=>{let i=this._scopes["*"];if(i&&(i.includes(t.scope)||i.includes("admin")))return!0;for(let[,r]of Object.entries(this._scopes))if(r.includes(t.scope)||r.includes("admin"))return!0;return!1})}_hasScope(t,i){let r=(s)=>s.includes("admin")||s.includes(i);if(t&&this._scopes[t])return r(this._scopes[t]);if(this._scopes["*"])return r(this._scopes["*"]);return!1}_send(t){this._t?.send(t)}}var Jt="migrations",Os=(t)=>JSON.stringify(t,function(i,r){let s=this[i];if(s instanceof Date)return{__skalex_date__:s.toISOString()};if(typeof r==="bigint")return{__skalex_bigint__:r.toString()};return r}),Rs=(t)=>JSON.parse(t,(i,r)=>{if(r&&typeof r==="object"){if("__skalex_bigint__"in r)return BigInt(r.__skalex_bigint__);if("__skalex_date__"in r)return new Date(r.__skalex_date__)}return r});class fe{constructor({path:t="./.db",format:i="gz",debug:r=!1,adapter:s,ai:n,encrypt:a,slowQueryLog:o,queryCache:c,memory:l,logger:d,plugins:u,llmAdapter:f,embeddingAdapter:h,regexMaxLength:_,idGenerator:p,serializer:g,deserializer:m,autoSave:w,ttlSweepInterval:v,lenientLoad:q}={}){if(this.dataDirectory=t,this.dataFormat=i,this.debug=r,!fe._errorsAttached)fe.SkalexError=Ze,fe.ValidationError=j,fe.UniqueConstraintError=Ue,fe.TransactionError=ke,fe.PersistenceError=We,fe.AdapterError=Re,fe.QueryError=pt,fe._errorsAttached=!0;this._adapterConfig=s??null;let E=s||new ua({dir:t,format:i});if(a)E=new va(E,a.key);if(this.fs=E,this._registry=new pa(da),this.collections=this._registry.stores,this._collectionInstances=this._registry._instances,this._migrations=new ha,this._connectPromise=null,this.isConnected=!1,this._aiConfig=n||null,this._encryptConfig=a||null,this._pluginsConfig=Array.isArray(u)?u:null,this._memoryConfig=l||null,this._regexMaxLength=_??500,this._idGenerator=p??null,this._serializer=g??Os,this._deserializer=m??Rs,this._autoSave=w??!1,this._txManager=new _a,this._ttlSweepInterval=v??0,this._ttlTimer=null,this._logger=d??ys,this._embeddingAdapter=h??(n?Mc(n):null),this._aiAdapter=f??(n?jc(n):null),this._persistence=new fa({adapter:this.fs,serializer:this._serializer,deserializer:this._deserializer,logger:this._logger,debug:this.debug,lenientLoad:q??!1}),this._changeLog=new xa(this),this._queryCache=new Sa(c||{}),this._eventBus=new Ia,this._queryLog=o?new ba(o):null,this._sessionStats=new Ta,this._plugins=new Oa,Array.isArray(u))for(let A of u)this._plugins.register(A)}async connect(){if(this._connectPromise)return this._connectPromise;return this._connectPromise=this._doConnect(),this._connectPromise}async _doConnect(){try{await this.loadData();let t=this._getMeta();if(t.queryCache)this._queryCache.fromJSON(t.queryCache);if(this._migrations._migrations.length>0){let i=t.appliedVersions||[],r=await this._migrations.run((s)=>this.useCollection(`_migration_${s}`),i);this._saveMeta({appliedVersions:r})}if(this._sweepTtl(),this._ttlSweepInterval>0){if(this._ttlTimer=setInterval(()=>this._sweepTtl(),this._ttlSweepInterval),this._ttlTimer?.unref)this._ttlTimer.unref()}this.isConnected=!0,this._log("> - Connected to the database (\u221A)")}catch(t){throw this._logger(`Error connecting to the database: ${t}`,"error"),t}}async disconnect(){try{if(this._ttlTimer)clearInterval(this._ttlTimer),this._ttlTimer=null;await this.saveData(),this._registry.clear(),this.collections=this._registry.stores,this._collectionInstances=this._registry._instances,this._connectPromise=null,this.isConnected=!1,this._log("> - Disconnected from the database (\u221A)")}catch(t){throw this._logger(`Error disconnecting from the database: ${t}`,"error"),t}}async _ensureConnected(){if(this.isConnected)return;return this.connect()}useCollection(t){return this._registry.get(t,this)}createCollection(t,i={}){return this._registry.create(t,i,this)}_createCollectionStore(t,i={}){this._registry.createStore(t,i)}async renameCollection(t,i){this._registry.rename(t,i),await this.saveData(i),await this.fs.delete(t)}async loadData(){await this._persistence.loadAll(this.collections,{parseSchema:aa,buildIndex:this._registry.buildIndex,IndexEngine:ei});for(let t in this._collectionInstances){let i=this.collections[t];if(i&&this._collectionInstances[t]._store!==i)this._collectionInstances[t]._store=i}}async saveData(t){await this._persistence.save(this.collections,t)}buildIndex(t,i){return this._registry.buildIndex(t,i)}addMigration(t){this._migrations.add(t)}migrationStatus(){let t=this._getMeta();return this._migrations.status(t.appliedVersions||[])}namespace(t){if(this._adapterConfig)throw new Re("ERR_SKALEX_ADAPTER_NAMESPACE_REQUIRES_FS","namespace() requires the default FsAdapter. When a custom storage adapter is configured, create a separate Skalex instance with your adapter instead.");let i=String(t).replace(/[^a-zA-Z0-9_-]/g,"_");if(!i)throw new j("ERR_SKALEX_VALIDATION_NAMESPACE_ID","namespace: id must contain at least one alphanumeric character",{id:t});return new fe({path:`${this.dataDirectory}/${i}`,format:this.dataFormat,debug:this.debug,ai:this._aiConfig||void 0,encrypt:this._encryptConfig||void 0,slowQueryLog:this._queryLog?{threshold:this._queryLog._threshold,maxEntries:this._queryLog._maxEntries}:void 0,queryCache:this._queryCache?{maxSize:this._queryCache._maxSize,ttl:this._queryCache._ttl}:void 0,plugins:this._pluginsConfig||void 0,memory:this._memoryConfig||void 0,logger:this._logger!==ys?this._logger:void 0,llmAdapter:this._aiAdapter&&!this._aiConfig?this._aiAdapter:void 0,embeddingAdapter:this._embeddingAdapter&&!this._aiConfig?this._embeddingAdapter:void 0,regexMaxLength:this._regexMaxLength!==500?this._regexMaxLength:void 0,idGenerator:this._idGenerator||void 0,serializer:this._serializer!==Os?this._serializer:void 0,deserializer:this._deserializer!==Rs?this._deserializer:void 0,autoSave:this._autoSave||void 0,ttlSweepInterval:this._ttlSweepInterval||void 0})}use(t){this._plugins.register(t)}watch(t){return this._eventBus.on("*",t)}sessionStats(t){if(t!==void 0)return this._sessionStats.get(t);return this._sessionStats.all()}get _inTransaction(){return this._txManager.active}_emitEvent(t,i){if(!this._txManager.defer(()=>this._eventBus.emit(t,i)))this._eventBus.emit(t,i)}async _runAfterHook(t,i){if(!this._txManager.defer(()=>this._plugins.run(t,i)))await this._plugins.run(t,i)}async _logChange(t,i,r,s,n){if(!this._txManager.defer(()=>this._changeLog.log(t,i,r,s,n)))await this._changeLog.log(t,i,r,s,n)}async transaction(t,i={}){return this._txManager.run(t,this,i)}async seed(t,{reset:i=!1}={}){for(let[r,s]of Object.entries(t)){if(i&&this.collections[r])this._applySnapshot(r,{data:[],index:new Map}),delete this._collectionInstances[r];await this.useCollection(r).insertMany(s)}await this.saveData()}dump(){return this._registry.dump()}inspect(t){return this._registry.inspect(t)}async import(t){let i=await this.fs.readRaw(t),r;try{r=JSON.parse(i)}catch{throw new We("ERR_SKALEX_PERSISTENCE_INVALID_JSON",`import: invalid JSON in file "${t}"`,{filePath:t})}let s=t.split("/").pop().replace(/\.[^.]+$/,"");return this.useCollection(s).insertMany(Array.isArray(r)?r:[r],{save:!0})}async embed(t){if(!this._embeddingAdapter)throw new Re("ERR_SKALEX_ADAPTER_EMBEDDING_REQUIRED","db.embed() requires an AI adapter. Pass { ai: { provider, apiKey } } to the Skalex constructor.");return this._embeddingAdapter.embed(t)}async ask(t,i,{limit:r=20}={}){if(!this._aiAdapter)throw new Re("ERR_SKALEX_ADAPTER_LLM_REQUIRED",'db.ask() requires a language model adapter. Configure { ai: { provider, model: "..." } }.');let s=this.useCollection(t),n=this.schema(t),a=this._queryCache.get(t,n,i);if(!a){a=await this._aiAdapter.generate(n,i);let o=Hc(a,n);if(o.length)o.forEach((c)=>this._log(`[ask] ${c}`));this._queryCache.set(t,n,i,a),this._saveMeta({queryCache:this._queryCache.toJSON()})}return s.find(Vc(a,{regexMaxLength:this._regexMaxLength}),{limit:r})}schema(t){return this._registry.schema(t)}useMemory(t){return new Ea(t,this)}changelog(){return this._changeLog}async restore(t,i,r={}){return this._changeLog.restore(t,i,r)}stats(t){return this._registry.stats(t)}slowQueries(t={}){if(!this._queryLog)return[];return this._queryLog.entries(t)}slowQueryCount(){return this._queryLog?this._queryLog.size:0}clearSlowQueries(){this._queryLog?.clear()}mcp(t={}){return new Na(this,t)}_getMeta(){let t=this.collections._meta;if(!t)return{};return t.index.get(Jt)||{}}_saveMeta(t){if(!this.collections._meta)this._createCollectionStore("_meta");let i=this.collections._meta,r=i.index.get(Jt);if(r)Object.assign(r,t);else{let s={_id:Jt,...t};i.data.push(s),i.index.set(Jt,s)}this._persistence.markDirty(this.collections,"_meta")}_sweepTtl(){for(let t in this.collections){let i=this.collections[t],r=Cc(i.data,i.index,i.fieldIndex?(s)=>i.fieldIndex.remove(s):null);if(r>0)this._persistence.markDirty(this.collections,t),this._log(`TTL sweep: removed ${r} expired docs from "${t}"`)}}_buildCollectionContext(){let t=this;return{ensureConnected:()=>t._ensureConnected(),get txManager(){return t._txManager},get plugins(){return t._plugins},get eventBus(){return t._eventBus},get sessionStats(){return t._sessionStats},get queryLog(){return t._queryLog},get logger(){return t._logger},get persistence(){return t._persistence},get collections(){return t.collections},embed:(i)=>t.embed(i),get idGenerator(){return t._idGenerator},get autoSave(){return t._autoSave},saveCollection:(i)=>t.saveData(i),snapshotCollection:(i)=>t._snapshotCollection(i),getCollection:(i)=>t.useCollection(i),emitEvent:(i,r)=>t._emitEvent(i,r),runAfterHook:(i,r)=>t._runAfterHook(i,r),logChange:(i,r,s,n,a)=>t._logChange(i,r,s,n,a),get fs(){return t.fs},get dataDirectory(){return t.dataDirectory}}}_log(t){if(this.debug)this._logger(t,"info")}_snapshotCollection(t){return{data:structuredClone(t.data)}}_applySnapshot(t,i){let r=this.collections[t];if(!r)return;if(r.data=i.data,r.index=this.buildIndex(i.data,"_id"),r.fieldIndex)r.fieldIndex.buildFromData(i.data)}}class $a{}var rd=new Map;function sd(t,i){rd.set(t,i)}var Cs=()=>new Date().toISOString();function S(t){if(!t)return t;let{_id:i,createdAt:r,updatedAt:s,_version:n,_expiresAt:a,...o}=t,c={...o};if(c.createdAt==null&&r!=null)c.createdAt=r instanceof Date?r.toISOString():String(r);if(c.updatedAt==null&&s!=null)c.updatedAt=s instanceof Date?s.toISOString():String(s);return c}class mr extends $a{dataDir;encryptionKey;lockPath;lockFd=null;db;tasks;config;gitRepos;bookmarks;notifications;pluginState;constructor(t){super();this.dataDir=t.dataDir,this.encryptionKey=t.encryptionKey,this.lockPath=Do(t.dataDir,".agent-db.lock")}static async create(t){if(!Ro(t.dataDir))Co(t.dataDir,{recursive:!0});let i=new mr(t);i.acquireLock();try{await i.init()}catch(r){throw i.releaseLock(),r}return i}acquireLock(){try{this.lockFd=No(this.lockPath,"wx",384),ko(this.lockFd,JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()}));return}catch(i){if(i.code!=="EEXIST")throw i}let t=!1;try{let i=JSON.parse($o(this.lockPath,"utf8"));if(!i.pid)t=!0;else try{process.kill(i.pid,0)}catch{t=!0}}catch{t=!0}if(t){try{Lr(this.lockPath)}catch{}this.acquireLock();return}throw Error(`Agent database is already open by another process (${this.lockPath})`)}releaseLock(){if(this.lockFd!==null){try{Oo(this.lockFd)}catch{}this.lockFd=null}try{Lr(this.lockPath)}catch{}}async init(){this.db=new fe({path:this.dataDir,encrypt:{key:this.encryptionKey},autoSave:!0,format:"gz",lenientLoad:!0}),this.tasks=this.db.createCollection("tasks",{schema:{id:{type:"string",required:!0,unique:!0},type:{type:"string",required:!0,enum:["command","script","file_operation"]},status:{type:"string",required:!0,enum:["pending","running","completed","failed"]},payload:{type:"string",required:!0},result:{type:"string"},error:{type:"string"},calendarTaskId:{type:"string"},exitCode:{type:"number"},timeout:{type:"number"}},indexes:["status","type"]}),this.config=this.db.createCollection("agent_config",{schema:{key:{type:"string",required:!0,unique:!0},value:{type:"string",required:!0}}}),this.gitRepos=this.db.createCollection("git_repositories",{schema:{id:{type:"string",required:!0,unique:!0},path:{type:"string",required:!0,unique:!0},name:{type:"string",required:!0},parentPath:{type:"string"},isSubmodule:{type:"boolean"},projectType:{type:"string"},vitePort:{type:"number"},lastScanned:{type:"string"}},indexes:["parentPath"]}),this.bookmarks=this.db.createCollection("bookmarked_commands",{schema:{id:{type:"string",required:!0,unique:!0},projectId:{type:"string"},command:{type:"string",required:!0},description:{type:"string"},category:{type:"string"}},indexes:["projectId","category"]}),this.notifications=this.db.createCollection("notifications",{schema:{id:{type:"string",required:!0,unique:!0},sessionName:{type:"string"},projectId:{type:"string"},type:{type:"string",required:!0,enum:["info","success","warning","error"]},title:{type:"string",required:!0},message:{type:"string",required:!0},status:{type:"string",required:!0,enum:["unread","read"]}},indexes:["status","projectId"]}),this.pluginState=this.db.createCollection("plugin_state",{schema:{pluginName:{type:"string",required:!0},key:{type:"string",required:!0},value:{type:"string",required:!0}},indexes:["pluginName"]}),await this.db.connect()}async close(){if(this.db?.isConnected)await this.db.disconnect();this.releaseLock()}getDbPath(){return this.dataDir}async createTask(t){let i={id:t.id,type:t.type,status:t.status,payload:t.payload};if(t.result!=null)i.result=t.result;if(t.error!=null)i.error=t.error;if(t.calendarTaskId!=null)i.calendarTaskId=t.calendarTaskId;if(t.exitCode!=null)i.exitCode=t.exitCode;if(t.timeout!=null)i.timeout=t.timeout;let r=await this.tasks.insertOne(i);return S(r)}async getTask(t){let i=await this.tasks.findOne({id:t});return i?S(i):void 0}async getAllTasks(){return(await this.tasks.find(void 0,{sort:{createdAt:-1}})).docs.map((t)=>S(t))}async getPendingTasks(){return(await this.tasks.find({status:"pending"},{sort:{createdAt:1}})).docs.map((t)=>S(t))}async updateTask(t,i){let r={};for(let[s,n]of Object.entries(i)){if(s==="id"||s==="createdAt"||s==="updatedAt")continue;r[s]=n??null}if(Object.keys(r).length===0)return;await this.tasks.updateOne({id:t},r)}async cancelTask(t){let i=await this.tasks.findOne({id:t});if(!i||i.status!=="pending"&&i.status!=="running")return!1;return await this.tasks.updateOne({id:t},{status:"failed",error:"Cancelled"}),!0}async getConfig(t){return(await this.config.findOne({key:t}))?.value}async setConfig(t,i){await this.config.upsert({key:t},{key:t,value:i})}async deleteConfig(t){return await this.config.deleteOne({key:t})!==null}async getAllConfig(){let t=await this.config.find(),i={};for(let r of t.docs)i[r.key]=r.value;return i}async bulkSetConfig(t){for(let[i,r]of Object.entries(t))await this.config.upsert({key:i},{key:i,value:r})}async getConfigStatus(){let t=await this.config.find(),i=null;for(let r of t.docs){let s=r.updatedAt,n=s instanceof Date?s.toISOString():typeof s==="string"?s:null;if(n&&(!i||n>i))i=n}return{totalKeys:t.docs.length,lastUpdated:i}}async createGitRepository(t){let i={id:t.id,path:t.path,name:t.name,isSubmodule:Boolean(t.isSubmodule),lastScanned:Cs()};if(t.parentPath!=null)i.parentPath=t.parentPath;if(t.projectType!=null)i.projectType=t.projectType;if(t.vitePort!=null)i.vitePort=t.vitePort;let r=await this.gitRepos.insertOne(i);return S(r)}async getGitRepository(t){let i=await this.gitRepos.findOne({id:t});return i?S(i):void 0}async getGitRepositoryByPath(t){let i=await this.gitRepos.findOne({path:t});return i?S(i):void 0}async getAllGitRepositories(){return(await this.gitRepos.find(void 0,{sort:{path:1}})).docs.map((t)=>S(t))}async updateGitRepository(t,i){let r={lastScanned:Cs()};for(let[s,n]of Object.entries(i)){if(s==="id"||s==="createdAt"||s==="updatedAt")continue;if(s==="isSubmodule"){r[s]=Boolean(n);continue}r[s]=n??null}await this.gitRepos.updateOne({id:t},r)}async deleteGitRepository(t){return await this.gitRepos.deleteOne({id:t})!==null}async fixGitHierarchy(){let t=await this.getAllGitRepositories(),i=0;for(let r of t){if(r.isSubmodule)continue;let s=t.find((n)=>n.id!==r.id&&r.path.startsWith(`${n.path}/`)&&!n.isSubmodule);if(s&&r.parentPath!==s.path)await this.updateGitRepository(r.id,{parentPath:s.path}),i++}return{fixed:i}}async createBookmarkedCommand(t){let i={id:t.id,command:t.command};if(t.projectId!=null)i.projectId=t.projectId;if(t.description!=null)i.description=t.description;if(t.category!=null)i.category=t.category;let r=await this.bookmarks.insertOne(i);return S(r)}async getBookmarkedCommand(t){let i=await this.bookmarks.findOne({id:t});return i?S(i):void 0}async getAllBookmarkedCommands(){return(await this.bookmarks.find(void 0,{sort:{createdAt:-1}})).docs.map((t)=>S(t))}async getBookmarkedCommandsByProject(t){let i=t===null?{projectId:{$fn:(r)=>r==null}}:{projectId:t};return(await this.bookmarks.find(i,{sort:{createdAt:-1}})).docs.map((r)=>S(r))}async getBookmarkedCommandsByCategory(t){return(await this.bookmarks.find({category:t},{sort:{createdAt:-1}})).docs.map((i)=>S(i))}async updateBookmarkedCommand(t,i){let r={};for(let[s,n]of Object.entries(i)){if(s==="id"||s==="createdAt"||s==="updatedAt")continue;r[s]=n??null}if(Object.keys(r).length===0)return;await this.bookmarks.updateOne({id:t},r)}async deleteBookmarkedCommand(t){return await this.bookmarks.deleteOne({id:t})!==null}async executeBookmarkedCommand(t){return this.getBookmarkedCommand(t)}async createNotification(t){let i={id:t.id,type:t.type,title:t.title,message:t.message,status:t.status};if(t.sessionName!=null)i.sessionName=t.sessionName;if(t.projectId!=null)i.projectId=t.projectId;let r=await this.notifications.insertOne(i);return S(r)}async getNotification(t){let i=await this.notifications.findOne({id:t});return i?S(i):void 0}async getAllNotifications(){return(await this.notifications.find(void 0,{sort:{createdAt:-1}})).docs.map((t)=>S(t))}async getNotificationsByProject(t){let i=t===null?{projectId:{$fn:(r)=>r==null}}:{projectId:t};return(await this.notifications.find(i,{sort:{createdAt:-1}})).docs.map((r)=>S(r))}async getGlobalNotifications(){return this.getNotificationsByProject(null)}async getUnreadNotifications(){return(await this.notifications.find({status:"unread"},{sort:{createdAt:-1}})).docs.map((t)=>S(t))}async updateNotificationStatus(t,i){await this.notifications.updateOne({id:t},{status:i})}async markAllNotificationsRead(){return(await this.notifications.updateMany({status:"unread"},{status:"read"})).length}async deleteNotification(t){return await this.notifications.deleteOne({id:t})!==null}async clearOldNotifications(t=30){let i=new Date(Date.now()-t*24*60*60*1000);return(await this.notifications.deleteMany({createdAt:{$fn:(r)=>r instanceof Date&&r<i}})).length}async getPluginState(t,i){return(await this.pluginState.findOne({$and:[{pluginName:t},{key:i}]}))?.value}async setPluginState(t,i,r){await this.pluginState.upsert({$and:[{pluginName:t},{key:i}]},{pluginName:t,key:i,value:r})}async deletePluginState(t,i){return await this.pluginState.deleteOne({$and:[{pluginName:t},{key:i}]})!==null}async getAllPluginState(t){return(await this.pluginState.find({pluginName:t},{sort:{key:1}})).docs.map((i)=>{let r=i.updatedAt,s=r instanceof Date?r.toISOString():typeof r==="string"?r:void 0;return{key:i.key,value:i.value,updatedAt:s}})}async deleteAllPluginState(t){return(await this.pluginState.deleteMany({pluginName:t})).length}}var ka=(t)=>mr.create(t);sd("skalex",ka);var nd=new Map;function Da(t,i){nd.set(t,i)}class La{}Da("skalex",ka);var Ns=()=>new Date().toISOString();function I(t){if(!t)return t;let{_id:i,createdAt:r,updatedAt:s,_version:n,_expiresAt:a,...o}=t,c={...o};if(c.createdAt==null&&r!=null)c.createdAt=r instanceof Date?r.toISOString():String(r);if(c.updatedAt==null&&s!=null)c.updatedAt=s instanceof Date?s.toISOString():String(s);return c}class yr extends La{dataDir;encryptionKey;lockPath;lockFd=null;db;tasks;config;gitRepos;bookmarks;notifications;pluginState;constructor(t){super();this.dataDir=t.dataDir,this.encryptionKey=t.encryptionKey,this.lockPath=Io(t.dataDir,".agent-db.lock")}static async create(t){if(!Ao(t.dataDir))vo(t.dataDir,{recursive:!0});let i=new yr(t);i.acquireLock();try{await i.init()}catch(r){throw i.releaseLock(),r}return i}acquireLock(){try{this.lockFd=Eo(this.lockPath,"wx",384),So(this.lockFd,JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()}));return}catch(i){if(i.code!=="EEXIST")throw i}let t=!1;try{let i=JSON.parse(xo(this.lockPath,"utf8"));if(!i.pid)t=!0;else try{process.kill(i.pid,0)}catch{t=!0}}catch{t=!0}if(t){try{Dr(this.lockPath)}catch{}this.acquireLock();return}throw Error(`Agent database is already open by another process (${this.lockPath})`)}releaseLock(){if(this.lockFd!==null){try{wo(this.lockFd)}catch{}this.lockFd=null}try{Dr(this.lockPath)}catch{}}async init(){this.db=new he({path:this.dataDir,encrypt:{key:this.encryptionKey},autoSave:!0,format:"gz",lenientLoad:!0}),this.tasks=this.db.createCollection("tasks",{schema:{id:{type:"string",required:!0,unique:!0},type:{type:"string",required:!0,enum:["command","script","file_operation"]},status:{type:"string",required:!0,enum:["pending","running","completed","failed"]},payload:{type:"string",required:!0},result:{type:"string"},error:{type:"string"},calendarTaskId:{type:"string"},exitCode:{type:"number"},timeout:{type:"number"}},indexes:["status","type"]}),this.config=this.db.createCollection("agent_config",{schema:{key:{type:"string",required:!0,unique:!0},value:{type:"string",required:!0}}}),this.gitRepos=this.db.createCollection("git_repositories",{schema:{id:{type:"string",required:!0,unique:!0},path:{type:"string",required:!0,unique:!0},name:{type:"string",required:!0},parentPath:{type:"string"},isSubmodule:{type:"boolean"},projectType:{type:"string"},vitePort:{type:"number"},lastScanned:{type:"string"}},indexes:["parentPath"]}),this.bookmarks=this.db.createCollection("bookmarked_commands",{schema:{id:{type:"string",required:!0,unique:!0},projectId:{type:"string"},command:{type:"string",required:!0},description:{type:"string"},category:{type:"string"}},indexes:["projectId","category"]}),this.notifications=this.db.createCollection("notifications",{schema:{id:{type:"string",required:!0,unique:!0},sessionName:{type:"string"},projectId:{type:"string"},type:{type:"string",required:!0,enum:["info","success","warning","error"]},title:{type:"string",required:!0},message:{type:"string",required:!0},status:{type:"string",required:!0,enum:["unread","read"]}},indexes:["status","projectId"]}),this.pluginState=this.db.createCollection("plugin_state",{schema:{pluginName:{type:"string",required:!0},key:{type:"string",required:!0},value:{type:"string",required:!0}},indexes:["pluginName"]}),await this.db.connect()}async close(){if(this.db?.isConnected)await this.db.disconnect();this.releaseLock()}getDbPath(){return this.dataDir}async createTask(t){let i={id:t.id,type:t.type,status:t.status,payload:t.payload};if(t.result!=null)i.result=t.result;if(t.error!=null)i.error=t.error;if(t.calendarTaskId!=null)i.calendarTaskId=t.calendarTaskId;if(t.exitCode!=null)i.exitCode=t.exitCode;if(t.timeout!=null)i.timeout=t.timeout;let r=await this.tasks.insertOne(i);return I(r)}async getTask(t){let i=await this.tasks.findOne({id:t});return i?I(i):void 0}async getAllTasks(){return(await this.tasks.find(void 0,{sort:{createdAt:-1}})).docs.map((t)=>I(t))}async getPendingTasks(){return(await this.tasks.find({status:"pending"},{sort:{createdAt:1}})).docs.map((t)=>I(t))}async updateTask(t,i){let r={};for(let[s,n]of Object.entries(i)){if(s==="id"||s==="createdAt"||s==="updatedAt")continue;r[s]=n??null}if(Object.keys(r).length===0)return;await this.tasks.updateOne({id:t},r)}async cancelTask(t){let i=await this.tasks.findOne({id:t});if(!i||i.status!=="pending"&&i.status!=="running")return!1;return await this.tasks.updateOne({id:t},{status:"failed",error:"Cancelled"}),!0}async getConfig(t){return(await this.config.findOne({key:t}))?.value}async setConfig(t,i){await this.config.upsert({key:t},{key:t,value:i})}async deleteConfig(t){return await this.config.deleteOne({key:t})!==null}async getAllConfig(){let t=await this.config.find(),i={};for(let r of t.docs)i[r.key]=r.value;return i}async bulkSetConfig(t){for(let[i,r]of Object.entries(t))await this.config.upsert({key:i},{key:i,value:r})}async getConfigStatus(){let t=await this.config.find(),i=null;for(let r of t.docs){let s=r.updatedAt,n=s instanceof Date?s.toISOString():typeof s==="string"?s:null;if(n&&(!i||n>i))i=n}return{totalKeys:t.docs.length,lastUpdated:i}}async createGitRepository(t){let i={id:t.id,path:t.path,name:t.name,isSubmodule:Boolean(t.isSubmodule),lastScanned:Ns()};if(t.parentPath!=null)i.parentPath=t.parentPath;if(t.projectType!=null)i.projectType=t.projectType;if(t.vitePort!=null)i.vitePort=t.vitePort;let r=await this.gitRepos.insertOne(i);return I(r)}async getGitRepository(t){let i=await this.gitRepos.findOne({id:t});return i?I(i):void 0}async getGitRepositoryByPath(t){let i=await this.gitRepos.findOne({path:t});return i?I(i):void 0}async getAllGitRepositories(){return(await this.gitRepos.find(void 0,{sort:{path:1}})).docs.map((t)=>I(t))}async updateGitRepository(t,i){let r={lastScanned:Ns()};for(let[s,n]of Object.entries(i)){if(s==="id"||s==="createdAt"||s==="updatedAt")continue;if(s==="isSubmodule"){r[s]=Boolean(n);continue}r[s]=n??null}await this.gitRepos.updateOne({id:t},r)}async deleteGitRepository(t){return await this.gitRepos.deleteOne({id:t})!==null}async fixGitHierarchy(){let t=await this.getAllGitRepositories(),i=0;for(let r of t){if(r.isSubmodule)continue;let s=t.find((n)=>n.id!==r.id&&r.path.startsWith(`${n.path}/`)&&!n.isSubmodule);if(s&&r.parentPath!==s.path)await this.updateGitRepository(r.id,{parentPath:s.path}),i++}return{fixed:i}}async createBookmarkedCommand(t){let i={id:t.id,command:t.command};if(t.projectId!=null)i.projectId=t.projectId;if(t.description!=null)i.description=t.description;if(t.category!=null)i.category=t.category;let r=await this.bookmarks.insertOne(i);return I(r)}async getBookmarkedCommand(t){let i=await this.bookmarks.findOne({id:t});return i?I(i):void 0}async getAllBookmarkedCommands(){return(await this.bookmarks.find(void 0,{sort:{createdAt:-1}})).docs.map((t)=>I(t))}async getBookmarkedCommandsByProject(t){let i=t===null?{projectId:{$fn:(r)=>r==null}}:{projectId:t};return(await this.bookmarks.find(i,{sort:{createdAt:-1}})).docs.map((r)=>I(r))}async getBookmarkedCommandsByCategory(t){return(await this.bookmarks.find({category:t},{sort:{createdAt:-1}})).docs.map((i)=>I(i))}async updateBookmarkedCommand(t,i){let r={};for(let[s,n]of Object.entries(i)){if(s==="id"||s==="createdAt"||s==="updatedAt")continue;r[s]=n??null}if(Object.keys(r).length===0)return;await this.bookmarks.updateOne({id:t},r)}async deleteBookmarkedCommand(t){return await this.bookmarks.deleteOne({id:t})!==null}async executeBookmarkedCommand(t){return this.getBookmarkedCommand(t)}async createNotification(t){let i={id:t.id,type:t.type,title:t.title,message:t.message,status:t.status};if(t.sessionName!=null)i.sessionName=t.sessionName;if(t.projectId!=null)i.projectId=t.projectId;let r=await this.notifications.insertOne(i);return I(r)}async getNotification(t){let i=await this.notifications.findOne({id:t});return i?I(i):void 0}async getAllNotifications(){return(await this.notifications.find(void 0,{sort:{createdAt:-1}})).docs.map((t)=>I(t))}async getNotificationsByProject(t){let i=t===null?{projectId:{$fn:(r)=>r==null}}:{projectId:t};return(await this.notifications.find(i,{sort:{createdAt:-1}})).docs.map((r)=>I(r))}async getGlobalNotifications(){return this.getNotificationsByProject(null)}async getUnreadNotifications(){return(await this.notifications.find({status:"unread"},{sort:{createdAt:-1}})).docs.map((t)=>I(t))}async updateNotificationStatus(t,i){await this.notifications.updateOne({id:t},{status:i})}async markAllNotificationsRead(){return(await this.notifications.updateMany({status:"unread"},{status:"read"})).length}async deleteNotification(t){return await this.notifications.deleteOne({id:t})!==null}async clearOldNotifications(t=30){let i=new Date(Date.now()-t*24*60*60*1000);return(await this.notifications.deleteMany({createdAt:{$fn:(r)=>r instanceof Date&&r<i}})).length}async getPluginState(t,i){return(await this.pluginState.findOne({$and:[{pluginName:t},{key:i}]}))?.value}async setPluginState(t,i,r){await this.pluginState.upsert({$and:[{pluginName:t},{key:i}]},{pluginName:t,key:i,value:r})}async deletePluginState(t,i){return await this.pluginState.deleteOne({$and:[{pluginName:t},{key:i}]})!==null}async getAllPluginState(t){return(await this.pluginState.find({pluginName:t},{sort:{key:1}})).docs.map((i)=>{let r=i.updatedAt,s=r instanceof Date?r.toISOString():typeof r==="string"?r:void 0;return{key:i.key,value:i.value,updatedAt:s}})}async deleteAllPluginState(t){return(await this.pluginState.deleteMany({pluginName:t})).length}}var Pa=(t)=>yr.create(t);Da("skalex",Pa);var ad=new Map;function Ma(t,i){ad.set(t,i)}class ja{}Ma("skalex",Pa);var $s=()=>new Date().toISOString();function R(t){if(!t)return t;let{_id:i,createdAt:r,updatedAt:s,_version:n,_expiresAt:a,...o}=t,c={...o};if(c.createdAt==null&&r!=null)c.createdAt=r instanceof Date?r.toISOString():String(r);if(c.updatedAt==null&&s!=null)c.updatedAt=s instanceof Date?s.toISOString():String(s);return c}class wr extends ja{dataDir;encryptionKey;lockPath;lockFd=null;db;tasks;config;gitRepos;bookmarks;notifications;pluginState;constructor(t){super();this.dataDir=t.dataDir,this.encryptionKey=t.encryptionKey,this.lockPath=go(t.dataDir,".agent-db.lock")}static async create(t){if(!uo(t.dataDir))ho(t.dataDir,{recursive:!0});let i=new wr(t);i.acquireLock();try{await i.init()}catch(r){throw i.releaseLock(),r}return i}acquireLock(){try{this.lockFd=fo(this.lockPath,"wx",384),po(this.lockFd,JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()}));return}catch(i){if(i.code!=="EEXIST")throw i}let t=!1;try{let i=JSON.parse(_o(this.lockPath,"utf8"));if(!i.pid)t=!0;else try{process.kill(i.pid,0)}catch{t=!0}}catch{t=!0}if(t){try{kr(this.lockPath)}catch{}this.acquireLock();return}throw Error(`Agent database is already open by another process (${this.lockPath})`)}releaseLock(){if(this.lockFd!==null){try{co(this.lockFd)}catch{}this.lockFd=null}try{kr(this.lockPath)}catch{}}async init(){this.db=new ue({path:this.dataDir,encrypt:{key:this.encryptionKey},autoSave:!0,format:"gz",lenientLoad:!0}),this.tasks=this.db.createCollection("tasks",{schema:{id:{type:"string",required:!0,unique:!0},type:{type:"string",required:!0,enum:["command","script","file_operation"]},status:{type:"string",required:!0,enum:["pending","running","completed","failed"]},payload:{type:"string",required:!0},result:{type:"string"},error:{type:"string"},calendarTaskId:{type:"string"},exitCode:{type:"number"},timeout:{type:"number"}},indexes:["status","type"]}),this.config=this.db.createCollection("agent_config",{schema:{key:{type:"string",required:!0,unique:!0},value:{type:"string",required:!0}}}),this.gitRepos=this.db.createCollection("git_repositories",{schema:{id:{type:"string",required:!0,unique:!0},path:{type:"string",required:!0,unique:!0},name:{type:"string",required:!0},parentPath:{type:"string"},isSubmodule:{type:"boolean"},projectType:{type:"string"},vitePort:{type:"number"},lastScanned:{type:"string"}},indexes:["parentPath"]}),this.bookmarks=this.db.createCollection("bookmarked_commands",{schema:{id:{type:"string",required:!0,unique:!0},projectId:{type:"string"},command:{type:"string",required:!0},description:{type:"string"},category:{type:"string"}},indexes:["projectId","category"]}),this.notifications=this.db.createCollection("notifications",{schema:{id:{type:"string",required:!0,unique:!0},sessionName:{type:"string"},projectId:{type:"string"},type:{type:"string",required:!0,enum:["info","success","warning","error"]},title:{type:"string",required:!0},message:{type:"string",required:!0},status:{type:"string",required:!0,enum:["unread","read"]}},indexes:["status","projectId"]}),this.pluginState=this.db.createCollection("plugin_state",{schema:{pluginName:{type:"string",required:!0},key:{type:"string",required:!0},value:{type:"string",required:!0}},indexes:["pluginName"]}),await this.db.connect()}async close(){if(this.db?.isConnected)await this.db.disconnect();this.releaseLock()}getDbPath(){return this.dataDir}async createTask(t){let i={id:t.id,type:t.type,status:t.status,payload:t.payload};if(t.result!=null)i.result=t.result;if(t.error!=null)i.error=t.error;if(t.calendarTaskId!=null)i.calendarTaskId=t.calendarTaskId;if(t.exitCode!=null)i.exitCode=t.exitCode;if(t.timeout!=null)i.timeout=t.timeout;let r=await this.tasks.insertOne(i);return R(r)}async getTask(t){let i=await this.tasks.findOne({id:t});return i?R(i):void 0}async getAllTasks(){return(await this.tasks.find(void 0,{sort:{createdAt:-1}})).docs.map((t)=>R(t))}async getPendingTasks(){return(await this.tasks.find({status:"pending"},{sort:{createdAt:1}})).docs.map((t)=>R(t))}async updateTask(t,i){let r={};for(let[s,n]of Object.entries(i)){if(s==="id"||s==="createdAt"||s==="updatedAt")continue;r[s]=n??null}if(Object.keys(r).length===0)return;await this.tasks.updateOne({id:t},r)}async cancelTask(t){let i=await this.tasks.findOne({id:t});if(!i||i.status!=="pending"&&i.status!=="running")return!1;return await this.tasks.updateOne({id:t},{status:"failed",error:"Cancelled"}),!0}async getConfig(t){return(await this.config.findOne({key:t}))?.value}async setConfig(t,i){await this.config.upsert({key:t},{key:t,value:i})}async deleteConfig(t){return await this.config.deleteOne({key:t})!==null}async getAllConfig(){let t=await this.config.find(),i={};for(let r of t.docs)i[r.key]=r.value;return i}async bulkSetConfig(t){for(let[i,r]of Object.entries(t))await this.config.upsert({key:i},{key:i,value:r})}async getConfigStatus(){let t=await this.config.find(),i=null;for(let r of t.docs){let s=r.updatedAt,n=s instanceof Date?s.toISOString():typeof s==="string"?s:null;if(n&&(!i||n>i))i=n}return{totalKeys:t.docs.length,lastUpdated:i}}async createGitRepository(t){let i={id:t.id,path:t.path,name:t.name,isSubmodule:Boolean(t.isSubmodule),lastScanned:$s()};if(t.parentPath!=null)i.parentPath=t.parentPath;if(t.projectType!=null)i.projectType=t.projectType;if(t.vitePort!=null)i.vitePort=t.vitePort;let r=await this.gitRepos.insertOne(i);return R(r)}async getGitRepository(t){let i=await this.gitRepos.findOne({id:t});return i?R(i):void 0}async getGitRepositoryByPath(t){let i=await this.gitRepos.findOne({path:t});return i?R(i):void 0}async getAllGitRepositories(){return(await this.gitRepos.find(void 0,{sort:{path:1}})).docs.map((t)=>R(t))}async updateGitRepository(t,i){let r={lastScanned:$s()};for(let[s,n]of Object.entries(i)){if(s==="id"||s==="createdAt"||s==="updatedAt")continue;if(s==="isSubmodule"){r[s]=Boolean(n);continue}r[s]=n??null}await this.gitRepos.updateOne({id:t},r)}async deleteGitRepository(t){return await this.gitRepos.deleteOne({id:t})!==null}async fixGitHierarchy(){let t=await this.getAllGitRepositories(),i=0;for(let r of t){if(r.isSubmodule)continue;let s=t.find((n)=>n.id!==r.id&&r.path.startsWith(`${n.path}/`)&&!n.isSubmodule);if(s&&r.parentPath!==s.path)await this.updateGitRepository(r.id,{parentPath:s.path}),i++}return{fixed:i}}async createBookmarkedCommand(t){let i={id:t.id,command:t.command};if(t.projectId!=null)i.projectId=t.projectId;if(t.description!=null)i.description=t.description;if(t.category!=null)i.category=t.category;let r=await this.bookmarks.insertOne(i);return R(r)}async getBookmarkedCommand(t){let i=await this.bookmarks.findOne({id:t});return i?R(i):void 0}async getAllBookmarkedCommands(){return(await this.bookmarks.find(void 0,{sort:{createdAt:-1}})).docs.map((t)=>R(t))}async getBookmarkedCommandsByProject(t){let i=t===null?{projectId:{$fn:(r)=>r==null}}:{projectId:t};return(await this.bookmarks.find(i,{sort:{createdAt:-1}})).docs.map((r)=>R(r))}async getBookmarkedCommandsByCategory(t){return(await this.bookmarks.find({category:t},{sort:{createdAt:-1}})).docs.map((i)=>R(i))}async updateBookmarkedCommand(t,i){let r={};for(let[s,n]of Object.entries(i)){if(s==="id"||s==="createdAt"||s==="updatedAt")continue;r[s]=n??null}if(Object.keys(r).length===0)return;await this.bookmarks.updateOne({id:t},r)}async deleteBookmarkedCommand(t){return await this.bookmarks.deleteOne({id:t})!==null}async executeBookmarkedCommand(t){return this.getBookmarkedCommand(t)}async createNotification(t){let i={id:t.id,type:t.type,title:t.title,message:t.message,status:t.status};if(t.sessionName!=null)i.sessionName=t.sessionName;if(t.projectId!=null)i.projectId=t.projectId;let r=await this.notifications.insertOne(i);return R(r)}async getNotification(t){let i=await this.notifications.findOne({id:t});return i?R(i):void 0}async getAllNotifications(){return(await this.notifications.find(void 0,{sort:{createdAt:-1}})).docs.map((t)=>R(t))}async getNotificationsByProject(t){let i=t===null?{projectId:{$fn:(r)=>r==null}}:{projectId:t};return(await this.notifications.find(i,{sort:{createdAt:-1}})).docs.map((r)=>R(r))}async getGlobalNotifications(){return this.getNotificationsByProject(null)}async getUnreadNotifications(){return(await this.notifications.find({status:"unread"},{sort:{createdAt:-1}})).docs.map((t)=>R(t))}async updateNotificationStatus(t,i){await this.notifications.updateOne({id:t},{status:i})}async markAllNotificationsRead(){return(await this.notifications.updateMany({status:"unread"},{status:"read"})).length}async deleteNotification(t){return await this.notifications.deleteOne({id:t})!==null}async clearOldNotifications(t=30){let i=new Date(Date.now()-t*24*60*60*1000);return(await this.notifications.deleteMany({createdAt:{$fn:(r)=>r instanceof Date&&r<i}})).length}async getPluginState(t,i){return(await this.pluginState.findOne({$and:[{pluginName:t},{key:i}]}))?.value}async setPluginState(t,i,r){await this.pluginState.upsert({$and:[{pluginName:t},{key:i}]},{pluginName:t,key:i,value:r})}async deletePluginState(t,i){return await this.pluginState.deleteOne({$and:[{pluginName:t},{key:i}]})!==null}async getAllPluginState(t){return(await this.pluginState.find({pluginName:t},{sort:{key:1}})).docs.map((i)=>{let r=i.updatedAt,s=r instanceof Date?r.toISOString():typeof r==="string"?r:void 0;return{key:i.key,value:i.value,updatedAt:s}})}async deleteAllPluginState(t){return(await this.pluginState.deleteMany({pluginName:t})).length}}var qa=(t)=>wr.create(t);Ma("skalex",qa);var od=new Map;function Ua(t,i){od.set(t,i)}class Fa{}Ua("skalex",qa);var ks=()=>new Date().toISOString();function k(t){if(!t)return t;let{_id:i,createdAt:r,updatedAt:s,_version:n,_expiresAt:a,...o}=t,c={...o};if(c.createdAt==null&&r!=null)c.createdAt=r instanceof Date?r.toISOString():String(r);if(c.updatedAt==null&&s!=null)c.updatedAt=s instanceof Date?s.toISOString():String(s);return c}class Ar extends Fa{dataDir;encryptionKey;lockPath;lockFd=null;db;tasks;config;gitRepos;bookmarks;notifications;pluginState;constructor(t){super();this.dataDir=t.dataDir,this.encryptionKey=t.encryptionKey,this.lockPath=ao(t.dataDir,".agent-db.lock")}static async create(t){if(!to(t.dataDir))io(t.dataDir,{recursive:!0});let i=new Ar(t);i.acquireLock();try{await i.init()}catch(r){throw i.releaseLock(),r}return i}acquireLock(){try{this.lockFd=ro(this.lockPath,"wx",384),no(this.lockFd,JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()}));return}catch(i){if(i.code!=="EEXIST")throw i}let t=!1;try{let i=JSON.parse(so(this.lockPath,"utf8"));if(!i.pid)t=!0;else try{process.kill(i.pid,0)}catch{t=!0}}catch{t=!0}if(t){try{$r(this.lockPath)}catch{}this.acquireLock();return}throw Error(`Agent database is already open by another process (${this.lockPath})`)}releaseLock(){if(this.lockFd!==null){try{eo(this.lockFd)}catch{}this.lockFd=null}try{$r(this.lockPath)}catch{}}async init(){this.db=new de({path:this.dataDir,encrypt:{key:this.encryptionKey},autoSave:!0,format:"gz",lenientLoad:!0}),this.tasks=this.db.createCollection("tasks",{schema:{id:{type:"string",required:!0,unique:!0},type:{type:"string",required:!0,enum:["command","script","file_operation"]},status:{type:"string",required:!0,enum:["pending","running","completed","failed"]},payload:{type:"string",required:!0},result:{type:"string"},error:{type:"string"},calendarTaskId:{type:"string"},exitCode:{type:"number"},timeout:{type:"number"}},indexes:["status","type"]}),this.config=this.db.createCollection("agent_config",{schema:{key:{type:"string",required:!0,unique:!0},value:{type:"string",required:!0}}}),this.gitRepos=this.db.createCollection("git_repositories",{schema:{id:{type:"string",required:!0,unique:!0},path:{type:"string",required:!0,unique:!0},name:{type:"string",required:!0},parentPath:{type:"string"},isSubmodule:{type:"boolean"},projectType:{type:"string"},vitePort:{type:"number"},lastScanned:{type:"string"}},indexes:["parentPath"]}),this.bookmarks=this.db.createCollection("bookmarked_commands",{schema:{id:{type:"string",required:!0,unique:!0},projectId:{type:"string"},command:{type:"string",required:!0},description:{type:"string"},category:{type:"string"}},indexes:["projectId","category"]}),this.notifications=this.db.createCollection("notifications",{schema:{id:{type:"string",required:!0,unique:!0},sessionName:{type:"string"},projectId:{type:"string"},type:{type:"string",required:!0,enum:["info","success","warning","error"]},title:{type:"string",required:!0},message:{type:"string",required:!0},status:{type:"string",required:!0,enum:["unread","read"]}},indexes:["status","projectId"]}),this.pluginState=this.db.createCollection("plugin_state",{schema:{pluginName:{type:"string",required:!0},key:{type:"string",required:!0},value:{type:"string",required:!0}},indexes:["pluginName"]}),await this.db.connect()}async close(){if(this.db?.isConnected)await this.db.disconnect();this.releaseLock()}getDbPath(){return this.dataDir}async createTask(t){let i={id:t.id,type:t.type,status:t.status,payload:t.payload};if(t.result!=null)i.result=t.result;if(t.error!=null)i.error=t.error;if(t.calendarTaskId!=null)i.calendarTaskId=t.calendarTaskId;if(t.exitCode!=null)i.exitCode=t.exitCode;if(t.timeout!=null)i.timeout=t.timeout;let r=await this.tasks.insertOne(i);return k(r)}async getTask(t){let i=await this.tasks.findOne({id:t});return i?k(i):void 0}async getAllTasks(){return(await this.tasks.find(void 0,{sort:{createdAt:-1}})).docs.map((t)=>k(t))}async getPendingTasks(){return(await this.tasks.find({status:"pending"},{sort:{createdAt:1}})).docs.map((t)=>k(t))}async updateTask(t,i){let r={};for(let[s,n]of Object.entries(i)){if(s==="id"||s==="createdAt"||s==="updatedAt")continue;r[s]=n??null}if(Object.keys(r).length===0)return;await this.tasks.updateOne({id:t},r)}async cancelTask(t){let i=await this.tasks.findOne({id:t});if(!i||i.status!=="pending"&&i.status!=="running")return!1;return await this.tasks.updateOne({id:t},{status:"failed",error:"Cancelled"}),!0}async getConfig(t){return(await this.config.findOne({key:t}))?.value}async setConfig(t,i){await this.config.upsert({key:t},{key:t,value:i})}async deleteConfig(t){return await this.config.deleteOne({key:t})!==null}async getAllConfig(){let t=await this.config.find(),i={};for(let r of t.docs)i[r.key]=r.value;return i}async bulkSetConfig(t){for(let[i,r]of Object.entries(t))await this.config.upsert({key:i},{key:i,value:r})}async getConfigStatus(){let t=await this.config.find(),i=null;for(let r of t.docs){let s=r.updatedAt,n=s instanceof Date?s.toISOString():typeof s==="string"?s:null;if(n&&(!i||n>i))i=n}return{totalKeys:t.docs.length,lastUpdated:i}}async createGitRepository(t){let i={id:t.id,path:t.path,name:t.name,isSubmodule:Boolean(t.isSubmodule),lastScanned:ks()};if(t.parentPath!=null)i.parentPath=t.parentPath;if(t.projectType!=null)i.projectType=t.projectType;if(t.vitePort!=null)i.vitePort=t.vitePort;let r=await this.gitRepos.insertOne(i);return k(r)}async getGitRepository(t){let i=await this.gitRepos.findOne({id:t});return i?k(i):void 0}async getGitRepositoryByPath(t){let i=await this.gitRepos.findOne({path:t});return i?k(i):void 0}async getAllGitRepositories(){return(await this.gitRepos.find(void 0,{sort:{path:1}})).docs.map((t)=>k(t))}async updateGitRepository(t,i){let r={lastScanned:ks()};for(let[s,n]of Object.entries(i)){if(s==="id"||s==="createdAt"||s==="updatedAt")continue;if(s==="isSubmodule"){r[s]=Boolean(n);continue}r[s]=n??null}await this.gitRepos.updateOne({id:t},r)}async deleteGitRepository(t){return await this.gitRepos.deleteOne({id:t})!==null}async fixGitHierarchy(){let t=await this.getAllGitRepositories(),i=0;for(let r of t){if(r.isSubmodule)continue;let s=t.find((n)=>n.id!==r.id&&r.path.startsWith(`${n.path}/`)&&!n.isSubmodule);if(s&&r.parentPath!==s.path)await this.updateGitRepository(r.id,{parentPath:s.path}),i++}return{fixed:i}}async createBookmarkedCommand(t){let i={id:t.id,command:t.command};if(t.projectId!=null)i.projectId=t.projectId;if(t.description!=null)i.description=t.description;if(t.category!=null)i.category=t.category;let r=await this.bookmarks.insertOne(i);return k(r)}async getBookmarkedCommand(t){let i=await this.bookmarks.findOne({id:t});return i?k(i):void 0}async getAllBookmarkedCommands(){return(await this.bookmarks.find(void 0,{sort:{createdAt:-1}})).docs.map((t)=>k(t))}async getBookmarkedCommandsByProject(t){let i=t===null?{projectId:{$fn:(r)=>r==null}}:{projectId:t};return(await this.bookmarks.find(i,{sort:{createdAt:-1}})).docs.map((r)=>k(r))}async getBookmarkedCommandsByCategory(t){return(await this.bookmarks.find({category:t},{sort:{createdAt:-1}})).docs.map((i)=>k(i))}async updateBookmarkedCommand(t,i){let r={};for(let[s,n]of Object.entries(i)){if(s==="id"||s==="createdAt"||s==="updatedAt")continue;r[s]=n??null}if(Object.keys(r).length===0)return;await this.bookmarks.updateOne({id:t},r)}async deleteBookmarkedCommand(t){return await this.bookmarks.deleteOne({id:t})!==null}async executeBookmarkedCommand(t){return this.getBookmarkedCommand(t)}async createNotification(t){let i={id:t.id,type:t.type,title:t.title,message:t.message,status:t.status};if(t.sessionName!=null)i.sessionName=t.sessionName;if(t.projectId!=null)i.projectId=t.projectId;let r=await this.notifications.insertOne(i);return k(r)}async getNotification(t){let i=await this.notifications.findOne({id:t});return i?k(i):void 0}async getAllNotifications(){return(await this.notifications.find(void 0,{sort:{createdAt:-1}})).docs.map((t)=>k(t))}async getNotificationsByProject(t){let i=t===null?{projectId:{$fn:(r)=>r==null}}:{projectId:t};return(await this.notifications.find(i,{sort:{createdAt:-1}})).docs.map((r)=>k(r))}async getGlobalNotifications(){return this.getNotificationsByProject(null)}async getUnreadNotifications(){return(await this.notifications.find({status:"unread"},{sort:{createdAt:-1}})).docs.map((t)=>k(t))}async updateNotificationStatus(t,i){await this.notifications.updateOne({id:t},{status:i})}async markAllNotificationsRead(){return(await this.notifications.updateMany({status:"unread"},{status:"read"})).length}async deleteNotification(t){return await this.notifications.deleteOne({id:t})!==null}async clearOldNotifications(t=30){let i=new Date(Date.now()-t*24*60*60*1000);return(await this.notifications.deleteMany({createdAt:{$fn:(r)=>r instanceof Date&&r<i}})).length}async getPluginState(t,i){return(await this.pluginState.findOne({$and:[{pluginName:t},{key:i}]}))?.value}async setPluginState(t,i,r){await this.pluginState.upsert({$and:[{pluginName:t},{key:i}]},{pluginName:t,key:i,value:r})}async deletePluginState(t,i){return await this.pluginState.deleteOne({$and:[{pluginName:t},{key:i}]})!==null}async getAllPluginState(t){return(await this.pluginState.find({pluginName:t},{sort:{key:1}})).docs.map((i)=>{let r=i.updatedAt,s=r instanceof Date?r.toISOString():typeof r==="string"?r:void 0;return{key:i.key,value:i.value,updatedAt:s}})}async deleteAllPluginState(t){return(await this.pluginState.deleteMany({pluginName:t})).length}}var Ka=(t)=>Ar.create(t);Ua("skalex",Ka);var vr=new Map;function ld(t,i){vr.set(t,i)}function Ds(t){return vr.get(t)}function cd(){return Array.from(vr.keys())}async function dd(t){if(t.adapterFactory)return t.adapterFactory;let i=t.adapterName??process.env.VIBE_STORAGE_ADAPTER??"skalex";if(i.startsWith("custom:")){let s=i.slice(7);if(!s)throw Error("VIBE_STORAGE_ADAPTER=custom: requires a module path after the colon");let n=await import(s),a=n.default??n.createAdapter;if(typeof a!=="function")throw Error(`Custom storage adapter at ${s} must export a default function (or \`createAdapter\`) of type AgentStorageAdapterFactory`);return a}let r=Ds(i);if(!r){let s={skalex:"@vibecontrols/vibe-plugin-storage-skalex",postgres:"@vibecontrols/vibe-plugin-storage-postgres",postgresql:"@vibecontrols/vibe-plugin-storage-postgres"}[i];if(s)try{await import(s),r=Ds(i)}catch{}}if(!r)throw Error(`Unknown storage adapter: "${i}". Registered adapters: ${cd().join(", ")||`(none \u2014 did you install @vibecontrols/vibe-plugin-storage-${i})?`}`);return r}async function er(t){if(!t.encryptionKey)throw Error("createAgentDatabase(): encryptionKey is required. Storage is always encrypted at rest.");if(!t.dbPath)throw Error("createAgentDatabase(): dbPath is required.");return(await dd(t))({dataDir:t.dbPath,encryptionKey:t.encryptionKey,adapterOptions:t.adapterOptions})}ld("skalex",Ka);var ud="@vibecontrols/vibe-plugin-storage",wu=hd();function hd(){try{let t=wi(Za(import.meta.url));for(let i=0;i<10&&t&&t!==wi(t);i++){let r=Qa(t,"package.json");if(Ja(r))try{let s=JSON.parse(Ya(r,"utf8"));if(s.name===ud&&typeof s.version==="string")return s.version}catch{}t=wi(t)}}catch{}return"0.0.0"}import ui from"os";import{mkdirSync as bd}from"fs";import{join as Td}from"path";var Er=[0,5000,15000,30000,60000],fd=2000,_d=5000,pd=120000,za=10,gd=1048576;class xr extends Error{resetAt;resource;constructor(t,i,r){super(t);this.name="RateLimitError",this.resource=i,this.resetAt=r}}function Sr(t,i){if(!t?.length)return null;let r=t.find((a)=>a.extensions?.code==="RATE_LIMITED");if(!r)return null;let s=r.extensions?.resetAt,n=null;if(s){let a=new Date(s);if(!Number.isNaN(a.getTime()))n=a}return new xr(`${i} rate limited${n?` until ${n.toISOString()}`:""}`,i,n)}function md(t){if(!t.resetAt)return 60000;let i=t.resetAt.getTime()-Date.now()+fd;return Math.min(Math.max(i,_d),pd)}async function yd(t,i){let r=t.headers.get("content-length");if(r){let l=Number.parseInt(r,10);if(Number.isInteger(l)&&l>i)throw Error(`Gateway response is too large (${l} bytes)`)}if(!t.body)return"";let s=t.body.getReader(),n=[],a=0;try{while(!0){let{done:l,value:d}=await s.read();if(l)break;if(!d)continue;if(a+=d.byteLength,a>i)throw await s.cancel().catch(()=>{return}),Error(`Gateway response exceeds ${i} bytes`);n.push(d)}}finally{s.releaseLock()}let o=new Uint8Array(a),c=0;for(let l of n)o.set(l,c),c+=l.byteLength;return new TextDecoder().decode(o)}async function Ir(t,i){let r=await yd(t,gd),s;try{s=r?JSON.parse(r):{}}catch(n){let a=r.slice(0,240).replace(/\s+/g," ");throw Error(`${i} returned non-JSON response (${t.status} ${t.statusText})${a?`: ${a}`:""}`,{cause:n})}if(!t.ok){let n=r.slice(0,240).replace(/\s+/g," ");throw Error(`${i} failed (${t.status} ${t.statusText})${n?`: ${n}`:""}`)}return s}function br(t){return t.endsWith("/graphql")?t:`${t}/graphql`}function wd(t){let i;try{i=new URL(t).hostname.toLowerCase().replace(/^\[|\]$/g,"")}catch{return!1}if(i==="localhost"||i==="127.0.0.1"||i==="::1"||i==="0.0.0.0"||i==="host.docker.internal")return!0;return i.endsWith(".localhost")||i.endsWith(".local")||i.endsWith(".local.burdenoff.com")}function Tr(t){if(!(process.env.VIBE_DEV_INSECURE_TLS==="1"||process.env.NODE_TLS_REJECT_UNAUTHORIZED==="0")&&!wd(t))return{};return{tls:{rejectUnauthorized:!1}}}async function Ad(t,i,r){let s=await fetch(br(t),{method:"POST",...Tr(t),headers:{"Content-Type":"application/json"},body:JSON.stringify({query:`mutation AuthenticateApp($input: AuthenticateAppInput!) {
|
|
107
107
|
authenticateApp(input: $input) { accessToken expiresIn }
|
|
108
|
-
}`,variables:{input:{clientId:i,clientSecret:r,scopes:[]}}}),signal:AbortSignal.timeout(15000)}),n=await Ir(s,"authenticateApp"),a=Sr(n.errors,"authenticateApp");if(a)throw a;if(n.errors?.length){let c=n.errors.map((l)=>l.extensions?.code??"UNKNOWN").join(",");throw Error(`authenticateApp errors [${c}]: ${n.errors.map((l)=>l.message).join("; ")}`)}let o=n.data?.authenticateApp?.accessToken;if(!o)throw Error("authenticateApp returned no token");return o}async function
|
|
108
|
+
}`,variables:{input:{clientId:i,clientSecret:r,scopes:[]}}}),signal:AbortSignal.timeout(15000)}),n=await Ir(s,"authenticateApp"),a=Sr(n.errors,"authenticateApp");if(a)throw a;if(n.errors?.length){let c=n.errors.map((l)=>l.extensions?.code??"UNKNOWN").join(",");throw Error(`authenticateApp errors [${c}]: ${n.errors.map((l)=>l.message).join("; ")}`)}let o=n.data?.authenticateApp?.accessToken;if(!o)throw Error("authenticateApp returned no token");return o}async function vd(t,i,r,s){let n=await fetch(br(t),{method:"POST",...Tr(t),headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`},body:JSON.stringify({query:`mutation IssueAgentWorkspaceToken($input: IssueWorkspaceTokenInput!) {
|
|
109
109
|
issueWorkspaceToken(input: $input) {
|
|
110
110
|
success
|
|
111
111
|
token
|
|
112
112
|
expiresAt
|
|
113
113
|
error { code message }
|
|
114
114
|
}
|
|
115
|
-
}`,variables:{input:{organizationId:s||r,workspaceId:r}}}),signal:AbortSignal.timeout(15000)}),a=await Ir(n,"issueWorkspaceToken"),o=Sr(a.errors,"issueWorkspaceToken");if(o)throw o;if(a.errors?.length)throw Error(`issueWorkspaceToken errors: ${a.errors.map((l)=>l.message).join("; ")}`);let c=a.data?.issueWorkspaceToken;if(!c?.success||!c.token){let l=c?.error?.code??"UNKNOWN",d=c?.error?.message??"no workspace token returned";throw Error(`issueWorkspaceToken failed [${l}]: ${d}`)}return c.token}async function
|
|
115
|
+
}`,variables:{input:{organizationId:s||r,workspaceId:r}}}),signal:AbortSignal.timeout(15000)}),a=await Ir(n,"issueWorkspaceToken"),o=Sr(a.errors,"issueWorkspaceToken");if(o)throw o;if(a.errors?.length)throw Error(`issueWorkspaceToken errors: ${a.errors.map((l)=>l.message).join("; ")}`);let c=a.data?.issueWorkspaceToken;if(!c?.success||!c.token){let l=c?.error?.code??"UNKNOWN",d=c?.error?.message??"no workspace token returned";throw Error(`issueWorkspaceToken failed [${l}]: ${d}`)}return c.token}async function Ed(t){let i=await Ad(t.globalGatewayUrl,t.clientId,t.clientSecret),r=await vd(t.workspaceGatewayUrl,i,t.workspaceId,t.organizationId),s=await fetch(br(t.workspaceGatewayUrl),{method:"POST",...Tr(t.workspaceGatewayUrl),headers:{"Content-Type":"application/json",Authorization:`Bearer ${i}`,"X-Workspace-Authorization":`Bearer ${r}`},body:JSON.stringify({query:`query FetchAgentEncryptionKey($workspaceId: ID!) {
|
|
116
116
|
vibecontrolsAgentEncryptionKey(workspaceId: $workspaceId)
|
|
117
|
-
}`,variables:{workspaceId:t.workspaceId}}),signal:AbortSignal.timeout(15000)}),n=await Ir(s,"vibecontrolsAgentEncryptionKey"),a=Sr(n.errors,"vibecontrolsAgentEncryptionKey");if(a)throw a;if(n.errors?.length)throw Error(`vibecontrolsAgentEncryptionKey errors: ${n.errors.map((c)=>c.message).join("; ")}`);let o=n.data?.vibecontrolsAgentEncryptionKey;if(!o)throw Error("vibecontrolsAgentEncryptionKey returned empty");return o}async function
|
|
117
|
+
}`,variables:{workspaceId:t.workspaceId}}),signal:AbortSignal.timeout(15000)}),n=await Ir(s,"vibecontrolsAgentEncryptionKey"),a=Sr(n.errors,"vibecontrolsAgentEncryptionKey");if(a)throw a;if(n.errors?.length)throw Error(`vibecontrolsAgentEncryptionKey errors: ${n.errors.map((c)=>c.message).join("; ")}`);let o=n.data?.vibecontrolsAgentEncryptionKey;if(!o)throw Error("vibecontrolsAgentEncryptionKey returned empty");return o}async function tr(t,i=Er.length,r={}){let s={...t,globalGatewayUrl:z(t.globalGatewayUrl,"globalGatewayUrl"),workspaceGatewayUrl:z(t.workspaceGatewayUrl,"workspaceGatewayUrl")},n=r.signal,a=()=>{if(n?.aborted)throw n.reason instanceof Error?n.reason:Error("encryption key fetch aborted")},o=(u)=>new Promise((f,h)=>{let _=setTimeout(()=>{if(n)n.removeEventListener("abort",p);f()},u),p=()=>{clearTimeout(_),h(n?.reason instanceof Error?n.reason:Error("encryption key fetch aborted"))};n?.addEventListener("abort",p,{once:!0})}),c,l=0,d=0;while(l<i){a();try{let u=await Ed(s);return e().logger.info("finalizer","Storage encryption key fetched from backend",{attempt:l+1,rateLimitRetries:d}),u}catch(u){if(c=u,a(),u instanceof xr){if(d>=za){e().logger.error("finalizer","Rate-limit retries exhausted; giving up",{resource:u.resource,resetAt:u.resetAt?.toISOString()??null,rateLimitRetries:d});break}let _=md(u);d+=1,e().logger.warn("finalizer",`Rate limited by ${u.resource}; waiting ${Math.round(_/1000)}s for window to clear (retry ${d}/${za})`,{resource:u.resource,resetAt:u.resetAt?.toISOString()??null,waitMs:_}),await o(_);continue}if(l+=1,l>=i){e().logger.error("finalizer","Failed to fetch storage encryption key from backend (final attempt)",{error:String(u),attempts:i});break}let h=Er[l]??Er.at(-1)??0;if(e().logger.warn("finalizer",`Storage key fetch attempt ${l}/${i} failed; retrying in ${Math.round(h/1000)}s`,{error:String(u)}),h>0)await o(h)}}throw c instanceof Error?c:Error(String(c??"encryption key fetch failed"))}async function xd(t){let i=await Sd(t);if(i)return i;return Id(t.name)}async function Sd(t){let i;try{i=await X({dir:t.dataDir,scope:t.name})}catch{return null}if(!i.clientId||!i.clientSecret||!i.globalGatewayUrl||!i.workspaceGatewayUrl||!i.workspaceId)return null;return{clientId:i.clientId,clientSecret:i.clientSecret,globalGatewayUrl:i.globalGatewayUrl,workspaceGatewayUrl:i.workspaceGatewayUrl,workspaceId:i.workspaceId,organizationId:i.organizationId}}function Id(t){let i=t.replace(/[^A-Za-z0-9_]/g,"_").toUpperCase(),r=(l)=>process.env[`VIBE_${i}_${l}`],s=r("CLIENT_ID"),n=r("CLIENT_SECRET"),a=r("GLOBAL_GATEWAY_URL"),o=r("WORKSPACE_GATEWAY_URL"),c=r("WORKSPACE_ID");if(!s||!n||!a||!o||!c)return null;return{clientId:s,clientSecret:n,globalGatewayUrl:a,workspaceGatewayUrl:o,workspaceId:c,organizationId:r("ORGANIZATION_ID")}}async function hi(t){let i=await xd(t);if(!i)return{ok:!1,error:`no creds for profile '${t.name}' (run gateway-auth against this profile or set VIBE_${t.name.toUpperCase()}_* env vars)`};t.setBootState("initializing");let r;try{let c=await tr(i);r=await er({dbPath:t.dataDir,encryptionKey:c})}catch(c){return t.setBootState("awaiting-config"),{ok:!1,error:c instanceof Error?c.message:String(c)}}let s=new xe(r);await s.hydrateDefaultsFromDb();let n=new W(r);await n.loadCorePlugins();try{await n.loadAll()}catch(c){t.logger.warn("secondary-profile-attach","failed to load some external plugins for secondary profile",{error:c instanceof Error?c.message:String(c)})}let a={storage:{async get(c,l){return await r.getPluginState(c,l)??null},async set(c,l,d){await r.setPluginState(c,l,d)},async delete(c,l){return r.deletePluginState(c,l)},async list(c){return await r.getAllPluginState(c)},async deleteAll(c){return r.deleteAllPluginState(c)}},logger:t.logger,serviceRegistry:s,getProvider:(c)=>s.getProvider(c),getAgentBaseUrl:()=>process.env.AGENT_URL||"http://localhost:0",getAgentVersion:()=>"0.0.0",broadcast:()=>{},workspaceQuery:async()=>({}),isGatewayConfigured:()=>!0,getAgentRecordId:async()=>await r.getConfig("gateway-auth:agentRecordId")??null,getWorkspaceId:async()=>await r.getConfig("gateway-auth:workspaceId")??null,getConfig:async(c)=>await r.getConfig(c)??void 0,getPluginRegistry:()=>"",getDataDir:()=>t.dataDir,cliContributors:new Ie,audit:{emit:(c,l)=>t.audit.emit("agent",c,l??{})},telemetry:{emit:()=>{}},os:b(),iframeBridge:ve()},o=new Rt(s,n,r,{},a,async()=>{});s.registerService("agent","lifecycle",o),t.attachServices({db:r,serviceRegistry:s,pluginManager:n,lifecycle:o,hostServices:a});try{_t(t)}catch(c){t.logger.warn("secondary-profile-attach","failed to mount per-profile plugin routes",{error:c instanceof Error?c.message:String(c)})}try{await t.keyVault.bindApiKey(K())}catch{}return t.setBootState("ready"),{ok:!0}}var bt="profile-reconciler",Od=60000,Rd=5000,Cd=30000,Nd=15,$d=200,kd=`
|
|
118
118
|
query VibecontrolsAgentProfiles($agentId: ID!) {
|
|
119
119
|
vibecontrolsAgentProfiles(agentId: $agentId) {
|
|
120
120
|
id
|
|
@@ -123,14 +123,14 @@ data: /message
|
|
|
123
123
|
isDefault
|
|
124
124
|
}
|
|
125
125
|
}
|
|
126
|
-
`,
|
|
126
|
+
`,Dd=`
|
|
127
127
|
mutation UpdateVibecontrolsAgentProfile($id: ID!, $input: UpdateVibecontrolsAgentProfileInput!) {
|
|
128
128
|
updateVibecontrolsAgentProfile(id: $id, input: $input) {
|
|
129
129
|
id
|
|
130
130
|
status
|
|
131
131
|
}
|
|
132
132
|
}
|
|
133
|
-
`;function
|
|
133
|
+
`;function di(t){return Td(C(),"agents",O(t))}async function Va(t){try{let i=await X({dir:di(t),scope:O(t)});return Boolean(i.clientId&&i.clientSecret)}catch{return!1}}async function Ld(t){for(let i=0;i<Nd;i++){if(await Va(t))return!0;await new Promise((r)=>setTimeout(r,$d))}return!1}async function Pd(t,i,r){let s,n=new Promise((a,o)=>{s=setTimeout(()=>o(Error(`${r} timed out after ${i}ms`)),i)});try{return await Promise.race([t,n])}finally{if(s)clearTimeout(s)}}var Tt=null,Or=!1;async function Ba(t,i){try{await T.workspaceQuery(Dd,{id:t,input:{status:i}})}catch{}}async function Xa(t){if(!T.isConfigured()||Or)return;Or=!0;let i=e().logger;try{let r=await t.getConfig("gateway-auth:agentRecordId");if(!r)return;let s=await T.workspaceQuery(kd,{agentId:r});if(s.errors?.length)return;let n=s.data?.vibecontrolsAgentProfiles??[];if(n.length===0)return;let a=e().name,o;try{o=await X({dir:di(a),scope:a})}catch{o=void 0}for(let c of n){if(c.isDefault||c.name===a||c.name==="default")continue;let l=N.get(c.name);if(l&&l.getBootState()==="ready"){if(c.status!=="ready")await Ba(c.id,"ready");continue}if(o?.clientId&&o.clientSecret&&!await Va(c.name))try{if(bd(di(c.name),{recursive:!0}),M({globalGatewayUrl:o.globalGatewayUrl,workspaceGatewayUrl:o.workspaceGatewayUrl,workspaceId:o.workspaceId,organizationId:o.organizationId,clientId:o.clientId,clientSecret:o.clientSecret},{dir:di(c.name),scope:O(c.name)}),!await Ld(c.name)){i.warn(bt,`Seeded creds for profile '${c.name}' not yet readable; retrying next tick`);continue}}catch(d){i.warn(bt,`Failed to seed config for profile '${c.name}'`,{error:d instanceof Error?d.message:String(d)});continue}i.info(bt,`Reconciling desired profile '${c.name}' from control plane`);try{let d=at(c.name),u=await Pd(hi(d),Cd,`attach '${c.name}'`),f=d.getBootState();await Ba(c.id,f),i.info(bt,`Profile '${c.name}' reconciled`,{ok:u.ok,status:f,error:u.error})}catch(d){i.warn(bt,`Failed to reconcile profile '${c.name}'`,{error:d instanceof Error?d.message:String(d)})}}}catch(r){e().logger.debug(bt,`Reconcile pass failed: ${r instanceof Error?r.message:String(r)}`)}finally{Or=!1}}function Ot(t,i){if(Tt)return;let r=Number(process.env.VIBE_PROFILE_RECONCILE_MS),s=Number.isFinite(r)&&r>0?Math.max(r,Rd):i??Od;Xa(t),Tt=setInterval(()=>{Xa(t)},s),Tt.unref?.()}function fi(){if(Tt)clearInterval(Tt),Tt=null}var et=10,Cr=3000,y="auto-report",Wa=`
|
|
134
134
|
mutation RegisterInstalledAgent($workspaceId: ID!, $input: RegisterInstalledAgentInput!) {
|
|
135
135
|
registerInstalledAgent(workspaceId: $workspaceId, input: $input) {
|
|
136
136
|
id
|
|
@@ -147,7 +147,7 @@ data: /message
|
|
|
147
147
|
tunnelStatus
|
|
148
148
|
}
|
|
149
149
|
}
|
|
150
|
-
`,
|
|
150
|
+
`,gi=`
|
|
151
151
|
query FindExistingAgent($workspaceId: ID!) {
|
|
152
152
|
vibecontrolsAgents(filter: { workspaceId: $workspaceId }) {
|
|
153
153
|
id
|
|
@@ -155,7 +155,7 @@ data: /message
|
|
|
155
155
|
tunnelUrl
|
|
156
156
|
}
|
|
157
157
|
}
|
|
158
|
-
`,
|
|
158
|
+
`,Md=`
|
|
159
159
|
mutation AgentHeartbeat($id: ID!) {
|
|
160
160
|
vibecontrolsAgentHeartbeat(id: $id) {
|
|
161
161
|
id
|
|
@@ -163,16 +163,16 @@ data: /message
|
|
|
163
163
|
lastHeartbeat
|
|
164
164
|
}
|
|
165
165
|
}
|
|
166
|
-
`,
|
|
166
|
+
`,jd=`
|
|
167
167
|
mutation DeactivateVibecontrolsAgent($id: ID!) {
|
|
168
168
|
deactivateVibecontrolsAgent(id: $id) {
|
|
169
169
|
id
|
|
170
170
|
isActive
|
|
171
171
|
}
|
|
172
172
|
}
|
|
173
|
-
`;async function
|
|
173
|
+
`;async function qd(t){if(process.env.AGENT_TUNNEL_URL){let i=xt(process.env.AGENT_TUNNEL_URL);if(!i)return e().logger.warn(y,"Ignoring invalid AGENT_TUNNEL_URL"),null;return e().logger.debug(y,`Using AGENT_TUNNEL_URL from environment: ${i}`),i}for(let i=1;i<=et;i++){let r=[],s=t.getProvider("tunnel");if(s)r.push(s);for(let n of t.listProvidersForType("tunnel")){let a=t.getProviderByName("tunnel",n.pluginName);if(a&&!r.includes(a))r.push(a)}for(let n of r){if(!n.getActiveTunnelUrl)continue;let a=await n.getActiveTunnelUrl(),o=ci(a);if(o)return e().logger.debug(y,`Tunnel URL available on attempt ${i}: ${o}`),o;if(a)e().logger.warn(y,"Tunnel provider returned invalid URL",{url:a})}if(i<et)e().logger.debug(y,`Tunnel URL not ready, retrying in ${Cr/1000}s (attempt ${i}/${et})`),await new Promise((n)=>setTimeout(n,Cr))}return e().logger.warn(y,`Tunnel URL not available after ${et} attempts`),null}async function Nr(t,i){let r=await t.getConfig("gateway-auth:agentRecordId");if(r)return r;let s=await t.getConfig("gateway-auth:workspaceId");if(!s)return null;let n=await T.workspaceQuery(gi,{workspaceId:s});if(n.errors?.length)return e().logger.warn(y,"Failed to discover existing agent record",{errors:n.errors.map((c)=>c.message)}),null;let a=i.toLowerCase(),o=n.data?.vibecontrolsAgents?.find((c)=>c.hostname.toLowerCase()===a);if(!o)return null;return await t.setConfig("gateway-auth:agentRecordId",o.id),e().logger.info(y,"Recovered existing agent record ID",{agentRecordId:o.id,hostname:i}),o.id}async function Ud(t,i){try{let r=await T.workspaceQuery(gi,{workspaceId:t});if(r.errors?.length)return!0;let s=r.data?.vibecontrolsAgents;if(!s)return!0;return s.some((n)=>n.id===i)}catch{return!0}}async function yi(t,i){if(!T.isConfigured())return;let r=await Nr(t,process.env.VIBE_AGENT_NAME||ui.hostname());if(!r)return;if(i!=="killed"){e().logger.debug(y,`Skipping '${i}' lifecycle sync \u2014 startup auto-report already refreshes the live agent record and the current backend schema has no dedicated lifecycle field.`);return}let s=await T.workspaceQuery(jd,{id:r});if(s.errors?.length)e().logger.warn(y,`Failed to report lifecycle state '${i}'`,{errors:s.errors.map((n)=>n.message)});else e().logger.info(y,`Reported lifecycle state: ${i}`)}async function Ga(t,i,r){let s=r||T.getConfig()?.workspaceId||"";for(let n=1;n<=3;n++){await new Promise((l)=>setTimeout(l,1500));let c=(await T.workspaceQuery(gi,{workspaceId:s})).data?.vibecontrolsAgents?.find((l)=>l.id===t)?.tunnelUrl??null;if(c===i)return e().logger.info(y,`Verified: backend tunnelUrl matches (attempt ${n})`),!0;e().logger.warn(y,`Verification failed (attempt ${n}/3): backend has '${c}', expected '${i}' \u2014 retrying update`),await T.workspaceQuery(Mt,{id:t,input:{tunnelUrl:i||null,tunnelStatus:i?"CONNECTED":"DISCONNECTED"}})}return e().logger.error(y,"Failed to verify tunnel URL update after 3 attempts"),!1}async function Ha(t,i){try{let r=await T.workspaceQuery(Wa,{workspaceId:t,input:{name:i.hostname,hostname:i.hostname,platform:i.platform,architecture:i.arch,tunnelUrl:i.tunnelUrl||null,agentApiKey:i.apiKey}});if(r.errors?.length)e().logger.debug(y,"API key re-assertion returned errors (non-fatal)",{errors:r.errors.map((s)=>s.message)});else e().logger.debug(y,"Re-asserted agent API key to backend")}catch(r){e().logger.debug(y,`API key re-assertion failed (non-fatal): ${r instanceof Error?r.message:String(r)}`)}}async function _i(t){try{let i=await T.workspaceQuery(Md,{id:t});if(i.errors?.length)e().logger.debug(y,"Heartbeat returned errors",{errors:i.errors.map((r)=>r.message)});else e().logger.debug(y,"Heartbeat sent successfully")}catch(i){e().logger.debug(y,`Heartbeat failed: ${i instanceof Error?i.message:String(i)}`)}}var Fd=`
|
|
174
174
|
mutation NotifyVibecontrolsAgentPluginChange($agentId: ID!) {
|
|
175
175
|
notifyVibecontrolsAgentPluginChange(agentId: $agentId)
|
|
176
176
|
}
|
|
177
|
-
`;async function
|
|
178
|
-
export{
|
|
177
|
+
`;async function rr(t){try{if(!T.isConfigured())return;let i=await t.getConfig("gateway-auth:agentRecordId");if(!i)return;let r=await T.workspaceQuery(Fd,{agentId:i});if(r.errors?.length)e().logger.debug(y,"Plugin-change notify returned errors",{errors:r.errors.map((s)=>s.message)})}catch(i){e().logger.debug(y,`Plugin-change notify failed: ${i instanceof Error?i.message:String(i)}`)}}var Nt=null,gt=null,Ct=!1;function Pt(t,i,r){if(Nt)return;let s=Number(process.env.VIBE_TUNNEL_SYNC_MS),n=Number.isFinite(s)&&s>0?s:r??60000;Nt=setInterval(async()=>{if(!T.isConfigured())return;try{let a=i.getProvider("tunnel");if(!a||!a.getActiveTunnelUrl)return;let o=Wt(await a.getActiveTunnelUrl()),c=await t.getConfig("gateway-auth:agentRecordId");if(!c)return;if(await _i(c),!o){if(!Ct)Ct=!(await T.workspaceQuery(Mt,{id:c,input:{tunnelStatus:"DISCONNECTED"}})).errors?.length,e().logger.warn(y,"No active tunnel URL \u2014 reported tunnel as DISCONNECTED",{reported:Ct});return}let l=Ct,d=T.getConfig()?.workspaceId||"",u;if(d)u=(await T.workspaceQuery(gi,{workspaceId:d})).data?.vibecontrolsAgents?.find((g)=>g.id===c)?.tunnelUrl??null;let f=o!==gt,h=u!==void 0&&u!==o;if(!f&&!h&&!l)return;e().logger.info(y,"Re-publishing tunnel URL",{reason:l?"tunnel-recovered":h?"backend-drift":"local-change",backend:u,local:o,lastReported:gt});let _=await T.workspaceQuery(Mt,{id:c,input:{tunnelUrl:o,tunnelStatus:"CONNECTED"}});if(!_.errors?.length)gt=o,Ct=!1,e().logger.info(y,"Tunnel URL synced to backend",{tunnelUrl:o});else e().logger.warn(y,"Tunnel URL sync returned errors",{errors:_.errors.map((p)=>p.message)})}catch(a){e().logger.debug(y,`Tunnel sync check failed: ${a instanceof Error?a.message:String(a)}`)}},n),Nt.unref?.()}function pi(){if(Nt)clearInterval(Nt),Nt=null;Ct=!1,gt=null}async function Rr(t,i){if(process.env.VIBE_BRIDGE_DISABLED==="1")return;try{let{bridgeClient:r}=await import("./bridge-client-9ax1cvj6.js"),{registerBridgeCommands:s,registerPluginBridgeService:n}=await import("./bridge-commands-xhzhghxt.js");s(r,t),n(t,r);let a=process.env.VIBECONTROLS_PROFILE||"default";r.start(i,a)}catch(r){e().logger.warn(y,`bridge-client start failed: ${r instanceof Error?r.message:String(r)}`)}}async function mi(t,i,r){if(!T.isConfigured()){e().logger.debug(y,"Gateway auth not configured \u2014 skipping auto-report");return}let s=await t.getConfig("gateway-auth:workspaceId");if(!s){e().logger.warn(y,"No workspaceId configured \u2014 skipping auto-report. "+"Configure via POST /api/agent/gateway-auth with workspaceId.");return}e().logger.info(y,"Starting auto-report to backend...");try{let n=process.env.VIBE_AGENT_NAME||ui.hostname(),a=ui.platform(),o=ui.arch(),c=Ae(),l=await qd(i),d=await Nr(t,n);if(d){e().logger.info(y,`Updating agent record ${d} via workspace gateway`);let f=await T.workspaceQuery(Mt,{id:d,input:{tunnelUrl:l||null,tunnelStatus:l?"CONNECTED":"DISCONNECTED",agentApiKey:r}});if(f.errors?.length){if(e().logger.warn(y,"Update mutation returned errors",{errors:f.errors.map((_)=>_.message)}),await Ud(s,d)){e().logger.warn(y,"Agent record still exists \u2014 treating update failure as transient; will retry on next sync (NOT registering a duplicate)",{agentRecordId:d}),await Rr(i,d),await Ha(s,{hostname:n,platform:a,arch:o,tunnelUrl:l,apiKey:r}),await _i(d),gt=l,Pt(t,i),Ot(t);return}e().logger.info(y,"Cached agent record no longer exists \u2014 clearing cache and registering fresh",{agentRecordId:d}),await t.setConfig("gateway-auth:agentRecordId",""),d=null}else{e().logger.info(y,"Agent record updated successfully",{agentRecordId:d,tunnelUrl:l}),await Rr(i,d),await Ga(d,l,s),await Ha(s,{hostname:n,platform:a,arch:o,tunnelUrl:l,apiKey:r}),await _i(d),gt=l,Pt(t,i),Ot(t);return}}e().logger.info(y,`Registering installed agent via workspace gateway (hostname: ${n})`);for(let f=1;f<=et&&!d;f++){if(f>1){let g=await Nr(t,n);if(g){d=g,e().logger.info(y,"Adopted an agent record discovered after a retry (not registering a duplicate)",{agentRecordId:d});break}}let h=await T.workspaceQuery(Wa,{workspaceId:s,input:{name:n,hostname:n,platform:a,architecture:o,tunnelUrl:l||null,agentApiKey:r}}),_=h.errors?.length?void 0:h.data?.registerInstalledAgent?.id;if(_){await t.setConfig("gateway-auth:agentRecordId",_),d=_,e().logger.info(y,"Agent registered successfully",{agentRecordId:_,name:h.data?.registerInstalledAgent?.name,tunnelUrl:l,version:c,attempt:f});break}let p=h.errors?.length?h.errors.map((g)=>g.message):["registerInstalledAgent returned no id"];if(f<et){let g=Math.min(30000,Cr*2**(f-1));e().logger.warn(y,`Register installed agent failed (attempt ${f}/${et}) \u2014 retrying in ${Math.round(g/1000)}s`,{errors:p}),await new Promise((m)=>setTimeout(m,g));continue}e().logger.error(y,"Register installed agent failed after retries \u2014 agent is running but NOT registered with the workspace",{errors:p}),e().recordDegradedReason("agent-registration",`registerInstalledAgent failed after ${et} attempts: ${p.join("; ")}`)}if(!d){Pt(t,i),Ot(t);return}let u=await T.workspaceQuery(Mt,{id:d,input:{tunnelUrl:l||null,tunnelStatus:l?"CONNECTED":"DISCONNECTED"}});if(u.errors?.length)e().logger.warn(y,"Post-registration agent update returned errors",{errors:u.errors.map((f)=>f.message)});else e().logger.info(y,"Post-registration agent sync completed",{agentRecordId:d,tunnelUrl:l});await Rr(i,d),await Ga(d,l,s),await _i(d),gt=l,Pt(t,i),Ot(t)}catch(n){e().logger.error(y,`Auto-report failed: ${n instanceof Error?n.message:String(n)}`);try{Pt(t,i),Ot(t)}catch{}}}var x="lifecycle";class Rt{serviceRegistry;pluginManager;db;app;hostServices;appStopFn;state="running";transition=Promise.resolve();constructor(t,i,r,s,n,a){this.serviceRegistry=t;this.pluginManager=i;this.db=r;this.app=s;this.hostServices=n;this.appStopFn=a}getState(){return this.state}enqueueTransition(t,i){let r=this.transition.then(i,i);return this.transition=r.catch((s)=>{e().logger.warn(x,`Lifecycle transition '${t}' failed`,{error:String(s)})}),r}async stop(){return this.enqueueTransition("stop",async()=>{if(this.state==="stopped"){e().logger.warn(x,"Agent is already stopped");return}e().logger.info(x,"Stopping agent..."),this.state="stopped";let t=this.serviceRegistry.getProvider("session");if(t)try{let i=await t.list();for(let r of i)if(r.status==="active")try{await t.kill(r.id),e().logger.debug(x,`Killed session ${r.id}`)}catch(s){e().logger.warn(x,`Failed to kill session ${r.id}`,{error:String(s)})}}catch(i){e().logger.warn(x,"Failed to list/stop sessions",{error:String(i)})}try{await this.pluginManager.dispatchServerStop()}catch(i){e().logger.warn(x,"Error during plugin stop dispatch",{error:String(i)})}e().logger.info(x,"Agent stopped (tunnel + HTTP still alive)");try{await yi(this.db,"stopped")}catch(i){e().logger.warn(x,"Failed to report stopped state to backend",{error:String(i)})}})}async start(){return this.enqueueTransition("start",async()=>{if(this.state==="running"){e().logger.warn(x,"Agent is already running");return}e().logger.info(x,"Starting agent..."),this.state="running";try{await this.pluginManager.dispatchServerStart(this.app,this.hostServices),await this.pluginManager.dispatchServerReady(this.app,this.hostServices)}catch(t){e().logger.warn(x,"Error during plugin start dispatch",{error:String(t)})}e().logger.info(x,"Agent started");try{await yi(this.db,"running")}catch(t){e().logger.warn(x,"Failed to report running state to backend",{error:String(t)})}})}async softStop(){return this.enqueueTransition("softStop",async()=>{e().logger.info(x,"Soft-stopping agent (hot-reload)...");try{await this.pluginManager.dispatchServerStop({reason:"reload"})}catch(t){e().logger.warn(x,"Error during plugin soft-stop dispatch",{error:String(t)})}try{await this.appStopFn({reason:"reload"})}catch{}e().logger.info(x,"Agent soft-stopped \u2014 exiting for reload"),process.exit(0)})}async prepareForReset(){return this.enqueueTransition("prepareForReset",async()=>{e().logger.info(x,"Preparing agent for reset..."),this.state="stopped";try{await this.pluginManager.dispatchServerStop({reason:"shutdown"})}catch(t){e().logger.warn(x,"Error during reset stop dispatch",{error:String(t)})}})}async kill(){return this.enqueueTransition("kill",async()=>{e().logger.info(x,"Killing agent...");try{await Promise.race([yi(this.db,"killed"),new Promise((i,r)=>setTimeout(()=>r(Error("Timeout")),5000))])}catch(i){e().logger.warn(x,"Failed to report killed state to backend",{error:String(i)})}let t=this.serviceRegistry.getProvider("tunnel");if(t)try{let i=await t.list();for(let r of i)try{await t.stop(r.id)}catch{}}catch(i){e().logger.warn(x,"Failed to stop tunnels",{error:String(i)})}try{await this.appStopFn()}catch{}e().logger.info(x,"Agent killed \u2014 exiting process"),process.exit(0)})}}
|
|
178
|
+
export{er,tr,Rt,hi,fi,rr,pi,mi};
|