@vibecontrols/agent 2026.1130.1 → 2026.1202.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (71) hide show
  1. package/dist/{agent-config-xwvsmn6b.js → agent-config-mg5dvtm3.js} +1 -1
  2. package/dist/{agent-ready-tracker-7ebr09d9.js → agent-ready-tracker-b1dxkhrt.js} +1 -1
  3. package/dist/app-hvt8zawq.js +2 -0
  4. package/dist/autostart.cmd-4c0rekqt.js +2 -0
  5. package/dist/bootstrap-workspace-wsjzmm9n.js +2 -0
  6. package/dist/bootstrap.service-0m0rcq8d.js +2 -0
  7. package/dist/{bridge-client-9ax1cvj6.js → bridge-client-fcwk5tyk.js} +1 -1
  8. package/dist/{bridge-commands-hc1gvngq.js → bridge-commands-xagq5kq7.js} +1 -1
  9. package/dist/cli.js +1 -1
  10. package/dist/daemon-profile-0bvscqm2.js +2 -0
  11. package/dist/{finalize-retry-worker-c38km3mt.js → finalize-retry-worker-qe7zagk7.js} +1 -1
  12. package/dist/gateway-client-8gfze3jv.js +2 -0
  13. package/dist/{index-dr6rsnpk.js → index-2a1yq04v.js} +3 -3
  14. package/dist/{index-dgbe8jm8.js → index-2nq1tefj.js} +1 -1
  15. package/dist/{index-j99tkngg.js → index-30qr1qm3.js} +1 -1
  16. package/dist/{index-ednz6yz2.js → index-4qqsx04e.js} +1 -1
  17. package/dist/{index-twtvt4yt.js → index-5ygnxt32.js} +3 -3
  18. package/dist/{index-rhn7wy1p.js → index-6g3qhprq.js} +1 -1
  19. package/dist/{index-5tghd67e.js → index-6xd9k363.js} +6 -6
  20. package/dist/{index-j9jwwzq2.js → index-8y4fys3s.js} +7 -7
  21. package/dist/{index-yfk0pb00.js → index-ag2b7yeg.js} +1 -1
  22. package/dist/{index-bk17490n.js → index-c9q14161.js} +1 -1
  23. package/dist/{index-damc6cvc.js → index-djwa3tm3.js} +1 -1
  24. package/dist/{index-0rmmrrfh.js → index-ep20qw1j.js} +1 -1
  25. package/dist/{index-6nv5rdqh.js → index-fm1wjs3r.js} +1 -1
  26. package/dist/{index-12gb48hg.js → index-j9cg16we.js} +1 -1
  27. package/dist/{index-f5nmxa9e.js → index-jhgd7sva.js} +1 -1
  28. package/dist/{index-76vza24h.js → index-mrcjqvnf.js} +1 -1
  29. package/dist/{index-p7fbnfwd.js → index-n3kwtv6f.js} +2 -2
  30. package/dist/{index-e5jdx9c1.js → index-nqa1m94e.js} +2 -2
  31. package/dist/index-nxpw3anc.js +30 -0
  32. package/dist/{index-zcnfj1q4.js → index-prp5nvsa.js} +3 -3
  33. package/dist/{index-qzwbctkv.js → index-pw6aqemr.js} +4 -4
  34. package/dist/{index-4kf3nr14.js → index-r1v0yazw.js} +2 -2
  35. package/dist/{index-q4fht6h2.js → index-r2j1t657.js} +19 -19
  36. package/dist/{index-vhz1c474.js → index-tn2vyz8q.js} +1 -1
  37. package/dist/{index-br9bakfm.js → index-txchzvfc.js} +2 -2
  38. package/dist/{index-85jn7v8t.js → index-xertgyzn.js} +5 -5
  39. package/dist/{index-wxb9dgwq.js → index-zekdqp0t.js} +1 -1
  40. package/dist/{index-8jk4a62x.js → index-zfhmg1gz.js} +6 -6
  41. package/dist/{index-sjs32cgn.js → index-zngtj9re.js} +2 -2
  42. package/dist/index.js +2 -2
  43. package/dist/key.cmd-eevbsknq.js +2 -0
  44. package/dist/log-shipper-h7azf3f8.js +2 -0
  45. package/dist/{path-utils-qgkdkp5j.js → path-utils-3sgj48ta.js} +1 -1
  46. package/dist/plugin-system-e1a3ttpy.js +2 -0
  47. package/dist/prereqs-runner-etehmhk8.js +2 -0
  48. package/dist/profile-mount-rr5kr708.js +2 -0
  49. package/dist/register-core-7kb2k9g3.js +2 -0
  50. package/dist/secondary-profile-attach-2x3dsnn8.js +2 -0
  51. package/dist/subprocess-j0r8hvmc.js +2 -0
  52. package/dist/telemetry-fyced899.js +2 -0
  53. package/dist/tunnel-bootstrap-rm5k7qw4.js +2 -0
  54. package/package.json +1 -1
  55. package/dist/app-ntnpwedw.js +0 -2
  56. package/dist/autostart.cmd-mdyv35dn.js +0 -2
  57. package/dist/bootstrap-workspace-1pt0bwy6.js +0 -2
  58. package/dist/bootstrap.service-gehm65tt.js +0 -2
  59. package/dist/daemon-profile-fnhc7pcf.js +0 -2
  60. package/dist/gateway-client-3zp6kkav.js +0 -2
  61. package/dist/index-7wm4bqx5.js +0 -21
  62. package/dist/key.cmd-y415ngam.js +0 -2
  63. package/dist/log-shipper-02rqvtq8.js +0 -2
  64. package/dist/plugin-system-e690jr6e.js +0 -2
  65. package/dist/prereqs-runner-w7z2dwa6.js +0 -2
  66. package/dist/profile-mount-ga5z1vx9.js +0 -2
  67. package/dist/register-core-n1dy472f.js +0 -2
  68. package/dist/secondary-profile-attach-v7kxsk4z.js +0 -2
  69. package/dist/subprocess-p9bv9nqz.js +0 -2
  70. package/dist/telemetry-1d3t1mbf.js +0 -2
  71. package/dist/tunnel-bootstrap-m51w4d94.js +0 -2
@@ -1,7 +1,7 @@
1
1
  // @bun
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-8jk4a62x.js";import{K}from"./index-qzwbctkv.js";import{_t}from"./index-p7fbnfwd.js";import{xe,Ie,ve}from"./index-br9bakfm.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(`
2
+ import{z,ci,Wt,xt,T,O,C,D,e,at}from"./index-nxpw3anc.js";import{M,X}from"./index-30qr1qm3.js";import{Ae,W}from"./index-zfhmg1gz.js";import{K}from"./index-pw6aqemr.js";import{_t}from"./index-n3kwtv6f.js";import{xe,Ie,ve}from"./index-txchzvfc.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 k 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 k("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 k("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 k("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 k("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got ${t}`,{ttl:t});return t*1000}if(typeof t!=="string")throw new k("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 k("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 k("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 k("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 k("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 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.
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 k("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 k("ERR_SKALEX_VALIDATION_MIGRATION",`Migration version must be a positive integer, got ${i}`,{version:i});if(typeof r!=="function")throw new k("ERR_SKALEX_VALIDATION_MIGRATION",`Migration version ${i} must have an "up" function`,{version:i});if(this._migrations.some((s)=>s.version===i))throw new k("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 k("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 k("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
@@ -25,7 +25,7 @@ data: /message
25
25
 
26
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,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(`
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=k,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 k("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
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
 
@@ -103,7 +103,7 @@ data: /message
103
103
 
104
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 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!) {
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 N(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 N(r)}async getTask(t){let i=await this.tasks.findOne({id:t});return i?N(i):void 0}async getAllTasks(){return(await this.tasks.find(void 0,{sort:{createdAt:-1}})).docs.map((t)=>N(t))}async getPendingTasks(){return(await this.tasks.find({status:"pending"},{sort:{createdAt:1}})).docs.map((t)=>N(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 N(r)}async getGitRepository(t){let i=await this.gitRepos.findOne({id:t});return i?N(i):void 0}async getGitRepositoryByPath(t){let i=await this.gitRepos.findOne({path:t});return i?N(i):void 0}async getAllGitRepositories(){return(await this.gitRepos.find(void 0,{sort:{path:1}})).docs.map((t)=>N(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 N(r)}async getBookmarkedCommand(t){let i=await this.bookmarks.findOne({id:t});return i?N(i):void 0}async getAllBookmarkedCommands(){return(await this.bookmarks.find(void 0,{sort:{createdAt:-1}})).docs.map((t)=>N(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)=>N(r))}async getBookmarkedCommandsByCategory(t){return(await this.bookmarks.find({category:t},{sort:{createdAt:-1}})).docs.map((i)=>N(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 N(r)}async getNotification(t){let i=await this.notifications.findOne({id:t});return i?N(i):void 0}async getAllNotifications(){return(await this.notifications.find(void 0,{sort:{createdAt:-1}})).docs.map((t)=>N(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)=>N(r))}async getGlobalNotifications(){return this.getNotificationsByProject(null)}async getUnreadNotifications(){return(await this.notifications.find({status:"unread"},{sort:{createdAt:-1}})).docs.map((t)=>N(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
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) {
@@ -130,7 +130,7 @@ data: /message
130
130
  status
131
131
  }
132
132
  }
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=`
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=D.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
@@ -174,5 +174,5 @@ data: /message
174
174
  mutation NotifyVibecontrolsAgentPluginChange($agentId: ID!) {
175
175
  notifyVibecontrolsAgentPluginChange(agentId: $agentId)
176
176
  }
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-hc1gvngq.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)})}}
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-fcwk5tyk.js"),{registerBridgeCommands:s,registerPluginBridgeService:n}=await import("./bridge-commands-xagq5kq7.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
178
  export{er,tr,Rt,hi,fi,rr,pi,mi};