@vibecontrols/vibe-plugin-storage 2026.509.1 → 2026.509.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +18 -34
- package/dist/index.js +3 -2
- package/package.json +2 -1
package/dist/index.d.ts
CHANGED
|
@@ -15,45 +15,29 @@
|
|
|
15
15
|
* importing this package, so the agent never has to depend on the
|
|
16
16
|
* skalex package directly. Override at runtime via VIBE_STORAGE_ADAPTER
|
|
17
17
|
* or pass `adapterFactory` to `createAgentDatabase()`.
|
|
18
|
+
*
|
|
19
|
+
* Plugin contract / host service / lifecycle helpers come from
|
|
20
|
+
* @vibecontrols/plugin-sdk — they are NOT redeclared here. The
|
|
21
|
+
* storage-domain contracts (`AgentDatabase`, `StorageProvider`,
|
|
22
|
+
* adapter-registry types) STAY inline because they are storage-domain
|
|
23
|
+
* shapes, not SDK surface.
|
|
18
24
|
*/
|
|
25
|
+
import { type VibePlugin, type VibePluginFactory } from "@vibecontrols/plugin-sdk/contract";
|
|
19
26
|
/**
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
*
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
name: string;
|
|
26
|
-
dataDir: string;
|
|
27
|
-
logger: {
|
|
28
|
-
info: (...args: unknown[]) => void;
|
|
29
|
-
warn: (...args: unknown[]) => void;
|
|
30
|
-
error: (...args: unknown[]) => void;
|
|
31
|
-
debug: (...args: unknown[]) => void;
|
|
32
|
-
};
|
|
33
|
-
audit?: {
|
|
34
|
-
emit: (event: string, payload?: unknown) => void;
|
|
35
|
-
};
|
|
36
|
-
}
|
|
37
|
-
/**
|
|
38
|
-
* Minimal VibePlugin shape this meta package returns from its
|
|
39
|
-
* createPlugin(ctx) factory. The storage facade has no routes / CLI /
|
|
40
|
-
* lifecycle hooks of its own — it ships solely so concrete adapters
|
|
41
|
-
* (Skalex, Postgres) can register themselves on import. The factory is
|
|
42
|
-
* required to satisfy Plugin Contract v2 in the agent's loader.
|
|
27
|
+
* Plugin Contract v2 factory. Returns a meta plugin that has no routes
|
|
28
|
+
* or CLI surface of its own — actual storage capability is exposed via
|
|
29
|
+
* the named exports below (registerAdapter / createAgentDatabase /
|
|
30
|
+
* AgentDatabase). The factory wires lifecycle hooks for the agent's
|
|
31
|
+
* loader so we can announce readiness via telemetry on start.
|
|
43
32
|
*/
|
|
44
|
-
export
|
|
45
|
-
name: string;
|
|
46
|
-
version: string;
|
|
47
|
-
description: string;
|
|
48
|
-
tags?: ReadonlyArray<string>;
|
|
49
|
-
}
|
|
50
|
-
export type VibePluginFactory = (ctx: ProfileContext) => VibeStoragePlugin;
|
|
33
|
+
export declare const createPlugin: VibePluginFactory;
|
|
51
34
|
/**
|
|
52
|
-
*
|
|
53
|
-
*
|
|
54
|
-
*
|
|
35
|
+
* Static manifest export — kept for the agent's defensive plugin loader
|
|
36
|
+
* that reads `vibePlugin` directly without invoking the factory.
|
|
37
|
+
* Lifecycle hooks here are no-ops; real registration happens via the
|
|
38
|
+
* factory above.
|
|
55
39
|
*/
|
|
56
|
-
export declare const
|
|
40
|
+
export declare const vibePlugin: VibePlugin;
|
|
57
41
|
export default createPlugin;
|
|
58
42
|
export { AgentDatabase, type AgentStorageAdapterFactory, type AgentStorageAdapterOptions, type StorageEntry, type Task, type GitRepository, type BookmarkedCommand, type Notification, } from "./types.js";
|
|
59
43
|
export { registerAdapter, getAdapter, listAdapters } from "./registry.js";
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
var __require=import.meta.require;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 nodeCrypto from"crypto";import nodePath from"path";import nodeFs from"fs";import zlib from"zlib";import http from"http";import{closeSync,existsSync,mkdirSync,openSync,readFileSync,unlinkSync,writeFileSync}from"fs";import{join}from"path";import nodeCrypto2 from"crypto";import nodePath2 from"path";import nodeFs2 from"fs";import zlib2 from"zlib";import http2 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
|
+
var __require=import.meta.require;function createLifecycleHooks(spec){let{name,onInit,onShutdown,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)}}}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)}};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 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 nodeCrypto from"crypto";import nodePath from"path";import nodeFs from"fs";import zlib from"zlib";import http from"http";import{closeSync,existsSync,mkdirSync,openSync,readFileSync,unlinkSync,writeFileSync}from"fs";import{join}from"path";import nodeCrypto2 from"crypto";import nodePath2 from"path";import nodeFs2 from"fs";import zlib2 from"zlib";import http2 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(`
|
|
3
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(`
|
|
4
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 nodeFs22=await import("fs"),nodePath22=await import("path"),dir=this._adapter.dir;if(!dir)return;let orphans=(await nodeFs22.default.promises.readdir(dir)).filter((f)=>f.includes(".tmp."));for(let orphan of orphans){let orphanPath=nodePath22.default.join(dir,orphan);try{await nodeFs22.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.
|
|
5
6
|
|
|
@@ -51,4 +52,4 @@ data: /message
|
|
|
51
52
|
|
|
52
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)+`
|
|
53
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(`
|
|
54
|
-
`))!==-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)}}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 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 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 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 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)}function getAdapter(name){return registry3.get(name)}function listAdapters(){return Array.from(registry3.keys())}class AgentDatabase3{}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})}registerAdapter3("skalex",createSkalexAgentDatabase2);var createPlugin=(_ctx)=>({name:"storage",version:"2026.508.5",description:"Storage facade \u2014 owns AgentDatabase contract and adapter registry",tags:["backend","adapter"]}),src_default=createPlugin;export{registerAdapter3 as registerAdapter,listAdapters,getAdapter,src_default as default,createPlugin,createAgentDatabase,AgentDatabase3 as AgentDatabase};
|
|
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)}}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 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 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 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 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)}function getAdapter(name){return registry3.get(name)}function listAdapters(){return Array.from(registry3.keys())}class AgentDatabase3{}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})}registerAdapter3("skalex",createSkalexAgentDatabase2);var PLUGIN_NAME="storage",PLUGIN_VERSION="2026.509.2",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"],capabilities:{storage:"rw"},onServerStart:lifecycle.onServerStart,onServerStop:lifecycle.onServerStop}},vibePlugin={name:PLUGIN_NAME,version:PLUGIN_VERSION,description:"Storage facade \u2014 owns AgentDatabase contract and adapter registry",tags:["backend","adapter"],capabilities:{storage:"rw"}},src_default=createPlugin;export{vibePlugin,registerAdapter3 as registerAdapter,listAdapters,getAdapter,src_default as default,createPlugin,createAgentDatabase,AgentDatabase3 as AgentDatabase};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@vibecontrols/vibe-plugin-storage",
|
|
3
|
-
"version": "2026.509.
|
|
3
|
+
"version": "2026.509.2",
|
|
4
4
|
"type": "module",
|
|
5
5
|
"main": "./dist/index.js",
|
|
6
6
|
"types": "./dist/index.d.ts",
|
|
@@ -27,6 +27,7 @@
|
|
|
27
27
|
"sanity": "bun run format:check && bun run lint && bun run type:check && bun run build"
|
|
28
28
|
},
|
|
29
29
|
"dependencies": {
|
|
30
|
+
"@vibecontrols/plugin-sdk": "2026.509.1",
|
|
30
31
|
"@vibecontrols/vibe-plugin-storage-skalex": "2026.509.1"
|
|
31
32
|
},
|
|
32
33
|
"devDependencies": {
|