@vibecontrols/vibe-plugin-storage 2026.601.1 → 2026.1110.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 (2) hide show
  1. package/dist/index.js +6 -6
  2. package/package.json +34 -21
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
1
  // @bun
2
- var __require=import.meta.require;import{existsSync as existsSync5,readFileSync as readFileSync5}from"fs";import{dirname,join as joinPath}from"path";import{fileURLToPath}from"url";function createLifecycleHooks(spec){let{name,onInit,onShutdown,onNuke,telemetryEventName,skipPlatforms}=spec;return{onServerStart:async(_app,hostServices)=>{if(skipPlatforms&&skipPlatforms.includes(process.platform)){process.stderr.write(`[${name}] skipping init on unsupported platform '${process.platform}'
3
- `);return}if(onInit)await onInit(hostServices);if(telemetryEventName)hostServices.telemetry?.emit(telemetryEventName,{plugin:name})},onServerStop:async(hostServices)=>{if(onShutdown)await onShutdown(hostServices)},onNuke:async(hostServices,ctx)=>{if(onNuke)return onNuke(hostServices,ctx)}}}var BoundLogger=class{constructor(logger,source){this.logger=logger,this.source=source}logger;source;info(message,meta){this.logger?.info?.(this.source,message,meta)}warn(message,meta){this.logger?.warn?.(this.source,message,meta)}error(message,meta){this.logger?.error?.(this.source,message,meta)}debug(message,meta){this.logger?.debug?.(this.source,message,meta)}};function currentSupportedOS(p=process.platform){if(p==="darwin")return"darwin";if(p==="win32")return"win32";return"linux"}async function provisionMetaProviders(host,metaProviders,platform=currentSupportedOS()){let plugins=host.plugins;if(!plugins||!metaProviders?.length)return;let skip=plugins.skipInstall?.()??!1;for(let ref of metaProviders){if(!ref.defaultOn?.includes(platform))continue;try{if(!skip)await plugins.install?.(ref.packageName,{refreshLatest:!0});if(await plugins.loadProvider?.(ref.packageName),await plugins.runPrereqs?.(ref.packageName,{skipInstall:skip}),ref.providerType&&ref.pluginName)await plugins.electDefault?.(ref.providerType,ref.pluginName)}catch{}}}var TelemetryEmitter=class{constructor(pluginName,pluginVersion,hostServices){this.pluginName=pluginName,this.pluginVersion=pluginVersion,this.hostServices=hostServices}pluginName;pluginVersion;hostServices;emit(eventName,payload){let target=this.hostServices?.telemetry;if(!target)return;target.emit(eventName,{plugin:this.pluginName,version:this.pluginVersion,timestamp:new Date().toISOString(),...payload??{}})}emitReady(context){this.emit(`${this.pluginName}.ready`,context)}emitError(error,context){this.emit(`${this.pluginName}.error`,{message:error.message,...context??{}})}emitEvent(type,payload){this.emit(type,payload)}};import{closeSync as closeSync4,existsSync as existsSync4,mkdirSync as mkdirSync4,openSync as openSync4,readFileSync as readFileSync4,unlinkSync as unlinkSync4,writeFileSync as writeFileSync4}from"fs";import{join as join4}from"path";import nodeCrypto from"crypto";import nodePath from"path";import nodeFs from"fs";import zlib from"zlib";import http from"http";import{closeSync as closeSync3,existsSync as existsSync3,mkdirSync as mkdirSync3,openSync as openSync3,readFileSync as readFileSync3,unlinkSync as unlinkSync3,writeFileSync as writeFileSync3}from"fs";import{join as join3}from"path";import nodeCrypto2 from"crypto";import nodePath2 from"path";import nodeFs2 from"fs";import zlib2 from"zlib";import http2 from"http";import{closeSync as closeSync2,existsSync as existsSync2,mkdirSync as mkdirSync2,openSync as openSync2,readFileSync as readFileSync2,unlinkSync as unlinkSync2,writeFileSync as writeFileSync2}from"fs";import{join as join2}from"path";import nodeCrypto22 from"crypto";import nodePath22 from"path";import nodeFs22 from"fs";import zlib22 from"zlib";import http22 from"http";import{closeSync,existsSync,mkdirSync,openSync,readFileSync,unlinkSync,writeFileSync}from"fs";import{join}from"path";import nodeCrypto222 from"crypto";import nodePath222 from"path";import nodeFs222 from"fs";import zlib222 from"zlib";import http222 from"http";function generateUniqueId(){let timestamp=Date.now().toString(16),random;try{random=nodeCrypto.randomBytes(8).toString("hex")}catch{let arr=new Uint8Array(8);crypto.getRandomValues(arr),random=Array.from(arr).map((b)=>b.toString(16).padStart(2,"0")).join("")}return`${timestamp}${random}`}function logger(error,type){let msg=error instanceof Error?error.message:error;if(type==="error")console.error(msg);else console.log(msg)}var _FORBIDDEN_KEYS=new Set(["__proto__","constructor","prototype"]);function resolveDotPath(obj,path){if(!path.includes(".")){if(_FORBIDDEN_KEYS.has(path))return;return obj[path]}let cur=obj;for(let p of path.split(".")){if(_FORBIDDEN_KEYS.has(p))return;if(cur==null)return;cur=cur[p]}return cur}class SkalexError extends Error{constructor(code,message,details={}){super(message);this.name=this.constructor.name,this.code=code,this.details=details}}class ValidationError extends SkalexError{}class UniqueConstraintError extends SkalexError{}class TransactionError extends SkalexError{}class PersistenceError extends SkalexError{}class AdapterError extends SkalexError{}class QueryError extends SkalexError{}function deepEqual(a,b){if(a===b)return!0;if(a==null||b==null)return!1;if(typeof a!==typeof b)return!1;if(a instanceof Date&&b instanceof Date)return a.getTime()===b.getTime();if(a instanceof RegExp&&b instanceof RegExp)return a.source===b.source&&a.flags===b.flags;if(Array.isArray(a)){if(!Array.isArray(b)||a.length!==b.length)return!1;for(let i=0;i<a.length;i++)if(!deepEqual(a[i],b[i]))return!1;return!0}if(typeof a==="object"){if(Array.isArray(b))return!1;let keysA=Object.keys(a);if(keysA.length!==Object.keys(b).length)return!1;for(let k of keysA){if(!Object.prototype.hasOwnProperty.call(b,k))return!1;if(!deepEqual(a[k],b[k]))return!1}return!0}return!1}function matchesFilter(item,filter){if(typeof filter==="function")return filter(item);if(filter==null)return!0;if(typeof filter==="object"&&Object.keys(filter).length===0)return!0;if("$or"in filter){let branches=filter.$or;if(!Array.isArray(branches))throw new QueryError("ERR_SKALEX_QUERY_INVALID_OPERATOR","$or must be an array of filters",{operator:"$or"});if(!branches.some((sub)=>matchesFilter(item,sub)))return!1}if("$and"in filter){let branches=filter.$and;if(!Array.isArray(branches))throw new QueryError("ERR_SKALEX_QUERY_INVALID_OPERATOR","$and must be an array of filters",{operator:"$and"});if(!branches.every((sub)=>matchesFilter(item,sub)))return!1}if("$not"in filter){if(matchesFilter(item,filter.$not))return!1}for(let key in filter){if(key==="$or"||key==="$and"||key==="$not")continue;let filterValue=filter[key],itemValue;try{itemValue=resolveDotPath(item,key)}catch{return!1}if(filterValue instanceof RegExp){if(!filterValue.test(String(itemValue)))return!1}else if(typeof filterValue==="object"&&filterValue!==null){if(Object.keys(filterValue).some((k)=>k.startsWith("$"))){if("$eq"in filterValue&&itemValue!==filterValue.$eq)return!1;if("$ne"in filterValue&&itemValue===filterValue.$ne)return!1;if("$gt"in filterValue&&!(itemValue>filterValue.$gt))return!1;if("$lt"in filterValue&&!(itemValue<filterValue.$lt))return!1;if("$gte"in filterValue&&!(itemValue>=filterValue.$gte))return!1;if("$lte"in filterValue&&!(itemValue<=filterValue.$lte))return!1;if("$in"in filterValue&&!filterValue.$in.includes(itemValue))return!1;if("$nin"in filterValue&&filterValue.$nin.includes(itemValue))return!1;if("$regex"in filterValue){if(!(filterValue.$regex instanceof RegExp?filterValue.$regex:new RegExp(filterValue.$regex)).test(String(itemValue)))return!1}if("$fn"in filterValue&&!filterValue.$fn(itemValue))return!1}else if(!deepEqual(itemValue,filterValue))return!1}else if(itemValue!==filterValue)return!1}return!0}function presortFilter(filter,indexedFields=new Set){if(typeof filter!=="object"||filter===null||typeof filter==="function")return filter;let indexed=[],equality=[],range=[],expensive=[],logical=[];for(let key in filter){if(key==="$or"||key==="$and"||key==="$not"){logical.push(key);continue}let val=filter[key];if(indexedFields.has(key))indexed.push(key);else if(val instanceof RegExp||typeof val==="object"&&val!==null&&(("$regex"in val)||("$fn"in val))||typeof val==="function")expensive.push(key);else if(typeof val==="object"&&val!==null&&(("$gt"in val)||("$lt"in val)||("$gte"in val)||("$lte"in val)||("$ne"in val)||("$in"in val)||("$nin"in val)))range.push(key);else equality.push(key)}let sorted={};for(let k of[...indexed,...equality,...range,...expensive,...logical])sorted[k]=filter[k];return sorted}var SUPPORTED_TYPES=new Set(["string","number","boolean","object","array","date","any"]);function typeOf(val){if(Array.isArray(val))return"array";if(val instanceof Date)return"date";return typeof val}function parseSchema(schema){let fields=new Map,uniqueFields=[];for(let[key,def]of Object.entries(schema)){let fieldDef;if(typeof def==="string"){if(!SUPPORTED_TYPES.has(def))throw new ValidationError("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${def}" for field "${key}"`,{field:key,type:def});fieldDef={type:def,required:!1,unique:!1}}else if(typeof def==="object"&&def!==null){let{type="any",required=!1,unique=!1,enum:enumVals}=def;if(!SUPPORTED_TYPES.has(type))throw new ValidationError("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${type}" for field "${key}"`,{field:key,type});if(fieldDef={type,required,unique,enum:enumVals},unique)uniqueFields.push(key)}else throw new ValidationError("ERR_SKALEX_VALIDATION_INVALID_SCHEMA",`Invalid schema definition for field "${key}"`,{field:key});fields.set(key,fieldDef)}return{fields,uniqueFields}}function validateDoc(doc,fields,strict=!1){let errors=[];for(let[key,def]of fields){let val=doc[key],missing=val===void 0||val===null;if(def.required&&missing){errors.push(`Field "${key}" is required`);continue}if(missing)continue;if(def.type!=="any"){let actualType=typeOf(val);if(actualType!==def.type)errors.push(`Field "${key}" must be of type "${def.type}", got "${actualType}"`)}if(def.enum&&!def.enum.includes(val))errors.push(`Field "${key}" must be one of [${def.enum.map((v)=>JSON.stringify(v)).join(", ")}], got ${JSON.stringify(val)}`)}if(strict){for(let key of Object.keys(doc))if(!key.startsWith("_")&&!fields.has(key))errors.push(`Unknown field "${key}" (strict mode)`)}return errors}function stripInvalidFields(doc,fields){let out={};for(let[key,val]of Object.entries(doc)){if(key.startsWith("_")){out[key]=val;continue}if(!fields.has(key))continue;let def=fields.get(key);if(def.type!=="any"){if(typeOf(val)!==def.type)continue}if(def.enum&&!def.enum.includes(val))continue;out[key]=val}return out}function inferSchema(doc){let schema={};for(let[key,val]of Object.entries(doc)){if(key.startsWith("_"))continue;let t=typeOf(val);schema[key]=SUPPORTED_TYPES.has(t)?t:"any"}return schema}function parseTtl(ttl){if(typeof ttl==="number"){if(ttl<=0)throw new ValidationError("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got ${ttl}`,{ttl});return ttl*1000}if(typeof ttl!=="string")throw new ValidationError("ERR_SKALEX_VALIDATION_TTL",`Invalid TTL value: ${ttl}`,{ttl});let match=ttl.match(/^(\d+(?:\.\d+)?)(ms|s|m|h|d)$/);if(!match)throw new ValidationError("ERR_SKALEX_VALIDATION_TTL_FORMAT",`Invalid TTL format: "${ttl}". Use e.g. 300 (seconds), "30m", "24h", "7d"`,{ttl});let val=parseFloat(match[1]);if(val<=0)throw new ValidationError("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got "${ttl}"`,{ttl});let unit=match[2],ms=val*{ms:1,s:1000,m:60000,h:3600000,d:86400000}[unit];if(!isFinite(ms))throw new ValidationError("ERR_SKALEX_VALIDATION_TTL",`TTL value "${ttl}" is too large`,{ttl});return ms}function computeExpiry(ttl){return new Date(Date.now()+parseTtl(ttl))}function sweep(data,idIndex,removeFromIndexes=null){let now=Date.now(),removed=0,i=data.length;while(i--){let doc=data[i];if(doc._expiresAt&&new Date(doc._expiresAt).getTime()<=now){if(data.splice(i,1),idIndex.delete(doc._id),removeFromIndexes)removeFromIndexes(doc);removed++}}return removed}function cosineSimilarity(a,b){if(a.length!==b.length)throw new QueryError("ERR_SKALEX_QUERY_VECTOR_MISMATCH",`Vector dimension mismatch: ${a.length} vs ${b.length}`,{expected:a.length,got:b.length});let dot=0,magA=0,magB=0;for(let i=0;i<a.length;i++)dot+=a[i]*b[i],magA+=a[i]*a[i],magB+=b[i]*b[i];let denom=Math.sqrt(magA*magB);return denom===0?0:dot/denom}function stripVector(doc){if(!("_vector"in doc))return{...doc};let{_vector,...rest}=doc;return rest}function count(docs){return docs.length}function sum(docs,field){let total=0;for(let doc of docs){let val=resolveDotPath(doc,field);if(typeof val==="number"&&!isNaN(val))total+=val}return total}function avg(docs,field){let total=0,n=0;for(let doc of docs){let val=resolveDotPath(doc,field);if(typeof val==="number"&&!isNaN(val))total+=val,n++}return n===0?null:total/n}function groupBy(docs,field){let groups=Object.create(null);for(let doc of docs){let key=String(resolveDotPath(doc,field)??"__null__");if(!groups[key])groups[key]=[];groups[key].push(doc)}return groups}class MutationPipeline{constructor(collection){this._col=collection}get _ctx(){return this._col._ctx}async execute({op,beforeHook,afterHook,hookPayload,mutate,afterHookPayload,save,session}){let ctx=this._ctx;await ctx.ensureConnected(),this._col._txSnapshotIfNeeded();let txm=ctx.txManager,isTxWrite=txm.active&&this._col._activeTxId===txm.context?.id,entryTxId=isTxWrite?txm.context.id:null,collTxId=this._col._createdInTxId,assertTxAlive=()=>{if(entryTxId!==null&&txm._abortedIds.has(entryTxId))throw new TransactionError("ERR_SKALEX_TX_ABORTED",`Transaction ${entryTxId} was aborted. No further mutations allowed.`);if(collTxId!==null&&txm._abortedIds.has(collTxId))throw new TransactionError("ERR_SKALEX_TX_ABORTED",`Transaction ${collTxId} was aborted. Collection obtained inside that transaction cannot be used for further mutations.`)};if(isTxWrite||collTxId!==null)assertTxAlive();if(beforeHook)await ctx.plugins.run(beforeHook,hookPayload);let{docs,prevDocs=[]}=await mutate(assertTxAlive);if(ctx.persistence.markDirty(ctx.collections,this._col.name),await this._col._saveIfNeeded(save),this._col._changelogEnabled)for(let i=0;i<docs.length;i++)await ctx.logChange(op,this._col.name,docs[i],prevDocs[i]??null,session||null);if(!isTxWrite||!txm.defer(()=>ctx.sessionStats.recordWrite(session)))ctx.sessionStats.recordWrite(session);for(let doc of docs)ctx.emitEvent(this._col.name,{op,collection:this._col.name,doc:stripVector(doc)});if(afterHook)if(afterHookPayload)await ctx.runAfterHook(afterHook,afterHookPayload(docs));else for(let doc of docs)await ctx.runAfterHook(afterHook,{collection:this._col.name,doc:stripVector(doc)});return{docs,prevDocs}}}function resolveFilterToValues(filter){let resolved={};for(let key in filter){if(key.startsWith("$"))continue;let val=filter[key];if(val&&typeof val==="object"&&!Array.isArray(val)){let keys=Object.keys(val);if(keys.length===1&&keys[0]==="$eq")resolved[key]=val.$eq}else resolved[key]=val}return resolved}var _DANGEROUS_KEYS=new Set(["__proto__","constructor","prototype"]);function stripDangerousKeys(val){if(typeof val!=="object"||val===null||Array.isArray(val))return val;let out={};for(let k of Object.keys(val)){if(_DANGEROUS_KEYS.has(k))continue;out[k]=stripDangerousKeys(val[k])}return out}class Collection{constructor(collectionData,database){this.name=collectionData.collectionName,this.database=database,this._ctx=database._buildCollectionContext(),this._store=collectionData,this._pipeline=new MutationPipeline(this),this._createdInTxId=database._txManager.context?.id??null,this._activeTxId=null}get _data(){return this._store.data}set _data(val){this._store.data=val}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(item,options={}){let{save,ifNotExists,ttl,embed,session}=options;if(ifNotExists){await this._ctx.ensureConnected();let existing=this._findRaw(item);if(existing)return stripVector({...existing})}let{docs}=await this._insertCore([item],{ttl,embed,session,save});return stripVector(docs[0])}async insertMany(items,options={}){let{save,ttl,embed,session}=options,{docs}=await this._insertCore(items,{ttl,embed,session,save});return docs.map(stripVector)}async _insertCore(items,{ttl,embed,session,save}){return this._pipeline.execute({op:"insert",beforeHook:null,afterHook:"afterInsert",hookPayload:null,save,session,mutate:async(assertTxAlive)=>{let newItems=[],batchIds=new Set;for(let item of items){let validated=this._applyValidation(item);await this._ctx.plugins.run("beforeInsert",{collection:this.name,doc:validated});let newItem=await this._buildDoc(validated,{ttl,embed});if(this._index.has(newItem._id)||batchIds.has(newItem._id))throw new UniqueConstraintError("ERR_SKALEX_UNIQUE_DUPLICATE_ID",`Duplicate _id "${newItem._id}" in collection "${this.name}"`,{id:newItem._id,collection:this.name});batchIds.add(newItem._id),newItems.push(newItem)}if(assertTxAlive(),this._fieldIndex)this._fieldIndex.assertUniqueBatch(newItems);for(let newItem of newItems)this._addToIndex(newItem);this._data.push(...newItems);for(let newItem of newItems)this._index.set(newItem._id,newItem);return this._enforceCapAfterInsert(),{docs:newItems}}})}async updateOne(filter,update,options={}){await this._ctx.ensureConnected();let oldDoc=this._findRaw(filter);if(!oldDoc)return null;let{save,session}=options,{docs}=await this._updateCore([oldDoc],filter,update,{save,session});return stripVector(docs[0])}async updateMany(filter,update,options={}){await this._ctx.ensureConnected();let oldDocs=this._findAllRaw(filter);if(oldDocs.length===0)return[];let{save,session}=options,{docs}=await this._updateCore(oldDocs,filter,update,{save,session});return docs.map(stripVector)}async _updateCore(oldDocs,filter,update,{save,session}){return this._pipeline.execute({op:"update",beforeHook:"beforeUpdate",afterHook:"afterUpdate",hookPayload:{collection:this.name,filter,update},save,session,afterHookPayload:(docs)=>({collection:this.name,filter,update,result:docs.length===1?docs[0]:docs}),mutate:async(assertTxAlive)=>{let prevDocs=this._changelogEnabled?oldDocs.map((doc)=>structuredClone(doc)):oldDocs.map(()=>null),nextDocs=oldDocs.map((doc)=>this._prepareUpdatedDoc(doc,update));this._assertUniqueCandidates(oldDocs,nextDocs),assertTxAlive();let targets=new Set(oldDocs),positions=new Map;for(let i=0;i<this._data.length;i++)if(targets.has(this._data[i]))positions.set(this._data[i],i);for(let i=0;i<oldDocs.length;i++)this._commitUpdatedDoc(oldDocs[i],nextDocs[i],positions);return{docs:nextDocs,prevDocs}}})}applyUpdate(item,update){for(let field in update){if(_DANGEROUS_KEYS.has(field))continue;if(field==="_id"||field==="createdAt")continue;let updateValue=update[field];if(Array.isArray(updateValue))item[field]=updateValue;else if(typeof updateValue==="object"&&updateValue!==null){let keys=Object.keys(updateValue);if(keys.some((k)=>k.startsWith("$"))){for(let key of keys)if(key==="$inc"&&typeof item[field]==="number")item[field]+=updateValue[key];else if(key==="$push"){if(!Array.isArray(item[field]))item[field]=[];item[field].push(updateValue[key])}}else item[field]=stripDangerousKeys(updateValue)}else item[field]=updateValue}if(item.updatedAt=new Date,this._versioning)item._version=(item._version??0)+1;return item}_prepareUpdatedDoc(currentDoc,update){let prev=structuredClone(currentDoc),next=structuredClone(currentDoc);if(this.applyUpdate(next,update),!this._schema)return next;let errors=validateDoc(next,this._schema,this._strict);if(!errors.length)return next;switch(this._onSchemaError){case"throw":throw new ValidationError("ERR_SKALEX_VALIDATION_UPDATE",`Update validation failed on doc "${currentDoc._id}": ${errors.join("; ")}`,{id:currentDoc._id,errors});case"strip":return this._stripCandidateToValid(next,prev);default:return this._ctx.logger(`[${this.name}] Update validation warning: ${errors.join("; ")}`,"warn"),next}}_stripCandidateToValid(next,prev){let stripped=stripInvalidFields(next,this._schema),merged=structuredClone(prev);for(let[key,val]of Object.entries(stripped)){if(key.startsWith("_"))continue;merged[key]=val}if(merged.updatedAt=next.updatedAt,this._versioning)merged._version=next._version;return merged}_commitUpdatedDoc(oldDoc,newDoc,positions){let idx=positions?positions.get(oldDoc):this._data.indexOf(oldDoc);if(idx===void 0||idx===-1)throw new PersistenceError("ERR_SKALEX_PERSISTENCE_DOC_MISSING",`Document "${oldDoc._id}" no longer exists in collection "${this.name}"`,{id:oldDoc._id,collection:this.name});this._data[idx]=newDoc,this._index.set(newDoc._id,newDoc),this._updateInIndex(oldDoc,newDoc)}_assertUniqueCandidates(oldDocs,nextDocs){this._fieldIndex?.assertUniqueCandidates(oldDocs,nextDocs)}async upsert(filter,doc,options={}){if(await this._ctx.ensureConnected(),this._findRaw(filter))return this.updateOne(filter,doc,options);return this.insertOne({...resolveFilterToValues(filter),...doc},options)}async upsertMany(docs,matchKey,options={}){await this._ctx.ensureConnected();let{save,...rest}=options,results=[];for(let doc of docs)results.push(await this.upsert({[matchKey]:doc[matchKey]},doc,{...rest,save:!1}));return await this._saveIfNeeded(save),results}async restore(filter,options={}){if(!this._softDelete)throw new QueryError("ERR_SKALEX_QUERY_SOFT_DELETE_REQUIRED",`restore() requires softDelete on "${this.name}"`,{collection:this.name});await this._ctx.ensureConnected();let{save,session}=options,item=this._findRaw(filter,{includeDeleted:!0});if(!item||!item._deletedAt)return null;let{docs}=await this._pipeline.execute({op:"restore",beforeHook:null,afterHook:null,hookPayload:null,save,session,mutate:async(assertTxAlive)=>{return assertTxAlive(),delete item._deletedAt,item.updatedAt=new Date,this._index.set(item._id,item),{docs:[item]}}});return stripVector(docs[0])}watch(filter,callback){if(typeof filter==="function")callback=filter,filter=null;if(callback)return this._ctx.eventBus.on(this.name,(event)=>{if(!filter||matchesFilter(event.doc,filter))callback(event)});return this._watchIterator(filter)}_watchIterator(filter){let queue=[],resolve=null,done=!1,unsub=this._ctx.eventBus.on(this.name,(event)=>{if(filter&&!matchesFilter(event.doc,filter))return;if(resolve){let r=resolve;resolve=null,r({value:event,done:!1})}else queue.push(event)});return{[Symbol.asyncIterator](){return this},next(){if(queue.length>0)return Promise.resolve({value:queue.shift(),done:!1});if(done)return Promise.resolve({value:void 0,done:!0});return new Promise((res)=>{resolve=res})},return(){if(done=!0,unsub(),resolve){let r=resolve;resolve=null,r({value:void 0,done:!0})}return Promise.resolve({value:void 0,done:!0})}}}async count(filter={}){return await this._ctx.ensureConnected(),count(this._findAllRaw(filter))}async sum(field,filter={}){return await this._ctx.ensureConnected(),sum(this._findAllRaw(filter),field)}async avg(field,filter={}){return await this._ctx.ensureConnected(),avg(this._findAllRaw(filter),field)}async groupBy(field,filter={}){return await this._ctx.ensureConnected(),groupBy(this._findAllRaw(filter),field)}async findOne(filter,options={}){await this._ctx.ensureConnected();let{populate,select,includeDeleted=!1}=options,item=this._findRaw(filter,{includeDeleted});if(!item)return null;let newItem=this._projectDoc(item,select);if(populate)await this._populateDoc(newItem,item,populate);return newItem}async find(filter,options={}){await this._ctx.ensureConnected();let _t0=Date.now(),{populate,select,sort,page=1,limit,session,includeDeleted=!1}=options;await this._ctx.plugins.run("beforeFind",{collection:this.name,filter,options});let candidates=this._getCandidates(filter),sortedFilter=presortFilter(filter,this._fieldIndex?this._fieldIndex.indexedFields:new Set),results=[];for(let item of candidates){if(this._softDelete&&item._deletedAt&&!includeDeleted)continue;if(!matchesFilter(item,sortedFilter))continue;let newItem=this._projectDoc(item,select);if(populate)await this._populateDoc(newItem,item,populate);results.push(newItem)}if(sort){let sortFields=Object.keys(sort);results.sort((a,b)=>{for(let field of sortFields){let dir=sort[field];if(a[field]<b[field])return-dir;if(a[field]>b[field])return dir}return 0})}let extra;if(limit){let totalDocs=results.length,totalPages=Math.ceil(totalDocs/limit),startIndex=(page-1)*limit;results=results.slice(startIndex,startIndex+limit),extra={page,totalDocs,totalPages}}return this._ctx.queryLog?.record({collection:this.name,op:"find",filter,duration:Date.now()-_t0,resultCount:results.length}),this._ctx.sessionStats.recordRead(session),await this._ctx.plugins.run("afterFind",{collection:this.name,filter,options,docs:results}),extra?{docs:results,...extra}:{docs:results}}async search(query,{filter,limit=10,minScore=0,session}={}){await this._ctx.ensureConnected();let _t0=Date.now();await this._ctx.plugins.run("beforeSearch",{collection:this.name,query,options:{filter,limit,minScore}});let queryVector=await this._ctx.embed(query),candidates=filter?this._findAllRaw(filter):this._data,scored=[];for(let doc of candidates){if(!doc._vector)continue;let score=cosineSimilarity(queryVector,doc._vector);if(score>=minScore)scored.push({doc,score})}scored.sort((a,b)=>b.score-a.score);let top=scored.slice(0,limit);this._ctx.queryLog?.record({collection:this.name,op:"search",query,duration:Date.now()-_t0,resultCount:top.length}),this._ctx.sessionStats.recordRead(session);let docs=top.map((r)=>stripVector(r.doc)),scores=top.map((r)=>r.score);return await this._ctx.plugins.run("afterSearch",{collection:this.name,query,options:{filter,limit,minScore},docs,scores}),{docs,scores}}async similar(id,{limit=10,minScore=0}={}){await this._ctx.ensureConnected();let source=this._index.get(id);if(!source||!source._vector)return{docs:[],scores:[]};let scored=[];for(let doc of this._data){if(doc._id===id||!doc._vector)continue;let score=cosineSimilarity(source._vector,doc._vector);if(score>=minScore)scored.push({doc,score})}scored.sort((a,b)=>b.score-a.score);let top=scored.slice(0,limit);return{docs:top.map((r)=>stripVector(r.doc)),scores:top.map((r)=>r.score)}}async deleteOne(filter,options={}){await this._ctx.ensureConnected();let{save,session}=options;if(this._softDelete){let item=this._findRaw(filter);if(!item)return null;let{docs:docs2}=await this._deleteCore("soft",[item],filter,{save,session});return stripVector(docs2[0])}let{docs}=await this._deleteCore("hard",null,filter,{save,session});if(docs.length===0)return null;return stripVector(docs[0])}async deleteMany(filter,options={}){await this._ctx.ensureConnected();let{save,session}=options;if(this._softDelete){let items=this._findAllRaw(filter);if(items.length===0)return[];let{docs:docs2}=await this._deleteCore("soft",items,filter,{save,session});return docs2.map(stripVector)}let{docs}=await this._deleteCore("hardMany",null,filter,{save,session});return docs.map(stripVector)}async _deleteCore(mode,items,filter,{save,session}){return this._pipeline.execute({op:"delete",beforeHook:"beforeDelete",afterHook:"afterDelete",hookPayload:{collection:this.name,filter},save,session,afterHookPayload:(docs)=>({collection:this.name,filter,result:docs.length===1?docs[0]:docs}),mutate:async(assertTxAlive)=>{if(assertTxAlive(),mode==="soft"){let now=new Date;for(let item of items)item._deletedAt=now,item.updatedAt=now,this._index.set(item._id,item);return{docs:items}}if(mode==="hard"){let idx=this._findIndex(filter);if(idx===-1)return{docs:[]};let deletedItem=this._data.splice(idx,1)[0];return this._index.delete(deletedItem._id),this._removeFromIndex(deletedItem),{docs:[deletedItem]}}let deletedItems=[],remainingItems=[];for(let item of this._data)if(matchesFilter(item,filter))deletedItems.push(item),this._index.delete(item._id),this._removeFromIndex(item);else remainingItems.push(item);return this._data=remainingItems,{docs:deletedItems}}})}async export(filter={},options={}){let{dir,name,format="json"}=options;try{let filteredData=this._data.filter((item)=>matchesFilter(item,filter));if(filteredData.length===0)throw new QueryError("ERR_SKALEX_QUERY_EXPORT_EMPTY",`export(): no documents matched the filter in "${this.name}"`,{collection:this.name});let content;if(format==="json")content=JSON.stringify(filteredData,null,2);else{let escapeCsv=(v)=>{if(v==null)return"";let s=typeof v==="object"?JSON.stringify(v):String(v);return s.includes(",")||s.includes('"')||s.includes(`
2
+ import{existsSync as existsSync5,readFileSync as readFileSync5}from"fs";import{dirname,join as joinPath}from"path";import{fileURLToPath}from"url";function createLifecycleHooks(spec){let{name,onInit,onShutdown,onNuke,telemetryEventName,skipPlatforms}=spec;return{onServerStart:async(_app,hostServices)=>{if(skipPlatforms&&skipPlatforms.includes(process.platform)){process.stderr.write(`[${name}] skipping init on unsupported platform '${process.platform}'
3
+ `);return}if(onInit)await onInit(hostServices);if(telemetryEventName)hostServices.telemetry?.emit(telemetryEventName,{plugin:name})},onServerStop:async(hostServices)=>{if(onShutdown)await onShutdown(hostServices)},onNuke:async(hostServices,ctx)=>{if(onNuke)return onNuke(hostServices,ctx)}}}var BoundLogger=class{constructor(logger,source){this.logger=logger,this.source=source}logger;source;info(message,meta){this.logger?.info?.(this.source,message,meta)}warn(message,meta){this.logger?.warn?.(this.source,message,meta)}error(message,meta){this.logger?.error?.(this.source,message,meta)}debug(message,meta){this.logger?.debug?.(this.source,message,meta)}};function currentSupportedOS(p=process.platform){if(p==="darwin")return"darwin";if(p==="win32")return"win32";return"linux"}async function provisionMetaProviders(host,metaProviders,platform=currentSupportedOS()){let plugins=host.plugins;if(!plugins||!metaProviders?.length)return;let skip=plugins.skipInstall?.()??!1;for(let ref of metaProviders){if(!ref.defaultOn?.includes(platform))continue;try{if(!skip)await plugins.install?.(ref.packageName,{refreshLatest:!0});if(await plugins.loadProvider?.(ref.packageName),await plugins.runPrereqs?.(ref.packageName,{skipInstall:skip}),ref.providerType&&ref.pluginName)await plugins.electDefault?.(ref.providerType,ref.pluginName)}catch{}}}var TelemetryEmitter=class{constructor(pluginName,pluginVersion,hostServices){this.pluginName=pluginName,this.pluginVersion=pluginVersion,this.hostServices=hostServices}pluginName;pluginVersion;hostServices;emit(eventName,payload){let target=this.hostServices?.telemetry;if(!target)return;target.emit(eventName,{plugin:this.pluginName,version:this.pluginVersion,timestamp:new Date().toISOString(),...payload??{}})}emitReady(context){this.emit(`${this.pluginName}.ready`,context)}emitError(error,context){this.emit(`${this.pluginName}.error`,{message:error.message,...context??{}})}emitEvent(type,payload){this.emit(type,payload)}};import{closeSync as closeSync4,existsSync as existsSync4,mkdirSync as mkdirSync4,openSync as openSync4,readFileSync as readFileSync4,unlinkSync as unlinkSync4,writeFileSync as writeFileSync4}from"fs";import{join as join4}from"path";import nodeCrypto from"crypto";import nodePath from"path";import nodeFs from"fs";import zlib from"zlib";import http from"http";import{closeSync as closeSync3,existsSync as existsSync3,mkdirSync as mkdirSync3,openSync as openSync3,readFileSync as readFileSync3,unlinkSync as unlinkSync3,writeFileSync as writeFileSync3}from"fs";import{join as join3}from"path";import nodeCrypto2 from"crypto";import nodePath2 from"path";import nodeFs2 from"fs";import zlib2 from"zlib";import http2 from"http";import{closeSync as closeSync2,existsSync as existsSync2,mkdirSync as mkdirSync2,openSync as openSync2,readFileSync as readFileSync2,unlinkSync as unlinkSync2,writeFileSync as writeFileSync2}from"fs";import{join as join2}from"path";import nodeCrypto22 from"crypto";import nodePath22 from"path";import nodeFs22 from"fs";import zlib22 from"zlib";import http22 from"http";import{closeSync,existsSync,mkdirSync,openSync,readFileSync,unlinkSync,writeFileSync}from"fs";import{join}from"path";import nodeCrypto222 from"crypto";import nodePath222 from"path";import nodeFs222 from"fs";import zlib222 from"zlib";import http222 from"http";function generateUniqueId(){let timestamp=Date.now().toString(16),random;try{random=nodeCrypto.randomBytes(8).toString("hex")}catch{let arr=new Uint8Array(8);crypto.getRandomValues(arr),random=Array.from(arr).map((b)=>b.toString(16).padStart(2,"0")).join("")}return`${timestamp}${random}`}function logger(error,type){let msg=error instanceof Error?error.message:error;if(type==="error")console.error(msg);else console.log(msg)}var _FORBIDDEN_KEYS=new Set(["__proto__","constructor","prototype"]);function resolveDotPath(obj,path){if(!path.includes(".")){if(_FORBIDDEN_KEYS.has(path))return;return obj[path]}let cur=obj;for(let p of path.split(".")){if(_FORBIDDEN_KEYS.has(p))return;if(cur==null)return;cur=cur[p]}return cur}class SkalexError extends Error{constructor(code,message,details={}){super(message);this.name=this.constructor.name,this.code=code,this.details=details}}class ValidationError extends SkalexError{}class UniqueConstraintError extends SkalexError{}class TransactionError extends SkalexError{}class PersistenceError extends SkalexError{}class AdapterError extends SkalexError{}class QueryError extends SkalexError{}function deepEqual(a,b){if(a===b)return!0;if(a==null||b==null)return!1;if(typeof a!==typeof b)return!1;if(a instanceof Date&&b instanceof Date)return a.getTime()===b.getTime();if(a instanceof RegExp&&b instanceof RegExp)return a.source===b.source&&a.flags===b.flags;if(Array.isArray(a)){if(!Array.isArray(b)||a.length!==b.length)return!1;for(let i=0;i<a.length;i++)if(!deepEqual(a[i],b[i]))return!1;return!0}if(typeof a==="object"){if(Array.isArray(b))return!1;let keysA=Object.keys(a);if(keysA.length!==Object.keys(b).length)return!1;for(let k of keysA){if(!Object.prototype.hasOwnProperty.call(b,k))return!1;if(!deepEqual(a[k],b[k]))return!1}return!0}return!1}function matchesFilter(item,filter){if(typeof filter==="function")return filter(item);if(filter==null)return!0;if(typeof filter==="object"&&Object.keys(filter).length===0)return!0;if("$or"in filter){let branches=filter.$or;if(!Array.isArray(branches))throw new QueryError("ERR_SKALEX_QUERY_INVALID_OPERATOR","$or must be an array of filters",{operator:"$or"});if(!branches.some((sub)=>matchesFilter(item,sub)))return!1}if("$and"in filter){let branches=filter.$and;if(!Array.isArray(branches))throw new QueryError("ERR_SKALEX_QUERY_INVALID_OPERATOR","$and must be an array of filters",{operator:"$and"});if(!branches.every((sub)=>matchesFilter(item,sub)))return!1}if("$not"in filter){if(matchesFilter(item,filter.$not))return!1}for(let key in filter){if(key==="$or"||key==="$and"||key==="$not")continue;let filterValue=filter[key],itemValue;try{itemValue=resolveDotPath(item,key)}catch{return!1}if(filterValue instanceof RegExp){if(!filterValue.test(String(itemValue)))return!1}else if(typeof filterValue==="object"&&filterValue!==null){if(Object.keys(filterValue).some((k)=>k.startsWith("$"))){if("$eq"in filterValue&&itemValue!==filterValue.$eq)return!1;if("$ne"in filterValue&&itemValue===filterValue.$ne)return!1;if("$gt"in filterValue&&!(itemValue>filterValue.$gt))return!1;if("$lt"in filterValue&&!(itemValue<filterValue.$lt))return!1;if("$gte"in filterValue&&!(itemValue>=filterValue.$gte))return!1;if("$lte"in filterValue&&!(itemValue<=filterValue.$lte))return!1;if("$in"in filterValue&&!filterValue.$in.includes(itemValue))return!1;if("$nin"in filterValue&&filterValue.$nin.includes(itemValue))return!1;if("$regex"in filterValue){if(!(filterValue.$regex instanceof RegExp?filterValue.$regex:new RegExp(filterValue.$regex)).test(String(itemValue)))return!1}if("$fn"in filterValue&&!filterValue.$fn(itemValue))return!1}else if(!deepEqual(itemValue,filterValue))return!1}else if(itemValue!==filterValue)return!1}return!0}function presortFilter(filter,indexedFields=new Set){if(typeof filter!=="object"||filter===null||typeof filter==="function")return filter;let indexed=[],equality=[],range=[],expensive=[],logical=[];for(let key in filter){if(key==="$or"||key==="$and"||key==="$not"){logical.push(key);continue}let val=filter[key];if(indexedFields.has(key))indexed.push(key);else if(val instanceof RegExp||typeof val==="object"&&val!==null&&(("$regex"in val)||("$fn"in val))||typeof val==="function")expensive.push(key);else if(typeof val==="object"&&val!==null&&(("$gt"in val)||("$lt"in val)||("$gte"in val)||("$lte"in val)||("$ne"in val)||("$in"in val)||("$nin"in val)))range.push(key);else equality.push(key)}let sorted={};for(let k of[...indexed,...equality,...range,...expensive,...logical])sorted[k]=filter[k];return sorted}var SUPPORTED_TYPES=new Set(["string","number","boolean","object","array","date","any"]);function typeOf(val){if(Array.isArray(val))return"array";if(val instanceof Date)return"date";return typeof val}function parseSchema(schema){let fields=new Map,uniqueFields=[];for(let[key,def]of Object.entries(schema)){let fieldDef;if(typeof def==="string"){if(!SUPPORTED_TYPES.has(def))throw new ValidationError("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${def}" for field "${key}"`,{field:key,type:def});fieldDef={type:def,required:!1,unique:!1}}else if(typeof def==="object"&&def!==null){let{type="any",required=!1,unique=!1,enum:enumVals}=def;if(!SUPPORTED_TYPES.has(type))throw new ValidationError("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${type}" for field "${key}"`,{field:key,type});if(fieldDef={type,required,unique,enum:enumVals},unique)uniqueFields.push(key)}else throw new ValidationError("ERR_SKALEX_VALIDATION_INVALID_SCHEMA",`Invalid schema definition for field "${key}"`,{field:key});fields.set(key,fieldDef)}return{fields,uniqueFields}}function validateDoc(doc,fields,strict=!1){let errors=[];for(let[key,def]of fields){let val=doc[key],missing=val===void 0||val===null;if(def.required&&missing){errors.push(`Field "${key}" is required`);continue}if(missing)continue;if(def.type!=="any"){let actualType=typeOf(val);if(actualType!==def.type)errors.push(`Field "${key}" must be of type "${def.type}", got "${actualType}"`)}if(def.enum&&!def.enum.includes(val))errors.push(`Field "${key}" must be one of [${def.enum.map((v)=>JSON.stringify(v)).join(", ")}], got ${JSON.stringify(val)}`)}if(strict){for(let key of Object.keys(doc))if(!key.startsWith("_")&&!fields.has(key))errors.push(`Unknown field "${key}" (strict mode)`)}return errors}function stripInvalidFields(doc,fields){let out={};for(let[key,val]of Object.entries(doc)){if(key.startsWith("_")){out[key]=val;continue}if(!fields.has(key))continue;let def=fields.get(key);if(def.type!=="any"){if(typeOf(val)!==def.type)continue}if(def.enum&&!def.enum.includes(val))continue;out[key]=val}return out}function inferSchema(doc){let schema={};for(let[key,val]of Object.entries(doc)){if(key.startsWith("_"))continue;let t=typeOf(val);schema[key]=SUPPORTED_TYPES.has(t)?t:"any"}return schema}function parseTtl(ttl){if(typeof ttl==="number"){if(ttl<=0)throw new ValidationError("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got ${ttl}`,{ttl});return ttl*1000}if(typeof ttl!=="string")throw new ValidationError("ERR_SKALEX_VALIDATION_TTL",`Invalid TTL value: ${ttl}`,{ttl});let match=ttl.match(/^(\d+(?:\.\d+)?)(ms|s|m|h|d)$/);if(!match)throw new ValidationError("ERR_SKALEX_VALIDATION_TTL_FORMAT",`Invalid TTL format: "${ttl}". Use e.g. 300 (seconds), "30m", "24h", "7d"`,{ttl});let val=parseFloat(match[1]);if(val<=0)throw new ValidationError("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got "${ttl}"`,{ttl});let unit=match[2],ms=val*{ms:1,s:1000,m:60000,h:3600000,d:86400000}[unit];if(!isFinite(ms))throw new ValidationError("ERR_SKALEX_VALIDATION_TTL",`TTL value "${ttl}" is too large`,{ttl});return ms}function computeExpiry(ttl){return new Date(Date.now()+parseTtl(ttl))}function sweep(data,idIndex,removeFromIndexes=null){let now=Date.now(),removed=0,i=data.length;while(i--){let doc=data[i];if(doc._expiresAt&&new Date(doc._expiresAt).getTime()<=now){if(data.splice(i,1),idIndex.delete(doc._id),removeFromIndexes)removeFromIndexes(doc);removed++}}return removed}function cosineSimilarity(a,b){if(a.length!==b.length)throw new QueryError("ERR_SKALEX_QUERY_VECTOR_MISMATCH",`Vector dimension mismatch: ${a.length} vs ${b.length}`,{expected:a.length,got:b.length});let dot=0,magA=0,magB=0;for(let i=0;i<a.length;i++)dot+=a[i]*b[i],magA+=a[i]*a[i],magB+=b[i]*b[i];let denom=Math.sqrt(magA*magB);return denom===0?0:dot/denom}function stripVector(doc){if(!("_vector"in doc))return{...doc};let{_vector,...rest}=doc;return rest}function count(docs){return docs.length}function sum(docs,field){let total=0;for(let doc of docs){let val=resolveDotPath(doc,field);if(typeof val==="number"&&!isNaN(val))total+=val}return total}function avg(docs,field){let total=0,n=0;for(let doc of docs){let val=resolveDotPath(doc,field);if(typeof val==="number"&&!isNaN(val))total+=val,n++}return n===0?null:total/n}function groupBy(docs,field){let groups=Object.create(null);for(let doc of docs){let key=String(resolveDotPath(doc,field)??"__null__");if(!groups[key])groups[key]=[];groups[key].push(doc)}return groups}class MutationPipeline{constructor(collection){this._col=collection}get _ctx(){return this._col._ctx}async execute({op,beforeHook,afterHook,hookPayload,mutate,afterHookPayload,save,session}){let ctx=this._ctx;await ctx.ensureConnected(),this._col._txSnapshotIfNeeded();let txm=ctx.txManager,isTxWrite=txm.active&&this._col._activeTxId===txm.context?.id,entryTxId=isTxWrite?txm.context.id:null,collTxId=this._col._createdInTxId,assertTxAlive=()=>{if(entryTxId!==null&&txm._abortedIds.has(entryTxId))throw new TransactionError("ERR_SKALEX_TX_ABORTED",`Transaction ${entryTxId} was aborted. No further mutations allowed.`);if(collTxId!==null&&txm._abortedIds.has(collTxId))throw new TransactionError("ERR_SKALEX_TX_ABORTED",`Transaction ${collTxId} was aborted. Collection obtained inside that transaction cannot be used for further mutations.`)};if(isTxWrite||collTxId!==null)assertTxAlive();if(beforeHook)await ctx.plugins.run(beforeHook,hookPayload);let{docs,prevDocs=[]}=await mutate(assertTxAlive);if(ctx.persistence.markDirty(ctx.collections,this._col.name),await this._col._saveIfNeeded(save),this._col._changelogEnabled)for(let i=0;i<docs.length;i++)await ctx.logChange(op,this._col.name,docs[i],prevDocs[i]??null,session||null);if(!isTxWrite||!txm.defer(()=>ctx.sessionStats.recordWrite(session)))ctx.sessionStats.recordWrite(session);for(let doc of docs)ctx.emitEvent(this._col.name,{op,collection:this._col.name,doc:stripVector(doc)});if(afterHook)if(afterHookPayload)await ctx.runAfterHook(afterHook,afterHookPayload(docs));else for(let doc of docs)await ctx.runAfterHook(afterHook,{collection:this._col.name,doc:stripVector(doc)});return{docs,prevDocs}}}function resolveFilterToValues(filter){let resolved={};for(let key in filter){if(key.startsWith("$"))continue;let val=filter[key];if(val&&typeof val==="object"&&!Array.isArray(val)){let keys=Object.keys(val);if(keys.length===1&&keys[0]==="$eq")resolved[key]=val.$eq}else resolved[key]=val}return resolved}var _DANGEROUS_KEYS=new Set(["__proto__","constructor","prototype"]);function stripDangerousKeys(val){if(typeof val!=="object"||val===null||Array.isArray(val))return val;let out={};for(let k of Object.keys(val)){if(_DANGEROUS_KEYS.has(k))continue;out[k]=stripDangerousKeys(val[k])}return out}class Collection{constructor(collectionData,database){this.name=collectionData.collectionName,this.database=database,this._ctx=database._buildCollectionContext(),this._store=collectionData,this._pipeline=new MutationPipeline(this),this._createdInTxId=database._txManager.context?.id??null,this._activeTxId=null}get _data(){return this._store.data}set _data(val){this._store.data=val}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(item,options={}){let{save,ifNotExists,ttl,embed,session}=options;if(ifNotExists){await this._ctx.ensureConnected();let existing=this._findRaw(item);if(existing)return stripVector({...existing})}let{docs}=await this._insertCore([item],{ttl,embed,session,save});return stripVector(docs[0])}async insertMany(items,options={}){let{save,ttl,embed,session}=options,{docs}=await this._insertCore(items,{ttl,embed,session,save});return docs.map(stripVector)}async _insertCore(items,{ttl,embed,session,save}){return this._pipeline.execute({op:"insert",beforeHook:null,afterHook:"afterInsert",hookPayload:null,save,session,mutate:async(assertTxAlive)=>{let newItems=[],batchIds=new Set;for(let item of items){let validated=this._applyValidation(item);await this._ctx.plugins.run("beforeInsert",{collection:this.name,doc:validated});let newItem=await this._buildDoc(validated,{ttl,embed});if(this._index.has(newItem._id)||batchIds.has(newItem._id))throw new UniqueConstraintError("ERR_SKALEX_UNIQUE_DUPLICATE_ID",`Duplicate _id "${newItem._id}" in collection "${this.name}"`,{id:newItem._id,collection:this.name});batchIds.add(newItem._id),newItems.push(newItem)}if(assertTxAlive(),this._fieldIndex)this._fieldIndex.assertUniqueBatch(newItems);for(let newItem of newItems)this._addToIndex(newItem);this._data.push(...newItems);for(let newItem of newItems)this._index.set(newItem._id,newItem);return this._enforceCapAfterInsert(),{docs:newItems}}})}async updateOne(filter,update,options={}){await this._ctx.ensureConnected();let oldDoc=this._findRaw(filter);if(!oldDoc)return null;let{save,session}=options,{docs}=await this._updateCore([oldDoc],filter,update,{save,session});return stripVector(docs[0])}async updateMany(filter,update,options={}){await this._ctx.ensureConnected();let oldDocs=this._findAllRaw(filter);if(oldDocs.length===0)return[];let{save,session}=options,{docs}=await this._updateCore(oldDocs,filter,update,{save,session});return docs.map(stripVector)}async _updateCore(oldDocs,filter,update,{save,session}){return this._pipeline.execute({op:"update",beforeHook:"beforeUpdate",afterHook:"afterUpdate",hookPayload:{collection:this.name,filter,update},save,session,afterHookPayload:(docs)=>({collection:this.name,filter,update,result:docs.length===1?docs[0]:docs}),mutate:async(assertTxAlive)=>{let prevDocs=this._changelogEnabled?oldDocs.map((doc)=>structuredClone(doc)):oldDocs.map(()=>null),nextDocs=oldDocs.map((doc)=>this._prepareUpdatedDoc(doc,update));this._assertUniqueCandidates(oldDocs,nextDocs),assertTxAlive();let targets=new Set(oldDocs),positions=new Map;for(let i=0;i<this._data.length;i++)if(targets.has(this._data[i]))positions.set(this._data[i],i);for(let i=0;i<oldDocs.length;i++)this._commitUpdatedDoc(oldDocs[i],nextDocs[i],positions);return{docs:nextDocs,prevDocs}}})}applyUpdate(item,update){for(let field in update){if(_DANGEROUS_KEYS.has(field))continue;if(field==="_id"||field==="createdAt")continue;let updateValue=update[field];if(Array.isArray(updateValue))item[field]=updateValue;else if(typeof updateValue==="object"&&updateValue!==null){let keys=Object.keys(updateValue);if(keys.some((k)=>k.startsWith("$"))){for(let key of keys)if(key==="$inc"&&typeof item[field]==="number")item[field]+=updateValue[key];else if(key==="$push"){if(!Array.isArray(item[field]))item[field]=[];item[field].push(updateValue[key])}}else item[field]=stripDangerousKeys(updateValue)}else item[field]=updateValue}if(item.updatedAt=new Date,this._versioning)item._version=(item._version??0)+1;return item}_prepareUpdatedDoc(currentDoc,update){let prev=structuredClone(currentDoc),next=structuredClone(currentDoc);if(this.applyUpdate(next,update),!this._schema)return next;let errors=validateDoc(next,this._schema,this._strict);if(!errors.length)return next;switch(this._onSchemaError){case"throw":throw new ValidationError("ERR_SKALEX_VALIDATION_UPDATE",`Update validation failed on doc "${currentDoc._id}": ${errors.join("; ")}`,{id:currentDoc._id,errors});case"strip":return this._stripCandidateToValid(next,prev);default:return this._ctx.logger(`[${this.name}] Update validation warning: ${errors.join("; ")}`,"warn"),next}}_stripCandidateToValid(next,prev){let stripped=stripInvalidFields(next,this._schema),merged=structuredClone(prev);for(let[key,val]of Object.entries(stripped)){if(key.startsWith("_"))continue;merged[key]=val}if(merged.updatedAt=next.updatedAt,this._versioning)merged._version=next._version;return merged}_commitUpdatedDoc(oldDoc,newDoc,positions){let idx=positions?positions.get(oldDoc):this._data.indexOf(oldDoc);if(idx===void 0||idx===-1)throw new PersistenceError("ERR_SKALEX_PERSISTENCE_DOC_MISSING",`Document "${oldDoc._id}" no longer exists in collection "${this.name}"`,{id:oldDoc._id,collection:this.name});this._data[idx]=newDoc,this._index.set(newDoc._id,newDoc),this._updateInIndex(oldDoc,newDoc)}_assertUniqueCandidates(oldDocs,nextDocs){this._fieldIndex?.assertUniqueCandidates(oldDocs,nextDocs)}async upsert(filter,doc,options={}){if(await this._ctx.ensureConnected(),this._findRaw(filter))return this.updateOne(filter,doc,options);return this.insertOne({...resolveFilterToValues(filter),...doc},options)}async upsertMany(docs,matchKey,options={}){await this._ctx.ensureConnected();let{save,...rest}=options,results=[];for(let doc of docs)results.push(await this.upsert({[matchKey]:doc[matchKey]},doc,{...rest,save:!1}));return await this._saveIfNeeded(save),results}async restore(filter,options={}){if(!this._softDelete)throw new QueryError("ERR_SKALEX_QUERY_SOFT_DELETE_REQUIRED",`restore() requires softDelete on "${this.name}"`,{collection:this.name});await this._ctx.ensureConnected();let{save,session}=options,item=this._findRaw(filter,{includeDeleted:!0});if(!item||!item._deletedAt)return null;let{docs}=await this._pipeline.execute({op:"restore",beforeHook:null,afterHook:null,hookPayload:null,save,session,mutate:async(assertTxAlive)=>(assertTxAlive(),delete item._deletedAt,item.updatedAt=new Date,this._index.set(item._id,item),{docs:[item]})});return stripVector(docs[0])}watch(filter,callback){if(typeof filter==="function")callback=filter,filter=null;if(callback)return this._ctx.eventBus.on(this.name,(event)=>{if(!filter||matchesFilter(event.doc,filter))callback(event)});return this._watchIterator(filter)}_watchIterator(filter){let queue=[],resolve=null,done=!1,unsub=this._ctx.eventBus.on(this.name,(event)=>{if(filter&&!matchesFilter(event.doc,filter))return;if(resolve){let r=resolve;resolve=null,r({value:event,done:!1})}else queue.push(event)});return{[Symbol.asyncIterator](){return this},next(){if(queue.length>0)return Promise.resolve({value:queue.shift(),done:!1});if(done)return Promise.resolve({value:void 0,done:!0});return new Promise((res)=>{resolve=res})},return(){if(done=!0,unsub(),resolve){let r=resolve;resolve=null,r({value:void 0,done:!0})}return Promise.resolve({value:void 0,done:!0})}}}async count(filter={}){return await this._ctx.ensureConnected(),count(this._findAllRaw(filter))}async sum(field,filter={}){return await this._ctx.ensureConnected(),sum(this._findAllRaw(filter),field)}async avg(field,filter={}){return await this._ctx.ensureConnected(),avg(this._findAllRaw(filter),field)}async groupBy(field,filter={}){return await this._ctx.ensureConnected(),groupBy(this._findAllRaw(filter),field)}async findOne(filter,options={}){await this._ctx.ensureConnected();let{populate,select,includeDeleted=!1}=options,item=this._findRaw(filter,{includeDeleted});if(!item)return null;let newItem=this._projectDoc(item,select);if(populate)await this._populateDoc(newItem,item,populate);return newItem}async find(filter,options={}){await this._ctx.ensureConnected();let _t0=Date.now(),{populate,select,sort,page=1,limit,session,includeDeleted=!1}=options;await this._ctx.plugins.run("beforeFind",{collection:this.name,filter,options});let candidates=this._getCandidates(filter),sortedFilter=presortFilter(filter,this._fieldIndex?this._fieldIndex.indexedFields:new Set),results=[];for(let item of candidates){if(this._softDelete&&item._deletedAt&&!includeDeleted)continue;if(!matchesFilter(item,sortedFilter))continue;let newItem=this._projectDoc(item,select);if(populate)await this._populateDoc(newItem,item,populate);results.push(newItem)}if(sort){let sortFields=Object.keys(sort);results.sort((a,b)=>{for(let field of sortFields){let dir=sort[field];if(a[field]<b[field])return-dir;if(a[field]>b[field])return dir}return 0})}let extra;if(limit){let totalDocs=results.length,totalPages=Math.ceil(totalDocs/limit),startIndex=(page-1)*limit;results=results.slice(startIndex,startIndex+limit),extra={page,totalDocs,totalPages}}return this._ctx.queryLog?.record({collection:this.name,op:"find",filter,duration:Date.now()-_t0,resultCount:results.length}),this._ctx.sessionStats.recordRead(session),await this._ctx.plugins.run("afterFind",{collection:this.name,filter,options,docs:results}),extra?{docs:results,...extra}:{docs:results}}async search(query,{filter,limit=10,minScore=0,session}={}){await this._ctx.ensureConnected();let _t0=Date.now();await this._ctx.plugins.run("beforeSearch",{collection:this.name,query,options:{filter,limit,minScore}});let queryVector=await this._ctx.embed(query),candidates=filter?this._findAllRaw(filter):this._data,scored=[];for(let doc of candidates){if(!doc._vector)continue;let score=cosineSimilarity(queryVector,doc._vector);if(score>=minScore)scored.push({doc,score})}scored.sort((a,b)=>b.score-a.score);let top=scored.slice(0,limit);this._ctx.queryLog?.record({collection:this.name,op:"search",query,duration:Date.now()-_t0,resultCount:top.length}),this._ctx.sessionStats.recordRead(session);let docs=top.map((r)=>stripVector(r.doc)),scores=top.map((r)=>r.score);return await this._ctx.plugins.run("afterSearch",{collection:this.name,query,options:{filter,limit,minScore},docs,scores}),{docs,scores}}async similar(id,{limit=10,minScore=0}={}){await this._ctx.ensureConnected();let source=this._index.get(id);if(!source||!source._vector)return{docs:[],scores:[]};let scored=[];for(let doc of this._data){if(doc._id===id||!doc._vector)continue;let score=cosineSimilarity(source._vector,doc._vector);if(score>=minScore)scored.push({doc,score})}scored.sort((a,b)=>b.score-a.score);let top=scored.slice(0,limit);return{docs:top.map((r)=>stripVector(r.doc)),scores:top.map((r)=>r.score)}}async deleteOne(filter,options={}){await this._ctx.ensureConnected();let{save,session}=options;if(this._softDelete){let item=this._findRaw(filter);if(!item)return null;let{docs:docs2}=await this._deleteCore("soft",[item],filter,{save,session});return stripVector(docs2[0])}let{docs}=await this._deleteCore("hard",null,filter,{save,session});if(docs.length===0)return null;return stripVector(docs[0])}async deleteMany(filter,options={}){await this._ctx.ensureConnected();let{save,session}=options;if(this._softDelete){let items=this._findAllRaw(filter);if(items.length===0)return[];let{docs:docs2}=await this._deleteCore("soft",items,filter,{save,session});return docs2.map(stripVector)}let{docs}=await this._deleteCore("hardMany",null,filter,{save,session});return docs.map(stripVector)}async _deleteCore(mode,items,filter,{save,session}){return this._pipeline.execute({op:"delete",beforeHook:"beforeDelete",afterHook:"afterDelete",hookPayload:{collection:this.name,filter},save,session,afterHookPayload:(docs)=>({collection:this.name,filter,result:docs.length===1?docs[0]:docs}),mutate:async(assertTxAlive)=>{if(assertTxAlive(),mode==="soft"){let now=new Date;for(let item of items)item._deletedAt=now,item.updatedAt=now,this._index.set(item._id,item);return{docs:items}}if(mode==="hard"){let idx=this._findIndex(filter);if(idx===-1)return{docs:[]};let deletedItem=this._data.splice(idx,1)[0];return this._index.delete(deletedItem._id),this._removeFromIndex(deletedItem),{docs:[deletedItem]}}let deletedItems=[],remainingItems=[];for(let item of this._data)if(matchesFilter(item,filter))deletedItems.push(item),this._index.delete(item._id),this._removeFromIndex(item);else remainingItems.push(item);return this._data=remainingItems,{docs:deletedItems}}})}async export(filter={},options={}){let{dir,name,format="json"}=options;try{let filteredData=this._data.filter((item)=>matchesFilter(item,filter));if(filteredData.length===0)throw new QueryError("ERR_SKALEX_QUERY_EXPORT_EMPTY",`export(): no documents matched the filter in "${this.name}"`,{collection:this.name});let content;if(format==="json")content=JSON.stringify(filteredData,null,2);else{let escapeCsv=(v)=>{if(v==null)return"";let s=typeof v==="object"?JSON.stringify(v):String(v);return s.includes(",")||s.includes('"')||s.includes(`
4
4
  `)||s.includes("\r")?`"${s.replace(/"/g,'""')}"`:s},header=Object.keys(filteredData[0]).map(escapeCsv).join(","),rows=filteredData.map((item)=>Object.values(item).map(escapeCsv).join(","));content=[header,...rows].join(`
5
5
  `)}if(typeof this._ctx.fs.writeRaw!=="function")throw new AdapterError("ERR_SKALEX_ADAPTER_NO_RAW_WRITE","export() requires a file-system adapter (FsAdapter). The current adapter does not support raw file writes.");let exportDir=dir||`${this._ctx.dataDirectory}/exports`,fileName=`${name||this.name}.${format}`,filePath=this._ctx.fs.join(exportDir,fileName);this._ctx.fs.ensureDir(exportDir),await this._ctx.fs.writeRaw(filePath,content)}catch(error){throw this._ctx.logger(`Error exporting "${this.name}": ${error.message}`,"error"),error}}_txSnapshotIfNeeded(){let txm=this._ctx.txManager;if(!txm.active)return;if(this._activeTxId!==txm.context?.id)return;txm.snapshotIfNeeded(this.name,this._store,(col)=>this._ctx.snapshotCollection(col))}async _saveIfNeeded(save){let txm=this._ctx.txManager;if(txm.active&&this._activeTxId===txm.context?.id)return;if(save??this._ctx.autoSave)await this._ctx.saveCollection(this.name)}_applyValidation(item){if(!this._schema)return item;let errors=validateDoc(item,this._schema,this._strict);if(!errors.length)return item;switch(this._onSchemaError){case"warn":return this._ctx.logger(`[${this.name}] Validation warning: ${errors.join("; ")}`,"warn"),item;case"strip":return stripInvalidFields(item,this._schema);default:throw new ValidationError("ERR_SKALEX_VALIDATION_FAILED",`Validation failed: ${errors.join("; ")}`,{errors})}}_enforceCapAfterInsert(){let max=this._maxDocs;if(!max||this._data.length<=max)return;let toEvict=this._data.splice(0,this._data.length-max);for(let doc of toEvict)this._index.delete(doc._id),this._removeFromIndex(doc)}_findRaw(filter,{includeDeleted=!1}={}){if(typeof filter==="function"){for(let doc of this._data){if(this._softDelete&&doc._deletedAt&&!includeDeleted)continue;if(filter(doc))return doc}return null}if(filter._id){let item=this._index.get(filter._id)||null;if(!item)return null;if(this._softDelete&&item._deletedAt&&!includeDeleted)return null;if(Object.keys(filter).length>1)return matchesFilter(item,filter)?item:null;return item}if(this._fieldIndex)for(let key in filter){if(key==="$or"||key==="$and"||key==="$not")continue;let val=filter[key];if(typeof val!=="object"||val===null){let candidates=this._fieldIndex._lookupIterable(key,val);if(candidates!==null){for(let doc of candidates){if(this._softDelete&&doc._deletedAt&&!includeDeleted)continue;if(matchesFilter(doc,filter))return doc}return null}}}for(let doc of this._data){if(this._softDelete&&doc._deletedAt&&!includeDeleted)continue;if(matchesFilter(doc,filter))return doc}return null}_findAllRaw(filter,{includeDeleted=!1}={}){if(filter&&typeof filter!=="function"&&filter._id){let item=this._index.get(filter._id);if(!item)return[];if(this._softDelete&&item._deletedAt&&!includeDeleted)return[];return matchesFilter(item,filter)?[item]:[]}let results=[];for(let doc of this._getCandidates(filter)){if(this._softDelete&&doc._deletedAt&&!includeDeleted)continue;if(matchesFilter(doc,filter))results.push(doc)}return results}_getCandidates(filter){if(!this._fieldIndex)return this._data;if(this._fieldIndex._compoundIndexes.size>0){let eqFields={};for(let key in filter){if(key==="$or"||key==="$and"||key==="$not")continue;let val=filter[key];if(typeof val!=="object"||val===null)eqFields[key]=val}if(Object.keys(eqFields).length>=2){let candidates=this._fieldIndex.lookupCompound(eqFields);if(candidates!==null)return candidates}}for(let key in filter){if(key==="$or"||key==="$and"||key==="$not")continue;let val=filter[key];if(typeof val!=="object"||val===null){let candidates=this._fieldIndex._lookupIterable(key,val);if(candidates!==null)return candidates}}return this._data}_findIndex(filter){for(let i=0;i<this._data.length;i++)if(matchesFilter(this._data[i],filter))return i;return-1}_addToIndex(doc){if(this._fieldIndex)this._fieldIndex.add(doc)}_removeFromIndex(doc){if(this._fieldIndex)this._fieldIndex.remove(doc)}_updateInIndex(oldDoc,doc){if(this._fieldIndex)this._fieldIndex.update(oldDoc,doc)}async _buildDoc(item,{ttl,embed}={}){let newItem={...item,_id:item._id??(this._ctx.idGenerator??generateUniqueId)(),createdAt:new Date,updatedAt:new Date},resolvedTtl=ttl??this._defaultTtl;if(resolvedTtl)newItem._expiresAt=computeExpiry(resolvedTtl);let resolvedEmbed=embed??this._defaultEmbed;if(resolvedEmbed){let text=typeof resolvedEmbed==="function"?resolvedEmbed(newItem):newItem[resolvedEmbed];newItem._vector=await this._ctx.embed(String(text))}if(this._versioning)newItem._version=1;return newItem}_projectDoc(doc,select){if(select){let out2={};for(let field of select){if(field==="_vector")continue;out2[field]=doc[field]}return out2}let out={...doc};return delete out._vector,out}async _populateDoc(out,source,fields){for(let field of fields){let item=await this._ctx.getCollection(field).findOne({_id:source[field]});if(item)out[field]=item}}}class StorageAdapter{async read(name){throw Error("StorageAdapter.read() not implemented")}async write(name,data){throw Error("StorageAdapter.write() not implemented")}async delete(name){throw Error("StorageAdapter.delete() not implemented")}async list(){throw Error("StorageAdapter.list() not implemented")}async writeAll(entries){for(let{name,data}of entries)await this.write(name,data)}}class FsAdapter extends StorageAdapter{constructor({dir,format="gz"}){super();this.dir=nodePath.resolve(dir),this.format=format,this._ensureDir(this.dir)}_ensureDir(dir){if(!nodeFs.existsSync(dir))nodeFs.mkdirSync(dir,{recursive:!0})}_filePath(name){return nodePath.join(this.dir,`${name}.${this.format}`)}async read(name){let fp=this._filePath(name);try{let raw=await nodeFs.promises.readFile(fp);if(this.format==="gz")raw=zlib.inflateSync(raw);return raw.toString("utf8")}catch(err){if(err.code==="ENOENT")return null;throw err}}async write(name,data){let fp=this._filePath(name),tmp=nodePath.join(this.dir,`${name}_${globalThis.crypto.randomUUID()}.tmp.${this.format}`);if(this.format==="gz"){let compressed=zlib.deflateSync(data);await nodeFs.promises.writeFile(tmp,compressed)}else await nodeFs.promises.writeFile(tmp,data,"utf8");await nodeFs.promises.rename(tmp,fp)}async writeAll(entries){let staged=[];try{for(let{name,data}of entries){let fp=this._filePath(name),tmp=nodePath.join(this.dir,`${name}_${globalThis.crypto.randomUUID()}.tmp.${this.format}`);if(this.format==="gz"){let compressed=zlib.deflateSync(data);await nodeFs.promises.writeFile(tmp,compressed)}else await nodeFs.promises.writeFile(tmp,data,"utf8");staged.push({tmp,fp})}for(let{tmp,fp}of staged)await nodeFs.promises.rename(tmp,fp)}catch(error){for(let{tmp}of staged)try{await nodeFs.promises.unlink(tmp)}catch{}throw error}}async delete(name){let fp=this._filePath(name);try{await nodeFs.promises.unlink(fp)}catch(err){if(err.code!=="ENOENT")throw err}}async list(){try{let files=await nodeFs.promises.readdir(this.dir),ext=`.${this.format}`;return files.filter((f)=>f.endsWith(ext)&&!f.includes(".tmp.")).map((f)=>f.slice(0,-ext.length))}catch(err){if(err.code==="ENOENT")return[];throw err}}join(...parts){return nodePath.join(...parts)}ensureDir(dir){this._ensureDir(dir)}async writeRaw(filePath,content){this._ensureDir(nodePath.dirname(filePath)),await nodeFs.promises.writeFile(filePath,content,"utf8")}async readRaw(filePath){return nodeFs.promises.readFile(nodePath.resolve(filePath),"utf8")}}class MigrationEngine{constructor(){this._migrations=[]}add(migration){let{version,up}=migration;if(typeof version!=="number"||version<1)throw new ValidationError("ERR_SKALEX_VALIDATION_MIGRATION",`Migration version must be a positive integer, got ${version}`,{version});if(typeof up!=="function")throw new ValidationError("ERR_SKALEX_VALIDATION_MIGRATION",`Migration version ${version} must have an "up" function`,{version});if(this._migrations.some((m)=>m.version===version))throw new ValidationError("ERR_SKALEX_VALIDATION_MIGRATION_DUPLICATE",`Migration version ${version} is already registered`,{version});this._migrations.push({...migration}),this._migrations.sort((a,b)=>a.version-b.version)}async run(getCollection,appliedVersions=[]){let applied=new Set(appliedVersions),pending=this._migrations.filter((m)=>!applied.has(m.version));for(let migration of pending){let collection=getCollection(migration.version);await migration.up(collection),applied.add(migration.version)}return[...applied].sort((a,b)=>a-b)}status(appliedVersions=[]){let applied=new Set(appliedVersions),pending=this._migrations.map((m)=>m.version).filter((v)=>!applied.has(v));return{current:appliedVersions.length?Math.max(...appliedVersions):0,applied:[...applied].sort((a,b)=>a-b),pending}}}var EMPTY_ITERABLE={[Symbol.iterator](){return{next(){return{done:!0}}}},size:0};function readOnlyIterable(set){return{[Symbol.iterator](){return set[Symbol.iterator]()},get size(){return set.size}}}function encodeTuple(values){return values.map((v)=>{if(v===null||v===void 0)return"\x00";if(typeof v==="boolean")return v?"\x01T":"\x01F";if(typeof v==="number")return`\x02${v}`;return`\x03${String(v)}`}).join("\x1F")}class IndexEngine{constructor(fields=[],unique=[]){this._fields=new Set,this._compoundFields=[];for(let f of fields)if(Array.isArray(f)){for(let subf of f)this._validateFieldName(subf);this._compoundFields.push(f)}else this._validateFieldName(f),this._fields.add(f);for(let f of unique)this._validateFieldName(f);this._uniqueFields=new Set(unique),this._indexedFields=new Set([...this._fields,...this._uniqueFields]),this._fieldIndexes=new Map,this._uniqueIndexes=new Map;for(let f of this._fields)this._fieldIndexes.set(f,new Map);for(let f of this._uniqueFields)if(this._uniqueIndexes.set(f,new Map),!this._fieldIndexes.has(f))this._fieldIndexes.set(f,new Map);this._compoundIndexes=new Map;for(let fieldSet of this._compoundFields)this._compoundIndexes.set(fieldSet.join("\x00"),{fields:fieldSet,map:new Map})}get indexedFields(){return this._indexedFields}buildFromData(data){for(let[,m]of this._fieldIndexes)m.clear();for(let[,m]of this._uniqueIndexes)m.clear();for(let[,ci]of this._compoundIndexes)ci.map.clear();for(let doc of data)this._indexDoc(doc)}add(doc){this._checkUnique(doc,null),this._indexDoc(doc)}remove(doc){for(let[field,map]of this._fieldIndexes){let val=doc[field];if(val!==void 0){let set=map.get(val);if(set){if(set.delete(doc),set.size===0)map.delete(val)}}}for(let[field,map]of this._uniqueIndexes){let val=doc[field];if(val!==void 0)map.delete(val)}for(let[,ci]of this._compoundIndexes){let tupleKey=encodeTuple(ci.fields.map((f)=>doc[f])),set=ci.map.get(tupleKey);if(set){if(set.delete(doc),set.size===0)ci.map.delete(tupleKey)}}}update(oldDoc,newDoc){this._checkUnique(newDoc,oldDoc),this.remove(oldDoc);try{this._indexDoc(newDoc)}catch(indexError){try{this._indexDoc(oldDoc)}catch{}throw indexError}}lookup(field,value){let map=this._fieldIndexes.get(field);if(!map)return null;let set=map.get(value);return set?[...set]:[]}_lookupIterable(field,value){let map=this._fieldIndexes.get(field);if(!map)return null;let set=map.get(value);return set?readOnlyIterable(set):EMPTY_ITERABLE}lookupCompound(fieldValues){let keys=Object.keys(fieldValues).sort();for(let[,ci]of this._compoundIndexes){let ciKeys=[...ci.fields].sort();if(ciKeys.length!==keys.length)continue;if(ciKeys.every((k,i)=>k===keys[i])){let tupleKey=encodeTuple(ci.fields.map((f)=>fieldValues[f])),set=ci.map.get(tupleKey);return set?readOnlyIterable(set):EMPTY_ITERABLE}}return null}isUniqueTaken(field,value){let map=this._uniqueIndexes.get(field);if(!map)return!1;return map.has(value)}assertUniqueCandidates(oldDocs,newDocs){if(this._uniqueFields.size===0)return;let batchOldIds=new Set(oldDocs.map((doc)=>doc._id));for(let field of this._uniqueFields){let reserved=new Set,uniqueMap=this._uniqueIndexes.get(field);if(uniqueMap){for(let[value,doc]of uniqueMap.entries())if(!batchOldIds.has(doc._id))reserved.add(value)}let seen=new Map;for(let i=0;i<newDocs.length;i++){let val=newDocs[i][field];if(val===void 0)continue;if(reserved.has(val))throw new UniqueConstraintError("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${field}" value "${val}" already exists`,{field,value:val});let prior=seen.get(val);if(prior&&prior!==oldDocs[i]._id)throw new UniqueConstraintError("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${field}" value "${val}" already exists`,{field,value:val});seen.set(val,oldDocs[i]._id)}}}assertUniqueBatch(newDocs){if(this._uniqueFields.size===0)return;for(let field of this._uniqueFields){let uniqueMap=this._uniqueIndexes.get(field),seen=new Set;for(let doc of newDocs){let val=doc[field];if(val===void 0)continue;if(uniqueMap&&uniqueMap.has(val))throw new UniqueConstraintError("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${field}" value "${val}" already exists`,{field,value:val});if(seen.has(val))throw new UniqueConstraintError("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: duplicate "${field}" value "${val}" within batch`,{field,value:val});seen.add(val)}}}_validateFieldName(field){if(field.includes("."))throw new ValidationError("ERR_SKALEX_VALIDATION_INDEX_DOT_PATH",`Index fields cannot use dot-notation: "${field}". Use a flat field name.`,{field})}_indexDoc(doc){for(let[field,map]of this._fieldIndexes){let val=doc[field];if(val!==void 0){if(!map.has(val))map.set(val,new Set);map.get(val).add(doc)}}for(let[field,map]of this._uniqueIndexes){let val=doc[field];if(val!==void 0)map.set(val,doc)}for(let[,ci]of this._compoundIndexes){for(let f of ci.fields){let val=doc[f];if(val!==void 0&&val!==null&&typeof val==="object")throw new ValidationError("ERR_SKALEX_VALIDATION_COMPOUND_INDEX",`Compound index field "${f}" must be a scalar value (string, number, or boolean), got ${Array.isArray(val)?"array":typeof val}`,{field:f})}let tupleKey=encodeTuple(ci.fields.map((f)=>doc[f]));if(!ci.map.has(tupleKey))ci.map.set(tupleKey,new Set);ci.map.get(tupleKey).add(doc)}}_checkUnique(newDoc,existingDoc){for(let field of this._uniqueFields){let val=newDoc[field];if(val===void 0)continue;let map=this._uniqueIndexes.get(field);if(!map)continue;let existing=map.get(val);if(existing&&existing._id!==existingDoc?._id)throw new UniqueConstraintError("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${field}" value "${val}" already exists`,{field,value:val})}}}var FLUSH_META_KEY="_flush",META_DOC_ID="migrations";class PersistenceManager{constructor({adapter,serializer,deserializer,logger:logger2,debug=!1,lenientLoad=!1}){this._adapter=adapter,this._serializer=serializer,this._deserializer=deserializer,this._logger=logger2,this._debug=debug,this._lenientLoad=lenientLoad,this._saveLock=Promise.resolve()}_withSaveLock(fn){let next=this._saveLock.then(fn);return this._saveLock=next.catch(()=>{}),next}async loadAll(collections,{parseSchema:parseSchema2,buildIndex,IndexEngine:IndexEngine2}){try{let names=await this._adapter.list();await Promise.all(names.map(async(name)=>{try{let raw=await this._adapter.read(name);if(!raw)return;let parsed=this._deserializer(raw),{collectionName,data}=parsed;if(!collectionName)return;let existing=collections[collectionName],rawSchema=existing?.rawSchema??parsed.rawSchema??null,parsedSchema=existing?.schema??(rawSchema?parseSchema2(rawSchema):null),changelog=existing?.changelog??parsed.changelog??!1,softDelete=existing?.softDelete??parsed.softDelete??!1,versioning=existing?.versioning??parsed.versioning??!1,strict=existing?.strict??parsed.strict??!1,onSchemaError=existing?.onSchemaError??parsed.onSchemaError??"throw",defaultTtl=existing?.defaultTtl??parsed.defaultTtl??null,defaultEmbed=existing?.defaultEmbed??parsed.defaultEmbed??null,maxDocs=existing?.maxDocs??parsed.maxDocs??null,fieldIndex=existing?existing.fieldIndex:null;if(!fieldIndex&&parsedSchema?.uniqueFields?.length)fieldIndex=new IndexEngine2([],parsedSchema.uniqueFields);let idIndex=buildIndex(data,"_id");if(fieldIndex)fieldIndex.buildFromData(data);collections[collectionName]={collectionName,data,index:idIndex,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:parsedSchema,rawSchema,fieldIndex,changelog,softDelete,versioning,strict,onSchemaError,defaultTtl,defaultEmbed,maxDocs}}catch(error){if(error.code==="ENOENT")return;if(this._lenientLoad){this._logger(`WARNING: Could not load collection "${name}": ${error.message}. Collection will be empty.`,"error");return}throw new PersistenceError("ERR_SKALEX_PERSISTENCE_CORRUPT",`Failed to load collection "${name}": ${error.message}`,{collection:name})}})),this._detectIncompleteFlush(collections),await this._cleanOrphanTempFiles()}catch(error){if(error.code!=="ENOENT")throw this._logger(`Error loading data: ${error}`,"error"),error}}async save(collections,collectionName){if(collectionName)await this._saveOne(collections,collectionName);else await Promise.all(Object.keys(collections).map((name)=>this._saveOne(collections,name)))}async saveDirty(collections){let dirtyNames=Object.keys(collections).filter((name)=>collections[name]._dirty);if(dirtyNames.length===0)return;await Promise.all(dirtyNames.map((name)=>this._saveOne(collections,name)))}saveAtomic(collections,names){return this._withSaveLock(async()=>{if(names.length===0)return;this._writeFlushSentinel(collections,names);let allNames=new Set(names);allNames.add("_meta");let entries=[...allNames].filter((n)=>collections[n]).map((name)=>({name,data:this._serializeCollection(collections[name])}));try{await this._adapter.writeAll(entries)}catch(error){throw new PersistenceError("ERR_SKALEX_PERSISTENCE_FLUSH_FAILED",`Batch save failed during writeAll: ${error.message}`,{collections:names})}for(let name of names)if(collections[name])collections[name]._dirty=!1;try{this._clearFlushSentinel(collections),await this._adapter.write("_meta",this._serializeCollection(collections._meta))}catch(error){this._logger(`WARNING: Batch data committed but sentinel clear failed: ${error.message}. Next load will report an incomplete flush (false positive).`,"error")}})}markDirty(collections,name){let col=collections[name];if(col)col._dirty=!0}_serializeCollection(col){let payload={collectionName:col.collectionName,data:col.data};if(col.rawSchema)payload.rawSchema=col.rawSchema;if(col.changelog)payload.changelog=col.changelog;if(col.softDelete)payload.softDelete=col.softDelete;if(col.versioning)payload.versioning=col.versioning;if(col.strict)payload.strict=col.strict;if(col.onSchemaError!=="throw")payload.onSchemaError=col.onSchemaError;if(col.defaultTtl)payload.defaultTtl=col.defaultTtl;if(col.defaultEmbed)payload.defaultEmbed=col.defaultEmbed;if(col.maxDocs)payload.maxDocs=col.maxDocs;return this._serializer(payload)}async _saveOne(collections,name){let col=collections[name];if(!col)return;if(col.isSaving)return col._pendingSave=!0,new Promise((resolve,reject)=>{(col._saveWaiters??=[]).push({resolve,reject})});col.isSaving=!0,col._pendingSave=!1;try{await this._writeCollection(name,col);while(col._pendingSave)col._pendingSave=!1,await this._writeCollection(name,col);this._resolveSaveWaiters(col)}catch(error){throw this._rejectSaveWaiters(col,error),error}finally{col.isSaving=!1}}async _writeCollection(name,col){try{await this._adapter.write(name,this._serializeCollection(col)),col._dirty=!1}catch(error){throw this._logger(`Error saving "${name}": ${error.message}`,"error"),error}}_resolveSaveWaiters(col){let waiters=col._saveWaiters?.splice(0)??[];for(let w of waiters)w.resolve()}_rejectSaveWaiters(col,error){let waiters=col._saveWaiters?.splice(0)??[];for(let w of waiters)w.reject(error)}_writeFlushSentinel(collections,names){let meta=this._getOrCreateMeta(collections);meta[FLUSH_META_KEY]={startedAt:new Date().toISOString(),collections:names,completedAt:null}}_clearFlushSentinel(collections){let meta=this._getOrCreateMeta(collections);if(meta[FLUSH_META_KEY])meta[FLUSH_META_KEY].completedAt=new Date().toISOString()}_detectIncompleteFlush(collections){let metaCol=collections._meta;if(!metaCol)return;let metaDoc=metaCol.index.get(META_DOC_ID);if(!metaDoc)return;let flush=metaDoc[FLUSH_META_KEY];if(!flush)return;if(flush.startedAt&&!flush.completedAt)this._logger(`WARNING: Incomplete flush detected (started ${flush.startedAt}, collections: ${flush.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 nodeFs23=await import("fs"),nodePath23=await import("path"),dir=this._adapter.dir;if(!dir)return;let orphans=(await nodeFs23.default.promises.readdir(dir)).filter((f)=>f.includes(".tmp."));for(let orphan of orphans){let orphanPath=nodePath23.default.join(dir,orphan);try{await nodeFs23.default.promises.unlink(orphanPath),this._log(`Cleaned orphan temp file: ${orphan}`)}catch{}}}catch{}}_getOrCreateMeta(collections){if(!collections._meta)collections._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 metaCol=collections._meta,doc=metaCol.index.get(META_DOC_ID);if(!doc)doc={_id:META_DOC_ID},metaCol.data.push(doc),metaCol.index.set(META_DOC_ID,doc);return doc}_log(msg){if(this._debug)this._logger(msg,"info")}}var _txIdCounter=0;class TransactionManager{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(fn,db,{timeout=0}={}){let execute=async()=>{await db._ensureConnected();let preExisting=new Set(Object.keys(db.collections)),ctx={id:++_txIdCounter,startedAt:Date.now(),aborted:!1,preExisting,touchedCollections:new Set,snapshots:new Map,deferredEffects:[],timeout};this._ctx=ctx;let timer=null,timeoutPromise=timeout>0?new Promise((_,reject)=>{timer=setTimeout(()=>{ctx.aborted=!0,reject(new TransactionError("ERR_SKALEX_TX_TIMEOUT",`Transaction ${ctx.id} timed out after ${timeout}ms`))},timeout)}):null,self=this,proxy=new Proxy(db,{get(target,prop){if(prop==="_txId")return ctx.id;if(ctx!==self._ctx)throw new TransactionError("ERR_SKALEX_TX_STALE_PROXY",`Transaction ${ctx.id} has ended. This proxy is no longer usable.`);if(prop==="collections")throw new TransactionError("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(prop==="useCollection")return(name)=>{let col=target.useCollection(name);return col._activeTxId=ctx.id,col};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value}});try{let fnPromise=fn(proxy),result=timeoutPromise?await Promise.race([fnPromise,timeoutPromise]):await fnPromise;if(ctx.aborted)throw new TransactionError("ERR_SKALEX_TX_ABORTED",`Transaction ${ctx.id} was aborted`);let touched=[...ctx.touchedCollections];if(touched.length>0)await db._persistence.saveAtomic(db.collections,touched);for(let effect of ctx.deferredEffects)await effect();return result}catch(error){for(let[name,snap]of ctx.snapshots)if(ctx.preExisting.has(name)){if(db._applySnapshot(name,snap),db.collections[name])db.collections[name]._dirty=snap._dirty}for(let name in db.collections)if(!ctx.preExisting.has(name))delete db.collections[name],delete db._collectionInstances[name];throw error}finally{if(timer)clearTimeout(timer);if(ctx.aborted)this._abortedIds.add(ctx.id);this._ctx=null;for(let name in db._collectionInstances){let inst=db._collectionInstances[name];if(inst._createdInTxId===ctx.id)inst._createdInTxId=null;if(inst._activeTxId===ctx.id)inst._activeTxId=null}}},next=this._txLock.then(execute);return this._txLock=next.catch(()=>{}),next}snapshotIfNeeded(name,col,snapshotFn){let ctx=this._ctx;if(!ctx)return;if(this._assertCtxNotAborted(ctx),!ctx.snapshots.has(name)){let snap=snapshotFn(col);snap._dirty=col._dirty??!1,ctx.snapshots.set(name,snap)}ctx.touchedCollections.add(name)}assertNotAborted(){let ctx=this._ctx;if(ctx)this._assertCtxNotAborted(ctx)}_assertCtxNotAborted(ctx){if(ctx.aborted)throw new TransactionError("ERR_SKALEX_TX_ABORTED",`Transaction ${ctx.id} was aborted. No further mutations allowed.`)}defer(effect){if(this._ctx)return this._ctx.deferredEffects.push(effect),!0;return!1}}class CollectionRegistry{constructor(CollectionClass){this._CollectionClass=CollectionClass,this.stores={},this._instances={}}get(name,db){if(this._instances[name])return this._instances[name];if(!this.stores[name])this.createStore(name);let instance=new this._CollectionClass(this.stores[name],db);return this._instances[name]=instance,instance}create(name,options={},db){this.createStore(name,options);let instance=new this._CollectionClass(this.stores[name],db);return this._instances[name]=instance,instance}createStore(name,{schema,indexes=[],changelog=!1,softDelete=!1,versioning=!1,strict=!1,onSchemaError="throw",defaultTtl=null,defaultEmbed=null,maxDocs=null}={}){let parsedSchema=null,fieldIndex=null;if(schema){parsedSchema=parseSchema(schema);let uniqueFields=parsedSchema.uniqueFields;if(indexes.length||uniqueFields.length)fieldIndex=new IndexEngine(indexes,uniqueFields)}else if(indexes.length)fieldIndex=new IndexEngine(indexes,[]);this.stores[name]={collectionName:name,data:[],index:new Map,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:parsedSchema,rawSchema:schema||null,fieldIndex,changelog,softDelete,versioning,strict,onSchemaError,defaultTtl,defaultEmbed,maxDocs}}rename(from,to){if(!this.stores[from])throw new PersistenceError("ERR_SKALEX_PERSISTENCE_COLLECTION_NOT_FOUND",`Collection "${from}" not found`,{collection:from});if(this.stores[to])throw new PersistenceError("ERR_SKALEX_PERSISTENCE_COLLECTION_EXISTS",`Collection "${to}" already exists`,{collection:to});let store=this.stores[from];if(store.collectionName=to,this.stores[to]=store,delete this.stores[from],this._instances[from]){let inst=this._instances[from];inst.name=to,this._instances[to]=inst,delete this._instances[from]}}buildIndex(data,keyField){let index=new Map;for(let item of data)index.set(item[keyField],item);return index}inspect(name){if(name){let col=this.stores[name];if(!col)return null;return{name,count:col.data.length,schema:col.schema?Object.fromEntries(col.schema.fields):null,indexes:col.fieldIndex?[...col.fieldIndex.indexedFields]:[],softDelete:col.softDelete??!1,versioning:col.versioning??!1,strict:col.strict??!1,onSchemaError:col.onSchemaError??"throw",maxDocs:col.maxDocs??null}}let result={};for(let n in this.stores)result[n]=this.inspect(n);return result}dump(){let result={};for(let name in this.stores)if(!name.startsWith("_"))result[name]=structuredClone(this.stores[name].data);return result}schema(name){let store=this.stores[name];if(!store)return null;if(store.schema)return Object.fromEntries([...store.schema.fields.entries()].map(([k,v])=>[k,v.type]));if(store.data.length>0)return inferSchema(store.data[0]);return null}stats(name){let calc=(n)=>{let col=this.stores[n];if(!col)return null;let count2=col.data.length,estimatedSize=0;for(let doc of col.data)try{estimatedSize+=JSON.stringify(doc).length}catch(_){}return{collection:n,count:count2,estimatedSize,avgDocSize:count2>0?Math.round(estimatedSize/count2):0}};if(name)return calc(name);return Object.keys(this.stores).map(calc)}clear(){this.stores={},this._instances={}}}class EmbeddingAdapter{async embed(text){throw Error("EmbeddingAdapter.embed() not implemented")}}var _env$4=(k)=>globalThis.process?.env?.[k]??globalThis.Deno?.env?.get(k);class OpenAIEmbeddingAdapter extends EmbeddingAdapter{constructor({apiKey=_env$4("OPENAI_API_KEY"),model=_env$4("OPENAI_EMBED_MODEL")??"text-embedding-3-small",baseUrl=_env$4("OPENAI_EMBED_BASE_URL")??"https://api.openai.com/v1/embeddings",dimensions=_env$4("OPENAI_EMBED_DIMENSIONS")!=null?Number(_env$4("OPENAI_EMBED_DIMENSIONS")):void 0,organization=_env$4("OPENAI_ORGANIZATION")??void 0,timeout=_env$4("OPENAI_EMBED_TIMEOUT")!=null?Number(_env$4("OPENAI_EMBED_TIMEOUT")):void 0,retries=Number(_env$4("OPENAI_EMBED_RETRIES")??0),retryDelay=Number(_env$4("OPENAI_EMBED_RETRY_DELAY")??1000),headers={},fetch:fetchFn=globalThis.fetch}={}){super();if(!apiKey)throw Error("OpenAIEmbeddingAdapter requires an apiKey");this.apiKey=apiKey,this.model=model,this.baseUrl=baseUrl,this.dimensions=dimensions,this.organization=organization,this.timeout=timeout,this.retries=retries,this.retryDelay=retryDelay,this.headers=headers,this._fetch=fetchFn}async embed(text){let lastErr;for(let attempt=0;attempt<=this.retries;attempt++){let controller=this.timeout!=null?new AbortController:null,timer=controller?setTimeout(()=>controller.abort(),this.timeout):null;try{let response=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:text,model:this.model,...this.dimensions!==void 0&&{dimensions:this.dimensions}}),...controller&&{signal:controller.signal}});if(!response.ok){let err=(await response.text()).slice(0,200);throw Error(`OpenAI embedding API error ${response.status}: ${err}`)}return(await response.json()).data[0].embedding}catch(err){if(lastErr=err,attempt<this.retries)await new Promise((r)=>setTimeout(r,this.retryDelay*2**attempt))}finally{if(timer!==null)clearTimeout(timer)}}throw lastErr}}var _env$3=(k)=>globalThis.process?.env?.[k]??globalThis.Deno?.env?.get(k);class OllamaEmbeddingAdapter extends EmbeddingAdapter{constructor({model=_env$3("OLLAMA_EMBED_MODEL")??"nomic-embed-text",host=_env$3("OLLAMA_HOST")??"http://localhost:11434",timeout=_env$3("OLLAMA_EMBED_TIMEOUT")!=null?Number(_env$3("OLLAMA_EMBED_TIMEOUT")):void 0,retries=Number(_env$3("OLLAMA_EMBED_RETRIES")??0),retryDelay=Number(_env$3("OLLAMA_EMBED_RETRY_DELAY")??1000),headers={},fetch:fetchFn=globalThis.fetch}={}){super();this.model=model,this.host=host,this.timeout=timeout,this.retries=retries,this.retryDelay=retryDelay,this.headers=headers,this._fetch=fetchFn}async embed(text){let lastErr;for(let attempt=0;attempt<=this.retries;attempt++){let controller=this.timeout!=null?new AbortController:null,timer=controller?setTimeout(()=>controller.abort(),this.timeout):null;try{let response=await this._fetch(`${this.host}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json",...this.headers},body:JSON.stringify({model:this.model,prompt:text}),...controller&&{signal:controller.signal}});if(!response.ok){let err=(await response.text()).slice(0,200);throw Error(`Ollama embedding API error ${response.status}: ${err}`)}return(await response.json()).embedding}catch(err){if(lastErr=err,attempt<this.retries)await new Promise((r)=>setTimeout(r,this.retryDelay*2**attempt))}finally{if(timer!==null)clearTimeout(timer)}}throw lastErr}}class LLMAdapter{async generate(schema,nlQuery){throw Error("LLMAdapter.generate() not implemented")}async summarize(texts){throw Error("LLMAdapter.summarize() not implemented")}}var SYSTEM_GENERATE=`You are a database query assistant. Convert the user's natural language request into a JSON filter object for a document database.
6
6
 
@@ -26,7 +26,7 @@ data: /message
26
26
 
27
27
  `),this._clients.add(res),req.on("close",()=>{this._clients.delete(res)})}async _handleMessage(req,res){let body="";req.setEncoding("utf8"),req.on("data",(c)=>{if(body+=c,body.length>this._maxBodySize)req.destroy(),res.writeHead(413,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Request body too large"}))}),req.on("end",async()=>{res.writeHead(202,{"Content-Type":"application/json"}),res.end("{}");let msg;try{msg=JSON.parse(body)}catch(_){this.send(error(null,PARSE_ERROR,"Parse error"));return}if(this._onMessage)await this._onMessage(msg).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 StdioTransport{constructor(){this._onMessage=null,this._buffer="",this._started=!1}onMessage(fn){this._onMessage=fn}send(msg){process.stdout.write(JSON.stringify(msg)+`
28
28
  `)}start(){if(this._started)return;this._started=!0,process.stdin.setEncoding("utf8"),process.stdin.on("data",(chunk)=>{this._buffer+=chunk;let idx;while((idx=this._buffer.indexOf(`
29
- `))!==-1){let line=this._buffer.slice(0,idx).trim();if(this._buffer=this._buffer.slice(idx+1),line&&this._onMessage){let msg;try{msg=JSON.parse(line)}catch(_){this.send(error(null,PARSE_ERROR,"Parse error"));continue}this._onMessage(msg).catch(()=>{})}}}),process.stdin.on("end",()=>{process.exit(0)})}stop(){process.stdin.removeAllListeners("data"),process.stdin.removeAllListeners("end"),this._started=!1}}var SERVER_INFO={name:"skalex",version:"4.0.0-alpha"},PROTOCOL_VERSION="2024-11-05";class SkalexMCPServer{constructor(db,opts={}){this._db=db,this._transport=opts.transport||"stdio",this._port=opts.port||3000,this._host=opts.host||"127.0.0.1",this._allowedOrigin=opts.allowedOrigin??null,this._maxBodySize=opts.maxBodySize??1048576,this._scopes=opts.scopes||{"*":["read"]},this._t=null}async listen(){if(this._transport==="http")this._t=new HttpTransport({port:this._port,host:this._host,allowedOrigin:this._allowedOrigin,maxBodySize:this._maxBodySize});else this._t=new StdioTransport;this._t.onMessage((msg)=>this._handleMessage(msg)),await this._t.start()}async connect(transport){if(this._t=transport,this._t.onMessage((msg)=>this._handleMessage(msg)),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(raw){let{msg,parseError}=typeof raw==="string"?parse(raw):{msg:raw};if(parseError){this._send(parseError);return}let{id,method,params}=msg;if(id===void 0){if(method==="notifications/initialized")return;return}try{switch(method){case"initialize":this._send(ok(id,{protocolVersion:PROTOCOL_VERSION,capabilities:{tools:{}},serverInfo:SERVER_INFO}));break;case"tools/list":this._send(ok(id,{tools:this._visibleTools()}));break;case"tools/call":await this._handleToolCall(id,params);break;case"ping":this._send(ok(id,{}));break;default:this._send(error(id,METHOD_NOT_FOUND,`Method not found: ${method}`))}}catch(err){this._send(error(id,INTERNAL_ERROR,err.message||"Internal error"))}}async _handleToolCall(id,params){let name=params?.name,args=params?.arguments??{};if(!name){this._send(error(id,INVALID_PARAMS,"tools/call requires params.name"));return}let def=TOOL_DEFS.find((t)=>t.name===name);if(!def){this._send(error(id,METHOD_NOT_FOUND,`Unknown tool: ${name}`));return}let collection=args.collection||args.collection_name||null;if(!this._hasScope(collection,def.scope)){this._send(ok(id,toolError(`Access denied: "${name}" requires "${def.scope}" scope on collection "${collection}".`)));return}try{let result=await callTool(name,args,this._db);this._send(ok(id,toolResult(JSON.stringify(result,null,2))))}catch(err){this._send(ok(id,toolError(err.message||String(err))))}}_visibleTools(){return TOOL_DEFS.filter((def)=>{let global=this._scopes["*"];if(global&&(global.includes(def.scope)||global.includes("admin")))return!0;for(let[,perms]of Object.entries(this._scopes))if(perms.includes(def.scope)||perms.includes("admin"))return!0;return!1})}_hasScope(collection,scope){let check=(perms)=>perms.includes("admin")||perms.includes(scope);if(collection&&this._scopes[collection])return check(this._scopes[collection]);if(this._scopes["*"])return check(this._scopes["*"]);return!1}_send(msg){this._t?.send(msg)}}var META_KEY="migrations",_serialize=(value)=>JSON.stringify(value,function(key,v){let raw=this[key];if(raw instanceof Date)return{__skalex_date__:raw.toISOString()};if(typeof v==="bigint")return{__skalex_bigint__:v.toString()};return v}),_deserialize=(text)=>JSON.parse(text,(_,v)=>{if(v&&typeof v==="object"){if("__skalex_bigint__"in v)return BigInt(v.__skalex_bigint__);if("__skalex_date__"in v)return new Date(v.__skalex_date__)}return v});class Skalex{constructor({path="./.db",format="gz",debug=!1,adapter,ai,encrypt,slowQueryLog,queryCache,memory,logger:logger$1,plugins,llmAdapter,embeddingAdapter,regexMaxLength,idGenerator,serializer,deserializer,autoSave,ttlSweepInterval,lenientLoad}={}){if(this.dataDirectory=path,this.dataFormat=format,this.debug=debug,!Skalex._errorsAttached)Skalex.SkalexError=SkalexError,Skalex.ValidationError=ValidationError,Skalex.UniqueConstraintError=UniqueConstraintError,Skalex.TransactionError=TransactionError,Skalex.PersistenceError=PersistenceError,Skalex.AdapterError=AdapterError,Skalex.QueryError=QueryError,Skalex._errorsAttached=!0;this._adapterConfig=adapter??null;let fs=adapter||new FsAdapter({dir:path,format});if(encrypt)fs=new EncryptedAdapter(fs,encrypt.key);if(this.fs=fs,this._registry=new CollectionRegistry(Collection),this.collections=this._registry.stores,this._collectionInstances=this._registry._instances,this._migrations=new MigrationEngine,this._connectPromise=null,this.isConnected=!1,this._aiConfig=ai||null,this._encryptConfig=encrypt||null,this._pluginsConfig=Array.isArray(plugins)?plugins:null,this._memoryConfig=memory||null,this._regexMaxLength=regexMaxLength??500,this._idGenerator=idGenerator??null,this._serializer=serializer??_serialize,this._deserializer=deserializer??_deserialize,this._autoSave=autoSave??!1,this._txManager=new TransactionManager,this._ttlSweepInterval=ttlSweepInterval??0,this._ttlTimer=null,this._logger=logger$1??logger,this._embeddingAdapter=embeddingAdapter??(ai?createEmbeddingAdapter(ai):null),this._aiAdapter=llmAdapter??(ai?createLLMAdapter(ai):null),this._persistence=new PersistenceManager({adapter:this.fs,serializer:this._serializer,deserializer:this._deserializer,logger:this._logger,debug:this.debug,lenientLoad:lenientLoad??!1}),this._changeLog=new ChangeLog(this),this._queryCache=new QueryCache(queryCache||{}),this._eventBus=new EventBus,this._queryLog=slowQueryLog?new QueryLog(slowQueryLog):null,this._sessionStats=new SessionStats,this._plugins=new PluginEngine,Array.isArray(plugins))for(let p of plugins)this._plugins.register(p)}async connect(){if(this._connectPromise)return this._connectPromise;return this._connectPromise=this._doConnect(),this._connectPromise}async _doConnect(){try{await this.loadData();let meta=this._getMeta();if(meta.queryCache)this._queryCache.fromJSON(meta.queryCache);if(this._migrations._migrations.length>0){let applied=meta.appliedVersions||[],newApplied=await this._migrations.run((version)=>this.useCollection(`_migration_${version}`),applied);this._saveMeta({appliedVersions:newApplied})}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(error2){throw this._logger(`Error connecting to the database: ${error2}`,"error"),error2}}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(error2){throw this._logger(`Error disconnecting from the database: ${error2}`,"error"),error2}}async _ensureConnected(){if(this.isConnected)return;return this.connect()}useCollection(collectionName){return this._registry.get(collectionName,this)}createCollection(collectionName,options={}){return this._registry.create(collectionName,options,this)}_createCollectionStore(collectionName,options={}){this._registry.createStore(collectionName,options)}async renameCollection(from,to){this._registry.rename(from,to),await this.saveData(to),await this.fs.delete(from)}async loadData(){await this._persistence.loadAll(this.collections,{parseSchema,buildIndex:this._registry.buildIndex,IndexEngine});for(let name in this._collectionInstances){let store=this.collections[name];if(store&&this._collectionInstances[name]._store!==store)this._collectionInstances[name]._store=store}}async saveData(collectionName){await this._persistence.save(this.collections,collectionName)}buildIndex(data,keyField){return this._registry.buildIndex(data,keyField)}addMigration(migration){this._migrations.add(migration)}migrationStatus(){let meta=this._getMeta();return this._migrations.status(meta.appliedVersions||[])}namespace(id){if(this._adapterConfig)throw new AdapterError("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 safeId=String(id).replace(/[^a-zA-Z0-9_-]/g,"_");if(!safeId)throw new ValidationError("ERR_SKALEX_VALIDATION_NAMESPACE_ID","namespace: id must contain at least one alphanumeric character",{id});return new Skalex({path:`${this.dataDirectory}/${safeId}`,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!==logger?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!==_serialize?this._serializer:void 0,deserializer:this._deserializer!==_deserialize?this._deserializer:void 0,autoSave:this._autoSave||void 0,ttlSweepInterval:this._ttlSweepInterval||void 0})}use(plugin){this._plugins.register(plugin)}watch(callback){return this._eventBus.on("*",callback)}sessionStats(sessionId){if(sessionId!==void 0)return this._sessionStats.get(sessionId);return this._sessionStats.all()}get _inTransaction(){return this._txManager.active}_emitEvent(collectionName,data){if(!this._txManager.defer(()=>this._eventBus.emit(collectionName,data)))this._eventBus.emit(collectionName,data)}async _runAfterHook(hook,data){if(!this._txManager.defer(()=>this._plugins.run(hook,data)))await this._plugins.run(hook,data)}async _logChange(op,collectionName,doc,prev,session){if(!this._txManager.defer(()=>this._changeLog.log(op,collectionName,doc,prev,session)))await this._changeLog.log(op,collectionName,doc,prev,session)}async transaction(fn,opts={}){return this._txManager.run(fn,this,opts)}async seed(fixtures,{reset=!1}={}){for(let[name,docs]of Object.entries(fixtures)){if(reset&&this.collections[name])this._applySnapshot(name,{data:[],index:new Map}),delete this._collectionInstances[name];await this.useCollection(name).insertMany(docs)}await this.saveData()}dump(){return this._registry.dump()}inspect(collectionName){return this._registry.inspect(collectionName)}async import(filePath){let content=await this.fs.readRaw(filePath),docs;try{docs=JSON.parse(content)}catch{throw new PersistenceError("ERR_SKALEX_PERSISTENCE_INVALID_JSON",`import: invalid JSON in file "${filePath}"`,{filePath})}let name=filePath.split("/").pop().replace(/\.[^.]+$/,"");return this.useCollection(name).insertMany(Array.isArray(docs)?docs:[docs],{save:!0})}async embed(text){if(!this._embeddingAdapter)throw new AdapterError("ERR_SKALEX_ADAPTER_EMBEDDING_REQUIRED","db.embed() requires an AI adapter. Pass { ai: { provider, apiKey } } to the Skalex constructor.");return this._embeddingAdapter.embed(text)}async ask(collectionName,nlQuery,{limit=20}={}){if(!this._aiAdapter)throw new AdapterError("ERR_SKALEX_ADAPTER_LLM_REQUIRED",'db.ask() requires a language model adapter. Configure { ai: { provider, model: "..." } }.');let col=this.useCollection(collectionName),schema=this.schema(collectionName),filter=this._queryCache.get(collectionName,schema,nlQuery);if(!filter){filter=await this._aiAdapter.generate(schema,nlQuery);let warnings=validateLLMFilter(filter,schema);if(warnings.length)warnings.forEach((w)=>this._log(`[ask] ${w}`));this._queryCache.set(collectionName,schema,nlQuery,filter),this._saveMeta({queryCache:this._queryCache.toJSON()})}return col.find(processLLMFilter(filter,{regexMaxLength:this._regexMaxLength}),{limit})}schema(collectionName){return this._registry.schema(collectionName)}useMemory(sessionId){return new Memory(sessionId,this)}changelog(){return this._changeLog}async restore(collectionName,timestamp,opts={}){return this._changeLog.restore(collectionName,timestamp,opts)}stats(collectionName){return this._registry.stats(collectionName)}slowQueries(opts={}){if(!this._queryLog)return[];return this._queryLog.entries(opts)}slowQueryCount(){return this._queryLog?this._queryLog.size:0}clearSlowQueries(){this._queryLog?.clear()}mcp(opts={}){return new SkalexMCPServer(this,opts)}_getMeta(){let metaCol=this.collections._meta;if(!metaCol)return{};return metaCol.index.get(META_KEY)||{}}_saveMeta(data){if(!this.collections._meta)this._createCollectionStore("_meta");let col=this.collections._meta,existing=col.index.get(META_KEY);if(existing)Object.assign(existing,data);else{let doc={_id:META_KEY,...data};col.data.push(doc),col.index.set(META_KEY,doc)}this._persistence.markDirty(this.collections,"_meta")}_sweepTtl(){for(let name in this.collections){let col=this.collections[name],removed=sweep(col.data,col.index,col.fieldIndex?(doc)=>col.fieldIndex.remove(doc):null);if(removed>0)this._persistence.markDirty(this.collections,name),this._log(`TTL sweep: removed ${removed} expired docs from "${name}"`)}}_buildCollectionContext(){let db=this;return{ensureConnected:()=>db._ensureConnected(),get txManager(){return db._txManager},get plugins(){return db._plugins},get eventBus(){return db._eventBus},get sessionStats(){return db._sessionStats},get queryLog(){return db._queryLog},get logger(){return db._logger},get persistence(){return db._persistence},get collections(){return db.collections},embed:(text)=>db.embed(text),get idGenerator(){return db._idGenerator},get autoSave(){return db._autoSave},saveCollection:(name)=>db.saveData(name),snapshotCollection:(col)=>db._snapshotCollection(col),getCollection:(name)=>db.useCollection(name),emitEvent:(name,data)=>db._emitEvent(name,data),runAfterHook:(hook,data)=>db._runAfterHook(hook,data),logChange:(op,col,doc,prev,session)=>db._logChange(op,col,doc,prev,session),get fs(){return db.fs},get dataDirectory(){return db.dataDirectory}}}_log(msg){if(this.debug)this._logger(msg,"info")}_snapshotCollection(col){return{data:structuredClone(col.data)}}_applySnapshot(name,snap){let col=this.collections[name];if(!col)return;if(col.data=snap.data,col.index=this.buildIndex(snap.data,"_id"),col.fieldIndex)col.fieldIndex.buildFromData(snap.data)}}function generateUniqueId2(){let timestamp=Date.now().toString(16),random;try{random=nodeCrypto2.randomBytes(8).toString("hex")}catch{let arr=new Uint8Array(8);crypto.getRandomValues(arr),random=Array.from(arr).map((b)=>b.toString(16).padStart(2,"0")).join("")}return`${timestamp}${random}`}function logger2(error2,type){let msg=error2 instanceof Error?error2.message:error2;if(type==="error")console.error(msg);else console.log(msg)}var _FORBIDDEN_KEYS2=new Set(["__proto__","constructor","prototype"]);function resolveDotPath2(obj,path){if(!path.includes(".")){if(_FORBIDDEN_KEYS2.has(path))return;return obj[path]}let cur=obj;for(let p of path.split(".")){if(_FORBIDDEN_KEYS2.has(p))return;if(cur==null)return;cur=cur[p]}return cur}class SkalexError2 extends Error{constructor(code,message,details={}){super(message);this.name=this.constructor.name,this.code=code,this.details=details}}class ValidationError2 extends SkalexError2{}class UniqueConstraintError2 extends SkalexError2{}class TransactionError2 extends SkalexError2{}class PersistenceError2 extends SkalexError2{}class AdapterError2 extends SkalexError2{}class QueryError2 extends SkalexError2{}function deepEqual2(a,b){if(a===b)return!0;if(a==null||b==null)return!1;if(typeof a!==typeof b)return!1;if(a instanceof Date&&b instanceof Date)return a.getTime()===b.getTime();if(a instanceof RegExp&&b instanceof RegExp)return a.source===b.source&&a.flags===b.flags;if(Array.isArray(a)){if(!Array.isArray(b)||a.length!==b.length)return!1;for(let i=0;i<a.length;i++)if(!deepEqual2(a[i],b[i]))return!1;return!0}if(typeof a==="object"){if(Array.isArray(b))return!1;let keysA=Object.keys(a);if(keysA.length!==Object.keys(b).length)return!1;for(let k of keysA){if(!Object.prototype.hasOwnProperty.call(b,k))return!1;if(!deepEqual2(a[k],b[k]))return!1}return!0}return!1}function matchesFilter2(item,filter){if(typeof filter==="function")return filter(item);if(filter==null)return!0;if(typeof filter==="object"&&Object.keys(filter).length===0)return!0;if("$or"in filter){let branches=filter.$or;if(!Array.isArray(branches))throw new QueryError2("ERR_SKALEX_QUERY_INVALID_OPERATOR","$or must be an array of filters",{operator:"$or"});if(!branches.some((sub)=>matchesFilter2(item,sub)))return!1}if("$and"in filter){let branches=filter.$and;if(!Array.isArray(branches))throw new QueryError2("ERR_SKALEX_QUERY_INVALID_OPERATOR","$and must be an array of filters",{operator:"$and"});if(!branches.every((sub)=>matchesFilter2(item,sub)))return!1}if("$not"in filter){if(matchesFilter2(item,filter.$not))return!1}for(let key in filter){if(key==="$or"||key==="$and"||key==="$not")continue;let filterValue=filter[key],itemValue;try{itemValue=resolveDotPath2(item,key)}catch{return!1}if(filterValue instanceof RegExp){if(!filterValue.test(String(itemValue)))return!1}else if(typeof filterValue==="object"&&filterValue!==null){if(Object.keys(filterValue).some((k)=>k.startsWith("$"))){if("$eq"in filterValue&&itemValue!==filterValue.$eq)return!1;if("$ne"in filterValue&&itemValue===filterValue.$ne)return!1;if("$gt"in filterValue&&!(itemValue>filterValue.$gt))return!1;if("$lt"in filterValue&&!(itemValue<filterValue.$lt))return!1;if("$gte"in filterValue&&!(itemValue>=filterValue.$gte))return!1;if("$lte"in filterValue&&!(itemValue<=filterValue.$lte))return!1;if("$in"in filterValue&&!filterValue.$in.includes(itemValue))return!1;if("$nin"in filterValue&&filterValue.$nin.includes(itemValue))return!1;if("$regex"in filterValue){if(!(filterValue.$regex instanceof RegExp?filterValue.$regex:new RegExp(filterValue.$regex)).test(String(itemValue)))return!1}if("$fn"in filterValue&&!filterValue.$fn(itemValue))return!1}else if(!deepEqual2(itemValue,filterValue))return!1}else if(itemValue!==filterValue)return!1}return!0}function presortFilter2(filter,indexedFields=new Set){if(typeof filter!=="object"||filter===null||typeof filter==="function")return filter;let indexed=[],equality=[],range=[],expensive=[],logical=[];for(let key in filter){if(key==="$or"||key==="$and"||key==="$not"){logical.push(key);continue}let val=filter[key];if(indexedFields.has(key))indexed.push(key);else if(val instanceof RegExp||typeof val==="object"&&val!==null&&(("$regex"in val)||("$fn"in val))||typeof val==="function")expensive.push(key);else if(typeof val==="object"&&val!==null&&(("$gt"in val)||("$lt"in val)||("$gte"in val)||("$lte"in val)||("$ne"in val)||("$in"in val)||("$nin"in val)))range.push(key);else equality.push(key)}let sorted={};for(let k of[...indexed,...equality,...range,...expensive,...logical])sorted[k]=filter[k];return sorted}var SUPPORTED_TYPES2=new Set(["string","number","boolean","object","array","date","any"]);function typeOf2(val){if(Array.isArray(val))return"array";if(val instanceof Date)return"date";return typeof val}function parseSchema2(schema){let fields=new Map,uniqueFields=[];for(let[key,def]of Object.entries(schema)){let fieldDef;if(typeof def==="string"){if(!SUPPORTED_TYPES2.has(def))throw new ValidationError2("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${def}" for field "${key}"`,{field:key,type:def});fieldDef={type:def,required:!1,unique:!1}}else if(typeof def==="object"&&def!==null){let{type="any",required=!1,unique=!1,enum:enumVals}=def;if(!SUPPORTED_TYPES2.has(type))throw new ValidationError2("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${type}" for field "${key}"`,{field:key,type});if(fieldDef={type,required,unique,enum:enumVals},unique)uniqueFields.push(key)}else throw new ValidationError2("ERR_SKALEX_VALIDATION_INVALID_SCHEMA",`Invalid schema definition for field "${key}"`,{field:key});fields.set(key,fieldDef)}return{fields,uniqueFields}}function validateDoc2(doc,fields,strict=!1){let errors=[];for(let[key,def]of fields){let val=doc[key],missing=val===void 0||val===null;if(def.required&&missing){errors.push(`Field "${key}" is required`);continue}if(missing)continue;if(def.type!=="any"){let actualType=typeOf2(val);if(actualType!==def.type)errors.push(`Field "${key}" must be of type "${def.type}", got "${actualType}"`)}if(def.enum&&!def.enum.includes(val))errors.push(`Field "${key}" must be one of [${def.enum.map((v)=>JSON.stringify(v)).join(", ")}], got ${JSON.stringify(val)}`)}if(strict){for(let key of Object.keys(doc))if(!key.startsWith("_")&&!fields.has(key))errors.push(`Unknown field "${key}" (strict mode)`)}return errors}function stripInvalidFields2(doc,fields){let out={};for(let[key,val]of Object.entries(doc)){if(key.startsWith("_")){out[key]=val;continue}if(!fields.has(key))continue;let def=fields.get(key);if(def.type!=="any"){if(typeOf2(val)!==def.type)continue}if(def.enum&&!def.enum.includes(val))continue;out[key]=val}return out}function inferSchema2(doc){let schema={};for(let[key,val]of Object.entries(doc)){if(key.startsWith("_"))continue;let t=typeOf2(val);schema[key]=SUPPORTED_TYPES2.has(t)?t:"any"}return schema}function parseTtl2(ttl){if(typeof ttl==="number"){if(ttl<=0)throw new ValidationError2("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got ${ttl}`,{ttl});return ttl*1000}if(typeof ttl!=="string")throw new ValidationError2("ERR_SKALEX_VALIDATION_TTL",`Invalid TTL value: ${ttl}`,{ttl});let match=ttl.match(/^(\d+(?:\.\d+)?)(ms|s|m|h|d)$/);if(!match)throw new ValidationError2("ERR_SKALEX_VALIDATION_TTL_FORMAT",`Invalid TTL format: "${ttl}". Use e.g. 300 (seconds), "30m", "24h", "7d"`,{ttl});let val=parseFloat(match[1]);if(val<=0)throw new ValidationError2("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got "${ttl}"`,{ttl});let unit=match[2],ms=val*{ms:1,s:1000,m:60000,h:3600000,d:86400000}[unit];if(!isFinite(ms))throw new ValidationError2("ERR_SKALEX_VALIDATION_TTL",`TTL value "${ttl}" is too large`,{ttl});return ms}function computeExpiry2(ttl){return new Date(Date.now()+parseTtl2(ttl))}function sweep2(data,idIndex,removeFromIndexes=null){let now=Date.now(),removed=0,i=data.length;while(i--){let doc=data[i];if(doc._expiresAt&&new Date(doc._expiresAt).getTime()<=now){if(data.splice(i,1),idIndex.delete(doc._id),removeFromIndexes)removeFromIndexes(doc);removed++}}return removed}function cosineSimilarity2(a,b){if(a.length!==b.length)throw new QueryError2("ERR_SKALEX_QUERY_VECTOR_MISMATCH",`Vector dimension mismatch: ${a.length} vs ${b.length}`,{expected:a.length,got:b.length});let dot=0,magA=0,magB=0;for(let i=0;i<a.length;i++)dot+=a[i]*b[i],magA+=a[i]*a[i],magB+=b[i]*b[i];let denom=Math.sqrt(magA*magB);return denom===0?0:dot/denom}function stripVector2(doc){if(!("_vector"in doc))return{...doc};let{_vector,...rest}=doc;return rest}function count2(docs){return docs.length}function sum2(docs,field){let total=0;for(let doc of docs){let val=resolveDotPath2(doc,field);if(typeof val==="number"&&!isNaN(val))total+=val}return total}function avg2(docs,field){let total=0,n=0;for(let doc of docs){let val=resolveDotPath2(doc,field);if(typeof val==="number"&&!isNaN(val))total+=val,n++}return n===0?null:total/n}function groupBy2(docs,field){let groups=Object.create(null);for(let doc of docs){let key=String(resolveDotPath2(doc,field)??"__null__");if(!groups[key])groups[key]=[];groups[key].push(doc)}return groups}class MutationPipeline2{constructor(collection){this._col=collection}get _ctx(){return this._col._ctx}async execute({op,beforeHook,afterHook,hookPayload,mutate,afterHookPayload,save,session}){let ctx=this._ctx;await ctx.ensureConnected(),this._col._txSnapshotIfNeeded();let txm=ctx.txManager,isTxWrite=txm.active&&this._col._activeTxId===txm.context?.id,entryTxId=isTxWrite?txm.context.id:null,collTxId=this._col._createdInTxId,assertTxAlive=()=>{if(entryTxId!==null&&txm._abortedIds.has(entryTxId))throw new TransactionError2("ERR_SKALEX_TX_ABORTED",`Transaction ${entryTxId} was aborted. No further mutations allowed.`);if(collTxId!==null&&txm._abortedIds.has(collTxId))throw new TransactionError2("ERR_SKALEX_TX_ABORTED",`Transaction ${collTxId} was aborted. Collection obtained inside that transaction cannot be used for further mutations.`)};if(isTxWrite||collTxId!==null)assertTxAlive();if(beforeHook)await ctx.plugins.run(beforeHook,hookPayload);let{docs,prevDocs=[]}=await mutate(assertTxAlive);if(ctx.persistence.markDirty(ctx.collections,this._col.name),await this._col._saveIfNeeded(save),this._col._changelogEnabled)for(let i=0;i<docs.length;i++)await ctx.logChange(op,this._col.name,docs[i],prevDocs[i]??null,session||null);if(!isTxWrite||!txm.defer(()=>ctx.sessionStats.recordWrite(session)))ctx.sessionStats.recordWrite(session);for(let doc of docs)ctx.emitEvent(this._col.name,{op,collection:this._col.name,doc:stripVector2(doc)});if(afterHook)if(afterHookPayload)await ctx.runAfterHook(afterHook,afterHookPayload(docs));else for(let doc of docs)await ctx.runAfterHook(afterHook,{collection:this._col.name,doc:stripVector2(doc)});return{docs,prevDocs}}}function resolveFilterToValues2(filter){let resolved={};for(let key in filter){if(key.startsWith("$"))continue;let val=filter[key];if(val&&typeof val==="object"&&!Array.isArray(val)){let keys=Object.keys(val);if(keys.length===1&&keys[0]==="$eq")resolved[key]=val.$eq}else resolved[key]=val}return resolved}var _DANGEROUS_KEYS2=new Set(["__proto__","constructor","prototype"]);function stripDangerousKeys2(val){if(typeof val!=="object"||val===null||Array.isArray(val))return val;let out={};for(let k of Object.keys(val)){if(_DANGEROUS_KEYS2.has(k))continue;out[k]=stripDangerousKeys2(val[k])}return out}class Collection2{constructor(collectionData,database){this.name=collectionData.collectionName,this.database=database,this._ctx=database._buildCollectionContext(),this._store=collectionData,this._pipeline=new MutationPipeline2(this),this._createdInTxId=database._txManager.context?.id??null,this._activeTxId=null}get _data(){return this._store.data}set _data(val){this._store.data=val}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(item,options={}){let{save,ifNotExists,ttl,embed,session}=options;if(ifNotExists){await this._ctx.ensureConnected();let existing=this._findRaw(item);if(existing)return stripVector2({...existing})}let{docs}=await this._insertCore([item],{ttl,embed,session,save});return stripVector2(docs[0])}async insertMany(items,options={}){let{save,ttl,embed,session}=options,{docs}=await this._insertCore(items,{ttl,embed,session,save});return docs.map(stripVector2)}async _insertCore(items,{ttl,embed,session,save}){return this._pipeline.execute({op:"insert",beforeHook:null,afterHook:"afterInsert",hookPayload:null,save,session,mutate:async(assertTxAlive)=>{let newItems=[],batchIds=new Set;for(let item of items){let validated=this._applyValidation(item);await this._ctx.plugins.run("beforeInsert",{collection:this.name,doc:validated});let newItem=await this._buildDoc(validated,{ttl,embed});if(this._index.has(newItem._id)||batchIds.has(newItem._id))throw new UniqueConstraintError2("ERR_SKALEX_UNIQUE_DUPLICATE_ID",`Duplicate _id "${newItem._id}" in collection "${this.name}"`,{id:newItem._id,collection:this.name});batchIds.add(newItem._id),newItems.push(newItem)}if(assertTxAlive(),this._fieldIndex)this._fieldIndex.assertUniqueBatch(newItems);for(let newItem of newItems)this._addToIndex(newItem);this._data.push(...newItems);for(let newItem of newItems)this._index.set(newItem._id,newItem);return this._enforceCapAfterInsert(),{docs:newItems}}})}async updateOne(filter,update,options={}){await this._ctx.ensureConnected();let oldDoc=this._findRaw(filter);if(!oldDoc)return null;let{save,session}=options,{docs}=await this._updateCore([oldDoc],filter,update,{save,session});return stripVector2(docs[0])}async updateMany(filter,update,options={}){await this._ctx.ensureConnected();let oldDocs=this._findAllRaw(filter);if(oldDocs.length===0)return[];let{save,session}=options,{docs}=await this._updateCore(oldDocs,filter,update,{save,session});return docs.map(stripVector2)}async _updateCore(oldDocs,filter,update,{save,session}){return this._pipeline.execute({op:"update",beforeHook:"beforeUpdate",afterHook:"afterUpdate",hookPayload:{collection:this.name,filter,update},save,session,afterHookPayload:(docs)=>({collection:this.name,filter,update,result:docs.length===1?docs[0]:docs}),mutate:async(assertTxAlive)=>{let prevDocs=this._changelogEnabled?oldDocs.map((doc)=>structuredClone(doc)):oldDocs.map(()=>null),nextDocs=oldDocs.map((doc)=>this._prepareUpdatedDoc(doc,update));this._assertUniqueCandidates(oldDocs,nextDocs),assertTxAlive();let targets=new Set(oldDocs),positions=new Map;for(let i=0;i<this._data.length;i++)if(targets.has(this._data[i]))positions.set(this._data[i],i);for(let i=0;i<oldDocs.length;i++)this._commitUpdatedDoc(oldDocs[i],nextDocs[i],positions);return{docs:nextDocs,prevDocs}}})}applyUpdate(item,update){for(let field in update){if(_DANGEROUS_KEYS2.has(field))continue;if(field==="_id"||field==="createdAt")continue;let updateValue=update[field];if(Array.isArray(updateValue))item[field]=updateValue;else if(typeof updateValue==="object"&&updateValue!==null){let keys=Object.keys(updateValue);if(keys.some((k)=>k.startsWith("$"))){for(let key of keys)if(key==="$inc"&&typeof item[field]==="number")item[field]+=updateValue[key];else if(key==="$push"){if(!Array.isArray(item[field]))item[field]=[];item[field].push(updateValue[key])}}else item[field]=stripDangerousKeys2(updateValue)}else item[field]=updateValue}if(item.updatedAt=new Date,this._versioning)item._version=(item._version??0)+1;return item}_prepareUpdatedDoc(currentDoc,update){let prev=structuredClone(currentDoc),next=structuredClone(currentDoc);if(this.applyUpdate(next,update),!this._schema)return next;let errors=validateDoc2(next,this._schema,this._strict);if(!errors.length)return next;switch(this._onSchemaError){case"throw":throw new ValidationError2("ERR_SKALEX_VALIDATION_UPDATE",`Update validation failed on doc "${currentDoc._id}": ${errors.join("; ")}`,{id:currentDoc._id,errors});case"strip":return this._stripCandidateToValid(next,prev);default:return this._ctx.logger(`[${this.name}] Update validation warning: ${errors.join("; ")}`,"warn"),next}}_stripCandidateToValid(next,prev){let stripped=stripInvalidFields2(next,this._schema),merged=structuredClone(prev);for(let[key,val]of Object.entries(stripped)){if(key.startsWith("_"))continue;merged[key]=val}if(merged.updatedAt=next.updatedAt,this._versioning)merged._version=next._version;return merged}_commitUpdatedDoc(oldDoc,newDoc,positions){let idx=positions?positions.get(oldDoc):this._data.indexOf(oldDoc);if(idx===void 0||idx===-1)throw new PersistenceError2("ERR_SKALEX_PERSISTENCE_DOC_MISSING",`Document "${oldDoc._id}" no longer exists in collection "${this.name}"`,{id:oldDoc._id,collection:this.name});this._data[idx]=newDoc,this._index.set(newDoc._id,newDoc),this._updateInIndex(oldDoc,newDoc)}_assertUniqueCandidates(oldDocs,nextDocs){this._fieldIndex?.assertUniqueCandidates(oldDocs,nextDocs)}async upsert(filter,doc,options={}){if(await this._ctx.ensureConnected(),this._findRaw(filter))return this.updateOne(filter,doc,options);return this.insertOne({...resolveFilterToValues2(filter),...doc},options)}async upsertMany(docs,matchKey,options={}){await this._ctx.ensureConnected();let{save,...rest}=options,results=[];for(let doc of docs)results.push(await this.upsert({[matchKey]:doc[matchKey]},doc,{...rest,save:!1}));return await this._saveIfNeeded(save),results}async restore(filter,options={}){if(!this._softDelete)throw new QueryError2("ERR_SKALEX_QUERY_SOFT_DELETE_REQUIRED",`restore() requires softDelete on "${this.name}"`,{collection:this.name});await this._ctx.ensureConnected();let{save,session}=options,item=this._findRaw(filter,{includeDeleted:!0});if(!item||!item._deletedAt)return null;let{docs}=await this._pipeline.execute({op:"restore",beforeHook:null,afterHook:null,hookPayload:null,save,session,mutate:async(assertTxAlive)=>{return assertTxAlive(),delete item._deletedAt,item.updatedAt=new Date,this._index.set(item._id,item),{docs:[item]}}});return stripVector2(docs[0])}watch(filter,callback){if(typeof filter==="function")callback=filter,filter=null;if(callback)return this._ctx.eventBus.on(this.name,(event)=>{if(!filter||matchesFilter2(event.doc,filter))callback(event)});return this._watchIterator(filter)}_watchIterator(filter){let queue=[],resolve=null,done=!1,unsub=this._ctx.eventBus.on(this.name,(event)=>{if(filter&&!matchesFilter2(event.doc,filter))return;if(resolve){let r=resolve;resolve=null,r({value:event,done:!1})}else queue.push(event)});return{[Symbol.asyncIterator](){return this},next(){if(queue.length>0)return Promise.resolve({value:queue.shift(),done:!1});if(done)return Promise.resolve({value:void 0,done:!0});return new Promise((res)=>{resolve=res})},return(){if(done=!0,unsub(),resolve){let r=resolve;resolve=null,r({value:void 0,done:!0})}return Promise.resolve({value:void 0,done:!0})}}}async count(filter={}){return await this._ctx.ensureConnected(),count2(this._findAllRaw(filter))}async sum(field,filter={}){return await this._ctx.ensureConnected(),sum2(this._findAllRaw(filter),field)}async avg(field,filter={}){return await this._ctx.ensureConnected(),avg2(this._findAllRaw(filter),field)}async groupBy(field,filter={}){return await this._ctx.ensureConnected(),groupBy2(this._findAllRaw(filter),field)}async findOne(filter,options={}){await this._ctx.ensureConnected();let{populate,select,includeDeleted=!1}=options,item=this._findRaw(filter,{includeDeleted});if(!item)return null;let newItem=this._projectDoc(item,select);if(populate)await this._populateDoc(newItem,item,populate);return newItem}async find(filter,options={}){await this._ctx.ensureConnected();let _t0=Date.now(),{populate,select,sort,page=1,limit,session,includeDeleted=!1}=options;await this._ctx.plugins.run("beforeFind",{collection:this.name,filter,options});let candidates=this._getCandidates(filter),sortedFilter=presortFilter2(filter,this._fieldIndex?this._fieldIndex.indexedFields:new Set),results=[];for(let item of candidates){if(this._softDelete&&item._deletedAt&&!includeDeleted)continue;if(!matchesFilter2(item,sortedFilter))continue;let newItem=this._projectDoc(item,select);if(populate)await this._populateDoc(newItem,item,populate);results.push(newItem)}if(sort){let sortFields=Object.keys(sort);results.sort((a,b)=>{for(let field of sortFields){let dir=sort[field];if(a[field]<b[field])return-dir;if(a[field]>b[field])return dir}return 0})}let extra;if(limit){let totalDocs=results.length,totalPages=Math.ceil(totalDocs/limit),startIndex=(page-1)*limit;results=results.slice(startIndex,startIndex+limit),extra={page,totalDocs,totalPages}}return this._ctx.queryLog?.record({collection:this.name,op:"find",filter,duration:Date.now()-_t0,resultCount:results.length}),this._ctx.sessionStats.recordRead(session),await this._ctx.plugins.run("afterFind",{collection:this.name,filter,options,docs:results}),extra?{docs:results,...extra}:{docs:results}}async search(query,{filter,limit=10,minScore=0,session}={}){await this._ctx.ensureConnected();let _t0=Date.now();await this._ctx.plugins.run("beforeSearch",{collection:this.name,query,options:{filter,limit,minScore}});let queryVector=await this._ctx.embed(query),candidates=filter?this._findAllRaw(filter):this._data,scored=[];for(let doc of candidates){if(!doc._vector)continue;let score=cosineSimilarity2(queryVector,doc._vector);if(score>=minScore)scored.push({doc,score})}scored.sort((a,b)=>b.score-a.score);let top=scored.slice(0,limit);this._ctx.queryLog?.record({collection:this.name,op:"search",query,duration:Date.now()-_t0,resultCount:top.length}),this._ctx.sessionStats.recordRead(session);let docs=top.map((r)=>stripVector2(r.doc)),scores=top.map((r)=>r.score);return await this._ctx.plugins.run("afterSearch",{collection:this.name,query,options:{filter,limit,minScore},docs,scores}),{docs,scores}}async similar(id,{limit=10,minScore=0}={}){await this._ctx.ensureConnected();let source=this._index.get(id);if(!source||!source._vector)return{docs:[],scores:[]};let scored=[];for(let doc of this._data){if(doc._id===id||!doc._vector)continue;let score=cosineSimilarity2(source._vector,doc._vector);if(score>=minScore)scored.push({doc,score})}scored.sort((a,b)=>b.score-a.score);let top=scored.slice(0,limit);return{docs:top.map((r)=>stripVector2(r.doc)),scores:top.map((r)=>r.score)}}async deleteOne(filter,options={}){await this._ctx.ensureConnected();let{save,session}=options;if(this._softDelete){let item=this._findRaw(filter);if(!item)return null;let{docs:docs2}=await this._deleteCore("soft",[item],filter,{save,session});return stripVector2(docs2[0])}let{docs}=await this._deleteCore("hard",null,filter,{save,session});if(docs.length===0)return null;return stripVector2(docs[0])}async deleteMany(filter,options={}){await this._ctx.ensureConnected();let{save,session}=options;if(this._softDelete){let items=this._findAllRaw(filter);if(items.length===0)return[];let{docs:docs2}=await this._deleteCore("soft",items,filter,{save,session});return docs2.map(stripVector2)}let{docs}=await this._deleteCore("hardMany",null,filter,{save,session});return docs.map(stripVector2)}async _deleteCore(mode,items,filter,{save,session}){return this._pipeline.execute({op:"delete",beforeHook:"beforeDelete",afterHook:"afterDelete",hookPayload:{collection:this.name,filter},save,session,afterHookPayload:(docs)=>({collection:this.name,filter,result:docs.length===1?docs[0]:docs}),mutate:async(assertTxAlive)=>{if(assertTxAlive(),mode==="soft"){let now=new Date;for(let item of items)item._deletedAt=now,item.updatedAt=now,this._index.set(item._id,item);return{docs:items}}if(mode==="hard"){let idx=this._findIndex(filter);if(idx===-1)return{docs:[]};let deletedItem=this._data.splice(idx,1)[0];return this._index.delete(deletedItem._id),this._removeFromIndex(deletedItem),{docs:[deletedItem]}}let deletedItems=[],remainingItems=[];for(let item of this._data)if(matchesFilter2(item,filter))deletedItems.push(item),this._index.delete(item._id),this._removeFromIndex(item);else remainingItems.push(item);return this._data=remainingItems,{docs:deletedItems}}})}async export(filter={},options={}){let{dir,name,format="json"}=options;try{let filteredData=this._data.filter((item)=>matchesFilter2(item,filter));if(filteredData.length===0)throw new QueryError2("ERR_SKALEX_QUERY_EXPORT_EMPTY",`export(): no documents matched the filter in "${this.name}"`,{collection:this.name});let content;if(format==="json")content=JSON.stringify(filteredData,null,2);else{let escapeCsv=(v)=>{if(v==null)return"";let s=typeof v==="object"?JSON.stringify(v):String(v);return s.includes(",")||s.includes('"')||s.includes(`
29
+ `))!==-1){let line=this._buffer.slice(0,idx).trim();if(this._buffer=this._buffer.slice(idx+1),line&&this._onMessage){let msg;try{msg=JSON.parse(line)}catch(_){this.send(error(null,PARSE_ERROR,"Parse error"));continue}this._onMessage(msg).catch(()=>{})}}}),process.stdin.on("end",()=>{process.exit(0)})}stop(){process.stdin.removeAllListeners("data"),process.stdin.removeAllListeners("end"),this._started=!1}}var SERVER_INFO={name:"skalex",version:"4.0.0-alpha"},PROTOCOL_VERSION="2024-11-05";class SkalexMCPServer{constructor(db,opts={}){this._db=db,this._transport=opts.transport||"stdio",this._port=opts.port||3000,this._host=opts.host||"127.0.0.1",this._allowedOrigin=opts.allowedOrigin??null,this._maxBodySize=opts.maxBodySize??1048576,this._scopes=opts.scopes||{"*":["read"]},this._t=null}async listen(){if(this._transport==="http")this._t=new HttpTransport({port:this._port,host:this._host,allowedOrigin:this._allowedOrigin,maxBodySize:this._maxBodySize});else this._t=new StdioTransport;this._t.onMessage((msg)=>this._handleMessage(msg)),await this._t.start()}async connect(transport){if(this._t=transport,this._t.onMessage((msg)=>this._handleMessage(msg)),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(raw){let{msg,parseError}=typeof raw==="string"?parse(raw):{msg:raw};if(parseError){this._send(parseError);return}let{id,method,params}=msg;if(id===void 0){if(method==="notifications/initialized")return;return}try{switch(method){case"initialize":this._send(ok(id,{protocolVersion:PROTOCOL_VERSION,capabilities:{tools:{}},serverInfo:SERVER_INFO}));break;case"tools/list":this._send(ok(id,{tools:this._visibleTools()}));break;case"tools/call":await this._handleToolCall(id,params);break;case"ping":this._send(ok(id,{}));break;default:this._send(error(id,METHOD_NOT_FOUND,`Method not found: ${method}`))}}catch(err){this._send(error(id,INTERNAL_ERROR,err.message||"Internal error"))}}async _handleToolCall(id,params){let name=params?.name,args=params?.arguments??{};if(!name){this._send(error(id,INVALID_PARAMS,"tools/call requires params.name"));return}let def=TOOL_DEFS.find((t)=>t.name===name);if(!def){this._send(error(id,METHOD_NOT_FOUND,`Unknown tool: ${name}`));return}let collection=args.collection||args.collection_name||null;if(!this._hasScope(collection,def.scope)){this._send(ok(id,toolError(`Access denied: "${name}" requires "${def.scope}" scope on collection "${collection}".`)));return}try{let result=await callTool(name,args,this._db);this._send(ok(id,toolResult(JSON.stringify(result,null,2))))}catch(err){this._send(ok(id,toolError(err.message||String(err))))}}_visibleTools(){return TOOL_DEFS.filter((def)=>{let global=this._scopes["*"];if(global&&(global.includes(def.scope)||global.includes("admin")))return!0;for(let[,perms]of Object.entries(this._scopes))if(perms.includes(def.scope)||perms.includes("admin"))return!0;return!1})}_hasScope(collection,scope){let check=(perms)=>perms.includes("admin")||perms.includes(scope);if(collection&&this._scopes[collection])return check(this._scopes[collection]);if(this._scopes["*"])return check(this._scopes["*"]);return!1}_send(msg){this._t?.send(msg)}}var META_KEY="migrations",_serialize=(value)=>JSON.stringify(value,function(key,v){let raw=this[key];if(raw instanceof Date)return{__skalex_date__:raw.toISOString()};if(typeof v==="bigint")return{__skalex_bigint__:v.toString()};return v}),_deserialize=(text)=>JSON.parse(text,(_,v)=>{if(v&&typeof v==="object"){if("__skalex_bigint__"in v)return BigInt(v.__skalex_bigint__);if("__skalex_date__"in v)return new Date(v.__skalex_date__)}return v});class Skalex{constructor({path="./.db",format="gz",debug=!1,adapter,ai,encrypt,slowQueryLog,queryCache,memory,logger:logger$1,plugins,llmAdapter,embeddingAdapter,regexMaxLength,idGenerator,serializer,deserializer,autoSave,ttlSweepInterval,lenientLoad}={}){if(this.dataDirectory=path,this.dataFormat=format,this.debug=debug,!Skalex._errorsAttached)Skalex.SkalexError=SkalexError,Skalex.ValidationError=ValidationError,Skalex.UniqueConstraintError=UniqueConstraintError,Skalex.TransactionError=TransactionError,Skalex.PersistenceError=PersistenceError,Skalex.AdapterError=AdapterError,Skalex.QueryError=QueryError,Skalex._errorsAttached=!0;this._adapterConfig=adapter??null;let fs=adapter||new FsAdapter({dir:path,format});if(encrypt)fs=new EncryptedAdapter(fs,encrypt.key);if(this.fs=fs,this._registry=new CollectionRegistry(Collection),this.collections=this._registry.stores,this._collectionInstances=this._registry._instances,this._migrations=new MigrationEngine,this._connectPromise=null,this.isConnected=!1,this._aiConfig=ai||null,this._encryptConfig=encrypt||null,this._pluginsConfig=Array.isArray(plugins)?plugins:null,this._memoryConfig=memory||null,this._regexMaxLength=regexMaxLength??500,this._idGenerator=idGenerator??null,this._serializer=serializer??_serialize,this._deserializer=deserializer??_deserialize,this._autoSave=autoSave??!1,this._txManager=new TransactionManager,this._ttlSweepInterval=ttlSweepInterval??0,this._ttlTimer=null,this._logger=logger$1??logger,this._embeddingAdapter=embeddingAdapter??(ai?createEmbeddingAdapter(ai):null),this._aiAdapter=llmAdapter??(ai?createLLMAdapter(ai):null),this._persistence=new PersistenceManager({adapter:this.fs,serializer:this._serializer,deserializer:this._deserializer,logger:this._logger,debug:this.debug,lenientLoad:lenientLoad??!1}),this._changeLog=new ChangeLog(this),this._queryCache=new QueryCache(queryCache||{}),this._eventBus=new EventBus,this._queryLog=slowQueryLog?new QueryLog(slowQueryLog):null,this._sessionStats=new SessionStats,this._plugins=new PluginEngine,Array.isArray(plugins))for(let p of plugins)this._plugins.register(p)}async connect(){if(this._connectPromise)return this._connectPromise;return this._connectPromise=this._doConnect(),this._connectPromise}async _doConnect(){try{await this.loadData();let meta=this._getMeta();if(meta.queryCache)this._queryCache.fromJSON(meta.queryCache);if(this._migrations._migrations.length>0){let applied=meta.appliedVersions||[],newApplied=await this._migrations.run((version)=>this.useCollection(`_migration_${version}`),applied);this._saveMeta({appliedVersions:newApplied})}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(error2){throw this._logger(`Error connecting to the database: ${error2}`,"error"),error2}}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(error2){throw this._logger(`Error disconnecting from the database: ${error2}`,"error"),error2}}async _ensureConnected(){if(this.isConnected)return;return this.connect()}useCollection(collectionName){return this._registry.get(collectionName,this)}createCollection(collectionName,options={}){return this._registry.create(collectionName,options,this)}_createCollectionStore(collectionName,options={}){this._registry.createStore(collectionName,options)}async renameCollection(from,to){this._registry.rename(from,to),await this.saveData(to),await this.fs.delete(from)}async loadData(){await this._persistence.loadAll(this.collections,{parseSchema,buildIndex:this._registry.buildIndex,IndexEngine});for(let name in this._collectionInstances){let store=this.collections[name];if(store&&this._collectionInstances[name]._store!==store)this._collectionInstances[name]._store=store}}async saveData(collectionName){await this._persistence.save(this.collections,collectionName)}buildIndex(data,keyField){return this._registry.buildIndex(data,keyField)}addMigration(migration){this._migrations.add(migration)}migrationStatus(){let meta=this._getMeta();return this._migrations.status(meta.appliedVersions||[])}namespace(id){if(this._adapterConfig)throw new AdapterError("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 safeId=String(id).replace(/[^a-zA-Z0-9_-]/g,"_");if(!safeId)throw new ValidationError("ERR_SKALEX_VALIDATION_NAMESPACE_ID","namespace: id must contain at least one alphanumeric character",{id});return new Skalex({path:`${this.dataDirectory}/${safeId}`,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!==logger?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!==_serialize?this._serializer:void 0,deserializer:this._deserializer!==_deserialize?this._deserializer:void 0,autoSave:this._autoSave||void 0,ttlSweepInterval:this._ttlSweepInterval||void 0})}use(plugin){this._plugins.register(plugin)}watch(callback){return this._eventBus.on("*",callback)}sessionStats(sessionId){if(sessionId!==void 0)return this._sessionStats.get(sessionId);return this._sessionStats.all()}get _inTransaction(){return this._txManager.active}_emitEvent(collectionName,data){if(!this._txManager.defer(()=>this._eventBus.emit(collectionName,data)))this._eventBus.emit(collectionName,data)}async _runAfterHook(hook,data){if(!this._txManager.defer(()=>this._plugins.run(hook,data)))await this._plugins.run(hook,data)}async _logChange(op,collectionName,doc,prev,session){if(!this._txManager.defer(()=>this._changeLog.log(op,collectionName,doc,prev,session)))await this._changeLog.log(op,collectionName,doc,prev,session)}async transaction(fn,opts={}){return this._txManager.run(fn,this,opts)}async seed(fixtures,{reset=!1}={}){for(let[name,docs]of Object.entries(fixtures)){if(reset&&this.collections[name])this._applySnapshot(name,{data:[],index:new Map}),delete this._collectionInstances[name];await this.useCollection(name).insertMany(docs)}await this.saveData()}dump(){return this._registry.dump()}inspect(collectionName){return this._registry.inspect(collectionName)}async import(filePath){let content=await this.fs.readRaw(filePath),docs;try{docs=JSON.parse(content)}catch{throw new PersistenceError("ERR_SKALEX_PERSISTENCE_INVALID_JSON",`import: invalid JSON in file "${filePath}"`,{filePath})}let name=filePath.split("/").pop().replace(/\.[^.]+$/,"");return this.useCollection(name).insertMany(Array.isArray(docs)?docs:[docs],{save:!0})}async embed(text){if(!this._embeddingAdapter)throw new AdapterError("ERR_SKALEX_ADAPTER_EMBEDDING_REQUIRED","db.embed() requires an AI adapter. Pass { ai: { provider, apiKey } } to the Skalex constructor.");return this._embeddingAdapter.embed(text)}async ask(collectionName,nlQuery,{limit=20}={}){if(!this._aiAdapter)throw new AdapterError("ERR_SKALEX_ADAPTER_LLM_REQUIRED",'db.ask() requires a language model adapter. Configure { ai: { provider, model: "..." } }.');let col=this.useCollection(collectionName),schema=this.schema(collectionName),filter=this._queryCache.get(collectionName,schema,nlQuery);if(!filter){filter=await this._aiAdapter.generate(schema,nlQuery);let warnings=validateLLMFilter(filter,schema);if(warnings.length)warnings.forEach((w)=>this._log(`[ask] ${w}`));this._queryCache.set(collectionName,schema,nlQuery,filter),this._saveMeta({queryCache:this._queryCache.toJSON()})}return col.find(processLLMFilter(filter,{regexMaxLength:this._regexMaxLength}),{limit})}schema(collectionName){return this._registry.schema(collectionName)}useMemory(sessionId){return new Memory(sessionId,this)}changelog(){return this._changeLog}async restore(collectionName,timestamp,opts={}){return this._changeLog.restore(collectionName,timestamp,opts)}stats(collectionName){return this._registry.stats(collectionName)}slowQueries(opts={}){if(!this._queryLog)return[];return this._queryLog.entries(opts)}slowQueryCount(){return this._queryLog?this._queryLog.size:0}clearSlowQueries(){this._queryLog?.clear()}mcp(opts={}){return new SkalexMCPServer(this,opts)}_getMeta(){let metaCol=this.collections._meta;if(!metaCol)return{};return metaCol.index.get(META_KEY)||{}}_saveMeta(data){if(!this.collections._meta)this._createCollectionStore("_meta");let col=this.collections._meta,existing=col.index.get(META_KEY);if(existing)Object.assign(existing,data);else{let doc={_id:META_KEY,...data};col.data.push(doc),col.index.set(META_KEY,doc)}this._persistence.markDirty(this.collections,"_meta")}_sweepTtl(){for(let name in this.collections){let col=this.collections[name],removed=sweep(col.data,col.index,col.fieldIndex?(doc)=>col.fieldIndex.remove(doc):null);if(removed>0)this._persistence.markDirty(this.collections,name),this._log(`TTL sweep: removed ${removed} expired docs from "${name}"`)}}_buildCollectionContext(){let db=this;return{ensureConnected:()=>db._ensureConnected(),get txManager(){return db._txManager},get plugins(){return db._plugins},get eventBus(){return db._eventBus},get sessionStats(){return db._sessionStats},get queryLog(){return db._queryLog},get logger(){return db._logger},get persistence(){return db._persistence},get collections(){return db.collections},embed:(text)=>db.embed(text),get idGenerator(){return db._idGenerator},get autoSave(){return db._autoSave},saveCollection:(name)=>db.saveData(name),snapshotCollection:(col)=>db._snapshotCollection(col),getCollection:(name)=>db.useCollection(name),emitEvent:(name,data)=>db._emitEvent(name,data),runAfterHook:(hook,data)=>db._runAfterHook(hook,data),logChange:(op,col,doc,prev,session)=>db._logChange(op,col,doc,prev,session),get fs(){return db.fs},get dataDirectory(){return db.dataDirectory}}}_log(msg){if(this.debug)this._logger(msg,"info")}_snapshotCollection(col){return{data:structuredClone(col.data)}}_applySnapshot(name,snap){let col=this.collections[name];if(!col)return;if(col.data=snap.data,col.index=this.buildIndex(snap.data,"_id"),col.fieldIndex)col.fieldIndex.buildFromData(snap.data)}}function generateUniqueId2(){let timestamp=Date.now().toString(16),random;try{random=nodeCrypto2.randomBytes(8).toString("hex")}catch{let arr=new Uint8Array(8);crypto.getRandomValues(arr),random=Array.from(arr).map((b)=>b.toString(16).padStart(2,"0")).join("")}return`${timestamp}${random}`}function logger2(error2,type){let msg=error2 instanceof Error?error2.message:error2;if(type==="error")console.error(msg);else console.log(msg)}var _FORBIDDEN_KEYS2=new Set(["__proto__","constructor","prototype"]);function resolveDotPath2(obj,path){if(!path.includes(".")){if(_FORBIDDEN_KEYS2.has(path))return;return obj[path]}let cur=obj;for(let p of path.split(".")){if(_FORBIDDEN_KEYS2.has(p))return;if(cur==null)return;cur=cur[p]}return cur}class SkalexError2 extends Error{constructor(code,message,details={}){super(message);this.name=this.constructor.name,this.code=code,this.details=details}}class ValidationError2 extends SkalexError2{}class UniqueConstraintError2 extends SkalexError2{}class TransactionError2 extends SkalexError2{}class PersistenceError2 extends SkalexError2{}class AdapterError2 extends SkalexError2{}class QueryError2 extends SkalexError2{}function deepEqual2(a,b){if(a===b)return!0;if(a==null||b==null)return!1;if(typeof a!==typeof b)return!1;if(a instanceof Date&&b instanceof Date)return a.getTime()===b.getTime();if(a instanceof RegExp&&b instanceof RegExp)return a.source===b.source&&a.flags===b.flags;if(Array.isArray(a)){if(!Array.isArray(b)||a.length!==b.length)return!1;for(let i=0;i<a.length;i++)if(!deepEqual2(a[i],b[i]))return!1;return!0}if(typeof a==="object"){if(Array.isArray(b))return!1;let keysA=Object.keys(a);if(keysA.length!==Object.keys(b).length)return!1;for(let k of keysA){if(!Object.prototype.hasOwnProperty.call(b,k))return!1;if(!deepEqual2(a[k],b[k]))return!1}return!0}return!1}function matchesFilter2(item,filter){if(typeof filter==="function")return filter(item);if(filter==null)return!0;if(typeof filter==="object"&&Object.keys(filter).length===0)return!0;if("$or"in filter){let branches=filter.$or;if(!Array.isArray(branches))throw new QueryError2("ERR_SKALEX_QUERY_INVALID_OPERATOR","$or must be an array of filters",{operator:"$or"});if(!branches.some((sub)=>matchesFilter2(item,sub)))return!1}if("$and"in filter){let branches=filter.$and;if(!Array.isArray(branches))throw new QueryError2("ERR_SKALEX_QUERY_INVALID_OPERATOR","$and must be an array of filters",{operator:"$and"});if(!branches.every((sub)=>matchesFilter2(item,sub)))return!1}if("$not"in filter){if(matchesFilter2(item,filter.$not))return!1}for(let key in filter){if(key==="$or"||key==="$and"||key==="$not")continue;let filterValue=filter[key],itemValue;try{itemValue=resolveDotPath2(item,key)}catch{return!1}if(filterValue instanceof RegExp){if(!filterValue.test(String(itemValue)))return!1}else if(typeof filterValue==="object"&&filterValue!==null){if(Object.keys(filterValue).some((k)=>k.startsWith("$"))){if("$eq"in filterValue&&itemValue!==filterValue.$eq)return!1;if("$ne"in filterValue&&itemValue===filterValue.$ne)return!1;if("$gt"in filterValue&&!(itemValue>filterValue.$gt))return!1;if("$lt"in filterValue&&!(itemValue<filterValue.$lt))return!1;if("$gte"in filterValue&&!(itemValue>=filterValue.$gte))return!1;if("$lte"in filterValue&&!(itemValue<=filterValue.$lte))return!1;if("$in"in filterValue&&!filterValue.$in.includes(itemValue))return!1;if("$nin"in filterValue&&filterValue.$nin.includes(itemValue))return!1;if("$regex"in filterValue){if(!(filterValue.$regex instanceof RegExp?filterValue.$regex:new RegExp(filterValue.$regex)).test(String(itemValue)))return!1}if("$fn"in filterValue&&!filterValue.$fn(itemValue))return!1}else if(!deepEqual2(itemValue,filterValue))return!1}else if(itemValue!==filterValue)return!1}return!0}function presortFilter2(filter,indexedFields=new Set){if(typeof filter!=="object"||filter===null||typeof filter==="function")return filter;let indexed=[],equality=[],range=[],expensive=[],logical=[];for(let key in filter){if(key==="$or"||key==="$and"||key==="$not"){logical.push(key);continue}let val=filter[key];if(indexedFields.has(key))indexed.push(key);else if(val instanceof RegExp||typeof val==="object"&&val!==null&&(("$regex"in val)||("$fn"in val))||typeof val==="function")expensive.push(key);else if(typeof val==="object"&&val!==null&&(("$gt"in val)||("$lt"in val)||("$gte"in val)||("$lte"in val)||("$ne"in val)||("$in"in val)||("$nin"in val)))range.push(key);else equality.push(key)}let sorted={};for(let k of[...indexed,...equality,...range,...expensive,...logical])sorted[k]=filter[k];return sorted}var SUPPORTED_TYPES2=new Set(["string","number","boolean","object","array","date","any"]);function typeOf2(val){if(Array.isArray(val))return"array";if(val instanceof Date)return"date";return typeof val}function parseSchema2(schema){let fields=new Map,uniqueFields=[];for(let[key,def]of Object.entries(schema)){let fieldDef;if(typeof def==="string"){if(!SUPPORTED_TYPES2.has(def))throw new ValidationError2("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${def}" for field "${key}"`,{field:key,type:def});fieldDef={type:def,required:!1,unique:!1}}else if(typeof def==="object"&&def!==null){let{type="any",required=!1,unique=!1,enum:enumVals}=def;if(!SUPPORTED_TYPES2.has(type))throw new ValidationError2("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${type}" for field "${key}"`,{field:key,type});if(fieldDef={type,required,unique,enum:enumVals},unique)uniqueFields.push(key)}else throw new ValidationError2("ERR_SKALEX_VALIDATION_INVALID_SCHEMA",`Invalid schema definition for field "${key}"`,{field:key});fields.set(key,fieldDef)}return{fields,uniqueFields}}function validateDoc2(doc,fields,strict=!1){let errors=[];for(let[key,def]of fields){let val=doc[key],missing=val===void 0||val===null;if(def.required&&missing){errors.push(`Field "${key}" is required`);continue}if(missing)continue;if(def.type!=="any"){let actualType=typeOf2(val);if(actualType!==def.type)errors.push(`Field "${key}" must be of type "${def.type}", got "${actualType}"`)}if(def.enum&&!def.enum.includes(val))errors.push(`Field "${key}" must be one of [${def.enum.map((v)=>JSON.stringify(v)).join(", ")}], got ${JSON.stringify(val)}`)}if(strict){for(let key of Object.keys(doc))if(!key.startsWith("_")&&!fields.has(key))errors.push(`Unknown field "${key}" (strict mode)`)}return errors}function stripInvalidFields2(doc,fields){let out={};for(let[key,val]of Object.entries(doc)){if(key.startsWith("_")){out[key]=val;continue}if(!fields.has(key))continue;let def=fields.get(key);if(def.type!=="any"){if(typeOf2(val)!==def.type)continue}if(def.enum&&!def.enum.includes(val))continue;out[key]=val}return out}function inferSchema2(doc){let schema={};for(let[key,val]of Object.entries(doc)){if(key.startsWith("_"))continue;let t=typeOf2(val);schema[key]=SUPPORTED_TYPES2.has(t)?t:"any"}return schema}function parseTtl2(ttl){if(typeof ttl==="number"){if(ttl<=0)throw new ValidationError2("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got ${ttl}`,{ttl});return ttl*1000}if(typeof ttl!=="string")throw new ValidationError2("ERR_SKALEX_VALIDATION_TTL",`Invalid TTL value: ${ttl}`,{ttl});let match=ttl.match(/^(\d+(?:\.\d+)?)(ms|s|m|h|d)$/);if(!match)throw new ValidationError2("ERR_SKALEX_VALIDATION_TTL_FORMAT",`Invalid TTL format: "${ttl}". Use e.g. 300 (seconds), "30m", "24h", "7d"`,{ttl});let val=parseFloat(match[1]);if(val<=0)throw new ValidationError2("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got "${ttl}"`,{ttl});let unit=match[2],ms=val*{ms:1,s:1000,m:60000,h:3600000,d:86400000}[unit];if(!isFinite(ms))throw new ValidationError2("ERR_SKALEX_VALIDATION_TTL",`TTL value "${ttl}" is too large`,{ttl});return ms}function computeExpiry2(ttl){return new Date(Date.now()+parseTtl2(ttl))}function sweep2(data,idIndex,removeFromIndexes=null){let now=Date.now(),removed=0,i=data.length;while(i--){let doc=data[i];if(doc._expiresAt&&new Date(doc._expiresAt).getTime()<=now){if(data.splice(i,1),idIndex.delete(doc._id),removeFromIndexes)removeFromIndexes(doc);removed++}}return removed}function cosineSimilarity2(a,b){if(a.length!==b.length)throw new QueryError2("ERR_SKALEX_QUERY_VECTOR_MISMATCH",`Vector dimension mismatch: ${a.length} vs ${b.length}`,{expected:a.length,got:b.length});let dot=0,magA=0,magB=0;for(let i=0;i<a.length;i++)dot+=a[i]*b[i],magA+=a[i]*a[i],magB+=b[i]*b[i];let denom=Math.sqrt(magA*magB);return denom===0?0:dot/denom}function stripVector2(doc){if(!("_vector"in doc))return{...doc};let{_vector,...rest}=doc;return rest}function count2(docs){return docs.length}function sum2(docs,field){let total=0;for(let doc of docs){let val=resolveDotPath2(doc,field);if(typeof val==="number"&&!isNaN(val))total+=val}return total}function avg2(docs,field){let total=0,n=0;for(let doc of docs){let val=resolveDotPath2(doc,field);if(typeof val==="number"&&!isNaN(val))total+=val,n++}return n===0?null:total/n}function groupBy2(docs,field){let groups=Object.create(null);for(let doc of docs){let key=String(resolveDotPath2(doc,field)??"__null__");if(!groups[key])groups[key]=[];groups[key].push(doc)}return groups}class MutationPipeline2{constructor(collection){this._col=collection}get _ctx(){return this._col._ctx}async execute({op,beforeHook,afterHook,hookPayload,mutate,afterHookPayload,save,session}){let ctx=this._ctx;await ctx.ensureConnected(),this._col._txSnapshotIfNeeded();let txm=ctx.txManager,isTxWrite=txm.active&&this._col._activeTxId===txm.context?.id,entryTxId=isTxWrite?txm.context.id:null,collTxId=this._col._createdInTxId,assertTxAlive=()=>{if(entryTxId!==null&&txm._abortedIds.has(entryTxId))throw new TransactionError2("ERR_SKALEX_TX_ABORTED",`Transaction ${entryTxId} was aborted. No further mutations allowed.`);if(collTxId!==null&&txm._abortedIds.has(collTxId))throw new TransactionError2("ERR_SKALEX_TX_ABORTED",`Transaction ${collTxId} was aborted. Collection obtained inside that transaction cannot be used for further mutations.`)};if(isTxWrite||collTxId!==null)assertTxAlive();if(beforeHook)await ctx.plugins.run(beforeHook,hookPayload);let{docs,prevDocs=[]}=await mutate(assertTxAlive);if(ctx.persistence.markDirty(ctx.collections,this._col.name),await this._col._saveIfNeeded(save),this._col._changelogEnabled)for(let i=0;i<docs.length;i++)await ctx.logChange(op,this._col.name,docs[i],prevDocs[i]??null,session||null);if(!isTxWrite||!txm.defer(()=>ctx.sessionStats.recordWrite(session)))ctx.sessionStats.recordWrite(session);for(let doc of docs)ctx.emitEvent(this._col.name,{op,collection:this._col.name,doc:stripVector2(doc)});if(afterHook)if(afterHookPayload)await ctx.runAfterHook(afterHook,afterHookPayload(docs));else for(let doc of docs)await ctx.runAfterHook(afterHook,{collection:this._col.name,doc:stripVector2(doc)});return{docs,prevDocs}}}function resolveFilterToValues2(filter){let resolved={};for(let key in filter){if(key.startsWith("$"))continue;let val=filter[key];if(val&&typeof val==="object"&&!Array.isArray(val)){let keys=Object.keys(val);if(keys.length===1&&keys[0]==="$eq")resolved[key]=val.$eq}else resolved[key]=val}return resolved}var _DANGEROUS_KEYS2=new Set(["__proto__","constructor","prototype"]);function stripDangerousKeys2(val){if(typeof val!=="object"||val===null||Array.isArray(val))return val;let out={};for(let k of Object.keys(val)){if(_DANGEROUS_KEYS2.has(k))continue;out[k]=stripDangerousKeys2(val[k])}return out}class Collection2{constructor(collectionData,database){this.name=collectionData.collectionName,this.database=database,this._ctx=database._buildCollectionContext(),this._store=collectionData,this._pipeline=new MutationPipeline2(this),this._createdInTxId=database._txManager.context?.id??null,this._activeTxId=null}get _data(){return this._store.data}set _data(val){this._store.data=val}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(item,options={}){let{save,ifNotExists,ttl,embed,session}=options;if(ifNotExists){await this._ctx.ensureConnected();let existing=this._findRaw(item);if(existing)return stripVector2({...existing})}let{docs}=await this._insertCore([item],{ttl,embed,session,save});return stripVector2(docs[0])}async insertMany(items,options={}){let{save,ttl,embed,session}=options,{docs}=await this._insertCore(items,{ttl,embed,session,save});return docs.map(stripVector2)}async _insertCore(items,{ttl,embed,session,save}){return this._pipeline.execute({op:"insert",beforeHook:null,afterHook:"afterInsert",hookPayload:null,save,session,mutate:async(assertTxAlive)=>{let newItems=[],batchIds=new Set;for(let item of items){let validated=this._applyValidation(item);await this._ctx.plugins.run("beforeInsert",{collection:this.name,doc:validated});let newItem=await this._buildDoc(validated,{ttl,embed});if(this._index.has(newItem._id)||batchIds.has(newItem._id))throw new UniqueConstraintError2("ERR_SKALEX_UNIQUE_DUPLICATE_ID",`Duplicate _id "${newItem._id}" in collection "${this.name}"`,{id:newItem._id,collection:this.name});batchIds.add(newItem._id),newItems.push(newItem)}if(assertTxAlive(),this._fieldIndex)this._fieldIndex.assertUniqueBatch(newItems);for(let newItem of newItems)this._addToIndex(newItem);this._data.push(...newItems);for(let newItem of newItems)this._index.set(newItem._id,newItem);return this._enforceCapAfterInsert(),{docs:newItems}}})}async updateOne(filter,update,options={}){await this._ctx.ensureConnected();let oldDoc=this._findRaw(filter);if(!oldDoc)return null;let{save,session}=options,{docs}=await this._updateCore([oldDoc],filter,update,{save,session});return stripVector2(docs[0])}async updateMany(filter,update,options={}){await this._ctx.ensureConnected();let oldDocs=this._findAllRaw(filter);if(oldDocs.length===0)return[];let{save,session}=options,{docs}=await this._updateCore(oldDocs,filter,update,{save,session});return docs.map(stripVector2)}async _updateCore(oldDocs,filter,update,{save,session}){return this._pipeline.execute({op:"update",beforeHook:"beforeUpdate",afterHook:"afterUpdate",hookPayload:{collection:this.name,filter,update},save,session,afterHookPayload:(docs)=>({collection:this.name,filter,update,result:docs.length===1?docs[0]:docs}),mutate:async(assertTxAlive)=>{let prevDocs=this._changelogEnabled?oldDocs.map((doc)=>structuredClone(doc)):oldDocs.map(()=>null),nextDocs=oldDocs.map((doc)=>this._prepareUpdatedDoc(doc,update));this._assertUniqueCandidates(oldDocs,nextDocs),assertTxAlive();let targets=new Set(oldDocs),positions=new Map;for(let i=0;i<this._data.length;i++)if(targets.has(this._data[i]))positions.set(this._data[i],i);for(let i=0;i<oldDocs.length;i++)this._commitUpdatedDoc(oldDocs[i],nextDocs[i],positions);return{docs:nextDocs,prevDocs}}})}applyUpdate(item,update){for(let field in update){if(_DANGEROUS_KEYS2.has(field))continue;if(field==="_id"||field==="createdAt")continue;let updateValue=update[field];if(Array.isArray(updateValue))item[field]=updateValue;else if(typeof updateValue==="object"&&updateValue!==null){let keys=Object.keys(updateValue);if(keys.some((k)=>k.startsWith("$"))){for(let key of keys)if(key==="$inc"&&typeof item[field]==="number")item[field]+=updateValue[key];else if(key==="$push"){if(!Array.isArray(item[field]))item[field]=[];item[field].push(updateValue[key])}}else item[field]=stripDangerousKeys2(updateValue)}else item[field]=updateValue}if(item.updatedAt=new Date,this._versioning)item._version=(item._version??0)+1;return item}_prepareUpdatedDoc(currentDoc,update){let prev=structuredClone(currentDoc),next=structuredClone(currentDoc);if(this.applyUpdate(next,update),!this._schema)return next;let errors=validateDoc2(next,this._schema,this._strict);if(!errors.length)return next;switch(this._onSchemaError){case"throw":throw new ValidationError2("ERR_SKALEX_VALIDATION_UPDATE",`Update validation failed on doc "${currentDoc._id}": ${errors.join("; ")}`,{id:currentDoc._id,errors});case"strip":return this._stripCandidateToValid(next,prev);default:return this._ctx.logger(`[${this.name}] Update validation warning: ${errors.join("; ")}`,"warn"),next}}_stripCandidateToValid(next,prev){let stripped=stripInvalidFields2(next,this._schema),merged=structuredClone(prev);for(let[key,val]of Object.entries(stripped)){if(key.startsWith("_"))continue;merged[key]=val}if(merged.updatedAt=next.updatedAt,this._versioning)merged._version=next._version;return merged}_commitUpdatedDoc(oldDoc,newDoc,positions){let idx=positions?positions.get(oldDoc):this._data.indexOf(oldDoc);if(idx===void 0||idx===-1)throw new PersistenceError2("ERR_SKALEX_PERSISTENCE_DOC_MISSING",`Document "${oldDoc._id}" no longer exists in collection "${this.name}"`,{id:oldDoc._id,collection:this.name});this._data[idx]=newDoc,this._index.set(newDoc._id,newDoc),this._updateInIndex(oldDoc,newDoc)}_assertUniqueCandidates(oldDocs,nextDocs){this._fieldIndex?.assertUniqueCandidates(oldDocs,nextDocs)}async upsert(filter,doc,options={}){if(await this._ctx.ensureConnected(),this._findRaw(filter))return this.updateOne(filter,doc,options);return this.insertOne({...resolveFilterToValues2(filter),...doc},options)}async upsertMany(docs,matchKey,options={}){await this._ctx.ensureConnected();let{save,...rest}=options,results=[];for(let doc of docs)results.push(await this.upsert({[matchKey]:doc[matchKey]},doc,{...rest,save:!1}));return await this._saveIfNeeded(save),results}async restore(filter,options={}){if(!this._softDelete)throw new QueryError2("ERR_SKALEX_QUERY_SOFT_DELETE_REQUIRED",`restore() requires softDelete on "${this.name}"`,{collection:this.name});await this._ctx.ensureConnected();let{save,session}=options,item=this._findRaw(filter,{includeDeleted:!0});if(!item||!item._deletedAt)return null;let{docs}=await this._pipeline.execute({op:"restore",beforeHook:null,afterHook:null,hookPayload:null,save,session,mutate:async(assertTxAlive)=>(assertTxAlive(),delete item._deletedAt,item.updatedAt=new Date,this._index.set(item._id,item),{docs:[item]})});return stripVector2(docs[0])}watch(filter,callback){if(typeof filter==="function")callback=filter,filter=null;if(callback)return this._ctx.eventBus.on(this.name,(event)=>{if(!filter||matchesFilter2(event.doc,filter))callback(event)});return this._watchIterator(filter)}_watchIterator(filter){let queue=[],resolve=null,done=!1,unsub=this._ctx.eventBus.on(this.name,(event)=>{if(filter&&!matchesFilter2(event.doc,filter))return;if(resolve){let r=resolve;resolve=null,r({value:event,done:!1})}else queue.push(event)});return{[Symbol.asyncIterator](){return this},next(){if(queue.length>0)return Promise.resolve({value:queue.shift(),done:!1});if(done)return Promise.resolve({value:void 0,done:!0});return new Promise((res)=>{resolve=res})},return(){if(done=!0,unsub(),resolve){let r=resolve;resolve=null,r({value:void 0,done:!0})}return Promise.resolve({value:void 0,done:!0})}}}async count(filter={}){return await this._ctx.ensureConnected(),count2(this._findAllRaw(filter))}async sum(field,filter={}){return await this._ctx.ensureConnected(),sum2(this._findAllRaw(filter),field)}async avg(field,filter={}){return await this._ctx.ensureConnected(),avg2(this._findAllRaw(filter),field)}async groupBy(field,filter={}){return await this._ctx.ensureConnected(),groupBy2(this._findAllRaw(filter),field)}async findOne(filter,options={}){await this._ctx.ensureConnected();let{populate,select,includeDeleted=!1}=options,item=this._findRaw(filter,{includeDeleted});if(!item)return null;let newItem=this._projectDoc(item,select);if(populate)await this._populateDoc(newItem,item,populate);return newItem}async find(filter,options={}){await this._ctx.ensureConnected();let _t0=Date.now(),{populate,select,sort,page=1,limit,session,includeDeleted=!1}=options;await this._ctx.plugins.run("beforeFind",{collection:this.name,filter,options});let candidates=this._getCandidates(filter),sortedFilter=presortFilter2(filter,this._fieldIndex?this._fieldIndex.indexedFields:new Set),results=[];for(let item of candidates){if(this._softDelete&&item._deletedAt&&!includeDeleted)continue;if(!matchesFilter2(item,sortedFilter))continue;let newItem=this._projectDoc(item,select);if(populate)await this._populateDoc(newItem,item,populate);results.push(newItem)}if(sort){let sortFields=Object.keys(sort);results.sort((a,b)=>{for(let field of sortFields){let dir=sort[field];if(a[field]<b[field])return-dir;if(a[field]>b[field])return dir}return 0})}let extra;if(limit){let totalDocs=results.length,totalPages=Math.ceil(totalDocs/limit),startIndex=(page-1)*limit;results=results.slice(startIndex,startIndex+limit),extra={page,totalDocs,totalPages}}return this._ctx.queryLog?.record({collection:this.name,op:"find",filter,duration:Date.now()-_t0,resultCount:results.length}),this._ctx.sessionStats.recordRead(session),await this._ctx.plugins.run("afterFind",{collection:this.name,filter,options,docs:results}),extra?{docs:results,...extra}:{docs:results}}async search(query,{filter,limit=10,minScore=0,session}={}){await this._ctx.ensureConnected();let _t0=Date.now();await this._ctx.plugins.run("beforeSearch",{collection:this.name,query,options:{filter,limit,minScore}});let queryVector=await this._ctx.embed(query),candidates=filter?this._findAllRaw(filter):this._data,scored=[];for(let doc of candidates){if(!doc._vector)continue;let score=cosineSimilarity2(queryVector,doc._vector);if(score>=minScore)scored.push({doc,score})}scored.sort((a,b)=>b.score-a.score);let top=scored.slice(0,limit);this._ctx.queryLog?.record({collection:this.name,op:"search",query,duration:Date.now()-_t0,resultCount:top.length}),this._ctx.sessionStats.recordRead(session);let docs=top.map((r)=>stripVector2(r.doc)),scores=top.map((r)=>r.score);return await this._ctx.plugins.run("afterSearch",{collection:this.name,query,options:{filter,limit,minScore},docs,scores}),{docs,scores}}async similar(id,{limit=10,minScore=0}={}){await this._ctx.ensureConnected();let source=this._index.get(id);if(!source||!source._vector)return{docs:[],scores:[]};let scored=[];for(let doc of this._data){if(doc._id===id||!doc._vector)continue;let score=cosineSimilarity2(source._vector,doc._vector);if(score>=minScore)scored.push({doc,score})}scored.sort((a,b)=>b.score-a.score);let top=scored.slice(0,limit);return{docs:top.map((r)=>stripVector2(r.doc)),scores:top.map((r)=>r.score)}}async deleteOne(filter,options={}){await this._ctx.ensureConnected();let{save,session}=options;if(this._softDelete){let item=this._findRaw(filter);if(!item)return null;let{docs:docs2}=await this._deleteCore("soft",[item],filter,{save,session});return stripVector2(docs2[0])}let{docs}=await this._deleteCore("hard",null,filter,{save,session});if(docs.length===0)return null;return stripVector2(docs[0])}async deleteMany(filter,options={}){await this._ctx.ensureConnected();let{save,session}=options;if(this._softDelete){let items=this._findAllRaw(filter);if(items.length===0)return[];let{docs:docs2}=await this._deleteCore("soft",items,filter,{save,session});return docs2.map(stripVector2)}let{docs}=await this._deleteCore("hardMany",null,filter,{save,session});return docs.map(stripVector2)}async _deleteCore(mode,items,filter,{save,session}){return this._pipeline.execute({op:"delete",beforeHook:"beforeDelete",afterHook:"afterDelete",hookPayload:{collection:this.name,filter},save,session,afterHookPayload:(docs)=>({collection:this.name,filter,result:docs.length===1?docs[0]:docs}),mutate:async(assertTxAlive)=>{if(assertTxAlive(),mode==="soft"){let now=new Date;for(let item of items)item._deletedAt=now,item.updatedAt=now,this._index.set(item._id,item);return{docs:items}}if(mode==="hard"){let idx=this._findIndex(filter);if(idx===-1)return{docs:[]};let deletedItem=this._data.splice(idx,1)[0];return this._index.delete(deletedItem._id),this._removeFromIndex(deletedItem),{docs:[deletedItem]}}let deletedItems=[],remainingItems=[];for(let item of this._data)if(matchesFilter2(item,filter))deletedItems.push(item),this._index.delete(item._id),this._removeFromIndex(item);else remainingItems.push(item);return this._data=remainingItems,{docs:deletedItems}}})}async export(filter={},options={}){let{dir,name,format="json"}=options;try{let filteredData=this._data.filter((item)=>matchesFilter2(item,filter));if(filteredData.length===0)throw new QueryError2("ERR_SKALEX_QUERY_EXPORT_EMPTY",`export(): no documents matched the filter in "${this.name}"`,{collection:this.name});let content;if(format==="json")content=JSON.stringify(filteredData,null,2);else{let escapeCsv=(v)=>{if(v==null)return"";let s=typeof v==="object"?JSON.stringify(v):String(v);return s.includes(",")||s.includes('"')||s.includes(`
30
30
  `)||s.includes("\r")?`"${s.replace(/"/g,'""')}"`:s},header=Object.keys(filteredData[0]).map(escapeCsv).join(","),rows=filteredData.map((item)=>Object.values(item).map(escapeCsv).join(","));content=[header,...rows].join(`
31
31
  `)}if(typeof this._ctx.fs.writeRaw!=="function")throw new AdapterError2("ERR_SKALEX_ADAPTER_NO_RAW_WRITE","export() requires a file-system adapter (FsAdapter). The current adapter does not support raw file writes.");let exportDir=dir||`${this._ctx.dataDirectory}/exports`,fileName=`${name||this.name}.${format}`,filePath=this._ctx.fs.join(exportDir,fileName);this._ctx.fs.ensureDir(exportDir),await this._ctx.fs.writeRaw(filePath,content)}catch(error2){throw this._ctx.logger(`Error exporting "${this.name}": ${error2.message}`,"error"),error2}}_txSnapshotIfNeeded(){let txm=this._ctx.txManager;if(!txm.active)return;if(this._activeTxId!==txm.context?.id)return;txm.snapshotIfNeeded(this.name,this._store,(col)=>this._ctx.snapshotCollection(col))}async _saveIfNeeded(save){let txm=this._ctx.txManager;if(txm.active&&this._activeTxId===txm.context?.id)return;if(save??this._ctx.autoSave)await this._ctx.saveCollection(this.name)}_applyValidation(item){if(!this._schema)return item;let errors=validateDoc2(item,this._schema,this._strict);if(!errors.length)return item;switch(this._onSchemaError){case"warn":return this._ctx.logger(`[${this.name}] Validation warning: ${errors.join("; ")}`,"warn"),item;case"strip":return stripInvalidFields2(item,this._schema);default:throw new ValidationError2("ERR_SKALEX_VALIDATION_FAILED",`Validation failed: ${errors.join("; ")}`,{errors})}}_enforceCapAfterInsert(){let max=this._maxDocs;if(!max||this._data.length<=max)return;let toEvict=this._data.splice(0,this._data.length-max);for(let doc of toEvict)this._index.delete(doc._id),this._removeFromIndex(doc)}_findRaw(filter,{includeDeleted=!1}={}){if(typeof filter==="function"){for(let doc of this._data){if(this._softDelete&&doc._deletedAt&&!includeDeleted)continue;if(filter(doc))return doc}return null}if(filter._id){let item=this._index.get(filter._id)||null;if(!item)return null;if(this._softDelete&&item._deletedAt&&!includeDeleted)return null;if(Object.keys(filter).length>1)return matchesFilter2(item,filter)?item:null;return item}if(this._fieldIndex)for(let key in filter){if(key==="$or"||key==="$and"||key==="$not")continue;let val=filter[key];if(typeof val!=="object"||val===null){let candidates=this._fieldIndex._lookupIterable(key,val);if(candidates!==null){for(let doc of candidates){if(this._softDelete&&doc._deletedAt&&!includeDeleted)continue;if(matchesFilter2(doc,filter))return doc}return null}}}for(let doc of this._data){if(this._softDelete&&doc._deletedAt&&!includeDeleted)continue;if(matchesFilter2(doc,filter))return doc}return null}_findAllRaw(filter,{includeDeleted=!1}={}){if(filter&&typeof filter!=="function"&&filter._id){let item=this._index.get(filter._id);if(!item)return[];if(this._softDelete&&item._deletedAt&&!includeDeleted)return[];return matchesFilter2(item,filter)?[item]:[]}let results=[];for(let doc of this._getCandidates(filter)){if(this._softDelete&&doc._deletedAt&&!includeDeleted)continue;if(matchesFilter2(doc,filter))results.push(doc)}return results}_getCandidates(filter){if(!this._fieldIndex)return this._data;if(this._fieldIndex._compoundIndexes.size>0){let eqFields={};for(let key in filter){if(key==="$or"||key==="$and"||key==="$not")continue;let val=filter[key];if(typeof val!=="object"||val===null)eqFields[key]=val}if(Object.keys(eqFields).length>=2){let candidates=this._fieldIndex.lookupCompound(eqFields);if(candidates!==null)return candidates}}for(let key in filter){if(key==="$or"||key==="$and"||key==="$not")continue;let val=filter[key];if(typeof val!=="object"||val===null){let candidates=this._fieldIndex._lookupIterable(key,val);if(candidates!==null)return candidates}}return this._data}_findIndex(filter){for(let i=0;i<this._data.length;i++)if(matchesFilter2(this._data[i],filter))return i;return-1}_addToIndex(doc){if(this._fieldIndex)this._fieldIndex.add(doc)}_removeFromIndex(doc){if(this._fieldIndex)this._fieldIndex.remove(doc)}_updateInIndex(oldDoc,doc){if(this._fieldIndex)this._fieldIndex.update(oldDoc,doc)}async _buildDoc(item,{ttl,embed}={}){let newItem={...item,_id:item._id??(this._ctx.idGenerator??generateUniqueId2)(),createdAt:new Date,updatedAt:new Date},resolvedTtl=ttl??this._defaultTtl;if(resolvedTtl)newItem._expiresAt=computeExpiry2(resolvedTtl);let resolvedEmbed=embed??this._defaultEmbed;if(resolvedEmbed){let text=typeof resolvedEmbed==="function"?resolvedEmbed(newItem):newItem[resolvedEmbed];newItem._vector=await this._ctx.embed(String(text))}if(this._versioning)newItem._version=1;return newItem}_projectDoc(doc,select){if(select){let out2={};for(let field of select){if(field==="_vector")continue;out2[field]=doc[field]}return out2}let out={...doc};return delete out._vector,out}async _populateDoc(out,source,fields){for(let field of fields){let item=await this._ctx.getCollection(field).findOne({_id:source[field]});if(item)out[field]=item}}}class StorageAdapter2{async read(name){throw Error("StorageAdapter.read() not implemented")}async write(name,data){throw Error("StorageAdapter.write() not implemented")}async delete(name){throw Error("StorageAdapter.delete() not implemented")}async list(){throw Error("StorageAdapter.list() not implemented")}async writeAll(entries){for(let{name,data}of entries)await this.write(name,data)}}class FsAdapter2 extends StorageAdapter2{constructor({dir,format="gz"}){super();this.dir=nodePath2.resolve(dir),this.format=format,this._ensureDir(this.dir)}_ensureDir(dir){if(!nodeFs2.existsSync(dir))nodeFs2.mkdirSync(dir,{recursive:!0})}_filePath(name){return nodePath2.join(this.dir,`${name}.${this.format}`)}async read(name){let fp=this._filePath(name);try{let raw=await nodeFs2.promises.readFile(fp);if(this.format==="gz")raw=zlib2.inflateSync(raw);return raw.toString("utf8")}catch(err){if(err.code==="ENOENT")return null;throw err}}async write(name,data){let fp=this._filePath(name),tmp=nodePath2.join(this.dir,`${name}_${globalThis.crypto.randomUUID()}.tmp.${this.format}`);if(this.format==="gz"){let compressed=zlib2.deflateSync(data);await nodeFs2.promises.writeFile(tmp,compressed)}else await nodeFs2.promises.writeFile(tmp,data,"utf8");await nodeFs2.promises.rename(tmp,fp)}async writeAll(entries){let staged=[];try{for(let{name,data}of entries){let fp=this._filePath(name),tmp=nodePath2.join(this.dir,`${name}_${globalThis.crypto.randomUUID()}.tmp.${this.format}`);if(this.format==="gz"){let compressed=zlib2.deflateSync(data);await nodeFs2.promises.writeFile(tmp,compressed)}else await nodeFs2.promises.writeFile(tmp,data,"utf8");staged.push({tmp,fp})}for(let{tmp,fp}of staged)await nodeFs2.promises.rename(tmp,fp)}catch(error2){for(let{tmp}of staged)try{await nodeFs2.promises.unlink(tmp)}catch{}throw error2}}async delete(name){let fp=this._filePath(name);try{await nodeFs2.promises.unlink(fp)}catch(err){if(err.code!=="ENOENT")throw err}}async list(){try{let files=await nodeFs2.promises.readdir(this.dir),ext=`.${this.format}`;return files.filter((f)=>f.endsWith(ext)&&!f.includes(".tmp.")).map((f)=>f.slice(0,-ext.length))}catch(err){if(err.code==="ENOENT")return[];throw err}}join(...parts){return nodePath2.join(...parts)}ensureDir(dir){this._ensureDir(dir)}async writeRaw(filePath,content){this._ensureDir(nodePath2.dirname(filePath)),await nodeFs2.promises.writeFile(filePath,content,"utf8")}async readRaw(filePath){return nodeFs2.promises.readFile(nodePath2.resolve(filePath),"utf8")}}class MigrationEngine2{constructor(){this._migrations=[]}add(migration){let{version,up}=migration;if(typeof version!=="number"||version<1)throw new ValidationError2("ERR_SKALEX_VALIDATION_MIGRATION",`Migration version must be a positive integer, got ${version}`,{version});if(typeof up!=="function")throw new ValidationError2("ERR_SKALEX_VALIDATION_MIGRATION",`Migration version ${version} must have an "up" function`,{version});if(this._migrations.some((m)=>m.version===version))throw new ValidationError2("ERR_SKALEX_VALIDATION_MIGRATION_DUPLICATE",`Migration version ${version} is already registered`,{version});this._migrations.push({...migration}),this._migrations.sort((a,b)=>a.version-b.version)}async run(getCollection,appliedVersions=[]){let applied=new Set(appliedVersions),pending=this._migrations.filter((m)=>!applied.has(m.version));for(let migration of pending){let collection=getCollection(migration.version);await migration.up(collection),applied.add(migration.version)}return[...applied].sort((a,b)=>a-b)}status(appliedVersions=[]){let applied=new Set(appliedVersions),pending=this._migrations.map((m)=>m.version).filter((v)=>!applied.has(v));return{current:appliedVersions.length?Math.max(...appliedVersions):0,applied:[...applied].sort((a,b)=>a-b),pending}}}var EMPTY_ITERABLE2={[Symbol.iterator](){return{next(){return{done:!0}}}},size:0};function readOnlyIterable2(set){return{[Symbol.iterator](){return set[Symbol.iterator]()},get size(){return set.size}}}function encodeTuple2(values){return values.map((v)=>{if(v===null||v===void 0)return"\x00";if(typeof v==="boolean")return v?"\x01T":"\x01F";if(typeof v==="number")return`\x02${v}`;return`\x03${String(v)}`}).join("\x1F")}class IndexEngine2{constructor(fields=[],unique=[]){this._fields=new Set,this._compoundFields=[];for(let f of fields)if(Array.isArray(f)){for(let subf of f)this._validateFieldName(subf);this._compoundFields.push(f)}else this._validateFieldName(f),this._fields.add(f);for(let f of unique)this._validateFieldName(f);this._uniqueFields=new Set(unique),this._indexedFields=new Set([...this._fields,...this._uniqueFields]),this._fieldIndexes=new Map,this._uniqueIndexes=new Map;for(let f of this._fields)this._fieldIndexes.set(f,new Map);for(let f of this._uniqueFields)if(this._uniqueIndexes.set(f,new Map),!this._fieldIndexes.has(f))this._fieldIndexes.set(f,new Map);this._compoundIndexes=new Map;for(let fieldSet of this._compoundFields)this._compoundIndexes.set(fieldSet.join("\x00"),{fields:fieldSet,map:new Map})}get indexedFields(){return this._indexedFields}buildFromData(data){for(let[,m]of this._fieldIndexes)m.clear();for(let[,m]of this._uniqueIndexes)m.clear();for(let[,ci]of this._compoundIndexes)ci.map.clear();for(let doc of data)this._indexDoc(doc)}add(doc){this._checkUnique(doc,null),this._indexDoc(doc)}remove(doc){for(let[field,map]of this._fieldIndexes){let val=doc[field];if(val!==void 0){let set=map.get(val);if(set){if(set.delete(doc),set.size===0)map.delete(val)}}}for(let[field,map]of this._uniqueIndexes){let val=doc[field];if(val!==void 0)map.delete(val)}for(let[,ci]of this._compoundIndexes){let tupleKey=encodeTuple2(ci.fields.map((f)=>doc[f])),set=ci.map.get(tupleKey);if(set){if(set.delete(doc),set.size===0)ci.map.delete(tupleKey)}}}update(oldDoc,newDoc){this._checkUnique(newDoc,oldDoc),this.remove(oldDoc);try{this._indexDoc(newDoc)}catch(indexError){try{this._indexDoc(oldDoc)}catch{}throw indexError}}lookup(field,value){let map=this._fieldIndexes.get(field);if(!map)return null;let set=map.get(value);return set?[...set]:[]}_lookupIterable(field,value){let map=this._fieldIndexes.get(field);if(!map)return null;let set=map.get(value);return set?readOnlyIterable2(set):EMPTY_ITERABLE2}lookupCompound(fieldValues){let keys=Object.keys(fieldValues).sort();for(let[,ci]of this._compoundIndexes){let ciKeys=[...ci.fields].sort();if(ciKeys.length!==keys.length)continue;if(ciKeys.every((k,i)=>k===keys[i])){let tupleKey=encodeTuple2(ci.fields.map((f)=>fieldValues[f])),set=ci.map.get(tupleKey);return set?readOnlyIterable2(set):EMPTY_ITERABLE2}}return null}isUniqueTaken(field,value){let map=this._uniqueIndexes.get(field);if(!map)return!1;return map.has(value)}assertUniqueCandidates(oldDocs,newDocs){if(this._uniqueFields.size===0)return;let batchOldIds=new Set(oldDocs.map((doc)=>doc._id));for(let field of this._uniqueFields){let reserved=new Set,uniqueMap=this._uniqueIndexes.get(field);if(uniqueMap){for(let[value,doc]of uniqueMap.entries())if(!batchOldIds.has(doc._id))reserved.add(value)}let seen=new Map;for(let i=0;i<newDocs.length;i++){let val=newDocs[i][field];if(val===void 0)continue;if(reserved.has(val))throw new UniqueConstraintError2("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${field}" value "${val}" already exists`,{field,value:val});let prior=seen.get(val);if(prior&&prior!==oldDocs[i]._id)throw new UniqueConstraintError2("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${field}" value "${val}" already exists`,{field,value:val});seen.set(val,oldDocs[i]._id)}}}assertUniqueBatch(newDocs){if(this._uniqueFields.size===0)return;for(let field of this._uniqueFields){let uniqueMap=this._uniqueIndexes.get(field),seen=new Set;for(let doc of newDocs){let val=doc[field];if(val===void 0)continue;if(uniqueMap&&uniqueMap.has(val))throw new UniqueConstraintError2("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${field}" value "${val}" already exists`,{field,value:val});if(seen.has(val))throw new UniqueConstraintError2("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: duplicate "${field}" value "${val}" within batch`,{field,value:val});seen.add(val)}}}_validateFieldName(field){if(field.includes("."))throw new ValidationError2("ERR_SKALEX_VALIDATION_INDEX_DOT_PATH",`Index fields cannot use dot-notation: "${field}". Use a flat field name.`,{field})}_indexDoc(doc){for(let[field,map]of this._fieldIndexes){let val=doc[field];if(val!==void 0){if(!map.has(val))map.set(val,new Set);map.get(val).add(doc)}}for(let[field,map]of this._uniqueIndexes){let val=doc[field];if(val!==void 0)map.set(val,doc)}for(let[,ci]of this._compoundIndexes){for(let f of ci.fields){let val=doc[f];if(val!==void 0&&val!==null&&typeof val==="object")throw new ValidationError2("ERR_SKALEX_VALIDATION_COMPOUND_INDEX",`Compound index field "${f}" must be a scalar value (string, number, or boolean), got ${Array.isArray(val)?"array":typeof val}`,{field:f})}let tupleKey=encodeTuple2(ci.fields.map((f)=>doc[f]));if(!ci.map.has(tupleKey))ci.map.set(tupleKey,new Set);ci.map.get(tupleKey).add(doc)}}_checkUnique(newDoc,existingDoc){for(let field of this._uniqueFields){let val=newDoc[field];if(val===void 0)continue;let map=this._uniqueIndexes.get(field);if(!map)continue;let existing=map.get(val);if(existing&&existing._id!==existingDoc?._id)throw new UniqueConstraintError2("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${field}" value "${val}" already exists`,{field,value:val})}}}var FLUSH_META_KEY2="_flush",META_DOC_ID2="migrations";class PersistenceManager2{constructor({adapter,serializer,deserializer,logger:logger22,debug=!1,lenientLoad=!1}){this._adapter=adapter,this._serializer=serializer,this._deserializer=deserializer,this._logger=logger22,this._debug=debug,this._lenientLoad=lenientLoad,this._saveLock=Promise.resolve()}_withSaveLock(fn){let next=this._saveLock.then(fn);return this._saveLock=next.catch(()=>{}),next}async loadAll(collections,{parseSchema:parseSchema22,buildIndex,IndexEngine:IndexEngine22}){try{let names=await this._adapter.list();await Promise.all(names.map(async(name)=>{try{let raw=await this._adapter.read(name);if(!raw)return;let parsed=this._deserializer(raw),{collectionName,data}=parsed;if(!collectionName)return;let existing=collections[collectionName],rawSchema=existing?.rawSchema??parsed.rawSchema??null,parsedSchema=existing?.schema??(rawSchema?parseSchema22(rawSchema):null),changelog=existing?.changelog??parsed.changelog??!1,softDelete=existing?.softDelete??parsed.softDelete??!1,versioning=existing?.versioning??parsed.versioning??!1,strict=existing?.strict??parsed.strict??!1,onSchemaError=existing?.onSchemaError??parsed.onSchemaError??"throw",defaultTtl=existing?.defaultTtl??parsed.defaultTtl??null,defaultEmbed=existing?.defaultEmbed??parsed.defaultEmbed??null,maxDocs=existing?.maxDocs??parsed.maxDocs??null,fieldIndex=existing?existing.fieldIndex:null;if(!fieldIndex&&parsedSchema?.uniqueFields?.length)fieldIndex=new IndexEngine22([],parsedSchema.uniqueFields);let idIndex=buildIndex(data,"_id");if(fieldIndex)fieldIndex.buildFromData(data);collections[collectionName]={collectionName,data,index:idIndex,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:parsedSchema,rawSchema,fieldIndex,changelog,softDelete,versioning,strict,onSchemaError,defaultTtl,defaultEmbed,maxDocs}}catch(error2){if(error2.code==="ENOENT")return;if(this._lenientLoad){this._logger(`WARNING: Could not load collection "${name}": ${error2.message}. Collection will be empty.`,"error");return}throw new PersistenceError2("ERR_SKALEX_PERSISTENCE_CORRUPT",`Failed to load collection "${name}": ${error2.message}`,{collection:name})}})),this._detectIncompleteFlush(collections),await this._cleanOrphanTempFiles()}catch(error2){if(error2.code!=="ENOENT")throw this._logger(`Error loading data: ${error2}`,"error"),error2}}async save(collections,collectionName){if(collectionName)await this._saveOne(collections,collectionName);else await Promise.all(Object.keys(collections).map((name)=>this._saveOne(collections,name)))}async saveDirty(collections){let dirtyNames=Object.keys(collections).filter((name)=>collections[name]._dirty);if(dirtyNames.length===0)return;await Promise.all(dirtyNames.map((name)=>this._saveOne(collections,name)))}saveAtomic(collections,names){return this._withSaveLock(async()=>{if(names.length===0)return;this._writeFlushSentinel(collections,names);let allNames=new Set(names);allNames.add("_meta");let entries=[...allNames].filter((n)=>collections[n]).map((name)=>({name,data:this._serializeCollection(collections[name])}));try{await this._adapter.writeAll(entries)}catch(error2){throw new PersistenceError2("ERR_SKALEX_PERSISTENCE_FLUSH_FAILED",`Batch save failed during writeAll: ${error2.message}`,{collections:names})}for(let name of names)if(collections[name])collections[name]._dirty=!1;try{this._clearFlushSentinel(collections),await this._adapter.write("_meta",this._serializeCollection(collections._meta))}catch(error2){this._logger(`WARNING: Batch data committed but sentinel clear failed: ${error2.message}. Next load will report an incomplete flush (false positive).`,"error")}})}markDirty(collections,name){let col=collections[name];if(col)col._dirty=!0}_serializeCollection(col){let payload={collectionName:col.collectionName,data:col.data};if(col.rawSchema)payload.rawSchema=col.rawSchema;if(col.changelog)payload.changelog=col.changelog;if(col.softDelete)payload.softDelete=col.softDelete;if(col.versioning)payload.versioning=col.versioning;if(col.strict)payload.strict=col.strict;if(col.onSchemaError!=="throw")payload.onSchemaError=col.onSchemaError;if(col.defaultTtl)payload.defaultTtl=col.defaultTtl;if(col.defaultEmbed)payload.defaultEmbed=col.defaultEmbed;if(col.maxDocs)payload.maxDocs=col.maxDocs;return this._serializer(payload)}async _saveOne(collections,name){let col=collections[name];if(!col)return;if(col.isSaving)return col._pendingSave=!0,new Promise((resolve,reject)=>{(col._saveWaiters??=[]).push({resolve,reject})});col.isSaving=!0,col._pendingSave=!1;try{await this._writeCollection(name,col);while(col._pendingSave)col._pendingSave=!1,await this._writeCollection(name,col);this._resolveSaveWaiters(col)}catch(error2){throw this._rejectSaveWaiters(col,error2),error2}finally{col.isSaving=!1}}async _writeCollection(name,col){try{await this._adapter.write(name,this._serializeCollection(col)),col._dirty=!1}catch(error2){throw this._logger(`Error saving "${name}": ${error2.message}`,"error"),error2}}_resolveSaveWaiters(col){let waiters=col._saveWaiters?.splice(0)??[];for(let w of waiters)w.resolve()}_rejectSaveWaiters(col,error2){let waiters=col._saveWaiters?.splice(0)??[];for(let w of waiters)w.reject(error2)}_writeFlushSentinel(collections,names){let meta=this._getOrCreateMeta(collections);meta[FLUSH_META_KEY2]={startedAt:new Date().toISOString(),collections:names,completedAt:null}}_clearFlushSentinel(collections){let meta=this._getOrCreateMeta(collections);if(meta[FLUSH_META_KEY2])meta[FLUSH_META_KEY2].completedAt=new Date().toISOString()}_detectIncompleteFlush(collections){let metaCol=collections._meta;if(!metaCol)return;let metaDoc=metaCol.index.get(META_DOC_ID2);if(!metaDoc)return;let flush=metaDoc[FLUSH_META_KEY2];if(!flush)return;if(flush.startedAt&&!flush.completedAt)this._logger(`WARNING: Incomplete flush detected (started ${flush.startedAt}, collections: ${flush.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 nodeFs23=await import("fs"),nodePath23=await import("path"),dir=this._adapter.dir;if(!dir)return;let orphans=(await nodeFs23.default.promises.readdir(dir)).filter((f)=>f.includes(".tmp."));for(let orphan of orphans){let orphanPath=nodePath23.default.join(dir,orphan);try{await nodeFs23.default.promises.unlink(orphanPath),this._log(`Cleaned orphan temp file: ${orphan}`)}catch{}}}catch{}}_getOrCreateMeta(collections){if(!collections._meta)collections._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 metaCol=collections._meta,doc=metaCol.index.get(META_DOC_ID2);if(!doc)doc={_id:META_DOC_ID2},metaCol.data.push(doc),metaCol.index.set(META_DOC_ID2,doc);return doc}_log(msg){if(this._debug)this._logger(msg,"info")}}var _txIdCounter2=0;class TransactionManager2{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(fn,db,{timeout=0}={}){let execute=async()=>{await db._ensureConnected();let preExisting=new Set(Object.keys(db.collections)),ctx={id:++_txIdCounter2,startedAt:Date.now(),aborted:!1,preExisting,touchedCollections:new Set,snapshots:new Map,deferredEffects:[],timeout};this._ctx=ctx;let timer=null,timeoutPromise=timeout>0?new Promise((_,reject)=>{timer=setTimeout(()=>{ctx.aborted=!0,reject(new TransactionError2("ERR_SKALEX_TX_TIMEOUT",`Transaction ${ctx.id} timed out after ${timeout}ms`))},timeout)}):null,self=this,proxy=new Proxy(db,{get(target,prop){if(prop==="_txId")return ctx.id;if(ctx!==self._ctx)throw new TransactionError2("ERR_SKALEX_TX_STALE_PROXY",`Transaction ${ctx.id} has ended. This proxy is no longer usable.`);if(prop==="collections")throw new TransactionError2("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(prop==="useCollection")return(name)=>{let col=target.useCollection(name);return col._activeTxId=ctx.id,col};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value}});try{let fnPromise=fn(proxy),result=timeoutPromise?await Promise.race([fnPromise,timeoutPromise]):await fnPromise;if(ctx.aborted)throw new TransactionError2("ERR_SKALEX_TX_ABORTED",`Transaction ${ctx.id} was aborted`);let touched=[...ctx.touchedCollections];if(touched.length>0)await db._persistence.saveAtomic(db.collections,touched);for(let effect of ctx.deferredEffects)await effect();return result}catch(error2){for(let[name,snap]of ctx.snapshots)if(ctx.preExisting.has(name)){if(db._applySnapshot(name,snap),db.collections[name])db.collections[name]._dirty=snap._dirty}for(let name in db.collections)if(!ctx.preExisting.has(name))delete db.collections[name],delete db._collectionInstances[name];throw error2}finally{if(timer)clearTimeout(timer);if(ctx.aborted)this._abortedIds.add(ctx.id);this._ctx=null;for(let name in db._collectionInstances){let inst=db._collectionInstances[name];if(inst._createdInTxId===ctx.id)inst._createdInTxId=null;if(inst._activeTxId===ctx.id)inst._activeTxId=null}}},next=this._txLock.then(execute);return this._txLock=next.catch(()=>{}),next}snapshotIfNeeded(name,col,snapshotFn){let ctx=this._ctx;if(!ctx)return;if(this._assertCtxNotAborted(ctx),!ctx.snapshots.has(name)){let snap=snapshotFn(col);snap._dirty=col._dirty??!1,ctx.snapshots.set(name,snap)}ctx.touchedCollections.add(name)}assertNotAborted(){let ctx=this._ctx;if(ctx)this._assertCtxNotAborted(ctx)}_assertCtxNotAborted(ctx){if(ctx.aborted)throw new TransactionError2("ERR_SKALEX_TX_ABORTED",`Transaction ${ctx.id} was aborted. No further mutations allowed.`)}defer(effect){if(this._ctx)return this._ctx.deferredEffects.push(effect),!0;return!1}}class CollectionRegistry2{constructor(CollectionClass){this._CollectionClass=CollectionClass,this.stores={},this._instances={}}get(name,db){if(this._instances[name])return this._instances[name];if(!this.stores[name])this.createStore(name);let instance=new this._CollectionClass(this.stores[name],db);return this._instances[name]=instance,instance}create(name,options={},db){this.createStore(name,options);let instance=new this._CollectionClass(this.stores[name],db);return this._instances[name]=instance,instance}createStore(name,{schema,indexes=[],changelog=!1,softDelete=!1,versioning=!1,strict=!1,onSchemaError="throw",defaultTtl=null,defaultEmbed=null,maxDocs=null}={}){let parsedSchema=null,fieldIndex=null;if(schema){parsedSchema=parseSchema2(schema);let uniqueFields=parsedSchema.uniqueFields;if(indexes.length||uniqueFields.length)fieldIndex=new IndexEngine2(indexes,uniqueFields)}else if(indexes.length)fieldIndex=new IndexEngine2(indexes,[]);this.stores[name]={collectionName:name,data:[],index:new Map,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:parsedSchema,rawSchema:schema||null,fieldIndex,changelog,softDelete,versioning,strict,onSchemaError,defaultTtl,defaultEmbed,maxDocs}}rename(from,to){if(!this.stores[from])throw new PersistenceError2("ERR_SKALEX_PERSISTENCE_COLLECTION_NOT_FOUND",`Collection "${from}" not found`,{collection:from});if(this.stores[to])throw new PersistenceError2("ERR_SKALEX_PERSISTENCE_COLLECTION_EXISTS",`Collection "${to}" already exists`,{collection:to});let store=this.stores[from];if(store.collectionName=to,this.stores[to]=store,delete this.stores[from],this._instances[from]){let inst=this._instances[from];inst.name=to,this._instances[to]=inst,delete this._instances[from]}}buildIndex(data,keyField){let index=new Map;for(let item of data)index.set(item[keyField],item);return index}inspect(name){if(name){let col=this.stores[name];if(!col)return null;return{name,count:col.data.length,schema:col.schema?Object.fromEntries(col.schema.fields):null,indexes:col.fieldIndex?[...col.fieldIndex.indexedFields]:[],softDelete:col.softDelete??!1,versioning:col.versioning??!1,strict:col.strict??!1,onSchemaError:col.onSchemaError??"throw",maxDocs:col.maxDocs??null}}let result={};for(let n in this.stores)result[n]=this.inspect(n);return result}dump(){let result={};for(let name in this.stores)if(!name.startsWith("_"))result[name]=structuredClone(this.stores[name].data);return result}schema(name){let store=this.stores[name];if(!store)return null;if(store.schema)return Object.fromEntries([...store.schema.fields.entries()].map(([k,v])=>[k,v.type]));if(store.data.length>0)return inferSchema2(store.data[0]);return null}stats(name){let calc=(n)=>{let col=this.stores[n];if(!col)return null;let count22=col.data.length,estimatedSize=0;for(let doc of col.data)try{estimatedSize+=JSON.stringify(doc).length}catch(_){}return{collection:n,count:count22,estimatedSize,avgDocSize:count22>0?Math.round(estimatedSize/count22):0}};if(name)return calc(name);return Object.keys(this.stores).map(calc)}clear(){this.stores={},this._instances={}}}class EmbeddingAdapter2{async embed(text){throw Error("EmbeddingAdapter.embed() not implemented")}}var _env$42=(k)=>globalThis.process?.env?.[k]??globalThis.Deno?.env?.get(k);class OpenAIEmbeddingAdapter2 extends EmbeddingAdapter2{constructor({apiKey=_env$42("OPENAI_API_KEY"),model=_env$42("OPENAI_EMBED_MODEL")??"text-embedding-3-small",baseUrl=_env$42("OPENAI_EMBED_BASE_URL")??"https://api.openai.com/v1/embeddings",dimensions=_env$42("OPENAI_EMBED_DIMENSIONS")!=null?Number(_env$42("OPENAI_EMBED_DIMENSIONS")):void 0,organization=_env$42("OPENAI_ORGANIZATION")??void 0,timeout=_env$42("OPENAI_EMBED_TIMEOUT")!=null?Number(_env$42("OPENAI_EMBED_TIMEOUT")):void 0,retries=Number(_env$42("OPENAI_EMBED_RETRIES")??0),retryDelay=Number(_env$42("OPENAI_EMBED_RETRY_DELAY")??1000),headers={},fetch:fetchFn=globalThis.fetch}={}){super();if(!apiKey)throw Error("OpenAIEmbeddingAdapter requires an apiKey");this.apiKey=apiKey,this.model=model,this.baseUrl=baseUrl,this.dimensions=dimensions,this.organization=organization,this.timeout=timeout,this.retries=retries,this.retryDelay=retryDelay,this.headers=headers,this._fetch=fetchFn}async embed(text){let lastErr;for(let attempt=0;attempt<=this.retries;attempt++){let controller=this.timeout!=null?new AbortController:null,timer=controller?setTimeout(()=>controller.abort(),this.timeout):null;try{let response=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:text,model:this.model,...this.dimensions!==void 0&&{dimensions:this.dimensions}}),...controller&&{signal:controller.signal}});if(!response.ok){let err=(await response.text()).slice(0,200);throw Error(`OpenAI embedding API error ${response.status}: ${err}`)}return(await response.json()).data[0].embedding}catch(err){if(lastErr=err,attempt<this.retries)await new Promise((r)=>setTimeout(r,this.retryDelay*2**attempt))}finally{if(timer!==null)clearTimeout(timer)}}throw lastErr}}var _env$32=(k)=>globalThis.process?.env?.[k]??globalThis.Deno?.env?.get(k);class OllamaEmbeddingAdapter2 extends EmbeddingAdapter2{constructor({model=_env$32("OLLAMA_EMBED_MODEL")??"nomic-embed-text",host=_env$32("OLLAMA_HOST")??"http://localhost:11434",timeout=_env$32("OLLAMA_EMBED_TIMEOUT")!=null?Number(_env$32("OLLAMA_EMBED_TIMEOUT")):void 0,retries=Number(_env$32("OLLAMA_EMBED_RETRIES")??0),retryDelay=Number(_env$32("OLLAMA_EMBED_RETRY_DELAY")??1000),headers={},fetch:fetchFn=globalThis.fetch}={}){super();this.model=model,this.host=host,this.timeout=timeout,this.retries=retries,this.retryDelay=retryDelay,this.headers=headers,this._fetch=fetchFn}async embed(text){let lastErr;for(let attempt=0;attempt<=this.retries;attempt++){let controller=this.timeout!=null?new AbortController:null,timer=controller?setTimeout(()=>controller.abort(),this.timeout):null;try{let response=await this._fetch(`${this.host}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json",...this.headers},body:JSON.stringify({model:this.model,prompt:text}),...controller&&{signal:controller.signal}});if(!response.ok){let err=(await response.text()).slice(0,200);throw Error(`Ollama embedding API error ${response.status}: ${err}`)}return(await response.json()).embedding}catch(err){if(lastErr=err,attempt<this.retries)await new Promise((r)=>setTimeout(r,this.retryDelay*2**attempt))}finally{if(timer!==null)clearTimeout(timer)}}throw lastErr}}class LLMAdapter2{async generate(schema,nlQuery){throw Error("LLMAdapter.generate() not implemented")}async summarize(texts){throw Error("LLMAdapter.summarize() not implemented")}}var SYSTEM_GENERATE2=`You are a database query assistant. Convert the user's natural language request into a JSON filter object for a document database.
32
32
 
@@ -52,7 +52,7 @@ data: /message
52
52
 
53
53
  `),this._clients.add(res),req.on("close",()=>{this._clients.delete(res)})}async _handleMessage(req,res){let body="";req.setEncoding("utf8"),req.on("data",(c)=>{if(body+=c,body.length>this._maxBodySize)req.destroy(),res.writeHead(413,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Request body too large"}))}),req.on("end",async()=>{res.writeHead(202,{"Content-Type":"application/json"}),res.end("{}");let msg;try{msg=JSON.parse(body)}catch(_){this.send(error2(null,PARSE_ERROR2,"Parse error"));return}if(this._onMessage)await this._onMessage(msg).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 StdioTransport2{constructor(){this._onMessage=null,this._buffer="",this._started=!1}onMessage(fn){this._onMessage=fn}send(msg){process.stdout.write(JSON.stringify(msg)+`
54
54
  `)}start(){if(this._started)return;this._started=!0,process.stdin.setEncoding("utf8"),process.stdin.on("data",(chunk)=>{this._buffer+=chunk;let idx;while((idx=this._buffer.indexOf(`
55
- `))!==-1){let line=this._buffer.slice(0,idx).trim();if(this._buffer=this._buffer.slice(idx+1),line&&this._onMessage){let msg;try{msg=JSON.parse(line)}catch(_){this.send(error2(null,PARSE_ERROR2,"Parse error"));continue}this._onMessage(msg).catch(()=>{})}}}),process.stdin.on("end",()=>{process.exit(0)})}stop(){process.stdin.removeAllListeners("data"),process.stdin.removeAllListeners("end"),this._started=!1}}var SERVER_INFO2={name:"skalex",version:"4.0.0-alpha"},PROTOCOL_VERSION2="2024-11-05";class SkalexMCPServer2{constructor(db,opts={}){this._db=db,this._transport=opts.transport||"stdio",this._port=opts.port||3000,this._host=opts.host||"127.0.0.1",this._allowedOrigin=opts.allowedOrigin??null,this._maxBodySize=opts.maxBodySize??1048576,this._scopes=opts.scopes||{"*":["read"]},this._t=null}async listen(){if(this._transport==="http")this._t=new HttpTransport2({port:this._port,host:this._host,allowedOrigin:this._allowedOrigin,maxBodySize:this._maxBodySize});else this._t=new StdioTransport2;this._t.onMessage((msg)=>this._handleMessage(msg)),await this._t.start()}async connect(transport){if(this._t=transport,this._t.onMessage((msg)=>this._handleMessage(msg)),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(raw){let{msg,parseError}=typeof raw==="string"?parse2(raw):{msg:raw};if(parseError){this._send(parseError);return}let{id,method,params}=msg;if(id===void 0){if(method==="notifications/initialized")return;return}try{switch(method){case"initialize":this._send(ok2(id,{protocolVersion:PROTOCOL_VERSION2,capabilities:{tools:{}},serverInfo:SERVER_INFO2}));break;case"tools/list":this._send(ok2(id,{tools:this._visibleTools()}));break;case"tools/call":await this._handleToolCall(id,params);break;case"ping":this._send(ok2(id,{}));break;default:this._send(error2(id,METHOD_NOT_FOUND2,`Method not found: ${method}`))}}catch(err){this._send(error2(id,INTERNAL_ERROR2,err.message||"Internal error"))}}async _handleToolCall(id,params){let name=params?.name,args=params?.arguments??{};if(!name){this._send(error2(id,INVALID_PARAMS2,"tools/call requires params.name"));return}let def=TOOL_DEFS2.find((t)=>t.name===name);if(!def){this._send(error2(id,METHOD_NOT_FOUND2,`Unknown tool: ${name}`));return}let collection=args.collection||args.collection_name||null;if(!this._hasScope(collection,def.scope)){this._send(ok2(id,toolError2(`Access denied: "${name}" requires "${def.scope}" scope on collection "${collection}".`)));return}try{let result=await callTool2(name,args,this._db);this._send(ok2(id,toolResult2(JSON.stringify(result,null,2))))}catch(err){this._send(ok2(id,toolError2(err.message||String(err))))}}_visibleTools(){return TOOL_DEFS2.filter((def)=>{let global=this._scopes["*"];if(global&&(global.includes(def.scope)||global.includes("admin")))return!0;for(let[,perms]of Object.entries(this._scopes))if(perms.includes(def.scope)||perms.includes("admin"))return!0;return!1})}_hasScope(collection,scope){let check=(perms)=>perms.includes("admin")||perms.includes(scope);if(collection&&this._scopes[collection])return check(this._scopes[collection]);if(this._scopes["*"])return check(this._scopes["*"]);return!1}_send(msg){this._t?.send(msg)}}var META_KEY2="migrations",_serialize2=(value)=>JSON.stringify(value,function(key,v){let raw=this[key];if(raw instanceof Date)return{__skalex_date__:raw.toISOString()};if(typeof v==="bigint")return{__skalex_bigint__:v.toString()};return v}),_deserialize2=(text)=>JSON.parse(text,(_,v)=>{if(v&&typeof v==="object"){if("__skalex_bigint__"in v)return BigInt(v.__skalex_bigint__);if("__skalex_date__"in v)return new Date(v.__skalex_date__)}return v});class Skalex2{constructor({path="./.db",format="gz",debug=!1,adapter,ai,encrypt,slowQueryLog,queryCache,memory,logger:logger$1,plugins,llmAdapter,embeddingAdapter,regexMaxLength,idGenerator,serializer,deserializer,autoSave,ttlSweepInterval,lenientLoad}={}){if(this.dataDirectory=path,this.dataFormat=format,this.debug=debug,!Skalex2._errorsAttached)Skalex2.SkalexError=SkalexError2,Skalex2.ValidationError=ValidationError2,Skalex2.UniqueConstraintError=UniqueConstraintError2,Skalex2.TransactionError=TransactionError2,Skalex2.PersistenceError=PersistenceError2,Skalex2.AdapterError=AdapterError2,Skalex2.QueryError=QueryError2,Skalex2._errorsAttached=!0;this._adapterConfig=adapter??null;let fs=adapter||new FsAdapter2({dir:path,format});if(encrypt)fs=new EncryptedAdapter2(fs,encrypt.key);if(this.fs=fs,this._registry=new CollectionRegistry2(Collection2),this.collections=this._registry.stores,this._collectionInstances=this._registry._instances,this._migrations=new MigrationEngine2,this._connectPromise=null,this.isConnected=!1,this._aiConfig=ai||null,this._encryptConfig=encrypt||null,this._pluginsConfig=Array.isArray(plugins)?plugins:null,this._memoryConfig=memory||null,this._regexMaxLength=regexMaxLength??500,this._idGenerator=idGenerator??null,this._serializer=serializer??_serialize2,this._deserializer=deserializer??_deserialize2,this._autoSave=autoSave??!1,this._txManager=new TransactionManager2,this._ttlSweepInterval=ttlSweepInterval??0,this._ttlTimer=null,this._logger=logger$1??logger2,this._embeddingAdapter=embeddingAdapter??(ai?createEmbeddingAdapter2(ai):null),this._aiAdapter=llmAdapter??(ai?createLLMAdapter2(ai):null),this._persistence=new PersistenceManager2({adapter:this.fs,serializer:this._serializer,deserializer:this._deserializer,logger:this._logger,debug:this.debug,lenientLoad:lenientLoad??!1}),this._changeLog=new ChangeLog2(this),this._queryCache=new QueryCache2(queryCache||{}),this._eventBus=new EventBus2,this._queryLog=slowQueryLog?new QueryLog2(slowQueryLog):null,this._sessionStats=new SessionStats2,this._plugins=new PluginEngine2,Array.isArray(plugins))for(let p of plugins)this._plugins.register(p)}async connect(){if(this._connectPromise)return this._connectPromise;return this._connectPromise=this._doConnect(),this._connectPromise}async _doConnect(){try{await this.loadData();let meta=this._getMeta();if(meta.queryCache)this._queryCache.fromJSON(meta.queryCache);if(this._migrations._migrations.length>0){let applied=meta.appliedVersions||[],newApplied=await this._migrations.run((version)=>this.useCollection(`_migration_${version}`),applied);this._saveMeta({appliedVersions:newApplied})}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(error22){throw this._logger(`Error connecting to the database: ${error22}`,"error"),error22}}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(error22){throw this._logger(`Error disconnecting from the database: ${error22}`,"error"),error22}}async _ensureConnected(){if(this.isConnected)return;return this.connect()}useCollection(collectionName){return this._registry.get(collectionName,this)}createCollection(collectionName,options={}){return this._registry.create(collectionName,options,this)}_createCollectionStore(collectionName,options={}){this._registry.createStore(collectionName,options)}async renameCollection(from,to){this._registry.rename(from,to),await this.saveData(to),await this.fs.delete(from)}async loadData(){await this._persistence.loadAll(this.collections,{parseSchema:parseSchema2,buildIndex:this._registry.buildIndex,IndexEngine:IndexEngine2});for(let name in this._collectionInstances){let store=this.collections[name];if(store&&this._collectionInstances[name]._store!==store)this._collectionInstances[name]._store=store}}async saveData(collectionName){await this._persistence.save(this.collections,collectionName)}buildIndex(data,keyField){return this._registry.buildIndex(data,keyField)}addMigration(migration){this._migrations.add(migration)}migrationStatus(){let meta=this._getMeta();return this._migrations.status(meta.appliedVersions||[])}namespace(id){if(this._adapterConfig)throw new AdapterError2("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 safeId=String(id).replace(/[^a-zA-Z0-9_-]/g,"_");if(!safeId)throw new ValidationError2("ERR_SKALEX_VALIDATION_NAMESPACE_ID","namespace: id must contain at least one alphanumeric character",{id});return new Skalex2({path:`${this.dataDirectory}/${safeId}`,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!==logger2?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!==_serialize2?this._serializer:void 0,deserializer:this._deserializer!==_deserialize2?this._deserializer:void 0,autoSave:this._autoSave||void 0,ttlSweepInterval:this._ttlSweepInterval||void 0})}use(plugin){this._plugins.register(plugin)}watch(callback){return this._eventBus.on("*",callback)}sessionStats(sessionId){if(sessionId!==void 0)return this._sessionStats.get(sessionId);return this._sessionStats.all()}get _inTransaction(){return this._txManager.active}_emitEvent(collectionName,data){if(!this._txManager.defer(()=>this._eventBus.emit(collectionName,data)))this._eventBus.emit(collectionName,data)}async _runAfterHook(hook,data){if(!this._txManager.defer(()=>this._plugins.run(hook,data)))await this._plugins.run(hook,data)}async _logChange(op,collectionName,doc,prev,session){if(!this._txManager.defer(()=>this._changeLog.log(op,collectionName,doc,prev,session)))await this._changeLog.log(op,collectionName,doc,prev,session)}async transaction(fn,opts={}){return this._txManager.run(fn,this,opts)}async seed(fixtures,{reset=!1}={}){for(let[name,docs]of Object.entries(fixtures)){if(reset&&this.collections[name])this._applySnapshot(name,{data:[],index:new Map}),delete this._collectionInstances[name];await this.useCollection(name).insertMany(docs)}await this.saveData()}dump(){return this._registry.dump()}inspect(collectionName){return this._registry.inspect(collectionName)}async import(filePath){let content=await this.fs.readRaw(filePath),docs;try{docs=JSON.parse(content)}catch{throw new PersistenceError2("ERR_SKALEX_PERSISTENCE_INVALID_JSON",`import: invalid JSON in file "${filePath}"`,{filePath})}let name=filePath.split("/").pop().replace(/\.[^.]+$/,"");return this.useCollection(name).insertMany(Array.isArray(docs)?docs:[docs],{save:!0})}async embed(text){if(!this._embeddingAdapter)throw new AdapterError2("ERR_SKALEX_ADAPTER_EMBEDDING_REQUIRED","db.embed() requires an AI adapter. Pass { ai: { provider, apiKey } } to the Skalex constructor.");return this._embeddingAdapter.embed(text)}async ask(collectionName,nlQuery,{limit=20}={}){if(!this._aiAdapter)throw new AdapterError2("ERR_SKALEX_ADAPTER_LLM_REQUIRED",'db.ask() requires a language model adapter. Configure { ai: { provider, model: "..." } }.');let col=this.useCollection(collectionName),schema=this.schema(collectionName),filter=this._queryCache.get(collectionName,schema,nlQuery);if(!filter){filter=await this._aiAdapter.generate(schema,nlQuery);let warnings=validateLLMFilter2(filter,schema);if(warnings.length)warnings.forEach((w)=>this._log(`[ask] ${w}`));this._queryCache.set(collectionName,schema,nlQuery,filter),this._saveMeta({queryCache:this._queryCache.toJSON()})}return col.find(processLLMFilter2(filter,{regexMaxLength:this._regexMaxLength}),{limit})}schema(collectionName){return this._registry.schema(collectionName)}useMemory(sessionId){return new Memory2(sessionId,this)}changelog(){return this._changeLog}async restore(collectionName,timestamp,opts={}){return this._changeLog.restore(collectionName,timestamp,opts)}stats(collectionName){return this._registry.stats(collectionName)}slowQueries(opts={}){if(!this._queryLog)return[];return this._queryLog.entries(opts)}slowQueryCount(){return this._queryLog?this._queryLog.size:0}clearSlowQueries(){this._queryLog?.clear()}mcp(opts={}){return new SkalexMCPServer2(this,opts)}_getMeta(){let metaCol=this.collections._meta;if(!metaCol)return{};return metaCol.index.get(META_KEY2)||{}}_saveMeta(data){if(!this.collections._meta)this._createCollectionStore("_meta");let col=this.collections._meta,existing=col.index.get(META_KEY2);if(existing)Object.assign(existing,data);else{let doc={_id:META_KEY2,...data};col.data.push(doc),col.index.set(META_KEY2,doc)}this._persistence.markDirty(this.collections,"_meta")}_sweepTtl(){for(let name in this.collections){let col=this.collections[name],removed=sweep2(col.data,col.index,col.fieldIndex?(doc)=>col.fieldIndex.remove(doc):null);if(removed>0)this._persistence.markDirty(this.collections,name),this._log(`TTL sweep: removed ${removed} expired docs from "${name}"`)}}_buildCollectionContext(){let db=this;return{ensureConnected:()=>db._ensureConnected(),get txManager(){return db._txManager},get plugins(){return db._plugins},get eventBus(){return db._eventBus},get sessionStats(){return db._sessionStats},get queryLog(){return db._queryLog},get logger(){return db._logger},get persistence(){return db._persistence},get collections(){return db.collections},embed:(text)=>db.embed(text),get idGenerator(){return db._idGenerator},get autoSave(){return db._autoSave},saveCollection:(name)=>db.saveData(name),snapshotCollection:(col)=>db._snapshotCollection(col),getCollection:(name)=>db.useCollection(name),emitEvent:(name,data)=>db._emitEvent(name,data),runAfterHook:(hook,data)=>db._runAfterHook(hook,data),logChange:(op,col,doc,prev,session)=>db._logChange(op,col,doc,prev,session),get fs(){return db.fs},get dataDirectory(){return db.dataDirectory}}}_log(msg){if(this.debug)this._logger(msg,"info")}_snapshotCollection(col){return{data:structuredClone(col.data)}}_applySnapshot(name,snap){let col=this.collections[name];if(!col)return;if(col.data=snap.data,col.index=this.buildIndex(snap.data,"_id"),col.fieldIndex)col.fieldIndex.buildFromData(snap.data)}}function generateUniqueId22(){let timestamp=Date.now().toString(16),random;try{random=nodeCrypto22.randomBytes(8).toString("hex")}catch{let arr=new Uint8Array(8);crypto.getRandomValues(arr),random=Array.from(arr).map((b)=>b.toString(16).padStart(2,"0")).join("")}return`${timestamp}${random}`}function logger22(error22,type){let msg=error22 instanceof Error?error22.message:error22;if(type==="error")console.error(msg);else console.log(msg)}var _FORBIDDEN_KEYS22=new Set(["__proto__","constructor","prototype"]);function resolveDotPath22(obj,path){if(!path.includes(".")){if(_FORBIDDEN_KEYS22.has(path))return;return obj[path]}let cur=obj;for(let p of path.split(".")){if(_FORBIDDEN_KEYS22.has(p))return;if(cur==null)return;cur=cur[p]}return cur}class SkalexError22 extends Error{constructor(code,message,details={}){super(message);this.name=this.constructor.name,this.code=code,this.details=details}}class ValidationError22 extends SkalexError22{}class UniqueConstraintError22 extends SkalexError22{}class TransactionError22 extends SkalexError22{}class PersistenceError22 extends SkalexError22{}class AdapterError22 extends SkalexError22{}class QueryError22 extends SkalexError22{}function deepEqual22(a,b){if(a===b)return!0;if(a==null||b==null)return!1;if(typeof a!==typeof b)return!1;if(a instanceof Date&&b instanceof Date)return a.getTime()===b.getTime();if(a instanceof RegExp&&b instanceof RegExp)return a.source===b.source&&a.flags===b.flags;if(Array.isArray(a)){if(!Array.isArray(b)||a.length!==b.length)return!1;for(let i=0;i<a.length;i++)if(!deepEqual22(a[i],b[i]))return!1;return!0}if(typeof a==="object"){if(Array.isArray(b))return!1;let keysA=Object.keys(a);if(keysA.length!==Object.keys(b).length)return!1;for(let k of keysA){if(!Object.prototype.hasOwnProperty.call(b,k))return!1;if(!deepEqual22(a[k],b[k]))return!1}return!0}return!1}function matchesFilter22(item,filter){if(typeof filter==="function")return filter(item);if(filter==null)return!0;if(typeof filter==="object"&&Object.keys(filter).length===0)return!0;if("$or"in filter){let branches=filter.$or;if(!Array.isArray(branches))throw new QueryError22("ERR_SKALEX_QUERY_INVALID_OPERATOR","$or must be an array of filters",{operator:"$or"});if(!branches.some((sub)=>matchesFilter22(item,sub)))return!1}if("$and"in filter){let branches=filter.$and;if(!Array.isArray(branches))throw new QueryError22("ERR_SKALEX_QUERY_INVALID_OPERATOR","$and must be an array of filters",{operator:"$and"});if(!branches.every((sub)=>matchesFilter22(item,sub)))return!1}if("$not"in filter){if(matchesFilter22(item,filter.$not))return!1}for(let key in filter){if(key==="$or"||key==="$and"||key==="$not")continue;let filterValue=filter[key],itemValue;try{itemValue=resolveDotPath22(item,key)}catch{return!1}if(filterValue instanceof RegExp){if(!filterValue.test(String(itemValue)))return!1}else if(typeof filterValue==="object"&&filterValue!==null){if(Object.keys(filterValue).some((k)=>k.startsWith("$"))){if("$eq"in filterValue&&itemValue!==filterValue.$eq)return!1;if("$ne"in filterValue&&itemValue===filterValue.$ne)return!1;if("$gt"in filterValue&&!(itemValue>filterValue.$gt))return!1;if("$lt"in filterValue&&!(itemValue<filterValue.$lt))return!1;if("$gte"in filterValue&&!(itemValue>=filterValue.$gte))return!1;if("$lte"in filterValue&&!(itemValue<=filterValue.$lte))return!1;if("$in"in filterValue&&!filterValue.$in.includes(itemValue))return!1;if("$nin"in filterValue&&filterValue.$nin.includes(itemValue))return!1;if("$regex"in filterValue){if(!(filterValue.$regex instanceof RegExp?filterValue.$regex:new RegExp(filterValue.$regex)).test(String(itemValue)))return!1}if("$fn"in filterValue&&!filterValue.$fn(itemValue))return!1}else if(!deepEqual22(itemValue,filterValue))return!1}else if(itemValue!==filterValue)return!1}return!0}function presortFilter22(filter,indexedFields=new Set){if(typeof filter!=="object"||filter===null||typeof filter==="function")return filter;let indexed=[],equality=[],range=[],expensive=[],logical=[];for(let key in filter){if(key==="$or"||key==="$and"||key==="$not"){logical.push(key);continue}let val=filter[key];if(indexedFields.has(key))indexed.push(key);else if(val instanceof RegExp||typeof val==="object"&&val!==null&&(("$regex"in val)||("$fn"in val))||typeof val==="function")expensive.push(key);else if(typeof val==="object"&&val!==null&&(("$gt"in val)||("$lt"in val)||("$gte"in val)||("$lte"in val)||("$ne"in val)||("$in"in val)||("$nin"in val)))range.push(key);else equality.push(key)}let sorted={};for(let k of[...indexed,...equality,...range,...expensive,...logical])sorted[k]=filter[k];return sorted}var SUPPORTED_TYPES22=new Set(["string","number","boolean","object","array","date","any"]);function typeOf22(val){if(Array.isArray(val))return"array";if(val instanceof Date)return"date";return typeof val}function parseSchema22(schema){let fields=new Map,uniqueFields=[];for(let[key,def]of Object.entries(schema)){let fieldDef;if(typeof def==="string"){if(!SUPPORTED_TYPES22.has(def))throw new ValidationError22("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${def}" for field "${key}"`,{field:key,type:def});fieldDef={type:def,required:!1,unique:!1}}else if(typeof def==="object"&&def!==null){let{type="any",required=!1,unique=!1,enum:enumVals}=def;if(!SUPPORTED_TYPES22.has(type))throw new ValidationError22("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${type}" for field "${key}"`,{field:key,type});if(fieldDef={type,required,unique,enum:enumVals},unique)uniqueFields.push(key)}else throw new ValidationError22("ERR_SKALEX_VALIDATION_INVALID_SCHEMA",`Invalid schema definition for field "${key}"`,{field:key});fields.set(key,fieldDef)}return{fields,uniqueFields}}function validateDoc22(doc,fields,strict=!1){let errors=[];for(let[key,def]of fields){let val=doc[key],missing=val===void 0||val===null;if(def.required&&missing){errors.push(`Field "${key}" is required`);continue}if(missing)continue;if(def.type!=="any"){let actualType=typeOf22(val);if(actualType!==def.type)errors.push(`Field "${key}" must be of type "${def.type}", got "${actualType}"`)}if(def.enum&&!def.enum.includes(val))errors.push(`Field "${key}" must be one of [${def.enum.map((v)=>JSON.stringify(v)).join(", ")}], got ${JSON.stringify(val)}`)}if(strict){for(let key of Object.keys(doc))if(!key.startsWith("_")&&!fields.has(key))errors.push(`Unknown field "${key}" (strict mode)`)}return errors}function stripInvalidFields22(doc,fields){let out={};for(let[key,val]of Object.entries(doc)){if(key.startsWith("_")){out[key]=val;continue}if(!fields.has(key))continue;let def=fields.get(key);if(def.type!=="any"){if(typeOf22(val)!==def.type)continue}if(def.enum&&!def.enum.includes(val))continue;out[key]=val}return out}function inferSchema22(doc){let schema={};for(let[key,val]of Object.entries(doc)){if(key.startsWith("_"))continue;let t=typeOf22(val);schema[key]=SUPPORTED_TYPES22.has(t)?t:"any"}return schema}function parseTtl22(ttl){if(typeof ttl==="number"){if(ttl<=0)throw new ValidationError22("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got ${ttl}`,{ttl});return ttl*1000}if(typeof ttl!=="string")throw new ValidationError22("ERR_SKALEX_VALIDATION_TTL",`Invalid TTL value: ${ttl}`,{ttl});let match=ttl.match(/^(\d+(?:\.\d+)?)(ms|s|m|h|d)$/);if(!match)throw new ValidationError22("ERR_SKALEX_VALIDATION_TTL_FORMAT",`Invalid TTL format: "${ttl}". Use e.g. 300 (seconds), "30m", "24h", "7d"`,{ttl});let val=parseFloat(match[1]);if(val<=0)throw new ValidationError22("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got "${ttl}"`,{ttl});let unit=match[2],ms=val*{ms:1,s:1000,m:60000,h:3600000,d:86400000}[unit];if(!isFinite(ms))throw new ValidationError22("ERR_SKALEX_VALIDATION_TTL",`TTL value "${ttl}" is too large`,{ttl});return ms}function computeExpiry22(ttl){return new Date(Date.now()+parseTtl22(ttl))}function sweep22(data,idIndex,removeFromIndexes=null){let now=Date.now(),removed=0,i=data.length;while(i--){let doc=data[i];if(doc._expiresAt&&new Date(doc._expiresAt).getTime()<=now){if(data.splice(i,1),idIndex.delete(doc._id),removeFromIndexes)removeFromIndexes(doc);removed++}}return removed}function cosineSimilarity22(a,b){if(a.length!==b.length)throw new QueryError22("ERR_SKALEX_QUERY_VECTOR_MISMATCH",`Vector dimension mismatch: ${a.length} vs ${b.length}`,{expected:a.length,got:b.length});let dot=0,magA=0,magB=0;for(let i=0;i<a.length;i++)dot+=a[i]*b[i],magA+=a[i]*a[i],magB+=b[i]*b[i];let denom=Math.sqrt(magA*magB);return denom===0?0:dot/denom}function stripVector22(doc){if(!("_vector"in doc))return{...doc};let{_vector,...rest}=doc;return rest}function count22(docs){return docs.length}function sum22(docs,field){let total=0;for(let doc of docs){let val=resolveDotPath22(doc,field);if(typeof val==="number"&&!isNaN(val))total+=val}return total}function avg22(docs,field){let total=0,n=0;for(let doc of docs){let val=resolveDotPath22(doc,field);if(typeof val==="number"&&!isNaN(val))total+=val,n++}return n===0?null:total/n}function groupBy22(docs,field){let groups=Object.create(null);for(let doc of docs){let key=String(resolveDotPath22(doc,field)??"__null__");if(!groups[key])groups[key]=[];groups[key].push(doc)}return groups}class MutationPipeline22{constructor(collection){this._col=collection}get _ctx(){return this._col._ctx}async execute({op,beforeHook,afterHook,hookPayload,mutate,afterHookPayload,save,session}){let ctx=this._ctx;await ctx.ensureConnected(),this._col._txSnapshotIfNeeded();let txm=ctx.txManager,isTxWrite=txm.active&&this._col._activeTxId===txm.context?.id,entryTxId=isTxWrite?txm.context.id:null,collTxId=this._col._createdInTxId,assertTxAlive=()=>{if(entryTxId!==null&&txm._abortedIds.has(entryTxId))throw new TransactionError22("ERR_SKALEX_TX_ABORTED",`Transaction ${entryTxId} was aborted. No further mutations allowed.`);if(collTxId!==null&&txm._abortedIds.has(collTxId))throw new TransactionError22("ERR_SKALEX_TX_ABORTED",`Transaction ${collTxId} was aborted. Collection obtained inside that transaction cannot be used for further mutations.`)};if(isTxWrite||collTxId!==null)assertTxAlive();if(beforeHook)await ctx.plugins.run(beforeHook,hookPayload);let{docs,prevDocs=[]}=await mutate(assertTxAlive);if(ctx.persistence.markDirty(ctx.collections,this._col.name),await this._col._saveIfNeeded(save),this._col._changelogEnabled)for(let i=0;i<docs.length;i++)await ctx.logChange(op,this._col.name,docs[i],prevDocs[i]??null,session||null);if(!isTxWrite||!txm.defer(()=>ctx.sessionStats.recordWrite(session)))ctx.sessionStats.recordWrite(session);for(let doc of docs)ctx.emitEvent(this._col.name,{op,collection:this._col.name,doc:stripVector22(doc)});if(afterHook)if(afterHookPayload)await ctx.runAfterHook(afterHook,afterHookPayload(docs));else for(let doc of docs)await ctx.runAfterHook(afterHook,{collection:this._col.name,doc:stripVector22(doc)});return{docs,prevDocs}}}function resolveFilterToValues22(filter){let resolved={};for(let key in filter){if(key.startsWith("$"))continue;let val=filter[key];if(val&&typeof val==="object"&&!Array.isArray(val)){let keys=Object.keys(val);if(keys.length===1&&keys[0]==="$eq")resolved[key]=val.$eq}else resolved[key]=val}return resolved}var _DANGEROUS_KEYS22=new Set(["__proto__","constructor","prototype"]);function stripDangerousKeys22(val){if(typeof val!=="object"||val===null||Array.isArray(val))return val;let out={};for(let k of Object.keys(val)){if(_DANGEROUS_KEYS22.has(k))continue;out[k]=stripDangerousKeys22(val[k])}return out}class Collection22{constructor(collectionData,database){this.name=collectionData.collectionName,this.database=database,this._ctx=database._buildCollectionContext(),this._store=collectionData,this._pipeline=new MutationPipeline22(this),this._createdInTxId=database._txManager.context?.id??null,this._activeTxId=null}get _data(){return this._store.data}set _data(val){this._store.data=val}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(item,options={}){let{save,ifNotExists,ttl,embed,session}=options;if(ifNotExists){await this._ctx.ensureConnected();let existing=this._findRaw(item);if(existing)return stripVector22({...existing})}let{docs}=await this._insertCore([item],{ttl,embed,session,save});return stripVector22(docs[0])}async insertMany(items,options={}){let{save,ttl,embed,session}=options,{docs}=await this._insertCore(items,{ttl,embed,session,save});return docs.map(stripVector22)}async _insertCore(items,{ttl,embed,session,save}){return this._pipeline.execute({op:"insert",beforeHook:null,afterHook:"afterInsert",hookPayload:null,save,session,mutate:async(assertTxAlive)=>{let newItems=[],batchIds=new Set;for(let item of items){let validated=this._applyValidation(item);await this._ctx.plugins.run("beforeInsert",{collection:this.name,doc:validated});let newItem=await this._buildDoc(validated,{ttl,embed});if(this._index.has(newItem._id)||batchIds.has(newItem._id))throw new UniqueConstraintError22("ERR_SKALEX_UNIQUE_DUPLICATE_ID",`Duplicate _id "${newItem._id}" in collection "${this.name}"`,{id:newItem._id,collection:this.name});batchIds.add(newItem._id),newItems.push(newItem)}if(assertTxAlive(),this._fieldIndex)this._fieldIndex.assertUniqueBatch(newItems);for(let newItem of newItems)this._addToIndex(newItem);this._data.push(...newItems);for(let newItem of newItems)this._index.set(newItem._id,newItem);return this._enforceCapAfterInsert(),{docs:newItems}}})}async updateOne(filter,update,options={}){await this._ctx.ensureConnected();let oldDoc=this._findRaw(filter);if(!oldDoc)return null;let{save,session}=options,{docs}=await this._updateCore([oldDoc],filter,update,{save,session});return stripVector22(docs[0])}async updateMany(filter,update,options={}){await this._ctx.ensureConnected();let oldDocs=this._findAllRaw(filter);if(oldDocs.length===0)return[];let{save,session}=options,{docs}=await this._updateCore(oldDocs,filter,update,{save,session});return docs.map(stripVector22)}async _updateCore(oldDocs,filter,update,{save,session}){return this._pipeline.execute({op:"update",beforeHook:"beforeUpdate",afterHook:"afterUpdate",hookPayload:{collection:this.name,filter,update},save,session,afterHookPayload:(docs)=>({collection:this.name,filter,update,result:docs.length===1?docs[0]:docs}),mutate:async(assertTxAlive)=>{let prevDocs=this._changelogEnabled?oldDocs.map((doc)=>structuredClone(doc)):oldDocs.map(()=>null),nextDocs=oldDocs.map((doc)=>this._prepareUpdatedDoc(doc,update));this._assertUniqueCandidates(oldDocs,nextDocs),assertTxAlive();let targets=new Set(oldDocs),positions=new Map;for(let i=0;i<this._data.length;i++)if(targets.has(this._data[i]))positions.set(this._data[i],i);for(let i=0;i<oldDocs.length;i++)this._commitUpdatedDoc(oldDocs[i],nextDocs[i],positions);return{docs:nextDocs,prevDocs}}})}applyUpdate(item,update){for(let field in update){if(_DANGEROUS_KEYS22.has(field))continue;if(field==="_id"||field==="createdAt")continue;let updateValue=update[field];if(Array.isArray(updateValue))item[field]=updateValue;else if(typeof updateValue==="object"&&updateValue!==null){let keys=Object.keys(updateValue);if(keys.some((k)=>k.startsWith("$"))){for(let key of keys)if(key==="$inc"&&typeof item[field]==="number")item[field]+=updateValue[key];else if(key==="$push"){if(!Array.isArray(item[field]))item[field]=[];item[field].push(updateValue[key])}}else item[field]=stripDangerousKeys22(updateValue)}else item[field]=updateValue}if(item.updatedAt=new Date,this._versioning)item._version=(item._version??0)+1;return item}_prepareUpdatedDoc(currentDoc,update){let prev=structuredClone(currentDoc),next=structuredClone(currentDoc);if(this.applyUpdate(next,update),!this._schema)return next;let errors=validateDoc22(next,this._schema,this._strict);if(!errors.length)return next;switch(this._onSchemaError){case"throw":throw new ValidationError22("ERR_SKALEX_VALIDATION_UPDATE",`Update validation failed on doc "${currentDoc._id}": ${errors.join("; ")}`,{id:currentDoc._id,errors});case"strip":return this._stripCandidateToValid(next,prev);default:return this._ctx.logger(`[${this.name}] Update validation warning: ${errors.join("; ")}`,"warn"),next}}_stripCandidateToValid(next,prev){let stripped=stripInvalidFields22(next,this._schema),merged=structuredClone(prev);for(let[key,val]of Object.entries(stripped)){if(key.startsWith("_"))continue;merged[key]=val}if(merged.updatedAt=next.updatedAt,this._versioning)merged._version=next._version;return merged}_commitUpdatedDoc(oldDoc,newDoc,positions){let idx=positions?positions.get(oldDoc):this._data.indexOf(oldDoc);if(idx===void 0||idx===-1)throw new PersistenceError22("ERR_SKALEX_PERSISTENCE_DOC_MISSING",`Document "${oldDoc._id}" no longer exists in collection "${this.name}"`,{id:oldDoc._id,collection:this.name});this._data[idx]=newDoc,this._index.set(newDoc._id,newDoc),this._updateInIndex(oldDoc,newDoc)}_assertUniqueCandidates(oldDocs,nextDocs){this._fieldIndex?.assertUniqueCandidates(oldDocs,nextDocs)}async upsert(filter,doc,options={}){if(await this._ctx.ensureConnected(),this._findRaw(filter))return this.updateOne(filter,doc,options);return this.insertOne({...resolveFilterToValues22(filter),...doc},options)}async upsertMany(docs,matchKey,options={}){await this._ctx.ensureConnected();let{save,...rest}=options,results=[];for(let doc of docs)results.push(await this.upsert({[matchKey]:doc[matchKey]},doc,{...rest,save:!1}));return await this._saveIfNeeded(save),results}async restore(filter,options={}){if(!this._softDelete)throw new QueryError22("ERR_SKALEX_QUERY_SOFT_DELETE_REQUIRED",`restore() requires softDelete on "${this.name}"`,{collection:this.name});await this._ctx.ensureConnected();let{save,session}=options,item=this._findRaw(filter,{includeDeleted:!0});if(!item||!item._deletedAt)return null;let{docs}=await this._pipeline.execute({op:"restore",beforeHook:null,afterHook:null,hookPayload:null,save,session,mutate:async(assertTxAlive)=>{return assertTxAlive(),delete item._deletedAt,item.updatedAt=new Date,this._index.set(item._id,item),{docs:[item]}}});return stripVector22(docs[0])}watch(filter,callback){if(typeof filter==="function")callback=filter,filter=null;if(callback)return this._ctx.eventBus.on(this.name,(event)=>{if(!filter||matchesFilter22(event.doc,filter))callback(event)});return this._watchIterator(filter)}_watchIterator(filter){let queue=[],resolve=null,done=!1,unsub=this._ctx.eventBus.on(this.name,(event)=>{if(filter&&!matchesFilter22(event.doc,filter))return;if(resolve){let r=resolve;resolve=null,r({value:event,done:!1})}else queue.push(event)});return{[Symbol.asyncIterator](){return this},next(){if(queue.length>0)return Promise.resolve({value:queue.shift(),done:!1});if(done)return Promise.resolve({value:void 0,done:!0});return new Promise((res)=>{resolve=res})},return(){if(done=!0,unsub(),resolve){let r=resolve;resolve=null,r({value:void 0,done:!0})}return Promise.resolve({value:void 0,done:!0})}}}async count(filter={}){return await this._ctx.ensureConnected(),count22(this._findAllRaw(filter))}async sum(field,filter={}){return await this._ctx.ensureConnected(),sum22(this._findAllRaw(filter),field)}async avg(field,filter={}){return await this._ctx.ensureConnected(),avg22(this._findAllRaw(filter),field)}async groupBy(field,filter={}){return await this._ctx.ensureConnected(),groupBy22(this._findAllRaw(filter),field)}async findOne(filter,options={}){await this._ctx.ensureConnected();let{populate,select,includeDeleted=!1}=options,item=this._findRaw(filter,{includeDeleted});if(!item)return null;let newItem=this._projectDoc(item,select);if(populate)await this._populateDoc(newItem,item,populate);return newItem}async find(filter,options={}){await this._ctx.ensureConnected();let _t0=Date.now(),{populate,select,sort,page=1,limit,session,includeDeleted=!1}=options;await this._ctx.plugins.run("beforeFind",{collection:this.name,filter,options});let candidates=this._getCandidates(filter),sortedFilter=presortFilter22(filter,this._fieldIndex?this._fieldIndex.indexedFields:new Set),results=[];for(let item of candidates){if(this._softDelete&&item._deletedAt&&!includeDeleted)continue;if(!matchesFilter22(item,sortedFilter))continue;let newItem=this._projectDoc(item,select);if(populate)await this._populateDoc(newItem,item,populate);results.push(newItem)}if(sort){let sortFields=Object.keys(sort);results.sort((a,b)=>{for(let field of sortFields){let dir=sort[field];if(a[field]<b[field])return-dir;if(a[field]>b[field])return dir}return 0})}let extra;if(limit){let totalDocs=results.length,totalPages=Math.ceil(totalDocs/limit),startIndex=(page-1)*limit;results=results.slice(startIndex,startIndex+limit),extra={page,totalDocs,totalPages}}return this._ctx.queryLog?.record({collection:this.name,op:"find",filter,duration:Date.now()-_t0,resultCount:results.length}),this._ctx.sessionStats.recordRead(session),await this._ctx.plugins.run("afterFind",{collection:this.name,filter,options,docs:results}),extra?{docs:results,...extra}:{docs:results}}async search(query,{filter,limit=10,minScore=0,session}={}){await this._ctx.ensureConnected();let _t0=Date.now();await this._ctx.plugins.run("beforeSearch",{collection:this.name,query,options:{filter,limit,minScore}});let queryVector=await this._ctx.embed(query),candidates=filter?this._findAllRaw(filter):this._data,scored=[];for(let doc of candidates){if(!doc._vector)continue;let score=cosineSimilarity22(queryVector,doc._vector);if(score>=minScore)scored.push({doc,score})}scored.sort((a,b)=>b.score-a.score);let top=scored.slice(0,limit);this._ctx.queryLog?.record({collection:this.name,op:"search",query,duration:Date.now()-_t0,resultCount:top.length}),this._ctx.sessionStats.recordRead(session);let docs=top.map((r)=>stripVector22(r.doc)),scores=top.map((r)=>r.score);return await this._ctx.plugins.run("afterSearch",{collection:this.name,query,options:{filter,limit,minScore},docs,scores}),{docs,scores}}async similar(id,{limit=10,minScore=0}={}){await this._ctx.ensureConnected();let source=this._index.get(id);if(!source||!source._vector)return{docs:[],scores:[]};let scored=[];for(let doc of this._data){if(doc._id===id||!doc._vector)continue;let score=cosineSimilarity22(source._vector,doc._vector);if(score>=minScore)scored.push({doc,score})}scored.sort((a,b)=>b.score-a.score);let top=scored.slice(0,limit);return{docs:top.map((r)=>stripVector22(r.doc)),scores:top.map((r)=>r.score)}}async deleteOne(filter,options={}){await this._ctx.ensureConnected();let{save,session}=options;if(this._softDelete){let item=this._findRaw(filter);if(!item)return null;let{docs:docs2}=await this._deleteCore("soft",[item],filter,{save,session});return stripVector22(docs2[0])}let{docs}=await this._deleteCore("hard",null,filter,{save,session});if(docs.length===0)return null;return stripVector22(docs[0])}async deleteMany(filter,options={}){await this._ctx.ensureConnected();let{save,session}=options;if(this._softDelete){let items=this._findAllRaw(filter);if(items.length===0)return[];let{docs:docs2}=await this._deleteCore("soft",items,filter,{save,session});return docs2.map(stripVector22)}let{docs}=await this._deleteCore("hardMany",null,filter,{save,session});return docs.map(stripVector22)}async _deleteCore(mode,items,filter,{save,session}){return this._pipeline.execute({op:"delete",beforeHook:"beforeDelete",afterHook:"afterDelete",hookPayload:{collection:this.name,filter},save,session,afterHookPayload:(docs)=>({collection:this.name,filter,result:docs.length===1?docs[0]:docs}),mutate:async(assertTxAlive)=>{if(assertTxAlive(),mode==="soft"){let now=new Date;for(let item of items)item._deletedAt=now,item.updatedAt=now,this._index.set(item._id,item);return{docs:items}}if(mode==="hard"){let idx=this._findIndex(filter);if(idx===-1)return{docs:[]};let deletedItem=this._data.splice(idx,1)[0];return this._index.delete(deletedItem._id),this._removeFromIndex(deletedItem),{docs:[deletedItem]}}let deletedItems=[],remainingItems=[];for(let item of this._data)if(matchesFilter22(item,filter))deletedItems.push(item),this._index.delete(item._id),this._removeFromIndex(item);else remainingItems.push(item);return this._data=remainingItems,{docs:deletedItems}}})}async export(filter={},options={}){let{dir,name,format="json"}=options;try{let filteredData=this._data.filter((item)=>matchesFilter22(item,filter));if(filteredData.length===0)throw new QueryError22("ERR_SKALEX_QUERY_EXPORT_EMPTY",`export(): no documents matched the filter in "${this.name}"`,{collection:this.name});let content;if(format==="json")content=JSON.stringify(filteredData,null,2);else{let escapeCsv=(v)=>{if(v==null)return"";let s=typeof v==="object"?JSON.stringify(v):String(v);return s.includes(",")||s.includes('"')||s.includes(`
55
+ `))!==-1){let line=this._buffer.slice(0,idx).trim();if(this._buffer=this._buffer.slice(idx+1),line&&this._onMessage){let msg;try{msg=JSON.parse(line)}catch(_){this.send(error2(null,PARSE_ERROR2,"Parse error"));continue}this._onMessage(msg).catch(()=>{})}}}),process.stdin.on("end",()=>{process.exit(0)})}stop(){process.stdin.removeAllListeners("data"),process.stdin.removeAllListeners("end"),this._started=!1}}var SERVER_INFO2={name:"skalex",version:"4.0.0-alpha"},PROTOCOL_VERSION2="2024-11-05";class SkalexMCPServer2{constructor(db,opts={}){this._db=db,this._transport=opts.transport||"stdio",this._port=opts.port||3000,this._host=opts.host||"127.0.0.1",this._allowedOrigin=opts.allowedOrigin??null,this._maxBodySize=opts.maxBodySize??1048576,this._scopes=opts.scopes||{"*":["read"]},this._t=null}async listen(){if(this._transport==="http")this._t=new HttpTransport2({port:this._port,host:this._host,allowedOrigin:this._allowedOrigin,maxBodySize:this._maxBodySize});else this._t=new StdioTransport2;this._t.onMessage((msg)=>this._handleMessage(msg)),await this._t.start()}async connect(transport){if(this._t=transport,this._t.onMessage((msg)=>this._handleMessage(msg)),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(raw){let{msg,parseError}=typeof raw==="string"?parse2(raw):{msg:raw};if(parseError){this._send(parseError);return}let{id,method,params}=msg;if(id===void 0){if(method==="notifications/initialized")return;return}try{switch(method){case"initialize":this._send(ok2(id,{protocolVersion:PROTOCOL_VERSION2,capabilities:{tools:{}},serverInfo:SERVER_INFO2}));break;case"tools/list":this._send(ok2(id,{tools:this._visibleTools()}));break;case"tools/call":await this._handleToolCall(id,params);break;case"ping":this._send(ok2(id,{}));break;default:this._send(error2(id,METHOD_NOT_FOUND2,`Method not found: ${method}`))}}catch(err){this._send(error2(id,INTERNAL_ERROR2,err.message||"Internal error"))}}async _handleToolCall(id,params){let name=params?.name,args=params?.arguments??{};if(!name){this._send(error2(id,INVALID_PARAMS2,"tools/call requires params.name"));return}let def=TOOL_DEFS2.find((t)=>t.name===name);if(!def){this._send(error2(id,METHOD_NOT_FOUND2,`Unknown tool: ${name}`));return}let collection=args.collection||args.collection_name||null;if(!this._hasScope(collection,def.scope)){this._send(ok2(id,toolError2(`Access denied: "${name}" requires "${def.scope}" scope on collection "${collection}".`)));return}try{let result=await callTool2(name,args,this._db);this._send(ok2(id,toolResult2(JSON.stringify(result,null,2))))}catch(err){this._send(ok2(id,toolError2(err.message||String(err))))}}_visibleTools(){return TOOL_DEFS2.filter((def)=>{let global=this._scopes["*"];if(global&&(global.includes(def.scope)||global.includes("admin")))return!0;for(let[,perms]of Object.entries(this._scopes))if(perms.includes(def.scope)||perms.includes("admin"))return!0;return!1})}_hasScope(collection,scope){let check=(perms)=>perms.includes("admin")||perms.includes(scope);if(collection&&this._scopes[collection])return check(this._scopes[collection]);if(this._scopes["*"])return check(this._scopes["*"]);return!1}_send(msg){this._t?.send(msg)}}var META_KEY2="migrations",_serialize2=(value)=>JSON.stringify(value,function(key,v){let raw=this[key];if(raw instanceof Date)return{__skalex_date__:raw.toISOString()};if(typeof v==="bigint")return{__skalex_bigint__:v.toString()};return v}),_deserialize2=(text)=>JSON.parse(text,(_,v)=>{if(v&&typeof v==="object"){if("__skalex_bigint__"in v)return BigInt(v.__skalex_bigint__);if("__skalex_date__"in v)return new Date(v.__skalex_date__)}return v});class Skalex2{constructor({path="./.db",format="gz",debug=!1,adapter,ai,encrypt,slowQueryLog,queryCache,memory,logger:logger$1,plugins,llmAdapter,embeddingAdapter,regexMaxLength,idGenerator,serializer,deserializer,autoSave,ttlSweepInterval,lenientLoad}={}){if(this.dataDirectory=path,this.dataFormat=format,this.debug=debug,!Skalex2._errorsAttached)Skalex2.SkalexError=SkalexError2,Skalex2.ValidationError=ValidationError2,Skalex2.UniqueConstraintError=UniqueConstraintError2,Skalex2.TransactionError=TransactionError2,Skalex2.PersistenceError=PersistenceError2,Skalex2.AdapterError=AdapterError2,Skalex2.QueryError=QueryError2,Skalex2._errorsAttached=!0;this._adapterConfig=adapter??null;let fs=adapter||new FsAdapter2({dir:path,format});if(encrypt)fs=new EncryptedAdapter2(fs,encrypt.key);if(this.fs=fs,this._registry=new CollectionRegistry2(Collection2),this.collections=this._registry.stores,this._collectionInstances=this._registry._instances,this._migrations=new MigrationEngine2,this._connectPromise=null,this.isConnected=!1,this._aiConfig=ai||null,this._encryptConfig=encrypt||null,this._pluginsConfig=Array.isArray(plugins)?plugins:null,this._memoryConfig=memory||null,this._regexMaxLength=regexMaxLength??500,this._idGenerator=idGenerator??null,this._serializer=serializer??_serialize2,this._deserializer=deserializer??_deserialize2,this._autoSave=autoSave??!1,this._txManager=new TransactionManager2,this._ttlSweepInterval=ttlSweepInterval??0,this._ttlTimer=null,this._logger=logger$1??logger2,this._embeddingAdapter=embeddingAdapter??(ai?createEmbeddingAdapter2(ai):null),this._aiAdapter=llmAdapter??(ai?createLLMAdapter2(ai):null),this._persistence=new PersistenceManager2({adapter:this.fs,serializer:this._serializer,deserializer:this._deserializer,logger:this._logger,debug:this.debug,lenientLoad:lenientLoad??!1}),this._changeLog=new ChangeLog2(this),this._queryCache=new QueryCache2(queryCache||{}),this._eventBus=new EventBus2,this._queryLog=slowQueryLog?new QueryLog2(slowQueryLog):null,this._sessionStats=new SessionStats2,this._plugins=new PluginEngine2,Array.isArray(plugins))for(let p of plugins)this._plugins.register(p)}async connect(){if(this._connectPromise)return this._connectPromise;return this._connectPromise=this._doConnect(),this._connectPromise}async _doConnect(){try{await this.loadData();let meta=this._getMeta();if(meta.queryCache)this._queryCache.fromJSON(meta.queryCache);if(this._migrations._migrations.length>0){let applied=meta.appliedVersions||[],newApplied=await this._migrations.run((version)=>this.useCollection(`_migration_${version}`),applied);this._saveMeta({appliedVersions:newApplied})}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(error22){throw this._logger(`Error connecting to the database: ${error22}`,"error"),error22}}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(error22){throw this._logger(`Error disconnecting from the database: ${error22}`,"error"),error22}}async _ensureConnected(){if(this.isConnected)return;return this.connect()}useCollection(collectionName){return this._registry.get(collectionName,this)}createCollection(collectionName,options={}){return this._registry.create(collectionName,options,this)}_createCollectionStore(collectionName,options={}){this._registry.createStore(collectionName,options)}async renameCollection(from,to){this._registry.rename(from,to),await this.saveData(to),await this.fs.delete(from)}async loadData(){await this._persistence.loadAll(this.collections,{parseSchema:parseSchema2,buildIndex:this._registry.buildIndex,IndexEngine:IndexEngine2});for(let name in this._collectionInstances){let store=this.collections[name];if(store&&this._collectionInstances[name]._store!==store)this._collectionInstances[name]._store=store}}async saveData(collectionName){await this._persistence.save(this.collections,collectionName)}buildIndex(data,keyField){return this._registry.buildIndex(data,keyField)}addMigration(migration){this._migrations.add(migration)}migrationStatus(){let meta=this._getMeta();return this._migrations.status(meta.appliedVersions||[])}namespace(id){if(this._adapterConfig)throw new AdapterError2("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 safeId=String(id).replace(/[^a-zA-Z0-9_-]/g,"_");if(!safeId)throw new ValidationError2("ERR_SKALEX_VALIDATION_NAMESPACE_ID","namespace: id must contain at least one alphanumeric character",{id});return new Skalex2({path:`${this.dataDirectory}/${safeId}`,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!==logger2?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!==_serialize2?this._serializer:void 0,deserializer:this._deserializer!==_deserialize2?this._deserializer:void 0,autoSave:this._autoSave||void 0,ttlSweepInterval:this._ttlSweepInterval||void 0})}use(plugin){this._plugins.register(plugin)}watch(callback){return this._eventBus.on("*",callback)}sessionStats(sessionId){if(sessionId!==void 0)return this._sessionStats.get(sessionId);return this._sessionStats.all()}get _inTransaction(){return this._txManager.active}_emitEvent(collectionName,data){if(!this._txManager.defer(()=>this._eventBus.emit(collectionName,data)))this._eventBus.emit(collectionName,data)}async _runAfterHook(hook,data){if(!this._txManager.defer(()=>this._plugins.run(hook,data)))await this._plugins.run(hook,data)}async _logChange(op,collectionName,doc,prev,session){if(!this._txManager.defer(()=>this._changeLog.log(op,collectionName,doc,prev,session)))await this._changeLog.log(op,collectionName,doc,prev,session)}async transaction(fn,opts={}){return this._txManager.run(fn,this,opts)}async seed(fixtures,{reset=!1}={}){for(let[name,docs]of Object.entries(fixtures)){if(reset&&this.collections[name])this._applySnapshot(name,{data:[],index:new Map}),delete this._collectionInstances[name];await this.useCollection(name).insertMany(docs)}await this.saveData()}dump(){return this._registry.dump()}inspect(collectionName){return this._registry.inspect(collectionName)}async import(filePath){let content=await this.fs.readRaw(filePath),docs;try{docs=JSON.parse(content)}catch{throw new PersistenceError2("ERR_SKALEX_PERSISTENCE_INVALID_JSON",`import: invalid JSON in file "${filePath}"`,{filePath})}let name=filePath.split("/").pop().replace(/\.[^.]+$/,"");return this.useCollection(name).insertMany(Array.isArray(docs)?docs:[docs],{save:!0})}async embed(text){if(!this._embeddingAdapter)throw new AdapterError2("ERR_SKALEX_ADAPTER_EMBEDDING_REQUIRED","db.embed() requires an AI adapter. Pass { ai: { provider, apiKey } } to the Skalex constructor.");return this._embeddingAdapter.embed(text)}async ask(collectionName,nlQuery,{limit=20}={}){if(!this._aiAdapter)throw new AdapterError2("ERR_SKALEX_ADAPTER_LLM_REQUIRED",'db.ask() requires a language model adapter. Configure { ai: { provider, model: "..." } }.');let col=this.useCollection(collectionName),schema=this.schema(collectionName),filter=this._queryCache.get(collectionName,schema,nlQuery);if(!filter){filter=await this._aiAdapter.generate(schema,nlQuery);let warnings=validateLLMFilter2(filter,schema);if(warnings.length)warnings.forEach((w)=>this._log(`[ask] ${w}`));this._queryCache.set(collectionName,schema,nlQuery,filter),this._saveMeta({queryCache:this._queryCache.toJSON()})}return col.find(processLLMFilter2(filter,{regexMaxLength:this._regexMaxLength}),{limit})}schema(collectionName){return this._registry.schema(collectionName)}useMemory(sessionId){return new Memory2(sessionId,this)}changelog(){return this._changeLog}async restore(collectionName,timestamp,opts={}){return this._changeLog.restore(collectionName,timestamp,opts)}stats(collectionName){return this._registry.stats(collectionName)}slowQueries(opts={}){if(!this._queryLog)return[];return this._queryLog.entries(opts)}slowQueryCount(){return this._queryLog?this._queryLog.size:0}clearSlowQueries(){this._queryLog?.clear()}mcp(opts={}){return new SkalexMCPServer2(this,opts)}_getMeta(){let metaCol=this.collections._meta;if(!metaCol)return{};return metaCol.index.get(META_KEY2)||{}}_saveMeta(data){if(!this.collections._meta)this._createCollectionStore("_meta");let col=this.collections._meta,existing=col.index.get(META_KEY2);if(existing)Object.assign(existing,data);else{let doc={_id:META_KEY2,...data};col.data.push(doc),col.index.set(META_KEY2,doc)}this._persistence.markDirty(this.collections,"_meta")}_sweepTtl(){for(let name in this.collections){let col=this.collections[name],removed=sweep2(col.data,col.index,col.fieldIndex?(doc)=>col.fieldIndex.remove(doc):null);if(removed>0)this._persistence.markDirty(this.collections,name),this._log(`TTL sweep: removed ${removed} expired docs from "${name}"`)}}_buildCollectionContext(){let db=this;return{ensureConnected:()=>db._ensureConnected(),get txManager(){return db._txManager},get plugins(){return db._plugins},get eventBus(){return db._eventBus},get sessionStats(){return db._sessionStats},get queryLog(){return db._queryLog},get logger(){return db._logger},get persistence(){return db._persistence},get collections(){return db.collections},embed:(text)=>db.embed(text),get idGenerator(){return db._idGenerator},get autoSave(){return db._autoSave},saveCollection:(name)=>db.saveData(name),snapshotCollection:(col)=>db._snapshotCollection(col),getCollection:(name)=>db.useCollection(name),emitEvent:(name,data)=>db._emitEvent(name,data),runAfterHook:(hook,data)=>db._runAfterHook(hook,data),logChange:(op,col,doc,prev,session)=>db._logChange(op,col,doc,prev,session),get fs(){return db.fs},get dataDirectory(){return db.dataDirectory}}}_log(msg){if(this.debug)this._logger(msg,"info")}_snapshotCollection(col){return{data:structuredClone(col.data)}}_applySnapshot(name,snap){let col=this.collections[name];if(!col)return;if(col.data=snap.data,col.index=this.buildIndex(snap.data,"_id"),col.fieldIndex)col.fieldIndex.buildFromData(snap.data)}}function generateUniqueId22(){let timestamp=Date.now().toString(16),random;try{random=nodeCrypto22.randomBytes(8).toString("hex")}catch{let arr=new Uint8Array(8);crypto.getRandomValues(arr),random=Array.from(arr).map((b)=>b.toString(16).padStart(2,"0")).join("")}return`${timestamp}${random}`}function logger22(error22,type){let msg=error22 instanceof Error?error22.message:error22;if(type==="error")console.error(msg);else console.log(msg)}var _FORBIDDEN_KEYS22=new Set(["__proto__","constructor","prototype"]);function resolveDotPath22(obj,path){if(!path.includes(".")){if(_FORBIDDEN_KEYS22.has(path))return;return obj[path]}let cur=obj;for(let p of path.split(".")){if(_FORBIDDEN_KEYS22.has(p))return;if(cur==null)return;cur=cur[p]}return cur}class SkalexError22 extends Error{constructor(code,message,details={}){super(message);this.name=this.constructor.name,this.code=code,this.details=details}}class ValidationError22 extends SkalexError22{}class UniqueConstraintError22 extends SkalexError22{}class TransactionError22 extends SkalexError22{}class PersistenceError22 extends SkalexError22{}class AdapterError22 extends SkalexError22{}class QueryError22 extends SkalexError22{}function deepEqual22(a,b){if(a===b)return!0;if(a==null||b==null)return!1;if(typeof a!==typeof b)return!1;if(a instanceof Date&&b instanceof Date)return a.getTime()===b.getTime();if(a instanceof RegExp&&b instanceof RegExp)return a.source===b.source&&a.flags===b.flags;if(Array.isArray(a)){if(!Array.isArray(b)||a.length!==b.length)return!1;for(let i=0;i<a.length;i++)if(!deepEqual22(a[i],b[i]))return!1;return!0}if(typeof a==="object"){if(Array.isArray(b))return!1;let keysA=Object.keys(a);if(keysA.length!==Object.keys(b).length)return!1;for(let k of keysA){if(!Object.prototype.hasOwnProperty.call(b,k))return!1;if(!deepEqual22(a[k],b[k]))return!1}return!0}return!1}function matchesFilter22(item,filter){if(typeof filter==="function")return filter(item);if(filter==null)return!0;if(typeof filter==="object"&&Object.keys(filter).length===0)return!0;if("$or"in filter){let branches=filter.$or;if(!Array.isArray(branches))throw new QueryError22("ERR_SKALEX_QUERY_INVALID_OPERATOR","$or must be an array of filters",{operator:"$or"});if(!branches.some((sub)=>matchesFilter22(item,sub)))return!1}if("$and"in filter){let branches=filter.$and;if(!Array.isArray(branches))throw new QueryError22("ERR_SKALEX_QUERY_INVALID_OPERATOR","$and must be an array of filters",{operator:"$and"});if(!branches.every((sub)=>matchesFilter22(item,sub)))return!1}if("$not"in filter){if(matchesFilter22(item,filter.$not))return!1}for(let key in filter){if(key==="$or"||key==="$and"||key==="$not")continue;let filterValue=filter[key],itemValue;try{itemValue=resolveDotPath22(item,key)}catch{return!1}if(filterValue instanceof RegExp){if(!filterValue.test(String(itemValue)))return!1}else if(typeof filterValue==="object"&&filterValue!==null){if(Object.keys(filterValue).some((k)=>k.startsWith("$"))){if("$eq"in filterValue&&itemValue!==filterValue.$eq)return!1;if("$ne"in filterValue&&itemValue===filterValue.$ne)return!1;if("$gt"in filterValue&&!(itemValue>filterValue.$gt))return!1;if("$lt"in filterValue&&!(itemValue<filterValue.$lt))return!1;if("$gte"in filterValue&&!(itemValue>=filterValue.$gte))return!1;if("$lte"in filterValue&&!(itemValue<=filterValue.$lte))return!1;if("$in"in filterValue&&!filterValue.$in.includes(itemValue))return!1;if("$nin"in filterValue&&filterValue.$nin.includes(itemValue))return!1;if("$regex"in filterValue){if(!(filterValue.$regex instanceof RegExp?filterValue.$regex:new RegExp(filterValue.$regex)).test(String(itemValue)))return!1}if("$fn"in filterValue&&!filterValue.$fn(itemValue))return!1}else if(!deepEqual22(itemValue,filterValue))return!1}else if(itemValue!==filterValue)return!1}return!0}function presortFilter22(filter,indexedFields=new Set){if(typeof filter!=="object"||filter===null||typeof filter==="function")return filter;let indexed=[],equality=[],range=[],expensive=[],logical=[];for(let key in filter){if(key==="$or"||key==="$and"||key==="$not"){logical.push(key);continue}let val=filter[key];if(indexedFields.has(key))indexed.push(key);else if(val instanceof RegExp||typeof val==="object"&&val!==null&&(("$regex"in val)||("$fn"in val))||typeof val==="function")expensive.push(key);else if(typeof val==="object"&&val!==null&&(("$gt"in val)||("$lt"in val)||("$gte"in val)||("$lte"in val)||("$ne"in val)||("$in"in val)||("$nin"in val)))range.push(key);else equality.push(key)}let sorted={};for(let k of[...indexed,...equality,...range,...expensive,...logical])sorted[k]=filter[k];return sorted}var SUPPORTED_TYPES22=new Set(["string","number","boolean","object","array","date","any"]);function typeOf22(val){if(Array.isArray(val))return"array";if(val instanceof Date)return"date";return typeof val}function parseSchema22(schema){let fields=new Map,uniqueFields=[];for(let[key,def]of Object.entries(schema)){let fieldDef;if(typeof def==="string"){if(!SUPPORTED_TYPES22.has(def))throw new ValidationError22("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${def}" for field "${key}"`,{field:key,type:def});fieldDef={type:def,required:!1,unique:!1}}else if(typeof def==="object"&&def!==null){let{type="any",required=!1,unique=!1,enum:enumVals}=def;if(!SUPPORTED_TYPES22.has(type))throw new ValidationError22("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${type}" for field "${key}"`,{field:key,type});if(fieldDef={type,required,unique,enum:enumVals},unique)uniqueFields.push(key)}else throw new ValidationError22("ERR_SKALEX_VALIDATION_INVALID_SCHEMA",`Invalid schema definition for field "${key}"`,{field:key});fields.set(key,fieldDef)}return{fields,uniqueFields}}function validateDoc22(doc,fields,strict=!1){let errors=[];for(let[key,def]of fields){let val=doc[key],missing=val===void 0||val===null;if(def.required&&missing){errors.push(`Field "${key}" is required`);continue}if(missing)continue;if(def.type!=="any"){let actualType=typeOf22(val);if(actualType!==def.type)errors.push(`Field "${key}" must be of type "${def.type}", got "${actualType}"`)}if(def.enum&&!def.enum.includes(val))errors.push(`Field "${key}" must be one of [${def.enum.map((v)=>JSON.stringify(v)).join(", ")}], got ${JSON.stringify(val)}`)}if(strict){for(let key of Object.keys(doc))if(!key.startsWith("_")&&!fields.has(key))errors.push(`Unknown field "${key}" (strict mode)`)}return errors}function stripInvalidFields22(doc,fields){let out={};for(let[key,val]of Object.entries(doc)){if(key.startsWith("_")){out[key]=val;continue}if(!fields.has(key))continue;let def=fields.get(key);if(def.type!=="any"){if(typeOf22(val)!==def.type)continue}if(def.enum&&!def.enum.includes(val))continue;out[key]=val}return out}function inferSchema22(doc){let schema={};for(let[key,val]of Object.entries(doc)){if(key.startsWith("_"))continue;let t=typeOf22(val);schema[key]=SUPPORTED_TYPES22.has(t)?t:"any"}return schema}function parseTtl22(ttl){if(typeof ttl==="number"){if(ttl<=0)throw new ValidationError22("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got ${ttl}`,{ttl});return ttl*1000}if(typeof ttl!=="string")throw new ValidationError22("ERR_SKALEX_VALIDATION_TTL",`Invalid TTL value: ${ttl}`,{ttl});let match=ttl.match(/^(\d+(?:\.\d+)?)(ms|s|m|h|d)$/);if(!match)throw new ValidationError22("ERR_SKALEX_VALIDATION_TTL_FORMAT",`Invalid TTL format: "${ttl}". Use e.g. 300 (seconds), "30m", "24h", "7d"`,{ttl});let val=parseFloat(match[1]);if(val<=0)throw new ValidationError22("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got "${ttl}"`,{ttl});let unit=match[2],ms=val*{ms:1,s:1000,m:60000,h:3600000,d:86400000}[unit];if(!isFinite(ms))throw new ValidationError22("ERR_SKALEX_VALIDATION_TTL",`TTL value "${ttl}" is too large`,{ttl});return ms}function computeExpiry22(ttl){return new Date(Date.now()+parseTtl22(ttl))}function sweep22(data,idIndex,removeFromIndexes=null){let now=Date.now(),removed=0,i=data.length;while(i--){let doc=data[i];if(doc._expiresAt&&new Date(doc._expiresAt).getTime()<=now){if(data.splice(i,1),idIndex.delete(doc._id),removeFromIndexes)removeFromIndexes(doc);removed++}}return removed}function cosineSimilarity22(a,b){if(a.length!==b.length)throw new QueryError22("ERR_SKALEX_QUERY_VECTOR_MISMATCH",`Vector dimension mismatch: ${a.length} vs ${b.length}`,{expected:a.length,got:b.length});let dot=0,magA=0,magB=0;for(let i=0;i<a.length;i++)dot+=a[i]*b[i],magA+=a[i]*a[i],magB+=b[i]*b[i];let denom=Math.sqrt(magA*magB);return denom===0?0:dot/denom}function stripVector22(doc){if(!("_vector"in doc))return{...doc};let{_vector,...rest}=doc;return rest}function count22(docs){return docs.length}function sum22(docs,field){let total=0;for(let doc of docs){let val=resolveDotPath22(doc,field);if(typeof val==="number"&&!isNaN(val))total+=val}return total}function avg22(docs,field){let total=0,n=0;for(let doc of docs){let val=resolveDotPath22(doc,field);if(typeof val==="number"&&!isNaN(val))total+=val,n++}return n===0?null:total/n}function groupBy22(docs,field){let groups=Object.create(null);for(let doc of docs){let key=String(resolveDotPath22(doc,field)??"__null__");if(!groups[key])groups[key]=[];groups[key].push(doc)}return groups}class MutationPipeline22{constructor(collection){this._col=collection}get _ctx(){return this._col._ctx}async execute({op,beforeHook,afterHook,hookPayload,mutate,afterHookPayload,save,session}){let ctx=this._ctx;await ctx.ensureConnected(),this._col._txSnapshotIfNeeded();let txm=ctx.txManager,isTxWrite=txm.active&&this._col._activeTxId===txm.context?.id,entryTxId=isTxWrite?txm.context.id:null,collTxId=this._col._createdInTxId,assertTxAlive=()=>{if(entryTxId!==null&&txm._abortedIds.has(entryTxId))throw new TransactionError22("ERR_SKALEX_TX_ABORTED",`Transaction ${entryTxId} was aborted. No further mutations allowed.`);if(collTxId!==null&&txm._abortedIds.has(collTxId))throw new TransactionError22("ERR_SKALEX_TX_ABORTED",`Transaction ${collTxId} was aborted. Collection obtained inside that transaction cannot be used for further mutations.`)};if(isTxWrite||collTxId!==null)assertTxAlive();if(beforeHook)await ctx.plugins.run(beforeHook,hookPayload);let{docs,prevDocs=[]}=await mutate(assertTxAlive);if(ctx.persistence.markDirty(ctx.collections,this._col.name),await this._col._saveIfNeeded(save),this._col._changelogEnabled)for(let i=0;i<docs.length;i++)await ctx.logChange(op,this._col.name,docs[i],prevDocs[i]??null,session||null);if(!isTxWrite||!txm.defer(()=>ctx.sessionStats.recordWrite(session)))ctx.sessionStats.recordWrite(session);for(let doc of docs)ctx.emitEvent(this._col.name,{op,collection:this._col.name,doc:stripVector22(doc)});if(afterHook)if(afterHookPayload)await ctx.runAfterHook(afterHook,afterHookPayload(docs));else for(let doc of docs)await ctx.runAfterHook(afterHook,{collection:this._col.name,doc:stripVector22(doc)});return{docs,prevDocs}}}function resolveFilterToValues22(filter){let resolved={};for(let key in filter){if(key.startsWith("$"))continue;let val=filter[key];if(val&&typeof val==="object"&&!Array.isArray(val)){let keys=Object.keys(val);if(keys.length===1&&keys[0]==="$eq")resolved[key]=val.$eq}else resolved[key]=val}return resolved}var _DANGEROUS_KEYS22=new Set(["__proto__","constructor","prototype"]);function stripDangerousKeys22(val){if(typeof val!=="object"||val===null||Array.isArray(val))return val;let out={};for(let k of Object.keys(val)){if(_DANGEROUS_KEYS22.has(k))continue;out[k]=stripDangerousKeys22(val[k])}return out}class Collection22{constructor(collectionData,database){this.name=collectionData.collectionName,this.database=database,this._ctx=database._buildCollectionContext(),this._store=collectionData,this._pipeline=new MutationPipeline22(this),this._createdInTxId=database._txManager.context?.id??null,this._activeTxId=null}get _data(){return this._store.data}set _data(val){this._store.data=val}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(item,options={}){let{save,ifNotExists,ttl,embed,session}=options;if(ifNotExists){await this._ctx.ensureConnected();let existing=this._findRaw(item);if(existing)return stripVector22({...existing})}let{docs}=await this._insertCore([item],{ttl,embed,session,save});return stripVector22(docs[0])}async insertMany(items,options={}){let{save,ttl,embed,session}=options,{docs}=await this._insertCore(items,{ttl,embed,session,save});return docs.map(stripVector22)}async _insertCore(items,{ttl,embed,session,save}){return this._pipeline.execute({op:"insert",beforeHook:null,afterHook:"afterInsert",hookPayload:null,save,session,mutate:async(assertTxAlive)=>{let newItems=[],batchIds=new Set;for(let item of items){let validated=this._applyValidation(item);await this._ctx.plugins.run("beforeInsert",{collection:this.name,doc:validated});let newItem=await this._buildDoc(validated,{ttl,embed});if(this._index.has(newItem._id)||batchIds.has(newItem._id))throw new UniqueConstraintError22("ERR_SKALEX_UNIQUE_DUPLICATE_ID",`Duplicate _id "${newItem._id}" in collection "${this.name}"`,{id:newItem._id,collection:this.name});batchIds.add(newItem._id),newItems.push(newItem)}if(assertTxAlive(),this._fieldIndex)this._fieldIndex.assertUniqueBatch(newItems);for(let newItem of newItems)this._addToIndex(newItem);this._data.push(...newItems);for(let newItem of newItems)this._index.set(newItem._id,newItem);return this._enforceCapAfterInsert(),{docs:newItems}}})}async updateOne(filter,update,options={}){await this._ctx.ensureConnected();let oldDoc=this._findRaw(filter);if(!oldDoc)return null;let{save,session}=options,{docs}=await this._updateCore([oldDoc],filter,update,{save,session});return stripVector22(docs[0])}async updateMany(filter,update,options={}){await this._ctx.ensureConnected();let oldDocs=this._findAllRaw(filter);if(oldDocs.length===0)return[];let{save,session}=options,{docs}=await this._updateCore(oldDocs,filter,update,{save,session});return docs.map(stripVector22)}async _updateCore(oldDocs,filter,update,{save,session}){return this._pipeline.execute({op:"update",beforeHook:"beforeUpdate",afterHook:"afterUpdate",hookPayload:{collection:this.name,filter,update},save,session,afterHookPayload:(docs)=>({collection:this.name,filter,update,result:docs.length===1?docs[0]:docs}),mutate:async(assertTxAlive)=>{let prevDocs=this._changelogEnabled?oldDocs.map((doc)=>structuredClone(doc)):oldDocs.map(()=>null),nextDocs=oldDocs.map((doc)=>this._prepareUpdatedDoc(doc,update));this._assertUniqueCandidates(oldDocs,nextDocs),assertTxAlive();let targets=new Set(oldDocs),positions=new Map;for(let i=0;i<this._data.length;i++)if(targets.has(this._data[i]))positions.set(this._data[i],i);for(let i=0;i<oldDocs.length;i++)this._commitUpdatedDoc(oldDocs[i],nextDocs[i],positions);return{docs:nextDocs,prevDocs}}})}applyUpdate(item,update){for(let field in update){if(_DANGEROUS_KEYS22.has(field))continue;if(field==="_id"||field==="createdAt")continue;let updateValue=update[field];if(Array.isArray(updateValue))item[field]=updateValue;else if(typeof updateValue==="object"&&updateValue!==null){let keys=Object.keys(updateValue);if(keys.some((k)=>k.startsWith("$"))){for(let key of keys)if(key==="$inc"&&typeof item[field]==="number")item[field]+=updateValue[key];else if(key==="$push"){if(!Array.isArray(item[field]))item[field]=[];item[field].push(updateValue[key])}}else item[field]=stripDangerousKeys22(updateValue)}else item[field]=updateValue}if(item.updatedAt=new Date,this._versioning)item._version=(item._version??0)+1;return item}_prepareUpdatedDoc(currentDoc,update){let prev=structuredClone(currentDoc),next=structuredClone(currentDoc);if(this.applyUpdate(next,update),!this._schema)return next;let errors=validateDoc22(next,this._schema,this._strict);if(!errors.length)return next;switch(this._onSchemaError){case"throw":throw new ValidationError22("ERR_SKALEX_VALIDATION_UPDATE",`Update validation failed on doc "${currentDoc._id}": ${errors.join("; ")}`,{id:currentDoc._id,errors});case"strip":return this._stripCandidateToValid(next,prev);default:return this._ctx.logger(`[${this.name}] Update validation warning: ${errors.join("; ")}`,"warn"),next}}_stripCandidateToValid(next,prev){let stripped=stripInvalidFields22(next,this._schema),merged=structuredClone(prev);for(let[key,val]of Object.entries(stripped)){if(key.startsWith("_"))continue;merged[key]=val}if(merged.updatedAt=next.updatedAt,this._versioning)merged._version=next._version;return merged}_commitUpdatedDoc(oldDoc,newDoc,positions){let idx=positions?positions.get(oldDoc):this._data.indexOf(oldDoc);if(idx===void 0||idx===-1)throw new PersistenceError22("ERR_SKALEX_PERSISTENCE_DOC_MISSING",`Document "${oldDoc._id}" no longer exists in collection "${this.name}"`,{id:oldDoc._id,collection:this.name});this._data[idx]=newDoc,this._index.set(newDoc._id,newDoc),this._updateInIndex(oldDoc,newDoc)}_assertUniqueCandidates(oldDocs,nextDocs){this._fieldIndex?.assertUniqueCandidates(oldDocs,nextDocs)}async upsert(filter,doc,options={}){if(await this._ctx.ensureConnected(),this._findRaw(filter))return this.updateOne(filter,doc,options);return this.insertOne({...resolveFilterToValues22(filter),...doc},options)}async upsertMany(docs,matchKey,options={}){await this._ctx.ensureConnected();let{save,...rest}=options,results=[];for(let doc of docs)results.push(await this.upsert({[matchKey]:doc[matchKey]},doc,{...rest,save:!1}));return await this._saveIfNeeded(save),results}async restore(filter,options={}){if(!this._softDelete)throw new QueryError22("ERR_SKALEX_QUERY_SOFT_DELETE_REQUIRED",`restore() requires softDelete on "${this.name}"`,{collection:this.name});await this._ctx.ensureConnected();let{save,session}=options,item=this._findRaw(filter,{includeDeleted:!0});if(!item||!item._deletedAt)return null;let{docs}=await this._pipeline.execute({op:"restore",beforeHook:null,afterHook:null,hookPayload:null,save,session,mutate:async(assertTxAlive)=>(assertTxAlive(),delete item._deletedAt,item.updatedAt=new Date,this._index.set(item._id,item),{docs:[item]})});return stripVector22(docs[0])}watch(filter,callback){if(typeof filter==="function")callback=filter,filter=null;if(callback)return this._ctx.eventBus.on(this.name,(event)=>{if(!filter||matchesFilter22(event.doc,filter))callback(event)});return this._watchIterator(filter)}_watchIterator(filter){let queue=[],resolve=null,done=!1,unsub=this._ctx.eventBus.on(this.name,(event)=>{if(filter&&!matchesFilter22(event.doc,filter))return;if(resolve){let r=resolve;resolve=null,r({value:event,done:!1})}else queue.push(event)});return{[Symbol.asyncIterator](){return this},next(){if(queue.length>0)return Promise.resolve({value:queue.shift(),done:!1});if(done)return Promise.resolve({value:void 0,done:!0});return new Promise((res)=>{resolve=res})},return(){if(done=!0,unsub(),resolve){let r=resolve;resolve=null,r({value:void 0,done:!0})}return Promise.resolve({value:void 0,done:!0})}}}async count(filter={}){return await this._ctx.ensureConnected(),count22(this._findAllRaw(filter))}async sum(field,filter={}){return await this._ctx.ensureConnected(),sum22(this._findAllRaw(filter),field)}async avg(field,filter={}){return await this._ctx.ensureConnected(),avg22(this._findAllRaw(filter),field)}async groupBy(field,filter={}){return await this._ctx.ensureConnected(),groupBy22(this._findAllRaw(filter),field)}async findOne(filter,options={}){await this._ctx.ensureConnected();let{populate,select,includeDeleted=!1}=options,item=this._findRaw(filter,{includeDeleted});if(!item)return null;let newItem=this._projectDoc(item,select);if(populate)await this._populateDoc(newItem,item,populate);return newItem}async find(filter,options={}){await this._ctx.ensureConnected();let _t0=Date.now(),{populate,select,sort,page=1,limit,session,includeDeleted=!1}=options;await this._ctx.plugins.run("beforeFind",{collection:this.name,filter,options});let candidates=this._getCandidates(filter),sortedFilter=presortFilter22(filter,this._fieldIndex?this._fieldIndex.indexedFields:new Set),results=[];for(let item of candidates){if(this._softDelete&&item._deletedAt&&!includeDeleted)continue;if(!matchesFilter22(item,sortedFilter))continue;let newItem=this._projectDoc(item,select);if(populate)await this._populateDoc(newItem,item,populate);results.push(newItem)}if(sort){let sortFields=Object.keys(sort);results.sort((a,b)=>{for(let field of sortFields){let dir=sort[field];if(a[field]<b[field])return-dir;if(a[field]>b[field])return dir}return 0})}let extra;if(limit){let totalDocs=results.length,totalPages=Math.ceil(totalDocs/limit),startIndex=(page-1)*limit;results=results.slice(startIndex,startIndex+limit),extra={page,totalDocs,totalPages}}return this._ctx.queryLog?.record({collection:this.name,op:"find",filter,duration:Date.now()-_t0,resultCount:results.length}),this._ctx.sessionStats.recordRead(session),await this._ctx.plugins.run("afterFind",{collection:this.name,filter,options,docs:results}),extra?{docs:results,...extra}:{docs:results}}async search(query,{filter,limit=10,minScore=0,session}={}){await this._ctx.ensureConnected();let _t0=Date.now();await this._ctx.plugins.run("beforeSearch",{collection:this.name,query,options:{filter,limit,minScore}});let queryVector=await this._ctx.embed(query),candidates=filter?this._findAllRaw(filter):this._data,scored=[];for(let doc of candidates){if(!doc._vector)continue;let score=cosineSimilarity22(queryVector,doc._vector);if(score>=minScore)scored.push({doc,score})}scored.sort((a,b)=>b.score-a.score);let top=scored.slice(0,limit);this._ctx.queryLog?.record({collection:this.name,op:"search",query,duration:Date.now()-_t0,resultCount:top.length}),this._ctx.sessionStats.recordRead(session);let docs=top.map((r)=>stripVector22(r.doc)),scores=top.map((r)=>r.score);return await this._ctx.plugins.run("afterSearch",{collection:this.name,query,options:{filter,limit,minScore},docs,scores}),{docs,scores}}async similar(id,{limit=10,minScore=0}={}){await this._ctx.ensureConnected();let source=this._index.get(id);if(!source||!source._vector)return{docs:[],scores:[]};let scored=[];for(let doc of this._data){if(doc._id===id||!doc._vector)continue;let score=cosineSimilarity22(source._vector,doc._vector);if(score>=minScore)scored.push({doc,score})}scored.sort((a,b)=>b.score-a.score);let top=scored.slice(0,limit);return{docs:top.map((r)=>stripVector22(r.doc)),scores:top.map((r)=>r.score)}}async deleteOne(filter,options={}){await this._ctx.ensureConnected();let{save,session}=options;if(this._softDelete){let item=this._findRaw(filter);if(!item)return null;let{docs:docs2}=await this._deleteCore("soft",[item],filter,{save,session});return stripVector22(docs2[0])}let{docs}=await this._deleteCore("hard",null,filter,{save,session});if(docs.length===0)return null;return stripVector22(docs[0])}async deleteMany(filter,options={}){await this._ctx.ensureConnected();let{save,session}=options;if(this._softDelete){let items=this._findAllRaw(filter);if(items.length===0)return[];let{docs:docs2}=await this._deleteCore("soft",items,filter,{save,session});return docs2.map(stripVector22)}let{docs}=await this._deleteCore("hardMany",null,filter,{save,session});return docs.map(stripVector22)}async _deleteCore(mode,items,filter,{save,session}){return this._pipeline.execute({op:"delete",beforeHook:"beforeDelete",afterHook:"afterDelete",hookPayload:{collection:this.name,filter},save,session,afterHookPayload:(docs)=>({collection:this.name,filter,result:docs.length===1?docs[0]:docs}),mutate:async(assertTxAlive)=>{if(assertTxAlive(),mode==="soft"){let now=new Date;for(let item of items)item._deletedAt=now,item.updatedAt=now,this._index.set(item._id,item);return{docs:items}}if(mode==="hard"){let idx=this._findIndex(filter);if(idx===-1)return{docs:[]};let deletedItem=this._data.splice(idx,1)[0];return this._index.delete(deletedItem._id),this._removeFromIndex(deletedItem),{docs:[deletedItem]}}let deletedItems=[],remainingItems=[];for(let item of this._data)if(matchesFilter22(item,filter))deletedItems.push(item),this._index.delete(item._id),this._removeFromIndex(item);else remainingItems.push(item);return this._data=remainingItems,{docs:deletedItems}}})}async export(filter={},options={}){let{dir,name,format="json"}=options;try{let filteredData=this._data.filter((item)=>matchesFilter22(item,filter));if(filteredData.length===0)throw new QueryError22("ERR_SKALEX_QUERY_EXPORT_EMPTY",`export(): no documents matched the filter in "${this.name}"`,{collection:this.name});let content;if(format==="json")content=JSON.stringify(filteredData,null,2);else{let escapeCsv=(v)=>{if(v==null)return"";let s=typeof v==="object"?JSON.stringify(v):String(v);return s.includes(",")||s.includes('"')||s.includes(`
56
56
  `)||s.includes("\r")?`"${s.replace(/"/g,'""')}"`:s},header=Object.keys(filteredData[0]).map(escapeCsv).join(","),rows=filteredData.map((item)=>Object.values(item).map(escapeCsv).join(","));content=[header,...rows].join(`
57
57
  `)}if(typeof this._ctx.fs.writeRaw!=="function")throw new AdapterError22("ERR_SKALEX_ADAPTER_NO_RAW_WRITE","export() requires a file-system adapter (FsAdapter). The current adapter does not support raw file writes.");let exportDir=dir||`${this._ctx.dataDirectory}/exports`,fileName=`${name||this.name}.${format}`,filePath=this._ctx.fs.join(exportDir,fileName);this._ctx.fs.ensureDir(exportDir),await this._ctx.fs.writeRaw(filePath,content)}catch(error22){throw this._ctx.logger(`Error exporting "${this.name}": ${error22.message}`,"error"),error22}}_txSnapshotIfNeeded(){let txm=this._ctx.txManager;if(!txm.active)return;if(this._activeTxId!==txm.context?.id)return;txm.snapshotIfNeeded(this.name,this._store,(col)=>this._ctx.snapshotCollection(col))}async _saveIfNeeded(save){let txm=this._ctx.txManager;if(txm.active&&this._activeTxId===txm.context?.id)return;if(save??this._ctx.autoSave)await this._ctx.saveCollection(this.name)}_applyValidation(item){if(!this._schema)return item;let errors=validateDoc22(item,this._schema,this._strict);if(!errors.length)return item;switch(this._onSchemaError){case"warn":return this._ctx.logger(`[${this.name}] Validation warning: ${errors.join("; ")}`,"warn"),item;case"strip":return stripInvalidFields22(item,this._schema);default:throw new ValidationError22("ERR_SKALEX_VALIDATION_FAILED",`Validation failed: ${errors.join("; ")}`,{errors})}}_enforceCapAfterInsert(){let max=this._maxDocs;if(!max||this._data.length<=max)return;let toEvict=this._data.splice(0,this._data.length-max);for(let doc of toEvict)this._index.delete(doc._id),this._removeFromIndex(doc)}_findRaw(filter,{includeDeleted=!1}={}){if(typeof filter==="function"){for(let doc of this._data){if(this._softDelete&&doc._deletedAt&&!includeDeleted)continue;if(filter(doc))return doc}return null}if(filter._id){let item=this._index.get(filter._id)||null;if(!item)return null;if(this._softDelete&&item._deletedAt&&!includeDeleted)return null;if(Object.keys(filter).length>1)return matchesFilter22(item,filter)?item:null;return item}if(this._fieldIndex)for(let key in filter){if(key==="$or"||key==="$and"||key==="$not")continue;let val=filter[key];if(typeof val!=="object"||val===null){let candidates=this._fieldIndex._lookupIterable(key,val);if(candidates!==null){for(let doc of candidates){if(this._softDelete&&doc._deletedAt&&!includeDeleted)continue;if(matchesFilter22(doc,filter))return doc}return null}}}for(let doc of this._data){if(this._softDelete&&doc._deletedAt&&!includeDeleted)continue;if(matchesFilter22(doc,filter))return doc}return null}_findAllRaw(filter,{includeDeleted=!1}={}){if(filter&&typeof filter!=="function"&&filter._id){let item=this._index.get(filter._id);if(!item)return[];if(this._softDelete&&item._deletedAt&&!includeDeleted)return[];return matchesFilter22(item,filter)?[item]:[]}let results=[];for(let doc of this._getCandidates(filter)){if(this._softDelete&&doc._deletedAt&&!includeDeleted)continue;if(matchesFilter22(doc,filter))results.push(doc)}return results}_getCandidates(filter){if(!this._fieldIndex)return this._data;if(this._fieldIndex._compoundIndexes.size>0){let eqFields={};for(let key in filter){if(key==="$or"||key==="$and"||key==="$not")continue;let val=filter[key];if(typeof val!=="object"||val===null)eqFields[key]=val}if(Object.keys(eqFields).length>=2){let candidates=this._fieldIndex.lookupCompound(eqFields);if(candidates!==null)return candidates}}for(let key in filter){if(key==="$or"||key==="$and"||key==="$not")continue;let val=filter[key];if(typeof val!=="object"||val===null){let candidates=this._fieldIndex._lookupIterable(key,val);if(candidates!==null)return candidates}}return this._data}_findIndex(filter){for(let i=0;i<this._data.length;i++)if(matchesFilter22(this._data[i],filter))return i;return-1}_addToIndex(doc){if(this._fieldIndex)this._fieldIndex.add(doc)}_removeFromIndex(doc){if(this._fieldIndex)this._fieldIndex.remove(doc)}_updateInIndex(oldDoc,doc){if(this._fieldIndex)this._fieldIndex.update(oldDoc,doc)}async _buildDoc(item,{ttl,embed}={}){let newItem={...item,_id:item._id??(this._ctx.idGenerator??generateUniqueId22)(),createdAt:new Date,updatedAt:new Date},resolvedTtl=ttl??this._defaultTtl;if(resolvedTtl)newItem._expiresAt=computeExpiry22(resolvedTtl);let resolvedEmbed=embed??this._defaultEmbed;if(resolvedEmbed){let text=typeof resolvedEmbed==="function"?resolvedEmbed(newItem):newItem[resolvedEmbed];newItem._vector=await this._ctx.embed(String(text))}if(this._versioning)newItem._version=1;return newItem}_projectDoc(doc,select){if(select){let out2={};for(let field of select){if(field==="_vector")continue;out2[field]=doc[field]}return out2}let out={...doc};return delete out._vector,out}async _populateDoc(out,source,fields){for(let field of fields){let item=await this._ctx.getCollection(field).findOne({_id:source[field]});if(item)out[field]=item}}}class StorageAdapter22{async read(name){throw Error("StorageAdapter.read() not implemented")}async write(name,data){throw Error("StorageAdapter.write() not implemented")}async delete(name){throw Error("StorageAdapter.delete() not implemented")}async list(){throw Error("StorageAdapter.list() not implemented")}async writeAll(entries){for(let{name,data}of entries)await this.write(name,data)}}class FsAdapter22 extends StorageAdapter22{constructor({dir,format="gz"}){super();this.dir=nodePath22.resolve(dir),this.format=format,this._ensureDir(this.dir)}_ensureDir(dir){if(!nodeFs22.existsSync(dir))nodeFs22.mkdirSync(dir,{recursive:!0})}_filePath(name){return nodePath22.join(this.dir,`${name}.${this.format}`)}async read(name){let fp=this._filePath(name);try{let raw=await nodeFs22.promises.readFile(fp);if(this.format==="gz")raw=zlib22.inflateSync(raw);return raw.toString("utf8")}catch(err){if(err.code==="ENOENT")return null;throw err}}async write(name,data){let fp=this._filePath(name),tmp=nodePath22.join(this.dir,`${name}_${globalThis.crypto.randomUUID()}.tmp.${this.format}`);if(this.format==="gz"){let compressed=zlib22.deflateSync(data);await nodeFs22.promises.writeFile(tmp,compressed)}else await nodeFs22.promises.writeFile(tmp,data,"utf8");await nodeFs22.promises.rename(tmp,fp)}async writeAll(entries){let staged=[];try{for(let{name,data}of entries){let fp=this._filePath(name),tmp=nodePath22.join(this.dir,`${name}_${globalThis.crypto.randomUUID()}.tmp.${this.format}`);if(this.format==="gz"){let compressed=zlib22.deflateSync(data);await nodeFs22.promises.writeFile(tmp,compressed)}else await nodeFs22.promises.writeFile(tmp,data,"utf8");staged.push({tmp,fp})}for(let{tmp,fp}of staged)await nodeFs22.promises.rename(tmp,fp)}catch(error22){for(let{tmp}of staged)try{await nodeFs22.promises.unlink(tmp)}catch{}throw error22}}async delete(name){let fp=this._filePath(name);try{await nodeFs22.promises.unlink(fp)}catch(err){if(err.code!=="ENOENT")throw err}}async list(){try{let files=await nodeFs22.promises.readdir(this.dir),ext=`.${this.format}`;return files.filter((f)=>f.endsWith(ext)&&!f.includes(".tmp.")).map((f)=>f.slice(0,-ext.length))}catch(err){if(err.code==="ENOENT")return[];throw err}}join(...parts){return nodePath22.join(...parts)}ensureDir(dir){this._ensureDir(dir)}async writeRaw(filePath,content){this._ensureDir(nodePath22.dirname(filePath)),await nodeFs22.promises.writeFile(filePath,content,"utf8")}async readRaw(filePath){return nodeFs22.promises.readFile(nodePath22.resolve(filePath),"utf8")}}class MigrationEngine22{constructor(){this._migrations=[]}add(migration){let{version,up}=migration;if(typeof version!=="number"||version<1)throw new ValidationError22("ERR_SKALEX_VALIDATION_MIGRATION",`Migration version must be a positive integer, got ${version}`,{version});if(typeof up!=="function")throw new ValidationError22("ERR_SKALEX_VALIDATION_MIGRATION",`Migration version ${version} must have an "up" function`,{version});if(this._migrations.some((m)=>m.version===version))throw new ValidationError22("ERR_SKALEX_VALIDATION_MIGRATION_DUPLICATE",`Migration version ${version} is already registered`,{version});this._migrations.push({...migration}),this._migrations.sort((a,b)=>a.version-b.version)}async run(getCollection,appliedVersions=[]){let applied=new Set(appliedVersions),pending=this._migrations.filter((m)=>!applied.has(m.version));for(let migration of pending){let collection=getCollection(migration.version);await migration.up(collection),applied.add(migration.version)}return[...applied].sort((a,b)=>a-b)}status(appliedVersions=[]){let applied=new Set(appliedVersions),pending=this._migrations.map((m)=>m.version).filter((v)=>!applied.has(v));return{current:appliedVersions.length?Math.max(...appliedVersions):0,applied:[...applied].sort((a,b)=>a-b),pending}}}var EMPTY_ITERABLE22={[Symbol.iterator](){return{next(){return{done:!0}}}},size:0};function readOnlyIterable22(set){return{[Symbol.iterator](){return set[Symbol.iterator]()},get size(){return set.size}}}function encodeTuple22(values){return values.map((v)=>{if(v===null||v===void 0)return"\x00";if(typeof v==="boolean")return v?"\x01T":"\x01F";if(typeof v==="number")return`\x02${v}`;return`\x03${String(v)}`}).join("\x1F")}class IndexEngine22{constructor(fields=[],unique=[]){this._fields=new Set,this._compoundFields=[];for(let f of fields)if(Array.isArray(f)){for(let subf of f)this._validateFieldName(subf);this._compoundFields.push(f)}else this._validateFieldName(f),this._fields.add(f);for(let f of unique)this._validateFieldName(f);this._uniqueFields=new Set(unique),this._indexedFields=new Set([...this._fields,...this._uniqueFields]),this._fieldIndexes=new Map,this._uniqueIndexes=new Map;for(let f of this._fields)this._fieldIndexes.set(f,new Map);for(let f of this._uniqueFields)if(this._uniqueIndexes.set(f,new Map),!this._fieldIndexes.has(f))this._fieldIndexes.set(f,new Map);this._compoundIndexes=new Map;for(let fieldSet of this._compoundFields)this._compoundIndexes.set(fieldSet.join("\x00"),{fields:fieldSet,map:new Map})}get indexedFields(){return this._indexedFields}buildFromData(data){for(let[,m]of this._fieldIndexes)m.clear();for(let[,m]of this._uniqueIndexes)m.clear();for(let[,ci]of this._compoundIndexes)ci.map.clear();for(let doc of data)this._indexDoc(doc)}add(doc){this._checkUnique(doc,null),this._indexDoc(doc)}remove(doc){for(let[field,map]of this._fieldIndexes){let val=doc[field];if(val!==void 0){let set=map.get(val);if(set){if(set.delete(doc),set.size===0)map.delete(val)}}}for(let[field,map]of this._uniqueIndexes){let val=doc[field];if(val!==void 0)map.delete(val)}for(let[,ci]of this._compoundIndexes){let tupleKey=encodeTuple22(ci.fields.map((f)=>doc[f])),set=ci.map.get(tupleKey);if(set){if(set.delete(doc),set.size===0)ci.map.delete(tupleKey)}}}update(oldDoc,newDoc){this._checkUnique(newDoc,oldDoc),this.remove(oldDoc);try{this._indexDoc(newDoc)}catch(indexError){try{this._indexDoc(oldDoc)}catch{}throw indexError}}lookup(field,value){let map=this._fieldIndexes.get(field);if(!map)return null;let set=map.get(value);return set?[...set]:[]}_lookupIterable(field,value){let map=this._fieldIndexes.get(field);if(!map)return null;let set=map.get(value);return set?readOnlyIterable22(set):EMPTY_ITERABLE22}lookupCompound(fieldValues){let keys=Object.keys(fieldValues).sort();for(let[,ci]of this._compoundIndexes){let ciKeys=[...ci.fields].sort();if(ciKeys.length!==keys.length)continue;if(ciKeys.every((k,i)=>k===keys[i])){let tupleKey=encodeTuple22(ci.fields.map((f)=>fieldValues[f])),set=ci.map.get(tupleKey);return set?readOnlyIterable22(set):EMPTY_ITERABLE22}}return null}isUniqueTaken(field,value){let map=this._uniqueIndexes.get(field);if(!map)return!1;return map.has(value)}assertUniqueCandidates(oldDocs,newDocs){if(this._uniqueFields.size===0)return;let batchOldIds=new Set(oldDocs.map((doc)=>doc._id));for(let field of this._uniqueFields){let reserved=new Set,uniqueMap=this._uniqueIndexes.get(field);if(uniqueMap){for(let[value,doc]of uniqueMap.entries())if(!batchOldIds.has(doc._id))reserved.add(value)}let seen=new Map;for(let i=0;i<newDocs.length;i++){let val=newDocs[i][field];if(val===void 0)continue;if(reserved.has(val))throw new UniqueConstraintError22("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${field}" value "${val}" already exists`,{field,value:val});let prior=seen.get(val);if(prior&&prior!==oldDocs[i]._id)throw new UniqueConstraintError22("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${field}" value "${val}" already exists`,{field,value:val});seen.set(val,oldDocs[i]._id)}}}assertUniqueBatch(newDocs){if(this._uniqueFields.size===0)return;for(let field of this._uniqueFields){let uniqueMap=this._uniqueIndexes.get(field),seen=new Set;for(let doc of newDocs){let val=doc[field];if(val===void 0)continue;if(uniqueMap&&uniqueMap.has(val))throw new UniqueConstraintError22("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${field}" value "${val}" already exists`,{field,value:val});if(seen.has(val))throw new UniqueConstraintError22("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: duplicate "${field}" value "${val}" within batch`,{field,value:val});seen.add(val)}}}_validateFieldName(field){if(field.includes("."))throw new ValidationError22("ERR_SKALEX_VALIDATION_INDEX_DOT_PATH",`Index fields cannot use dot-notation: "${field}". Use a flat field name.`,{field})}_indexDoc(doc){for(let[field,map]of this._fieldIndexes){let val=doc[field];if(val!==void 0){if(!map.has(val))map.set(val,new Set);map.get(val).add(doc)}}for(let[field,map]of this._uniqueIndexes){let val=doc[field];if(val!==void 0)map.set(val,doc)}for(let[,ci]of this._compoundIndexes){for(let f of ci.fields){let val=doc[f];if(val!==void 0&&val!==null&&typeof val==="object")throw new ValidationError22("ERR_SKALEX_VALIDATION_COMPOUND_INDEX",`Compound index field "${f}" must be a scalar value (string, number, or boolean), got ${Array.isArray(val)?"array":typeof val}`,{field:f})}let tupleKey=encodeTuple22(ci.fields.map((f)=>doc[f]));if(!ci.map.has(tupleKey))ci.map.set(tupleKey,new Set);ci.map.get(tupleKey).add(doc)}}_checkUnique(newDoc,existingDoc){for(let field of this._uniqueFields){let val=newDoc[field];if(val===void 0)continue;let map=this._uniqueIndexes.get(field);if(!map)continue;let existing=map.get(val);if(existing&&existing._id!==existingDoc?._id)throw new UniqueConstraintError22("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${field}" value "${val}" already exists`,{field,value:val})}}}var FLUSH_META_KEY22="_flush",META_DOC_ID22="migrations";class PersistenceManager22{constructor({adapter,serializer,deserializer,logger:logger222,debug=!1,lenientLoad=!1}){this._adapter=adapter,this._serializer=serializer,this._deserializer=deserializer,this._logger=logger222,this._debug=debug,this._lenientLoad=lenientLoad,this._saveLock=Promise.resolve()}_withSaveLock(fn){let next=this._saveLock.then(fn);return this._saveLock=next.catch(()=>{}),next}async loadAll(collections,{parseSchema:parseSchema222,buildIndex,IndexEngine:IndexEngine222}){try{let names=await this._adapter.list();await Promise.all(names.map(async(name)=>{try{let raw=await this._adapter.read(name);if(!raw)return;let parsed=this._deserializer(raw),{collectionName,data}=parsed;if(!collectionName)return;let existing=collections[collectionName],rawSchema=existing?.rawSchema??parsed.rawSchema??null,parsedSchema=existing?.schema??(rawSchema?parseSchema222(rawSchema):null),changelog=existing?.changelog??parsed.changelog??!1,softDelete=existing?.softDelete??parsed.softDelete??!1,versioning=existing?.versioning??parsed.versioning??!1,strict=existing?.strict??parsed.strict??!1,onSchemaError=existing?.onSchemaError??parsed.onSchemaError??"throw",defaultTtl=existing?.defaultTtl??parsed.defaultTtl??null,defaultEmbed=existing?.defaultEmbed??parsed.defaultEmbed??null,maxDocs=existing?.maxDocs??parsed.maxDocs??null,fieldIndex=existing?existing.fieldIndex:null;if(!fieldIndex&&parsedSchema?.uniqueFields?.length)fieldIndex=new IndexEngine222([],parsedSchema.uniqueFields);let idIndex=buildIndex(data,"_id");if(fieldIndex)fieldIndex.buildFromData(data);collections[collectionName]={collectionName,data,index:idIndex,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:parsedSchema,rawSchema,fieldIndex,changelog,softDelete,versioning,strict,onSchemaError,defaultTtl,defaultEmbed,maxDocs}}catch(error22){if(error22.code==="ENOENT")return;if(this._lenientLoad){this._logger(`WARNING: Could not load collection "${name}": ${error22.message}. Collection will be empty.`,"error");return}throw new PersistenceError22("ERR_SKALEX_PERSISTENCE_CORRUPT",`Failed to load collection "${name}": ${error22.message}`,{collection:name})}})),this._detectIncompleteFlush(collections),await this._cleanOrphanTempFiles()}catch(error22){if(error22.code!=="ENOENT")throw this._logger(`Error loading data: ${error22}`,"error"),error22}}async save(collections,collectionName){if(collectionName)await this._saveOne(collections,collectionName);else await Promise.all(Object.keys(collections).map((name)=>this._saveOne(collections,name)))}async saveDirty(collections){let dirtyNames=Object.keys(collections).filter((name)=>collections[name]._dirty);if(dirtyNames.length===0)return;await Promise.all(dirtyNames.map((name)=>this._saveOne(collections,name)))}saveAtomic(collections,names){return this._withSaveLock(async()=>{if(names.length===0)return;this._writeFlushSentinel(collections,names);let allNames=new Set(names);allNames.add("_meta");let entries=[...allNames].filter((n)=>collections[n]).map((name)=>({name,data:this._serializeCollection(collections[name])}));try{await this._adapter.writeAll(entries)}catch(error22){throw new PersistenceError22("ERR_SKALEX_PERSISTENCE_FLUSH_FAILED",`Batch save failed during writeAll: ${error22.message}`,{collections:names})}for(let name of names)if(collections[name])collections[name]._dirty=!1;try{this._clearFlushSentinel(collections),await this._adapter.write("_meta",this._serializeCollection(collections._meta))}catch(error22){this._logger(`WARNING: Batch data committed but sentinel clear failed: ${error22.message}. Next load will report an incomplete flush (false positive).`,"error")}})}markDirty(collections,name){let col=collections[name];if(col)col._dirty=!0}_serializeCollection(col){let payload={collectionName:col.collectionName,data:col.data};if(col.rawSchema)payload.rawSchema=col.rawSchema;if(col.changelog)payload.changelog=col.changelog;if(col.softDelete)payload.softDelete=col.softDelete;if(col.versioning)payload.versioning=col.versioning;if(col.strict)payload.strict=col.strict;if(col.onSchemaError!=="throw")payload.onSchemaError=col.onSchemaError;if(col.defaultTtl)payload.defaultTtl=col.defaultTtl;if(col.defaultEmbed)payload.defaultEmbed=col.defaultEmbed;if(col.maxDocs)payload.maxDocs=col.maxDocs;return this._serializer(payload)}async _saveOne(collections,name){let col=collections[name];if(!col)return;if(col.isSaving)return col._pendingSave=!0,new Promise((resolve,reject)=>{(col._saveWaiters??=[]).push({resolve,reject})});col.isSaving=!0,col._pendingSave=!1;try{await this._writeCollection(name,col);while(col._pendingSave)col._pendingSave=!1,await this._writeCollection(name,col);this._resolveSaveWaiters(col)}catch(error22){throw this._rejectSaveWaiters(col,error22),error22}finally{col.isSaving=!1}}async _writeCollection(name,col){try{await this._adapter.write(name,this._serializeCollection(col)),col._dirty=!1}catch(error22){throw this._logger(`Error saving "${name}": ${error22.message}`,"error"),error22}}_resolveSaveWaiters(col){let waiters=col._saveWaiters?.splice(0)??[];for(let w of waiters)w.resolve()}_rejectSaveWaiters(col,error22){let waiters=col._saveWaiters?.splice(0)??[];for(let w of waiters)w.reject(error22)}_writeFlushSentinel(collections,names){let meta=this._getOrCreateMeta(collections);meta[FLUSH_META_KEY22]={startedAt:new Date().toISOString(),collections:names,completedAt:null}}_clearFlushSentinel(collections){let meta=this._getOrCreateMeta(collections);if(meta[FLUSH_META_KEY22])meta[FLUSH_META_KEY22].completedAt=new Date().toISOString()}_detectIncompleteFlush(collections){let metaCol=collections._meta;if(!metaCol)return;let metaDoc=metaCol.index.get(META_DOC_ID22);if(!metaDoc)return;let flush=metaDoc[FLUSH_META_KEY22];if(!flush)return;if(flush.startedAt&&!flush.completedAt)this._logger(`WARNING: Incomplete flush detected (started ${flush.startedAt}, collections: ${flush.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 nodeFs2222=await import("fs"),nodePath2222=await import("path"),dir=this._adapter.dir;if(!dir)return;let orphans=(await nodeFs2222.default.promises.readdir(dir)).filter((f)=>f.includes(".tmp."));for(let orphan of orphans){let orphanPath=nodePath2222.default.join(dir,orphan);try{await nodeFs2222.default.promises.unlink(orphanPath),this._log(`Cleaned orphan temp file: ${orphan}`)}catch{}}}catch{}}_getOrCreateMeta(collections){if(!collections._meta)collections._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 metaCol=collections._meta,doc=metaCol.index.get(META_DOC_ID22);if(!doc)doc={_id:META_DOC_ID22},metaCol.data.push(doc),metaCol.index.set(META_DOC_ID22,doc);return doc}_log(msg){if(this._debug)this._logger(msg,"info")}}var _txIdCounter22=0;class TransactionManager22{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(fn,db,{timeout=0}={}){let execute=async()=>{await db._ensureConnected();let preExisting=new Set(Object.keys(db.collections)),ctx={id:++_txIdCounter22,startedAt:Date.now(),aborted:!1,preExisting,touchedCollections:new Set,snapshots:new Map,deferredEffects:[],timeout};this._ctx=ctx;let timer=null,timeoutPromise=timeout>0?new Promise((_,reject)=>{timer=setTimeout(()=>{ctx.aborted=!0,reject(new TransactionError22("ERR_SKALEX_TX_TIMEOUT",`Transaction ${ctx.id} timed out after ${timeout}ms`))},timeout)}):null,self=this,proxy=new Proxy(db,{get(target,prop){if(prop==="_txId")return ctx.id;if(ctx!==self._ctx)throw new TransactionError22("ERR_SKALEX_TX_STALE_PROXY",`Transaction ${ctx.id} has ended. This proxy is no longer usable.`);if(prop==="collections")throw new TransactionError22("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(prop==="useCollection")return(name)=>{let col=target.useCollection(name);return col._activeTxId=ctx.id,col};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value}});try{let fnPromise=fn(proxy),result=timeoutPromise?await Promise.race([fnPromise,timeoutPromise]):await fnPromise;if(ctx.aborted)throw new TransactionError22("ERR_SKALEX_TX_ABORTED",`Transaction ${ctx.id} was aborted`);let touched=[...ctx.touchedCollections];if(touched.length>0)await db._persistence.saveAtomic(db.collections,touched);for(let effect of ctx.deferredEffects)await effect();return result}catch(error22){for(let[name,snap]of ctx.snapshots)if(ctx.preExisting.has(name)){if(db._applySnapshot(name,snap),db.collections[name])db.collections[name]._dirty=snap._dirty}for(let name in db.collections)if(!ctx.preExisting.has(name))delete db.collections[name],delete db._collectionInstances[name];throw error22}finally{if(timer)clearTimeout(timer);if(ctx.aborted)this._abortedIds.add(ctx.id);this._ctx=null;for(let name in db._collectionInstances){let inst=db._collectionInstances[name];if(inst._createdInTxId===ctx.id)inst._createdInTxId=null;if(inst._activeTxId===ctx.id)inst._activeTxId=null}}},next=this._txLock.then(execute);return this._txLock=next.catch(()=>{}),next}snapshotIfNeeded(name,col,snapshotFn){let ctx=this._ctx;if(!ctx)return;if(this._assertCtxNotAborted(ctx),!ctx.snapshots.has(name)){let snap=snapshotFn(col);snap._dirty=col._dirty??!1,ctx.snapshots.set(name,snap)}ctx.touchedCollections.add(name)}assertNotAborted(){let ctx=this._ctx;if(ctx)this._assertCtxNotAborted(ctx)}_assertCtxNotAborted(ctx){if(ctx.aborted)throw new TransactionError22("ERR_SKALEX_TX_ABORTED",`Transaction ${ctx.id} was aborted. No further mutations allowed.`)}defer(effect){if(this._ctx)return this._ctx.deferredEffects.push(effect),!0;return!1}}class CollectionRegistry22{constructor(CollectionClass){this._CollectionClass=CollectionClass,this.stores={},this._instances={}}get(name,db){if(this._instances[name])return this._instances[name];if(!this.stores[name])this.createStore(name);let instance=new this._CollectionClass(this.stores[name],db);return this._instances[name]=instance,instance}create(name,options={},db){this.createStore(name,options);let instance=new this._CollectionClass(this.stores[name],db);return this._instances[name]=instance,instance}createStore(name,{schema,indexes=[],changelog=!1,softDelete=!1,versioning=!1,strict=!1,onSchemaError="throw",defaultTtl=null,defaultEmbed=null,maxDocs=null}={}){let parsedSchema=null,fieldIndex=null;if(schema){parsedSchema=parseSchema22(schema);let uniqueFields=parsedSchema.uniqueFields;if(indexes.length||uniqueFields.length)fieldIndex=new IndexEngine22(indexes,uniqueFields)}else if(indexes.length)fieldIndex=new IndexEngine22(indexes,[]);this.stores[name]={collectionName:name,data:[],index:new Map,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:parsedSchema,rawSchema:schema||null,fieldIndex,changelog,softDelete,versioning,strict,onSchemaError,defaultTtl,defaultEmbed,maxDocs}}rename(from,to){if(!this.stores[from])throw new PersistenceError22("ERR_SKALEX_PERSISTENCE_COLLECTION_NOT_FOUND",`Collection "${from}" not found`,{collection:from});if(this.stores[to])throw new PersistenceError22("ERR_SKALEX_PERSISTENCE_COLLECTION_EXISTS",`Collection "${to}" already exists`,{collection:to});let store=this.stores[from];if(store.collectionName=to,this.stores[to]=store,delete this.stores[from],this._instances[from]){let inst=this._instances[from];inst.name=to,this._instances[to]=inst,delete this._instances[from]}}buildIndex(data,keyField){let index=new Map;for(let item of data)index.set(item[keyField],item);return index}inspect(name){if(name){let col=this.stores[name];if(!col)return null;return{name,count:col.data.length,schema:col.schema?Object.fromEntries(col.schema.fields):null,indexes:col.fieldIndex?[...col.fieldIndex.indexedFields]:[],softDelete:col.softDelete??!1,versioning:col.versioning??!1,strict:col.strict??!1,onSchemaError:col.onSchemaError??"throw",maxDocs:col.maxDocs??null}}let result={};for(let n in this.stores)result[n]=this.inspect(n);return result}dump(){let result={};for(let name in this.stores)if(!name.startsWith("_"))result[name]=structuredClone(this.stores[name].data);return result}schema(name){let store=this.stores[name];if(!store)return null;if(store.schema)return Object.fromEntries([...store.schema.fields.entries()].map(([k,v])=>[k,v.type]));if(store.data.length>0)return inferSchema22(store.data[0]);return null}stats(name){let calc=(n)=>{let col=this.stores[n];if(!col)return null;let count222=col.data.length,estimatedSize=0;for(let doc of col.data)try{estimatedSize+=JSON.stringify(doc).length}catch(_){}return{collection:n,count:count222,estimatedSize,avgDocSize:count222>0?Math.round(estimatedSize/count222):0}};if(name)return calc(name);return Object.keys(this.stores).map(calc)}clear(){this.stores={},this._instances={}}}class EmbeddingAdapter22{async embed(text){throw Error("EmbeddingAdapter.embed() not implemented")}}var _env$422=(k)=>globalThis.process?.env?.[k]??globalThis.Deno?.env?.get(k);class OpenAIEmbeddingAdapter22 extends EmbeddingAdapter22{constructor({apiKey=_env$422("OPENAI_API_KEY"),model=_env$422("OPENAI_EMBED_MODEL")??"text-embedding-3-small",baseUrl=_env$422("OPENAI_EMBED_BASE_URL")??"https://api.openai.com/v1/embeddings",dimensions=_env$422("OPENAI_EMBED_DIMENSIONS")!=null?Number(_env$422("OPENAI_EMBED_DIMENSIONS")):void 0,organization=_env$422("OPENAI_ORGANIZATION")??void 0,timeout=_env$422("OPENAI_EMBED_TIMEOUT")!=null?Number(_env$422("OPENAI_EMBED_TIMEOUT")):void 0,retries=Number(_env$422("OPENAI_EMBED_RETRIES")??0),retryDelay=Number(_env$422("OPENAI_EMBED_RETRY_DELAY")??1000),headers={},fetch:fetchFn=globalThis.fetch}={}){super();if(!apiKey)throw Error("OpenAIEmbeddingAdapter requires an apiKey");this.apiKey=apiKey,this.model=model,this.baseUrl=baseUrl,this.dimensions=dimensions,this.organization=organization,this.timeout=timeout,this.retries=retries,this.retryDelay=retryDelay,this.headers=headers,this._fetch=fetchFn}async embed(text){let lastErr;for(let attempt=0;attempt<=this.retries;attempt++){let controller=this.timeout!=null?new AbortController:null,timer=controller?setTimeout(()=>controller.abort(),this.timeout):null;try{let response=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:text,model:this.model,...this.dimensions!==void 0&&{dimensions:this.dimensions}}),...controller&&{signal:controller.signal}});if(!response.ok){let err=(await response.text()).slice(0,200);throw Error(`OpenAI embedding API error ${response.status}: ${err}`)}return(await response.json()).data[0].embedding}catch(err){if(lastErr=err,attempt<this.retries)await new Promise((r)=>setTimeout(r,this.retryDelay*2**attempt))}finally{if(timer!==null)clearTimeout(timer)}}throw lastErr}}var _env$322=(k)=>globalThis.process?.env?.[k]??globalThis.Deno?.env?.get(k);class OllamaEmbeddingAdapter22 extends EmbeddingAdapter22{constructor({model=_env$322("OLLAMA_EMBED_MODEL")??"nomic-embed-text",host=_env$322("OLLAMA_HOST")??"http://localhost:11434",timeout=_env$322("OLLAMA_EMBED_TIMEOUT")!=null?Number(_env$322("OLLAMA_EMBED_TIMEOUT")):void 0,retries=Number(_env$322("OLLAMA_EMBED_RETRIES")??0),retryDelay=Number(_env$322("OLLAMA_EMBED_RETRY_DELAY")??1000),headers={},fetch:fetchFn=globalThis.fetch}={}){super();this.model=model,this.host=host,this.timeout=timeout,this.retries=retries,this.retryDelay=retryDelay,this.headers=headers,this._fetch=fetchFn}async embed(text){let lastErr;for(let attempt=0;attempt<=this.retries;attempt++){let controller=this.timeout!=null?new AbortController:null,timer=controller?setTimeout(()=>controller.abort(),this.timeout):null;try{let response=await this._fetch(`${this.host}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json",...this.headers},body:JSON.stringify({model:this.model,prompt:text}),...controller&&{signal:controller.signal}});if(!response.ok){let err=(await response.text()).slice(0,200);throw Error(`Ollama embedding API error ${response.status}: ${err}`)}return(await response.json()).embedding}catch(err){if(lastErr=err,attempt<this.retries)await new Promise((r)=>setTimeout(r,this.retryDelay*2**attempt))}finally{if(timer!==null)clearTimeout(timer)}}throw lastErr}}class LLMAdapter22{async generate(schema,nlQuery){throw Error("LLMAdapter.generate() not implemented")}async summarize(texts){throw Error("LLMAdapter.summarize() not implemented")}}var SYSTEM_GENERATE22=`You are a database query assistant. Convert the user's natural language request into a JSON filter object for a document database.
58
58
 
@@ -78,7 +78,7 @@ data: /message
78
78
 
79
79
  `),this._clients.add(res),req.on("close",()=>{this._clients.delete(res)})}async _handleMessage(req,res){let body="";req.setEncoding("utf8"),req.on("data",(c)=>{if(body+=c,body.length>this._maxBodySize)req.destroy(),res.writeHead(413,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Request body too large"}))}),req.on("end",async()=>{res.writeHead(202,{"Content-Type":"application/json"}),res.end("{}");let msg;try{msg=JSON.parse(body)}catch(_){this.send(error22(null,PARSE_ERROR22,"Parse error"));return}if(this._onMessage)await this._onMessage(msg).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 StdioTransport22{constructor(){this._onMessage=null,this._buffer="",this._started=!1}onMessage(fn){this._onMessage=fn}send(msg){process.stdout.write(JSON.stringify(msg)+`
80
80
  `)}start(){if(this._started)return;this._started=!0,process.stdin.setEncoding("utf8"),process.stdin.on("data",(chunk)=>{this._buffer+=chunk;let idx;while((idx=this._buffer.indexOf(`
81
- `))!==-1){let line=this._buffer.slice(0,idx).trim();if(this._buffer=this._buffer.slice(idx+1),line&&this._onMessage){let msg;try{msg=JSON.parse(line)}catch(_){this.send(error22(null,PARSE_ERROR22,"Parse error"));continue}this._onMessage(msg).catch(()=>{})}}}),process.stdin.on("end",()=>{process.exit(0)})}stop(){process.stdin.removeAllListeners("data"),process.stdin.removeAllListeners("end"),this._started=!1}}var SERVER_INFO22={name:"skalex",version:"4.0.0-alpha"},PROTOCOL_VERSION22="2024-11-05";class SkalexMCPServer22{constructor(db,opts={}){this._db=db,this._transport=opts.transport||"stdio",this._port=opts.port||3000,this._host=opts.host||"127.0.0.1",this._allowedOrigin=opts.allowedOrigin??null,this._maxBodySize=opts.maxBodySize??1048576,this._scopes=opts.scopes||{"*":["read"]},this._t=null}async listen(){if(this._transport==="http")this._t=new HttpTransport22({port:this._port,host:this._host,allowedOrigin:this._allowedOrigin,maxBodySize:this._maxBodySize});else this._t=new StdioTransport22;this._t.onMessage((msg)=>this._handleMessage(msg)),await this._t.start()}async connect(transport){if(this._t=transport,this._t.onMessage((msg)=>this._handleMessage(msg)),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(raw){let{msg,parseError}=typeof raw==="string"?parse22(raw):{msg:raw};if(parseError){this._send(parseError);return}let{id,method,params}=msg;if(id===void 0){if(method==="notifications/initialized")return;return}try{switch(method){case"initialize":this._send(ok22(id,{protocolVersion:PROTOCOL_VERSION22,capabilities:{tools:{}},serverInfo:SERVER_INFO22}));break;case"tools/list":this._send(ok22(id,{tools:this._visibleTools()}));break;case"tools/call":await this._handleToolCall(id,params);break;case"ping":this._send(ok22(id,{}));break;default:this._send(error22(id,METHOD_NOT_FOUND22,`Method not found: ${method}`))}}catch(err){this._send(error22(id,INTERNAL_ERROR22,err.message||"Internal error"))}}async _handleToolCall(id,params){let name=params?.name,args=params?.arguments??{};if(!name){this._send(error22(id,INVALID_PARAMS22,"tools/call requires params.name"));return}let def=TOOL_DEFS22.find((t)=>t.name===name);if(!def){this._send(error22(id,METHOD_NOT_FOUND22,`Unknown tool: ${name}`));return}let collection=args.collection||args.collection_name||null;if(!this._hasScope(collection,def.scope)){this._send(ok22(id,toolError22(`Access denied: "${name}" requires "${def.scope}" scope on collection "${collection}".`)));return}try{let result=await callTool22(name,args,this._db);this._send(ok22(id,toolResult22(JSON.stringify(result,null,2))))}catch(err){this._send(ok22(id,toolError22(err.message||String(err))))}}_visibleTools(){return TOOL_DEFS22.filter((def)=>{let global=this._scopes["*"];if(global&&(global.includes(def.scope)||global.includes("admin")))return!0;for(let[,perms]of Object.entries(this._scopes))if(perms.includes(def.scope)||perms.includes("admin"))return!0;return!1})}_hasScope(collection,scope){let check=(perms)=>perms.includes("admin")||perms.includes(scope);if(collection&&this._scopes[collection])return check(this._scopes[collection]);if(this._scopes["*"])return check(this._scopes["*"]);return!1}_send(msg){this._t?.send(msg)}}var META_KEY22="migrations",_serialize22=(value)=>JSON.stringify(value,function(key,v){let raw=this[key];if(raw instanceof Date)return{__skalex_date__:raw.toISOString()};if(typeof v==="bigint")return{__skalex_bigint__:v.toString()};return v}),_deserialize22=(text)=>JSON.parse(text,(_,v)=>{if(v&&typeof v==="object"){if("__skalex_bigint__"in v)return BigInt(v.__skalex_bigint__);if("__skalex_date__"in v)return new Date(v.__skalex_date__)}return v});class Skalex22{constructor({path="./.db",format="gz",debug=!1,adapter,ai,encrypt,slowQueryLog,queryCache,memory,logger:logger$1,plugins,llmAdapter,embeddingAdapter,regexMaxLength,idGenerator,serializer,deserializer,autoSave,ttlSweepInterval,lenientLoad}={}){if(this.dataDirectory=path,this.dataFormat=format,this.debug=debug,!Skalex22._errorsAttached)Skalex22.SkalexError=SkalexError22,Skalex22.ValidationError=ValidationError22,Skalex22.UniqueConstraintError=UniqueConstraintError22,Skalex22.TransactionError=TransactionError22,Skalex22.PersistenceError=PersistenceError22,Skalex22.AdapterError=AdapterError22,Skalex22.QueryError=QueryError22,Skalex22._errorsAttached=!0;this._adapterConfig=adapter??null;let fs=adapter||new FsAdapter22({dir:path,format});if(encrypt)fs=new EncryptedAdapter22(fs,encrypt.key);if(this.fs=fs,this._registry=new CollectionRegistry22(Collection22),this.collections=this._registry.stores,this._collectionInstances=this._registry._instances,this._migrations=new MigrationEngine22,this._connectPromise=null,this.isConnected=!1,this._aiConfig=ai||null,this._encryptConfig=encrypt||null,this._pluginsConfig=Array.isArray(plugins)?plugins:null,this._memoryConfig=memory||null,this._regexMaxLength=regexMaxLength??500,this._idGenerator=idGenerator??null,this._serializer=serializer??_serialize22,this._deserializer=deserializer??_deserialize22,this._autoSave=autoSave??!1,this._txManager=new TransactionManager22,this._ttlSweepInterval=ttlSweepInterval??0,this._ttlTimer=null,this._logger=logger$1??logger22,this._embeddingAdapter=embeddingAdapter??(ai?createEmbeddingAdapter22(ai):null),this._aiAdapter=llmAdapter??(ai?createLLMAdapter22(ai):null),this._persistence=new PersistenceManager22({adapter:this.fs,serializer:this._serializer,deserializer:this._deserializer,logger:this._logger,debug:this.debug,lenientLoad:lenientLoad??!1}),this._changeLog=new ChangeLog22(this),this._queryCache=new QueryCache22(queryCache||{}),this._eventBus=new EventBus22,this._queryLog=slowQueryLog?new QueryLog22(slowQueryLog):null,this._sessionStats=new SessionStats22,this._plugins=new PluginEngine22,Array.isArray(plugins))for(let p of plugins)this._plugins.register(p)}async connect(){if(this._connectPromise)return this._connectPromise;return this._connectPromise=this._doConnect(),this._connectPromise}async _doConnect(){try{await this.loadData();let meta=this._getMeta();if(meta.queryCache)this._queryCache.fromJSON(meta.queryCache);if(this._migrations._migrations.length>0){let applied=meta.appliedVersions||[],newApplied=await this._migrations.run((version)=>this.useCollection(`_migration_${version}`),applied);this._saveMeta({appliedVersions:newApplied})}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(error222){throw this._logger(`Error connecting to the database: ${error222}`,"error"),error222}}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(error222){throw this._logger(`Error disconnecting from the database: ${error222}`,"error"),error222}}async _ensureConnected(){if(this.isConnected)return;return this.connect()}useCollection(collectionName){return this._registry.get(collectionName,this)}createCollection(collectionName,options={}){return this._registry.create(collectionName,options,this)}_createCollectionStore(collectionName,options={}){this._registry.createStore(collectionName,options)}async renameCollection(from,to){this._registry.rename(from,to),await this.saveData(to),await this.fs.delete(from)}async loadData(){await this._persistence.loadAll(this.collections,{parseSchema:parseSchema22,buildIndex:this._registry.buildIndex,IndexEngine:IndexEngine22});for(let name in this._collectionInstances){let store=this.collections[name];if(store&&this._collectionInstances[name]._store!==store)this._collectionInstances[name]._store=store}}async saveData(collectionName){await this._persistence.save(this.collections,collectionName)}buildIndex(data,keyField){return this._registry.buildIndex(data,keyField)}addMigration(migration){this._migrations.add(migration)}migrationStatus(){let meta=this._getMeta();return this._migrations.status(meta.appliedVersions||[])}namespace(id){if(this._adapterConfig)throw new AdapterError22("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 safeId=String(id).replace(/[^a-zA-Z0-9_-]/g,"_");if(!safeId)throw new ValidationError22("ERR_SKALEX_VALIDATION_NAMESPACE_ID","namespace: id must contain at least one alphanumeric character",{id});return new Skalex22({path:`${this.dataDirectory}/${safeId}`,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!==logger22?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!==_serialize22?this._serializer:void 0,deserializer:this._deserializer!==_deserialize22?this._deserializer:void 0,autoSave:this._autoSave||void 0,ttlSweepInterval:this._ttlSweepInterval||void 0})}use(plugin){this._plugins.register(plugin)}watch(callback){return this._eventBus.on("*",callback)}sessionStats(sessionId){if(sessionId!==void 0)return this._sessionStats.get(sessionId);return this._sessionStats.all()}get _inTransaction(){return this._txManager.active}_emitEvent(collectionName,data){if(!this._txManager.defer(()=>this._eventBus.emit(collectionName,data)))this._eventBus.emit(collectionName,data)}async _runAfterHook(hook,data){if(!this._txManager.defer(()=>this._plugins.run(hook,data)))await this._plugins.run(hook,data)}async _logChange(op,collectionName,doc,prev,session){if(!this._txManager.defer(()=>this._changeLog.log(op,collectionName,doc,prev,session)))await this._changeLog.log(op,collectionName,doc,prev,session)}async transaction(fn,opts={}){return this._txManager.run(fn,this,opts)}async seed(fixtures,{reset=!1}={}){for(let[name,docs]of Object.entries(fixtures)){if(reset&&this.collections[name])this._applySnapshot(name,{data:[],index:new Map}),delete this._collectionInstances[name];await this.useCollection(name).insertMany(docs)}await this.saveData()}dump(){return this._registry.dump()}inspect(collectionName){return this._registry.inspect(collectionName)}async import(filePath){let content=await this.fs.readRaw(filePath),docs;try{docs=JSON.parse(content)}catch{throw new PersistenceError22("ERR_SKALEX_PERSISTENCE_INVALID_JSON",`import: invalid JSON in file "${filePath}"`,{filePath})}let name=filePath.split("/").pop().replace(/\.[^.]+$/,"");return this.useCollection(name).insertMany(Array.isArray(docs)?docs:[docs],{save:!0})}async embed(text){if(!this._embeddingAdapter)throw new AdapterError22("ERR_SKALEX_ADAPTER_EMBEDDING_REQUIRED","db.embed() requires an AI adapter. Pass { ai: { provider, apiKey } } to the Skalex constructor.");return this._embeddingAdapter.embed(text)}async ask(collectionName,nlQuery,{limit=20}={}){if(!this._aiAdapter)throw new AdapterError22("ERR_SKALEX_ADAPTER_LLM_REQUIRED",'db.ask() requires a language model adapter. Configure { ai: { provider, model: "..." } }.');let col=this.useCollection(collectionName),schema=this.schema(collectionName),filter=this._queryCache.get(collectionName,schema,nlQuery);if(!filter){filter=await this._aiAdapter.generate(schema,nlQuery);let warnings=validateLLMFilter22(filter,schema);if(warnings.length)warnings.forEach((w)=>this._log(`[ask] ${w}`));this._queryCache.set(collectionName,schema,nlQuery,filter),this._saveMeta({queryCache:this._queryCache.toJSON()})}return col.find(processLLMFilter22(filter,{regexMaxLength:this._regexMaxLength}),{limit})}schema(collectionName){return this._registry.schema(collectionName)}useMemory(sessionId){return new Memory22(sessionId,this)}changelog(){return this._changeLog}async restore(collectionName,timestamp,opts={}){return this._changeLog.restore(collectionName,timestamp,opts)}stats(collectionName){return this._registry.stats(collectionName)}slowQueries(opts={}){if(!this._queryLog)return[];return this._queryLog.entries(opts)}slowQueryCount(){return this._queryLog?this._queryLog.size:0}clearSlowQueries(){this._queryLog?.clear()}mcp(opts={}){return new SkalexMCPServer22(this,opts)}_getMeta(){let metaCol=this.collections._meta;if(!metaCol)return{};return metaCol.index.get(META_KEY22)||{}}_saveMeta(data){if(!this.collections._meta)this._createCollectionStore("_meta");let col=this.collections._meta,existing=col.index.get(META_KEY22);if(existing)Object.assign(existing,data);else{let doc={_id:META_KEY22,...data};col.data.push(doc),col.index.set(META_KEY22,doc)}this._persistence.markDirty(this.collections,"_meta")}_sweepTtl(){for(let name in this.collections){let col=this.collections[name],removed=sweep22(col.data,col.index,col.fieldIndex?(doc)=>col.fieldIndex.remove(doc):null);if(removed>0)this._persistence.markDirty(this.collections,name),this._log(`TTL sweep: removed ${removed} expired docs from "${name}"`)}}_buildCollectionContext(){let db=this;return{ensureConnected:()=>db._ensureConnected(),get txManager(){return db._txManager},get plugins(){return db._plugins},get eventBus(){return db._eventBus},get sessionStats(){return db._sessionStats},get queryLog(){return db._queryLog},get logger(){return db._logger},get persistence(){return db._persistence},get collections(){return db.collections},embed:(text)=>db.embed(text),get idGenerator(){return db._idGenerator},get autoSave(){return db._autoSave},saveCollection:(name)=>db.saveData(name),snapshotCollection:(col)=>db._snapshotCollection(col),getCollection:(name)=>db.useCollection(name),emitEvent:(name,data)=>db._emitEvent(name,data),runAfterHook:(hook,data)=>db._runAfterHook(hook,data),logChange:(op,col,doc,prev,session)=>db._logChange(op,col,doc,prev,session),get fs(){return db.fs},get dataDirectory(){return db.dataDirectory}}}_log(msg){if(this.debug)this._logger(msg,"info")}_snapshotCollection(col){return{data:structuredClone(col.data)}}_applySnapshot(name,snap){let col=this.collections[name];if(!col)return;if(col.data=snap.data,col.index=this.buildIndex(snap.data,"_id"),col.fieldIndex)col.fieldIndex.buildFromData(snap.data)}}function generateUniqueId222(){let timestamp=Date.now().toString(16),random;try{random=nodeCrypto222.randomBytes(8).toString("hex")}catch{let arr=new Uint8Array(8);crypto.getRandomValues(arr),random=Array.from(arr).map((b)=>b.toString(16).padStart(2,"0")).join("")}return`${timestamp}${random}`}function logger222(error222,type){let msg=error222 instanceof Error?error222.message:error222;if(type==="error")console.error(msg);else console.log(msg)}var _FORBIDDEN_KEYS222=new Set(["__proto__","constructor","prototype"]);function resolveDotPath222(obj,path){if(!path.includes(".")){if(_FORBIDDEN_KEYS222.has(path))return;return obj[path]}let cur=obj;for(let p of path.split(".")){if(_FORBIDDEN_KEYS222.has(p))return;if(cur==null)return;cur=cur[p]}return cur}class SkalexError222 extends Error{constructor(code,message,details={}){super(message);this.name=this.constructor.name,this.code=code,this.details=details}}class ValidationError222 extends SkalexError222{}class UniqueConstraintError222 extends SkalexError222{}class TransactionError222 extends SkalexError222{}class PersistenceError222 extends SkalexError222{}class AdapterError222 extends SkalexError222{}class QueryError222 extends SkalexError222{}function deepEqual222(a,b){if(a===b)return!0;if(a==null||b==null)return!1;if(typeof a!==typeof b)return!1;if(a instanceof Date&&b instanceof Date)return a.getTime()===b.getTime();if(a instanceof RegExp&&b instanceof RegExp)return a.source===b.source&&a.flags===b.flags;if(Array.isArray(a)){if(!Array.isArray(b)||a.length!==b.length)return!1;for(let i=0;i<a.length;i++)if(!deepEqual222(a[i],b[i]))return!1;return!0}if(typeof a==="object"){if(Array.isArray(b))return!1;let keysA=Object.keys(a);if(keysA.length!==Object.keys(b).length)return!1;for(let k of keysA){if(!Object.prototype.hasOwnProperty.call(b,k))return!1;if(!deepEqual222(a[k],b[k]))return!1}return!0}return!1}function matchesFilter222(item,filter){if(typeof filter==="function")return filter(item);if(filter==null)return!0;if(typeof filter==="object"&&Object.keys(filter).length===0)return!0;if("$or"in filter){let branches=filter.$or;if(!Array.isArray(branches))throw new QueryError222("ERR_SKALEX_QUERY_INVALID_OPERATOR","$or must be an array of filters",{operator:"$or"});if(!branches.some((sub)=>matchesFilter222(item,sub)))return!1}if("$and"in filter){let branches=filter.$and;if(!Array.isArray(branches))throw new QueryError222("ERR_SKALEX_QUERY_INVALID_OPERATOR","$and must be an array of filters",{operator:"$and"});if(!branches.every((sub)=>matchesFilter222(item,sub)))return!1}if("$not"in filter){if(matchesFilter222(item,filter.$not))return!1}for(let key in filter){if(key==="$or"||key==="$and"||key==="$not")continue;let filterValue=filter[key],itemValue;try{itemValue=resolveDotPath222(item,key)}catch{return!1}if(filterValue instanceof RegExp){if(!filterValue.test(String(itemValue)))return!1}else if(typeof filterValue==="object"&&filterValue!==null){if(Object.keys(filterValue).some((k)=>k.startsWith("$"))){if("$eq"in filterValue&&itemValue!==filterValue.$eq)return!1;if("$ne"in filterValue&&itemValue===filterValue.$ne)return!1;if("$gt"in filterValue&&!(itemValue>filterValue.$gt))return!1;if("$lt"in filterValue&&!(itemValue<filterValue.$lt))return!1;if("$gte"in filterValue&&!(itemValue>=filterValue.$gte))return!1;if("$lte"in filterValue&&!(itemValue<=filterValue.$lte))return!1;if("$in"in filterValue&&!filterValue.$in.includes(itemValue))return!1;if("$nin"in filterValue&&filterValue.$nin.includes(itemValue))return!1;if("$regex"in filterValue){if(!(filterValue.$regex instanceof RegExp?filterValue.$regex:new RegExp(filterValue.$regex)).test(String(itemValue)))return!1}if("$fn"in filterValue&&!filterValue.$fn(itemValue))return!1}else if(!deepEqual222(itemValue,filterValue))return!1}else if(itemValue!==filterValue)return!1}return!0}function presortFilter222(filter,indexedFields=new Set){if(typeof filter!=="object"||filter===null||typeof filter==="function")return filter;let indexed=[],equality=[],range=[],expensive=[],logical=[];for(let key in filter){if(key==="$or"||key==="$and"||key==="$not"){logical.push(key);continue}let val=filter[key];if(indexedFields.has(key))indexed.push(key);else if(val instanceof RegExp||typeof val==="object"&&val!==null&&(("$regex"in val)||("$fn"in val))||typeof val==="function")expensive.push(key);else if(typeof val==="object"&&val!==null&&(("$gt"in val)||("$lt"in val)||("$gte"in val)||("$lte"in val)||("$ne"in val)||("$in"in val)||("$nin"in val)))range.push(key);else equality.push(key)}let sorted={};for(let k of[...indexed,...equality,...range,...expensive,...logical])sorted[k]=filter[k];return sorted}var SUPPORTED_TYPES222=new Set(["string","number","boolean","object","array","date","any"]);function typeOf222(val){if(Array.isArray(val))return"array";if(val instanceof Date)return"date";return typeof val}function parseSchema222(schema){let fields=new Map,uniqueFields=[];for(let[key,def]of Object.entries(schema)){let fieldDef;if(typeof def==="string"){if(!SUPPORTED_TYPES222.has(def))throw new ValidationError222("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${def}" for field "${key}"`,{field:key,type:def});fieldDef={type:def,required:!1,unique:!1}}else if(typeof def==="object"&&def!==null){let{type="any",required=!1,unique=!1,enum:enumVals}=def;if(!SUPPORTED_TYPES222.has(type))throw new ValidationError222("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${type}" for field "${key}"`,{field:key,type});if(fieldDef={type,required,unique,enum:enumVals},unique)uniqueFields.push(key)}else throw new ValidationError222("ERR_SKALEX_VALIDATION_INVALID_SCHEMA",`Invalid schema definition for field "${key}"`,{field:key});fields.set(key,fieldDef)}return{fields,uniqueFields}}function validateDoc222(doc,fields,strict=!1){let errors=[];for(let[key,def]of fields){let val=doc[key],missing=val===void 0||val===null;if(def.required&&missing){errors.push(`Field "${key}" is required`);continue}if(missing)continue;if(def.type!=="any"){let actualType=typeOf222(val);if(actualType!==def.type)errors.push(`Field "${key}" must be of type "${def.type}", got "${actualType}"`)}if(def.enum&&!def.enum.includes(val))errors.push(`Field "${key}" must be one of [${def.enum.map((v)=>JSON.stringify(v)).join(", ")}], got ${JSON.stringify(val)}`)}if(strict){for(let key of Object.keys(doc))if(!key.startsWith("_")&&!fields.has(key))errors.push(`Unknown field "${key}" (strict mode)`)}return errors}function stripInvalidFields222(doc,fields){let out={};for(let[key,val]of Object.entries(doc)){if(key.startsWith("_")){out[key]=val;continue}if(!fields.has(key))continue;let def=fields.get(key);if(def.type!=="any"){if(typeOf222(val)!==def.type)continue}if(def.enum&&!def.enum.includes(val))continue;out[key]=val}return out}function inferSchema222(doc){let schema={};for(let[key,val]of Object.entries(doc)){if(key.startsWith("_"))continue;let t=typeOf222(val);schema[key]=SUPPORTED_TYPES222.has(t)?t:"any"}return schema}function parseTtl222(ttl){if(typeof ttl==="number"){if(ttl<=0)throw new ValidationError222("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got ${ttl}`,{ttl});return ttl*1000}if(typeof ttl!=="string")throw new ValidationError222("ERR_SKALEX_VALIDATION_TTL",`Invalid TTL value: ${ttl}`,{ttl});let match=ttl.match(/^(\d+(?:\.\d+)?)(ms|s|m|h|d)$/);if(!match)throw new ValidationError222("ERR_SKALEX_VALIDATION_TTL_FORMAT",`Invalid TTL format: "${ttl}". Use e.g. 300 (seconds), "30m", "24h", "7d"`,{ttl});let val=parseFloat(match[1]);if(val<=0)throw new ValidationError222("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got "${ttl}"`,{ttl});let unit=match[2],ms=val*{ms:1,s:1000,m:60000,h:3600000,d:86400000}[unit];if(!isFinite(ms))throw new ValidationError222("ERR_SKALEX_VALIDATION_TTL",`TTL value "${ttl}" is too large`,{ttl});return ms}function computeExpiry222(ttl){return new Date(Date.now()+parseTtl222(ttl))}function sweep222(data,idIndex,removeFromIndexes=null){let now=Date.now(),removed=0,i=data.length;while(i--){let doc=data[i];if(doc._expiresAt&&new Date(doc._expiresAt).getTime()<=now){if(data.splice(i,1),idIndex.delete(doc._id),removeFromIndexes)removeFromIndexes(doc);removed++}}return removed}function cosineSimilarity222(a,b){if(a.length!==b.length)throw new QueryError222("ERR_SKALEX_QUERY_VECTOR_MISMATCH",`Vector dimension mismatch: ${a.length} vs ${b.length}`,{expected:a.length,got:b.length});let dot=0,magA=0,magB=0;for(let i=0;i<a.length;i++)dot+=a[i]*b[i],magA+=a[i]*a[i],magB+=b[i]*b[i];let denom=Math.sqrt(magA*magB);return denom===0?0:dot/denom}function stripVector222(doc){if(!("_vector"in doc))return{...doc};let{_vector,...rest}=doc;return rest}function count222(docs){return docs.length}function sum222(docs,field){let total=0;for(let doc of docs){let val=resolveDotPath222(doc,field);if(typeof val==="number"&&!isNaN(val))total+=val}return total}function avg222(docs,field){let total=0,n=0;for(let doc of docs){let val=resolveDotPath222(doc,field);if(typeof val==="number"&&!isNaN(val))total+=val,n++}return n===0?null:total/n}function groupBy222(docs,field){let groups=Object.create(null);for(let doc of docs){let key=String(resolveDotPath222(doc,field)??"__null__");if(!groups[key])groups[key]=[];groups[key].push(doc)}return groups}class MutationPipeline222{constructor(collection){this._col=collection}get _ctx(){return this._col._ctx}async execute({op,beforeHook,afterHook,hookPayload,mutate,afterHookPayload,save,session}){let ctx=this._ctx;await ctx.ensureConnected(),this._col._txSnapshotIfNeeded();let txm=ctx.txManager,isTxWrite=txm.active&&this._col._activeTxId===txm.context?.id,entryTxId=isTxWrite?txm.context.id:null,collTxId=this._col._createdInTxId,assertTxAlive=()=>{if(entryTxId!==null&&txm._abortedIds.has(entryTxId))throw new TransactionError222("ERR_SKALEX_TX_ABORTED",`Transaction ${entryTxId} was aborted. No further mutations allowed.`);if(collTxId!==null&&txm._abortedIds.has(collTxId))throw new TransactionError222("ERR_SKALEX_TX_ABORTED",`Transaction ${collTxId} was aborted. Collection obtained inside that transaction cannot be used for further mutations.`)};if(isTxWrite||collTxId!==null)assertTxAlive();if(beforeHook)await ctx.plugins.run(beforeHook,hookPayload);let{docs,prevDocs=[]}=await mutate(assertTxAlive);if(ctx.persistence.markDirty(ctx.collections,this._col.name),await this._col._saveIfNeeded(save),this._col._changelogEnabled)for(let i=0;i<docs.length;i++)await ctx.logChange(op,this._col.name,docs[i],prevDocs[i]??null,session||null);if(!isTxWrite||!txm.defer(()=>ctx.sessionStats.recordWrite(session)))ctx.sessionStats.recordWrite(session);for(let doc of docs)ctx.emitEvent(this._col.name,{op,collection:this._col.name,doc:stripVector222(doc)});if(afterHook)if(afterHookPayload)await ctx.runAfterHook(afterHook,afterHookPayload(docs));else for(let doc of docs)await ctx.runAfterHook(afterHook,{collection:this._col.name,doc:stripVector222(doc)});return{docs,prevDocs}}}function resolveFilterToValues222(filter){let resolved={};for(let key in filter){if(key.startsWith("$"))continue;let val=filter[key];if(val&&typeof val==="object"&&!Array.isArray(val)){let keys=Object.keys(val);if(keys.length===1&&keys[0]==="$eq")resolved[key]=val.$eq}else resolved[key]=val}return resolved}var _DANGEROUS_KEYS222=new Set(["__proto__","constructor","prototype"]);function stripDangerousKeys222(val){if(typeof val!=="object"||val===null||Array.isArray(val))return val;let out={};for(let k of Object.keys(val)){if(_DANGEROUS_KEYS222.has(k))continue;out[k]=stripDangerousKeys222(val[k])}return out}class Collection222{constructor(collectionData,database){this.name=collectionData.collectionName,this.database=database,this._ctx=database._buildCollectionContext(),this._store=collectionData,this._pipeline=new MutationPipeline222(this),this._createdInTxId=database._txManager.context?.id??null,this._activeTxId=null}get _data(){return this._store.data}set _data(val){this._store.data=val}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(item,options={}){let{save,ifNotExists,ttl,embed,session}=options;if(ifNotExists){await this._ctx.ensureConnected();let existing=this._findRaw(item);if(existing)return stripVector222({...existing})}let{docs}=await this._insertCore([item],{ttl,embed,session,save});return stripVector222(docs[0])}async insertMany(items,options={}){let{save,ttl,embed,session}=options,{docs}=await this._insertCore(items,{ttl,embed,session,save});return docs.map(stripVector222)}async _insertCore(items,{ttl,embed,session,save}){return this._pipeline.execute({op:"insert",beforeHook:null,afterHook:"afterInsert",hookPayload:null,save,session,mutate:async(assertTxAlive)=>{let newItems=[],batchIds=new Set;for(let item of items){let validated=this._applyValidation(item);await this._ctx.plugins.run("beforeInsert",{collection:this.name,doc:validated});let newItem=await this._buildDoc(validated,{ttl,embed});if(this._index.has(newItem._id)||batchIds.has(newItem._id))throw new UniqueConstraintError222("ERR_SKALEX_UNIQUE_DUPLICATE_ID",`Duplicate _id "${newItem._id}" in collection "${this.name}"`,{id:newItem._id,collection:this.name});batchIds.add(newItem._id),newItems.push(newItem)}if(assertTxAlive(),this._fieldIndex)this._fieldIndex.assertUniqueBatch(newItems);for(let newItem of newItems)this._addToIndex(newItem);this._data.push(...newItems);for(let newItem of newItems)this._index.set(newItem._id,newItem);return this._enforceCapAfterInsert(),{docs:newItems}}})}async updateOne(filter,update,options={}){await this._ctx.ensureConnected();let oldDoc=this._findRaw(filter);if(!oldDoc)return null;let{save,session}=options,{docs}=await this._updateCore([oldDoc],filter,update,{save,session});return stripVector222(docs[0])}async updateMany(filter,update,options={}){await this._ctx.ensureConnected();let oldDocs=this._findAllRaw(filter);if(oldDocs.length===0)return[];let{save,session}=options,{docs}=await this._updateCore(oldDocs,filter,update,{save,session});return docs.map(stripVector222)}async _updateCore(oldDocs,filter,update,{save,session}){return this._pipeline.execute({op:"update",beforeHook:"beforeUpdate",afterHook:"afterUpdate",hookPayload:{collection:this.name,filter,update},save,session,afterHookPayload:(docs)=>({collection:this.name,filter,update,result:docs.length===1?docs[0]:docs}),mutate:async(assertTxAlive)=>{let prevDocs=this._changelogEnabled?oldDocs.map((doc)=>structuredClone(doc)):oldDocs.map(()=>null),nextDocs=oldDocs.map((doc)=>this._prepareUpdatedDoc(doc,update));this._assertUniqueCandidates(oldDocs,nextDocs),assertTxAlive();let targets=new Set(oldDocs),positions=new Map;for(let i=0;i<this._data.length;i++)if(targets.has(this._data[i]))positions.set(this._data[i],i);for(let i=0;i<oldDocs.length;i++)this._commitUpdatedDoc(oldDocs[i],nextDocs[i],positions);return{docs:nextDocs,prevDocs}}})}applyUpdate(item,update){for(let field in update){if(_DANGEROUS_KEYS222.has(field))continue;if(field==="_id"||field==="createdAt")continue;let updateValue=update[field];if(Array.isArray(updateValue))item[field]=updateValue;else if(typeof updateValue==="object"&&updateValue!==null){let keys=Object.keys(updateValue);if(keys.some((k)=>k.startsWith("$"))){for(let key of keys)if(key==="$inc"&&typeof item[field]==="number")item[field]+=updateValue[key];else if(key==="$push"){if(!Array.isArray(item[field]))item[field]=[];item[field].push(updateValue[key])}}else item[field]=stripDangerousKeys222(updateValue)}else item[field]=updateValue}if(item.updatedAt=new Date,this._versioning)item._version=(item._version??0)+1;return item}_prepareUpdatedDoc(currentDoc,update){let prev=structuredClone(currentDoc),next=structuredClone(currentDoc);if(this.applyUpdate(next,update),!this._schema)return next;let errors=validateDoc222(next,this._schema,this._strict);if(!errors.length)return next;switch(this._onSchemaError){case"throw":throw new ValidationError222("ERR_SKALEX_VALIDATION_UPDATE",`Update validation failed on doc "${currentDoc._id}": ${errors.join("; ")}`,{id:currentDoc._id,errors});case"strip":return this._stripCandidateToValid(next,prev);default:return this._ctx.logger(`[${this.name}] Update validation warning: ${errors.join("; ")}`,"warn"),next}}_stripCandidateToValid(next,prev){let stripped=stripInvalidFields222(next,this._schema),merged=structuredClone(prev);for(let[key,val]of Object.entries(stripped)){if(key.startsWith("_"))continue;merged[key]=val}if(merged.updatedAt=next.updatedAt,this._versioning)merged._version=next._version;return merged}_commitUpdatedDoc(oldDoc,newDoc,positions){let idx=positions?positions.get(oldDoc):this._data.indexOf(oldDoc);if(idx===void 0||idx===-1)throw new PersistenceError222("ERR_SKALEX_PERSISTENCE_DOC_MISSING",`Document "${oldDoc._id}" no longer exists in collection "${this.name}"`,{id:oldDoc._id,collection:this.name});this._data[idx]=newDoc,this._index.set(newDoc._id,newDoc),this._updateInIndex(oldDoc,newDoc)}_assertUniqueCandidates(oldDocs,nextDocs){this._fieldIndex?.assertUniqueCandidates(oldDocs,nextDocs)}async upsert(filter,doc,options={}){if(await this._ctx.ensureConnected(),this._findRaw(filter))return this.updateOne(filter,doc,options);return this.insertOne({...resolveFilterToValues222(filter),...doc},options)}async upsertMany(docs,matchKey,options={}){await this._ctx.ensureConnected();let{save,...rest}=options,results=[];for(let doc of docs)results.push(await this.upsert({[matchKey]:doc[matchKey]},doc,{...rest,save:!1}));return await this._saveIfNeeded(save),results}async restore(filter,options={}){if(!this._softDelete)throw new QueryError222("ERR_SKALEX_QUERY_SOFT_DELETE_REQUIRED",`restore() requires softDelete on "${this.name}"`,{collection:this.name});await this._ctx.ensureConnected();let{save,session}=options,item=this._findRaw(filter,{includeDeleted:!0});if(!item||!item._deletedAt)return null;let{docs}=await this._pipeline.execute({op:"restore",beforeHook:null,afterHook:null,hookPayload:null,save,session,mutate:async(assertTxAlive)=>{return assertTxAlive(),delete item._deletedAt,item.updatedAt=new Date,this._index.set(item._id,item),{docs:[item]}}});return stripVector222(docs[0])}watch(filter,callback){if(typeof filter==="function")callback=filter,filter=null;if(callback)return this._ctx.eventBus.on(this.name,(event)=>{if(!filter||matchesFilter222(event.doc,filter))callback(event)});return this._watchIterator(filter)}_watchIterator(filter){let queue=[],resolve=null,done=!1,unsub=this._ctx.eventBus.on(this.name,(event)=>{if(filter&&!matchesFilter222(event.doc,filter))return;if(resolve){let r=resolve;resolve=null,r({value:event,done:!1})}else queue.push(event)});return{[Symbol.asyncIterator](){return this},next(){if(queue.length>0)return Promise.resolve({value:queue.shift(),done:!1});if(done)return Promise.resolve({value:void 0,done:!0});return new Promise((res)=>{resolve=res})},return(){if(done=!0,unsub(),resolve){let r=resolve;resolve=null,r({value:void 0,done:!0})}return Promise.resolve({value:void 0,done:!0})}}}async count(filter={}){return await this._ctx.ensureConnected(),count222(this._findAllRaw(filter))}async sum(field,filter={}){return await this._ctx.ensureConnected(),sum222(this._findAllRaw(filter),field)}async avg(field,filter={}){return await this._ctx.ensureConnected(),avg222(this._findAllRaw(filter),field)}async groupBy(field,filter={}){return await this._ctx.ensureConnected(),groupBy222(this._findAllRaw(filter),field)}async findOne(filter,options={}){await this._ctx.ensureConnected();let{populate,select,includeDeleted=!1}=options,item=this._findRaw(filter,{includeDeleted});if(!item)return null;let newItem=this._projectDoc(item,select);if(populate)await this._populateDoc(newItem,item,populate);return newItem}async find(filter,options={}){await this._ctx.ensureConnected();let _t0=Date.now(),{populate,select,sort,page=1,limit,session,includeDeleted=!1}=options;await this._ctx.plugins.run("beforeFind",{collection:this.name,filter,options});let candidates=this._getCandidates(filter),sortedFilter=presortFilter222(filter,this._fieldIndex?this._fieldIndex.indexedFields:new Set),results=[];for(let item of candidates){if(this._softDelete&&item._deletedAt&&!includeDeleted)continue;if(!matchesFilter222(item,sortedFilter))continue;let newItem=this._projectDoc(item,select);if(populate)await this._populateDoc(newItem,item,populate);results.push(newItem)}if(sort){let sortFields=Object.keys(sort);results.sort((a,b)=>{for(let field of sortFields){let dir=sort[field];if(a[field]<b[field])return-dir;if(a[field]>b[field])return dir}return 0})}let extra;if(limit){let totalDocs=results.length,totalPages=Math.ceil(totalDocs/limit),startIndex=(page-1)*limit;results=results.slice(startIndex,startIndex+limit),extra={page,totalDocs,totalPages}}return this._ctx.queryLog?.record({collection:this.name,op:"find",filter,duration:Date.now()-_t0,resultCount:results.length}),this._ctx.sessionStats.recordRead(session),await this._ctx.plugins.run("afterFind",{collection:this.name,filter,options,docs:results}),extra?{docs:results,...extra}:{docs:results}}async search(query,{filter,limit=10,minScore=0,session}={}){await this._ctx.ensureConnected();let _t0=Date.now();await this._ctx.plugins.run("beforeSearch",{collection:this.name,query,options:{filter,limit,minScore}});let queryVector=await this._ctx.embed(query),candidates=filter?this._findAllRaw(filter):this._data,scored=[];for(let doc of candidates){if(!doc._vector)continue;let score=cosineSimilarity222(queryVector,doc._vector);if(score>=minScore)scored.push({doc,score})}scored.sort((a,b)=>b.score-a.score);let top=scored.slice(0,limit);this._ctx.queryLog?.record({collection:this.name,op:"search",query,duration:Date.now()-_t0,resultCount:top.length}),this._ctx.sessionStats.recordRead(session);let docs=top.map((r)=>stripVector222(r.doc)),scores=top.map((r)=>r.score);return await this._ctx.plugins.run("afterSearch",{collection:this.name,query,options:{filter,limit,minScore},docs,scores}),{docs,scores}}async similar(id,{limit=10,minScore=0}={}){await this._ctx.ensureConnected();let source=this._index.get(id);if(!source||!source._vector)return{docs:[],scores:[]};let scored=[];for(let doc of this._data){if(doc._id===id||!doc._vector)continue;let score=cosineSimilarity222(source._vector,doc._vector);if(score>=minScore)scored.push({doc,score})}scored.sort((a,b)=>b.score-a.score);let top=scored.slice(0,limit);return{docs:top.map((r)=>stripVector222(r.doc)),scores:top.map((r)=>r.score)}}async deleteOne(filter,options={}){await this._ctx.ensureConnected();let{save,session}=options;if(this._softDelete){let item=this._findRaw(filter);if(!item)return null;let{docs:docs2}=await this._deleteCore("soft",[item],filter,{save,session});return stripVector222(docs2[0])}let{docs}=await this._deleteCore("hard",null,filter,{save,session});if(docs.length===0)return null;return stripVector222(docs[0])}async deleteMany(filter,options={}){await this._ctx.ensureConnected();let{save,session}=options;if(this._softDelete){let items=this._findAllRaw(filter);if(items.length===0)return[];let{docs:docs2}=await this._deleteCore("soft",items,filter,{save,session});return docs2.map(stripVector222)}let{docs}=await this._deleteCore("hardMany",null,filter,{save,session});return docs.map(stripVector222)}async _deleteCore(mode,items,filter,{save,session}){return this._pipeline.execute({op:"delete",beforeHook:"beforeDelete",afterHook:"afterDelete",hookPayload:{collection:this.name,filter},save,session,afterHookPayload:(docs)=>({collection:this.name,filter,result:docs.length===1?docs[0]:docs}),mutate:async(assertTxAlive)=>{if(assertTxAlive(),mode==="soft"){let now=new Date;for(let item of items)item._deletedAt=now,item.updatedAt=now,this._index.set(item._id,item);return{docs:items}}if(mode==="hard"){let idx=this._findIndex(filter);if(idx===-1)return{docs:[]};let deletedItem=this._data.splice(idx,1)[0];return this._index.delete(deletedItem._id),this._removeFromIndex(deletedItem),{docs:[deletedItem]}}let deletedItems=[],remainingItems=[];for(let item of this._data)if(matchesFilter222(item,filter))deletedItems.push(item),this._index.delete(item._id),this._removeFromIndex(item);else remainingItems.push(item);return this._data=remainingItems,{docs:deletedItems}}})}async export(filter={},options={}){let{dir,name,format="json"}=options;try{let filteredData=this._data.filter((item)=>matchesFilter222(item,filter));if(filteredData.length===0)throw new QueryError222("ERR_SKALEX_QUERY_EXPORT_EMPTY",`export(): no documents matched the filter in "${this.name}"`,{collection:this.name});let content;if(format==="json")content=JSON.stringify(filteredData,null,2);else{let escapeCsv=(v)=>{if(v==null)return"";let s=typeof v==="object"?JSON.stringify(v):String(v);return s.includes(",")||s.includes('"')||s.includes(`
81
+ `))!==-1){let line=this._buffer.slice(0,idx).trim();if(this._buffer=this._buffer.slice(idx+1),line&&this._onMessage){let msg;try{msg=JSON.parse(line)}catch(_){this.send(error22(null,PARSE_ERROR22,"Parse error"));continue}this._onMessage(msg).catch(()=>{})}}}),process.stdin.on("end",()=>{process.exit(0)})}stop(){process.stdin.removeAllListeners("data"),process.stdin.removeAllListeners("end"),this._started=!1}}var SERVER_INFO22={name:"skalex",version:"4.0.0-alpha"},PROTOCOL_VERSION22="2024-11-05";class SkalexMCPServer22{constructor(db,opts={}){this._db=db,this._transport=opts.transport||"stdio",this._port=opts.port||3000,this._host=opts.host||"127.0.0.1",this._allowedOrigin=opts.allowedOrigin??null,this._maxBodySize=opts.maxBodySize??1048576,this._scopes=opts.scopes||{"*":["read"]},this._t=null}async listen(){if(this._transport==="http")this._t=new HttpTransport22({port:this._port,host:this._host,allowedOrigin:this._allowedOrigin,maxBodySize:this._maxBodySize});else this._t=new StdioTransport22;this._t.onMessage((msg)=>this._handleMessage(msg)),await this._t.start()}async connect(transport){if(this._t=transport,this._t.onMessage((msg)=>this._handleMessage(msg)),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(raw){let{msg,parseError}=typeof raw==="string"?parse22(raw):{msg:raw};if(parseError){this._send(parseError);return}let{id,method,params}=msg;if(id===void 0){if(method==="notifications/initialized")return;return}try{switch(method){case"initialize":this._send(ok22(id,{protocolVersion:PROTOCOL_VERSION22,capabilities:{tools:{}},serverInfo:SERVER_INFO22}));break;case"tools/list":this._send(ok22(id,{tools:this._visibleTools()}));break;case"tools/call":await this._handleToolCall(id,params);break;case"ping":this._send(ok22(id,{}));break;default:this._send(error22(id,METHOD_NOT_FOUND22,`Method not found: ${method}`))}}catch(err){this._send(error22(id,INTERNAL_ERROR22,err.message||"Internal error"))}}async _handleToolCall(id,params){let name=params?.name,args=params?.arguments??{};if(!name){this._send(error22(id,INVALID_PARAMS22,"tools/call requires params.name"));return}let def=TOOL_DEFS22.find((t)=>t.name===name);if(!def){this._send(error22(id,METHOD_NOT_FOUND22,`Unknown tool: ${name}`));return}let collection=args.collection||args.collection_name||null;if(!this._hasScope(collection,def.scope)){this._send(ok22(id,toolError22(`Access denied: "${name}" requires "${def.scope}" scope on collection "${collection}".`)));return}try{let result=await callTool22(name,args,this._db);this._send(ok22(id,toolResult22(JSON.stringify(result,null,2))))}catch(err){this._send(ok22(id,toolError22(err.message||String(err))))}}_visibleTools(){return TOOL_DEFS22.filter((def)=>{let global=this._scopes["*"];if(global&&(global.includes(def.scope)||global.includes("admin")))return!0;for(let[,perms]of Object.entries(this._scopes))if(perms.includes(def.scope)||perms.includes("admin"))return!0;return!1})}_hasScope(collection,scope){let check=(perms)=>perms.includes("admin")||perms.includes(scope);if(collection&&this._scopes[collection])return check(this._scopes[collection]);if(this._scopes["*"])return check(this._scopes["*"]);return!1}_send(msg){this._t?.send(msg)}}var META_KEY22="migrations",_serialize22=(value)=>JSON.stringify(value,function(key,v){let raw=this[key];if(raw instanceof Date)return{__skalex_date__:raw.toISOString()};if(typeof v==="bigint")return{__skalex_bigint__:v.toString()};return v}),_deserialize22=(text)=>JSON.parse(text,(_,v)=>{if(v&&typeof v==="object"){if("__skalex_bigint__"in v)return BigInt(v.__skalex_bigint__);if("__skalex_date__"in v)return new Date(v.__skalex_date__)}return v});class Skalex22{constructor({path="./.db",format="gz",debug=!1,adapter,ai,encrypt,slowQueryLog,queryCache,memory,logger:logger$1,plugins,llmAdapter,embeddingAdapter,regexMaxLength,idGenerator,serializer,deserializer,autoSave,ttlSweepInterval,lenientLoad}={}){if(this.dataDirectory=path,this.dataFormat=format,this.debug=debug,!Skalex22._errorsAttached)Skalex22.SkalexError=SkalexError22,Skalex22.ValidationError=ValidationError22,Skalex22.UniqueConstraintError=UniqueConstraintError22,Skalex22.TransactionError=TransactionError22,Skalex22.PersistenceError=PersistenceError22,Skalex22.AdapterError=AdapterError22,Skalex22.QueryError=QueryError22,Skalex22._errorsAttached=!0;this._adapterConfig=adapter??null;let fs=adapter||new FsAdapter22({dir:path,format});if(encrypt)fs=new EncryptedAdapter22(fs,encrypt.key);if(this.fs=fs,this._registry=new CollectionRegistry22(Collection22),this.collections=this._registry.stores,this._collectionInstances=this._registry._instances,this._migrations=new MigrationEngine22,this._connectPromise=null,this.isConnected=!1,this._aiConfig=ai||null,this._encryptConfig=encrypt||null,this._pluginsConfig=Array.isArray(plugins)?plugins:null,this._memoryConfig=memory||null,this._regexMaxLength=regexMaxLength??500,this._idGenerator=idGenerator??null,this._serializer=serializer??_serialize22,this._deserializer=deserializer??_deserialize22,this._autoSave=autoSave??!1,this._txManager=new TransactionManager22,this._ttlSweepInterval=ttlSweepInterval??0,this._ttlTimer=null,this._logger=logger$1??logger22,this._embeddingAdapter=embeddingAdapter??(ai?createEmbeddingAdapter22(ai):null),this._aiAdapter=llmAdapter??(ai?createLLMAdapter22(ai):null),this._persistence=new PersistenceManager22({adapter:this.fs,serializer:this._serializer,deserializer:this._deserializer,logger:this._logger,debug:this.debug,lenientLoad:lenientLoad??!1}),this._changeLog=new ChangeLog22(this),this._queryCache=new QueryCache22(queryCache||{}),this._eventBus=new EventBus22,this._queryLog=slowQueryLog?new QueryLog22(slowQueryLog):null,this._sessionStats=new SessionStats22,this._plugins=new PluginEngine22,Array.isArray(plugins))for(let p of plugins)this._plugins.register(p)}async connect(){if(this._connectPromise)return this._connectPromise;return this._connectPromise=this._doConnect(),this._connectPromise}async _doConnect(){try{await this.loadData();let meta=this._getMeta();if(meta.queryCache)this._queryCache.fromJSON(meta.queryCache);if(this._migrations._migrations.length>0){let applied=meta.appliedVersions||[],newApplied=await this._migrations.run((version)=>this.useCollection(`_migration_${version}`),applied);this._saveMeta({appliedVersions:newApplied})}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(error222){throw this._logger(`Error connecting to the database: ${error222}`,"error"),error222}}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(error222){throw this._logger(`Error disconnecting from the database: ${error222}`,"error"),error222}}async _ensureConnected(){if(this.isConnected)return;return this.connect()}useCollection(collectionName){return this._registry.get(collectionName,this)}createCollection(collectionName,options={}){return this._registry.create(collectionName,options,this)}_createCollectionStore(collectionName,options={}){this._registry.createStore(collectionName,options)}async renameCollection(from,to){this._registry.rename(from,to),await this.saveData(to),await this.fs.delete(from)}async loadData(){await this._persistence.loadAll(this.collections,{parseSchema:parseSchema22,buildIndex:this._registry.buildIndex,IndexEngine:IndexEngine22});for(let name in this._collectionInstances){let store=this.collections[name];if(store&&this._collectionInstances[name]._store!==store)this._collectionInstances[name]._store=store}}async saveData(collectionName){await this._persistence.save(this.collections,collectionName)}buildIndex(data,keyField){return this._registry.buildIndex(data,keyField)}addMigration(migration){this._migrations.add(migration)}migrationStatus(){let meta=this._getMeta();return this._migrations.status(meta.appliedVersions||[])}namespace(id){if(this._adapterConfig)throw new AdapterError22("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 safeId=String(id).replace(/[^a-zA-Z0-9_-]/g,"_");if(!safeId)throw new ValidationError22("ERR_SKALEX_VALIDATION_NAMESPACE_ID","namespace: id must contain at least one alphanumeric character",{id});return new Skalex22({path:`${this.dataDirectory}/${safeId}`,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!==logger22?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!==_serialize22?this._serializer:void 0,deserializer:this._deserializer!==_deserialize22?this._deserializer:void 0,autoSave:this._autoSave||void 0,ttlSweepInterval:this._ttlSweepInterval||void 0})}use(plugin){this._plugins.register(plugin)}watch(callback){return this._eventBus.on("*",callback)}sessionStats(sessionId){if(sessionId!==void 0)return this._sessionStats.get(sessionId);return this._sessionStats.all()}get _inTransaction(){return this._txManager.active}_emitEvent(collectionName,data){if(!this._txManager.defer(()=>this._eventBus.emit(collectionName,data)))this._eventBus.emit(collectionName,data)}async _runAfterHook(hook,data){if(!this._txManager.defer(()=>this._plugins.run(hook,data)))await this._plugins.run(hook,data)}async _logChange(op,collectionName,doc,prev,session){if(!this._txManager.defer(()=>this._changeLog.log(op,collectionName,doc,prev,session)))await this._changeLog.log(op,collectionName,doc,prev,session)}async transaction(fn,opts={}){return this._txManager.run(fn,this,opts)}async seed(fixtures,{reset=!1}={}){for(let[name,docs]of Object.entries(fixtures)){if(reset&&this.collections[name])this._applySnapshot(name,{data:[],index:new Map}),delete this._collectionInstances[name];await this.useCollection(name).insertMany(docs)}await this.saveData()}dump(){return this._registry.dump()}inspect(collectionName){return this._registry.inspect(collectionName)}async import(filePath){let content=await this.fs.readRaw(filePath),docs;try{docs=JSON.parse(content)}catch{throw new PersistenceError22("ERR_SKALEX_PERSISTENCE_INVALID_JSON",`import: invalid JSON in file "${filePath}"`,{filePath})}let name=filePath.split("/").pop().replace(/\.[^.]+$/,"");return this.useCollection(name).insertMany(Array.isArray(docs)?docs:[docs],{save:!0})}async embed(text){if(!this._embeddingAdapter)throw new AdapterError22("ERR_SKALEX_ADAPTER_EMBEDDING_REQUIRED","db.embed() requires an AI adapter. Pass { ai: { provider, apiKey } } to the Skalex constructor.");return this._embeddingAdapter.embed(text)}async ask(collectionName,nlQuery,{limit=20}={}){if(!this._aiAdapter)throw new AdapterError22("ERR_SKALEX_ADAPTER_LLM_REQUIRED",'db.ask() requires a language model adapter. Configure { ai: { provider, model: "..." } }.');let col=this.useCollection(collectionName),schema=this.schema(collectionName),filter=this._queryCache.get(collectionName,schema,nlQuery);if(!filter){filter=await this._aiAdapter.generate(schema,nlQuery);let warnings=validateLLMFilter22(filter,schema);if(warnings.length)warnings.forEach((w)=>this._log(`[ask] ${w}`));this._queryCache.set(collectionName,schema,nlQuery,filter),this._saveMeta({queryCache:this._queryCache.toJSON()})}return col.find(processLLMFilter22(filter,{regexMaxLength:this._regexMaxLength}),{limit})}schema(collectionName){return this._registry.schema(collectionName)}useMemory(sessionId){return new Memory22(sessionId,this)}changelog(){return this._changeLog}async restore(collectionName,timestamp,opts={}){return this._changeLog.restore(collectionName,timestamp,opts)}stats(collectionName){return this._registry.stats(collectionName)}slowQueries(opts={}){if(!this._queryLog)return[];return this._queryLog.entries(opts)}slowQueryCount(){return this._queryLog?this._queryLog.size:0}clearSlowQueries(){this._queryLog?.clear()}mcp(opts={}){return new SkalexMCPServer22(this,opts)}_getMeta(){let metaCol=this.collections._meta;if(!metaCol)return{};return metaCol.index.get(META_KEY22)||{}}_saveMeta(data){if(!this.collections._meta)this._createCollectionStore("_meta");let col=this.collections._meta,existing=col.index.get(META_KEY22);if(existing)Object.assign(existing,data);else{let doc={_id:META_KEY22,...data};col.data.push(doc),col.index.set(META_KEY22,doc)}this._persistence.markDirty(this.collections,"_meta")}_sweepTtl(){for(let name in this.collections){let col=this.collections[name],removed=sweep22(col.data,col.index,col.fieldIndex?(doc)=>col.fieldIndex.remove(doc):null);if(removed>0)this._persistence.markDirty(this.collections,name),this._log(`TTL sweep: removed ${removed} expired docs from "${name}"`)}}_buildCollectionContext(){let db=this;return{ensureConnected:()=>db._ensureConnected(),get txManager(){return db._txManager},get plugins(){return db._plugins},get eventBus(){return db._eventBus},get sessionStats(){return db._sessionStats},get queryLog(){return db._queryLog},get logger(){return db._logger},get persistence(){return db._persistence},get collections(){return db.collections},embed:(text)=>db.embed(text),get idGenerator(){return db._idGenerator},get autoSave(){return db._autoSave},saveCollection:(name)=>db.saveData(name),snapshotCollection:(col)=>db._snapshotCollection(col),getCollection:(name)=>db.useCollection(name),emitEvent:(name,data)=>db._emitEvent(name,data),runAfterHook:(hook,data)=>db._runAfterHook(hook,data),logChange:(op,col,doc,prev,session)=>db._logChange(op,col,doc,prev,session),get fs(){return db.fs},get dataDirectory(){return db.dataDirectory}}}_log(msg){if(this.debug)this._logger(msg,"info")}_snapshotCollection(col){return{data:structuredClone(col.data)}}_applySnapshot(name,snap){let col=this.collections[name];if(!col)return;if(col.data=snap.data,col.index=this.buildIndex(snap.data,"_id"),col.fieldIndex)col.fieldIndex.buildFromData(snap.data)}}function generateUniqueId222(){let timestamp=Date.now().toString(16),random;try{random=nodeCrypto222.randomBytes(8).toString("hex")}catch{let arr=new Uint8Array(8);crypto.getRandomValues(arr),random=Array.from(arr).map((b)=>b.toString(16).padStart(2,"0")).join("")}return`${timestamp}${random}`}function logger222(error222,type){let msg=error222 instanceof Error?error222.message:error222;if(type==="error")console.error(msg);else console.log(msg)}var _FORBIDDEN_KEYS222=new Set(["__proto__","constructor","prototype"]);function resolveDotPath222(obj,path){if(!path.includes(".")){if(_FORBIDDEN_KEYS222.has(path))return;return obj[path]}let cur=obj;for(let p of path.split(".")){if(_FORBIDDEN_KEYS222.has(p))return;if(cur==null)return;cur=cur[p]}return cur}class SkalexError222 extends Error{constructor(code,message,details={}){super(message);this.name=this.constructor.name,this.code=code,this.details=details}}class ValidationError222 extends SkalexError222{}class UniqueConstraintError222 extends SkalexError222{}class TransactionError222 extends SkalexError222{}class PersistenceError222 extends SkalexError222{}class AdapterError222 extends SkalexError222{}class QueryError222 extends SkalexError222{}function deepEqual222(a,b){if(a===b)return!0;if(a==null||b==null)return!1;if(typeof a!==typeof b)return!1;if(a instanceof Date&&b instanceof Date)return a.getTime()===b.getTime();if(a instanceof RegExp&&b instanceof RegExp)return a.source===b.source&&a.flags===b.flags;if(Array.isArray(a)){if(!Array.isArray(b)||a.length!==b.length)return!1;for(let i=0;i<a.length;i++)if(!deepEqual222(a[i],b[i]))return!1;return!0}if(typeof a==="object"){if(Array.isArray(b))return!1;let keysA=Object.keys(a);if(keysA.length!==Object.keys(b).length)return!1;for(let k of keysA){if(!Object.prototype.hasOwnProperty.call(b,k))return!1;if(!deepEqual222(a[k],b[k]))return!1}return!0}return!1}function matchesFilter222(item,filter){if(typeof filter==="function")return filter(item);if(filter==null)return!0;if(typeof filter==="object"&&Object.keys(filter).length===0)return!0;if("$or"in filter){let branches=filter.$or;if(!Array.isArray(branches))throw new QueryError222("ERR_SKALEX_QUERY_INVALID_OPERATOR","$or must be an array of filters",{operator:"$or"});if(!branches.some((sub)=>matchesFilter222(item,sub)))return!1}if("$and"in filter){let branches=filter.$and;if(!Array.isArray(branches))throw new QueryError222("ERR_SKALEX_QUERY_INVALID_OPERATOR","$and must be an array of filters",{operator:"$and"});if(!branches.every((sub)=>matchesFilter222(item,sub)))return!1}if("$not"in filter){if(matchesFilter222(item,filter.$not))return!1}for(let key in filter){if(key==="$or"||key==="$and"||key==="$not")continue;let filterValue=filter[key],itemValue;try{itemValue=resolveDotPath222(item,key)}catch{return!1}if(filterValue instanceof RegExp){if(!filterValue.test(String(itemValue)))return!1}else if(typeof filterValue==="object"&&filterValue!==null){if(Object.keys(filterValue).some((k)=>k.startsWith("$"))){if("$eq"in filterValue&&itemValue!==filterValue.$eq)return!1;if("$ne"in filterValue&&itemValue===filterValue.$ne)return!1;if("$gt"in filterValue&&!(itemValue>filterValue.$gt))return!1;if("$lt"in filterValue&&!(itemValue<filterValue.$lt))return!1;if("$gte"in filterValue&&!(itemValue>=filterValue.$gte))return!1;if("$lte"in filterValue&&!(itemValue<=filterValue.$lte))return!1;if("$in"in filterValue&&!filterValue.$in.includes(itemValue))return!1;if("$nin"in filterValue&&filterValue.$nin.includes(itemValue))return!1;if("$regex"in filterValue){if(!(filterValue.$regex instanceof RegExp?filterValue.$regex:new RegExp(filterValue.$regex)).test(String(itemValue)))return!1}if("$fn"in filterValue&&!filterValue.$fn(itemValue))return!1}else if(!deepEqual222(itemValue,filterValue))return!1}else if(itemValue!==filterValue)return!1}return!0}function presortFilter222(filter,indexedFields=new Set){if(typeof filter!=="object"||filter===null||typeof filter==="function")return filter;let indexed=[],equality=[],range=[],expensive=[],logical=[];for(let key in filter){if(key==="$or"||key==="$and"||key==="$not"){logical.push(key);continue}let val=filter[key];if(indexedFields.has(key))indexed.push(key);else if(val instanceof RegExp||typeof val==="object"&&val!==null&&(("$regex"in val)||("$fn"in val))||typeof val==="function")expensive.push(key);else if(typeof val==="object"&&val!==null&&(("$gt"in val)||("$lt"in val)||("$gte"in val)||("$lte"in val)||("$ne"in val)||("$in"in val)||("$nin"in val)))range.push(key);else equality.push(key)}let sorted={};for(let k of[...indexed,...equality,...range,...expensive,...logical])sorted[k]=filter[k];return sorted}var SUPPORTED_TYPES222=new Set(["string","number","boolean","object","array","date","any"]);function typeOf222(val){if(Array.isArray(val))return"array";if(val instanceof Date)return"date";return typeof val}function parseSchema222(schema){let fields=new Map,uniqueFields=[];for(let[key,def]of Object.entries(schema)){let fieldDef;if(typeof def==="string"){if(!SUPPORTED_TYPES222.has(def))throw new ValidationError222("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${def}" for field "${key}"`,{field:key,type:def});fieldDef={type:def,required:!1,unique:!1}}else if(typeof def==="object"&&def!==null){let{type="any",required=!1,unique=!1,enum:enumVals}=def;if(!SUPPORTED_TYPES222.has(type))throw new ValidationError222("ERR_SKALEX_VALIDATION_UNKNOWN_TYPE",`Unknown schema type "${type}" for field "${key}"`,{field:key,type});if(fieldDef={type,required,unique,enum:enumVals},unique)uniqueFields.push(key)}else throw new ValidationError222("ERR_SKALEX_VALIDATION_INVALID_SCHEMA",`Invalid schema definition for field "${key}"`,{field:key});fields.set(key,fieldDef)}return{fields,uniqueFields}}function validateDoc222(doc,fields,strict=!1){let errors=[];for(let[key,def]of fields){let val=doc[key],missing=val===void 0||val===null;if(def.required&&missing){errors.push(`Field "${key}" is required`);continue}if(missing)continue;if(def.type!=="any"){let actualType=typeOf222(val);if(actualType!==def.type)errors.push(`Field "${key}" must be of type "${def.type}", got "${actualType}"`)}if(def.enum&&!def.enum.includes(val))errors.push(`Field "${key}" must be one of [${def.enum.map((v)=>JSON.stringify(v)).join(", ")}], got ${JSON.stringify(val)}`)}if(strict){for(let key of Object.keys(doc))if(!key.startsWith("_")&&!fields.has(key))errors.push(`Unknown field "${key}" (strict mode)`)}return errors}function stripInvalidFields222(doc,fields){let out={};for(let[key,val]of Object.entries(doc)){if(key.startsWith("_")){out[key]=val;continue}if(!fields.has(key))continue;let def=fields.get(key);if(def.type!=="any"){if(typeOf222(val)!==def.type)continue}if(def.enum&&!def.enum.includes(val))continue;out[key]=val}return out}function inferSchema222(doc){let schema={};for(let[key,val]of Object.entries(doc)){if(key.startsWith("_"))continue;let t=typeOf222(val);schema[key]=SUPPORTED_TYPES222.has(t)?t:"any"}return schema}function parseTtl222(ttl){if(typeof ttl==="number"){if(ttl<=0)throw new ValidationError222("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got ${ttl}`,{ttl});return ttl*1000}if(typeof ttl!=="string")throw new ValidationError222("ERR_SKALEX_VALIDATION_TTL",`Invalid TTL value: ${ttl}`,{ttl});let match=ttl.match(/^(\d+(?:\.\d+)?)(ms|s|m|h|d)$/);if(!match)throw new ValidationError222("ERR_SKALEX_VALIDATION_TTL_FORMAT",`Invalid TTL format: "${ttl}". Use e.g. 300 (seconds), "30m", "24h", "7d"`,{ttl});let val=parseFloat(match[1]);if(val<=0)throw new ValidationError222("ERR_SKALEX_VALIDATION_TTL",`TTL must be positive, got "${ttl}"`,{ttl});let unit=match[2],ms=val*{ms:1,s:1000,m:60000,h:3600000,d:86400000}[unit];if(!isFinite(ms))throw new ValidationError222("ERR_SKALEX_VALIDATION_TTL",`TTL value "${ttl}" is too large`,{ttl});return ms}function computeExpiry222(ttl){return new Date(Date.now()+parseTtl222(ttl))}function sweep222(data,idIndex,removeFromIndexes=null){let now=Date.now(),removed=0,i=data.length;while(i--){let doc=data[i];if(doc._expiresAt&&new Date(doc._expiresAt).getTime()<=now){if(data.splice(i,1),idIndex.delete(doc._id),removeFromIndexes)removeFromIndexes(doc);removed++}}return removed}function cosineSimilarity222(a,b){if(a.length!==b.length)throw new QueryError222("ERR_SKALEX_QUERY_VECTOR_MISMATCH",`Vector dimension mismatch: ${a.length} vs ${b.length}`,{expected:a.length,got:b.length});let dot=0,magA=0,magB=0;for(let i=0;i<a.length;i++)dot+=a[i]*b[i],magA+=a[i]*a[i],magB+=b[i]*b[i];let denom=Math.sqrt(magA*magB);return denom===0?0:dot/denom}function stripVector222(doc){if(!("_vector"in doc))return{...doc};let{_vector,...rest}=doc;return rest}function count222(docs){return docs.length}function sum222(docs,field){let total=0;for(let doc of docs){let val=resolveDotPath222(doc,field);if(typeof val==="number"&&!isNaN(val))total+=val}return total}function avg222(docs,field){let total=0,n=0;for(let doc of docs){let val=resolveDotPath222(doc,field);if(typeof val==="number"&&!isNaN(val))total+=val,n++}return n===0?null:total/n}function groupBy222(docs,field){let groups=Object.create(null);for(let doc of docs){let key=String(resolveDotPath222(doc,field)??"__null__");if(!groups[key])groups[key]=[];groups[key].push(doc)}return groups}class MutationPipeline222{constructor(collection){this._col=collection}get _ctx(){return this._col._ctx}async execute({op,beforeHook,afterHook,hookPayload,mutate,afterHookPayload,save,session}){let ctx=this._ctx;await ctx.ensureConnected(),this._col._txSnapshotIfNeeded();let txm=ctx.txManager,isTxWrite=txm.active&&this._col._activeTxId===txm.context?.id,entryTxId=isTxWrite?txm.context.id:null,collTxId=this._col._createdInTxId,assertTxAlive=()=>{if(entryTxId!==null&&txm._abortedIds.has(entryTxId))throw new TransactionError222("ERR_SKALEX_TX_ABORTED",`Transaction ${entryTxId} was aborted. No further mutations allowed.`);if(collTxId!==null&&txm._abortedIds.has(collTxId))throw new TransactionError222("ERR_SKALEX_TX_ABORTED",`Transaction ${collTxId} was aborted. Collection obtained inside that transaction cannot be used for further mutations.`)};if(isTxWrite||collTxId!==null)assertTxAlive();if(beforeHook)await ctx.plugins.run(beforeHook,hookPayload);let{docs,prevDocs=[]}=await mutate(assertTxAlive);if(ctx.persistence.markDirty(ctx.collections,this._col.name),await this._col._saveIfNeeded(save),this._col._changelogEnabled)for(let i=0;i<docs.length;i++)await ctx.logChange(op,this._col.name,docs[i],prevDocs[i]??null,session||null);if(!isTxWrite||!txm.defer(()=>ctx.sessionStats.recordWrite(session)))ctx.sessionStats.recordWrite(session);for(let doc of docs)ctx.emitEvent(this._col.name,{op,collection:this._col.name,doc:stripVector222(doc)});if(afterHook)if(afterHookPayload)await ctx.runAfterHook(afterHook,afterHookPayload(docs));else for(let doc of docs)await ctx.runAfterHook(afterHook,{collection:this._col.name,doc:stripVector222(doc)});return{docs,prevDocs}}}function resolveFilterToValues222(filter){let resolved={};for(let key in filter){if(key.startsWith("$"))continue;let val=filter[key];if(val&&typeof val==="object"&&!Array.isArray(val)){let keys=Object.keys(val);if(keys.length===1&&keys[0]==="$eq")resolved[key]=val.$eq}else resolved[key]=val}return resolved}var _DANGEROUS_KEYS222=new Set(["__proto__","constructor","prototype"]);function stripDangerousKeys222(val){if(typeof val!=="object"||val===null||Array.isArray(val))return val;let out={};for(let k of Object.keys(val)){if(_DANGEROUS_KEYS222.has(k))continue;out[k]=stripDangerousKeys222(val[k])}return out}class Collection222{constructor(collectionData,database){this.name=collectionData.collectionName,this.database=database,this._ctx=database._buildCollectionContext(),this._store=collectionData,this._pipeline=new MutationPipeline222(this),this._createdInTxId=database._txManager.context?.id??null,this._activeTxId=null}get _data(){return this._store.data}set _data(val){this._store.data=val}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(item,options={}){let{save,ifNotExists,ttl,embed,session}=options;if(ifNotExists){await this._ctx.ensureConnected();let existing=this._findRaw(item);if(existing)return stripVector222({...existing})}let{docs}=await this._insertCore([item],{ttl,embed,session,save});return stripVector222(docs[0])}async insertMany(items,options={}){let{save,ttl,embed,session}=options,{docs}=await this._insertCore(items,{ttl,embed,session,save});return docs.map(stripVector222)}async _insertCore(items,{ttl,embed,session,save}){return this._pipeline.execute({op:"insert",beforeHook:null,afterHook:"afterInsert",hookPayload:null,save,session,mutate:async(assertTxAlive)=>{let newItems=[],batchIds=new Set;for(let item of items){let validated=this._applyValidation(item);await this._ctx.plugins.run("beforeInsert",{collection:this.name,doc:validated});let newItem=await this._buildDoc(validated,{ttl,embed});if(this._index.has(newItem._id)||batchIds.has(newItem._id))throw new UniqueConstraintError222("ERR_SKALEX_UNIQUE_DUPLICATE_ID",`Duplicate _id "${newItem._id}" in collection "${this.name}"`,{id:newItem._id,collection:this.name});batchIds.add(newItem._id),newItems.push(newItem)}if(assertTxAlive(),this._fieldIndex)this._fieldIndex.assertUniqueBatch(newItems);for(let newItem of newItems)this._addToIndex(newItem);this._data.push(...newItems);for(let newItem of newItems)this._index.set(newItem._id,newItem);return this._enforceCapAfterInsert(),{docs:newItems}}})}async updateOne(filter,update,options={}){await this._ctx.ensureConnected();let oldDoc=this._findRaw(filter);if(!oldDoc)return null;let{save,session}=options,{docs}=await this._updateCore([oldDoc],filter,update,{save,session});return stripVector222(docs[0])}async updateMany(filter,update,options={}){await this._ctx.ensureConnected();let oldDocs=this._findAllRaw(filter);if(oldDocs.length===0)return[];let{save,session}=options,{docs}=await this._updateCore(oldDocs,filter,update,{save,session});return docs.map(stripVector222)}async _updateCore(oldDocs,filter,update,{save,session}){return this._pipeline.execute({op:"update",beforeHook:"beforeUpdate",afterHook:"afterUpdate",hookPayload:{collection:this.name,filter,update},save,session,afterHookPayload:(docs)=>({collection:this.name,filter,update,result:docs.length===1?docs[0]:docs}),mutate:async(assertTxAlive)=>{let prevDocs=this._changelogEnabled?oldDocs.map((doc)=>structuredClone(doc)):oldDocs.map(()=>null),nextDocs=oldDocs.map((doc)=>this._prepareUpdatedDoc(doc,update));this._assertUniqueCandidates(oldDocs,nextDocs),assertTxAlive();let targets=new Set(oldDocs),positions=new Map;for(let i=0;i<this._data.length;i++)if(targets.has(this._data[i]))positions.set(this._data[i],i);for(let i=0;i<oldDocs.length;i++)this._commitUpdatedDoc(oldDocs[i],nextDocs[i],positions);return{docs:nextDocs,prevDocs}}})}applyUpdate(item,update){for(let field in update){if(_DANGEROUS_KEYS222.has(field))continue;if(field==="_id"||field==="createdAt")continue;let updateValue=update[field];if(Array.isArray(updateValue))item[field]=updateValue;else if(typeof updateValue==="object"&&updateValue!==null){let keys=Object.keys(updateValue);if(keys.some((k)=>k.startsWith("$"))){for(let key of keys)if(key==="$inc"&&typeof item[field]==="number")item[field]+=updateValue[key];else if(key==="$push"){if(!Array.isArray(item[field]))item[field]=[];item[field].push(updateValue[key])}}else item[field]=stripDangerousKeys222(updateValue)}else item[field]=updateValue}if(item.updatedAt=new Date,this._versioning)item._version=(item._version??0)+1;return item}_prepareUpdatedDoc(currentDoc,update){let prev=structuredClone(currentDoc),next=structuredClone(currentDoc);if(this.applyUpdate(next,update),!this._schema)return next;let errors=validateDoc222(next,this._schema,this._strict);if(!errors.length)return next;switch(this._onSchemaError){case"throw":throw new ValidationError222("ERR_SKALEX_VALIDATION_UPDATE",`Update validation failed on doc "${currentDoc._id}": ${errors.join("; ")}`,{id:currentDoc._id,errors});case"strip":return this._stripCandidateToValid(next,prev);default:return this._ctx.logger(`[${this.name}] Update validation warning: ${errors.join("; ")}`,"warn"),next}}_stripCandidateToValid(next,prev){let stripped=stripInvalidFields222(next,this._schema),merged=structuredClone(prev);for(let[key,val]of Object.entries(stripped)){if(key.startsWith("_"))continue;merged[key]=val}if(merged.updatedAt=next.updatedAt,this._versioning)merged._version=next._version;return merged}_commitUpdatedDoc(oldDoc,newDoc,positions){let idx=positions?positions.get(oldDoc):this._data.indexOf(oldDoc);if(idx===void 0||idx===-1)throw new PersistenceError222("ERR_SKALEX_PERSISTENCE_DOC_MISSING",`Document "${oldDoc._id}" no longer exists in collection "${this.name}"`,{id:oldDoc._id,collection:this.name});this._data[idx]=newDoc,this._index.set(newDoc._id,newDoc),this._updateInIndex(oldDoc,newDoc)}_assertUniqueCandidates(oldDocs,nextDocs){this._fieldIndex?.assertUniqueCandidates(oldDocs,nextDocs)}async upsert(filter,doc,options={}){if(await this._ctx.ensureConnected(),this._findRaw(filter))return this.updateOne(filter,doc,options);return this.insertOne({...resolveFilterToValues222(filter),...doc},options)}async upsertMany(docs,matchKey,options={}){await this._ctx.ensureConnected();let{save,...rest}=options,results=[];for(let doc of docs)results.push(await this.upsert({[matchKey]:doc[matchKey]},doc,{...rest,save:!1}));return await this._saveIfNeeded(save),results}async restore(filter,options={}){if(!this._softDelete)throw new QueryError222("ERR_SKALEX_QUERY_SOFT_DELETE_REQUIRED",`restore() requires softDelete on "${this.name}"`,{collection:this.name});await this._ctx.ensureConnected();let{save,session}=options,item=this._findRaw(filter,{includeDeleted:!0});if(!item||!item._deletedAt)return null;let{docs}=await this._pipeline.execute({op:"restore",beforeHook:null,afterHook:null,hookPayload:null,save,session,mutate:async(assertTxAlive)=>(assertTxAlive(),delete item._deletedAt,item.updatedAt=new Date,this._index.set(item._id,item),{docs:[item]})});return stripVector222(docs[0])}watch(filter,callback){if(typeof filter==="function")callback=filter,filter=null;if(callback)return this._ctx.eventBus.on(this.name,(event)=>{if(!filter||matchesFilter222(event.doc,filter))callback(event)});return this._watchIterator(filter)}_watchIterator(filter){let queue=[],resolve=null,done=!1,unsub=this._ctx.eventBus.on(this.name,(event)=>{if(filter&&!matchesFilter222(event.doc,filter))return;if(resolve){let r=resolve;resolve=null,r({value:event,done:!1})}else queue.push(event)});return{[Symbol.asyncIterator](){return this},next(){if(queue.length>0)return Promise.resolve({value:queue.shift(),done:!1});if(done)return Promise.resolve({value:void 0,done:!0});return new Promise((res)=>{resolve=res})},return(){if(done=!0,unsub(),resolve){let r=resolve;resolve=null,r({value:void 0,done:!0})}return Promise.resolve({value:void 0,done:!0})}}}async count(filter={}){return await this._ctx.ensureConnected(),count222(this._findAllRaw(filter))}async sum(field,filter={}){return await this._ctx.ensureConnected(),sum222(this._findAllRaw(filter),field)}async avg(field,filter={}){return await this._ctx.ensureConnected(),avg222(this._findAllRaw(filter),field)}async groupBy(field,filter={}){return await this._ctx.ensureConnected(),groupBy222(this._findAllRaw(filter),field)}async findOne(filter,options={}){await this._ctx.ensureConnected();let{populate,select,includeDeleted=!1}=options,item=this._findRaw(filter,{includeDeleted});if(!item)return null;let newItem=this._projectDoc(item,select);if(populate)await this._populateDoc(newItem,item,populate);return newItem}async find(filter,options={}){await this._ctx.ensureConnected();let _t0=Date.now(),{populate,select,sort,page=1,limit,session,includeDeleted=!1}=options;await this._ctx.plugins.run("beforeFind",{collection:this.name,filter,options});let candidates=this._getCandidates(filter),sortedFilter=presortFilter222(filter,this._fieldIndex?this._fieldIndex.indexedFields:new Set),results=[];for(let item of candidates){if(this._softDelete&&item._deletedAt&&!includeDeleted)continue;if(!matchesFilter222(item,sortedFilter))continue;let newItem=this._projectDoc(item,select);if(populate)await this._populateDoc(newItem,item,populate);results.push(newItem)}if(sort){let sortFields=Object.keys(sort);results.sort((a,b)=>{for(let field of sortFields){let dir=sort[field];if(a[field]<b[field])return-dir;if(a[field]>b[field])return dir}return 0})}let extra;if(limit){let totalDocs=results.length,totalPages=Math.ceil(totalDocs/limit),startIndex=(page-1)*limit;results=results.slice(startIndex,startIndex+limit),extra={page,totalDocs,totalPages}}return this._ctx.queryLog?.record({collection:this.name,op:"find",filter,duration:Date.now()-_t0,resultCount:results.length}),this._ctx.sessionStats.recordRead(session),await this._ctx.plugins.run("afterFind",{collection:this.name,filter,options,docs:results}),extra?{docs:results,...extra}:{docs:results}}async search(query,{filter,limit=10,minScore=0,session}={}){await this._ctx.ensureConnected();let _t0=Date.now();await this._ctx.plugins.run("beforeSearch",{collection:this.name,query,options:{filter,limit,minScore}});let queryVector=await this._ctx.embed(query),candidates=filter?this._findAllRaw(filter):this._data,scored=[];for(let doc of candidates){if(!doc._vector)continue;let score=cosineSimilarity222(queryVector,doc._vector);if(score>=minScore)scored.push({doc,score})}scored.sort((a,b)=>b.score-a.score);let top=scored.slice(0,limit);this._ctx.queryLog?.record({collection:this.name,op:"search",query,duration:Date.now()-_t0,resultCount:top.length}),this._ctx.sessionStats.recordRead(session);let docs=top.map((r)=>stripVector222(r.doc)),scores=top.map((r)=>r.score);return await this._ctx.plugins.run("afterSearch",{collection:this.name,query,options:{filter,limit,minScore},docs,scores}),{docs,scores}}async similar(id,{limit=10,minScore=0}={}){await this._ctx.ensureConnected();let source=this._index.get(id);if(!source||!source._vector)return{docs:[],scores:[]};let scored=[];for(let doc of this._data){if(doc._id===id||!doc._vector)continue;let score=cosineSimilarity222(source._vector,doc._vector);if(score>=minScore)scored.push({doc,score})}scored.sort((a,b)=>b.score-a.score);let top=scored.slice(0,limit);return{docs:top.map((r)=>stripVector222(r.doc)),scores:top.map((r)=>r.score)}}async deleteOne(filter,options={}){await this._ctx.ensureConnected();let{save,session}=options;if(this._softDelete){let item=this._findRaw(filter);if(!item)return null;let{docs:docs2}=await this._deleteCore("soft",[item],filter,{save,session});return stripVector222(docs2[0])}let{docs}=await this._deleteCore("hard",null,filter,{save,session});if(docs.length===0)return null;return stripVector222(docs[0])}async deleteMany(filter,options={}){await this._ctx.ensureConnected();let{save,session}=options;if(this._softDelete){let items=this._findAllRaw(filter);if(items.length===0)return[];let{docs:docs2}=await this._deleteCore("soft",items,filter,{save,session});return docs2.map(stripVector222)}let{docs}=await this._deleteCore("hardMany",null,filter,{save,session});return docs.map(stripVector222)}async _deleteCore(mode,items,filter,{save,session}){return this._pipeline.execute({op:"delete",beforeHook:"beforeDelete",afterHook:"afterDelete",hookPayload:{collection:this.name,filter},save,session,afterHookPayload:(docs)=>({collection:this.name,filter,result:docs.length===1?docs[0]:docs}),mutate:async(assertTxAlive)=>{if(assertTxAlive(),mode==="soft"){let now=new Date;for(let item of items)item._deletedAt=now,item.updatedAt=now,this._index.set(item._id,item);return{docs:items}}if(mode==="hard"){let idx=this._findIndex(filter);if(idx===-1)return{docs:[]};let deletedItem=this._data.splice(idx,1)[0];return this._index.delete(deletedItem._id),this._removeFromIndex(deletedItem),{docs:[deletedItem]}}let deletedItems=[],remainingItems=[];for(let item of this._data)if(matchesFilter222(item,filter))deletedItems.push(item),this._index.delete(item._id),this._removeFromIndex(item);else remainingItems.push(item);return this._data=remainingItems,{docs:deletedItems}}})}async export(filter={},options={}){let{dir,name,format="json"}=options;try{let filteredData=this._data.filter((item)=>matchesFilter222(item,filter));if(filteredData.length===0)throw new QueryError222("ERR_SKALEX_QUERY_EXPORT_EMPTY",`export(): no documents matched the filter in "${this.name}"`,{collection:this.name});let content;if(format==="json")content=JSON.stringify(filteredData,null,2);else{let escapeCsv=(v)=>{if(v==null)return"";let s=typeof v==="object"?JSON.stringify(v):String(v);return s.includes(",")||s.includes('"')||s.includes(`
82
82
  `)||s.includes("\r")?`"${s.replace(/"/g,'""')}"`:s},header=Object.keys(filteredData[0]).map(escapeCsv).join(","),rows=filteredData.map((item)=>Object.values(item).map(escapeCsv).join(","));content=[header,...rows].join(`
83
83
  `)}if(typeof this._ctx.fs.writeRaw!=="function")throw new AdapterError222("ERR_SKALEX_ADAPTER_NO_RAW_WRITE","export() requires a file-system adapter (FsAdapter). The current adapter does not support raw file writes.");let exportDir=dir||`${this._ctx.dataDirectory}/exports`,fileName=`${name||this.name}.${format}`,filePath=this._ctx.fs.join(exportDir,fileName);this._ctx.fs.ensureDir(exportDir),await this._ctx.fs.writeRaw(filePath,content)}catch(error222){throw this._ctx.logger(`Error exporting "${this.name}": ${error222.message}`,"error"),error222}}_txSnapshotIfNeeded(){let txm=this._ctx.txManager;if(!txm.active)return;if(this._activeTxId!==txm.context?.id)return;txm.snapshotIfNeeded(this.name,this._store,(col)=>this._ctx.snapshotCollection(col))}async _saveIfNeeded(save){let txm=this._ctx.txManager;if(txm.active&&this._activeTxId===txm.context?.id)return;if(save??this._ctx.autoSave)await this._ctx.saveCollection(this.name)}_applyValidation(item){if(!this._schema)return item;let errors=validateDoc222(item,this._schema,this._strict);if(!errors.length)return item;switch(this._onSchemaError){case"warn":return this._ctx.logger(`[${this.name}] Validation warning: ${errors.join("; ")}`,"warn"),item;case"strip":return stripInvalidFields222(item,this._schema);default:throw new ValidationError222("ERR_SKALEX_VALIDATION_FAILED",`Validation failed: ${errors.join("; ")}`,{errors})}}_enforceCapAfterInsert(){let max=this._maxDocs;if(!max||this._data.length<=max)return;let toEvict=this._data.splice(0,this._data.length-max);for(let doc of toEvict)this._index.delete(doc._id),this._removeFromIndex(doc)}_findRaw(filter,{includeDeleted=!1}={}){if(typeof filter==="function"){for(let doc of this._data){if(this._softDelete&&doc._deletedAt&&!includeDeleted)continue;if(filter(doc))return doc}return null}if(filter._id){let item=this._index.get(filter._id)||null;if(!item)return null;if(this._softDelete&&item._deletedAt&&!includeDeleted)return null;if(Object.keys(filter).length>1)return matchesFilter222(item,filter)?item:null;return item}if(this._fieldIndex)for(let key in filter){if(key==="$or"||key==="$and"||key==="$not")continue;let val=filter[key];if(typeof val!=="object"||val===null){let candidates=this._fieldIndex._lookupIterable(key,val);if(candidates!==null){for(let doc of candidates){if(this._softDelete&&doc._deletedAt&&!includeDeleted)continue;if(matchesFilter222(doc,filter))return doc}return null}}}for(let doc of this._data){if(this._softDelete&&doc._deletedAt&&!includeDeleted)continue;if(matchesFilter222(doc,filter))return doc}return null}_findAllRaw(filter,{includeDeleted=!1}={}){if(filter&&typeof filter!=="function"&&filter._id){let item=this._index.get(filter._id);if(!item)return[];if(this._softDelete&&item._deletedAt&&!includeDeleted)return[];return matchesFilter222(item,filter)?[item]:[]}let results=[];for(let doc of this._getCandidates(filter)){if(this._softDelete&&doc._deletedAt&&!includeDeleted)continue;if(matchesFilter222(doc,filter))results.push(doc)}return results}_getCandidates(filter){if(!this._fieldIndex)return this._data;if(this._fieldIndex._compoundIndexes.size>0){let eqFields={};for(let key in filter){if(key==="$or"||key==="$and"||key==="$not")continue;let val=filter[key];if(typeof val!=="object"||val===null)eqFields[key]=val}if(Object.keys(eqFields).length>=2){let candidates=this._fieldIndex.lookupCompound(eqFields);if(candidates!==null)return candidates}}for(let key in filter){if(key==="$or"||key==="$and"||key==="$not")continue;let val=filter[key];if(typeof val!=="object"||val===null){let candidates=this._fieldIndex._lookupIterable(key,val);if(candidates!==null)return candidates}}return this._data}_findIndex(filter){for(let i=0;i<this._data.length;i++)if(matchesFilter222(this._data[i],filter))return i;return-1}_addToIndex(doc){if(this._fieldIndex)this._fieldIndex.add(doc)}_removeFromIndex(doc){if(this._fieldIndex)this._fieldIndex.remove(doc)}_updateInIndex(oldDoc,doc){if(this._fieldIndex)this._fieldIndex.update(oldDoc,doc)}async _buildDoc(item,{ttl,embed}={}){let newItem={...item,_id:item._id??(this._ctx.idGenerator??generateUniqueId222)(),createdAt:new Date,updatedAt:new Date},resolvedTtl=ttl??this._defaultTtl;if(resolvedTtl)newItem._expiresAt=computeExpiry222(resolvedTtl);let resolvedEmbed=embed??this._defaultEmbed;if(resolvedEmbed){let text=typeof resolvedEmbed==="function"?resolvedEmbed(newItem):newItem[resolvedEmbed];newItem._vector=await this._ctx.embed(String(text))}if(this._versioning)newItem._version=1;return newItem}_projectDoc(doc,select){if(select){let out2={};for(let field of select){if(field==="_vector")continue;out2[field]=doc[field]}return out2}let out={...doc};return delete out._vector,out}async _populateDoc(out,source,fields){for(let field of fields){let item=await this._ctx.getCollection(field).findOne({_id:source[field]});if(item)out[field]=item}}}class StorageAdapter222{async read(name){throw Error("StorageAdapter.read() not implemented")}async write(name,data){throw Error("StorageAdapter.write() not implemented")}async delete(name){throw Error("StorageAdapter.delete() not implemented")}async list(){throw Error("StorageAdapter.list() not implemented")}async writeAll(entries){for(let{name,data}of entries)await this.write(name,data)}}class FsAdapter222 extends StorageAdapter222{constructor({dir,format="gz"}){super();this.dir=nodePath222.resolve(dir),this.format=format,this._ensureDir(this.dir)}_ensureDir(dir){if(!nodeFs222.existsSync(dir))nodeFs222.mkdirSync(dir,{recursive:!0})}_filePath(name){return nodePath222.join(this.dir,`${name}.${this.format}`)}async read(name){let fp=this._filePath(name);try{let raw=await nodeFs222.promises.readFile(fp);if(this.format==="gz")raw=zlib222.inflateSync(raw);return raw.toString("utf8")}catch(err){if(err.code==="ENOENT")return null;throw err}}async write(name,data){let fp=this._filePath(name),tmp=nodePath222.join(this.dir,`${name}_${globalThis.crypto.randomUUID()}.tmp.${this.format}`);if(this.format==="gz"){let compressed=zlib222.deflateSync(data);await nodeFs222.promises.writeFile(tmp,compressed)}else await nodeFs222.promises.writeFile(tmp,data,"utf8");await nodeFs222.promises.rename(tmp,fp)}async writeAll(entries){let staged=[];try{for(let{name,data}of entries){let fp=this._filePath(name),tmp=nodePath222.join(this.dir,`${name}_${globalThis.crypto.randomUUID()}.tmp.${this.format}`);if(this.format==="gz"){let compressed=zlib222.deflateSync(data);await nodeFs222.promises.writeFile(tmp,compressed)}else await nodeFs222.promises.writeFile(tmp,data,"utf8");staged.push({tmp,fp})}for(let{tmp,fp}of staged)await nodeFs222.promises.rename(tmp,fp)}catch(error222){for(let{tmp}of staged)try{await nodeFs222.promises.unlink(tmp)}catch{}throw error222}}async delete(name){let fp=this._filePath(name);try{await nodeFs222.promises.unlink(fp)}catch(err){if(err.code!=="ENOENT")throw err}}async list(){try{let files=await nodeFs222.promises.readdir(this.dir),ext=`.${this.format}`;return files.filter((f)=>f.endsWith(ext)&&!f.includes(".tmp.")).map((f)=>f.slice(0,-ext.length))}catch(err){if(err.code==="ENOENT")return[];throw err}}join(...parts){return nodePath222.join(...parts)}ensureDir(dir){this._ensureDir(dir)}async writeRaw(filePath,content){this._ensureDir(nodePath222.dirname(filePath)),await nodeFs222.promises.writeFile(filePath,content,"utf8")}async readRaw(filePath){return nodeFs222.promises.readFile(nodePath222.resolve(filePath),"utf8")}}class MigrationEngine222{constructor(){this._migrations=[]}add(migration){let{version,up}=migration;if(typeof version!=="number"||version<1)throw new ValidationError222("ERR_SKALEX_VALIDATION_MIGRATION",`Migration version must be a positive integer, got ${version}`,{version});if(typeof up!=="function")throw new ValidationError222("ERR_SKALEX_VALIDATION_MIGRATION",`Migration version ${version} must have an "up" function`,{version});if(this._migrations.some((m)=>m.version===version))throw new ValidationError222("ERR_SKALEX_VALIDATION_MIGRATION_DUPLICATE",`Migration version ${version} is already registered`,{version});this._migrations.push({...migration}),this._migrations.sort((a,b)=>a.version-b.version)}async run(getCollection,appliedVersions=[]){let applied=new Set(appliedVersions),pending=this._migrations.filter((m)=>!applied.has(m.version));for(let migration of pending){let collection=getCollection(migration.version);await migration.up(collection),applied.add(migration.version)}return[...applied].sort((a,b)=>a-b)}status(appliedVersions=[]){let applied=new Set(appliedVersions),pending=this._migrations.map((m)=>m.version).filter((v)=>!applied.has(v));return{current:appliedVersions.length?Math.max(...appliedVersions):0,applied:[...applied].sort((a,b)=>a-b),pending}}}var EMPTY_ITERABLE222={[Symbol.iterator](){return{next(){return{done:!0}}}},size:0};function readOnlyIterable222(set){return{[Symbol.iterator](){return set[Symbol.iterator]()},get size(){return set.size}}}function encodeTuple222(values){return values.map((v)=>{if(v===null||v===void 0)return"\x00";if(typeof v==="boolean")return v?"\x01T":"\x01F";if(typeof v==="number")return`\x02${v}`;return`\x03${String(v)}`}).join("\x1F")}class IndexEngine222{constructor(fields=[],unique=[]){this._fields=new Set,this._compoundFields=[];for(let f of fields)if(Array.isArray(f)){for(let subf of f)this._validateFieldName(subf);this._compoundFields.push(f)}else this._validateFieldName(f),this._fields.add(f);for(let f of unique)this._validateFieldName(f);this._uniqueFields=new Set(unique),this._indexedFields=new Set([...this._fields,...this._uniqueFields]),this._fieldIndexes=new Map,this._uniqueIndexes=new Map;for(let f of this._fields)this._fieldIndexes.set(f,new Map);for(let f of this._uniqueFields)if(this._uniqueIndexes.set(f,new Map),!this._fieldIndexes.has(f))this._fieldIndexes.set(f,new Map);this._compoundIndexes=new Map;for(let fieldSet of this._compoundFields)this._compoundIndexes.set(fieldSet.join("\x00"),{fields:fieldSet,map:new Map})}get indexedFields(){return this._indexedFields}buildFromData(data){for(let[,m]of this._fieldIndexes)m.clear();for(let[,m]of this._uniqueIndexes)m.clear();for(let[,ci]of this._compoundIndexes)ci.map.clear();for(let doc of data)this._indexDoc(doc)}add(doc){this._checkUnique(doc,null),this._indexDoc(doc)}remove(doc){for(let[field,map]of this._fieldIndexes){let val=doc[field];if(val!==void 0){let set=map.get(val);if(set){if(set.delete(doc),set.size===0)map.delete(val)}}}for(let[field,map]of this._uniqueIndexes){let val=doc[field];if(val!==void 0)map.delete(val)}for(let[,ci]of this._compoundIndexes){let tupleKey=encodeTuple222(ci.fields.map((f)=>doc[f])),set=ci.map.get(tupleKey);if(set){if(set.delete(doc),set.size===0)ci.map.delete(tupleKey)}}}update(oldDoc,newDoc){this._checkUnique(newDoc,oldDoc),this.remove(oldDoc);try{this._indexDoc(newDoc)}catch(indexError){try{this._indexDoc(oldDoc)}catch{}throw indexError}}lookup(field,value){let map=this._fieldIndexes.get(field);if(!map)return null;let set=map.get(value);return set?[...set]:[]}_lookupIterable(field,value){let map=this._fieldIndexes.get(field);if(!map)return null;let set=map.get(value);return set?readOnlyIterable222(set):EMPTY_ITERABLE222}lookupCompound(fieldValues){let keys=Object.keys(fieldValues).sort();for(let[,ci]of this._compoundIndexes){let ciKeys=[...ci.fields].sort();if(ciKeys.length!==keys.length)continue;if(ciKeys.every((k,i)=>k===keys[i])){let tupleKey=encodeTuple222(ci.fields.map((f)=>fieldValues[f])),set=ci.map.get(tupleKey);return set?readOnlyIterable222(set):EMPTY_ITERABLE222}}return null}isUniqueTaken(field,value){let map=this._uniqueIndexes.get(field);if(!map)return!1;return map.has(value)}assertUniqueCandidates(oldDocs,newDocs){if(this._uniqueFields.size===0)return;let batchOldIds=new Set(oldDocs.map((doc)=>doc._id));for(let field of this._uniqueFields){let reserved=new Set,uniqueMap=this._uniqueIndexes.get(field);if(uniqueMap){for(let[value,doc]of uniqueMap.entries())if(!batchOldIds.has(doc._id))reserved.add(value)}let seen=new Map;for(let i=0;i<newDocs.length;i++){let val=newDocs[i][field];if(val===void 0)continue;if(reserved.has(val))throw new UniqueConstraintError222("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${field}" value "${val}" already exists`,{field,value:val});let prior=seen.get(val);if(prior&&prior!==oldDocs[i]._id)throw new UniqueConstraintError222("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${field}" value "${val}" already exists`,{field,value:val});seen.set(val,oldDocs[i]._id)}}}assertUniqueBatch(newDocs){if(this._uniqueFields.size===0)return;for(let field of this._uniqueFields){let uniqueMap=this._uniqueIndexes.get(field),seen=new Set;for(let doc of newDocs){let val=doc[field];if(val===void 0)continue;if(uniqueMap&&uniqueMap.has(val))throw new UniqueConstraintError222("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${field}" value "${val}" already exists`,{field,value:val});if(seen.has(val))throw new UniqueConstraintError222("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: duplicate "${field}" value "${val}" within batch`,{field,value:val});seen.add(val)}}}_validateFieldName(field){if(field.includes("."))throw new ValidationError222("ERR_SKALEX_VALIDATION_INDEX_DOT_PATH",`Index fields cannot use dot-notation: "${field}". Use a flat field name.`,{field})}_indexDoc(doc){for(let[field,map]of this._fieldIndexes){let val=doc[field];if(val!==void 0){if(!map.has(val))map.set(val,new Set);map.get(val).add(doc)}}for(let[field,map]of this._uniqueIndexes){let val=doc[field];if(val!==void 0)map.set(val,doc)}for(let[,ci]of this._compoundIndexes){for(let f of ci.fields){let val=doc[f];if(val!==void 0&&val!==null&&typeof val==="object")throw new ValidationError222("ERR_SKALEX_VALIDATION_COMPOUND_INDEX",`Compound index field "${f}" must be a scalar value (string, number, or boolean), got ${Array.isArray(val)?"array":typeof val}`,{field:f})}let tupleKey=encodeTuple222(ci.fields.map((f)=>doc[f]));if(!ci.map.has(tupleKey))ci.map.set(tupleKey,new Set);ci.map.get(tupleKey).add(doc)}}_checkUnique(newDoc,existingDoc){for(let field of this._uniqueFields){let val=newDoc[field];if(val===void 0)continue;let map=this._uniqueIndexes.get(field);if(!map)continue;let existing=map.get(val);if(existing&&existing._id!==existingDoc?._id)throw new UniqueConstraintError222("ERR_SKALEX_UNIQUE_VIOLATION",`Unique constraint violation: field "${field}" value "${val}" already exists`,{field,value:val})}}}var FLUSH_META_KEY222="_flush",META_DOC_ID222="migrations";class PersistenceManager222{constructor({adapter,serializer,deserializer,logger:logger2222,debug=!1,lenientLoad=!1}){this._adapter=adapter,this._serializer=serializer,this._deserializer=deserializer,this._logger=logger2222,this._debug=debug,this._lenientLoad=lenientLoad,this._saveLock=Promise.resolve()}_withSaveLock(fn){let next=this._saveLock.then(fn);return this._saveLock=next.catch(()=>{}),next}async loadAll(collections,{parseSchema:parseSchema2222,buildIndex,IndexEngine:IndexEngine2222}){try{let names=await this._adapter.list();await Promise.all(names.map(async(name)=>{try{let raw=await this._adapter.read(name);if(!raw)return;let parsed=this._deserializer(raw),{collectionName,data}=parsed;if(!collectionName)return;let existing=collections[collectionName],rawSchema=existing?.rawSchema??parsed.rawSchema??null,parsedSchema=existing?.schema??(rawSchema?parseSchema2222(rawSchema):null),changelog=existing?.changelog??parsed.changelog??!1,softDelete=existing?.softDelete??parsed.softDelete??!1,versioning=existing?.versioning??parsed.versioning??!1,strict=existing?.strict??parsed.strict??!1,onSchemaError=existing?.onSchemaError??parsed.onSchemaError??"throw",defaultTtl=existing?.defaultTtl??parsed.defaultTtl??null,defaultEmbed=existing?.defaultEmbed??parsed.defaultEmbed??null,maxDocs=existing?.maxDocs??parsed.maxDocs??null,fieldIndex=existing?existing.fieldIndex:null;if(!fieldIndex&&parsedSchema?.uniqueFields?.length)fieldIndex=new IndexEngine2222([],parsedSchema.uniqueFields);let idIndex=buildIndex(data,"_id");if(fieldIndex)fieldIndex.buildFromData(data);collections[collectionName]={collectionName,data,index:idIndex,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:parsedSchema,rawSchema,fieldIndex,changelog,softDelete,versioning,strict,onSchemaError,defaultTtl,defaultEmbed,maxDocs}}catch(error222){if(error222.code==="ENOENT")return;if(this._lenientLoad){this._logger(`WARNING: Could not load collection "${name}": ${error222.message}. Collection will be empty.`,"error");return}throw new PersistenceError222("ERR_SKALEX_PERSISTENCE_CORRUPT",`Failed to load collection "${name}": ${error222.message}`,{collection:name})}})),this._detectIncompleteFlush(collections),await this._cleanOrphanTempFiles()}catch(error222){if(error222.code!=="ENOENT")throw this._logger(`Error loading data: ${error222}`,"error"),error222}}async save(collections,collectionName){if(collectionName)await this._saveOne(collections,collectionName);else await Promise.all(Object.keys(collections).map((name)=>this._saveOne(collections,name)))}async saveDirty(collections){let dirtyNames=Object.keys(collections).filter((name)=>collections[name]._dirty);if(dirtyNames.length===0)return;await Promise.all(dirtyNames.map((name)=>this._saveOne(collections,name)))}saveAtomic(collections,names){return this._withSaveLock(async()=>{if(names.length===0)return;this._writeFlushSentinel(collections,names);let allNames=new Set(names);allNames.add("_meta");let entries=[...allNames].filter((n)=>collections[n]).map((name)=>({name,data:this._serializeCollection(collections[name])}));try{await this._adapter.writeAll(entries)}catch(error222){throw new PersistenceError222("ERR_SKALEX_PERSISTENCE_FLUSH_FAILED",`Batch save failed during writeAll: ${error222.message}`,{collections:names})}for(let name of names)if(collections[name])collections[name]._dirty=!1;try{this._clearFlushSentinel(collections),await this._adapter.write("_meta",this._serializeCollection(collections._meta))}catch(error222){this._logger(`WARNING: Batch data committed but sentinel clear failed: ${error222.message}. Next load will report an incomplete flush (false positive).`,"error")}})}markDirty(collections,name){let col=collections[name];if(col)col._dirty=!0}_serializeCollection(col){let payload={collectionName:col.collectionName,data:col.data};if(col.rawSchema)payload.rawSchema=col.rawSchema;if(col.changelog)payload.changelog=col.changelog;if(col.softDelete)payload.softDelete=col.softDelete;if(col.versioning)payload.versioning=col.versioning;if(col.strict)payload.strict=col.strict;if(col.onSchemaError!=="throw")payload.onSchemaError=col.onSchemaError;if(col.defaultTtl)payload.defaultTtl=col.defaultTtl;if(col.defaultEmbed)payload.defaultEmbed=col.defaultEmbed;if(col.maxDocs)payload.maxDocs=col.maxDocs;return this._serializer(payload)}async _saveOne(collections,name){let col=collections[name];if(!col)return;if(col.isSaving)return col._pendingSave=!0,new Promise((resolve,reject)=>{(col._saveWaiters??=[]).push({resolve,reject})});col.isSaving=!0,col._pendingSave=!1;try{await this._writeCollection(name,col);while(col._pendingSave)col._pendingSave=!1,await this._writeCollection(name,col);this._resolveSaveWaiters(col)}catch(error222){throw this._rejectSaveWaiters(col,error222),error222}finally{col.isSaving=!1}}async _writeCollection(name,col){try{await this._adapter.write(name,this._serializeCollection(col)),col._dirty=!1}catch(error222){throw this._logger(`Error saving "${name}": ${error222.message}`,"error"),error222}}_resolveSaveWaiters(col){let waiters=col._saveWaiters?.splice(0)??[];for(let w of waiters)w.resolve()}_rejectSaveWaiters(col,error222){let waiters=col._saveWaiters?.splice(0)??[];for(let w of waiters)w.reject(error222)}_writeFlushSentinel(collections,names){let meta=this._getOrCreateMeta(collections);meta[FLUSH_META_KEY222]={startedAt:new Date().toISOString(),collections:names,completedAt:null}}_clearFlushSentinel(collections){let meta=this._getOrCreateMeta(collections);if(meta[FLUSH_META_KEY222])meta[FLUSH_META_KEY222].completedAt=new Date().toISOString()}_detectIncompleteFlush(collections){let metaCol=collections._meta;if(!metaCol)return;let metaDoc=metaCol.index.get(META_DOC_ID222);if(!metaDoc)return;let flush=metaDoc[FLUSH_META_KEY222];if(!flush)return;if(flush.startedAt&&!flush.completedAt)this._logger(`WARNING: Incomplete flush detected (started ${flush.startedAt}, collections: ${flush.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 nodeFs2222=await import("fs"),nodePath2222=await import("path"),dir=this._adapter.dir;if(!dir)return;let orphans=(await nodeFs2222.default.promises.readdir(dir)).filter((f)=>f.includes(".tmp."));for(let orphan of orphans){let orphanPath=nodePath2222.default.join(dir,orphan);try{await nodeFs2222.default.promises.unlink(orphanPath),this._log(`Cleaned orphan temp file: ${orphan}`)}catch{}}}catch{}}_getOrCreateMeta(collections){if(!collections._meta)collections._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 metaCol=collections._meta,doc=metaCol.index.get(META_DOC_ID222);if(!doc)doc={_id:META_DOC_ID222},metaCol.data.push(doc),metaCol.index.set(META_DOC_ID222,doc);return doc}_log(msg){if(this._debug)this._logger(msg,"info")}}var _txIdCounter222=0;class TransactionManager222{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(fn,db,{timeout=0}={}){let execute=async()=>{await db._ensureConnected();let preExisting=new Set(Object.keys(db.collections)),ctx={id:++_txIdCounter222,startedAt:Date.now(),aborted:!1,preExisting,touchedCollections:new Set,snapshots:new Map,deferredEffects:[],timeout};this._ctx=ctx;let timer=null,timeoutPromise=timeout>0?new Promise((_,reject)=>{timer=setTimeout(()=>{ctx.aborted=!0,reject(new TransactionError222("ERR_SKALEX_TX_TIMEOUT",`Transaction ${ctx.id} timed out after ${timeout}ms`))},timeout)}):null,self=this,proxy=new Proxy(db,{get(target,prop){if(prop==="_txId")return ctx.id;if(ctx!==self._ctx)throw new TransactionError222("ERR_SKALEX_TX_STALE_PROXY",`Transaction ${ctx.id} has ended. This proxy is no longer usable.`);if(prop==="collections")throw new TransactionError222("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(prop==="useCollection")return(name)=>{let col=target.useCollection(name);return col._activeTxId=ctx.id,col};let value=Reflect.get(target,prop);return typeof value==="function"?value.bind(target):value}});try{let fnPromise=fn(proxy),result=timeoutPromise?await Promise.race([fnPromise,timeoutPromise]):await fnPromise;if(ctx.aborted)throw new TransactionError222("ERR_SKALEX_TX_ABORTED",`Transaction ${ctx.id} was aborted`);let touched=[...ctx.touchedCollections];if(touched.length>0)await db._persistence.saveAtomic(db.collections,touched);for(let effect of ctx.deferredEffects)await effect();return result}catch(error222){for(let[name,snap]of ctx.snapshots)if(ctx.preExisting.has(name)){if(db._applySnapshot(name,snap),db.collections[name])db.collections[name]._dirty=snap._dirty}for(let name in db.collections)if(!ctx.preExisting.has(name))delete db.collections[name],delete db._collectionInstances[name];throw error222}finally{if(timer)clearTimeout(timer);if(ctx.aborted)this._abortedIds.add(ctx.id);this._ctx=null;for(let name in db._collectionInstances){let inst=db._collectionInstances[name];if(inst._createdInTxId===ctx.id)inst._createdInTxId=null;if(inst._activeTxId===ctx.id)inst._activeTxId=null}}},next=this._txLock.then(execute);return this._txLock=next.catch(()=>{}),next}snapshotIfNeeded(name,col,snapshotFn){let ctx=this._ctx;if(!ctx)return;if(this._assertCtxNotAborted(ctx),!ctx.snapshots.has(name)){let snap=snapshotFn(col);snap._dirty=col._dirty??!1,ctx.snapshots.set(name,snap)}ctx.touchedCollections.add(name)}assertNotAborted(){let ctx=this._ctx;if(ctx)this._assertCtxNotAborted(ctx)}_assertCtxNotAborted(ctx){if(ctx.aborted)throw new TransactionError222("ERR_SKALEX_TX_ABORTED",`Transaction ${ctx.id} was aborted. No further mutations allowed.`)}defer(effect){if(this._ctx)return this._ctx.deferredEffects.push(effect),!0;return!1}}class CollectionRegistry222{constructor(CollectionClass){this._CollectionClass=CollectionClass,this.stores={},this._instances={}}get(name,db){if(this._instances[name])return this._instances[name];if(!this.stores[name])this.createStore(name);let instance=new this._CollectionClass(this.stores[name],db);return this._instances[name]=instance,instance}create(name,options={},db){this.createStore(name,options);let instance=new this._CollectionClass(this.stores[name],db);return this._instances[name]=instance,instance}createStore(name,{schema,indexes=[],changelog=!1,softDelete=!1,versioning=!1,strict=!1,onSchemaError="throw",defaultTtl=null,defaultEmbed=null,maxDocs=null}={}){let parsedSchema=null,fieldIndex=null;if(schema){parsedSchema=parseSchema222(schema);let uniqueFields=parsedSchema.uniqueFields;if(indexes.length||uniqueFields.length)fieldIndex=new IndexEngine222(indexes,uniqueFields)}else if(indexes.length)fieldIndex=new IndexEngine222(indexes,[]);this.stores[name]={collectionName:name,data:[],index:new Map,isSaving:!1,_pendingSave:!1,_dirty:!1,schema:parsedSchema,rawSchema:schema||null,fieldIndex,changelog,softDelete,versioning,strict,onSchemaError,defaultTtl,defaultEmbed,maxDocs}}rename(from,to){if(!this.stores[from])throw new PersistenceError222("ERR_SKALEX_PERSISTENCE_COLLECTION_NOT_FOUND",`Collection "${from}" not found`,{collection:from});if(this.stores[to])throw new PersistenceError222("ERR_SKALEX_PERSISTENCE_COLLECTION_EXISTS",`Collection "${to}" already exists`,{collection:to});let store=this.stores[from];if(store.collectionName=to,this.stores[to]=store,delete this.stores[from],this._instances[from]){let inst=this._instances[from];inst.name=to,this._instances[to]=inst,delete this._instances[from]}}buildIndex(data,keyField){let index=new Map;for(let item of data)index.set(item[keyField],item);return index}inspect(name){if(name){let col=this.stores[name];if(!col)return null;return{name,count:col.data.length,schema:col.schema?Object.fromEntries(col.schema.fields):null,indexes:col.fieldIndex?[...col.fieldIndex.indexedFields]:[],softDelete:col.softDelete??!1,versioning:col.versioning??!1,strict:col.strict??!1,onSchemaError:col.onSchemaError??"throw",maxDocs:col.maxDocs??null}}let result={};for(let n in this.stores)result[n]=this.inspect(n);return result}dump(){let result={};for(let name in this.stores)if(!name.startsWith("_"))result[name]=structuredClone(this.stores[name].data);return result}schema(name){let store=this.stores[name];if(!store)return null;if(store.schema)return Object.fromEntries([...store.schema.fields.entries()].map(([k,v])=>[k,v.type]));if(store.data.length>0)return inferSchema222(store.data[0]);return null}stats(name){let calc=(n)=>{let col=this.stores[n];if(!col)return null;let count2222=col.data.length,estimatedSize=0;for(let doc of col.data)try{estimatedSize+=JSON.stringify(doc).length}catch(_){}return{collection:n,count:count2222,estimatedSize,avgDocSize:count2222>0?Math.round(estimatedSize/count2222):0}};if(name)return calc(name);return Object.keys(this.stores).map(calc)}clear(){this.stores={},this._instances={}}}class EmbeddingAdapter222{async embed(text){throw Error("EmbeddingAdapter.embed() not implemented")}}var _env$4222=(k)=>globalThis.process?.env?.[k]??globalThis.Deno?.env?.get(k);class OpenAIEmbeddingAdapter222 extends EmbeddingAdapter222{constructor({apiKey=_env$4222("OPENAI_API_KEY"),model=_env$4222("OPENAI_EMBED_MODEL")??"text-embedding-3-small",baseUrl=_env$4222("OPENAI_EMBED_BASE_URL")??"https://api.openai.com/v1/embeddings",dimensions=_env$4222("OPENAI_EMBED_DIMENSIONS")!=null?Number(_env$4222("OPENAI_EMBED_DIMENSIONS")):void 0,organization=_env$4222("OPENAI_ORGANIZATION")??void 0,timeout=_env$4222("OPENAI_EMBED_TIMEOUT")!=null?Number(_env$4222("OPENAI_EMBED_TIMEOUT")):void 0,retries=Number(_env$4222("OPENAI_EMBED_RETRIES")??0),retryDelay=Number(_env$4222("OPENAI_EMBED_RETRY_DELAY")??1000),headers={},fetch:fetchFn=globalThis.fetch}={}){super();if(!apiKey)throw Error("OpenAIEmbeddingAdapter requires an apiKey");this.apiKey=apiKey,this.model=model,this.baseUrl=baseUrl,this.dimensions=dimensions,this.organization=organization,this.timeout=timeout,this.retries=retries,this.retryDelay=retryDelay,this.headers=headers,this._fetch=fetchFn}async embed(text){let lastErr;for(let attempt=0;attempt<=this.retries;attempt++){let controller=this.timeout!=null?new AbortController:null,timer=controller?setTimeout(()=>controller.abort(),this.timeout):null;try{let response=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:text,model:this.model,...this.dimensions!==void 0&&{dimensions:this.dimensions}}),...controller&&{signal:controller.signal}});if(!response.ok){let err=(await response.text()).slice(0,200);throw Error(`OpenAI embedding API error ${response.status}: ${err}`)}return(await response.json()).data[0].embedding}catch(err){if(lastErr=err,attempt<this.retries)await new Promise((r)=>setTimeout(r,this.retryDelay*2**attempt))}finally{if(timer!==null)clearTimeout(timer)}}throw lastErr}}var _env$3222=(k)=>globalThis.process?.env?.[k]??globalThis.Deno?.env?.get(k);class OllamaEmbeddingAdapter222 extends EmbeddingAdapter222{constructor({model=_env$3222("OLLAMA_EMBED_MODEL")??"nomic-embed-text",host=_env$3222("OLLAMA_HOST")??"http://localhost:11434",timeout=_env$3222("OLLAMA_EMBED_TIMEOUT")!=null?Number(_env$3222("OLLAMA_EMBED_TIMEOUT")):void 0,retries=Number(_env$3222("OLLAMA_EMBED_RETRIES")??0),retryDelay=Number(_env$3222("OLLAMA_EMBED_RETRY_DELAY")??1000),headers={},fetch:fetchFn=globalThis.fetch}={}){super();this.model=model,this.host=host,this.timeout=timeout,this.retries=retries,this.retryDelay=retryDelay,this.headers=headers,this._fetch=fetchFn}async embed(text){let lastErr;for(let attempt=0;attempt<=this.retries;attempt++){let controller=this.timeout!=null?new AbortController:null,timer=controller?setTimeout(()=>controller.abort(),this.timeout):null;try{let response=await this._fetch(`${this.host}/api/embeddings`,{method:"POST",headers:{"Content-Type":"application/json",...this.headers},body:JSON.stringify({model:this.model,prompt:text}),...controller&&{signal:controller.signal}});if(!response.ok){let err=(await response.text()).slice(0,200);throw Error(`Ollama embedding API error ${response.status}: ${err}`)}return(await response.json()).embedding}catch(err){if(lastErr=err,attempt<this.retries)await new Promise((r)=>setTimeout(r,this.retryDelay*2**attempt))}finally{if(timer!==null)clearTimeout(timer)}}throw lastErr}}class LLMAdapter222{async generate(schema,nlQuery){throw Error("LLMAdapter.generate() not implemented")}async summarize(texts){throw Error("LLMAdapter.summarize() not implemented")}}var SYSTEM_GENERATE222=`You are a database query assistant. Convert the user's natural language request into a JSON filter object for a document database.
84
84
 
@@ -104,4 +104,4 @@ data: /message
104
104
 
105
105
  `),this._clients.add(res),req.on("close",()=>{this._clients.delete(res)})}async _handleMessage(req,res){let body="";req.setEncoding("utf8"),req.on("data",(c)=>{if(body+=c,body.length>this._maxBodySize)req.destroy(),res.writeHead(413,{"Content-Type":"application/json"}),res.end(JSON.stringify({error:"Request body too large"}))}),req.on("end",async()=>{res.writeHead(202,{"Content-Type":"application/json"}),res.end("{}");let msg;try{msg=JSON.parse(body)}catch(_){this.send(error222(null,PARSE_ERROR222,"Parse error"));return}if(this._onMessage)await this._onMessage(msg).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 StdioTransport222{constructor(){this._onMessage=null,this._buffer="",this._started=!1}onMessage(fn){this._onMessage=fn}send(msg){process.stdout.write(JSON.stringify(msg)+`
106
106
  `)}start(){if(this._started)return;this._started=!0,process.stdin.setEncoding("utf8"),process.stdin.on("data",(chunk)=>{this._buffer+=chunk;let idx;while((idx=this._buffer.indexOf(`
107
- `))!==-1){let line=this._buffer.slice(0,idx).trim();if(this._buffer=this._buffer.slice(idx+1),line&&this._onMessage){let msg;try{msg=JSON.parse(line)}catch(_){this.send(error222(null,PARSE_ERROR222,"Parse error"));continue}this._onMessage(msg).catch(()=>{})}}}),process.stdin.on("end",()=>{process.exit(0)})}stop(){process.stdin.removeAllListeners("data"),process.stdin.removeAllListeners("end"),this._started=!1}}var SERVER_INFO222={name:"skalex",version:"4.0.0-alpha"},PROTOCOL_VERSION222="2024-11-05";class SkalexMCPServer222{constructor(db,opts={}){this._db=db,this._transport=opts.transport||"stdio",this._port=opts.port||3000,this._host=opts.host||"127.0.0.1",this._allowedOrigin=opts.allowedOrigin??null,this._maxBodySize=opts.maxBodySize??1048576,this._scopes=opts.scopes||{"*":["read"]},this._t=null}async listen(){if(this._transport==="http")this._t=new HttpTransport222({port:this._port,host:this._host,allowedOrigin:this._allowedOrigin,maxBodySize:this._maxBodySize});else this._t=new StdioTransport222;this._t.onMessage((msg)=>this._handleMessage(msg)),await this._t.start()}async connect(transport){if(this._t=transport,this._t.onMessage((msg)=>this._handleMessage(msg)),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(raw){let{msg,parseError}=typeof raw==="string"?parse222(raw):{msg:raw};if(parseError){this._send(parseError);return}let{id,method,params}=msg;if(id===void 0){if(method==="notifications/initialized")return;return}try{switch(method){case"initialize":this._send(ok222(id,{protocolVersion:PROTOCOL_VERSION222,capabilities:{tools:{}},serverInfo:SERVER_INFO222}));break;case"tools/list":this._send(ok222(id,{tools:this._visibleTools()}));break;case"tools/call":await this._handleToolCall(id,params);break;case"ping":this._send(ok222(id,{}));break;default:this._send(error222(id,METHOD_NOT_FOUND222,`Method not found: ${method}`))}}catch(err){this._send(error222(id,INTERNAL_ERROR222,err.message||"Internal error"))}}async _handleToolCall(id,params){let name=params?.name,args=params?.arguments??{};if(!name){this._send(error222(id,INVALID_PARAMS222,"tools/call requires params.name"));return}let def=TOOL_DEFS222.find((t)=>t.name===name);if(!def){this._send(error222(id,METHOD_NOT_FOUND222,`Unknown tool: ${name}`));return}let collection=args.collection||args.collection_name||null;if(!this._hasScope(collection,def.scope)){this._send(ok222(id,toolError222(`Access denied: "${name}" requires "${def.scope}" scope on collection "${collection}".`)));return}try{let result=await callTool222(name,args,this._db);this._send(ok222(id,toolResult222(JSON.stringify(result,null,2))))}catch(err){this._send(ok222(id,toolError222(err.message||String(err))))}}_visibleTools(){return TOOL_DEFS222.filter((def)=>{let global=this._scopes["*"];if(global&&(global.includes(def.scope)||global.includes("admin")))return!0;for(let[,perms]of Object.entries(this._scopes))if(perms.includes(def.scope)||perms.includes("admin"))return!0;return!1})}_hasScope(collection,scope){let check=(perms)=>perms.includes("admin")||perms.includes(scope);if(collection&&this._scopes[collection])return check(this._scopes[collection]);if(this._scopes["*"])return check(this._scopes["*"]);return!1}_send(msg){this._t?.send(msg)}}var META_KEY222="migrations",_serialize222=(value)=>JSON.stringify(value,function(key,v){let raw=this[key];if(raw instanceof Date)return{__skalex_date__:raw.toISOString()};if(typeof v==="bigint")return{__skalex_bigint__:v.toString()};return v}),_deserialize222=(text)=>JSON.parse(text,(_,v)=>{if(v&&typeof v==="object"){if("__skalex_bigint__"in v)return BigInt(v.__skalex_bigint__);if("__skalex_date__"in v)return new Date(v.__skalex_date__)}return v});class Skalex222{constructor({path="./.db",format="gz",debug=!1,adapter,ai,encrypt,slowQueryLog,queryCache,memory,logger:logger$1,plugins,llmAdapter,embeddingAdapter,regexMaxLength,idGenerator,serializer,deserializer,autoSave,ttlSweepInterval,lenientLoad}={}){if(this.dataDirectory=path,this.dataFormat=format,this.debug=debug,!Skalex222._errorsAttached)Skalex222.SkalexError=SkalexError222,Skalex222.ValidationError=ValidationError222,Skalex222.UniqueConstraintError=UniqueConstraintError222,Skalex222.TransactionError=TransactionError222,Skalex222.PersistenceError=PersistenceError222,Skalex222.AdapterError=AdapterError222,Skalex222.QueryError=QueryError222,Skalex222._errorsAttached=!0;this._adapterConfig=adapter??null;let fs=adapter||new FsAdapter222({dir:path,format});if(encrypt)fs=new EncryptedAdapter222(fs,encrypt.key);if(this.fs=fs,this._registry=new CollectionRegistry222(Collection222),this.collections=this._registry.stores,this._collectionInstances=this._registry._instances,this._migrations=new MigrationEngine222,this._connectPromise=null,this.isConnected=!1,this._aiConfig=ai||null,this._encryptConfig=encrypt||null,this._pluginsConfig=Array.isArray(plugins)?plugins:null,this._memoryConfig=memory||null,this._regexMaxLength=regexMaxLength??500,this._idGenerator=idGenerator??null,this._serializer=serializer??_serialize222,this._deserializer=deserializer??_deserialize222,this._autoSave=autoSave??!1,this._txManager=new TransactionManager222,this._ttlSweepInterval=ttlSweepInterval??0,this._ttlTimer=null,this._logger=logger$1??logger222,this._embeddingAdapter=embeddingAdapter??(ai?createEmbeddingAdapter222(ai):null),this._aiAdapter=llmAdapter??(ai?createLLMAdapter222(ai):null),this._persistence=new PersistenceManager222({adapter:this.fs,serializer:this._serializer,deserializer:this._deserializer,logger:this._logger,debug:this.debug,lenientLoad:lenientLoad??!1}),this._changeLog=new ChangeLog222(this),this._queryCache=new QueryCache222(queryCache||{}),this._eventBus=new EventBus222,this._queryLog=slowQueryLog?new QueryLog222(slowQueryLog):null,this._sessionStats=new SessionStats222,this._plugins=new PluginEngine222,Array.isArray(plugins))for(let p of plugins)this._plugins.register(p)}async connect(){if(this._connectPromise)return this._connectPromise;return this._connectPromise=this._doConnect(),this._connectPromise}async _doConnect(){try{await this.loadData();let meta=this._getMeta();if(meta.queryCache)this._queryCache.fromJSON(meta.queryCache);if(this._migrations._migrations.length>0){let applied=meta.appliedVersions||[],newApplied=await this._migrations.run((version)=>this.useCollection(`_migration_${version}`),applied);this._saveMeta({appliedVersions:newApplied})}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(error2222){throw this._logger(`Error connecting to the database: ${error2222}`,"error"),error2222}}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(error2222){throw this._logger(`Error disconnecting from the database: ${error2222}`,"error"),error2222}}async _ensureConnected(){if(this.isConnected)return;return this.connect()}useCollection(collectionName){return this._registry.get(collectionName,this)}createCollection(collectionName,options={}){return this._registry.create(collectionName,options,this)}_createCollectionStore(collectionName,options={}){this._registry.createStore(collectionName,options)}async renameCollection(from,to){this._registry.rename(from,to),await this.saveData(to),await this.fs.delete(from)}async loadData(){await this._persistence.loadAll(this.collections,{parseSchema:parseSchema222,buildIndex:this._registry.buildIndex,IndexEngine:IndexEngine222});for(let name in this._collectionInstances){let store=this.collections[name];if(store&&this._collectionInstances[name]._store!==store)this._collectionInstances[name]._store=store}}async saveData(collectionName){await this._persistence.save(this.collections,collectionName)}buildIndex(data,keyField){return this._registry.buildIndex(data,keyField)}addMigration(migration){this._migrations.add(migration)}migrationStatus(){let meta=this._getMeta();return this._migrations.status(meta.appliedVersions||[])}namespace(id){if(this._adapterConfig)throw new AdapterError222("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 safeId=String(id).replace(/[^a-zA-Z0-9_-]/g,"_");if(!safeId)throw new ValidationError222("ERR_SKALEX_VALIDATION_NAMESPACE_ID","namespace: id must contain at least one alphanumeric character",{id});return new Skalex222({path:`${this.dataDirectory}/${safeId}`,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!==logger222?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!==_serialize222?this._serializer:void 0,deserializer:this._deserializer!==_deserialize222?this._deserializer:void 0,autoSave:this._autoSave||void 0,ttlSweepInterval:this._ttlSweepInterval||void 0})}use(plugin){this._plugins.register(plugin)}watch(callback){return this._eventBus.on("*",callback)}sessionStats(sessionId){if(sessionId!==void 0)return this._sessionStats.get(sessionId);return this._sessionStats.all()}get _inTransaction(){return this._txManager.active}_emitEvent(collectionName,data){if(!this._txManager.defer(()=>this._eventBus.emit(collectionName,data)))this._eventBus.emit(collectionName,data)}async _runAfterHook(hook,data){if(!this._txManager.defer(()=>this._plugins.run(hook,data)))await this._plugins.run(hook,data)}async _logChange(op,collectionName,doc,prev,session){if(!this._txManager.defer(()=>this._changeLog.log(op,collectionName,doc,prev,session)))await this._changeLog.log(op,collectionName,doc,prev,session)}async transaction(fn,opts={}){return this._txManager.run(fn,this,opts)}async seed(fixtures,{reset=!1}={}){for(let[name,docs]of Object.entries(fixtures)){if(reset&&this.collections[name])this._applySnapshot(name,{data:[],index:new Map}),delete this._collectionInstances[name];await this.useCollection(name).insertMany(docs)}await this.saveData()}dump(){return this._registry.dump()}inspect(collectionName){return this._registry.inspect(collectionName)}async import(filePath){let content=await this.fs.readRaw(filePath),docs;try{docs=JSON.parse(content)}catch{throw new PersistenceError222("ERR_SKALEX_PERSISTENCE_INVALID_JSON",`import: invalid JSON in file "${filePath}"`,{filePath})}let name=filePath.split("/").pop().replace(/\.[^.]+$/,"");return this.useCollection(name).insertMany(Array.isArray(docs)?docs:[docs],{save:!0})}async embed(text){if(!this._embeddingAdapter)throw new AdapterError222("ERR_SKALEX_ADAPTER_EMBEDDING_REQUIRED","db.embed() requires an AI adapter. Pass { ai: { provider, apiKey } } to the Skalex constructor.");return this._embeddingAdapter.embed(text)}async ask(collectionName,nlQuery,{limit=20}={}){if(!this._aiAdapter)throw new AdapterError222("ERR_SKALEX_ADAPTER_LLM_REQUIRED",'db.ask() requires a language model adapter. Configure { ai: { provider, model: "..." } }.');let col=this.useCollection(collectionName),schema=this.schema(collectionName),filter=this._queryCache.get(collectionName,schema,nlQuery);if(!filter){filter=await this._aiAdapter.generate(schema,nlQuery);let warnings=validateLLMFilter222(filter,schema);if(warnings.length)warnings.forEach((w)=>this._log(`[ask] ${w}`));this._queryCache.set(collectionName,schema,nlQuery,filter),this._saveMeta({queryCache:this._queryCache.toJSON()})}return col.find(processLLMFilter222(filter,{regexMaxLength:this._regexMaxLength}),{limit})}schema(collectionName){return this._registry.schema(collectionName)}useMemory(sessionId){return new Memory222(sessionId,this)}changelog(){return this._changeLog}async restore(collectionName,timestamp,opts={}){return this._changeLog.restore(collectionName,timestamp,opts)}stats(collectionName){return this._registry.stats(collectionName)}slowQueries(opts={}){if(!this._queryLog)return[];return this._queryLog.entries(opts)}slowQueryCount(){return this._queryLog?this._queryLog.size:0}clearSlowQueries(){this._queryLog?.clear()}mcp(opts={}){return new SkalexMCPServer222(this,opts)}_getMeta(){let metaCol=this.collections._meta;if(!metaCol)return{};return metaCol.index.get(META_KEY222)||{}}_saveMeta(data){if(!this.collections._meta)this._createCollectionStore("_meta");let col=this.collections._meta,existing=col.index.get(META_KEY222);if(existing)Object.assign(existing,data);else{let doc={_id:META_KEY222,...data};col.data.push(doc),col.index.set(META_KEY222,doc)}this._persistence.markDirty(this.collections,"_meta")}_sweepTtl(){for(let name in this.collections){let col=this.collections[name],removed=sweep222(col.data,col.index,col.fieldIndex?(doc)=>col.fieldIndex.remove(doc):null);if(removed>0)this._persistence.markDirty(this.collections,name),this._log(`TTL sweep: removed ${removed} expired docs from "${name}"`)}}_buildCollectionContext(){let db=this;return{ensureConnected:()=>db._ensureConnected(),get txManager(){return db._txManager},get plugins(){return db._plugins},get eventBus(){return db._eventBus},get sessionStats(){return db._sessionStats},get queryLog(){return db._queryLog},get logger(){return db._logger},get persistence(){return db._persistence},get collections(){return db.collections},embed:(text)=>db.embed(text),get idGenerator(){return db._idGenerator},get autoSave(){return db._autoSave},saveCollection:(name)=>db.saveData(name),snapshotCollection:(col)=>db._snapshotCollection(col),getCollection:(name)=>db.useCollection(name),emitEvent:(name,data)=>db._emitEvent(name,data),runAfterHook:(hook,data)=>db._runAfterHook(hook,data),logChange:(op,col,doc,prev,session)=>db._logChange(op,col,doc,prev,session),get fs(){return db.fs},get dataDirectory(){return db.dataDirectory}}}_log(msg){if(this.debug)this._logger(msg,"info")}_snapshotCollection(col){return{data:structuredClone(col.data)}}_applySnapshot(name,snap){let col=this.collections[name];if(!col)return;if(col.data=snap.data,col.index=this.buildIndex(snap.data,"_id"),col.fieldIndex)col.fieldIndex.buildFromData(snap.data)}}class AgentDatabase{}var registry=new Map;function registerAdapter(name,factory){registry.set(name,factory)}var nowIso=()=>new Date().toISOString();function cleanDoc(doc){if(!doc)return doc;let{_id:_ignoredId,createdAt:rawCreatedAt,updatedAt:rawUpdatedAt,_version:_ignoredVersion,_expiresAt:_ignoredExpires,...rest}=doc,out={...rest};if(out.createdAt==null&&rawCreatedAt!=null)out.createdAt=rawCreatedAt instanceof Date?rawCreatedAt.toISOString():String(rawCreatedAt);if(out.updatedAt==null&&rawUpdatedAt!=null)out.updatedAt=rawUpdatedAt instanceof Date?rawUpdatedAt.toISOString():String(rawUpdatedAt);return out}class SkalexAgentDatabase extends AgentDatabase{dataDir;encryptionKey;lockPath;lockFd=null;db;tasks;config;gitRepos;bookmarks;notifications;pluginState;constructor(opts){super();this.dataDir=opts.dataDir,this.encryptionKey=opts.encryptionKey,this.lockPath=join(opts.dataDir,".agent-db.lock")}static async create(opts){if(!existsSync(opts.dataDir))mkdirSync(opts.dataDir,{recursive:!0});let instance=new SkalexAgentDatabase(opts);instance.acquireLock();try{await instance.init()}catch(err){throw instance.releaseLock(),err}return instance}acquireLock(){try{this.lockFd=openSync(this.lockPath,"wx",384),writeFileSync(this.lockFd,JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()}));return}catch(err){if(err.code!=="EEXIST")throw err}let stale=!1;try{let raw=JSON.parse(readFileSync(this.lockPath,"utf8"));if(!raw.pid)stale=!0;else try{process.kill(raw.pid,0)}catch{stale=!0}}catch{stale=!0}if(stale){try{unlinkSync(this.lockPath)}catch{}this.acquireLock();return}throw Error(`Agent database is already open by another process (${this.lockPath})`)}releaseLock(){if(this.lockFd!==null){try{closeSync(this.lockFd)}catch{}this.lockFd=null}try{unlinkSync(this.lockPath)}catch{}}async init(){this.db=new Skalex222({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(task){let doc={id:task.id,type:task.type,status:task.status,payload:task.payload};if(task.result!=null)doc.result=task.result;if(task.error!=null)doc.error=task.error;if(task.calendarTaskId!=null)doc.calendarTaskId=task.calendarTaskId;if(task.exitCode!=null)doc.exitCode=task.exitCode;if(task.timeout!=null)doc.timeout=task.timeout;let inserted=await this.tasks.insertOne(doc);return cleanDoc(inserted)}async getTask(id){let doc=await this.tasks.findOne({id});return doc?cleanDoc(doc):void 0}async getAllTasks(){return(await this.tasks.find(void 0,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc(d))}async getPendingTasks(){return(await this.tasks.find({status:"pending"},{sort:{createdAt:1}})).docs.map((d)=>cleanDoc(d))}async updateTask(id,updates){let patch={};for(let[k,v]of Object.entries(updates)){if(k==="id"||k==="createdAt"||k==="updatedAt")continue;patch[k]=v??null}if(Object.keys(patch).length===0)return;await this.tasks.updateOne({id},patch)}async cancelTask(id){let existing=await this.tasks.findOne({id});if(!existing||existing.status!=="pending"&&existing.status!=="running")return!1;return await this.tasks.updateOne({id},{status:"failed",error:"Cancelled"}),!0}async getConfig(key){return(await this.config.findOne({key}))?.value}async setConfig(key,value){await this.config.upsert({key},{key,value})}async deleteConfig(key){return await this.config.deleteOne({key})!==null}async getAllConfig(){let res=await this.config.find(),out={};for(let doc of res.docs)out[doc.key]=doc.value;return out}async bulkSetConfig(entries){for(let[key,value]of Object.entries(entries))await this.config.upsert({key},{key,value})}async getConfigStatus(){let res=await this.config.find(),latest=null;for(let doc of res.docs){let raw=doc.updatedAt,iso=raw instanceof Date?raw.toISOString():typeof raw==="string"?raw:null;if(iso&&(!latest||iso>latest))latest=iso}return{totalKeys:res.docs.length,lastUpdated:latest}}async createGitRepository(repo){let doc={id:repo.id,path:repo.path,name:repo.name,isSubmodule:Boolean(repo.isSubmodule),lastScanned:nowIso()};if(repo.parentPath!=null)doc.parentPath=repo.parentPath;if(repo.projectType!=null)doc.projectType=repo.projectType;if(repo.vitePort!=null)doc.vitePort=repo.vitePort;let inserted=await this.gitRepos.insertOne(doc);return cleanDoc(inserted)}async getGitRepository(id){let doc=await this.gitRepos.findOne({id});return doc?cleanDoc(doc):void 0}async getGitRepositoryByPath(path){let doc=await this.gitRepos.findOne({path});return doc?cleanDoc(doc):void 0}async getAllGitRepositories(){return(await this.gitRepos.find(void 0,{sort:{path:1}})).docs.map((d)=>cleanDoc(d))}async updateGitRepository(id,updates){let patch={lastScanned:nowIso()};for(let[k,v]of Object.entries(updates)){if(k==="id"||k==="createdAt"||k==="updatedAt")continue;if(k==="isSubmodule"){patch[k]=Boolean(v);continue}patch[k]=v??null}await this.gitRepos.updateOne({id},patch)}async deleteGitRepository(id){return await this.gitRepos.deleteOne({id})!==null}async fixGitHierarchy(){let repos=await this.getAllGitRepositories(),fixed=0;for(let repo of repos){if(repo.isSubmodule)continue;let parent=repos.find((r)=>r.id!==repo.id&&repo.path.startsWith(`${r.path}/`)&&!r.isSubmodule);if(parent&&repo.parentPath!==parent.path)await this.updateGitRepository(repo.id,{parentPath:parent.path}),fixed++}return{fixed}}async createBookmarkedCommand(cmd){let doc={id:cmd.id,command:cmd.command};if(cmd.projectId!=null)doc.projectId=cmd.projectId;if(cmd.description!=null)doc.description=cmd.description;if(cmd.category!=null)doc.category=cmd.category;let inserted=await this.bookmarks.insertOne(doc);return cleanDoc(inserted)}async getBookmarkedCommand(id){let doc=await this.bookmarks.findOne({id});return doc?cleanDoc(doc):void 0}async getAllBookmarkedCommands(){return(await this.bookmarks.find(void 0,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc(d))}async getBookmarkedCommandsByProject(projectId){let filter=projectId===null?{projectId:{$fn:(v)=>v==null}}:{projectId};return(await this.bookmarks.find(filter,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc(d))}async getBookmarkedCommandsByCategory(category){return(await this.bookmarks.find({category},{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc(d))}async updateBookmarkedCommand(id,updates){let patch={};for(let[k,v]of Object.entries(updates)){if(k==="id"||k==="createdAt"||k==="updatedAt")continue;patch[k]=v??null}if(Object.keys(patch).length===0)return;await this.bookmarks.updateOne({id},patch)}async deleteBookmarkedCommand(id){return await this.bookmarks.deleteOne({id})!==null}async executeBookmarkedCommand(id){return this.getBookmarkedCommand(id)}async createNotification(notification){let doc={id:notification.id,type:notification.type,title:notification.title,message:notification.message,status:notification.status};if(notification.sessionName!=null)doc.sessionName=notification.sessionName;if(notification.projectId!=null)doc.projectId=notification.projectId;let inserted=await this.notifications.insertOne(doc);return cleanDoc(inserted)}async getNotification(id){let doc=await this.notifications.findOne({id});return doc?cleanDoc(doc):void 0}async getAllNotifications(){return(await this.notifications.find(void 0,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc(d))}async getNotificationsByProject(projectId){let filter=projectId===null?{projectId:{$fn:(v)=>v==null}}:{projectId};return(await this.notifications.find(filter,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc(d))}async getGlobalNotifications(){return this.getNotificationsByProject(null)}async getUnreadNotifications(){return(await this.notifications.find({status:"unread"},{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc(d))}async updateNotificationStatus(id,status){await this.notifications.updateOne({id},{status})}async markAllNotificationsRead(){return(await this.notifications.updateMany({status:"unread"},{status:"read"})).length}async deleteNotification(id){return await this.notifications.deleteOne({id})!==null}async clearOldNotifications(olderThanDays=30){let cutoff=new Date(Date.now()-olderThanDays*24*60*60*1000);return(await this.notifications.deleteMany({createdAt:{$fn:(v)=>v instanceof Date&&v<cutoff}})).length}async getPluginState(pluginName,key){return(await this.pluginState.findOne({$and:[{pluginName},{key}]}))?.value}async setPluginState(pluginName,key,value){await this.pluginState.upsert({$and:[{pluginName},{key}]},{pluginName,key,value})}async deletePluginState(pluginName,key){return await this.pluginState.deleteOne({$and:[{pluginName},{key}]})!==null}async getAllPluginState(pluginName){return(await this.pluginState.find({pluginName},{sort:{key:1}})).docs.map((doc)=>{let raw=doc.updatedAt,updatedAt=raw instanceof Date?raw.toISOString():typeof raw==="string"?raw:void 0;return{key:doc.key,value:doc.value,updatedAt}})}async deleteAllPluginState(pluginName){return(await this.pluginState.deleteMany({pluginName})).length}}var createSkalexAgentDatabase=(opts)=>SkalexAgentDatabase.create(opts);registerAdapter("skalex",createSkalexAgentDatabase);var registry2=new Map;function registerAdapter2(name,factory){registry2.set(name,factory)}class AgentDatabase2{}registerAdapter2("skalex",createSkalexAgentDatabase);var nowIso2=()=>new Date().toISOString();function cleanDoc2(doc){if(!doc)return doc;let{_id:_ignoredId,createdAt:rawCreatedAt,updatedAt:rawUpdatedAt,_version:_ignoredVersion,_expiresAt:_ignoredExpires,...rest}=doc,out={...rest};if(out.createdAt==null&&rawCreatedAt!=null)out.createdAt=rawCreatedAt instanceof Date?rawCreatedAt.toISOString():String(rawCreatedAt);if(out.updatedAt==null&&rawUpdatedAt!=null)out.updatedAt=rawUpdatedAt instanceof Date?rawUpdatedAt.toISOString():String(rawUpdatedAt);return out}class SkalexAgentDatabase2 extends AgentDatabase2{dataDir;encryptionKey;lockPath;lockFd=null;db;tasks;config;gitRepos;bookmarks;notifications;pluginState;constructor(opts){super();this.dataDir=opts.dataDir,this.encryptionKey=opts.encryptionKey,this.lockPath=join2(opts.dataDir,".agent-db.lock")}static async create(opts){if(!existsSync2(opts.dataDir))mkdirSync2(opts.dataDir,{recursive:!0});let instance=new SkalexAgentDatabase2(opts);instance.acquireLock();try{await instance.init()}catch(err){throw instance.releaseLock(),err}return instance}acquireLock(){try{this.lockFd=openSync2(this.lockPath,"wx",384),writeFileSync2(this.lockFd,JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()}));return}catch(err){if(err.code!=="EEXIST")throw err}let stale=!1;try{let raw=JSON.parse(readFileSync2(this.lockPath,"utf8"));if(!raw.pid)stale=!0;else try{process.kill(raw.pid,0)}catch{stale=!0}}catch{stale=!0}if(stale){try{unlinkSync2(this.lockPath)}catch{}this.acquireLock();return}throw Error(`Agent database is already open by another process (${this.lockPath})`)}releaseLock(){if(this.lockFd!==null){try{closeSync2(this.lockFd)}catch{}this.lockFd=null}try{unlinkSync2(this.lockPath)}catch{}}async init(){this.db=new Skalex22({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(task){let doc={id:task.id,type:task.type,status:task.status,payload:task.payload};if(task.result!=null)doc.result=task.result;if(task.error!=null)doc.error=task.error;if(task.calendarTaskId!=null)doc.calendarTaskId=task.calendarTaskId;if(task.exitCode!=null)doc.exitCode=task.exitCode;if(task.timeout!=null)doc.timeout=task.timeout;let inserted=await this.tasks.insertOne(doc);return cleanDoc2(inserted)}async getTask(id){let doc=await this.tasks.findOne({id});return doc?cleanDoc2(doc):void 0}async getAllTasks(){return(await this.tasks.find(void 0,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc2(d))}async getPendingTasks(){return(await this.tasks.find({status:"pending"},{sort:{createdAt:1}})).docs.map((d)=>cleanDoc2(d))}async updateTask(id,updates){let patch={};for(let[k,v]of Object.entries(updates)){if(k==="id"||k==="createdAt"||k==="updatedAt")continue;patch[k]=v??null}if(Object.keys(patch).length===0)return;await this.tasks.updateOne({id},patch)}async cancelTask(id){let existing=await this.tasks.findOne({id});if(!existing||existing.status!=="pending"&&existing.status!=="running")return!1;return await this.tasks.updateOne({id},{status:"failed",error:"Cancelled"}),!0}async getConfig(key){return(await this.config.findOne({key}))?.value}async setConfig(key,value){await this.config.upsert({key},{key,value})}async deleteConfig(key){return await this.config.deleteOne({key})!==null}async getAllConfig(){let res=await this.config.find(),out={};for(let doc of res.docs)out[doc.key]=doc.value;return out}async bulkSetConfig(entries){for(let[key,value]of Object.entries(entries))await this.config.upsert({key},{key,value})}async getConfigStatus(){let res=await this.config.find(),latest=null;for(let doc of res.docs){let raw=doc.updatedAt,iso=raw instanceof Date?raw.toISOString():typeof raw==="string"?raw:null;if(iso&&(!latest||iso>latest))latest=iso}return{totalKeys:res.docs.length,lastUpdated:latest}}async createGitRepository(repo){let doc={id:repo.id,path:repo.path,name:repo.name,isSubmodule:Boolean(repo.isSubmodule),lastScanned:nowIso2()};if(repo.parentPath!=null)doc.parentPath=repo.parentPath;if(repo.projectType!=null)doc.projectType=repo.projectType;if(repo.vitePort!=null)doc.vitePort=repo.vitePort;let inserted=await this.gitRepos.insertOne(doc);return cleanDoc2(inserted)}async getGitRepository(id){let doc=await this.gitRepos.findOne({id});return doc?cleanDoc2(doc):void 0}async getGitRepositoryByPath(path){let doc=await this.gitRepos.findOne({path});return doc?cleanDoc2(doc):void 0}async getAllGitRepositories(){return(await this.gitRepos.find(void 0,{sort:{path:1}})).docs.map((d)=>cleanDoc2(d))}async updateGitRepository(id,updates){let patch={lastScanned:nowIso2()};for(let[k,v]of Object.entries(updates)){if(k==="id"||k==="createdAt"||k==="updatedAt")continue;if(k==="isSubmodule"){patch[k]=Boolean(v);continue}patch[k]=v??null}await this.gitRepos.updateOne({id},patch)}async deleteGitRepository(id){return await this.gitRepos.deleteOne({id})!==null}async fixGitHierarchy(){let repos=await this.getAllGitRepositories(),fixed=0;for(let repo of repos){if(repo.isSubmodule)continue;let parent=repos.find((r)=>r.id!==repo.id&&repo.path.startsWith(`${r.path}/`)&&!r.isSubmodule);if(parent&&repo.parentPath!==parent.path)await this.updateGitRepository(repo.id,{parentPath:parent.path}),fixed++}return{fixed}}async createBookmarkedCommand(cmd){let doc={id:cmd.id,command:cmd.command};if(cmd.projectId!=null)doc.projectId=cmd.projectId;if(cmd.description!=null)doc.description=cmd.description;if(cmd.category!=null)doc.category=cmd.category;let inserted=await this.bookmarks.insertOne(doc);return cleanDoc2(inserted)}async getBookmarkedCommand(id){let doc=await this.bookmarks.findOne({id});return doc?cleanDoc2(doc):void 0}async getAllBookmarkedCommands(){return(await this.bookmarks.find(void 0,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc2(d))}async getBookmarkedCommandsByProject(projectId){let filter=projectId===null?{projectId:{$fn:(v)=>v==null}}:{projectId};return(await this.bookmarks.find(filter,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc2(d))}async getBookmarkedCommandsByCategory(category){return(await this.bookmarks.find({category},{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc2(d))}async updateBookmarkedCommand(id,updates){let patch={};for(let[k,v]of Object.entries(updates)){if(k==="id"||k==="createdAt"||k==="updatedAt")continue;patch[k]=v??null}if(Object.keys(patch).length===0)return;await this.bookmarks.updateOne({id},patch)}async deleteBookmarkedCommand(id){return await this.bookmarks.deleteOne({id})!==null}async executeBookmarkedCommand(id){return this.getBookmarkedCommand(id)}async createNotification(notification){let doc={id:notification.id,type:notification.type,title:notification.title,message:notification.message,status:notification.status};if(notification.sessionName!=null)doc.sessionName=notification.sessionName;if(notification.projectId!=null)doc.projectId=notification.projectId;let inserted=await this.notifications.insertOne(doc);return cleanDoc2(inserted)}async getNotification(id){let doc=await this.notifications.findOne({id});return doc?cleanDoc2(doc):void 0}async getAllNotifications(){return(await this.notifications.find(void 0,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc2(d))}async getNotificationsByProject(projectId){let filter=projectId===null?{projectId:{$fn:(v)=>v==null}}:{projectId};return(await this.notifications.find(filter,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc2(d))}async getGlobalNotifications(){return this.getNotificationsByProject(null)}async getUnreadNotifications(){return(await this.notifications.find({status:"unread"},{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc2(d))}async updateNotificationStatus(id,status){await this.notifications.updateOne({id},{status})}async markAllNotificationsRead(){return(await this.notifications.updateMany({status:"unread"},{status:"read"})).length}async deleteNotification(id){return await this.notifications.deleteOne({id})!==null}async clearOldNotifications(olderThanDays=30){let cutoff=new Date(Date.now()-olderThanDays*24*60*60*1000);return(await this.notifications.deleteMany({createdAt:{$fn:(v)=>v instanceof Date&&v<cutoff}})).length}async getPluginState(pluginName,key){return(await this.pluginState.findOne({$and:[{pluginName},{key}]}))?.value}async setPluginState(pluginName,key,value){await this.pluginState.upsert({$and:[{pluginName},{key}]},{pluginName,key,value})}async deletePluginState(pluginName,key){return await this.pluginState.deleteOne({$and:[{pluginName},{key}]})!==null}async getAllPluginState(pluginName){return(await this.pluginState.find({pluginName},{sort:{key:1}})).docs.map((doc)=>{let raw=doc.updatedAt,updatedAt=raw instanceof Date?raw.toISOString():typeof raw==="string"?raw:void 0;return{key:doc.key,value:doc.value,updatedAt}})}async deleteAllPluginState(pluginName){return(await this.pluginState.deleteMany({pluginName})).length}}var createSkalexAgentDatabase2=(opts)=>SkalexAgentDatabase2.create(opts);registerAdapter2("skalex",createSkalexAgentDatabase2);var registry3=new Map;function registerAdapter3(name,factory){registry3.set(name,factory)}class AgentDatabase3{}registerAdapter3("skalex",createSkalexAgentDatabase2);var nowIso3=()=>new Date().toISOString();function cleanDoc3(doc){if(!doc)return doc;let{_id:_ignoredId,createdAt:rawCreatedAt,updatedAt:rawUpdatedAt,_version:_ignoredVersion,_expiresAt:_ignoredExpires,...rest}=doc,out={...rest};if(out.createdAt==null&&rawCreatedAt!=null)out.createdAt=rawCreatedAt instanceof Date?rawCreatedAt.toISOString():String(rawCreatedAt);if(out.updatedAt==null&&rawUpdatedAt!=null)out.updatedAt=rawUpdatedAt instanceof Date?rawUpdatedAt.toISOString():String(rawUpdatedAt);return out}class SkalexAgentDatabase3 extends AgentDatabase3{dataDir;encryptionKey;lockPath;lockFd=null;db;tasks;config;gitRepos;bookmarks;notifications;pluginState;constructor(opts){super();this.dataDir=opts.dataDir,this.encryptionKey=opts.encryptionKey,this.lockPath=join3(opts.dataDir,".agent-db.lock")}static async create(opts){if(!existsSync3(opts.dataDir))mkdirSync3(opts.dataDir,{recursive:!0});let instance=new SkalexAgentDatabase3(opts);instance.acquireLock();try{await instance.init()}catch(err){throw instance.releaseLock(),err}return instance}acquireLock(){try{this.lockFd=openSync3(this.lockPath,"wx",384),writeFileSync3(this.lockFd,JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()}));return}catch(err){if(err.code!=="EEXIST")throw err}let stale=!1;try{let raw=JSON.parse(readFileSync3(this.lockPath,"utf8"));if(!raw.pid)stale=!0;else try{process.kill(raw.pid,0)}catch{stale=!0}}catch{stale=!0}if(stale){try{unlinkSync3(this.lockPath)}catch{}this.acquireLock();return}throw Error(`Agent database is already open by another process (${this.lockPath})`)}releaseLock(){if(this.lockFd!==null){try{closeSync3(this.lockFd)}catch{}this.lockFd=null}try{unlinkSync3(this.lockPath)}catch{}}async init(){this.db=new Skalex2({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(task){let doc={id:task.id,type:task.type,status:task.status,payload:task.payload};if(task.result!=null)doc.result=task.result;if(task.error!=null)doc.error=task.error;if(task.calendarTaskId!=null)doc.calendarTaskId=task.calendarTaskId;if(task.exitCode!=null)doc.exitCode=task.exitCode;if(task.timeout!=null)doc.timeout=task.timeout;let inserted=await this.tasks.insertOne(doc);return cleanDoc3(inserted)}async getTask(id){let doc=await this.tasks.findOne({id});return doc?cleanDoc3(doc):void 0}async getAllTasks(){return(await this.tasks.find(void 0,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc3(d))}async getPendingTasks(){return(await this.tasks.find({status:"pending"},{sort:{createdAt:1}})).docs.map((d)=>cleanDoc3(d))}async updateTask(id,updates){let patch={};for(let[k,v]of Object.entries(updates)){if(k==="id"||k==="createdAt"||k==="updatedAt")continue;patch[k]=v??null}if(Object.keys(patch).length===0)return;await this.tasks.updateOne({id},patch)}async cancelTask(id){let existing=await this.tasks.findOne({id});if(!existing||existing.status!=="pending"&&existing.status!=="running")return!1;return await this.tasks.updateOne({id},{status:"failed",error:"Cancelled"}),!0}async getConfig(key){return(await this.config.findOne({key}))?.value}async setConfig(key,value){await this.config.upsert({key},{key,value})}async deleteConfig(key){return await this.config.deleteOne({key})!==null}async getAllConfig(){let res=await this.config.find(),out={};for(let doc of res.docs)out[doc.key]=doc.value;return out}async bulkSetConfig(entries){for(let[key,value]of Object.entries(entries))await this.config.upsert({key},{key,value})}async getConfigStatus(){let res=await this.config.find(),latest=null;for(let doc of res.docs){let raw=doc.updatedAt,iso=raw instanceof Date?raw.toISOString():typeof raw==="string"?raw:null;if(iso&&(!latest||iso>latest))latest=iso}return{totalKeys:res.docs.length,lastUpdated:latest}}async createGitRepository(repo){let doc={id:repo.id,path:repo.path,name:repo.name,isSubmodule:Boolean(repo.isSubmodule),lastScanned:nowIso3()};if(repo.parentPath!=null)doc.parentPath=repo.parentPath;if(repo.projectType!=null)doc.projectType=repo.projectType;if(repo.vitePort!=null)doc.vitePort=repo.vitePort;let inserted=await this.gitRepos.insertOne(doc);return cleanDoc3(inserted)}async getGitRepository(id){let doc=await this.gitRepos.findOne({id});return doc?cleanDoc3(doc):void 0}async getGitRepositoryByPath(path){let doc=await this.gitRepos.findOne({path});return doc?cleanDoc3(doc):void 0}async getAllGitRepositories(){return(await this.gitRepos.find(void 0,{sort:{path:1}})).docs.map((d)=>cleanDoc3(d))}async updateGitRepository(id,updates){let patch={lastScanned:nowIso3()};for(let[k,v]of Object.entries(updates)){if(k==="id"||k==="createdAt"||k==="updatedAt")continue;if(k==="isSubmodule"){patch[k]=Boolean(v);continue}patch[k]=v??null}await this.gitRepos.updateOne({id},patch)}async deleteGitRepository(id){return await this.gitRepos.deleteOne({id})!==null}async fixGitHierarchy(){let repos=await this.getAllGitRepositories(),fixed=0;for(let repo of repos){if(repo.isSubmodule)continue;let parent=repos.find((r)=>r.id!==repo.id&&repo.path.startsWith(`${r.path}/`)&&!r.isSubmodule);if(parent&&repo.parentPath!==parent.path)await this.updateGitRepository(repo.id,{parentPath:parent.path}),fixed++}return{fixed}}async createBookmarkedCommand(cmd){let doc={id:cmd.id,command:cmd.command};if(cmd.projectId!=null)doc.projectId=cmd.projectId;if(cmd.description!=null)doc.description=cmd.description;if(cmd.category!=null)doc.category=cmd.category;let inserted=await this.bookmarks.insertOne(doc);return cleanDoc3(inserted)}async getBookmarkedCommand(id){let doc=await this.bookmarks.findOne({id});return doc?cleanDoc3(doc):void 0}async getAllBookmarkedCommands(){return(await this.bookmarks.find(void 0,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc3(d))}async getBookmarkedCommandsByProject(projectId){let filter=projectId===null?{projectId:{$fn:(v)=>v==null}}:{projectId};return(await this.bookmarks.find(filter,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc3(d))}async getBookmarkedCommandsByCategory(category){return(await this.bookmarks.find({category},{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc3(d))}async updateBookmarkedCommand(id,updates){let patch={};for(let[k,v]of Object.entries(updates)){if(k==="id"||k==="createdAt"||k==="updatedAt")continue;patch[k]=v??null}if(Object.keys(patch).length===0)return;await this.bookmarks.updateOne({id},patch)}async deleteBookmarkedCommand(id){return await this.bookmarks.deleteOne({id})!==null}async executeBookmarkedCommand(id){return this.getBookmarkedCommand(id)}async createNotification(notification){let doc={id:notification.id,type:notification.type,title:notification.title,message:notification.message,status:notification.status};if(notification.sessionName!=null)doc.sessionName=notification.sessionName;if(notification.projectId!=null)doc.projectId=notification.projectId;let inserted=await this.notifications.insertOne(doc);return cleanDoc3(inserted)}async getNotification(id){let doc=await this.notifications.findOne({id});return doc?cleanDoc3(doc):void 0}async getAllNotifications(){return(await this.notifications.find(void 0,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc3(d))}async getNotificationsByProject(projectId){let filter=projectId===null?{projectId:{$fn:(v)=>v==null}}:{projectId};return(await this.notifications.find(filter,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc3(d))}async getGlobalNotifications(){return this.getNotificationsByProject(null)}async getUnreadNotifications(){return(await this.notifications.find({status:"unread"},{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc3(d))}async updateNotificationStatus(id,status){await this.notifications.updateOne({id},{status})}async markAllNotificationsRead(){return(await this.notifications.updateMany({status:"unread"},{status:"read"})).length}async deleteNotification(id){return await this.notifications.deleteOne({id})!==null}async clearOldNotifications(olderThanDays=30){let cutoff=new Date(Date.now()-olderThanDays*24*60*60*1000);return(await this.notifications.deleteMany({createdAt:{$fn:(v)=>v instanceof Date&&v<cutoff}})).length}async getPluginState(pluginName,key){return(await this.pluginState.findOne({$and:[{pluginName},{key}]}))?.value}async setPluginState(pluginName,key,value){await this.pluginState.upsert({$and:[{pluginName},{key}]},{pluginName,key,value})}async deletePluginState(pluginName,key){return await this.pluginState.deleteOne({$and:[{pluginName},{key}]})!==null}async getAllPluginState(pluginName){return(await this.pluginState.find({pluginName},{sort:{key:1}})).docs.map((doc)=>{let raw=doc.updatedAt,updatedAt=raw instanceof Date?raw.toISOString():typeof raw==="string"?raw:void 0;return{key:doc.key,value:doc.value,updatedAt}})}async deleteAllPluginState(pluginName){return(await this.pluginState.deleteMany({pluginName})).length}}var createSkalexAgentDatabase3=(opts)=>SkalexAgentDatabase3.create(opts);registerAdapter3("skalex",createSkalexAgentDatabase3);var registry4=new Map;function registerAdapter4(name,factory){registry4.set(name,factory)}class AgentDatabase4{}registerAdapter4("skalex",createSkalexAgentDatabase3);var nowIso4=()=>new Date().toISOString();function cleanDoc4(doc){if(!doc)return doc;let{_id:_ignoredId,createdAt:rawCreatedAt,updatedAt:rawUpdatedAt,_version:_ignoredVersion,_expiresAt:_ignoredExpires,...rest}=doc,out={...rest};if(out.createdAt==null&&rawCreatedAt!=null)out.createdAt=rawCreatedAt instanceof Date?rawCreatedAt.toISOString():String(rawCreatedAt);if(out.updatedAt==null&&rawUpdatedAt!=null)out.updatedAt=rawUpdatedAt instanceof Date?rawUpdatedAt.toISOString():String(rawUpdatedAt);return out}class SkalexAgentDatabase4 extends AgentDatabase4{dataDir;encryptionKey;lockPath;lockFd=null;db;tasks;config;gitRepos;bookmarks;notifications;pluginState;constructor(opts){super();this.dataDir=opts.dataDir,this.encryptionKey=opts.encryptionKey,this.lockPath=join4(opts.dataDir,".agent-db.lock")}static async create(opts){if(!existsSync4(opts.dataDir))mkdirSync4(opts.dataDir,{recursive:!0});let instance=new SkalexAgentDatabase4(opts);instance.acquireLock();try{await instance.init()}catch(err){throw instance.releaseLock(),err}return instance}acquireLock(){try{this.lockFd=openSync4(this.lockPath,"wx",384),writeFileSync4(this.lockFd,JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()}));return}catch(err){if(err.code!=="EEXIST")throw err}let stale=!1;try{let raw=JSON.parse(readFileSync4(this.lockPath,"utf8"));if(!raw.pid)stale=!0;else try{process.kill(raw.pid,0)}catch{stale=!0}}catch{stale=!0}if(stale){try{unlinkSync4(this.lockPath)}catch{}this.acquireLock();return}throw Error(`Agent database is already open by another process (${this.lockPath})`)}releaseLock(){if(this.lockFd!==null){try{closeSync4(this.lockFd)}catch{}this.lockFd=null}try{unlinkSync4(this.lockPath)}catch{}}async init(){this.db=new Skalex({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(task){let doc={id:task.id,type:task.type,status:task.status,payload:task.payload};if(task.result!=null)doc.result=task.result;if(task.error!=null)doc.error=task.error;if(task.calendarTaskId!=null)doc.calendarTaskId=task.calendarTaskId;if(task.exitCode!=null)doc.exitCode=task.exitCode;if(task.timeout!=null)doc.timeout=task.timeout;let inserted=await this.tasks.insertOne(doc);return cleanDoc4(inserted)}async getTask(id){let doc=await this.tasks.findOne({id});return doc?cleanDoc4(doc):void 0}async getAllTasks(){return(await this.tasks.find(void 0,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc4(d))}async getPendingTasks(){return(await this.tasks.find({status:"pending"},{sort:{createdAt:1}})).docs.map((d)=>cleanDoc4(d))}async updateTask(id,updates){let patch={};for(let[k,v]of Object.entries(updates)){if(k==="id"||k==="createdAt"||k==="updatedAt")continue;patch[k]=v??null}if(Object.keys(patch).length===0)return;await this.tasks.updateOne({id},patch)}async cancelTask(id){let existing=await this.tasks.findOne({id});if(!existing||existing.status!=="pending"&&existing.status!=="running")return!1;return await this.tasks.updateOne({id},{status:"failed",error:"Cancelled"}),!0}async getConfig(key){return(await this.config.findOne({key}))?.value}async setConfig(key,value){await this.config.upsert({key},{key,value})}async deleteConfig(key){return await this.config.deleteOne({key})!==null}async getAllConfig(){let res=await this.config.find(),out={};for(let doc of res.docs)out[doc.key]=doc.value;return out}async bulkSetConfig(entries){for(let[key,value]of Object.entries(entries))await this.config.upsert({key},{key,value})}async getConfigStatus(){let res=await this.config.find(),latest=null;for(let doc of res.docs){let raw=doc.updatedAt,iso=raw instanceof Date?raw.toISOString():typeof raw==="string"?raw:null;if(iso&&(!latest||iso>latest))latest=iso}return{totalKeys:res.docs.length,lastUpdated:latest}}async createGitRepository(repo){let doc={id:repo.id,path:repo.path,name:repo.name,isSubmodule:Boolean(repo.isSubmodule),lastScanned:nowIso4()};if(repo.parentPath!=null)doc.parentPath=repo.parentPath;if(repo.projectType!=null)doc.projectType=repo.projectType;if(repo.vitePort!=null)doc.vitePort=repo.vitePort;let inserted=await this.gitRepos.insertOne(doc);return cleanDoc4(inserted)}async getGitRepository(id){let doc=await this.gitRepos.findOne({id});return doc?cleanDoc4(doc):void 0}async getGitRepositoryByPath(path){let doc=await this.gitRepos.findOne({path});return doc?cleanDoc4(doc):void 0}async getAllGitRepositories(){return(await this.gitRepos.find(void 0,{sort:{path:1}})).docs.map((d)=>cleanDoc4(d))}async updateGitRepository(id,updates){let patch={lastScanned:nowIso4()};for(let[k,v]of Object.entries(updates)){if(k==="id"||k==="createdAt"||k==="updatedAt")continue;if(k==="isSubmodule"){patch[k]=Boolean(v);continue}patch[k]=v??null}await this.gitRepos.updateOne({id},patch)}async deleteGitRepository(id){return await this.gitRepos.deleteOne({id})!==null}async fixGitHierarchy(){let repos=await this.getAllGitRepositories(),fixed=0;for(let repo of repos){if(repo.isSubmodule)continue;let parent=repos.find((r)=>r.id!==repo.id&&repo.path.startsWith(`${r.path}/`)&&!r.isSubmodule);if(parent&&repo.parentPath!==parent.path)await this.updateGitRepository(repo.id,{parentPath:parent.path}),fixed++}return{fixed}}async createBookmarkedCommand(cmd){let doc={id:cmd.id,command:cmd.command};if(cmd.projectId!=null)doc.projectId=cmd.projectId;if(cmd.description!=null)doc.description=cmd.description;if(cmd.category!=null)doc.category=cmd.category;let inserted=await this.bookmarks.insertOne(doc);return cleanDoc4(inserted)}async getBookmarkedCommand(id){let doc=await this.bookmarks.findOne({id});return doc?cleanDoc4(doc):void 0}async getAllBookmarkedCommands(){return(await this.bookmarks.find(void 0,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc4(d))}async getBookmarkedCommandsByProject(projectId){let filter=projectId===null?{projectId:{$fn:(v)=>v==null}}:{projectId};return(await this.bookmarks.find(filter,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc4(d))}async getBookmarkedCommandsByCategory(category){return(await this.bookmarks.find({category},{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc4(d))}async updateBookmarkedCommand(id,updates){let patch={};for(let[k,v]of Object.entries(updates)){if(k==="id"||k==="createdAt"||k==="updatedAt")continue;patch[k]=v??null}if(Object.keys(patch).length===0)return;await this.bookmarks.updateOne({id},patch)}async deleteBookmarkedCommand(id){return await this.bookmarks.deleteOne({id})!==null}async executeBookmarkedCommand(id){return this.getBookmarkedCommand(id)}async createNotification(notification){let doc={id:notification.id,type:notification.type,title:notification.title,message:notification.message,status:notification.status};if(notification.sessionName!=null)doc.sessionName=notification.sessionName;if(notification.projectId!=null)doc.projectId=notification.projectId;let inserted=await this.notifications.insertOne(doc);return cleanDoc4(inserted)}async getNotification(id){let doc=await this.notifications.findOne({id});return doc?cleanDoc4(doc):void 0}async getAllNotifications(){return(await this.notifications.find(void 0,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc4(d))}async getNotificationsByProject(projectId){let filter=projectId===null?{projectId:{$fn:(v)=>v==null}}:{projectId};return(await this.notifications.find(filter,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc4(d))}async getGlobalNotifications(){return this.getNotificationsByProject(null)}async getUnreadNotifications(){return(await this.notifications.find({status:"unread"},{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc4(d))}async updateNotificationStatus(id,status){await this.notifications.updateOne({id},{status})}async markAllNotificationsRead(){return(await this.notifications.updateMany({status:"unread"},{status:"read"})).length}async deleteNotification(id){return await this.notifications.deleteOne({id})!==null}async clearOldNotifications(olderThanDays=30){let cutoff=new Date(Date.now()-olderThanDays*24*60*60*1000);return(await this.notifications.deleteMany({createdAt:{$fn:(v)=>v instanceof Date&&v<cutoff}})).length}async getPluginState(pluginName,key){return(await this.pluginState.findOne({$and:[{pluginName},{key}]}))?.value}async setPluginState(pluginName,key,value){await this.pluginState.upsert({$and:[{pluginName},{key}]},{pluginName,key,value})}async deletePluginState(pluginName,key){return await this.pluginState.deleteOne({$and:[{pluginName},{key}]})!==null}async getAllPluginState(pluginName){return(await this.pluginState.find({pluginName},{sort:{key:1}})).docs.map((doc)=>{let raw=doc.updatedAt,updatedAt=raw instanceof Date?raw.toISOString():typeof raw==="string"?raw:void 0;return{key:doc.key,value:doc.value,updatedAt}})}async deleteAllPluginState(pluginName){return(await this.pluginState.deleteMany({pluginName})).length}}var createSkalexAgentDatabase4=(opts)=>SkalexAgentDatabase4.create(opts);registerAdapter4("skalex",createSkalexAgentDatabase4);var registry5=new Map;function registerAdapter5(name,factory){registry5.set(name,factory)}function getAdapter(name){return registry5.get(name)}function listAdapters(){return Array.from(registry5.keys())}class AgentDatabase5{}async function resolveFactory(options){if(options.adapterFactory)return options.adapterFactory;let name=options.adapterName??process.env.VIBE_STORAGE_ADAPTER??"skalex";if(name.startsWith("custom:")){let modPath=name.slice(7);if(!modPath)throw Error("VIBE_STORAGE_ADAPTER=custom: requires a module path after the colon");let mod=await import(modPath),factory2=mod.default??mod.createAdapter;if(typeof factory2!=="function")throw Error(`Custom storage adapter at ${modPath} must export a default function (or \`createAdapter\`) of type AgentStorageAdapterFactory`);return factory2}let factory=getAdapter(name);if(!factory){let candidate={skalex:"@vibecontrols/vibe-plugin-storage-skalex",postgres:"@vibecontrols/vibe-plugin-storage-postgres",postgresql:"@vibecontrols/vibe-plugin-storage-postgres"}[name];if(candidate)try{await import(candidate),factory=getAdapter(name)}catch{}}if(!factory)throw Error(`Unknown storage adapter: "${name}". Registered adapters: ${listAdapters().join(", ")||`(none \u2014 did you install @vibecontrols/vibe-plugin-storage-${name})?`}`);return factory}async function createAgentDatabase(options){if(!options.encryptionKey)throw Error("createAgentDatabase(): encryptionKey is required. Storage is always encrypted at rest.");if(!options.dbPath)throw Error("createAgentDatabase(): dbPath is required.");return(await resolveFactory(options))({dataDir:options.dbPath,encryptionKey:options.encryptionKey,adapterOptions:options.adapterOptions})}registerAdapter5("skalex",createSkalexAgentDatabase4);var PLUGIN_NAME="storage",PLUGIN_PACKAGE_NAME="@vibecontrols/vibe-plugin-storage",PLUGIN_VERSION=getPluginVersion();function getPluginVersion(){try{let dir=dirname(fileURLToPath(import.meta.url));for(let i=0;i<10&&dir&&dir!==dirname(dir);i++){let pkgPath=joinPath(dir,"package.json");if(existsSync5(pkgPath))try{let pkg=JSON.parse(readFileSync5(pkgPath,"utf8"));if(pkg.name===PLUGIN_PACKAGE_NAME&&typeof pkg.version==="string")return pkg.version}catch{}dir=dirname(dir)}}catch{}return"0.0.0"}var STORAGE_PROVIDERS=[{packageName:"@vibecontrols/vibe-plugin-storage-skalex",pluginName:"storage-skalex",defaultOn:["linux","darwin","win32"]},{packageName:"@vibecontrols/vibe-plugin-storage-postgres",pluginName:"storage-postgres"}],createPlugin=(ctx)=>{let log=new BoundLogger(ctx.logger,PLUGIN_NAME),lifecycle=createLifecycleHooks({name:PLUGIN_NAME,telemetryEventName:"storage.ready",onInit:(hostServices)=>{new TelemetryEmitter(PLUGIN_NAME,PLUGIN_VERSION,hostServices).emitReady(),log.info("storage meta plugin ready (skalex adapter auto-registered)")}});return{name:PLUGIN_NAME,version:PLUGIN_VERSION,description:"Storage facade \u2014 owns AgentDatabase contract and adapter registry",tags:["backend","adapter"],metaProviders:STORAGE_PROVIDERS,provisionProviders:(hostServices)=>provisionMetaProviders(hostServices,STORAGE_PROVIDERS),capabilities:{storage:"rw"},onServerStart:lifecycle.onServerStart,onServerStop:lifecycle.onServerStop}},src_default=createPlugin;export{registerAdapter5 as registerAdapter,listAdapters,getAdapter,src_default as default,createPlugin,createAgentDatabase,AgentDatabase5 as AgentDatabase};
107
+ `))!==-1){let line=this._buffer.slice(0,idx).trim();if(this._buffer=this._buffer.slice(idx+1),line&&this._onMessage){let msg;try{msg=JSON.parse(line)}catch(_){this.send(error222(null,PARSE_ERROR222,"Parse error"));continue}this._onMessage(msg).catch(()=>{})}}}),process.stdin.on("end",()=>{process.exit(0)})}stop(){process.stdin.removeAllListeners("data"),process.stdin.removeAllListeners("end"),this._started=!1}}var SERVER_INFO222={name:"skalex",version:"4.0.0-alpha"},PROTOCOL_VERSION222="2024-11-05";class SkalexMCPServer222{constructor(db,opts={}){this._db=db,this._transport=opts.transport||"stdio",this._port=opts.port||3000,this._host=opts.host||"127.0.0.1",this._allowedOrigin=opts.allowedOrigin??null,this._maxBodySize=opts.maxBodySize??1048576,this._scopes=opts.scopes||{"*":["read"]},this._t=null}async listen(){if(this._transport==="http")this._t=new HttpTransport222({port:this._port,host:this._host,allowedOrigin:this._allowedOrigin,maxBodySize:this._maxBodySize});else this._t=new StdioTransport222;this._t.onMessage((msg)=>this._handleMessage(msg)),await this._t.start()}async connect(transport){if(this._t=transport,this._t.onMessage((msg)=>this._handleMessage(msg)),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(raw){let{msg,parseError}=typeof raw==="string"?parse222(raw):{msg:raw};if(parseError){this._send(parseError);return}let{id,method,params}=msg;if(id===void 0){if(method==="notifications/initialized")return;return}try{switch(method){case"initialize":this._send(ok222(id,{protocolVersion:PROTOCOL_VERSION222,capabilities:{tools:{}},serverInfo:SERVER_INFO222}));break;case"tools/list":this._send(ok222(id,{tools:this._visibleTools()}));break;case"tools/call":await this._handleToolCall(id,params);break;case"ping":this._send(ok222(id,{}));break;default:this._send(error222(id,METHOD_NOT_FOUND222,`Method not found: ${method}`))}}catch(err){this._send(error222(id,INTERNAL_ERROR222,err.message||"Internal error"))}}async _handleToolCall(id,params){let name=params?.name,args=params?.arguments??{};if(!name){this._send(error222(id,INVALID_PARAMS222,"tools/call requires params.name"));return}let def=TOOL_DEFS222.find((t)=>t.name===name);if(!def){this._send(error222(id,METHOD_NOT_FOUND222,`Unknown tool: ${name}`));return}let collection=args.collection||args.collection_name||null;if(!this._hasScope(collection,def.scope)){this._send(ok222(id,toolError222(`Access denied: "${name}" requires "${def.scope}" scope on collection "${collection}".`)));return}try{let result=await callTool222(name,args,this._db);this._send(ok222(id,toolResult222(JSON.stringify(result,null,2))))}catch(err){this._send(ok222(id,toolError222(err.message||String(err))))}}_visibleTools(){return TOOL_DEFS222.filter((def)=>{let global=this._scopes["*"];if(global&&(global.includes(def.scope)||global.includes("admin")))return!0;for(let[,perms]of Object.entries(this._scopes))if(perms.includes(def.scope)||perms.includes("admin"))return!0;return!1})}_hasScope(collection,scope){let check=(perms)=>perms.includes("admin")||perms.includes(scope);if(collection&&this._scopes[collection])return check(this._scopes[collection]);if(this._scopes["*"])return check(this._scopes["*"]);return!1}_send(msg){this._t?.send(msg)}}var META_KEY222="migrations",_serialize222=(value)=>JSON.stringify(value,function(key,v){let raw=this[key];if(raw instanceof Date)return{__skalex_date__:raw.toISOString()};if(typeof v==="bigint")return{__skalex_bigint__:v.toString()};return v}),_deserialize222=(text)=>JSON.parse(text,(_,v)=>{if(v&&typeof v==="object"){if("__skalex_bigint__"in v)return BigInt(v.__skalex_bigint__);if("__skalex_date__"in v)return new Date(v.__skalex_date__)}return v});class Skalex222{constructor({path="./.db",format="gz",debug=!1,adapter,ai,encrypt,slowQueryLog,queryCache,memory,logger:logger$1,plugins,llmAdapter,embeddingAdapter,regexMaxLength,idGenerator,serializer,deserializer,autoSave,ttlSweepInterval,lenientLoad}={}){if(this.dataDirectory=path,this.dataFormat=format,this.debug=debug,!Skalex222._errorsAttached)Skalex222.SkalexError=SkalexError222,Skalex222.ValidationError=ValidationError222,Skalex222.UniqueConstraintError=UniqueConstraintError222,Skalex222.TransactionError=TransactionError222,Skalex222.PersistenceError=PersistenceError222,Skalex222.AdapterError=AdapterError222,Skalex222.QueryError=QueryError222,Skalex222._errorsAttached=!0;this._adapterConfig=adapter??null;let fs=adapter||new FsAdapter222({dir:path,format});if(encrypt)fs=new EncryptedAdapter222(fs,encrypt.key);if(this.fs=fs,this._registry=new CollectionRegistry222(Collection222),this.collections=this._registry.stores,this._collectionInstances=this._registry._instances,this._migrations=new MigrationEngine222,this._connectPromise=null,this.isConnected=!1,this._aiConfig=ai||null,this._encryptConfig=encrypt||null,this._pluginsConfig=Array.isArray(plugins)?plugins:null,this._memoryConfig=memory||null,this._regexMaxLength=regexMaxLength??500,this._idGenerator=idGenerator??null,this._serializer=serializer??_serialize222,this._deserializer=deserializer??_deserialize222,this._autoSave=autoSave??!1,this._txManager=new TransactionManager222,this._ttlSweepInterval=ttlSweepInterval??0,this._ttlTimer=null,this._logger=logger$1??logger222,this._embeddingAdapter=embeddingAdapter??(ai?createEmbeddingAdapter222(ai):null),this._aiAdapter=llmAdapter??(ai?createLLMAdapter222(ai):null),this._persistence=new PersistenceManager222({adapter:this.fs,serializer:this._serializer,deserializer:this._deserializer,logger:this._logger,debug:this.debug,lenientLoad:lenientLoad??!1}),this._changeLog=new ChangeLog222(this),this._queryCache=new QueryCache222(queryCache||{}),this._eventBus=new EventBus222,this._queryLog=slowQueryLog?new QueryLog222(slowQueryLog):null,this._sessionStats=new SessionStats222,this._plugins=new PluginEngine222,Array.isArray(plugins))for(let p of plugins)this._plugins.register(p)}async connect(){if(this._connectPromise)return this._connectPromise;return this._connectPromise=this._doConnect(),this._connectPromise}async _doConnect(){try{await this.loadData();let meta=this._getMeta();if(meta.queryCache)this._queryCache.fromJSON(meta.queryCache);if(this._migrations._migrations.length>0){let applied=meta.appliedVersions||[],newApplied=await this._migrations.run((version)=>this.useCollection(`_migration_${version}`),applied);this._saveMeta({appliedVersions:newApplied})}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(error2222){throw this._logger(`Error connecting to the database: ${error2222}`,"error"),error2222}}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(error2222){throw this._logger(`Error disconnecting from the database: ${error2222}`,"error"),error2222}}async _ensureConnected(){if(this.isConnected)return;return this.connect()}useCollection(collectionName){return this._registry.get(collectionName,this)}createCollection(collectionName,options={}){return this._registry.create(collectionName,options,this)}_createCollectionStore(collectionName,options={}){this._registry.createStore(collectionName,options)}async renameCollection(from,to){this._registry.rename(from,to),await this.saveData(to),await this.fs.delete(from)}async loadData(){await this._persistence.loadAll(this.collections,{parseSchema:parseSchema222,buildIndex:this._registry.buildIndex,IndexEngine:IndexEngine222});for(let name in this._collectionInstances){let store=this.collections[name];if(store&&this._collectionInstances[name]._store!==store)this._collectionInstances[name]._store=store}}async saveData(collectionName){await this._persistence.save(this.collections,collectionName)}buildIndex(data,keyField){return this._registry.buildIndex(data,keyField)}addMigration(migration){this._migrations.add(migration)}migrationStatus(){let meta=this._getMeta();return this._migrations.status(meta.appliedVersions||[])}namespace(id){if(this._adapterConfig)throw new AdapterError222("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 safeId=String(id).replace(/[^a-zA-Z0-9_-]/g,"_");if(!safeId)throw new ValidationError222("ERR_SKALEX_VALIDATION_NAMESPACE_ID","namespace: id must contain at least one alphanumeric character",{id});return new Skalex222({path:`${this.dataDirectory}/${safeId}`,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!==logger222?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!==_serialize222?this._serializer:void 0,deserializer:this._deserializer!==_deserialize222?this._deserializer:void 0,autoSave:this._autoSave||void 0,ttlSweepInterval:this._ttlSweepInterval||void 0})}use(plugin){this._plugins.register(plugin)}watch(callback){return this._eventBus.on("*",callback)}sessionStats(sessionId){if(sessionId!==void 0)return this._sessionStats.get(sessionId);return this._sessionStats.all()}get _inTransaction(){return this._txManager.active}_emitEvent(collectionName,data){if(!this._txManager.defer(()=>this._eventBus.emit(collectionName,data)))this._eventBus.emit(collectionName,data)}async _runAfterHook(hook,data){if(!this._txManager.defer(()=>this._plugins.run(hook,data)))await this._plugins.run(hook,data)}async _logChange(op,collectionName,doc,prev,session){if(!this._txManager.defer(()=>this._changeLog.log(op,collectionName,doc,prev,session)))await this._changeLog.log(op,collectionName,doc,prev,session)}async transaction(fn,opts={}){return this._txManager.run(fn,this,opts)}async seed(fixtures,{reset=!1}={}){for(let[name,docs]of Object.entries(fixtures)){if(reset&&this.collections[name])this._applySnapshot(name,{data:[],index:new Map}),delete this._collectionInstances[name];await this.useCollection(name).insertMany(docs)}await this.saveData()}dump(){return this._registry.dump()}inspect(collectionName){return this._registry.inspect(collectionName)}async import(filePath){let content=await this.fs.readRaw(filePath),docs;try{docs=JSON.parse(content)}catch{throw new PersistenceError222("ERR_SKALEX_PERSISTENCE_INVALID_JSON",`import: invalid JSON in file "${filePath}"`,{filePath})}let name=filePath.split("/").pop().replace(/\.[^.]+$/,"");return this.useCollection(name).insertMany(Array.isArray(docs)?docs:[docs],{save:!0})}async embed(text){if(!this._embeddingAdapter)throw new AdapterError222("ERR_SKALEX_ADAPTER_EMBEDDING_REQUIRED","db.embed() requires an AI adapter. Pass { ai: { provider, apiKey } } to the Skalex constructor.");return this._embeddingAdapter.embed(text)}async ask(collectionName,nlQuery,{limit=20}={}){if(!this._aiAdapter)throw new AdapterError222("ERR_SKALEX_ADAPTER_LLM_REQUIRED",'db.ask() requires a language model adapter. Configure { ai: { provider, model: "..." } }.');let col=this.useCollection(collectionName),schema=this.schema(collectionName),filter=this._queryCache.get(collectionName,schema,nlQuery);if(!filter){filter=await this._aiAdapter.generate(schema,nlQuery);let warnings=validateLLMFilter222(filter,schema);if(warnings.length)warnings.forEach((w)=>this._log(`[ask] ${w}`));this._queryCache.set(collectionName,schema,nlQuery,filter),this._saveMeta({queryCache:this._queryCache.toJSON()})}return col.find(processLLMFilter222(filter,{regexMaxLength:this._regexMaxLength}),{limit})}schema(collectionName){return this._registry.schema(collectionName)}useMemory(sessionId){return new Memory222(sessionId,this)}changelog(){return this._changeLog}async restore(collectionName,timestamp,opts={}){return this._changeLog.restore(collectionName,timestamp,opts)}stats(collectionName){return this._registry.stats(collectionName)}slowQueries(opts={}){if(!this._queryLog)return[];return this._queryLog.entries(opts)}slowQueryCount(){return this._queryLog?this._queryLog.size:0}clearSlowQueries(){this._queryLog?.clear()}mcp(opts={}){return new SkalexMCPServer222(this,opts)}_getMeta(){let metaCol=this.collections._meta;if(!metaCol)return{};return metaCol.index.get(META_KEY222)||{}}_saveMeta(data){if(!this.collections._meta)this._createCollectionStore("_meta");let col=this.collections._meta,existing=col.index.get(META_KEY222);if(existing)Object.assign(existing,data);else{let doc={_id:META_KEY222,...data};col.data.push(doc),col.index.set(META_KEY222,doc)}this._persistence.markDirty(this.collections,"_meta")}_sweepTtl(){for(let name in this.collections){let col=this.collections[name],removed=sweep222(col.data,col.index,col.fieldIndex?(doc)=>col.fieldIndex.remove(doc):null);if(removed>0)this._persistence.markDirty(this.collections,name),this._log(`TTL sweep: removed ${removed} expired docs from "${name}"`)}}_buildCollectionContext(){let db=this;return{ensureConnected:()=>db._ensureConnected(),get txManager(){return db._txManager},get plugins(){return db._plugins},get eventBus(){return db._eventBus},get sessionStats(){return db._sessionStats},get queryLog(){return db._queryLog},get logger(){return db._logger},get persistence(){return db._persistence},get collections(){return db.collections},embed:(text)=>db.embed(text),get idGenerator(){return db._idGenerator},get autoSave(){return db._autoSave},saveCollection:(name)=>db.saveData(name),snapshotCollection:(col)=>db._snapshotCollection(col),getCollection:(name)=>db.useCollection(name),emitEvent:(name,data)=>db._emitEvent(name,data),runAfterHook:(hook,data)=>db._runAfterHook(hook,data),logChange:(op,col,doc,prev,session)=>db._logChange(op,col,doc,prev,session),get fs(){return db.fs},get dataDirectory(){return db.dataDirectory}}}_log(msg){if(this.debug)this._logger(msg,"info")}_snapshotCollection(col){return{data:structuredClone(col.data)}}_applySnapshot(name,snap){let col=this.collections[name];if(!col)return;if(col.data=snap.data,col.index=this.buildIndex(snap.data,"_id"),col.fieldIndex)col.fieldIndex.buildFromData(snap.data)}}class AgentDatabase{}var registry=new Map;function registerAdapter(name,factory){registry.set(name,factory)}var nowIso=()=>new Date().toISOString();function cleanDoc(doc){if(!doc)return doc;let{_id:_ignoredId,createdAt:rawCreatedAt,updatedAt:rawUpdatedAt,_version:_ignoredVersion,_expiresAt:_ignoredExpires,...rest}=doc,out={...rest};if(out.createdAt==null&&rawCreatedAt!=null)out.createdAt=rawCreatedAt instanceof Date?rawCreatedAt.toISOString():String(rawCreatedAt);if(out.updatedAt==null&&rawUpdatedAt!=null)out.updatedAt=rawUpdatedAt instanceof Date?rawUpdatedAt.toISOString():String(rawUpdatedAt);return out}class SkalexAgentDatabase extends AgentDatabase{dataDir;encryptionKey;lockPath;lockFd=null;db;tasks;config;gitRepos;bookmarks;notifications;pluginState;constructor(opts){super();this.dataDir=opts.dataDir,this.encryptionKey=opts.encryptionKey,this.lockPath=join(opts.dataDir,".agent-db.lock")}static async create(opts){if(!existsSync(opts.dataDir))mkdirSync(opts.dataDir,{recursive:!0});let instance=new SkalexAgentDatabase(opts);instance.acquireLock();try{await instance.init()}catch(err){throw instance.releaseLock(),err}return instance}acquireLock(){try{this.lockFd=openSync(this.lockPath,"wx",384),writeFileSync(this.lockFd,JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()}));return}catch(err){if(err.code!=="EEXIST")throw err}let stale=!1;try{let raw=JSON.parse(readFileSync(this.lockPath,"utf8"));if(!raw.pid)stale=!0;else try{process.kill(raw.pid,0)}catch{stale=!0}}catch{stale=!0}if(stale){try{unlinkSync(this.lockPath)}catch{}this.acquireLock();return}throw Error(`Agent database is already open by another process (${this.lockPath})`)}releaseLock(){if(this.lockFd!==null){try{closeSync(this.lockFd)}catch{}this.lockFd=null}try{unlinkSync(this.lockPath)}catch{}}async init(){this.db=new Skalex222({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(task){let doc={id:task.id,type:task.type,status:task.status,payload:task.payload};if(task.result!=null)doc.result=task.result;if(task.error!=null)doc.error=task.error;if(task.calendarTaskId!=null)doc.calendarTaskId=task.calendarTaskId;if(task.exitCode!=null)doc.exitCode=task.exitCode;if(task.timeout!=null)doc.timeout=task.timeout;let inserted=await this.tasks.insertOne(doc);return cleanDoc(inserted)}async getTask(id){let doc=await this.tasks.findOne({id});return doc?cleanDoc(doc):void 0}async getAllTasks(){return(await this.tasks.find(void 0,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc(d))}async getPendingTasks(){return(await this.tasks.find({status:"pending"},{sort:{createdAt:1}})).docs.map((d)=>cleanDoc(d))}async updateTask(id,updates){let patch={};for(let[k,v]of Object.entries(updates)){if(k==="id"||k==="createdAt"||k==="updatedAt")continue;patch[k]=v??null}if(Object.keys(patch).length===0)return;await this.tasks.updateOne({id},patch)}async cancelTask(id){let existing=await this.tasks.findOne({id});if(!existing||existing.status!=="pending"&&existing.status!=="running")return!1;return await this.tasks.updateOne({id},{status:"failed",error:"Cancelled"}),!0}async getConfig(key){return(await this.config.findOne({key}))?.value}async setConfig(key,value){await this.config.upsert({key},{key,value})}async deleteConfig(key){return await this.config.deleteOne({key})!==null}async getAllConfig(){let res=await this.config.find(),out={};for(let doc of res.docs)out[doc.key]=doc.value;return out}async bulkSetConfig(entries){for(let[key,value]of Object.entries(entries))await this.config.upsert({key},{key,value})}async getConfigStatus(){let res=await this.config.find(),latest=null;for(let doc of res.docs){let raw=doc.updatedAt,iso=raw instanceof Date?raw.toISOString():typeof raw==="string"?raw:null;if(iso&&(!latest||iso>latest))latest=iso}return{totalKeys:res.docs.length,lastUpdated:latest}}async createGitRepository(repo){let doc={id:repo.id,path:repo.path,name:repo.name,isSubmodule:Boolean(repo.isSubmodule),lastScanned:nowIso()};if(repo.parentPath!=null)doc.parentPath=repo.parentPath;if(repo.projectType!=null)doc.projectType=repo.projectType;if(repo.vitePort!=null)doc.vitePort=repo.vitePort;let inserted=await this.gitRepos.insertOne(doc);return cleanDoc(inserted)}async getGitRepository(id){let doc=await this.gitRepos.findOne({id});return doc?cleanDoc(doc):void 0}async getGitRepositoryByPath(path){let doc=await this.gitRepos.findOne({path});return doc?cleanDoc(doc):void 0}async getAllGitRepositories(){return(await this.gitRepos.find(void 0,{sort:{path:1}})).docs.map((d)=>cleanDoc(d))}async updateGitRepository(id,updates){let patch={lastScanned:nowIso()};for(let[k,v]of Object.entries(updates)){if(k==="id"||k==="createdAt"||k==="updatedAt")continue;if(k==="isSubmodule"){patch[k]=Boolean(v);continue}patch[k]=v??null}await this.gitRepos.updateOne({id},patch)}async deleteGitRepository(id){return await this.gitRepos.deleteOne({id})!==null}async fixGitHierarchy(){let repos=await this.getAllGitRepositories(),fixed=0;for(let repo of repos){if(repo.isSubmodule)continue;let parent=repos.find((r)=>r.id!==repo.id&&repo.path.startsWith(`${r.path}/`)&&!r.isSubmodule);if(parent&&repo.parentPath!==parent.path)await this.updateGitRepository(repo.id,{parentPath:parent.path}),fixed++}return{fixed}}async createBookmarkedCommand(cmd){let doc={id:cmd.id,command:cmd.command};if(cmd.projectId!=null)doc.projectId=cmd.projectId;if(cmd.description!=null)doc.description=cmd.description;if(cmd.category!=null)doc.category=cmd.category;let inserted=await this.bookmarks.insertOne(doc);return cleanDoc(inserted)}async getBookmarkedCommand(id){let doc=await this.bookmarks.findOne({id});return doc?cleanDoc(doc):void 0}async getAllBookmarkedCommands(){return(await this.bookmarks.find(void 0,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc(d))}async getBookmarkedCommandsByProject(projectId){let filter=projectId===null?{projectId:{$fn:(v)=>v==null}}:{projectId};return(await this.bookmarks.find(filter,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc(d))}async getBookmarkedCommandsByCategory(category){return(await this.bookmarks.find({category},{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc(d))}async updateBookmarkedCommand(id,updates){let patch={};for(let[k,v]of Object.entries(updates)){if(k==="id"||k==="createdAt"||k==="updatedAt")continue;patch[k]=v??null}if(Object.keys(patch).length===0)return;await this.bookmarks.updateOne({id},patch)}async deleteBookmarkedCommand(id){return await this.bookmarks.deleteOne({id})!==null}async executeBookmarkedCommand(id){return this.getBookmarkedCommand(id)}async createNotification(notification){let doc={id:notification.id,type:notification.type,title:notification.title,message:notification.message,status:notification.status};if(notification.sessionName!=null)doc.sessionName=notification.sessionName;if(notification.projectId!=null)doc.projectId=notification.projectId;let inserted=await this.notifications.insertOne(doc);return cleanDoc(inserted)}async getNotification(id){let doc=await this.notifications.findOne({id});return doc?cleanDoc(doc):void 0}async getAllNotifications(){return(await this.notifications.find(void 0,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc(d))}async getNotificationsByProject(projectId){let filter=projectId===null?{projectId:{$fn:(v)=>v==null}}:{projectId};return(await this.notifications.find(filter,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc(d))}async getGlobalNotifications(){return this.getNotificationsByProject(null)}async getUnreadNotifications(){return(await this.notifications.find({status:"unread"},{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc(d))}async updateNotificationStatus(id,status){await this.notifications.updateOne({id},{status})}async markAllNotificationsRead(){return(await this.notifications.updateMany({status:"unread"},{status:"read"})).length}async deleteNotification(id){return await this.notifications.deleteOne({id})!==null}async clearOldNotifications(olderThanDays=30){let cutoff=new Date(Date.now()-olderThanDays*24*60*60*1000);return(await this.notifications.deleteMany({createdAt:{$fn:(v)=>v instanceof Date&&v<cutoff}})).length}async getPluginState(pluginName,key){return(await this.pluginState.findOne({$and:[{pluginName},{key}]}))?.value}async setPluginState(pluginName,key,value){await this.pluginState.upsert({$and:[{pluginName},{key}]},{pluginName,key,value})}async deletePluginState(pluginName,key){return await this.pluginState.deleteOne({$and:[{pluginName},{key}]})!==null}async getAllPluginState(pluginName){return(await this.pluginState.find({pluginName},{sort:{key:1}})).docs.map((doc)=>{let raw=doc.updatedAt,updatedAt=raw instanceof Date?raw.toISOString():typeof raw==="string"?raw:void 0;return{key:doc.key,value:doc.value,updatedAt}})}async deleteAllPluginState(pluginName){return(await this.pluginState.deleteMany({pluginName})).length}}var createSkalexAgentDatabase=(opts)=>SkalexAgentDatabase.create(opts);registerAdapter("skalex",createSkalexAgentDatabase);var registry2=new Map;function registerAdapter2(name,factory){registry2.set(name,factory)}class AgentDatabase2{}registerAdapter2("skalex",createSkalexAgentDatabase);var nowIso2=()=>new Date().toISOString();function cleanDoc2(doc){if(!doc)return doc;let{_id:_ignoredId,createdAt:rawCreatedAt,updatedAt:rawUpdatedAt,_version:_ignoredVersion,_expiresAt:_ignoredExpires,...rest}=doc,out={...rest};if(out.createdAt==null&&rawCreatedAt!=null)out.createdAt=rawCreatedAt instanceof Date?rawCreatedAt.toISOString():String(rawCreatedAt);if(out.updatedAt==null&&rawUpdatedAt!=null)out.updatedAt=rawUpdatedAt instanceof Date?rawUpdatedAt.toISOString():String(rawUpdatedAt);return out}class SkalexAgentDatabase2 extends AgentDatabase2{dataDir;encryptionKey;lockPath;lockFd=null;db;tasks;config;gitRepos;bookmarks;notifications;pluginState;constructor(opts){super();this.dataDir=opts.dataDir,this.encryptionKey=opts.encryptionKey,this.lockPath=join2(opts.dataDir,".agent-db.lock")}static async create(opts){if(!existsSync2(opts.dataDir))mkdirSync2(opts.dataDir,{recursive:!0});let instance=new SkalexAgentDatabase2(opts);instance.acquireLock();try{await instance.init()}catch(err){throw instance.releaseLock(),err}return instance}acquireLock(){try{this.lockFd=openSync2(this.lockPath,"wx",384),writeFileSync2(this.lockFd,JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()}));return}catch(err){if(err.code!=="EEXIST")throw err}let stale=!1;try{let raw=JSON.parse(readFileSync2(this.lockPath,"utf8"));if(!raw.pid)stale=!0;else try{process.kill(raw.pid,0)}catch{stale=!0}}catch{stale=!0}if(stale){try{unlinkSync2(this.lockPath)}catch{}this.acquireLock();return}throw Error(`Agent database is already open by another process (${this.lockPath})`)}releaseLock(){if(this.lockFd!==null){try{closeSync2(this.lockFd)}catch{}this.lockFd=null}try{unlinkSync2(this.lockPath)}catch{}}async init(){this.db=new Skalex22({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(task){let doc={id:task.id,type:task.type,status:task.status,payload:task.payload};if(task.result!=null)doc.result=task.result;if(task.error!=null)doc.error=task.error;if(task.calendarTaskId!=null)doc.calendarTaskId=task.calendarTaskId;if(task.exitCode!=null)doc.exitCode=task.exitCode;if(task.timeout!=null)doc.timeout=task.timeout;let inserted=await this.tasks.insertOne(doc);return cleanDoc2(inserted)}async getTask(id){let doc=await this.tasks.findOne({id});return doc?cleanDoc2(doc):void 0}async getAllTasks(){return(await this.tasks.find(void 0,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc2(d))}async getPendingTasks(){return(await this.tasks.find({status:"pending"},{sort:{createdAt:1}})).docs.map((d)=>cleanDoc2(d))}async updateTask(id,updates){let patch={};for(let[k,v]of Object.entries(updates)){if(k==="id"||k==="createdAt"||k==="updatedAt")continue;patch[k]=v??null}if(Object.keys(patch).length===0)return;await this.tasks.updateOne({id},patch)}async cancelTask(id){let existing=await this.tasks.findOne({id});if(!existing||existing.status!=="pending"&&existing.status!=="running")return!1;return await this.tasks.updateOne({id},{status:"failed",error:"Cancelled"}),!0}async getConfig(key){return(await this.config.findOne({key}))?.value}async setConfig(key,value){await this.config.upsert({key},{key,value})}async deleteConfig(key){return await this.config.deleteOne({key})!==null}async getAllConfig(){let res=await this.config.find(),out={};for(let doc of res.docs)out[doc.key]=doc.value;return out}async bulkSetConfig(entries){for(let[key,value]of Object.entries(entries))await this.config.upsert({key},{key,value})}async getConfigStatus(){let res=await this.config.find(),latest=null;for(let doc of res.docs){let raw=doc.updatedAt,iso=raw instanceof Date?raw.toISOString():typeof raw==="string"?raw:null;if(iso&&(!latest||iso>latest))latest=iso}return{totalKeys:res.docs.length,lastUpdated:latest}}async createGitRepository(repo){let doc={id:repo.id,path:repo.path,name:repo.name,isSubmodule:Boolean(repo.isSubmodule),lastScanned:nowIso2()};if(repo.parentPath!=null)doc.parentPath=repo.parentPath;if(repo.projectType!=null)doc.projectType=repo.projectType;if(repo.vitePort!=null)doc.vitePort=repo.vitePort;let inserted=await this.gitRepos.insertOne(doc);return cleanDoc2(inserted)}async getGitRepository(id){let doc=await this.gitRepos.findOne({id});return doc?cleanDoc2(doc):void 0}async getGitRepositoryByPath(path){let doc=await this.gitRepos.findOne({path});return doc?cleanDoc2(doc):void 0}async getAllGitRepositories(){return(await this.gitRepos.find(void 0,{sort:{path:1}})).docs.map((d)=>cleanDoc2(d))}async updateGitRepository(id,updates){let patch={lastScanned:nowIso2()};for(let[k,v]of Object.entries(updates)){if(k==="id"||k==="createdAt"||k==="updatedAt")continue;if(k==="isSubmodule"){patch[k]=Boolean(v);continue}patch[k]=v??null}await this.gitRepos.updateOne({id},patch)}async deleteGitRepository(id){return await this.gitRepos.deleteOne({id})!==null}async fixGitHierarchy(){let repos=await this.getAllGitRepositories(),fixed=0;for(let repo of repos){if(repo.isSubmodule)continue;let parent=repos.find((r)=>r.id!==repo.id&&repo.path.startsWith(`${r.path}/`)&&!r.isSubmodule);if(parent&&repo.parentPath!==parent.path)await this.updateGitRepository(repo.id,{parentPath:parent.path}),fixed++}return{fixed}}async createBookmarkedCommand(cmd){let doc={id:cmd.id,command:cmd.command};if(cmd.projectId!=null)doc.projectId=cmd.projectId;if(cmd.description!=null)doc.description=cmd.description;if(cmd.category!=null)doc.category=cmd.category;let inserted=await this.bookmarks.insertOne(doc);return cleanDoc2(inserted)}async getBookmarkedCommand(id){let doc=await this.bookmarks.findOne({id});return doc?cleanDoc2(doc):void 0}async getAllBookmarkedCommands(){return(await this.bookmarks.find(void 0,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc2(d))}async getBookmarkedCommandsByProject(projectId){let filter=projectId===null?{projectId:{$fn:(v)=>v==null}}:{projectId};return(await this.bookmarks.find(filter,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc2(d))}async getBookmarkedCommandsByCategory(category){return(await this.bookmarks.find({category},{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc2(d))}async updateBookmarkedCommand(id,updates){let patch={};for(let[k,v]of Object.entries(updates)){if(k==="id"||k==="createdAt"||k==="updatedAt")continue;patch[k]=v??null}if(Object.keys(patch).length===0)return;await this.bookmarks.updateOne({id},patch)}async deleteBookmarkedCommand(id){return await this.bookmarks.deleteOne({id})!==null}async executeBookmarkedCommand(id){return this.getBookmarkedCommand(id)}async createNotification(notification){let doc={id:notification.id,type:notification.type,title:notification.title,message:notification.message,status:notification.status};if(notification.sessionName!=null)doc.sessionName=notification.sessionName;if(notification.projectId!=null)doc.projectId=notification.projectId;let inserted=await this.notifications.insertOne(doc);return cleanDoc2(inserted)}async getNotification(id){let doc=await this.notifications.findOne({id});return doc?cleanDoc2(doc):void 0}async getAllNotifications(){return(await this.notifications.find(void 0,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc2(d))}async getNotificationsByProject(projectId){let filter=projectId===null?{projectId:{$fn:(v)=>v==null}}:{projectId};return(await this.notifications.find(filter,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc2(d))}async getGlobalNotifications(){return this.getNotificationsByProject(null)}async getUnreadNotifications(){return(await this.notifications.find({status:"unread"},{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc2(d))}async updateNotificationStatus(id,status){await this.notifications.updateOne({id},{status})}async markAllNotificationsRead(){return(await this.notifications.updateMany({status:"unread"},{status:"read"})).length}async deleteNotification(id){return await this.notifications.deleteOne({id})!==null}async clearOldNotifications(olderThanDays=30){let cutoff=new Date(Date.now()-olderThanDays*24*60*60*1000);return(await this.notifications.deleteMany({createdAt:{$fn:(v)=>v instanceof Date&&v<cutoff}})).length}async getPluginState(pluginName,key){return(await this.pluginState.findOne({$and:[{pluginName},{key}]}))?.value}async setPluginState(pluginName,key,value){await this.pluginState.upsert({$and:[{pluginName},{key}]},{pluginName,key,value})}async deletePluginState(pluginName,key){return await this.pluginState.deleteOne({$and:[{pluginName},{key}]})!==null}async getAllPluginState(pluginName){return(await this.pluginState.find({pluginName},{sort:{key:1}})).docs.map((doc)=>{let raw=doc.updatedAt,updatedAt=raw instanceof Date?raw.toISOString():typeof raw==="string"?raw:void 0;return{key:doc.key,value:doc.value,updatedAt}})}async deleteAllPluginState(pluginName){return(await this.pluginState.deleteMany({pluginName})).length}}var createSkalexAgentDatabase2=(opts)=>SkalexAgentDatabase2.create(opts);registerAdapter2("skalex",createSkalexAgentDatabase2);var registry3=new Map;function registerAdapter3(name,factory){registry3.set(name,factory)}class AgentDatabase3{}registerAdapter3("skalex",createSkalexAgentDatabase2);var nowIso3=()=>new Date().toISOString();function cleanDoc3(doc){if(!doc)return doc;let{_id:_ignoredId,createdAt:rawCreatedAt,updatedAt:rawUpdatedAt,_version:_ignoredVersion,_expiresAt:_ignoredExpires,...rest}=doc,out={...rest};if(out.createdAt==null&&rawCreatedAt!=null)out.createdAt=rawCreatedAt instanceof Date?rawCreatedAt.toISOString():String(rawCreatedAt);if(out.updatedAt==null&&rawUpdatedAt!=null)out.updatedAt=rawUpdatedAt instanceof Date?rawUpdatedAt.toISOString():String(rawUpdatedAt);return out}class SkalexAgentDatabase3 extends AgentDatabase3{dataDir;encryptionKey;lockPath;lockFd=null;db;tasks;config;gitRepos;bookmarks;notifications;pluginState;constructor(opts){super();this.dataDir=opts.dataDir,this.encryptionKey=opts.encryptionKey,this.lockPath=join3(opts.dataDir,".agent-db.lock")}static async create(opts){if(!existsSync3(opts.dataDir))mkdirSync3(opts.dataDir,{recursive:!0});let instance=new SkalexAgentDatabase3(opts);instance.acquireLock();try{await instance.init()}catch(err){throw instance.releaseLock(),err}return instance}acquireLock(){try{this.lockFd=openSync3(this.lockPath,"wx",384),writeFileSync3(this.lockFd,JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()}));return}catch(err){if(err.code!=="EEXIST")throw err}let stale=!1;try{let raw=JSON.parse(readFileSync3(this.lockPath,"utf8"));if(!raw.pid)stale=!0;else try{process.kill(raw.pid,0)}catch{stale=!0}}catch{stale=!0}if(stale){try{unlinkSync3(this.lockPath)}catch{}this.acquireLock();return}throw Error(`Agent database is already open by another process (${this.lockPath})`)}releaseLock(){if(this.lockFd!==null){try{closeSync3(this.lockFd)}catch{}this.lockFd=null}try{unlinkSync3(this.lockPath)}catch{}}async init(){this.db=new Skalex2({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(task){let doc={id:task.id,type:task.type,status:task.status,payload:task.payload};if(task.result!=null)doc.result=task.result;if(task.error!=null)doc.error=task.error;if(task.calendarTaskId!=null)doc.calendarTaskId=task.calendarTaskId;if(task.exitCode!=null)doc.exitCode=task.exitCode;if(task.timeout!=null)doc.timeout=task.timeout;let inserted=await this.tasks.insertOne(doc);return cleanDoc3(inserted)}async getTask(id){let doc=await this.tasks.findOne({id});return doc?cleanDoc3(doc):void 0}async getAllTasks(){return(await this.tasks.find(void 0,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc3(d))}async getPendingTasks(){return(await this.tasks.find({status:"pending"},{sort:{createdAt:1}})).docs.map((d)=>cleanDoc3(d))}async updateTask(id,updates){let patch={};for(let[k,v]of Object.entries(updates)){if(k==="id"||k==="createdAt"||k==="updatedAt")continue;patch[k]=v??null}if(Object.keys(patch).length===0)return;await this.tasks.updateOne({id},patch)}async cancelTask(id){let existing=await this.tasks.findOne({id});if(!existing||existing.status!=="pending"&&existing.status!=="running")return!1;return await this.tasks.updateOne({id},{status:"failed",error:"Cancelled"}),!0}async getConfig(key){return(await this.config.findOne({key}))?.value}async setConfig(key,value){await this.config.upsert({key},{key,value})}async deleteConfig(key){return await this.config.deleteOne({key})!==null}async getAllConfig(){let res=await this.config.find(),out={};for(let doc of res.docs)out[doc.key]=doc.value;return out}async bulkSetConfig(entries){for(let[key,value]of Object.entries(entries))await this.config.upsert({key},{key,value})}async getConfigStatus(){let res=await this.config.find(),latest=null;for(let doc of res.docs){let raw=doc.updatedAt,iso=raw instanceof Date?raw.toISOString():typeof raw==="string"?raw:null;if(iso&&(!latest||iso>latest))latest=iso}return{totalKeys:res.docs.length,lastUpdated:latest}}async createGitRepository(repo){let doc={id:repo.id,path:repo.path,name:repo.name,isSubmodule:Boolean(repo.isSubmodule),lastScanned:nowIso3()};if(repo.parentPath!=null)doc.parentPath=repo.parentPath;if(repo.projectType!=null)doc.projectType=repo.projectType;if(repo.vitePort!=null)doc.vitePort=repo.vitePort;let inserted=await this.gitRepos.insertOne(doc);return cleanDoc3(inserted)}async getGitRepository(id){let doc=await this.gitRepos.findOne({id});return doc?cleanDoc3(doc):void 0}async getGitRepositoryByPath(path){let doc=await this.gitRepos.findOne({path});return doc?cleanDoc3(doc):void 0}async getAllGitRepositories(){return(await this.gitRepos.find(void 0,{sort:{path:1}})).docs.map((d)=>cleanDoc3(d))}async updateGitRepository(id,updates){let patch={lastScanned:nowIso3()};for(let[k,v]of Object.entries(updates)){if(k==="id"||k==="createdAt"||k==="updatedAt")continue;if(k==="isSubmodule"){patch[k]=Boolean(v);continue}patch[k]=v??null}await this.gitRepos.updateOne({id},patch)}async deleteGitRepository(id){return await this.gitRepos.deleteOne({id})!==null}async fixGitHierarchy(){let repos=await this.getAllGitRepositories(),fixed=0;for(let repo of repos){if(repo.isSubmodule)continue;let parent=repos.find((r)=>r.id!==repo.id&&repo.path.startsWith(`${r.path}/`)&&!r.isSubmodule);if(parent&&repo.parentPath!==parent.path)await this.updateGitRepository(repo.id,{parentPath:parent.path}),fixed++}return{fixed}}async createBookmarkedCommand(cmd){let doc={id:cmd.id,command:cmd.command};if(cmd.projectId!=null)doc.projectId=cmd.projectId;if(cmd.description!=null)doc.description=cmd.description;if(cmd.category!=null)doc.category=cmd.category;let inserted=await this.bookmarks.insertOne(doc);return cleanDoc3(inserted)}async getBookmarkedCommand(id){let doc=await this.bookmarks.findOne({id});return doc?cleanDoc3(doc):void 0}async getAllBookmarkedCommands(){return(await this.bookmarks.find(void 0,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc3(d))}async getBookmarkedCommandsByProject(projectId){let filter=projectId===null?{projectId:{$fn:(v)=>v==null}}:{projectId};return(await this.bookmarks.find(filter,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc3(d))}async getBookmarkedCommandsByCategory(category){return(await this.bookmarks.find({category},{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc3(d))}async updateBookmarkedCommand(id,updates){let patch={};for(let[k,v]of Object.entries(updates)){if(k==="id"||k==="createdAt"||k==="updatedAt")continue;patch[k]=v??null}if(Object.keys(patch).length===0)return;await this.bookmarks.updateOne({id},patch)}async deleteBookmarkedCommand(id){return await this.bookmarks.deleteOne({id})!==null}async executeBookmarkedCommand(id){return this.getBookmarkedCommand(id)}async createNotification(notification){let doc={id:notification.id,type:notification.type,title:notification.title,message:notification.message,status:notification.status};if(notification.sessionName!=null)doc.sessionName=notification.sessionName;if(notification.projectId!=null)doc.projectId=notification.projectId;let inserted=await this.notifications.insertOne(doc);return cleanDoc3(inserted)}async getNotification(id){let doc=await this.notifications.findOne({id});return doc?cleanDoc3(doc):void 0}async getAllNotifications(){return(await this.notifications.find(void 0,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc3(d))}async getNotificationsByProject(projectId){let filter=projectId===null?{projectId:{$fn:(v)=>v==null}}:{projectId};return(await this.notifications.find(filter,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc3(d))}async getGlobalNotifications(){return this.getNotificationsByProject(null)}async getUnreadNotifications(){return(await this.notifications.find({status:"unread"},{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc3(d))}async updateNotificationStatus(id,status){await this.notifications.updateOne({id},{status})}async markAllNotificationsRead(){return(await this.notifications.updateMany({status:"unread"},{status:"read"})).length}async deleteNotification(id){return await this.notifications.deleteOne({id})!==null}async clearOldNotifications(olderThanDays=30){let cutoff=new Date(Date.now()-olderThanDays*24*60*60*1000);return(await this.notifications.deleteMany({createdAt:{$fn:(v)=>v instanceof Date&&v<cutoff}})).length}async getPluginState(pluginName,key){return(await this.pluginState.findOne({$and:[{pluginName},{key}]}))?.value}async setPluginState(pluginName,key,value){await this.pluginState.upsert({$and:[{pluginName},{key}]},{pluginName,key,value})}async deletePluginState(pluginName,key){return await this.pluginState.deleteOne({$and:[{pluginName},{key}]})!==null}async getAllPluginState(pluginName){return(await this.pluginState.find({pluginName},{sort:{key:1}})).docs.map((doc)=>{let raw=doc.updatedAt,updatedAt=raw instanceof Date?raw.toISOString():typeof raw==="string"?raw:void 0;return{key:doc.key,value:doc.value,updatedAt}})}async deleteAllPluginState(pluginName){return(await this.pluginState.deleteMany({pluginName})).length}}var createSkalexAgentDatabase3=(opts)=>SkalexAgentDatabase3.create(opts);registerAdapter3("skalex",createSkalexAgentDatabase3);var registry4=new Map;function registerAdapter4(name,factory){registry4.set(name,factory)}class AgentDatabase4{}registerAdapter4("skalex",createSkalexAgentDatabase3);var nowIso4=()=>new Date().toISOString();function cleanDoc4(doc){if(!doc)return doc;let{_id:_ignoredId,createdAt:rawCreatedAt,updatedAt:rawUpdatedAt,_version:_ignoredVersion,_expiresAt:_ignoredExpires,...rest}=doc,out={...rest};if(out.createdAt==null&&rawCreatedAt!=null)out.createdAt=rawCreatedAt instanceof Date?rawCreatedAt.toISOString():String(rawCreatedAt);if(out.updatedAt==null&&rawUpdatedAt!=null)out.updatedAt=rawUpdatedAt instanceof Date?rawUpdatedAt.toISOString():String(rawUpdatedAt);return out}class SkalexAgentDatabase4 extends AgentDatabase4{dataDir;encryptionKey;lockPath;lockFd=null;db;tasks;config;gitRepos;bookmarks;notifications;pluginState;constructor(opts){super();this.dataDir=opts.dataDir,this.encryptionKey=opts.encryptionKey,this.lockPath=join4(opts.dataDir,".agent-db.lock")}static async create(opts){if(!existsSync4(opts.dataDir))mkdirSync4(opts.dataDir,{recursive:!0});let instance=new SkalexAgentDatabase4(opts);instance.acquireLock();try{await instance.init()}catch(err){throw instance.releaseLock(),err}return instance}acquireLock(){try{this.lockFd=openSync4(this.lockPath,"wx",384),writeFileSync4(this.lockFd,JSON.stringify({pid:process.pid,createdAt:new Date().toISOString()}));return}catch(err){if(err.code!=="EEXIST")throw err}let stale=!1;try{let raw=JSON.parse(readFileSync4(this.lockPath,"utf8"));if(!raw.pid)stale=!0;else try{process.kill(raw.pid,0)}catch{stale=!0}}catch{stale=!0}if(stale){try{unlinkSync4(this.lockPath)}catch{}this.acquireLock();return}throw Error(`Agent database is already open by another process (${this.lockPath})`)}releaseLock(){if(this.lockFd!==null){try{closeSync4(this.lockFd)}catch{}this.lockFd=null}try{unlinkSync4(this.lockPath)}catch{}}async init(){this.db=new Skalex({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(task){let doc={id:task.id,type:task.type,status:task.status,payload:task.payload};if(task.result!=null)doc.result=task.result;if(task.error!=null)doc.error=task.error;if(task.calendarTaskId!=null)doc.calendarTaskId=task.calendarTaskId;if(task.exitCode!=null)doc.exitCode=task.exitCode;if(task.timeout!=null)doc.timeout=task.timeout;let inserted=await this.tasks.insertOne(doc);return cleanDoc4(inserted)}async getTask(id){let doc=await this.tasks.findOne({id});return doc?cleanDoc4(doc):void 0}async getAllTasks(){return(await this.tasks.find(void 0,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc4(d))}async getPendingTasks(){return(await this.tasks.find({status:"pending"},{sort:{createdAt:1}})).docs.map((d)=>cleanDoc4(d))}async updateTask(id,updates){let patch={};for(let[k,v]of Object.entries(updates)){if(k==="id"||k==="createdAt"||k==="updatedAt")continue;patch[k]=v??null}if(Object.keys(patch).length===0)return;await this.tasks.updateOne({id},patch)}async cancelTask(id){let existing=await this.tasks.findOne({id});if(!existing||existing.status!=="pending"&&existing.status!=="running")return!1;return await this.tasks.updateOne({id},{status:"failed",error:"Cancelled"}),!0}async getConfig(key){return(await this.config.findOne({key}))?.value}async setConfig(key,value){await this.config.upsert({key},{key,value})}async deleteConfig(key){return await this.config.deleteOne({key})!==null}async getAllConfig(){let res=await this.config.find(),out={};for(let doc of res.docs)out[doc.key]=doc.value;return out}async bulkSetConfig(entries){for(let[key,value]of Object.entries(entries))await this.config.upsert({key},{key,value})}async getConfigStatus(){let res=await this.config.find(),latest=null;for(let doc of res.docs){let raw=doc.updatedAt,iso=raw instanceof Date?raw.toISOString():typeof raw==="string"?raw:null;if(iso&&(!latest||iso>latest))latest=iso}return{totalKeys:res.docs.length,lastUpdated:latest}}async createGitRepository(repo){let doc={id:repo.id,path:repo.path,name:repo.name,isSubmodule:Boolean(repo.isSubmodule),lastScanned:nowIso4()};if(repo.parentPath!=null)doc.parentPath=repo.parentPath;if(repo.projectType!=null)doc.projectType=repo.projectType;if(repo.vitePort!=null)doc.vitePort=repo.vitePort;let inserted=await this.gitRepos.insertOne(doc);return cleanDoc4(inserted)}async getGitRepository(id){let doc=await this.gitRepos.findOne({id});return doc?cleanDoc4(doc):void 0}async getGitRepositoryByPath(path){let doc=await this.gitRepos.findOne({path});return doc?cleanDoc4(doc):void 0}async getAllGitRepositories(){return(await this.gitRepos.find(void 0,{sort:{path:1}})).docs.map((d)=>cleanDoc4(d))}async updateGitRepository(id,updates){let patch={lastScanned:nowIso4()};for(let[k,v]of Object.entries(updates)){if(k==="id"||k==="createdAt"||k==="updatedAt")continue;if(k==="isSubmodule"){patch[k]=Boolean(v);continue}patch[k]=v??null}await this.gitRepos.updateOne({id},patch)}async deleteGitRepository(id){return await this.gitRepos.deleteOne({id})!==null}async fixGitHierarchy(){let repos=await this.getAllGitRepositories(),fixed=0;for(let repo of repos){if(repo.isSubmodule)continue;let parent=repos.find((r)=>r.id!==repo.id&&repo.path.startsWith(`${r.path}/`)&&!r.isSubmodule);if(parent&&repo.parentPath!==parent.path)await this.updateGitRepository(repo.id,{parentPath:parent.path}),fixed++}return{fixed}}async createBookmarkedCommand(cmd){let doc={id:cmd.id,command:cmd.command};if(cmd.projectId!=null)doc.projectId=cmd.projectId;if(cmd.description!=null)doc.description=cmd.description;if(cmd.category!=null)doc.category=cmd.category;let inserted=await this.bookmarks.insertOne(doc);return cleanDoc4(inserted)}async getBookmarkedCommand(id){let doc=await this.bookmarks.findOne({id});return doc?cleanDoc4(doc):void 0}async getAllBookmarkedCommands(){return(await this.bookmarks.find(void 0,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc4(d))}async getBookmarkedCommandsByProject(projectId){let filter=projectId===null?{projectId:{$fn:(v)=>v==null}}:{projectId};return(await this.bookmarks.find(filter,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc4(d))}async getBookmarkedCommandsByCategory(category){return(await this.bookmarks.find({category},{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc4(d))}async updateBookmarkedCommand(id,updates){let patch={};for(let[k,v]of Object.entries(updates)){if(k==="id"||k==="createdAt"||k==="updatedAt")continue;patch[k]=v??null}if(Object.keys(patch).length===0)return;await this.bookmarks.updateOne({id},patch)}async deleteBookmarkedCommand(id){return await this.bookmarks.deleteOne({id})!==null}async executeBookmarkedCommand(id){return this.getBookmarkedCommand(id)}async createNotification(notification){let doc={id:notification.id,type:notification.type,title:notification.title,message:notification.message,status:notification.status};if(notification.sessionName!=null)doc.sessionName=notification.sessionName;if(notification.projectId!=null)doc.projectId=notification.projectId;let inserted=await this.notifications.insertOne(doc);return cleanDoc4(inserted)}async getNotification(id){let doc=await this.notifications.findOne({id});return doc?cleanDoc4(doc):void 0}async getAllNotifications(){return(await this.notifications.find(void 0,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc4(d))}async getNotificationsByProject(projectId){let filter=projectId===null?{projectId:{$fn:(v)=>v==null}}:{projectId};return(await this.notifications.find(filter,{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc4(d))}async getGlobalNotifications(){return this.getNotificationsByProject(null)}async getUnreadNotifications(){return(await this.notifications.find({status:"unread"},{sort:{createdAt:-1}})).docs.map((d)=>cleanDoc4(d))}async updateNotificationStatus(id,status){await this.notifications.updateOne({id},{status})}async markAllNotificationsRead(){return(await this.notifications.updateMany({status:"unread"},{status:"read"})).length}async deleteNotification(id){return await this.notifications.deleteOne({id})!==null}async clearOldNotifications(olderThanDays=30){let cutoff=new Date(Date.now()-olderThanDays*24*60*60*1000);return(await this.notifications.deleteMany({createdAt:{$fn:(v)=>v instanceof Date&&v<cutoff}})).length}async getPluginState(pluginName,key){return(await this.pluginState.findOne({$and:[{pluginName},{key}]}))?.value}async setPluginState(pluginName,key,value){await this.pluginState.upsert({$and:[{pluginName},{key}]},{pluginName,key,value})}async deletePluginState(pluginName,key){return await this.pluginState.deleteOne({$and:[{pluginName},{key}]})!==null}async getAllPluginState(pluginName){return(await this.pluginState.find({pluginName},{sort:{key:1}})).docs.map((doc)=>{let raw=doc.updatedAt,updatedAt=raw instanceof Date?raw.toISOString():typeof raw==="string"?raw:void 0;return{key:doc.key,value:doc.value,updatedAt}})}async deleteAllPluginState(pluginName){return(await this.pluginState.deleteMany({pluginName})).length}}var createSkalexAgentDatabase4=(opts)=>SkalexAgentDatabase4.create(opts);registerAdapter4("skalex",createSkalexAgentDatabase4);var registry5=new Map;function registerAdapter5(name,factory){registry5.set(name,factory)}function getAdapter(name){return registry5.get(name)}function listAdapters(){return Array.from(registry5.keys())}class AgentDatabase5{}async function resolveFactory(options){if(options.adapterFactory)return options.adapterFactory;let name=options.adapterName??process.env.VIBE_STORAGE_ADAPTER??"skalex";if(name.startsWith("custom:")){let modPath=name.slice(7);if(!modPath)throw Error("VIBE_STORAGE_ADAPTER=custom: requires a module path after the colon");let mod=await import(modPath),factory=mod.default??mod.createAdapter;if(typeof factory!=="function")throw Error(`Custom storage adapter at ${modPath} must export a default function (or \`createAdapter\`) of type AgentStorageAdapterFactory`);return factory}let factory=getAdapter(name);if(!factory){let candidate={skalex:"@vibecontrols/vibe-plugin-storage-skalex",postgres:"@vibecontrols/vibe-plugin-storage-postgres",postgresql:"@vibecontrols/vibe-plugin-storage-postgres"}[name];if(candidate)try{await import(candidate),factory=getAdapter(name)}catch{}}if(!factory)throw Error(`Unknown storage adapter: "${name}". Registered adapters: ${listAdapters().join(", ")||`(none \u2014 did you install @vibecontrols/vibe-plugin-storage-${name})?`}`);return factory}async function createAgentDatabase(options){if(!options.encryptionKey)throw Error("createAgentDatabase(): encryptionKey is required. Storage is always encrypted at rest.");if(!options.dbPath)throw Error("createAgentDatabase(): dbPath is required.");return(await resolveFactory(options))({dataDir:options.dbPath,encryptionKey:options.encryptionKey,adapterOptions:options.adapterOptions})}registerAdapter5("skalex",createSkalexAgentDatabase4);var PLUGIN_NAME="storage",PLUGIN_PACKAGE_NAME="@vibecontrols/vibe-plugin-storage",PLUGIN_VERSION=getPluginVersion();function getPluginVersion(){try{let dir=dirname(fileURLToPath(import.meta.url));for(let i=0;i<10&&dir&&dir!==dirname(dir);i++){let pkgPath=joinPath(dir,"package.json");if(existsSync5(pkgPath))try{let pkg=JSON.parse(readFileSync5(pkgPath,"utf8"));if(pkg.name===PLUGIN_PACKAGE_NAME&&typeof pkg.version==="string")return pkg.version}catch{}dir=dirname(dir)}}catch{}return"0.0.0"}var STORAGE_PROVIDERS=[{packageName:"@vibecontrols/vibe-plugin-storage-skalex",pluginName:"storage-skalex",defaultOn:["linux","darwin","win32"]},{packageName:"@vibecontrols/vibe-plugin-storage-postgres",pluginName:"storage-postgres"}],createPlugin=(ctx)=>{let log=new BoundLogger(ctx.logger,PLUGIN_NAME),lifecycle=createLifecycleHooks({name:PLUGIN_NAME,telemetryEventName:"storage.ready",onInit:(hostServices)=>{new TelemetryEmitter(PLUGIN_NAME,PLUGIN_VERSION,hostServices).emitReady(),log.info("storage meta plugin ready (skalex adapter auto-registered)")}});return{name:PLUGIN_NAME,version:PLUGIN_VERSION,description:"Storage facade \u2014 owns AgentDatabase contract and adapter registry",tags:["backend","adapter"],metaProviders:STORAGE_PROVIDERS,provisionProviders:(hostServices)=>provisionMetaProviders(hostServices,STORAGE_PROVIDERS),capabilities:{storage:"rw"},onServerStart:lifecycle.onServerStart,onServerStop:lifecycle.onServerStop}},src_default=createPlugin;export{AgentDatabase5 as AgentDatabase,createAgentDatabase,createPlugin,src_default as default,getAdapter,listAdapters,registerAdapter5 as registerAdapter};