@soulcraft/brainy 0.28.0 → 0.30.0
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/README.md +71 -0
- package/dist/brainy.js +90220 -0
- package/dist/brainy.min.js +12511 -0
- package/dist/brainyData.d.ts +53 -0
- package/dist/coreTypes.d.ts +75 -0
- package/dist/hnsw/hnswIndex.d.ts +15 -0
- package/dist/hnsw/hnswIndex.d.ts.map +1 -1
- package/dist/statistics/statisticsManager.d.ts +121 -0
- package/dist/storage/adapters/baseStorageAdapter.d.ts +46 -0
- package/dist/storage/adapters/baseStorageAdapter.d.ts.map +1 -1
- package/dist/storage/adapters/memoryStorage.d.ts +41 -0
- package/dist/storage/adapters/memoryStorage.d.ts.map +1 -1
- package/dist/storage/baseStorage.d.ts +46 -0
- package/dist/storage/baseStorage.d.ts.map +1 -1
- package/dist/storage/fileSystemStorage.d.ts +73 -0
- package/dist/storage/fileSystemStorage.d.ts.map +1 -0
- package/dist/storage/opfsStorage.d.ts +236 -0
- package/dist/storage/opfsStorage.d.ts.map +1 -0
- package/dist/storage/s3CompatibleStorage.d.ts +157 -0
- package/dist/storage/s3CompatibleStorage.d.ts.map +1 -0
- package/dist/types/paginationTypes.d.ts +111 -0
- package/dist/types/paginationTypes.d.ts.map +1 -0
- package/dist/unified.js +782 -86
- package/dist/unified.min.js +1 -1
- package/dist/utils/environmentDetection.d.ts +47 -0
- package/dist/utils/environmentDetection.d.ts.map +1 -0
- package/dist/utils/logger.d.ts +99 -0
- package/dist/utils/logger.d.ts.map +1 -0
- package/dist/utils/version.d.ts +5 -0
- package/dist/utils/version.d.ts.map +1 -0
- package/package.json +15 -8
package/dist/unified.min.js
CHANGED
|
@@ -6,7 +6,7 @@ function e(e,t){return t.forEach(function(t){t&&"string"!=typeof t&&!Array.isArr
|
|
|
6
6
|
* @author Feross Aboukhadijeh <https://feross.org>
|
|
7
7
|
* @license MIT
|
|
8
8
|
*/
|
|
9
|
-
function(e){const t=s,n=f,r="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=i,e.SlowBuffer=function(e){+e!=e&&(e=0);return i.alloc(+e)},e.INSPECT_MAX_BYTES=50;const a=2147483647;function o(e){if(e>a)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,i.prototype),t}function i(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return u(e)}return c(e,t,n)}function c(e,t,n){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!i.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const n=0|m(e,t);let r=o(n);const a=r.write(e,t);a!==n&&(r=r.slice(0,a));return r}(e,t);if(ArrayBuffer.isView(e))return function(e){if(X(e,Uint8Array)){const t=new Uint8Array(e);return h(t.buffer,t.byteOffset,t.byteLength)}return d(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(X(e,ArrayBuffer)||e&&X(e.buffer,ArrayBuffer))return h(e,t,n);if("undefined"!=typeof SharedArrayBuffer&&(X(e,SharedArrayBuffer)||e&&X(e.buffer,SharedArrayBuffer)))return h(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const r=e.valueOf&&e.valueOf();if(null!=r&&r!==e)return i.from(r,t,n);const a=function(e){if(i.isBuffer(e)){const t=0|p(e.length),n=o(t);return 0===n.length||e.copy(n,0,0,t),n}if(void 0!==e.length)return"number"!=typeof e.length||Y(e.length)?o(0):d(e);if("Buffer"===e.type&&Array.isArray(e.data))return d(e.data)}(e);if(a)return a;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return i.from(e[Symbol.toPrimitive]("string"),t,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function l(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function u(e){return l(e),o(e<0?0:0|p(e))}function d(e){const t=e.length<0?0:0|p(e.length),n=o(t);for(let r=0;r<t;r+=1)n[r]=255&e[r];return n}function h(e,t,n){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(n||0))throw new RangeError('"length" is outside of buffer bounds');let r;return r=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n),Object.setPrototypeOf(r,i.prototype),r}function p(e){if(e>=a)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+a.toString(16)+" bytes");return 0|e}function m(e,t){if(i.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||X(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const n=e.length,r=arguments.length>2&&!0===arguments[2];if(!r&&0===n)return 0;let a=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return H(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return q(e).length;default:if(a)return r?-1:H(e).length;t=(""+t).toLowerCase(),a=!0}}function g(e,t,n){let r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return A(this,t,n);case"utf8":case"utf-8":return N(this,t,n);case"ascii":return E(this,t,n);case"latin1":case"binary":return $(this,t,n);case"base64":return T(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return R(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function y(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function b(e,t,n,r,a){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),Y(n=+n)&&(n=a?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(a)return-1;n=e.length-1}else if(n<0){if(!a)return-1;n=0}if("string"==typeof t&&(t=i.from(t,r)),i.isBuffer(t))return 0===t.length?-1:x(e,t,n,r,a);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?a?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):x(e,[t],n,r,a);throw new TypeError("val must be string, number or Buffer")}function x(e,t,n,r,a){let s,o=1,i=e.length,c=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;o=2,i/=2,c/=2,n/=2}function l(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(a){let r=-1;for(s=n;s<i;s++)if(l(e,s)===l(t,-1===r?0:s-r)){if(-1===r&&(r=s),s-r+1===c)return r*o}else-1!==r&&(s-=s-r),r=-1}else for(n+c>i&&(n=i-c),s=n;s>=0;s--){let n=!0;for(let r=0;r<c;r++)if(l(e,s+r)!==l(t,r)){n=!1;break}if(n)return s}return-1}function w(e,t,n,r){n=Number(n)||0;const a=e.length-n;r?(r=Number(r))>a&&(r=a):r=a;const s=t.length;let o;for(r>s/2&&(r=s/2),o=0;o<r;++o){const r=parseInt(t.substr(2*o,2),16);if(Y(r))return o;e[n+o]=r}return o}function v(e,t,n,r){return K(H(t,e.length-n),e,n,r)}function k(e,t,n,r){return K(function(e){const t=[];for(let n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function I(e,t,n,r){return K(q(t),e,n,r)}function S(e,t,n,r){return K(function(e,t){let n,r,a;const s=[];for(let o=0;o<e.length&&!((t-=2)<0);++o)n=e.charCodeAt(o),r=n>>8,a=n%256,s.push(a),s.push(r);return s}(t,e.length-n),e,n,r)}function T(e,n,r){return 0===n&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function N(e,t,n){n=Math.min(e.length,n);const r=[];let a=t;for(;a<n;){const t=e[a];let s=null,o=t>239?4:t>223?3:t>191?2:1;if(a+o<=n){let n,r,i,c;switch(o){case 1:t<128&&(s=t);break;case 2:n=e[a+1],128==(192&n)&&(c=(31&t)<<6|63&n,c>127&&(s=c));break;case 3:n=e[a+1],r=e[a+2],128==(192&n)&&128==(192&r)&&(c=(15&t)<<12|(63&n)<<6|63&r,c>2047&&(c<55296||c>57343)&&(s=c));break;case 4:n=e[a+1],r=e[a+2],i=e[a+3],128==(192&n)&&128==(192&r)&&128==(192&i)&&(c=(15&t)<<18|(63&n)<<12|(63&r)<<6|63&i,c>65535&&c<1114112&&(s=c))}}null===s?(s=65533,o=1):s>65535&&(s-=65536,r.push(s>>>10&1023|55296),s=56320|1023&s),r.push(s),a+=o}return function(e){const t=e.length;if(t<=C)return String.fromCharCode.apply(String,e);let n="",r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=C));return n}(r)}e.kMaxLength=a,i.TYPED_ARRAY_SUPPORT=function(){try{const e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),i.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(i.prototype,"parent",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.buffer}}),Object.defineProperty(i.prototype,"offset",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.byteOffset}}),i.poolSize=8192,i.from=function(e,t,n){return c(e,t,n)},Object.setPrototypeOf(i.prototype,Uint8Array.prototype),Object.setPrototypeOf(i,Uint8Array),i.alloc=function(e,t,n){return function(e,t,n){return l(e),e<=0?o(e):void 0!==t?"string"==typeof n?o(e).fill(t,n):o(e).fill(t):o(e)}(e,t,n)},i.allocUnsafe=function(e){return u(e)},i.allocUnsafeSlow=function(e){return u(e)},i.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==i.prototype},i.compare=function(e,t){if(X(e,Uint8Array)&&(e=i.from(e,e.offset,e.byteLength)),X(t,Uint8Array)&&(t=i.from(t,t.offset,t.byteLength)),!i.isBuffer(e)||!i.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let n=e.length,r=t.length;for(let a=0,s=Math.min(n,r);a<s;++a)if(e[a]!==t[a]){n=e[a],r=t[a];break}return n<r?-1:r<n?1:0},i.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},i.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return i.alloc(0);let n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;const r=i.allocUnsafe(t);let a=0;for(n=0;n<e.length;++n){let t=e[n];if(X(t,Uint8Array))a+t.length>r.length?(i.isBuffer(t)||(t=i.from(t)),t.copy(r,a)):Uint8Array.prototype.set.call(r,t,a);else{if(!i.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(r,a)}a+=t.length}return r},i.byteLength=m,i.prototype._isBuffer=!0,i.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)y(this,t,t+1);return this},i.prototype.swap32=function(){const e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)y(this,t,t+3),y(this,t+1,t+2);return this},i.prototype.swap64=function(){const e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)y(this,t,t+7),y(this,t+1,t+6),y(this,t+2,t+5),y(this,t+3,t+4);return this},i.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?N(this,0,e):g.apply(this,arguments)},i.prototype.toLocaleString=i.prototype.toString,i.prototype.equals=function(e){if(!i.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===i.compare(this,e)},i.prototype.inspect=function(){let t="";const n=e.INSPECT_MAX_BYTES;return t=this.toString("hex",0,n).replace(/(.{2})/g,"$1 ").trim(),this.length>n&&(t+=" ... "),"<Buffer "+t+">"},r&&(i.prototype[r]=i.prototype.inspect),i.prototype.compare=function(e,t,n,r,a){if(X(e,Uint8Array)&&(e=i.from(e,e.offset,e.byteLength)),!i.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===a&&(a=this.length),t<0||n>e.length||r<0||a>this.length)throw new RangeError("out of range index");if(r>=a&&t>=n)return 0;if(r>=a)return-1;if(t>=n)return 1;if(this===e)return 0;let s=(a>>>=0)-(r>>>=0),o=(n>>>=0)-(t>>>=0);const c=Math.min(s,o),l=this.slice(r,a),u=e.slice(t,n);for(let e=0;e<c;++e)if(l[e]!==u[e]){s=l[e],o=u[e];break}return s<o?-1:o<s?1:0},i.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},i.prototype.indexOf=function(e,t,n){return b(this,e,t,n,!0)},i.prototype.lastIndexOf=function(e,t,n){return b(this,e,t,n,!1)},i.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}const a=this.length-t;if((void 0===n||n>a)&&(n=a),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");let s=!1;for(;;)switch(r){case"hex":return w(this,e,t,n);case"utf8":case"utf-8":return v(this,e,t,n);case"ascii":case"latin1":case"binary":return k(this,e,t,n);case"base64":return I(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,e,t,n);default:if(s)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),s=!0}},i.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const C=4096;function E(e,t,n){let r="";n=Math.min(e.length,n);for(let a=t;a<n;++a)r+=String.fromCharCode(127&e[a]);return r}function $(e,t,n){let r="";n=Math.min(e.length,n);for(let a=t;a<n;++a)r+=String.fromCharCode(e[a]);return r}function A(e,t,n){const r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);let a="";for(let r=t;r<n;++r)a+=Q[e[r]];return a}function R(e,t,n){const r=e.slice(t,n);let a="";for(let e=0;e<r.length-1;e+=2)a+=String.fromCharCode(r[e]+256*r[e+1]);return a}function _(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function O(e,t,n,r,a,s){if(!i.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>a||t<s)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function F(e,t,n,r,a){W(t,r,a,e,n,7);let s=Number(t&BigInt(4294967295));e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,n}function D(e,t,n,r,a){W(t,r,a,e,n,7);let s=Number(t&BigInt(4294967295));e[n+7]=s,s>>=8,e[n+6]=s,s>>=8,e[n+5]=s,s>>=8,e[n+4]=s;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[n+3]=o,o>>=8,e[n+2]=o,o>>=8,e[n+1]=o,o>>=8,e[n]=o,n+8}function M(e,t,n,r,a,s){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function P(e,t,r,a,s){return t=+t,r>>>=0,s||M(e,0,r,4),n.write(e,t,r,a,23,4),r+4}function B(e,t,r,a,s){return t=+t,r>>>=0,s||M(e,0,r,8),n.write(e,t,r,a,52,8),r+8}i.prototype.slice=function(e,t){const n=this.length;(e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t<e&&(t=e);const r=this.subarray(e,t);return Object.setPrototypeOf(r,i.prototype),r},i.prototype.readUintLE=i.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||_(e,t,this.length);let r=this[e],a=1,s=0;for(;++s<t&&(a*=256);)r+=this[e+s]*a;return r},i.prototype.readUintBE=i.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||_(e,t,this.length);let r=this[e+--t],a=1;for(;t>0&&(a*=256);)r+=this[e+--t]*a;return r},i.prototype.readUint8=i.prototype.readUInt8=function(e,t){return e>>>=0,t||_(e,1,this.length),this[e]},i.prototype.readUint16LE=i.prototype.readUInt16LE=function(e,t){return e>>>=0,t||_(e,2,this.length),this[e]|this[e+1]<<8},i.prototype.readUint16BE=i.prototype.readUInt16BE=function(e,t){return e>>>=0,t||_(e,2,this.length),this[e]<<8|this[e+1]},i.prototype.readUint32LE=i.prototype.readUInt32LE=function(e,t){return e>>>=0,t||_(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},i.prototype.readUint32BE=i.prototype.readUInt32BE=function(e,t){return e>>>=0,t||_(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},i.prototype.readBigUInt64LE=J(function(e){V(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||G(e,this.length-8);const r=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,a=this[++e]+256*this[++e]+65536*this[++e]+n*2**24;return BigInt(r)+(BigInt(a)<<BigInt(32))}),i.prototype.readBigUInt64BE=J(function(e){V(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||G(e,this.length-8);const r=t*2**24+65536*this[++e]+256*this[++e]+this[++e],a=this[++e]*2**24+65536*this[++e]+256*this[++e]+n;return(BigInt(r)<<BigInt(32))+BigInt(a)}),i.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||_(e,t,this.length);let r=this[e],a=1,s=0;for(;++s<t&&(a*=256);)r+=this[e+s]*a;return a*=128,r>=a&&(r-=Math.pow(2,8*t)),r},i.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||_(e,t,this.length);let r=t,a=1,s=this[e+--r];for(;r>0&&(a*=256);)s+=this[e+--r]*a;return a*=128,s>=a&&(s-=Math.pow(2,8*t)),s},i.prototype.readInt8=function(e,t){return e>>>=0,t||_(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},i.prototype.readInt16LE=function(e,t){e>>>=0,t||_(e,2,this.length);const n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},i.prototype.readInt16BE=function(e,t){e>>>=0,t||_(e,2,this.length);const n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},i.prototype.readInt32LE=function(e,t){return e>>>=0,t||_(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},i.prototype.readInt32BE=function(e,t){return e>>>=0,t||_(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},i.prototype.readBigInt64LE=J(function(e){V(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||G(e,this.length-8);const r=this[e+4]+256*this[e+5]+65536*this[e+6]+(n<<24);return(BigInt(r)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)}),i.prototype.readBigInt64BE=J(function(e){V(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||G(e,this.length-8);const r=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(r)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+n)}),i.prototype.readFloatLE=function(e,t){return e>>>=0,t||_(e,4,this.length),n.read(this,e,!0,23,4)},i.prototype.readFloatBE=function(e,t){return e>>>=0,t||_(e,4,this.length),n.read(this,e,!1,23,4)},i.prototype.readDoubleLE=function(e,t){return e>>>=0,t||_(e,8,this.length),n.read(this,e,!0,52,8)},i.prototype.readDoubleBE=function(e,t){return e>>>=0,t||_(e,8,this.length),n.read(this,e,!1,52,8)},i.prototype.writeUintLE=i.prototype.writeUIntLE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){O(this,e,t,n,Math.pow(2,8*n)-1,0)}let a=1,s=0;for(this[t]=255&e;++s<n&&(a*=256);)this[t+s]=e/a&255;return t+n},i.prototype.writeUintBE=i.prototype.writeUIntBE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){O(this,e,t,n,Math.pow(2,8*n)-1,0)}let a=n-1,s=1;for(this[t+a]=255&e;--a>=0&&(s*=256);)this[t+a]=e/s&255;return t+n},i.prototype.writeUint8=i.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,1,255,0),this[t]=255&e,t+1},i.prototype.writeUint16LE=i.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},i.prototype.writeUint16BE=i.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},i.prototype.writeUint32LE=i.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},i.prototype.writeUint32BE=i.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},i.prototype.writeBigUInt64LE=J(function(e,t=0){return F(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),i.prototype.writeBigUInt64BE=J(function(e,t=0){return D(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),i.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);O(this,e,t,n,r-1,-r)}let a=0,s=1,o=0;for(this[t]=255&e;++a<n&&(s*=256);)e<0&&0===o&&0!==this[t+a-1]&&(o=1),this[t+a]=(e/s|0)-o&255;return t+n},i.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);O(this,e,t,n,r-1,-r)}let a=n-1,s=1,o=0;for(this[t+a]=255&e;--a>=0&&(s*=256);)e<0&&0===o&&0!==this[t+a+1]&&(o=1),this[t+a]=(e/s|0)-o&255;return t+n},i.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},i.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},i.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},i.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},i.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},i.prototype.writeBigInt64LE=J(function(e,t=0){return F(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),i.prototype.writeBigInt64BE=J(function(e,t=0){return D(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),i.prototype.writeFloatLE=function(e,t,n){return P(this,e,t,!0,n)},i.prototype.writeFloatBE=function(e,t,n){return P(this,e,t,!1,n)},i.prototype.writeDoubleLE=function(e,t,n){return B(this,e,t,!0,n)},i.prototype.writeDoubleBE=function(e,t,n){return B(this,e,t,!1,n)},i.prototype.copy=function(e,t,n,r){if(!i.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<n&&(r=n),r===n)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);const a=r-n;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(t,n,r):Uint8Array.prototype.set.call(e,this.subarray(n,r),t),a},i.prototype.fill=function(e,t,n,r){if("string"==typeof e){if("string"==typeof t?(r=t,t=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!i.isEncoding(r))throw new TypeError("Unknown encoding: "+r);if(1===e.length){const t=e.charCodeAt(0);("utf8"===r&&t<128||"latin1"===r)&&(e=t)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;let a;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(a=t;a<n;++a)this[a]=e;else{const s=i.isBuffer(e)?e:i.from(e,r),o=s.length;if(0===o)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(a=0;a<n-t;++a)this[a+t]=s[a%o]}return this};const L={};function z(e,t,n){L[e]=class extends n{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}function U(e){let t="",n=e.length;const r="-"===e[0]?1:0;for(;n>=r+4;n-=3)t=`_${e.slice(n-3,n)}${t}`;return`${e.slice(0,n)}${t}`}function W(e,t,n,r,a,s){if(e>n||e<t){const n="bigint"==typeof t?"n":"";let r;throw r=0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(s+1)}${n}`:`>= -(2${n} ** ${8*(s+1)-1}${n}) and < 2 ** ${8*(s+1)-1}${n}`,new L.ERR_OUT_OF_RANGE("value",r,e)}!function(e,t,n){V(t,"offset"),void 0!==e[t]&&void 0!==e[t+n]||G(t,e.length-(n+1))}(r,a,s)}function V(e,t){if("number"!=typeof e)throw new L.ERR_INVALID_ARG_TYPE(t,"number",e)}function G(e,t,n){if(Math.floor(e)!==e)throw V(e,n),new L.ERR_OUT_OF_RANGE("offset","an integer",e);if(t<0)throw new L.ERR_BUFFER_OUT_OF_BOUNDS;throw new L.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${t}`,e)}z("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),z("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),z("ERR_OUT_OF_RANGE",function(e,t,n){let r=`The value of "${e}" is out of range.`,a=n;return Number.isInteger(n)&&Math.abs(n)>2**32?a=U(String(n)):"bigint"==typeof n&&(a=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(a=U(a)),a+="n"),r+=` It must be ${t}. Received ${a}`,r},RangeError);const j=/[^+/0-9A-Za-z-_]/g;function H(e,t){let n;t=t||1/0;const r=e.length;let a=null;const s=[];for(let o=0;o<r;++o){if(n=e.charCodeAt(o),n>55295&&n<57344){if(!a){if(n>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(o+1===r){(t-=3)>-1&&s.push(239,191,189);continue}a=n;continue}if(n<56320){(t-=3)>-1&&s.push(239,191,189),a=n;continue}n=65536+(a-55296<<10|n-56320)}else a&&(t-=3)>-1&&s.push(239,191,189);if(a=null,n<128){if((t-=1)<0)break;s.push(n)}else if(n<2048){if((t-=2)<0)break;s.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;s.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;s.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return s}function q(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(j,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function K(e,t,n,r){let a;for(a=0;a<r&&!(a+n>=t.length||a>=e.length);++a)t[a+n]=e[a];return a}function X(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function Y(e){return e!=e}const Q=function(){const e="0123456789abcdef",t=new Array(256);for(let n=0;n<16;++n){const r=16*n;for(let a=0;a<16;++a)t[r+a]=e[n]+e[a]}return t}();function J(e){return"undefined"==typeof BigInt?Z:e}function Z(){throw new Error("BigInt not supported")}}(a);let I=!1;if("undefined"!=typeof globalThis&&g())try{void 0===globalThis.TextEncoder&&(globalThis.TextEncoder=TextEncoder),void 0===globalThis.TextDecoder&&(globalThis.TextDecoder=TextDecoder),"undefined"!=typeof global&&(global.TextEncoder||(global.TextEncoder=TextEncoder),global.TextDecoder||(global.TextDecoder=TextDecoder),global.__TextEncoder__=TextEncoder,global.__TextDecoder__=TextDecoder);const e={TextEncoder:TextEncoder,TextDecoder:TextDecoder,types:{isFloat32Array:e=>e instanceof Float32Array,isInt32Array:e=>e instanceof Int32Array,isUint8Array:e=>e instanceof Uint8Array,isUint8ClampedArray:e=>e instanceof Uint8ClampedArray}};if("undefined"!=typeof global&&(global.__brainy_util__=e),"undefined"!=typeof global&&global.require&&global.require.cache)for(const t in global.require.cache)if(t.endsWith("/util.js")||"util"===t){const n=global.require.cache[t];n&&n.exports&&Object.assign(n.exports,e)}try{const e=require("util");e.TextEncoder=TextEncoder,e.TextDecoder=TextDecoder}catch(e){}const t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};if(t&&t.Float32Array){const e=t.Float32Array,n=class extends e{constructor(e,t,n){if(e instanceof ArrayBuffer){const r=t||0,a=void 0!==n?n:(e.byteLength-r)/4;if((e.byteLength-r)%4!=0&&void 0===n)try{const t=4*Math.floor((e.byteLength-r)/4),n=new ArrayBuffer(t),a=new Uint8Array(e,r,t);new Uint8Array(n).set(a),super(n)}catch(t){console.warn("Float32Array alignment failed, using original constructor:",t),super(e,r,a)}else super(e,r,a)}else super(e,t,n)}};try{Object.setPrototypeOf(n,e),Object.defineProperty(n,"name",{value:"Float32Array"}),Object.defineProperty(n,"BYTES_PER_ELEMENT",{value:4}),t.Float32Array=n}catch(e){console.warn("Failed to patch Float32Array:",e)}}if("undefined"!=typeof global){const e=e=>{e&&"object"==typeof e&&!e.TextEncoder&&(e.TextEncoder=TextEncoder,e.TextDecoder=TextDecoder,e.types=e.types||{isFloat32Array:e=>e instanceof Float32Array,isInt32Array:e=>e instanceof Int32Array,isUint8Array:e=>e instanceof Uint8Array,isUint8ClampedArray:e=>e instanceof Uint8ClampedArray})};global._utilShim&&e(global._utilShim),"undefined"!=typeof globalThis&&globalThis._utilShim&&e(globalThis._utilShim),global._utilShim?e(global._utilShim):global._utilShim={TextEncoder:TextEncoder,TextDecoder:TextDecoder,types:{isFloat32Array:e=>e instanceof Float32Array,isInt32Array:e=>e instanceof Int32Array,isUint8Array:e=>e instanceof Uint8Array,isUint8ClampedArray:e=>e instanceof Uint8ClampedArray}},"undefined"==typeof globalThis||globalThis._utilShim||(globalThis._utilShim=global._utilShim);try{Object.defineProperty(global,"_utilShim",{get(){return this.__utilShim||{}},set(t){e(t),this.__utilShim=t},configurable:!0})}catch(e){}try{Object.defineProperty(globalThis,"_utilShim",{get(){return this.__utilShim||{}},set(t){e(t),this.__utilShim=t},configurable:!0})}catch(e){}}console.log("Brainy: Successfully patched TensorFlow.js PlatformNode at module load time"),I=!0}catch(e){console.warn("Brainy: Failed to apply early TensorFlow.js platform patch:",e)}async function S(){if("undefined"!=typeof window&&"undefined"!=typeof document)return;const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};if(!I||void 0===e.__TextEncoder__||void 0===e.__TextDecoder__)try{console.log("Brainy: Applying TensorFlow.js platform patch via function call"),e.TextEncoder||(e.TextEncoder=TextEncoder),e.TextDecoder||(e.TextDecoder=TextDecoder),e.__TextEncoder__=TextEncoder,e.__TextDecoder__=TextDecoder,"undefined"!=typeof process&&process.versions&&(process.versions.node||(process.versions.node=process.version));try{const e=await Promise.resolve().then(function(){return Ht});e.TextEncoder=TextEncoder,e.TextDecoder=TextDecoder}catch(e){}I=!0}catch(e){console.warn("Brainy: Failed to apply TensorFlow.js platform patch:",e)}}S().catch(e=>{console.warn("Failed to apply TensorFlow patch at module load:",e)});var T=Object.freeze({__proto__:null,applyTensorFlowPatch:S});const N="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof self?self:null;let C;N&&(N.TextEncoder||(N.TextEncoder=TextEncoder),N.TextDecoder||(N.TextDecoder=TextDecoder),N.__TextEncoder__=TextEncoder,N.__TextDecoder__=TextDecoder),S(),console.log("Applied TensorFlow.js patch via ES modules in setup.ts");const E=new Uint8Array(16);function $(){if(!C&&(C="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!C))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return C(E)}const A=[];for(let e=0;e<256;++e)A.push((e+256).toString(16).slice(1));var R={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function _(e,t,n){if(R.randomUUID&&!e)return R.randomUUID();const r=(e=e||{}).random||(e.rng||$)();return r[6]=15&r[6]|64,r[8]=63&r[8]|128,function(e,t=0){return A[e[t+0]]+A[e[t+1]]+A[e[t+2]]+A[e[t+3]]+"-"+A[e[t+4]]+A[e[t+5]]+"-"+A[e[t+6]]+A[e[t+7]]+"-"+A[e[t+8]]+A[e[t+9]]+"-"+A[e[t+10]]+A[e[t+11]]+A[e[t+12]]+A[e[t+13]]+A[e[t+14]]+A[e[t+15]]}(r)}const O=(e,t)=>{if(e.length!==t.length)throw new Error("Vectors must have the same dimensions");const n=e.reduce((e,n,r)=>{const a=n-t[r];return e+a*a},0);return Math.sqrt(n)},F=(e,t)=>{if(e.length!==t.length)throw new Error("Vectors must have the same dimensions");const{dotProduct:n,normA:r,normB:a}=e.reduce((e,n,r)=>({dotProduct:e.dotProduct+n*t[r],normA:e.normA+n*n,normB:e.normB+t[r]*t[r]}),{dotProduct:0,normA:0,normB:0});if(0===r||0===a)return 2;return 1-n/(Math.sqrt(r)*Math.sqrt(a))},D=(e,t)=>{if(e.length!==t.length)throw new Error("Vectors must have the same dimensions");return e.reduce((e,n,r)=>e+Math.abs(n-t[r]),0)},M=(e,t)=>{if(e.length!==t.length)throw new Error("Vectors must have the same dimensions");const n=e.reduce((e,n,r)=>e+n*t[r],0);return-n};async function P(e,t,n=O){if(t.length<10)return t.map(t=>n(e,t));try{return t.map(t=>n(e,t))}catch(r){return console.error("Batch distance calculation failed:",r),t.map(t=>n(e,t))}}const B=new Map;function L(e,t){if(g())return function(e,t){return new Promise((n,r)=>{try{import("node:worker_threads").then(({Worker:a,isMainThread:s,parentPort:o,workerData:i})=>{if(!s&&o){const e=new Function("return "+i.fnString)()(i.args);return void o.postMessage({result:e})}const c=`worker-${Math.random().toString(36).substring(2,9)}`;let l;if(B.size<4)l=new a("\n import { parentPort, workerData } from 'node:worker_threads';\n\n // Add TensorFlow.js platform patch for Node.js\n if (typeof global !== 'undefined') {\n try {\n // Define a custom PlatformNode class\n class PlatformNode {\n constructor() {\n // Create a util object with necessary methods\n this.util = {\n // Add isFloat32Array and isTypedArray directly to util\n isFloat32Array: (arr) => {\n return !!(\n arr instanceof Float32Array ||\n (arr &&\n Object.prototype.toString.call(arr) === '[object Float32Array]')\n );\n },\n isTypedArray: (arr) => {\n return !!(ArrayBuffer.isView(arr) && !(arr instanceof DataView));\n },\n // Use native TextEncoder and TextDecoder\n TextEncoder: TextEncoder,\n TextDecoder: TextDecoder\n };\n\n // Initialize encoders using native constructors\n this.textEncoder = new TextEncoder();\n this.textDecoder = new TextDecoder();\n }\n\n // Define isFloat32Array directly on the instance\n isFloat32Array(arr) {\n return !!(\n arr instanceof Float32Array ||\n (arr && Object.prototype.toString.call(arr) === '[object Float32Array]')\n );\n }\n\n // Define isTypedArray directly on the instance\n isTypedArray(arr) {\n return !!(ArrayBuffer.isView(arr) && !(arr instanceof DataView));\n }\n }\n\n // Assign the PlatformNode class to the global object\n global.PlatformNode = PlatformNode;\n\n // Also create an instance and assign it to global.platformNode\n global.platformNode = new PlatformNode();\n\n // Ensure global.util exists and has the necessary methods\n if (!global.util) {\n global.util = {};\n }\n\n // Add isFloat32Array method if it doesn't exist\n if (!global.util.isFloat32Array) {\n global.util.isFloat32Array = (arr) => {\n return !!(\n arr instanceof Float32Array ||\n (arr && Object.prototype.toString.call(arr) === '[object Float32Array]')\n );\n };\n }\n\n // Add isTypedArray method if it doesn't exist\n if (!global.util.isTypedArray) {\n global.util.isTypedArray = (arr) => {\n return !!(ArrayBuffer.isView(arr) && !(arr instanceof DataView));\n };\n }\n } catch (error) {\n console.warn('Failed to apply TensorFlow.js platform patch:', error);\n }\n }\n\n const fn = new Function('return ' + workerData.fnString)();\n const result = fn(workerData.args);\n parentPort.postMessage({ result });\n ",{eval:!0,workerData:{fnString:e,args:t}}),B.set(c,l);else{const n=Array.from(B.keys()),r=n[Math.floor(Math.random()*n.length)];l=B.get(r),l._busy&&(l.terminate(),l=new a("\n import { parentPort, workerData } from 'node:worker_threads';\n\n // Add TensorFlow.js platform patch for Node.js\n if (typeof global !== 'undefined') {\n try {\n // Define a custom PlatformNode class\n class PlatformNode {\n constructor() {\n // Create a util object with necessary methods\n this.util = {\n // Use native TextEncoder and TextDecoder\n TextEncoder: TextEncoder,\n TextDecoder: TextDecoder\n };\n\n // Initialize encoders using native constructors\n this.textEncoder = new TextEncoder();\n this.textDecoder = new TextDecoder();\n }\n\n // Define isFloat32Array directly on the instance\n isFloat32Array(arr) {\n return !!(\n arr instanceof Float32Array ||\n (arr && Object.prototype.toString.call(arr) === '[object Float32Array]')\n );\n }\n\n // Define isTypedArray directly on the instance\n isTypedArray(arr) {\n return !!(ArrayBuffer.isView(arr) && !(arr instanceof DataView));\n }\n }\n\n // Assign the PlatformNode class to the global object\n global.PlatformNode = PlatformNode;\n\n // Also create an instance and assign it to global.platformNode\n global.platformNode = new PlatformNode();\n\n // Ensure global.util exists and has the necessary methods\n if (!global.util) {\n global.util = {};\n }\n\n // Add isFloat32Array method if it doesn't exist\n if (!global.util.isFloat32Array) {\n global.util.isFloat32Array = (arr) => {\n return !!(\n arr instanceof Float32Array ||\n (arr && Object.prototype.toString.call(arr) === '[object Float32Array]')\n );\n };\n }\n\n // Add isTypedArray method if it doesn't exist\n if (!global.util.isTypedArray) {\n global.util.isTypedArray = (arr) => {\n return !!(ArrayBuffer.isView(arr) && !(arr instanceof DataView));\n };\n }\n } catch (error) {\n console.warn('Failed to apply TensorFlow.js platform patch:', error);\n }\n }\n\n const fn = new Function('return ' + workerData.fnString)();\n const result = fn(workerData.args);\n parentPort.postMessage({ result });\n ",{eval:!0,workerData:{fnString:e,args:t}}),B.set(r,l)),l._busy=!0}l.on("message",e=>{l._busy=!1,n(e.result)}),l.on("error",e=>{l._busy=!1,r(e)}),l.on("exit",e=>{0!==e&&(l._busy=!1,r(new Error(`Worker stopped with exit code ${e}`)))})}).catch(r)}catch(e){r(e)}})}(e,t);if(m()&&"undefined"!=typeof window&&window.Worker)return function(e,t){return new Promise((n,r)=>{try{let a,s="./worker.js";try{if(void 0!==import.meta&&import.meta.url){s=`${import.meta.url.substring(0,import.meta.url.lastIndexOf("/")+1)}worker.js`}else if("undefined"!=typeof document){const e=document.getElementsByTagName("script");for(let t=0;t<e.length;t++){const n=e[t].src;if(n&&n.includes("unified.js")){s=n.substring(0,n.lastIndexOf("/")+1)+"worker.js";break}}}}catch(e){console.warn("Could not determine worker path from import.meta.url, using relative path",e)}if("./worker.js"===s&&"undefined"!=typeof window){const e=window.location.href,t=e.substring(0,e.lastIndexOf("/")+1);if(s=`${t}worker.js`,"undefined"!=typeof document){const e=`${t}dist/worker.js`,n=new XMLHttpRequest;n.open("HEAD",e,!1);try{n.send(),n.status>=200&&n.status<300&&(s=e)}catch(e){}}}console.log("Using worker path:",s);try{a=new Worker(s)}catch(s){console.warn("Failed to create Web Worker from file, trying inline worker:",s);try{const e=new Blob(["\n // Brainy Inline Worker Script\n console.log('Brainy Inline Worker: Started');\n\n self.onmessage = function (e) {\n try {\n console.log('Brainy Inline Worker: Received message', e.data ? 'with data' : 'without data');\n\n if (!e.data || !e.data.fnString) {\n throw new Error('Invalid message: missing function string');\n }\n\n console.log('Brainy Inline Worker: Creating function from string');\n const fn = new Function('return ' + e.data.fnString)();\n\n console.log('Brainy Inline Worker: Executing function with args');\n const result = fn(e.data.args);\n\n console.log('Brainy Inline Worker: Function executed successfully, posting result');\n self.postMessage({ result: result });\n } catch (error) {\n console.error('Brainy Inline Worker: Error executing function', error);\n self.postMessage({ \n error: error.message,\n stack: error.stack\n });\n }\n };\n "],{type:"application/javascript"}),t=URL.createObjectURL(e);a=new Worker(t),console.log("Created inline worker using Blob URL")}catch(a){console.warn("Failed to create inline Web Worker, falling back to main thread execution:",a);try{const r=new Function("return "+e)();return void n(r(t))}catch(e){return void r(e)}}}const o=setTimeout(()=>{console.warn("Web Worker execution timed out, falling back to main thread"),a.terminate();try{const r=new Function("return "+e)();n(r(t))}catch(e){r(e)}},25e3);a.onmessage=function(e){clearTimeout(o),e.data.error?r(new Error(e.data.error)):n(e.data.result),a.terminate()},a.onerror=function(s){clearTimeout(o),console.warn("Web Worker error, falling back to main thread execution:",s.message),a.terminate();try{const r=new Function("return "+e)();n(r(t))}catch(e){r(e)}},a.postMessage({fnString:e,args:t})}catch(e){r(e)}})}(e,t);try{let n;try{n=new Function("return "+e)()}catch(t){console.warn("Fallback: Error creating function with return syntax, trying alternative approaches",t);try{n=new Function("return ("+e+")")()}catch(r){console.warn("Fallback: Error creating function with parentheses wrapping",r);try{n=new Function(e)()}catch(r){console.warn("Fallback: Direct approach failed, trying with function wrapper",r);try{n=new Function("return function(args) { return ("+e+")(args); }")()}catch(e){throw console.error("Fallback: All approaches to create function failed",e),new Error("Failed to create function from string: "+t.message)}}}}return Promise.resolve(n(t))}catch(e){return Promise.reject(e)}}function z(){g()&&import("node:worker_threads").then(({Worker:e})=>{for(const e of B.values())e.terminate();B.clear(),console.log("Worker pools cleaned up")}).catch(console.error)}let U=class{constructor(e={}){this.model=null,this.initialized=!1,this.tf=null,this.use=null,this.backend="cpu",this.verbose=!0,this.verbose=void 0===e.verbose||e.verbose}addServerCompatibilityPolyfills(){if(m())return;const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};try{e.util||(e.util={}),e.util.isFloat32Array||(e.util.isFloat32Array=e=>!!(e instanceof Float32Array||e&&"[object Float32Array]"===Object.prototype.toString.call(e))),e.util.isTypedArray||(e.util.isTypedArray=e=>!(!ArrayBuffer.isView(e)||e instanceof DataView))}catch(e){console.warn("Failed to add utility polyfills:",e)}}isTestEnvironment(){return"undefined"!=typeof process&&("true"===process.env.VITEST||"undefined"!=typeof global&&global.__vitest__||process.argv.some(e=>e.includes("vitest")))}logger(e,t,...n){("error"===e||this.verbose)&&console[e](t,...n)}async loadModelWithRetry(e,t=3,n=1e3){let r=null;const a=[];if(this.use){const e=["https://storage.googleapis.com/tfjs-models/savedmodel/universal_sentence_encoder/model.json","https://tfhub.dev/tensorflow/tfjs-model/universal-sentence-encoder-lite/1/default/1/model.json","https://tfhub.dev/tensorflow/tfjs-model/universal-sentence-encoder/1/default/1/model.json","https://tfhub.dev/tensorflow/tfjs-model/universal-sentence-encoder/1/default/1","https://tfhub.dev/tensorflow/universal-sentence-encoder/4","https://tfhub.dev/tensorflow/universal-sentence-encoder/4/default/1/model.json"];for(const t of e)this.use.load?a.push(()=>this.use.load(t)):this.use.default&&this.use.default.load&&a.push(()=>this.use.default.load(t))}for(let s=0;s<=t;s++)try{this.logger("log",0===s?"Loading Universal Sentence Encoder model...":`Retrying Universal Sentence Encoder model loading (attempt ${s+1}/${t+1})...`);const n=await e();return s>0&&this.logger("log","Universal Sentence Encoder model loaded successfully after retry"),n}catch(e){r=e;const o=r.message||String(r),i=o.includes("Failed to parse model JSON")||o.includes("Failed to fetch")||o.includes("Network error")||o.includes("ENOTFOUND")||o.includes("ECONNRESET")||o.includes("ETIMEDOUT")||o.includes("JSON")||o.includes("model.json")||o.includes("byte length")||o.includes("tensor should have")||o.includes("shape")||o.includes("dimensions");if(!(s<t&&i)){if(s>=t){if(this.logger("warn",`Universal Sentence Encoder model loading failed after ${t+1} attempts. Last error: ${o}. Trying alternative URLs...`),a.length>0)for(let e=0;e<a.length;e++)try{this.logger("log",`Trying alternative model URL ${e+1}/${a.length}...`);const t=await a[e]();return this.logger("log",`Successfully loaded Universal Sentence Encoder from alternative URL ${e+1}`),t}catch(t){this.logger("warn",`Failed to load from alternative URL ${e+1}: ${t}`)}this.logger("error",`Universal Sentence Encoder model loading failed after trying all alternatives. Last error: ${o}`)}else this.logger("error",`Universal Sentence Encoder model loading failed with non-retryable error: ${o}`);throw r}{const e=n*Math.pow(2,s);this.logger("warn",`Universal Sentence Encoder model loading failed (attempt ${s+1}): ${o}. Retrying in ${e}ms...`),await new Promise(t=>setTimeout(t,e))}}throw r||new Error("Unknown error during model loading")}async init(){try{const e=console.warn;console.warn=function(t,...n){t&&"string"==typeof t&&t.includes("Hi, looks like you are running TensorFlow.js in Node.js")||e(t,...n)},this.addServerCompatibilityPolyfills();try{const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof self?self:null;if(e)try{if("undefined"!=typeof process&&process.versions&&process.versions.node){const t=await Promise.resolve().then(function(){return Ht});e.TextEncoder||(e.TextEncoder=t.TextEncoder),e.TextDecoder||(e.TextDecoder=t.TextDecoder)}}catch(t){e.TextEncoder||(e.TextEncoder=TextEncoder),e.TextDecoder||(e.TextDecoder=TextDecoder)}const{applyTensorFlowPatch:t}=await Promise.resolve().then(function(){return T});await t(),this.tf=await Promise.resolve().then(function(){return Fy}),await Promise.resolve().then(function(){return gS});try{if(m()){await Promise.resolve().then(function(){return KO});try{this.tf.setBackend?(await this.tf.setBackend("webgl"),this.backend="webgl",console.log("Using WebGL backend for TensorFlow.js")):console.warn("tf.setBackend is not available, falling back to CPU")}catch(e){console.warn("WebGL backend not available, falling back to CPU:",e),this.backend="cpu"}}}catch(e){console.warn("WebGL backend not available, falling back to CPU:",e),this.backend="cpu"}this.use=await Promise.resolve().then(function(){return ED})}catch(e){return this.logger("error","Failed to initialize TensorFlow.js:",e),this.logger("warn","Will use fallback embedding mechanism"),void(this.initialized=!0)}this.tf&&this.tf.setBackend&&await this.tf.setBackend(this.backend);const t=function(e){let t=null;if(e.load&&"function"==typeof e.load)t=e.load;else if(e.default&&e.default.load&&"function"==typeof e.default.load)t=e.default.load;else if(e.default&&"function"==typeof e.default)t=e.default;else if("function"==typeof e)t=e;else if(e.UniversalSentenceEncoder&&"function"==typeof e.UniversalSentenceEncoder.load)t=e.UniversalSentenceEncoder.load;else if(e.default&&e.default.UniversalSentenceEncoder&&"function"==typeof e.default.UniversalSentenceEncoder.load)t=e.default.UniversalSentenceEncoder.load;else for(const n in e)if("function"==typeof e[n]){if((e[n].name||n).toLowerCase().includes("load")){t=e[n];break}}else if("object"==typeof e[n]&&null!==e[n]){for(const r in e[n])if("function"==typeof e[n][r]){if((e[n][r].name||r).toLowerCase().includes("load")){t=e[n][r];break}}if(t)break}if(t)return async()=>await t();return null}(this.use);if(!t)return this.logger("warn","Could not find Universal Sentence Encoder load function, using fallback"),void(this.initialized=!0);try{this.model=await this.loadModelWithRetry(t),this.initialized=!0}catch(e){this.logger("warn","Failed to load Universal Sentence Encoder model, using fallback:",e),this.initialized=!0}console.warn=e}catch(e){this.logger("error","Failed to initialize Universal Sentence Encoder:",e),this.logger("warn","Using fallback embedding mechanism due to initialization failure"),this.initialized=!0}}generateFallbackVector(e){const t=new Array(512).fill(0);if(!e||""===e.trim())return t;const n=e=>{let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return t},r=e.split(/\s+/);for(let e=0;e<r.length&&e<512;e++){const a=r[e];if(a){const e=n(a);t[Math.abs(e)%512]=e%1e3/1e3}}if(e.length>0){const r=n(e);for(let e=0;e<10;e++){t[(Math.abs(r)+50*e)%512]=(r+e)%1e3/1e3}}return t}async embed(e){this.initialized||await this.init();try{let t;if("string"==typeof e){if(""===e.trim())return new Array(512).fill(0);t=[e]}else{if(!Array.isArray(e)||!e.every(e=>"string"==typeof e))throw new Error("UniversalSentenceEncoder only supports string or string[] data");if(0===e.length||e.every(e=>""===e.trim()))return new Array(512).fill(0);if(t=e.filter(e=>""!==e.trim()),0===t.length)return new Array(512).fill(0)}if(!this.model)return this.logger("warn","Using fallback embedding mechanism (model not available)"),this.generateFallbackVector(t[0]);const n=await this.model.embed(t),r=await n.array();n.dispose();let a=r[0];if(512!==a.length)if(this.logger("warn",`Embedding dimension mismatch: expected 512, got ${a.length}. Standardizing...`),a.length<512){const e=new Array(512).fill(0);for(let t=0;t<a.length;t++)e[t]=a[t];a=e}else if(a.length>512)if(1536===a.length){const e=new Array(512).fill(0);for(let t=0;t<512;t++)e[t]=a[3*t];a=e}else a=a.slice(0,512);return a}catch(t){return this.logger("warn","Failed to embed text with Universal Sentence Encoder, using fallback:",t),"string"==typeof e?this.generateFallbackVector(e):Array.isArray(e)&&e.length>0?this.generateFallbackVector(e[0]):new Array(512).fill(0)}}async embedBatch(e){this.initialized||await this.init();try{if(0===e.length)return[];const t=e.filter(e=>"string"==typeof e&&""!==e.trim());if(0===t.length)return e.map(()=>new Array(512).fill(0));if(!this.model)return this.logger("warn","Using fallback embedding mechanism for batch (model not available)"),e.map(e=>"string"==typeof e&&""!==e.trim()?this.generateFallbackVector(e):new Array(512).fill(0));const n=await this.model.embed(t),r=await n.array();n.dispose();const a=r.map(e=>{if(512!==e.length){if(this.logger("warn",`Batch embedding dimension mismatch: expected 512, got ${e.length}. Standardizing...`),e.length<512){const t=new Array(512).fill(0);for(let n=0;n<e.length;n++)t[n]=e[n];return t}if(e.length>512){if(1536===e.length){const t=new Array(512).fill(0);for(let n=0;n<512;n++)t[n]=e[3*n];return t}return e.slice(0,512)}}return e}),s=[];let o=0;for(let t=0;t<e.length;t++){const n=e[t];"string"==typeof n&&""!==n.trim()?(s.push(a[o]),o++):s.push(new Array(512).fill(0))}return s}catch(t){return this.logger("warn","Failed to batch embed text with Universal Sentence Encoder, using fallback:",t),e.map(e=>"string"==typeof e&&""!==e.trim()?this.generateFallbackVector(e):new Array(512).fill(0))}}async dispose(){if(this.model&&this.tf)try{this.model.dispose(),this.tf.disposeVariables(),this.initialized=!1}catch(e){this.logger("error","Failed to dispose Universal Sentence Encoder:",e)}return Promise.resolve()}};function W(e,t,n=[],r=!0){"undefined"!=typeof process&&("true"===process.env.VITEST||"undefined"!=typeof global&&global.__vitest__||process.argv.some(e=>e.includes("vitest")))||console[e](t,...n)}function V(e){return e?async t=>await e.embed(t):q()}let G=null,j=!1,H=!0;function q(e={}){return void 0!==e.verbose&&(H=e.verbose),G||(G=new U({verbose:H})),async e=>{try{if(!j)try{await G.init(),j=!0}catch(e){throw j=!1,e}return await G.embed(e)}catch(e){throw W("error","Failed to use TensorFlow embedding:",[e],H),new Error(`Universal Sentence Encoder is required but failed: ${e}`)}}}function K(e={}){return q(e)}const X=K();let Y=null,Q=!1,J=!0;function Z(e={}){return void 0!==e.verbose&&(J=e.verbose),Y||(Y=new U({verbose:J})),async e=>{try{return Q||(await Y.init(),Q=!0),await Y.embedBatch(e)}catch(e){throw W("error","Failed to use TensorFlow batch embedding:",[e],J),new Error(`Universal Sentence Encoder batch embedding failed: ${e}`)}}}function ee(e={}){return Z(e)}const te=ee();function ne(e){const t=V(e);return async e=>{const n=t.toString();return await L(n,e)}}var re=Object.freeze({__proto__:null,UniversalSentenceEncoder:U,createBatchEmbeddingFunction:Z,createEmbeddingFunction:V,createTensorFlowEmbeddingFunction:q,createThreadedEmbeddingFunction:ne,defaultBatchEmbeddingFunction:te,defaultEmbeddingFunction:X,getDefaultBatchEmbeddingFunction:ee,getDefaultEmbeddingFunction:K});async function ae(e,t={}){if(!e)throw new Error("BrainyData instance must be provided to getStatistics");try{return await e.getStatistics(t)}catch(e){throw console.error("Failed to get statistics:",e),new Error(`Failed to get statistics: ${e}`)}}const se={M:16,efConstruction:200,efSearch:50,ml:16};class oe{constructor(e={},t=O,n={}){this.nouns=new Map,this.entryPointId=null,this.maxLevel=0,this.dimension=null,this.useParallelization=!0,this.config={...se,...e},this.distanceFunction=t,this.useParallelization=void 0===n.useParallelization||n.useParallelization}setUseParallelization(e){this.useParallelization=e}getUseParallelization(){return this.useParallelization}async calculateDistancesInParallel(e,t){if(!this.useParallelization||t.length<10)return t.map(t=>({id:t.id,distance:this.distanceFunction(e,t.vector)}));try{const n=t.map(e=>e.vector),r=await P(e,n,this.distanceFunction);return t.map((e,t)=>({id:e.id,distance:r[t]}))}catch(n){return console.error("Error in GPU-accelerated distance calculation, falling back to sequential processing:",n),t.map(t=>({id:t.id,distance:this.distanceFunction(e,t.vector)}))}}async addItem(e){if(!e)throw new Error("Item is undefined or null");const{id:t,vector:n}=e;if(!n)throw new Error("Vector is undefined or null");if(null===this.dimension)this.dimension=n.length;else if(n.length!==this.dimension)throw new Error(`Vector dimension mismatch: expected ${this.dimension}, got ${n.length}`);const r=this.getRandomLevel(),a={id:t,vector:n,connections:new Map};for(let e=0;e<=r;e++)a.connections.set(e,new Set);if(0===this.nouns.size)return this.entryPointId=t,this.maxLevel=r,this.nouns.set(t,a),t;if(!this.entryPointId)return console.error("Entry point ID is null"),this.entryPointId=t,this.maxLevel=r,this.nouns.set(t,a),t;const s=this.nouns.get(this.entryPointId);if(!s)return console.error(`Entry point with ID ${this.entryPointId} not found`),this.entryPointId=t,this.maxLevel=r,this.nouns.set(t,a),t;let o=s,i=this.distanceFunction(n,s.vector);for(let e=this.maxLevel;e>r;e--){let t=!0;for(;t;){t=!1;const r=o.connections.get(e)||new Set;for(const e of r){const r=this.nouns.get(e);if(!r)continue;const a=this.distanceFunction(n,r.vector);a<i&&(i=a,o=r,t=!0)}}}for(let e=Math.min(r,this.maxLevel);e>=0;e--){const r=await this.searchLayer(n,o,this.config.efConstruction,e),s=this.selectNeighbors(n,r,this.config.M);for(const[n,r]of s){const r=this.nouns.get(n);r&&(a.connections.get(e).add(n),r.connections.has(e)||r.connections.set(e,new Set),r.connections.get(e).add(t),r.connections.get(e).size>this.config.M&&this.pruneConnections(r,e))}if(r.size>0){const[e,t]=[...r][0];if(t<i){i=t;const n=this.nouns.get(e);n?o=n:console.error(`Nearest noun with ID ${e} not found in addItem`)}}}return r>this.maxLevel&&(this.maxLevel=r,this.entryPointId=t),this.nouns.set(t,a),t}async search(e,t=10){if(0===this.nouns.size)return[];if(!e)throw new Error("Query vector is undefined or null");if(null!==this.dimension&&e.length!==this.dimension)throw new Error(`Query vector dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(!this.entryPointId)return console.error("Entry point ID is null"),[];const n=this.nouns.get(this.entryPointId);if(!n)return console.error(`Entry point with ID ${this.entryPointId} not found`),[];let r=n,a=this.distanceFunction(e,r.vector);for(let t=this.maxLevel;t>0;t--){let n=!0;for(;n;){n=!1;const s=r.connections.get(t)||new Set;if(this.useParallelization&&s.size>=10){const t=[];for(const e of s){const n=this.nouns.get(e);n&&t.push({id:e,vector:n.vector})}const o=await this.calculateDistancesInParallel(e,t);for(const{id:e,distance:t}of o)if(t<a){a=t;const s=this.nouns.get(e);s&&(r=s,n=!0)}}else for(const t of s){const s=this.nouns.get(t);if(!s)continue;const o=this.distanceFunction(e,s.vector);o<a&&(a=o,r=s,n=!0)}}}return[...await this.searchLayer(e,r,Math.max(this.config.efSearch,t),0)].slice(0,t)}removeItem(e){if(!this.nouns.has(e))return!1;const t=this.nouns.get(e);for(const[n,r]of t.connections.entries())for(const t of r){const r=this.nouns.get(t);r&&(r.connections.has(n)&&(r.connections.get(n).delete(e),this.pruneConnections(r,n)))}for(const[t,n]of this.nouns.entries())if(t!==e)for(const[t,r]of n.connections.entries())r.has(e)&&(r.delete(e),this.pruneConnections(n,t));if(this.nouns.delete(e),this.entryPointId===e)if(0===this.nouns.size)this.entryPointId=null,this.maxLevel=0;else{let e=0,t=null;for(const[n,r]of this.nouns.entries()){if(0===r.connections.size)continue;const a=Math.max(...r.connections.keys());a>=e&&(e=a,t=n)}this.entryPointId=t,this.maxLevel=e}return!0}getNouns(){return new Map(this.nouns)}clear(){this.nouns.clear(),this.entryPointId=null,this.maxLevel=0}size(){return this.nouns.size}getDistanceFunction(){return this.distanceFunction}getEntryPointId(){return this.entryPointId}getMaxLevel(){return this.maxLevel}getDimension(){return this.dimension}getConfig(){return{...this.config}}async searchLayer(e,t,n,r){const a=new Set([t.id]),s=new Map;s.set(t.id,this.distanceFunction(e,t.vector));const o=new Map;for(o.set(t.id,this.distanceFunction(e,t.vector));s.size>0;){const[t,i]=[...s][0];s.delete(t);const c=[...o][o.size-1];if(o.size>=n&&i>c[1])break;const l=this.nouns.get(t);if(!l){console.error(`Noun with ID ${t} not found in searchLayer`);continue}const u=l.connections.get(r)||new Set;if(this.useParallelization&&u.size>=10){const t=[];for(const e of u)if(!a.has(e)){a.add(e);const n=this.nouns.get(e);if(!n)continue;t.push({id:e,vector:n.vector})}if(t.length>0){const r=await this.calculateDistancesInParallel(e,t);for(const{id:e,distance:t}of r)if((o.size<n||t<c[1])&&(s.set(e,t),o.set(e,t),o.size>n)){const e=[...o].sort((e,t)=>e[1]-t[1]);o.clear();for(let t=0;t<n;t++)o.set(e[t][0],e[t][1])}}}else for(const t of u)if(!a.has(t)){a.add(t);const r=this.nouns.get(t);if(!r)continue;const i=this.distanceFunction(e,r.vector);if((o.size<n||i<c[1])&&(s.set(t,i),o.set(t,i),o.size>n)){const e=[...o].sort((e,t)=>e[1]-t[1]);o.clear();for(let t=0;t<n;t++)o.set(e[t][0],e[t][1])}}}return new Map([...o].sort((e,t)=>e[1]-t[1]))}selectNeighbors(e,t,n){if(t.size<=n)return t;const r=[...t].sort((e,t)=>e[1]-t[1]),a=new Map;for(let e=0;e<Math.min(n,r.length);e++)a.set(r[e][0],r[e][1]);return a}pruneConnections(e,t){const n=e.connections.get(t);if(n.size<=this.config.M)return;const r=new Map,a=new Set;for(const t of n){const n=this.nouns.get(t);n&&(r.set(t,this.distanceFunction(e.vector,n.vector)),a.add(t))}if(0===r.size)return void e.connections.set(t,new Set);const s=this.selectNeighbors(e.vector,r,this.config.M);e.connections.set(t,new Set(s.keys()))}getRandomLevel(){const e=Math.random();return Math.floor(-Math.log(e)*(1/Math.log(this.config.M)))}}const ie={M:16,efConstruction:200,efSearch:50,ml:16,memoryThreshold:1073741824,productQuantization:{enabled:!1,numSubvectors:16,numCentroids:256},useDiskBasedIndex:!1};class ce{constructor(e=16,t=256){this.centroids=[],this.subvectorSize=0,this.initialized=!1,this.dimension=0,this.numSubvectors=e,this.numCentroids=t}train(e){if(0===e.length)throw new Error("Cannot train product quantizer with empty vector set");this.dimension=e[0].length,this.subvectorSize=Math.ceil(this.dimension/this.numSubvectors);for(let t=0;t<this.numSubvectors;t++){const n=e.map(e=>{const n=t*this.subvectorSize,r=Math.min(n+this.subvectorSize,this.dimension);return e.slice(n,r)});this.centroids[t]=this.kMeansPlusPlus(n,this.numCentroids)}this.initialized=!0}quantize(e){if(!this.initialized)throw new Error("Product quantizer not initialized. Call train() first.");if(e.length!==this.dimension)throw new Error(`Vector dimension mismatch: expected ${this.dimension}, got ${e.length}`);const t=[];for(let n=0;n<this.numSubvectors;n++){const r=n*this.subvectorSize,a=Math.min(r+this.subvectorSize,this.dimension),s=e.slice(r,a);let o=Number.MAX_VALUE,i=0;for(let e=0;e<this.centroids[n].length;e++){const t=this.centroids[n][e],r=this.euclideanDistanceSquared(s,t);r<o&&(o=r,i=e)}t.push(i)}return t}reconstruct(e){if(!this.initialized)throw new Error("Product quantizer not initialized. Call train() first.");if(e.length!==this.numSubvectors)throw new Error(`Code length mismatch: expected ${this.numSubvectors}, got ${e.length}`);const t=[];for(let n=0;n<this.numSubvectors;n++){const r=e[n],a=this.centroids[n][r];for(const e of a)t.push(e)}return t.slice(0,this.dimension)}euclideanDistanceSquared(e,t){let n=0;const r=Math.min(e.length,t.length);for(let a=0;a<r;a++){const r=e[a]-t[a];n+=r*r}return n}kMeansPlusPlus(e,t){if(e.length<t)return[...e];const n=[],r=Math.floor(Math.random()*e.length);n.push([...e[r]]);for(let r=1;r<t;r++){const t=e.map(e=>{let t=Number.MAX_VALUE;for(const r of n){const n=this.euclideanDistanceSquared(e,r);t=Math.min(t,n)}return t}),r=t.reduce((e,t)=>e+t,0);let a=Math.random()*r,s=0;for(let e=0;e<t.length;e++)if(a-=t[e],a<=0){s=e;break}n.push([...e[s]])}return n}getCentroids(){return this.centroids}setCentroids(e){this.centroids=e,this.numSubvectors=e.length,this.numCentroids=e[0].length,this.initialized=!0}getDimension(){return this.dimension}setDimension(e){this.dimension=e,this.subvectorSize=Math.ceil(e/this.numSubvectors)}}class le extends oe{constructor(e={},t,n=null){super(e,t),this.productQuantizer=null,this.storage=null,this.useDiskBasedIndex=!1,this.useProductQuantization=!1,this.quantizedVectors=new Map,this.memoryUsage=0,this.vectorCount=0,this.memoryUpdateLock=Promise.resolve(),this.optimizedConfig={...ie,...e},this.storage=n,this.optimizedConfig.productQuantization?.enabled&&(this.useProductQuantization=!0,this.productQuantizer=new ce(this.optimizedConfig.productQuantization.numSubvectors,this.optimizedConfig.productQuantization.numCentroids)),this.useDiskBasedIndex=this.optimizedConfig.useDiskBasedIndex||!1}async updateMemoryUsage(e,t){this.memoryUpdateLock=this.memoryUpdateLock.then(async()=>{this.memoryUsage=Math.max(0,this.memoryUsage+e),this.vectorCount=Math.max(0,this.vectorCount+t)}),await this.memoryUpdateLock}async getMemoryUsageAsync(){return await this.memoryUpdateLock,{memoryUsage:this.memoryUsage,vectorCount:this.vectorCount}}async addItem(e){if(!e)throw new Error("Item is undefined or null");const{id:t,vector:n}=e;if(!n)throw new Error("Vector is undefined or null");const r=8*n.length+this.optimizedConfig.M*this.optimizedConfig.ml*16;await this.updateMemoryUsage(r,1);const a=await this.getMemoryUsageAsync();if(this.useProductQuantization&&a.memoryUsage>this.optimizedConfig.memoryThreshold&&this.productQuantizer&&!this.productQuantizer.getDimension()&&this.initializeProductQuantizer(),this.useProductQuantization&&this.productQuantizer&&this.productQuantizer.getDimension()>0){const e=this.productQuantizer.quantize(n);this.quantizedVectors.set(t,e);const r=this.productQuantizer.reconstruct(e);return await super.addItem({id:t,vector:r})}if(this.useDiskBasedIndex&&this.storage){const e={id:t,vector:n,connections:new Map};this.storage.saveNoun(e).catch(e=>{console.error(`Failed to save noun ${t} to storage:`,e)})}return await super.addItem(e)}async search(e,t=10){if(!e)throw new Error("Query vector is undefined or null");if(this.useProductQuantization&&this.productQuantizer&&this.productQuantizer.getDimension()>0){const n=this.productQuantizer.quantize(e),r=this.productQuantizer.reconstruct(n);return await super.search(r,t)}return await super.search(e,t)}removeItem(e){return this.useProductQuantization&&this.quantizedVectors.delete(e),this.useDiskBasedIndex&&this.storage&&this.storage.deleteNoun(e).catch(t=>{console.error(`Failed to delete noun ${e} from storage:`,t)}),this.getMemoryUsageAsync().then(e=>{if(e.vectorCount>0){const t=e.memoryUsage/e.vectorCount;this.updateMemoryUsage(-t,-1)}}).catch(e=>{console.error("Failed to update memory usage after removal:",e)}),super.removeItem(e)}async clear(){this.useProductQuantization&&(this.quantizedVectors.clear(),this.productQuantizer=new ce(this.optimizedConfig.productQuantization.numSubvectors,this.optimizedConfig.productQuantization.numCentroids));const e=await this.getMemoryUsageAsync();await this.updateMemoryUsage(-e.memoryUsage,-e.vectorCount),super.clear()}initializeProductQuantizer(){if(!this.productQuantizer)return;const e=super.getNouns(),t=[];for(const[n,r]of e)t.push(r.vector);if(t.length>0){this.productQuantizer.train(t);for(const[t,n]of e){const e=this.productQuantizer.quantize(n.vector);this.quantizedVectors.set(t,e)}console.log(`Initialized product quantizer with ${t.length} vectors`)}}getProductQuantizer(){return this.productQuantizer}getOptimizedConfig(){return{...this.optimizedConfig}}getMemoryUsage(){return this.memoryUsage}setStorage(e){this.storage=e}getStorage(){return this.storage}setUseDiskBasedIndex(e){this.useDiskBasedIndex=e}getUseDiskBasedIndex(){return this.useDiskBasedIndex}setUseProductQuantization(e){this.useProductQuantization=e}getUseProductQuantization(){return this.useProductQuantization}}class ue{constructor(){this.statisticsCache=null,this.statisticsBatchUpdateTimerId=null,this.statisticsModified=!1,this.lastStatisticsFlushTime=0,this.MIN_FLUSH_INTERVAL_MS=5e3,this.MAX_FLUSH_DELAY_MS=3e4}async saveStatistics(e){this.statisticsCache={nounCount:{...e.nounCount},verbCount:{...e.verbCount},metadataCount:{...e.metadataCount},hnswIndexSize:e.hnswIndexSize,lastUpdated:e.lastUpdated},this.scheduleBatchUpdate()}async getStatistics(){if(this.statisticsCache)return{nounCount:{...this.statisticsCache.nounCount},verbCount:{...this.statisticsCache.verbCount},metadataCount:{...this.statisticsCache.metadataCount},hnswIndexSize:this.statisticsCache.hnswIndexSize,lastUpdated:this.statisticsCache.lastUpdated};const e=await this.getStatisticsData();return e&&(this.statisticsCache={nounCount:{...e.nounCount},verbCount:{...e.verbCount},metadataCount:{...e.metadataCount},hnswIndexSize:e.hnswIndexSize,lastUpdated:e.lastUpdated}),e}scheduleBatchUpdate(){if(this.statisticsModified=!0,null!==this.statisticsBatchUpdateTimerId)return;const e=Date.now()-this.lastStatisticsFlushTime<this.MIN_FLUSH_INTERVAL_MS?this.MAX_FLUSH_DELAY_MS:this.MIN_FLUSH_INTERVAL_MS;this.statisticsBatchUpdateTimerId=setTimeout(()=>{this.flushStatistics()},e)}async flushStatistics(){if(null!==this.statisticsBatchUpdateTimerId&&(clearTimeout(this.statisticsBatchUpdateTimerId),this.statisticsBatchUpdateTimerId=null),this.statisticsModified&&this.statisticsCache)try{await this.saveStatisticsData(this.statisticsCache),this.lastStatisticsFlushTime=Date.now(),this.statisticsModified=!1}catch(e){console.error("Failed to flush statistics data:",e),this.statisticsModified=!0}}async incrementStatistic(e,t,n=1){let r=this.statisticsCache;r||(r=await this.getStatisticsData(),r||(r=this.createDefaultStatistics()),this.statisticsCache={nounCount:{...r.nounCount},verbCount:{...r.verbCount},metadataCount:{...r.metadataCount},hnswIndexSize:r.hnswIndexSize,lastUpdated:r.lastUpdated});const a={noun:this.statisticsCache.nounCount,verb:this.statisticsCache.verbCount,metadata:this.statisticsCache.metadataCount}[e];a[t]=(a[t]||0)+n,this.statisticsCache.lastUpdated=(new Date).toISOString(),this.scheduleBatchUpdate()}async decrementStatistic(e,t,n=1){let r=this.statisticsCache;r||(r=await this.getStatisticsData(),r||(r=this.createDefaultStatistics()),this.statisticsCache={nounCount:{...r.nounCount},verbCount:{...r.verbCount},metadataCount:{...r.metadataCount},hnswIndexSize:r.hnswIndexSize,lastUpdated:r.lastUpdated});const a={noun:this.statisticsCache.nounCount,verb:this.statisticsCache.verbCount,metadata:this.statisticsCache.metadataCount}[e];a[t]=Math.max(0,(a[t]||0)-n),this.statisticsCache.lastUpdated=(new Date).toISOString(),this.scheduleBatchUpdate()}async updateHnswIndexSize(e){let t=this.statisticsCache;t||(t=await this.getStatisticsData(),t||(t=this.createDefaultStatistics()),this.statisticsCache={nounCount:{...t.nounCount},verbCount:{...t.verbCount},metadataCount:{...t.metadataCount},hnswIndexSize:t.hnswIndexSize,lastUpdated:t.lastUpdated}),this.statisticsCache.hnswIndexSize=e,this.statisticsCache.lastUpdated=(new Date).toISOString(),this.scheduleBatchUpdate()}async flushStatisticsToStorage(){this.statisticsCache&&this.statisticsModified&&await this.flushStatistics()}createDefaultStatistics(){return{nounCount:{},verbCount:{},metadataCount:{},hnswIndexSize:0,lastUpdated:(new Date).toISOString()}}}const de="nouns",he="verbs",pe="metadata",fe="index",me="statistics";class ge extends ue{constructor(){super(...arguments),this.isInitialized=!1}async ensureInitialized(){this.isInitialized||await this.init()}async saveNoun(e){return await this.ensureInitialized(),this.saveNoun_internal(e)}async getNoun(e){return await this.ensureInitialized(),this.getNoun_internal(e)}async getAllNouns(){return await this.ensureInitialized(),this.getAllNouns_internal()}async getNounsByNounType(e){return await this.ensureInitialized(),this.getNounsByNounType_internal(e)}async deleteNoun(e){return await this.ensureInitialized(),this.deleteNoun_internal(e)}async saveVerb(e){return await this.ensureInitialized(),this.saveVerb_internal(e)}async getVerb(e){return await this.ensureInitialized(),this.getVerb_internal(e)}async getAllVerbs(){return await this.ensureInitialized(),this.getAllVerbs_internal()}async getVerbsBySource(e){return await this.ensureInitialized(),this.getVerbsBySource_internal(e)}async getVerbsByTarget(e){return await this.ensureInitialized(),this.getVerbsByTarget_internal(e)}async getVerbsByType(e){return await this.ensureInitialized(),this.getVerbsByType_internal(e)}async deleteVerb(e){return await this.ensureInitialized(),this.deleteVerb_internal(e)}mapToObject(e,t=e=>e){const n={};for(const[r,a]of e.entries())n[r.toString()]=t(a);return n}}class ye extends ge{constructor(){super(),this.nouns=new Map,this.verbs=new Map,this.metadata=new Map,this.statistics=null}async init(){this.isInitialized=!0}async saveNoun_internal(e){const t={id:e.id,vector:[...e.vector],connections:new Map};for(const[n,r]of e.connections.entries())t.connections.set(n,new Set(r));this.nouns.set(e.id,t)}async getNoun_internal(e){const t=this.nouns.get(e);if(!t)return null;const n={id:t.id,vector:[...t.vector],connections:new Map};for(const[e,r]of t.connections.entries())n.connections.set(e,new Set(r));return n}async getAllNouns_internal(){const e=[];for(const[t,n]of this.nouns.entries()){const t={id:n.id,vector:[...n.vector],connections:new Map};for(const[e,r]of n.connections.entries())t.connections.set(e,new Set(r));e.push(t)}return e}async getNounsByNounType_internal(e){const t=[];for(const[n,r]of this.nouns.entries()){const a=await this.getMetadata(n);if(a&&a.noun===e){const e={id:r.id,vector:[...r.vector],connections:new Map};for(const[t,n]of r.connections.entries())e.connections.set(t,new Set(n));t.push(e)}}return t}async deleteNoun_internal(e){this.nouns.delete(e)}async saveVerb_internal(e){const t={id:e.id,vector:[...e.vector],connections:new Map,sourceId:e.sourceId,targetId:e.targetId,source:e.sourceId||e.source,target:e.targetId||e.target,verb:e.type||e.verb,type:e.type||e.verb,weight:e.weight,metadata:e.metadata};for(const[n,r]of e.connections.entries())t.connections.set(n,new Set(r));this.verbs.set(e.id,t)}async getVerb_internal(e){const t=this.verbs.get(e);if(!t)return null;const n={seconds:Math.floor(Date.now()/1e3),nanoseconds:Date.now()%1e3*1e6},r={id:t.id,vector:[...t.vector],connections:new Map,sourceId:t.sourceId||t.source||"",targetId:t.targetId||t.target||"",source:t.sourceId||t.source||"",target:t.targetId||t.target||"",verb:t.type||t.verb,type:t.type||t.verb,weight:t.weight,metadata:t.metadata,createdAt:t.createdAt||n,updatedAt:t.updatedAt||n,createdBy:t.createdBy||{augmentation:"unknown",version:"1.0"}};for(const[e,n]of t.connections.entries())r.connections.set(e,new Set(n));return r}async getAllVerbs_internal(){const e=[];for(const[t,n]of this.verbs.entries()){const t={seconds:Math.floor(Date.now()/1e3),nanoseconds:Date.now()%1e3*1e6},r={augmentation:"unknown",version:"1.0"},a={id:n.id,vector:[...n.vector],connections:new Map,sourceId:n.sourceId||n.source||"",targetId:n.targetId||n.target||"",source:n.sourceId||n.source||"",target:n.targetId||n.target||"",verb:n.type||n.verb,weight:n.weight,metadata:n.metadata,createdAt:n.createdAt||t,updatedAt:n.updatedAt||t,createdBy:n.createdBy||r};for(const[e,t]of n.connections.entries())a.connections.set(e,new Set(t));e.push(a)}return e}async getVerbsBySource_internal(e){return(await this.getAllVerbs_internal()).filter(t=>(t.sourceId||t.source)===e)}async getVerbsByTarget_internal(e){return(await this.getAllVerbs_internal()).filter(t=>(t.targetId||t.target)===e)}async getVerbsByType_internal(e){return(await this.getAllVerbs_internal()).filter(t=>(t.type||t.verb)===e)}async deleteVerb_internal(e){this.verbs.delete(e)}async saveMetadata(e,t){this.metadata.set(e,JSON.parse(JSON.stringify(t)))}async getMetadata(e){const t=this.metadata.get(e);return t?JSON.parse(JSON.stringify(t)):null}async clear(){this.nouns.clear(),this.verbs.clear(),this.metadata.clear(),this.statistics=null}async getStorageStatus(){return{type:"memory",used:0,quota:null,details:{nodeCount:this.nouns.size,edgeCount:this.verbs.size,metadataCount:this.metadata.size}}}async saveStatisticsData(e){this.statistics={nounCount:{...e.nounCount},verbCount:{...e.verbCount},metadataCount:{...e.metadataCount},hnswIndexSize:e.hnswIndexSize,lastUpdated:e.lastUpdated}}async getStatisticsData(){return this.statistics?{nounCount:{...this.statistics.nounCount},verbCount:{...this.statistics.verbCount},metadataCount:{...this.statistics.metadataCount},hnswIndexSize:this.statistics.hnswIndexSize,lastUpdated:this.statistics.lastUpdated}:null}}async function be(e){return e.getFile()}class xe extends ge{constructor(){super(),this.rootDir=null,this.nounsDir=null,this.verbsDir=null,this.metadataDir=null,this.indexDir=null,this.isAvailable=!1,this.isPersistentRequested=!1,this.isPersistentGranted=!1,this.statistics=null,this.activeLocks=new Set,this.lockPrefix="opfs-lock-",this.isAvailable="undefined"!=typeof navigator&&"storage"in navigator&&"getDirectory"in navigator.storage}async init(){if(!this.isInitialized){if(!this.isAvailable)throw new Error("Origin Private File System is not available in this environment");try{const e=await navigator.storage.getDirectory();this.rootDir=await e.getDirectoryHandle("opfs-vector-db",{create:!0}),this.nounsDir=await this.rootDir.getDirectoryHandle(de,{create:!0}),this.verbsDir=await this.rootDir.getDirectoryHandle(he,{create:!0}),this.metadataDir=await this.rootDir.getDirectoryHandle(pe,{create:!0}),this.indexDir=await this.rootDir.getDirectoryHandle(fe,{create:!0}),this.isInitialized=!0}catch(e){throw console.error("Failed to initialize OPFS storage:",e),new Error(`Failed to initialize OPFS storage: ${e}`)}}}isOPFSAvailable(){return this.isAvailable}async requestPersistentStorage(){if(!this.isAvailable)return console.warn("Cannot request persistent storage: OPFS is not available"),!1;try{return this.isPersistentGranted=await navigator.storage.persisted(),this.isPersistentGranted||(this.isPersistentGranted=await navigator.storage.persist()),this.isPersistentRequested=!0,this.isPersistentGranted}catch(e){return console.warn("Failed to request persistent storage:",e),!1}}async isPersistent(){if(!this.isAvailable)return!1;try{return this.isPersistentGranted=await navigator.storage.persisted(),this.isPersistentGranted}catch(e){return console.warn("Failed to check persistent storage status:",e),!1}}async saveNoun_internal(e){await this.ensureInitialized();try{const t={...e,connections:this.mapToObject(e.connections,e=>Array.from(e))},n=await this.nounsDir.getFileHandle(e.id,{create:!0}),r=await n.createWritable();await r.write(JSON.stringify(t)),await r.close()}catch(t){throw console.error(`Failed to save noun ${e.id}:`,t),new Error(`Failed to save noun ${e.id}: ${t}`)}}async getNoun_internal(e){await this.ensureInitialized();try{const t=await this.nounsDir.getFileHandle(e),n=await t.getFile(),r=await n.text(),a=JSON.parse(r),s=new Map;for(const[e,t]of Object.entries(a.connections))s.set(Number(e),new Set(t));return{id:a.id,vector:a.vector,connections:s}}catch(e){return null}}async getAllNouns_internal(){await this.ensureInitialized();const e=[];try{for await(const[t,n]of this.nounsDir.entries())if("file"===n.kind)try{const t=await be(n),r=await t.text(),a=JSON.parse(r),s=new Map;for(const[e,t]of Object.entries(a.connections))s.set(Number(e),new Set(t));e.push({id:a.id,vector:a.vector,connections:s})}catch(e){console.error(`Error reading noun file ${t}:`,e)}}catch(e){console.error("Error reading nouns directory:",e)}return e}async getNounsByNounType_internal(e){return this.getNodesByNounType(e)}async getNodesByNounType(e){await this.ensureInitialized();const t=[];try{for await(const[n,r]of this.nounsDir.entries())if("file"===r.kind)try{const n=await be(r),a=await n.text(),s=JSON.parse(a),o=await this.getMetadata(s.id);if(o&&o.noun===e){const e=new Map;for(const[t,n]of Object.entries(s.connections))e.set(Number(t),new Set(n));t.push({id:s.id,vector:s.vector,connections:e})}}catch(e){console.error(`Error reading node file ${n}:`,e)}}catch(e){console.error("Error reading nouns directory:",e)}return t}async deleteNoun_internal(e){return this.deleteNode(e)}async deleteNode(e){await this.ensureInitialized();try{await this.nounsDir.removeEntry(e)}catch(t){if("NotFoundError"!==t.name)throw console.error(`Error deleting node ${e}:`,t),t}}async saveVerb_internal(e){return this.saveEdge(e)}async saveEdge(e){await this.ensureInitialized();try{const t={...e,connections:this.mapToObject(e.connections,e=>Array.from(e))},n=await this.verbsDir.getFileHandle(e.id,{create:!0}),r=await n.createWritable();await r.write(JSON.stringify(t)),await r.close()}catch(t){throw console.error(`Failed to save edge ${e.id}:`,t),new Error(`Failed to save edge ${e.id}: ${t}`)}}async getVerb_internal(e){return this.getEdge(e)}async getEdge(e){await this.ensureInitialized();try{const t=await this.verbsDir.getFileHandle(e),n=await t.getFile(),r=await n.text(),a=JSON.parse(r),s=new Map;for(const[e,t]of Object.entries(a.connections))s.set(Number(e),new Set(t));const o={seconds:Math.floor(Date.now()/1e3),nanoseconds:Date.now()%1e3*1e6},i={augmentation:"unknown",version:"1.0"};return{id:a.id,vector:a.vector,connections:s,sourceId:a.sourceId||a.source,targetId:a.targetId||a.target,source:a.sourceId||a.source,target:a.targetId||a.target,verb:a.type||a.verb,weight:a.weight,metadata:a.metadata,createdAt:a.createdAt||o,updatedAt:a.updatedAt||o,createdBy:a.createdBy||i}}catch(e){return null}}async getAllVerbs_internal(){return this.getAllEdges()}async getAllEdges(){await this.ensureInitialized();const e=[];try{for await(const[t,n]of this.verbsDir.entries())if("file"===n.kind)try{const t=await be(n),r=await t.text(),a=JSON.parse(r),s=new Map;for(const[e,t]of Object.entries(a.connections))s.set(Number(e),new Set(t));const o={seconds:Math.floor(Date.now()/1e3),nanoseconds:Date.now()%1e3*1e6},i={augmentation:"unknown",version:"1.0"};e.push({id:a.id,vector:a.vector,connections:s,sourceId:a.sourceId||a.source,targetId:a.targetId||a.target,source:a.sourceId||a.source,target:a.targetId||a.target,verb:a.type||a.verb,weight:a.weight,metadata:a.metadata,createdAt:a.createdAt||o,updatedAt:a.updatedAt||o,createdBy:a.createdBy||i})}catch(e){console.error(`Error reading edge file ${t}:`,e)}}catch(e){console.error("Error reading verbs directory:",e)}return e}async getVerbsBySource_internal(e){return this.getEdgesBySource(e)}async getEdgesBySource(e){return(await this.getAllEdges()).filter(t=>(t.sourceId||t.source)===e)}async getVerbsByTarget_internal(e){return this.getEdgesByTarget(e)}async getEdgesByTarget(e){return(await this.getAllEdges()).filter(t=>(t.targetId||t.target)===e)}async getVerbsByType_internal(e){return this.getEdgesByType(e)}async getEdgesByType(e){return(await this.getAllEdges()).filter(t=>(t.type||t.verb)===e)}async deleteVerb_internal(e){return this.deleteEdge(e)}async deleteEdge(e){await this.ensureInitialized();try{await this.verbsDir.removeEntry(e)}catch(t){if("NotFoundError"!==t.name)throw console.error(`Error deleting edge ${e}:`,t),t}}async saveMetadata(e,t){await this.ensureInitialized();try{const n=await this.metadataDir.getFileHandle(e,{create:!0}),r=await n.createWritable();await r.write(JSON.stringify(t)),await r.close()}catch(t){throw console.error(`Failed to save metadata ${e}:`,t),new Error(`Failed to save metadata ${e}: ${t}`)}}async getMetadata(e){await this.ensureInitialized();try{const t=await this.metadataDir.getFileHandle(e),n=await t.getFile(),r=await n.text();return JSON.parse(r)}catch(e){return null}}async clear(){await this.ensureInitialized();const e=async e=>{try{for await(const[t,n]of e.entries())await e.removeEntry(t,{recursive:!0})}catch(e){throw console.error("Error removing directory contents:",e),e}};try{await e(this.nounsDir),await e(this.verbsDir),await e(this.metadataDir),await e(this.indexDir)}catch(e){throw console.error("Error clearing storage:",e),e}}async getStorageStatus(){await this.ensureInitialized();try{let e=0;const t=async e=>{let n=0;try{for await(const[r,a]of e.entries())if("file"===a.kind){n+=(await a.getFile()).size}else"directory"===a.kind&&(n+=await t(a))}catch(e){console.warn("Error calculating size for directory:",e)}return n},n=async e=>{let t=0;try{for await(const[n,r]of e.entries())"file"===r.kind&&t++}catch(e){console.warn("Error counting files in directory:",e)}return t};this.nounsDir&&(e+=await t(this.nounsDir)),this.verbsDir&&(e+=await t(this.verbsDir)),this.metadataDir&&(e+=await t(this.metadataDir)),this.indexDir&&(e+=await t(this.indexDir));let r=null,a={isPersistent:await this.isPersistent(),nounTypes:{}};try{if(navigator.storage&&navigator.storage.estimate){const e=await navigator.storage.estimate();r=e.quota||null,a={...a,usage:e.usage,quota:e.quota,freePercentage:e.quota?(e.quota-(e.usage||0))/e.quota*100:null}}}catch(e){console.warn("Unable to get storage estimate:",e)}this.nounsDir&&(a.nounsCount=await n(this.nounsDir)),this.verbsDir&&(a.verbsCount=await n(this.verbsDir)),this.metadataDir&&(a.metadataCount=await n(this.metadataDir));const s={};if(this.metadataDir)for await(const[e,t]of this.metadataDir.entries())if("file"===t.kind)try{const e=await be(t),n=await e.text(),r=JSON.parse(n);r.noun&&(s[r.noun]=(s[r.noun]||0)+1)}catch(t){console.error(`Error reading metadata file ${e}:`,t)}return a.nounTypes=s,{type:"opfs",used:e,quota:r,details:a}}catch(e){return console.error("Failed to get storage status:",e),{type:"opfs",used:0,quota:null,details:{error:String(e)}}}}getStatisticsKeyForDate(e){return`statistics_${e.getUTCFullYear()}${String(e.getUTCMonth()+1).padStart(2,"0")}${String(e.getUTCDate()).padStart(2,"0")}.json`}getCurrentStatisticsKey(){return this.getStatisticsKeyForDate(new Date)}getLegacyStatisticsKey(){return"statistics.json"}async acquireLock(e,t=3e4){if("undefined"==typeof localStorage)return console.warn("localStorage not available, proceeding without lock"),!1;const n=`${this.lockPrefix}${e}`,r=`${Date.now()}_${Math.random()}_${window.location.href}`,a=Date.now()+t;try{const s=localStorage.getItem(n);if(s)try{if(JSON.parse(s).expiresAt>Date.now())return!1}catch(e){console.warn(`Invalid lock data for ${n}:`,e)}const o={lockValue:r,expiresAt:a,tabId:window.location.href,timestamp:Date.now()};return localStorage.setItem(n,JSON.stringify(o)),this.activeLocks.add(e),setTimeout(()=>{this.releaseLock(e,r).catch(t=>{console.warn(`Failed to auto-release expired lock ${e}:`,t)})},t),!0}catch(t){return console.warn(`Failed to acquire lock ${e}:`,t),!1}}async releaseLock(e,t){if("undefined"==typeof localStorage)return;const n=`${this.lockPrefix}${e}`;try{if(t){const r=localStorage.getItem(n);if(r)try{if(JSON.parse(r).lockValue!==t)return}catch(t){return localStorage.removeItem(n),void this.activeLocks.delete(e)}}localStorage.removeItem(n),this.activeLocks.delete(e)}catch(t){console.warn(`Failed to release lock ${e}:`,t)}}async cleanupExpiredLocks(){if("undefined"!=typeof localStorage)try{const e=Date.now(),t=[];for(let n=0;n<localStorage.length;n++){const r=localStorage.key(n);if(r&&r.startsWith(this.lockPrefix))try{const n=localStorage.getItem(r);if(n){if(JSON.parse(n).expiresAt<=e){t.push(r);const e=r.replace(this.lockPrefix,"");this.activeLocks.delete(e)}}}catch(e){t.push(r)}}t.forEach(e=>{localStorage.removeItem(e)}),t.length>0&&console.log(`Cleaned up ${t.length} expired locks`)}catch(e){console.warn("Failed to cleanup expired locks:",e)}}async saveStatisticsData(e){const t="statistics",n=await this.acquireLock(t,1e4);n||console.warn("Failed to acquire lock for statistics update, proceeding without lock");try{const t=await this.getStatisticsData();let n;if(n=t?{nounCount:{...t.nounCount,...e.nounCount},verbCount:{...t.verbCount,...e.verbCount},metadataCount:{...t.metadataCount,...e.metadataCount},hnswIndexSize:Math.max(e.hnswIndexSize||0,t.hnswIndexSize||0),lastUpdated:(new Date).toISOString()}:{...e,lastUpdated:(new Date).toISOString()},this.statistics={nounCount:{...n.nounCount},verbCount:{...n.verbCount},metadataCount:{...n.metadataCount},hnswIndexSize:n.hnswIndexSize,lastUpdated:n.lastUpdated},await this.ensureInitialized(),!this.indexDir)throw new Error("Index directory not initialized");const r=this.getCurrentStatisticsKey(),a=await this.indexDir.getFileHandle(r,{create:!0}),s=await a.createWritable();if(await s.write(JSON.stringify(this.statistics,null,2)),await s.close(),Math.random()<.1){const e=this.getLegacyStatisticsKey(),t=await this.indexDir.getFileHandle(e,{create:!0}),n=await t.createWritable();await n.write(JSON.stringify(this.statistics,null,2)),await n.close()}}catch(e){throw console.error("Failed to save statistics data:",e),new Error(`Failed to save statistics data: ${e}`)}finally{n&&await this.releaseLock(t)}}async getStatisticsData(){if(this.statistics)return{nounCount:{...this.statistics.nounCount},verbCount:{...this.statistics.verbCount},metadataCount:{...this.statistics.metadataCount},hnswIndexSize:this.statistics.hnswIndexSize,lastUpdated:this.statistics.lastUpdated};try{if(await this.ensureInitialized(),!this.indexDir)throw new Error("Index directory not initialized");const e=this.getCurrentStatisticsKey();try{const t=await this.indexDir.getFileHandle(e,{create:!1}),n=await t.getFile(),r=await n.text();if(this.statistics=JSON.parse(r),this.statistics)return{nounCount:{...this.statistics.nounCount},verbCount:{...this.statistics.verbCount},metadataCount:{...this.statistics.metadataCount},hnswIndexSize:this.statistics.hnswIndexSize,lastUpdated:this.statistics.lastUpdated}}catch(e){const t=new Date;t.setDate(t.getDate()-1);const n=this.getStatisticsKeyForDate(t);try{const e=await this.indexDir.getFileHandle(n,{create:!1}),t=await e.getFile(),r=await t.text();if(this.statistics=JSON.parse(r),this.statistics)return{nounCount:{...this.statistics.nounCount},verbCount:{...this.statistics.verbCount},metadataCount:{...this.statistics.metadataCount},hnswIndexSize:this.statistics.hnswIndexSize,lastUpdated:this.statistics.lastUpdated}}catch(e){const t=this.getLegacyStatisticsKey();try{const e=await this.indexDir.getFileHandle(t,{create:!1}),n=await e.getFile(),r=await n.text();if(this.statistics=JSON.parse(r),this.statistics)return{nounCount:{...this.statistics.nounCount},verbCount:{...this.statistics.verbCount},metadataCount:{...this.statistics.metadataCount},hnswIndexSize:this.statistics.hnswIndexSize,lastUpdated:this.statistics.lastUpdated}}catch(e){return null}}}return this.statistics?this.statistics:null}catch(e){throw console.error("Failed to get statistics data:",e),new Error(`Failed to get statistics data: ${e}`)}}}class we extends Error{constructor(e,t,n=!1,r,a,s){super(e),this.name="BrainyError",this.type=t,this.retryable=n,this.originalError=r,this.attemptNumber=a,this.maxRetries=s,Error.captureStackTrace&&Error.captureStackTrace(this,we)}static timeout(e,t,n){return new we(`Operation '${e}' timed out after ${t}ms`,"TIMEOUT",!0,n)}static network(e,t){return new we(`Network error: ${e}`,"NETWORK",!0,t)}static storage(e,t){return new we(`Storage error: ${e}`,"STORAGE",!0,t)}static notFound(e){return new we(`Resource not found: ${e}`,"NOT_FOUND",!1)}static retryExhausted(e,t,n){return new we(`Operation '${e}' failed after ${t} retry attempts`,"RETRY_EXHAUSTED",!1,n,t,t)}static isRetryable(e){if(e instanceof we)return e.retryable;const t=e.message.toLowerCase(),n=e.name.toLowerCase();return!!(t.includes("timeout")||t.includes("network")||t.includes("connection")||t.includes("econnreset")||t.includes("enotfound")||t.includes("etimedout")||n.includes("timeout"))||!!(t.includes("throttling")||t.includes("rate limit")||t.includes("service unavailable")||t.includes("internal server error")||t.includes("bad gateway")||t.includes("gateway timeout"))}static fromError(e,t){if(e instanceof we)return e;const n=e.message.toLowerCase(),r=e.name.toLowerCase();return n.includes("timeout")||r.includes("timeout")?we.timeout(t||"unknown",0,e):n.includes("network")||n.includes("connection")||n.includes("econnreset")||n.includes("enotfound")||n.includes("etimedout")?we.network(e.message,e):n.includes("nosuchkey")||n.includes("not found")||n.includes("does not exist")?we.notFound(t||"resource"):we.storage(e.message,e)}}const ve={get:3e4,add:6e4,delete:3e4},ke={maxRetries:3,initialDelay:1e3,maxDelay:1e4,backoffMultiplier:2};function Ie(e,t,n,r){const a=t*Math.pow(r,e-1);return Math.min(a,n)}function Se(e){return new Promise(t=>setTimeout(t,e))}async function Te(e,t,n,r={}){return async function(e,t,n={}){const{maxRetries:r=ke.maxRetries,initialDelay:a=ke.initialDelay,maxDelay:s=ke.maxDelay,backoffMultiplier:o=ke.backoffMultiplier}=n;let i;for(let n=1;n<=r+1;n++)try{return await e()}catch(e){if(i=e instanceof Error?e:new Error(String(e)),n>r)break;if(!we.isRetryable(i))throw we.fromError(i,t);const c=Ie(n,a,s,o);console.warn(`Operation '${t}' failed on attempt ${n}/${r+1}. Retrying in ${c}ms. Error: ${i.message}`),await Se(c)}throw we.retryExhausted(t,r,i)}(()=>function(e,t,n){return new Promise((r,a)=>{const s=setTimeout(()=>{a(we.timeout(n,t))},t);e.then(e=>{clearTimeout(s),r(e)}).catch(e=>{clearTimeout(s),a(e)})})}(e(),n,t),t,r)}function Ne(e,t={}){const n={...ve,...t.timeouts},r={...ke,...t.retryPolicy},a=n[e];return async function(e,t){return Te(e,t,a,r)}}class Ce{constructor(e={}){this.getExecutor=Ne("get",e),this.addExecutor=Ne("add",e),this.deleteExecutor=Ne("delete",e)}async executeGet(e,t){return this.getExecutor(e,t)}async executeAdd(e,t){return this.addExecutor(e,t)}async executeDelete(e,t){return this.deleteExecutor(e,t)}}class Ee extends ge{constructor(e){super(),this.s3Client=null,this.statisticsCache=null,this.lockPrefix="locks/",this.activeLocks=new Set,this.changeLogPrefix="change-log/",this.statisticsBatchUpdateTimerId=null,this.statisticsModified=!1,this.lastStatisticsFlushTime=0,this.MIN_FLUSH_INTERVAL_MS=5e3,this.MAX_FLUSH_DELAY_MS=3e4,this.bucketName=e.bucketName,this.region=e.region||"auto",this.endpoint=e.endpoint,this.accountId=e.accountId,this.accessKeyId=e.accessKeyId,this.secretAccessKey=e.secretAccessKey,this.sessionToken=e.sessionToken,this.serviceType=e.serviceType||"s3",this.operationExecutors=new Ce(e.operationConfig),this.nounPrefix=`${de}/`,this.verbPrefix=`${he}/`,this.metadataPrefix=`${pe}/`,this.indexPrefix=`${fe}/`}async init(){if(!this.isInitialized)try{const{S3Client:e}=await import("@aws-sdk/client-s3"),t={region:this.region,credentials:{accessKeyId:this.accessKeyId,secretAccessKey:this.secretAccessKey}};this.sessionToken&&(t.credentials.sessionToken=this.sessionToken),this.endpoint&&(t.endpoint=this.endpoint),"r2"===this.serviceType&&this.accountId&&(t.endpoint=`https://${this.accountId}.r2.cloudflarestorage.com`),this.s3Client=new e(t);const{HeadBucketCommand:n}=await import("@aws-sdk/client-s3");await this.s3Client.send(new n({Bucket:this.bucketName})),this.isInitialized=!0}catch(e){throw console.error(`Failed to initialize ${this.serviceType} storage:`,e),new Error(`Failed to initialize ${this.serviceType} storage: ${e}`)}}async saveNoun_internal(e){return this.saveNode(e)}async saveNode(e){await this.ensureInitialized();try{console.log(`Saving node ${e.id} to bucket ${this.bucketName}`);const t={...e,connections:this.mapToObject(e.connections,e=>Array.from(e))},{PutObjectCommand:n}=await import("@aws-sdk/client-s3"),r=`${this.nounPrefix}${e.id}.json`,a=JSON.stringify(t,null,2);console.log(`Saving node to key: ${r}`),console.log(`Node data: ${a.substring(0,100)}${a.length>100?"...":""}`);const s=await this.s3Client.send(new n({Bucket:this.bucketName,Key:r,Body:a,ContentType:"application/json"}));console.log(`Node ${e.id} saved successfully:`,s),await this.appendToChangeLog({timestamp:Date.now(),operation:"add",entityType:"noun",entityId:e.id,data:{vector:e.vector,metadata:e.metadata}});const{GetObjectCommand:o}=await import("@aws-sdk/client-s3");try{const t=await this.s3Client.send(new o({Bucket:this.bucketName,Key:r}));t&&t.Body?console.log(`Verified node ${e.id} was saved correctly`):console.error(`Failed to verify node ${e.id} was saved correctly: no response or body`)}catch(t){console.error(`Failed to verify node ${e.id} was saved correctly:`,t)}}catch(t){throw console.error(`Failed to save node ${e.id}:`,t),new Error(`Failed to save node ${e.id}: ${t}`)}}async getNoun_internal(e){return this.getNode(e)}async getNode(e){await this.ensureInitialized();try{const{GetObjectCommand:t}=await import("@aws-sdk/client-s3");console.log(`Getting node ${e} from bucket ${this.bucketName}`);const n=`${this.nounPrefix}${e}.json`;console.log(`Looking for node at key: ${n}`);const r=await this.s3Client.send(new t({Bucket:this.bucketName,Key:n}));if(!r||!r.Body)return console.log(`No node found for ${e}`),null;const a=await r.Body.transformToString();console.log(`Retrieved node body: ${a.substring(0,100)}${a.length>100?"...":""}`);try{const t=JSON.parse(a);if(console.log(`Parsed node data for ${e}:`,t),!(t&&t.id&&t.vector&&t.connections))return console.error(`Invalid node data for ${e}:`,t),null;const n=new Map;for(const[e,r]of Object.entries(t.connections))n.set(Number(e),new Set(r));const r={id:t.id,vector:t.vector,connections:n};return console.log(`Successfully retrieved node ${e}:`,r),r}catch(t){return console.error(`Failed to parse node data for ${e}:`,t),null}}catch(t){return console.log(`Error getting node for ${e}:`,t),null}}async getAllNouns_internal(){return this.getAllNodes()}async getAllNodes(){await this.ensureInitialized();try{const{ListObjectsV2Command:e,GetObjectCommand:t}=await import("@aws-sdk/client-s3");console.log(`Getting all nodes from bucket ${this.bucketName} with prefix ${this.nounPrefix}`);const n=await this.s3Client.send(new e({Bucket:this.bucketName,Prefix:this.nounPrefix})),r=[];if(!n||!n.Contents||0===n.Contents.length)return console.log(`No nodes found in bucket ${this.bucketName} with prefix ${this.nounPrefix}`),r;console.log(`Found ${n.Contents.length} nodes in bucket ${this.bucketName}`),console.log("Keys found:");for(const e of n.Contents)e&&e.Key&&console.log(`- ${e.Key}`);const a=n.Contents.map(async e=>{if(!e||!e.Key)return console.log("Skipping undefined object or object without Key"),null;try{const n=e.Key.replace(this.nounPrefix,"").replace(".json","");console.log(`Getting node with ID ${n} from key ${e.Key}`);const r=await this.s3Client.send(new t({Bucket:this.bucketName,Key:e.Key}));if(!r||!r.Body)return console.log(`No response or response body for node ${n}`),null;const a=await r.Body.transformToString();console.log(`Retrieved node body for ${n}: ${a.substring(0,100)}${a.length>100?"...":""}`);try{const e=JSON.parse(a);if(console.log(`Parsed node data for ${n}:`,e),!(e&&e.id&&e.vector&&e.connections))return console.error(`Invalid node data for ${n}:`,e),null;const t=new Map;for(const[n,r]of Object.entries(e.connections))t.set(Number(n),new Set(r));const r={id:e.id,vector:e.vector,connections:t};return console.log(`Successfully retrieved node ${n}:`,r),r}catch(e){return console.error(`Failed to parse node data for ${n}:`,e),null}}catch(t){return console.error(`Error getting node from ${e.Key}:`,t),null}}),s=(await Promise.all(a)).filter(e=>null!==e);console.log(`Returning ${s.length} nodes`);for(const e of s)console.log(`- Node ${e.id}`);return s}catch(e){return console.error("Failed to get all nodes:",e),[]}}async getNounsByNounType_internal(e){return this.getNodesByNounType(e)}async getNodesByNounType(e){await this.ensureInitialized();try{const t=await this.getAllNodes(),n=[];for(const r of t){const t=await this.getMetadata(r.id);t&&t.noun===e&&n.push(r)}return n}catch(t){return console.error(`Failed to get nodes by noun type ${e}:`,t),[]}}async deleteNoun_internal(e){return this.deleteNode(e)}async deleteNode(e){await this.ensureInitialized();try{const{DeleteObjectCommand:t}=await import("@aws-sdk/client-s3");await this.s3Client.send(new t({Bucket:this.bucketName,Key:`${this.nounPrefix}${e}.json`})),await this.appendToChangeLog({timestamp:Date.now(),operation:"delete",entityType:"noun",entityId:e})}catch(t){throw console.error(`Failed to delete node ${e}:`,t),new Error(`Failed to delete node ${e}: ${t}`)}}async saveVerb_internal(e){return this.saveEdge(e)}async saveEdge(e){await this.ensureInitialized();try{const t={...e,connections:this.mapToObject(e.connections,e=>Array.from(e))},{PutObjectCommand:n}=await import("@aws-sdk/client-s3");await this.s3Client.send(new n({Bucket:this.bucketName,Key:`${this.verbPrefix}${e.id}.json`,Body:JSON.stringify(t,null,2),ContentType:"application/json"})),await this.appendToChangeLog({timestamp:Date.now(),operation:"add",entityType:"verb",entityId:e.id,data:{sourceId:e.sourceId||e.source,targetId:e.targetId||e.target,type:e.type||e.verb,vector:e.vector,metadata:e.metadata}})}catch(t){throw console.error(`Failed to save edge ${e.id}:`,t),new Error(`Failed to save edge ${e.id}: ${t}`)}}async getVerb_internal(e){return this.getEdge(e)}async getEdge(e){await this.ensureInitialized();try{const{GetObjectCommand:t}=await import("@aws-sdk/client-s3");console.log(`Getting edge ${e} from bucket ${this.bucketName}`);const n=`${this.verbPrefix}${e}.json`;console.log(`Looking for edge at key: ${n}`);const r=await this.s3Client.send(new t({Bucket:this.bucketName,Key:n}));if(!r||!r.Body)return console.log(`No edge found for ${e}`),null;const a=await r.Body.transformToString();console.log(`Retrieved edge body: ${a.substring(0,100)}${a.length>100?"...":""}`);try{const t=JSON.parse(a);if(console.log(`Parsed edge data for ${e}:`,t),!(t&&t.id&&t.vector&&t.connections&&(t.sourceId||t.source)&&(t.targetId||t.target)&&(t.type||t.verb)))return console.error(`Invalid edge data for ${e}:`,t),null;const n=new Map;for(const[e,r]of Object.entries(t.connections))n.set(Number(e),new Set(r));const r={seconds:Math.floor(Date.now()/1e3),nanoseconds:Date.now()%1e3*1e6},s={augmentation:"unknown",version:"1.0"},o={id:t.id,vector:t.vector,connections:n,sourceId:t.sourceId||t.source,targetId:t.targetId||t.target,source:t.sourceId||t.source,target:t.targetId||t.target,verb:t.type||t.verb,type:t.type||t.verb,weight:t.weight||1,metadata:t.metadata||{},createdAt:t.createdAt||r,updatedAt:t.updatedAt||r,createdBy:t.createdBy||s};return console.log(`Successfully retrieved edge ${e}:`,o),o}catch(t){return console.error(`Failed to parse edge data for ${e}:`,t),null}}catch(t){return console.log(`Error getting edge for ${e}:`,t),null}}async getAllVerbs_internal(){return this.getAllEdges()}async getAllEdges(){await this.ensureInitialized();try{const{ListObjectsV2Command:e,GetObjectCommand:t}=await import("@aws-sdk/client-s3"),n=await this.s3Client.send(new e({Bucket:this.bucketName,Prefix:this.verbPrefix})),r=[];if(!n.Contents||0===n.Contents.length)return r;const a=n.Contents.map(async e=>{try{e.Key.replace(this.verbPrefix,"").replace(".json","");const n=await this.s3Client.send(new t({Bucket:this.bucketName,Key:e.Key})),r=await n.Body.transformToString(),a=JSON.parse(r),s=new Map;for(const[e,t]of Object.entries(a.connections))s.set(Number(e),new Set(t));const o={seconds:Math.floor(Date.now()/1e3),nanoseconds:Date.now()%1e3*1e6},i={augmentation:"unknown",version:"1.0"};return{id:a.id,vector:a.vector,connections:s,sourceId:a.sourceId||a.source,targetId:a.targetId||a.target,source:a.sourceId||a.source,target:a.targetId||a.target,verb:a.type||a.verb,type:a.type||a.verb,weight:a.weight||1,metadata:a.metadata||{},createdAt:a.createdAt||o,updatedAt:a.updatedAt||o,createdBy:a.createdBy||i}}catch(t){return console.error(`Error getting edge from ${e.Key}:`,t),null}});return(await Promise.all(a)).filter(e=>null!==e)}catch(e){return console.error("Failed to get all edges:",e),[]}}async getVerbsBySource_internal(e){return this.getEdgesBySource(e)}async getEdgesBySource(e){return(await this.getAllEdges()).filter(t=>(t.sourceId||t.source)===e)}async getVerbsByTarget_internal(e){return this.getEdgesByTarget(e)}async getEdgesByTarget(e){return(await this.getAllEdges()).filter(t=>(t.targetId||t.target)===e)}async getVerbsByType_internal(e){return this.getEdgesByType(e)}async getEdgesByType(e){return(await this.getAllEdges()).filter(t=>(t.type||t.verb)===e)}async deleteVerb_internal(e){return this.deleteEdge(e)}async deleteEdge(e){await this.ensureInitialized();try{const{DeleteObjectCommand:t}=await import("@aws-sdk/client-s3");await this.s3Client.send(new t({Bucket:this.bucketName,Key:`${this.verbPrefix}${e}.json`})),await this.appendToChangeLog({timestamp:Date.now(),operation:"delete",entityType:"verb",entityId:e})}catch(t){throw console.error(`Failed to delete edge ${e}:`,t),new Error(`Failed to delete edge ${e}: ${t}`)}}async saveMetadata(e,t){await this.ensureInitialized();try{console.log(`Saving metadata for ${e} to bucket ${this.bucketName}`);const{PutObjectCommand:n}=await import("@aws-sdk/client-s3"),r=`${this.metadataPrefix}${e}.json`,a=JSON.stringify(t,null,2);console.log(`Saving metadata to key: ${r}`),console.log(`Metadata: ${a}`);const s=await this.s3Client.send(new n({Bucket:this.bucketName,Key:r,Body:a,ContentType:"application/json"}));console.log(`Metadata for ${e} saved successfully:`,s),await this.appendToChangeLog({timestamp:Date.now(),operation:"add",entityType:"metadata",entityId:e,data:t});const{GetObjectCommand:o}=await import("@aws-sdk/client-s3");try{const t=await this.s3Client.send(new o({Bucket:this.bucketName,Key:r}));if(t&&t.Body){const n=await t.Body.transformToString();console.log(`Verified metadata for ${e} was saved correctly: ${n}`)}else console.error(`Failed to verify metadata for ${e} was saved correctly: no response or body`)}catch(t){console.error(`Failed to verify metadata for ${e} was saved correctly:`,t)}}catch(t){throw console.error(`Failed to save metadata for ${e}:`,t),new Error(`Failed to save metadata for ${e}: ${t}`)}}async getMetadata(e){return await this.ensureInitialized(),this.operationExecutors.executeGet(async()=>{try{const{GetObjectCommand:t}=await import("@aws-sdk/client-s3");console.log(`Getting metadata for ${e} from bucket ${this.bucketName}`);const n=`${this.metadataPrefix}${e}.json`;console.log(`Looking for metadata at key: ${n}`);const r=await this.s3Client.send(new t({Bucket:this.bucketName,Key:n}));if(!r||!r.Body)return console.log(`No metadata found for ${e}`),null;const a=await r.Body.transformToString();console.log(`Retrieved metadata body: ${a}`);try{const t=JSON.parse(a);return console.log(`Successfully retrieved metadata for ${e}:`,t),t}catch(t){return console.error(`Failed to parse metadata for ${e}:`,t),null}}catch(t){if("NoSuchKey"===t.name||t.message&&(t.message.includes("NoSuchKey")||t.message.includes("not found")||t.message.includes("does not exist")))return console.log(`Metadata not found for ${e}`),null;throw we.fromError(t,`getMetadata(${e})`)}},`getMetadata(${e})`)}async clear(){await this.ensureInitialized();try{const{ListObjectsV2Command:e,DeleteObjectCommand:t}=await import("@aws-sdk/client-s3"),n=async n=>{const r=await this.s3Client.send(new e({Bucket:this.bucketName,Prefix:n}));if(r&&r.Contents&&0!==r.Contents.length)for(const e of r.Contents)e&&e.Key&&await this.s3Client.send(new t({Bucket:this.bucketName,Key:e.Key}))};await n(this.nounPrefix),await n(this.verbPrefix),await n(this.metadataPrefix),await n(this.indexPrefix)}catch(e){throw console.error("Failed to clear storage:",e),new Error(`Failed to clear storage: ${e}`)}}async getStorageStatus(){await this.ensureInitialized();try{const{ListObjectsV2Command:e}=await import("@aws-sdk/client-s3");let t=0,n=0,r=0,a=0;const s=async t=>{let n=0,r=0;const a=await this.s3Client.send(new e({Bucket:this.bucketName,Prefix:t}));if(!a||!a.Contents||0===a.Contents.length)return{size:n,count:r};for(const e of a.Contents)if(e){n+=("number"==typeof e.Size?e.Size:e.Size?parseInt(e.Size.toString(),10):0)||0,r++,0===n&&r>0&&(n=100*r)}return{size:n,count:r}},o=await s(this.nounPrefix),i=await s(this.verbPrefix),c=await s(this.metadataPrefix),l=await s(this.indexPrefix);t=o.size+i.size+c.size+l.size,n=o.count,r=i.count,a=c.count,0===t&&(n>0||r>0||a>0)&&(console.log(`Setting minimum size for ${n} nodes, ${r} edges, and ${a} metadata objects`),t=100*(n+r+a)),(n>0||r>0||a>0)&&(console.log(`Ensuring positive size for storage status with ${n} nodes, ${r} edges, and ${a} metadata objects`),t=Math.max(t,1));const u={},d=await this.s3Client.send(new e({Bucket:this.bucketName,Prefix:this.metadataPrefix}));if(d&&d.Contents){const{GetObjectCommand:e}=await import("@aws-sdk/client-s3");for(const t of d.Contents)if(t&&t.Key)try{const n=await this.s3Client.send(new e({Bucket:this.bucketName,Key:t.Key}));if(n&&n.Body){const e=await n.Body.transformToString();try{const t=JSON.parse(e);t&&t.noun&&(u[t.noun]=(u[t.noun]||0)+1)}catch(e){console.error(`Failed to parse metadata from ${t.Key}:`,e)}}}catch(e){console.error(`Error getting metadata from ${t.Key}:`,e)}}return{type:this.serviceType,used:t,quota:null,details:{bucketName:this.bucketName,region:this.region,endpoint:this.endpoint,nodeCount:n,edgeCount:r,metadataCount:a,nounTypes:u}}}catch(e){return console.error("Failed to get storage status:",e),{type:this.serviceType,used:0,quota:null,details:{error:String(e)}}}}getStatisticsKeyForDate(e){const t=e.getUTCFullYear(),n=String(e.getUTCMonth()+1).padStart(2,"0"),r=String(e.getUTCDate()).padStart(2,"0");return`${this.indexPrefix}${me}_${t}${n}${r}.json`}getCurrentStatisticsKey(){return this.getStatisticsKeyForDate(new Date)}getLegacyStatisticsKey(){return`${this.indexPrefix}${me}.json`}scheduleBatchUpdate(){if(this.statisticsModified=!0,null!==this.statisticsBatchUpdateTimerId)return;const e=Date.now()-this.lastStatisticsFlushTime<this.MIN_FLUSH_INTERVAL_MS?this.MAX_FLUSH_DELAY_MS:this.MIN_FLUSH_INTERVAL_MS;this.statisticsBatchUpdateTimerId=setTimeout(()=>{this.flushStatistics()},e)}async flushStatistics(){if(null!==this.statisticsBatchUpdateTimerId&&(clearTimeout(this.statisticsBatchUpdateTimerId),this.statisticsBatchUpdateTimerId=null),!this.statisticsModified||!this.statisticsCache)return;const e="statistics-flush",t=`${Date.now()}_${Math.random()}_${process.pid||"browser"}`;if(await this.acquireLock(e,15e3))try{if(!this.statisticsModified||!this.statisticsCache)return;const{PutObjectCommand:e,GetObjectCommand:t}=await import("@aws-sdk/client-s3"),n=this.getCurrentStatisticsKey();let r=null;try{r=await this.tryGetStatisticsFromKey(n)}catch(e){console.warn("Could not read current statistics from storage, using local cache:",e)}let a=this.statisticsCache;r&&(a=this.mergeStatistics(r,this.statisticsCache));const s=JSON.stringify(a,null,2);if(await this.s3Client.send(new e({Bucket:this.bucketName,Key:n,Body:s,ContentType:"application/json",Metadata:{"last-updated":Date.now().toString(),"updated-by":process.pid?.toString()||"browser"}})),this.lastStatisticsFlushTime=Date.now(),this.statisticsModified=!1,this.statisticsCache=a,Math.random()<.1){const t=this.getLegacyStatisticsKey();await this.s3Client.send(new e({Bucket:this.bucketName,Key:t,Body:s,ContentType:"application/json"}))}}catch(e){console.error("Failed to flush statistics data:",e),this.statisticsModified=!0}finally{await this.releaseLock(e,t)}else console.log("Statistics flush skipped - another instance is updating")}mergeStatistics(e,t){const n={...e.nounCount};for(const[e,r]of Object.entries(t.nounCount))n[e]=Math.max(n[e]||0,r);const r={...e.verbCount};for(const[e,n]of Object.entries(t.verbCount))r[e]=Math.max(r[e]||0,n);const a={...e.metadataCount};for(const[e,n]of Object.entries(t.metadataCount))a[e]=Math.max(a[e]||0,n);return{nounCount:n,verbCount:r,metadataCount:a,hnswIndexSize:Math.max(e.hnswIndexSize,t.hnswIndexSize),lastUpdated:new Date(Math.max(new Date(e.lastUpdated).getTime(),new Date(t.lastUpdated).getTime())).toISOString()}}async saveStatisticsData(e){await this.ensureInitialized();try{this.statisticsCache={nounCount:{...e.nounCount},verbCount:{...e.verbCount},metadataCount:{...e.metadataCount},hnswIndexSize:e.hnswIndexSize,lastUpdated:e.lastUpdated},this.scheduleBatchUpdate()}catch(e){throw console.error("Failed to save statistics data:",e),new Error(`Failed to save statistics data: ${e}`)}}async getStatisticsData(){if(await this.ensureInitialized(),this.statisticsCache)return{nounCount:{...this.statisticsCache.nounCount},verbCount:{...this.statisticsCache.verbCount},metadataCount:{...this.statisticsCache.metadataCount},hnswIndexSize:this.statisticsCache.hnswIndexSize,lastUpdated:this.statisticsCache.lastUpdated};try{const{GetObjectCommand:e}=await import("@aws-sdk/client-s3"),t=this.getCurrentStatisticsKey();let n=await this.tryGetStatisticsFromKey(t);if(!n){const e=new Date;e.setDate(e.getDate()-1);const t=this.getStatisticsKeyForDate(e);n=await this.tryGetStatisticsFromKey(t)}if(!n){const e=this.getLegacyStatisticsKey();n=await this.tryGetStatisticsFromKey(e)}return n&&(this.statisticsCache={nounCount:{...n.nounCount},verbCount:{...n.verbCount},metadataCount:{...n.metadataCount},hnswIndexSize:n.hnswIndexSize,lastUpdated:n.lastUpdated}),n}catch(e){throw console.error("Error getting statistics data:",e),e}}async tryGetStatisticsFromKey(e){try{const{GetObjectCommand:t}=await import("@aws-sdk/client-s3"),n=await this.s3Client.send(new t({Bucket:this.bucketName,Key:e}));if(!n||!n.Body)return null;const r=await n.Body.transformToString();return JSON.parse(r)}catch(e){if("NoSuchKey"===e.name||e.message&&(e.message.includes("NoSuchKey")||e.message.includes("not found")||e.message.includes("does not exist")))return null;throw e}}async appendToChangeLog(e){try{const{PutObjectCommand:t}=await import("@aws-sdk/client-s3"),n=`${this.changeLogPrefix}${e.timestamp}-${Math.random().toString(36).substr(2,9)}.json`,r={...e,instanceId:process.pid?.toString()||"browser"};await this.s3Client.send(new t({Bucket:this.bucketName,Key:n,Body:JSON.stringify(r),ContentType:"application/json",Metadata:{timestamp:e.timestamp.toString(),operation:e.operation,"entity-type":e.entityType,"entity-id":e.entityId}}))}catch(e){console.warn("Failed to append to change log:",e)}}async getChangesSince(e,t=1e3){await this.ensureInitialized();try{const{ListObjectsV2Command:n,GetObjectCommand:r}=await import("@aws-sdk/client-s3"),a=await this.s3Client.send(new n({Bucket:this.bucketName,Prefix:this.changeLogPrefix,MaxKeys:2*t}));if(!a.Contents)return[];const s=[];for(const n of a.Contents){if(!n.Key||s.length>=t)break;try{const t=await this.s3Client.send(new r({Bucket:this.bucketName,Key:n.Key}));if(t.Body){const n=await t.Body.transformToString(),r=JSON.parse(n);r.timestamp>e&&s.push(r)}}catch(e){console.warn(`Failed to read change log entry ${n.Key}:`,e)}}return s.sort((e,t)=>e.timestamp-t.timestamp),s.slice(0,t)}catch(e){return console.error("Failed to get changes from change log:",e),[]}}async cleanupOldChangeLogs(e){await this.ensureInitialized();try{const{ListObjectsV2Command:t,DeleteObjectCommand:n}=await import("@aws-sdk/client-s3"),r=await this.s3Client.send(new t({Bucket:this.bucketName,Prefix:this.changeLogPrefix,MaxKeys:1e3}));if(!r.Contents)return;const a=[];for(const t of r.Contents){if(!t.Key)continue;const n=t.Key.split("/");if(n.length>=2){const r=n[n.length-1].split("-")[0],s=parseInt(r);!isNaN(s)&&s<e&&a.push(t.Key)}}for(const e of a)try{await this.s3Client.send(new n({Bucket:this.bucketName,Key:e}))}catch(t){console.warn(`Failed to delete old change log entry ${e}:`,t)}a.length>0&&console.log(`Cleaned up ${a.length} old change log entries`)}catch(e){console.warn("Failed to cleanup old change logs:",e)}}async acquireLock(e,t=3e4){await this.ensureInitialized();const n=`${this.lockPrefix}${e}`,r=`${Date.now()}_${Math.random()}_${process.pid||"browser"}`,a=Date.now()+t;try{const{PutObjectCommand:s,HeadObjectCommand:o}=await import("@aws-sdk/client-s3");try{const e=await this.s3Client.send(new o({Bucket:this.bucketName,Key:n})),t=e.Metadata?.["expires-at"];if(t&&parseInt(t)>Date.now())return!1}catch(e){if("NoSuchKey"!==e.name&&!e.message?.includes("NoSuchKey")&&"NotFound"!==e.name&&!e.message?.includes("NotFound"))throw e}return await this.s3Client.send(new s({Bucket:this.bucketName,Key:n,Body:r,ContentType:"text/plain",Metadata:{"expires-at":a.toString(),"lock-value":r}})),this.activeLocks.add(e),setTimeout(()=>{this.releaseLock(e,r).catch(t=>{console.warn(`Failed to auto-release expired lock ${e}:`,t)})},t),!0}catch(t){return console.warn(`Failed to acquire lock ${e}:`,t),!1}}async releaseLock(e,t){await this.ensureInitialized();const n=`${this.lockPrefix}${e}`;try{const{DeleteObjectCommand:r,GetObjectCommand:a}=await import("@aws-sdk/client-s3");if(t)try{const e=await this.s3Client.send(new a({Bucket:this.bucketName,Key:n}));if(await(e.Body?.transformToString())!==t)return}catch(e){if("NoSuchKey"===e.name||e.message?.includes("NoSuchKey")||"NotFound"===e.name||e.message?.includes("NotFound"))return;throw e}await this.s3Client.send(new r({Bucket:this.bucketName,Key:n})),this.activeLocks.delete(e)}catch(t){console.warn(`Failed to release lock ${e}:`,t)}}async cleanupExpiredLocks(){await this.ensureInitialized();try{const{ListObjectsV2Command:e,DeleteObjectCommand:t,HeadObjectCommand:n}=await import("@aws-sdk/client-s3"),r=await this.s3Client.send(new e({Bucket:this.bucketName,Prefix:this.lockPrefix,MaxKeys:1e3}));if(!r.Contents)return;const a=Date.now(),s=[];for(const e of r.Contents)if(e.Key)try{const t=await this.s3Client.send(new n({Bucket:this.bucketName,Key:e.Key})),r=t.Metadata?.["expires-at"];r&&parseInt(r)<a&&s.push(e.Key)}catch(t){s.push(e.Key)}for(const e of s)try{await this.s3Client.send(new t({Bucket:this.bucketName,Key:e}))}catch(t){console.warn(`Failed to delete expired lock ${e}:`,t)}s.length>0&&console.log(`Cleaned up ${s.length} expired locks`)}catch(e){console.warn("Failed to cleanup expired locks:",e)}}}let $e,Ae;try{const e=import("fs"),t=import("path");Promise.all([e,t]).then(([e,t])=>{$e=e,Ae=t.default}).catch(e=>{console.error("Failed to load Node.js modules:",e)})}catch(e){console.error("FileSystemStorage: Failed to load Node.js modules. This adapter is not supported in this environment.",e)}class Re extends ge{constructor(e){super(),this.activeLocks=new Set,this.rootDir=e}async init(){if(!this.isInitialized){if(!$e||!Ae)throw new Error("FileSystemStorage requires a Node.js environment, but `fs` and `path` modules could not be loaded.");try{this.nounsDir=Ae.join(this.rootDir,de),this.verbsDir=Ae.join(this.rootDir,he),this.metadataDir=Ae.join(this.rootDir,pe),this.indexDir=Ae.join(this.rootDir,fe),this.lockDir=Ae.join(this.rootDir,"locks"),await this.ensureDirectoryExists(this.rootDir),await this.ensureDirectoryExists(this.nounsDir),await this.ensureDirectoryExists(this.verbsDir),await this.ensureDirectoryExists(this.metadataDir),await this.ensureDirectoryExists(this.indexDir),await this.ensureDirectoryExists(this.lockDir),this.isInitialized=!0}catch(e){throw console.error("Error initializing FileSystemStorage:",e),e}}}async ensureDirectoryExists(e){try{await $e.promises.mkdir(e,{recursive:!0})}catch(e){if("EEXIST"!==e.code)throw e}}async saveNode(e){await this.ensureInitialized();const t={...e,connections:this.mapToObject(e.connections,e=>Array.from(e))},n=Ae.join(this.nounsDir,`${e.id}.json`);await $e.promises.writeFile(n,JSON.stringify(t,null,2))}async getNode(e){await this.ensureInitialized();const t=Ae.join(this.nounsDir,`${e}.json`);try{const e=await $e.promises.readFile(t,"utf-8"),n=JSON.parse(e),r=new Map;for(const[e,t]of Object.entries(n.connections))r.set(Number(e),new Set(t));return{id:n.id,vector:n.vector,connections:r}}catch(t){return"ENOENT"!==t.code&&console.error(`Error reading node ${e}:`,t),null}}async getAllNodes(){await this.ensureInitialized();const e=[];try{const t=await $e.promises.readdir(this.nounsDir);for(const n of t)if(n.endsWith(".json")){const t=Ae.join(this.nounsDir,n),r=await $e.promises.readFile(t,"utf-8"),a=JSON.parse(r),s=new Map;for(const[e,t]of Object.entries(a.connections))s.set(Number(e),new Set(t));e.push({id:a.id,vector:a.vector,connections:s})}}catch(e){"ENOENT"!==e.code&&console.error(`Error reading directory ${this.nounsDir}:`,e)}return e}async getNodesByNounType(e){await this.ensureInitialized();const t=[];try{const n=await $e.promises.readdir(this.nounsDir);for(const r of n)if(r.endsWith(".json")){const n=Ae.join(this.nounsDir,r),a=await $e.promises.readFile(n,"utf-8"),s=JSON.parse(a),o=s.id,i=await this.getMetadata(o);if(i&&i.noun===e){const e=new Map;for(const[t,n]of Object.entries(s.connections))e.set(Number(t),new Set(n));t.push({id:s.id,vector:s.vector,connections:e})}}}catch(e){"ENOENT"!==e.code&&console.error(`Error reading directory ${this.nounsDir}:`,e)}return t}async deleteNode(e){await this.ensureInitialized();const t=Ae.join(this.nounsDir,`${e}.json`);try{await $e.promises.unlink(t)}catch(e){if("ENOENT"!==e.code)throw console.error(`Error deleting node file ${t}:`,e),e}}async saveEdge(e){await this.ensureInitialized();const t={...e,connections:this.mapToObject(e.connections,e=>Array.from(e))},n=Ae.join(this.verbsDir,`${e.id}.json`);await $e.promises.writeFile(n,JSON.stringify(t,null,2))}async getEdge(e){await this.ensureInitialized();const t=Ae.join(this.verbsDir,`${e}.json`);try{const e=await $e.promises.readFile(t,"utf-8"),n=JSON.parse(e),r=new Map;for(const[e,t]of Object.entries(n.connections))r.set(Number(e),new Set(t));return{id:n.id,vector:n.vector,connections:r,sourceId:n.sourceId,targetId:n.targetId,type:n.type,weight:n.weight,metadata:n.metadata}}catch(t){return"ENOENT"!==t.code&&console.error(`Error reading edge ${e}:`,t),null}}async getAllEdges(){await this.ensureInitialized();const e=[];try{const t=await $e.promises.readdir(this.verbsDir);for(const n of t)if(n.endsWith(".json")){const t=Ae.join(this.verbsDir,n),r=await $e.promises.readFile(t,"utf-8"),a=JSON.parse(r),s=new Map;for(const[e,t]of Object.entries(a.connections))s.set(Number(e),new Set(t));e.push({id:a.id,vector:a.vector,connections:s,sourceId:a.sourceId,targetId:a.targetId,type:a.type,weight:a.weight,metadata:a.metadata})}}catch(e){"ENOENT"!==e.code&&console.error(`Error reading directory ${this.verbsDir}:`,e)}return e}async getEdgesBySource(e){return(await this.getAllEdges()).filter(t=>t.sourceId===e)}async getEdgesByTarget(e){return(await this.getAllEdges()).filter(t=>t.targetId===e)}async getEdgesByType(e){return(await this.getAllEdges()).filter(t=>t.type===e)}async deleteEdge(e){await this.ensureInitialized();const t=Ae.join(this.verbsDir,`${e}.json`);try{await $e.promises.unlink(t)}catch(e){if("ENOENT"!==e.code)throw console.error(`Error deleting edge file ${t}:`,e),e}}async saveMetadata(e,t){await this.ensureInitialized();const n=Ae.join(this.metadataDir,`${e}.json`);await $e.promises.writeFile(n,JSON.stringify(t,null,2))}async getMetadata(e){await this.ensureInitialized();const t=Ae.join(this.metadataDir,`${e}.json`);try{const e=await $e.promises.readFile(t,"utf-8");return JSON.parse(e)}catch(t){return"ENOENT"!==t.code&&console.error(`Error reading metadata ${e}:`,t),null}}async clear(){await this.ensureInitialized();const e=async t=>{try{const n=await $e.promises.readdir(t);for(const r of n){const n=Ae.join(t,r);(await $e.promises.stat(n)).isDirectory()?(await e(n),await $e.promises.rmdir(n)):await $e.promises.unlink(n)}}catch(e){if("ENOENT"!==e.code)throw console.error(`Error removing directory contents ${t}:`,e),e}};await e(this.nounsDir),await e(this.verbsDir),await e(this.metadataDir),await e(this.indexDir)}async getStorageStatus(){await this.ensureInitialized();try{let e=0;const t=async e=>{let n=0;try{const r=await $e.promises.readdir(e);for(const a of r){const r=Ae.join(e,a),s=await $e.promises.stat(r);s.isDirectory()?n+=await t(r):n+=s.size}}catch(t){"ENOENT"!==t.code&&console.error(`Error calculating size for directory ${e}:`,t)}return n},n=await t(this.nounsDir),r=await t(this.verbsDir),a=await t(this.metadataDir),s=await t(this.indexDir);e=n+r+a+s;const o=(await $e.promises.readdir(this.nounsDir)).filter(e=>e.endsWith(".json")).length,i=(await $e.promises.readdir(this.verbsDir)).filter(e=>e.endsWith(".json")).length,c=(await $e.promises.readdir(this.metadataDir)).filter(e=>e.endsWith(".json")).length,l={},u=await $e.promises.readdir(this.metadataDir);for(const e of u)if(e.endsWith(".json"))try{const t=Ae.join(this.metadataDir,e),n=await $e.promises.readFile(t,"utf-8"),r=JSON.parse(n);r.noun&&(l[r.noun]=(l[r.noun]||0)+1)}catch(t){console.error(`Error reading metadata file ${e}:`,t)}return{type:"filesystem",used:e,quota:null,details:{rootDirectory:this.rootDir,nounsCount:o,verbsCount:i,metadataCount:c,nounsDirSize:n,verbsDirSize:r,metadataDirSize:a,indexDirSize:s,nounTypes:l}}}catch(e){return console.error("Failed to get storage status:",e),{type:"filesystem",used:0,quota:null,details:{error:String(e)}}}}async saveNoun_internal(e){return this.saveNode(e)}async getNoun_internal(e){return this.getNode(e)}async getAllNouns_internal(){return this.getAllNodes()}async getNounsByNounType_internal(e){return this.getNodesByNounType(e)}async deleteNoun_internal(e){return this.deleteNode(e)}async saveVerb_internal(e){return this.saveEdge(e)}async getVerb_internal(e){return this.getEdge(e)}async getAllVerbs_internal(){return this.getAllEdges()}async getVerbsBySource_internal(e){return this.getEdgesBySource(e)}async getVerbsByTarget_internal(e){return this.getEdgesByTarget(e)}async getVerbsByType_internal(e){return this.getEdgesByType(e)}async deleteVerb_internal(e){return this.deleteEdge(e)}async acquireLock(e,t=3e4){await this.ensureInitialized();const n=Ae.join(this.lockDir,`${e}.lock`),r=`${Date.now()}_${Math.random()}_${process.pid||"unknown"}`,a=Date.now()+t;try{try{const e=await $e.promises.readFile(n,"utf-8");if(JSON.parse(e).expiresAt>Date.now())return!1}catch(e){"ENOENT"!==e.code&&console.warn(`Error reading lock file ${n}:`,e)}const s={lockValue:r,expiresAt:a,pid:process.pid||"unknown",timestamp:Date.now()};return await $e.promises.writeFile(n,JSON.stringify(s,null,2)),this.activeLocks.add(e),setTimeout(()=>{this.releaseLock(e,r).catch(t=>{console.warn(`Failed to auto-release expired lock ${e}:`,t)})},t),!0}catch(t){return console.warn(`Failed to acquire lock ${e}:`,t),!1}}async releaseLock(e,t){await this.ensureInitialized();const n=Ae.join(this.lockDir,`${e}.lock`);try{if(t)try{const e=await $e.promises.readFile(n,"utf-8");if(JSON.parse(e).lockValue!==t)return}catch(e){if("ENOENT"===e.code)return;throw e}await $e.promises.unlink(n),this.activeLocks.delete(e)}catch(t){"ENOENT"!==t.code&&console.warn(`Failed to release lock ${e}:`,t)}}async cleanupExpiredLocks(){await this.ensureInitialized();try{const e=await $e.promises.readdir(this.lockDir),t=Date.now();for(const n of e){if(!n.endsWith(".lock"))continue;const e=Ae.join(this.lockDir,n);try{const r=await $e.promises.readFile(e,"utf-8");if(JSON.parse(r).expiresAt<=t){await $e.promises.unlink(e);const t=n.replace(".lock","");this.activeLocks.delete(t)}}catch(t){try{await $e.promises.unlink(e)}catch(t){console.warn(`Failed to cleanup invalid lock file ${e}:`,t)}}}}catch(e){console.warn("Failed to cleanup expired locks:",e)}}async saveStatisticsData(e){const t="statistics",n=await this.acquireLock(t,1e4);n||console.warn("Failed to acquire lock for statistics update, proceeding without lock");try{const t=await this.getMetadata(me);if(t){const n={totalNodes:Math.max(e.totalNodes||0,t.totalNodes||0),totalEdges:Math.max(e.totalEdges||0,t.totalEdges||0),totalMetadata:Math.max(e.totalMetadata||0,t.totalMetadata||0),...t,...e,lastUpdated:(new Date).toISOString()};await this.saveMetadata(me,n)}else{const t={...e,lastUpdated:(new Date).toISOString()};await this.saveMetadata(me,t)}}finally{n&&await this.releaseLock(t)}}async getStatisticsData(){return this.getMetadata(me)}}var _e=Object.freeze({__proto__:null,FileSystemStorage:Re});async function Oe(e={}){if(e.forceMemoryStorage)return console.log("Using memory storage (forced)"),new ye;if(e.forceFileSystemStorage){if(m())return console.warn("FileSystemStorage is not available in browser environments, falling back to memory storage"),new ye;console.log("Using file system storage (forced)");const{FileSystemStorage:t}=await Promise.resolve().then(function(){return _e});return new t(e.rootDirectory||"./brainy-data")}if(e.type&&"auto"!==e.type)switch(e.type){case"memory":return console.log("Using memory storage"),new ye;case"opfs":{const t=new xe;if(t.isOPFSAvailable()){if(console.log("Using OPFS storage"),await t.init(),e.requestPersistentStorage){const e=await t.requestPersistentStorage();console.log("Persistent storage "+(e?"granted":"denied"))}return t}return console.warn("OPFS storage is not available, falling back to memory storage"),new ye}case"filesystem":{if(m())return console.warn("FileSystemStorage is not available in browser environments, falling back to memory storage"),new ye;console.log("Using file system storage");const{FileSystemStorage:t}=await Promise.resolve().then(function(){return _e});return new t(e.rootDirectory||"./brainy-data")}case"s3":return e.s3Storage?(console.log("Using Amazon S3 storage"),new Ee({bucketName:e.s3Storage.bucketName,region:e.s3Storage.region,accessKeyId:e.s3Storage.accessKeyId,secretAccessKey:e.s3Storage.secretAccessKey,sessionToken:e.s3Storage.sessionToken,serviceType:"s3",operationConfig:e.operationConfig})):(console.warn("S3 storage configuration is missing, falling back to memory storage"),new ye);case"r2":return e.r2Storage?(console.log("Using Cloudflare R2 storage"),new Ee({bucketName:e.r2Storage.bucketName,accountId:e.r2Storage.accountId,accessKeyId:e.r2Storage.accessKeyId,secretAccessKey:e.r2Storage.secretAccessKey,serviceType:"r2"})):(console.warn("R2 storage configuration is missing, falling back to memory storage"),new ye);case"gcs":return e.gcsStorage?(console.log("Using Google Cloud Storage"),new Ee({bucketName:e.gcsStorage.bucketName,region:e.gcsStorage.region,endpoint:e.gcsStorage.endpoint||"https://storage.googleapis.com",accessKeyId:e.gcsStorage.accessKeyId,secretAccessKey:e.gcsStorage.secretAccessKey,serviceType:"gcs"})):(console.warn("GCS storage configuration is missing, falling back to memory storage"),new ye);default:return console.warn(`Unknown storage type: ${e.type}, falling back to memory storage`),new ye}if(e.customS3Storage)return console.log(`Using custom S3-compatible storage: ${e.customS3Storage.serviceType||"custom"}`),new Ee({bucketName:e.customS3Storage.bucketName,region:e.customS3Storage.region,endpoint:e.customS3Storage.endpoint,accessKeyId:e.customS3Storage.accessKeyId,secretAccessKey:e.customS3Storage.secretAccessKey,serviceType:e.customS3Storage.serviceType||"custom"});if(e.r2Storage)return console.log("Using Cloudflare R2 storage"),new Ee({bucketName:e.r2Storage.bucketName,accountId:e.r2Storage.accountId,accessKeyId:e.r2Storage.accessKeyId,secretAccessKey:e.r2Storage.secretAccessKey,serviceType:"r2"});if(e.s3Storage)return console.log("Using Amazon S3 storage"),new Ee({bucketName:e.s3Storage.bucketName,region:e.s3Storage.region,accessKeyId:e.s3Storage.accessKeyId,secretAccessKey:e.s3Storage.secretAccessKey,sessionToken:e.s3Storage.sessionToken,serviceType:"s3"});if(e.gcsStorage)return console.log("Using Google Cloud Storage"),new Ee({bucketName:e.gcsStorage.bucketName,region:e.gcsStorage.region,endpoint:e.gcsStorage.endpoint||"https://storage.googleapis.com",accessKeyId:e.gcsStorage.accessKeyId,secretAccessKey:e.gcsStorage.secretAccessKey,serviceType:"gcs"});const t=new xe;if(t.isOPFSAvailable()){if(console.log("Using OPFS storage (auto-detected)"),await t.init(),e.requestPersistentStorage){const e=await t.requestPersistentStorage();console.log("Persistent storage "+(e?"granted":"denied"))}return t}try{if("undefined"!=typeof process&&process.versions&&process.versions.node)return console.log("Using file system storage (auto-detected)"),new Re(e.rootDirectory||"./brainy-data")}catch(e){}return console.log("Using memory storage (auto-detected)"),new ye}const Fe={Person:"person",Organization:"organization",Location:"location",Thing:"thing",Concept:"concept",Event:"event",Document:"document",Media:"media",File:"file",Message:"message",Content:"content",Collection:"collection",Dataset:"dataset",Product:"product",Service:"service",User:"user",Task:"task",Project:"project",Process:"process",State:"state",Role:"role",Topic:"topic",Language:"language",Currency:"currency",Measurement:"measurement"},De={RelatedTo:"relatedTo",Contains:"contains",PartOf:"partOf",LocatedAt:"locatedAt",References:"references",Precedes:"precedes",Succeeds:"succeeds",Causes:"causes",DependsOn:"dependsOn",Requires:"requires",Creates:"creates",Transforms:"transforms",Becomes:"becomes",Modifies:"modifies",Consumes:"consumes",Owns:"owns",AttributedTo:"attributedTo",CreatedBy:"createdBy",BelongsTo:"belongsTo",MemberOf:"memberOf",WorksWith:"worksWith",FriendOf:"friendOf",Follows:"follows",Likes:"likes",ReportsTo:"reportsTo",Supervises:"supervises",Mentors:"mentors",Communicates:"communicates",Describes:"describes",Defines:"defines",Categorizes:"categorizes",Measures:"measures",Evaluates:"evaluates",Uses:"uses",Implements:"implements",Extends:"extends"};var Me,Pe;!function(e){e.SENSE="sense",e.CONDUIT="conduit",e.COGNITION="cognition",e.MEMORY="memory",e.PERCEPTION="perception",e.DIALOG="dialog",e.ACTIVATION="activation",e.WEBSOCKET="webSocket"}(Me||(Me={}));class Be{constructor(e){this.description="Base conduit augmentation",this.enabled=!0,this.isInitialized=!1,this.connections=new Map,this.name=e}async initialize(){if(!this.isInitialized)try{this.isInitialized=!0}catch(e){throw console.error(`Failed to initialize ${this.name}:`,e),new Error(`Failed to initialize ${this.name}: ${e}`)}}async shutDown(){for(const[e,t]of this.connections.entries())try{t.close&&await t.close()}catch(t){console.error(`Failed to close connection ${e}:`,t)}this.connections.clear(),this.isInitialized=!1}async getStatus(){return this.isInitialized?"active":"inactive"}async ensureInitialized(){this.isInitialized||await this.initialize()}}class Le extends Be{constructor(e="websocket-conduit"){super(e),this.description="Conduit augmentation that syncs Brainy instances using WebSockets",this.webSocketConnections=new Map,this.messageCallbacks=new Map}getType(){return Me.CONDUIT}async establishConnection(e,t){await this.ensureInitialized();try{const n=e,r=t.protocols,a=await this.connectWebSocket(n,r);return this.connections.set(a.connectionId,a),{success:!0,data:a}}catch(t){return console.error(`Failed to establish connection to ${e}:`,t),{success:!1,data:null,error:`Failed to establish connection: ${t}`}}}async readData(e,t){await this.ensureInitialized();try{const n=e.connectionId;if(!n)throw new Error("connectionId is required for reading data");if(!this.webSocketConnections.get(n))throw new Error(`Connection ${n} not found`);const r={type:"read",query:e.query||{},requestId:_(),options:t};return await this.sendWebSocketMessage(n,r),new Promise(e=>{const t=a=>{const s=a;s&&"readResponse"===s.type&&s.requestId===r.requestId&&(this.offWebSocketMessage(n,t),e({success:s.success,data:s.data,error:s.error}))};this.onWebSocketMessage(n,t),setTimeout(()=>{this.offWebSocketMessage(n,t),e({success:!1,data:null,error:"Timeout waiting for read response"})},3e4)})}catch(e){return console.error("Failed to read data:",e),{success:!1,data:null,error:`Failed to read data: ${e}`}}}async writeData(e,t){await this.ensureInitialized();try{const n=e.connectionId;if(!n)throw new Error("connectionId is required for writing data");if(!this.webSocketConnections.get(n))throw new Error(`Connection ${n} not found`);const r={type:"write",data:e.data||{},requestId:_(),options:t};return await this.sendWebSocketMessage(n,r),new Promise(e=>{const t=a=>{const s=a;s&&"writeResponse"===s.type&&s.requestId===r.requestId&&(this.offWebSocketMessage(n,t),e({success:s.success,data:s.data,error:s.error}))};this.onWebSocketMessage(n,t),setTimeout(()=>{this.offWebSocketMessage(n,t),e({success:!1,data:null,error:"Timeout waiting for write response"})},3e4)})}catch(e){return console.error("Failed to write data:",e),{success:!1,data:null,error:`Failed to write data: ${e}`}}}async monitorStream(e,t){await this.ensureInitialized();try{if(!this.webSocketConnections.get(e))throw new Error(`Connection ${e} not found`);await this.onWebSocketMessage(e,t)}catch(t){throw console.error(`Failed to monitor stream ${e}:`,t),new Error(`Failed to monitor stream: ${t}`)}}async connectWebSocket(e,t){return await this.ensureInitialized(),new Promise((n,r)=>{try{if("undefined"==typeof WebSocket)throw new Error("WebSocket is not available in this environment");const a=new WebSocket(e,t),s=_(),o={connectionId:s,url:e,status:"disconnected",send:async e=>{if(a.readyState!==WebSocket.OPEN)throw new Error("WebSocket is not open");a.send(e)},close:async()=>{a.close()}};a.onopen=()=>{o.status="connected",n(o)},a.onerror=t=>{o.status="error",console.error(`WebSocket error for ${e}:`,t),a.readyState!==WebSocket.OPEN&&r(new Error(`WebSocket connection failed: ${t}`))},a.onclose=()=>{o.status="disconnected",this.webSocketConnections.delete(s),this.messageCallbacks.delete(s)};const i=e=>{const t=this.messageCallbacks.get(s);if(t)for(const n of t)try{n(e)}catch(e){console.error("Error in WebSocket message callback:",e)}};o._messageHandlerWrapper=i,a.onmessage=e=>{try{let t=e.data;if("string"==typeof t)try{t=JSON.parse(t)}catch{}i(t)}catch(e){console.error("Error handling WebSocket message:",e)}},o._streamMessageHandler=e=>a.onmessage&&a.onmessage(e),this.webSocketConnections.set(s,o),this.messageCallbacks.set(s,new Set)}catch(e){r(e)}})}async sendWebSocketMessage(e,t){await this.ensureInitialized();const n=this.webSocketConnections.get(e);if(!n)throw new Error(`WebSocket connection ${e} not found`);if(!n.send)throw new Error(`WebSocket connection ${e} does not support sending messages`);let r;r="string"==typeof t||t instanceof ArrayBuffer||t instanceof Blob||ArrayBuffer.isView(t)?t:JSON.stringify(t),await n.send(r)}async onWebSocketMessage(e,t){await this.ensureInitialized();if(!this.webSocketConnections.get(e))throw new Error(`WebSocket connection ${e} not found`);let n=this.messageCallbacks.get(e);n||(n=new Set,this.messageCallbacks.set(e,n)),n.add(t)}async offWebSocketMessage(e,t){await this.ensureInitialized();const n=this.messageCallbacks.get(e);n&&n.delete(t)}async closeWebSocket(e,t,n){await this.ensureInitialized();const r=this.webSocketConnections.get(e);if(!r)throw new Error(`WebSocket connection ${e} not found`);if(!r.close)throw new Error(`WebSocket connection ${e} does not support closing`);await r.close(),this.webSocketConnections.delete(e),this.messageCallbacks.delete(e)}}class ze extends Be{constructor(e="webrtc-conduit"){super(e),this.description="Conduit augmentation that syncs Brainy instances using WebRTC",this.peerConnections=new Map,this.dataChannels=new Map,this.webSocketConnections=new Map,this.messageCallbacks=new Map,this.signalServer=null}getType(){return Me.CONDUIT}async initialize(){if(!this.isInitialized)try{if("undefined"==typeof RTCPeerConnection)throw new Error("WebRTC is not available in this environment");this.isInitialized=!0}catch(e){throw console.error(`Failed to initialize ${this.name}:`,e),new Error(`Failed to initialize ${this.name}: ${e}`)}}async establishConnection(e,t){await this.ensureInitialized();try{!this.signalServer&&t.signalServerUrl&&(this.signalServer=await this.connectWebSocket(t.signalServerUrl),await this.onWebSocketMessage(this.signalServer.connectionId,async e=>{const n=e;if("ice-candidate"===n.type&&n.targetPeerId===t.localPeerId){const e=this.peerConnections.get(n.sourcePeerId);if(e)try{await e.addIceCandidate(new RTCIceCandidate(n.candidate))}catch(e){console.error("Failed to add ICE candidate:",e)}}else if("offer"===n.type&&n.targetPeerId===t.localPeerId)await this.handleOffer(n.sourcePeerId,n.offer,t);else if("answer"===n.type&&n.targetPeerId===t.localPeerId){const e=this.peerConnections.get(n.sourcePeerId);if(e)try{await e.setRemoteDescription(new RTCSessionDescription(n.answer))}catch(e){console.error("Failed to set remote description:",e)}}}));const n=new RTCPeerConnection({iceServers:t.iceServers||[{urls:"stun:stun.l.google.com:19302"}]}),r=_();this.peerConnections.set(e,n);const a=n.createDataChannel("brainy-sync",{ordered:!0});a.onopen=()=>{console.log(`Data channel to ${e} opened`)},a.onclose=()=>{console.log(`Data channel to ${e} closed`),this.dataChannels.delete(e),this.peerConnections.delete(e),this.webSocketConnections.delete(r),this.messageCallbacks.delete(r)},a.onerror=e=>{console.error("Data channel error:",e)};const s=e=>{const t=this.messageCallbacks.get(r);if(t)for(const n of t)try{n(e)}catch(e){console.error("Error in WebRTC message callback:",e)}};a.onmessage=e=>{try{let t=e.data;if("string"==typeof t)try{t=JSON.parse(t)}catch{}s(t)}catch(e){console.error("Error handling WebRTC message:",e)}},this.dataChannels.set(e,a),n.onicecandidate=n=>{n.candidate&&this.signalServer&&this.sendWebSocketMessage(this.signalServer.connectionId,{type:"ice-candidate",sourcePeerId:t.localPeerId,targetPeerId:e,candidate:n.candidate})};const o={connectionId:r,url:`webrtc://${e}`,status:"disconnected",send:async t=>{const n=this.dataChannels.get(e);if(!n||"open"!==n.readyState)throw new Error("WebRTC data channel is not open");"string"==typeof t||t instanceof Blob?n.send(t):t instanceof ArrayBuffer?n.send(new Uint8Array(t)):ArrayBuffer.isView(t)?n.send(t):n.send(JSON.stringify(t))},close:async()=>{const t=this.dataChannels.get(e);t&&t.close();const n=this.peerConnections.get(e);n&&n.close(),this.dataChannels.delete(e),this.peerConnections.delete(e),this.webSocketConnections.delete(r),this.messageCallbacks.delete(r)},_messageHandlerWrapper:s};this.webSocketConnections.set(r,o),this.messageCallbacks.set(r,new Set);const i=await n.createOffer();return await n.setLocalDescription(i),this.signalServer&&await this.sendWebSocketMessage(this.signalServer.connectionId,{type:"offer",sourcePeerId:t.localPeerId,targetPeerId:e,offer:i}),{success:!0,data:o}}catch(t){return console.error(`Failed to establish WebRTC connection to ${e}:`,t),{success:!1,data:null,error:`Failed to establish WebRTC connection: ${t}`}}}async handleOffer(e,t,n){try{let r=this.peerConnections.get(e);r||(r=new RTCPeerConnection({iceServers:n.iceServers||[{urls:"stun:stun.l.google.com:19302"}]}),this.peerConnections.set(e,r),r.onicecandidate=t=>{t.candidate&&this.signalServer&&this.sendWebSocketMessage(this.signalServer.connectionId,{type:"ice-candidate",sourcePeerId:n.localPeerId,targetPeerId:e,candidate:t.candidate})},r.ondatachannel=t=>{const n=t.channel,r=_();this.dataChannels.set(e,n),n.onopen=()=>{console.log(`Data channel from ${e} opened`)},n.onclose=()=>{console.log(`Data channel from ${e} closed`),this.dataChannels.delete(e),this.peerConnections.delete(e),this.webSocketConnections.delete(r),this.messageCallbacks.delete(r)},n.onerror=e=>{console.error("Data channel error:",e)};const a=e=>{const t=this.messageCallbacks.get(r);if(t)for(const n of t)try{n(e)}catch(e){console.error("Error in WebRTC message callback:",e)}};n.onmessage=e=>{try{let t=e.data;if("string"==typeof t)try{t=JSON.parse(t)}catch{}a(t)}catch(e){console.error("Error handling WebRTC message:",e)}};const s={connectionId:r,url:`webrtc://${e}`,status:"disconnected",send:async e=>{if("open"!==n.readyState)throw new Error("WebRTC data channel is not open");"string"==typeof e||e instanceof Blob?n.send(e):e instanceof ArrayBuffer?n.send(new Uint8Array(e)):ArrayBuffer.isView(e)?n.send(e):n.send(JSON.stringify(e))},close:async()=>{n.close();const t=this.peerConnections.get(e);t&&t.close(),this.dataChannels.delete(e),this.peerConnections.delete(e),this.webSocketConnections.delete(r),this.messageCallbacks.delete(r)},_messageHandlerWrapper:a};this.webSocketConnections.set(r,s),this.messageCallbacks.set(r,new Set)}),await r.setRemoteDescription(new RTCSessionDescription(t));const a=await r.createAnswer();await r.setLocalDescription(a),this.signalServer&&await this.sendWebSocketMessage(this.signalServer.connectionId,{type:"answer",sourcePeerId:n.localPeerId,targetPeerId:e,answer:a})}catch(e){throw console.error("Failed to handle WebRTC offer:",e),new Error(`Failed to handle WebRTC offer: ${e}`)}}async readData(e,t){await this.ensureInitialized();try{const n=e.connectionId;if(!n)throw new Error("connectionId is required for reading data");if(!this.webSocketConnections.get(n))throw new Error(`Connection ${n} not found`);const r={type:"read",query:e.query||{},requestId:_(),options:t};return await this.sendWebSocketMessage(n,r),new Promise(e=>{const t=a=>{const s=a;s&&"readResponse"===s.type&&s.requestId===r.requestId&&(this.offWebSocketMessage(n,t),e({success:s.success,data:s.data,error:s.error}))};this.onWebSocketMessage(n,t),setTimeout(()=>{this.offWebSocketMessage(n,t),e({success:!1,data:null,error:"Timeout waiting for read response"})},3e4)})}catch(e){return console.error("Failed to read data:",e),{success:!1,data:null,error:`Failed to read data: ${e}`}}}async writeData(e,t){await this.ensureInitialized();try{const n=e.connectionId;if(!n)throw new Error("connectionId is required for writing data");if(!this.webSocketConnections.get(n))throw new Error(`Connection ${n} not found`);const r={type:"write",data:e.data||{},requestId:_(),options:t};return await this.sendWebSocketMessage(n,r),new Promise(e=>{const t=a=>{const s=a;s&&"writeResponse"===s.type&&s.requestId===r.requestId&&(this.offWebSocketMessage(n,t),e({success:s.success,data:s.data,error:s.error}))};this.onWebSocketMessage(n,t),setTimeout(()=>{this.offWebSocketMessage(n,t),e({success:!1,data:null,error:"Timeout waiting for write response"})},3e4)})}catch(e){return console.error("Failed to write data:",e),{success:!1,data:null,error:`Failed to write data: ${e}`}}}async monitorStream(e,t){await this.ensureInitialized();try{if(!this.webSocketConnections.get(e))throw new Error(`Connection ${e} not found`);await this.onWebSocketMessage(e,t)}catch(t){throw console.error(`Failed to monitor stream ${e}:`,t),new Error(`Failed to monitor stream: ${t}`)}}async connectWebSocket(e,t){return await this.ensureInitialized(),new Promise((n,r)=>{try{if("undefined"==typeof WebSocket)throw new Error("WebSocket is not available in this environment");const a=new WebSocket(e,t),s=_(),o={connectionId:s,url:e,status:"disconnected",send:async e=>{if(a.readyState!==WebSocket.OPEN)throw new Error("WebSocket is not open");a.send(e)},close:async()=>{a.close()}};a.onopen=()=>{o.status="connected",n(o)},a.onerror=t=>{o.status="error",console.error(`WebSocket error for ${e}:`,t),a.readyState!==WebSocket.OPEN&&r(new Error(`WebSocket connection failed: ${t}`))},a.onclose=()=>{o.status="disconnected",this.webSocketConnections.delete(s),this.messageCallbacks.delete(s)};const i=e=>{const t=this.messageCallbacks.get(s);if(t)for(const n of t)try{n(e)}catch(e){console.error("Error in WebSocket message callback:",e)}};o._messageHandlerWrapper=i,a.onmessage=e=>{try{let t=e.data;if("string"==typeof t)try{t=JSON.parse(t)}catch{}i(t)}catch(e){console.error("Error handling WebSocket message:",e)}},o._streamMessageHandler=e=>a.onmessage&&a.onmessage(e),this.webSocketConnections.set(s,o),this.messageCallbacks.set(s,new Set)}catch(e){r(e)}})}async sendWebSocketMessage(e,t){await this.ensureInitialized();const n=this.webSocketConnections.get(e);if(!n)throw new Error(`Connection ${e} not found`);if(!n.send)throw new Error(`Connection ${e} does not support sending messages`);let r;r="string"==typeof t||t instanceof ArrayBuffer||t instanceof Blob||ArrayBuffer.isView(t)?t:JSON.stringify(t),await n.send(r)}async onWebSocketMessage(e,t){await this.ensureInitialized();if(!this.webSocketConnections.get(e))throw new Error(`Connection ${e} not found`);let n=this.messageCallbacks.get(e);n||(n=new Set,this.messageCallbacks.set(e,n)),n.add(t)}async offWebSocketMessage(e,t){await this.ensureInitialized();const n=this.messageCallbacks.get(e);n&&n.delete(t)}async closeWebSocket(e,t,n){await this.ensureInitialized();const r=this.webSocketConnections.get(e);if(!r)throw new Error(`Connection ${e} not found`);if(!r.close)throw new Error(`Connection ${e} does not support closing`);await r.close(),this.webSocketConnections.delete(e),this.messageCallbacks.delete(e)}}async function Ue(e,t,n={}){switch(e){case"websocket":const n=new Le(t||"websocket-conduit");return await n.initialize(),n;case"webrtc":const r=new ze(t||"webrtc-conduit");return await r.initialize(),r;default:throw new Error(`Unknown conduit augmentation type: ${e}`)}}class We extends Le{constructor(e="server-search-conduit"){super(e),this.localDb=null}async initialize(){if(!this.isInitialized)try{if(await super.initialize(),!this.localDb)throw new Error("Local database not set. Call setLocalDb before initializing.");this.isInitialized=!0}catch(e){throw console.error(`Failed to initialize ${this.name}:`,e),new Error(`Failed to initialize ${this.name}: ${e}`)}}setLocalDb(e){this.localDb=e}getLocalDb(){return this.localDb}async searchServer(e,t,n=10){await this.ensureInitialized();try{const r=await this.readData({connectionId:e,query:{type:"search",query:t,limit:n}});if(r.success&&r.data){const e=r.data;if(this.localDb)for(const t of e){await this.localDb.get(t.id)||await this.localDb.add(t.vector,t.metadata)}return{success:!0,data:e}}return{success:!1,data:null,error:r.error||"Unknown error searching server"}}catch(e){return console.error("Error searching server:",e),{success:!1,data:null,error:`Error searching server: ${e}`}}}async searchLocal(e,t=10){await this.ensureInitialized();try{if(!this.localDb)return{success:!1,data:null,error:"Local database not initialized"};return{success:!0,data:await this.localDb.searchText(e,t)}}catch(e){return console.error("Error searching local database:",e),{success:!1,data:null,error:`Error searching local database: ${e}`}}}async searchCombined(e,t,n=10){await this.ensureInitialized();try{const r=await this.searchLocal(t,n);if(!r.success)return r;const a=r.data;if(a.length>=n)return r;const s=await this.searchServer(e,t,n-a.length);if(!s.success)return r;const o=s.data,i=[...a],c=new Set(a.map(e=>e.id));for(const e of o)c.has(e.id)||i.push(e);return{success:!0,data:i}}catch(e){return console.error("Error performing combined search:",e),{success:!1,data:null,error:`Error performing combined search: ${e}`}}}async addToBoth(e,t,n={}){await this.ensureInitialized();try{if(!this.localDb)return{success:!1,data:"",error:"Local database not initialized"};const r=await this.localDb.add(t,n),a=await this.localDb.get(r);if(!a)return{success:!1,data:"",error:"Failed to retrieve newly created noun"};const s=await this.writeData({connectionId:e,data:{type:"addNoun",vector:a.vector,metadata:a.metadata}});return s.success?{success:!0,data:r}:{success:!0,data:r,error:`Added locally but failed to add to server: ${s.error}`}}catch(e){return console.error("Error adding data to both:",e),{success:!1,data:"",error:`Error adding data to both: ${e}`}}}}class Ve{constructor(e="server-search-activation"){this.enabled=!0,this.isInitialized=!1,this.conduitAugmentation=null,this.connections=new Map,this.name=e,this.description="Activation augmentation for server-hosted Brainy search"}getType(){return Me.ACTIVATION}async initialize(){this.isInitialized||(this.isInitialized=!0)}async shutDown(){this.isInitialized=!1}async getStatus(){return this.isInitialized?"active":"inactive"}setConduitAugmentation(e){this.conduitAugmentation=e}storeConnection(e,t){this.connections.set(e,t)}getConnection(e){return this.connections.get(e)}triggerAction(e,t){if(!this.conduitAugmentation)return{success:!1,data:null,error:"Conduit augmentation not set"};switch(e){case"connectToServer":return this.handleConnectToServer(t||{});case"searchServer":return this.handleSearchServer(t||{});case"searchLocal":return this.handleSearchLocal(t||{});case"searchCombined":return this.handleSearchCombined(t||{});case"addToBoth":return this.handleAddToBoth(t||{});default:return{success:!1,data:null,error:`Unknown action: ${e}`}}}handleConnectToServer(e){const t=e.serverUrl,n=e.protocols;return t?{success:!0,data:this.conduitAugmentation.establishConnection(t,{protocols:n})}:{success:!1,data:null,error:"serverUrl parameter is required"}}handleSearchServer(e){const t=e.connectionId,n=e.query,r=e.limit||10;return t?n?{success:!0,data:this.conduitAugmentation.searchServer(t,n,r)}:{success:!1,data:null,error:"query parameter is required"}:{success:!1,data:null,error:"connectionId parameter is required"}}handleSearchLocal(e){const t=e.query,n=e.limit||10;return t?{success:!0,data:this.conduitAugmentation.searchLocal(t,n)}:{success:!1,data:null,error:"query parameter is required"}}handleSearchCombined(e){const t=e.connectionId,n=e.query,r=e.limit||10;return t?n?{success:!0,data:this.conduitAugmentation.searchCombined(t,n,r)}:{success:!1,data:null,error:"query parameter is required"}:{success:!1,data:null,error:"connectionId parameter is required"}}handleAddToBoth(e){const t=e.connectionId,n=e.data,r=e.metadata||{};return t?n?{success:!0,data:this.conduitAugmentation.addToBoth(t,n,r)}:{success:!1,data:null,error:"data parameter is required"}:{success:!1,data:null,error:"connectionId parameter is required"}}generateOutput(e,t){return{success:!1,data:"",error:"generateOutput is not implemented for ServerSearchActivationAugmentation"}}interactExternal(e,t){return{success:!1,data:null,error:"interactExternal is not implemented for ServerSearchActivationAugmentation"}}}async function Ge(e,t={}){const n=new We(t.conduitName);await n.initialize(),t.localDb&&n.setLocalDb(t.localDb);const r=new Ve(t.activationName);await r.initialize(),r.setConduitAugmentation(n);const a=await n.establishConnection(e,{protocols:t.protocols});if(!a.success||!a.data)throw new Error(`Failed to connect to server: ${a.error}`);const s=a.data;return r.storeConnection(s.connectionId,s),{conduit:n,activation:r,connection:s}}!function(e){e.SEQUENTIAL="sequential",e.PARALLEL="parallel",e.FIRST_SUCCESS="firstSuccess",e.FIRST_RESULT="firstResult",e.THREADED="threaded"}(Pe||(Pe={}));const je={mode:Pe.SEQUENTIAL,timeout:3e4,stopOnError:!1,forceThreading:!1,disableThreading:!1};const He=new class{constructor(){this.registry={sense:[],conduit:[],cognition:[],memory:[],perception:[],dialog:[],activation:[],webSocket:[]}}register(e){let t=!1;if(this.isAugmentationType(e,"processRawData","listenToFeed")?(this.registry.sense.push(e),t=!0):this.isAugmentationType(e,"establishConnection","readData","writeData","monitorStream")?(this.registry.conduit.push(e),t=!0):this.isAugmentationType(e,"reason","infer","executeLogic")?(this.registry.cognition.push(e),t=!0):this.isAugmentationType(e,"storeData","retrieveData","updateData","deleteData","listDataKeys")?(this.registry.memory.push(e),t=!0):this.isAugmentationType(e,"interpret","organize","generateVisualization")?(this.registry.perception.push(e),t=!0):this.isAugmentationType(e,"processUserInput","generateResponse","manageContext")?(this.registry.dialog.push(e),t=!0):this.isAugmentationType(e,"triggerAction","generateOutput","interactExternal")&&(this.registry.activation.push(e),t=!0),this.isAugmentationType(e,"connectWebSocket","sendWebSocketMessage","onWebSocketMessage","closeWebSocket")&&(this.registry.webSocket.push(e),t=!0),!t)throw new Error(`Unknown augmentation type: ${e.name}`);return this}unregister(e){for(const t in this.registry){const n=this.registry[t],r=n.findIndex(t=>t.name===e);-1!==r&&n.splice(r,1)}return this}async initialize(){const e=this.getAllAugmentations();await Promise.all(e.map(e=>e.initialize().catch(t=>{console.error(`Failed to initialize augmentation ${e.name}:`,t)})))}async shutDown(){const e=this.getAllAugmentations();await Promise.all(e.map(e=>e.shutDown().catch(t=>{console.error(`Failed to shut down augmentation ${e.name}:`,t)})))}async executeSensePipeline(e,t,n={}){const r={...je,...n};return this.executeTypedPipeline(this.registry.sense,e,t,r)}async executeConduitPipeline(e,t,n={}){const r={...je,...n};return this.executeTypedPipeline(this.registry.conduit,e,t,r)}async executeCognitionPipeline(e,t,n={}){const r={...je,...n};return this.executeTypedPipeline(this.registry.cognition,e,t,r)}async executeMemoryPipeline(e,t,n={}){const r={...je,...n};return this.executeTypedPipeline(this.registry.memory,e,t,r)}async executePerceptionPipeline(e,t,n={}){const r={...je,...n};return this.executeTypedPipeline(this.registry.perception,e,t,r)}async executeDialogPipeline(e,t,n={}){const r={...je,...n};return this.executeTypedPipeline(this.registry.dialog,e,t,r)}async executeActivationPipeline(e,t,n={}){const r={...je,...n};return this.executeTypedPipeline(this.registry.activation,e,t,r)}getAllAugmentations(){const e=new Set([...this.registry.sense,...this.registry.conduit,...this.registry.cognition,...this.registry.memory,...this.registry.perception,...this.registry.dialog,...this.registry.activation,...this.registry.webSocket]);return Array.from(e)}getAugmentationsByType(e){switch(e){case Me.SENSE:return[...this.registry.sense];case Me.CONDUIT:return[...this.registry.conduit];case Me.COGNITION:return[...this.registry.cognition];case Me.MEMORY:return[...this.registry.memory];case Me.PERCEPTION:return[...this.registry.perception];case Me.DIALOG:return[...this.registry.dialog];case Me.ACTIVATION:return[...this.registry.activation];case Me.WEBSOCKET:return[...this.registry.webSocket];default:return[]}}getAvailableAugmentationTypes(){const e=[];return this.registry.sense.length>0&&e.push(Me.SENSE),this.registry.conduit.length>0&&e.push(Me.CONDUIT),this.registry.cognition.length>0&&e.push(Me.COGNITION),this.registry.memory.length>0&&e.push(Me.MEMORY),this.registry.perception.length>0&&e.push(Me.PERCEPTION),this.registry.dialog.length>0&&e.push(Me.DIALOG),this.registry.activation.length>0&&e.push(Me.ACTIVATION),this.registry.webSocket.length>0&&e.push(Me.WEBSOCKET),e}getWebSocketAugmentations(){return[...this.registry.webSocket]}isAugmentationType(e,...t){return!!["initialize","shutDown","getStatus"].every(t=>"function"==typeof e[t])&&t.every(t=>"function"==typeof e[t])}shouldUseThreading(e){return!e.disableThreading&&((e.forceThreading||e.mode===Pe.THREADED)&&v())}async executeTypedPipeline(e,t,n,r){const a=e.filter(e=>!1!==e.enabled);if(0===a.length)return[];const s=async e=>{try{const a=r.timeout?new Promise((n,a)=>{setTimeout(()=>{a(new Error(`Timeout executing ${String(t)} on ${e.name}`))},r.timeout)}):null;let s;if(this.shouldUseThreading(r))try{s=L(((...n)=>e[t].apply(e,n)).toString(),n)}catch(r){console.warn(`Failed to execute in thread, falling back to main thread: ${r}`),s=Promise.resolve(e[t](...n))}else s=Promise.resolve(e[t](...n));return a?await Promise.race([s,a]):await s}catch(n){return console.error(`Error executing ${String(t)} on ${e.name}:`,n),{success:!1,data:null,error:n instanceof Error?n.message:String(n)}}};switch(r.mode){case Pe.PARALLEL:return a.map(s);case Pe.THREADED:const e={...r,forceThreading:!0},t=async t=>{const n=r;r=e;const a=await s(t);return r=n,a};return a.map(t);case Pe.FIRST_SUCCESS:for(const e of a){const t=s(e);if((await t).success)return[t]}return[];case Pe.FIRST_RESULT:for(const e of a){const t=s(e),n=await t;if(n.success&&n.data)return[t]}return[];case Pe.SEQUENTIAL:default:const n=[];for(const e of a){const t=s(e);if(n.push(t),r.stopOnError){if(!(await t).success)break}}return n}}};class qe{get dimensions(){return this._dimensions}get maxConnections(){return this.index.getConfig().M||16}get efConstruction(){return this.index.getConfig().efConstruction||200}constructor(e={}){if(this.storage=null,this.isInitialized=!1,this.isInitializing=!1,this.storageConfig={},this.useOptimizedIndex=!1,this.loggingConfig={verbose:!0},this.timeoutConfig={},this.retryConfig={},this.realtimeUpdateConfig={enabled:!1,interval:3e4,updateStatistics:!0,updateIndex:!0},this.updateTimerId=null,this.lastUpdateTime=0,this.lastKnownNounCount=0,this.remoteServerConfig=null,this.serverSearchConduit=null,this.serverConnection=null,this._dimensions=512,this.distanceFunction=e.distanceFunction||F,this.index=new le(e.hnsw||{},this.distanceFunction,e.storageAdapter||null),this.useOptimizedIndex=!0,this.storage=e.storageAdapter||null,void 0!==e.logging&&(this.loggingConfig={...this.loggingConfig,...e.logging}),e.embeddingFunction?this.embeddingFunction=e.embeddingFunction:this.embeddingFunction=K({verbose:this.loggingConfig?.verbose}),this.requestPersistentStorage=e.storage?.requestPersistentStorage||!1,this.readOnly=e.readOnly||!1,this.writeOnly=e.writeOnly||!1,this.readOnly&&this.writeOnly)throw new Error("Database cannot be both read-only and write-only");this.storageConfig=e.storage||{},this.timeoutConfig=e.timeouts||{},this.retryConfig=e.retryPolicy||{},e.remoteServer&&(this.remoteServerConfig=e.remoteServer),e.realtimeUpdates&&(this.realtimeUpdateConfig={...this.realtimeUpdateConfig,...e.realtimeUpdates})}checkReadOnly(){if(this.readOnly)throw new Error("Cannot perform write operation: database is in read-only mode")}checkWriteOnly(){if(this.writeOnly)throw new Error("Cannot perform search operation: database is in write-only mode")}startRealtimeUpdates(){this.realtimeUpdateConfig.enabled&&null===this.updateTimerId&&(this.getNounCount().then(e=>{this.lastKnownNounCount=e}).catch(e=>{console.warn("Failed to get initial noun count for real-time updates:",e)}),this.updateTimerId=setInterval(()=>{this.checkForUpdates().catch(e=>{console.warn("Error during real-time update check:",e)})},this.realtimeUpdateConfig.interval),this.loggingConfig?.verbose&&console.log(`Real-time updates started with interval: ${this.realtimeUpdateConfig.interval}ms`))}stopRealtimeUpdates(){null!==this.updateTimerId&&(clearInterval(this.updateTimerId),this.updateTimerId=null,this.loggingConfig?.verbose&&console.log("Real-time updates stopped"))}async checkForUpdatesNow(){return await this.ensureInitialized(),this.checkForUpdates()}enableRealtimeUpdates(e){e&&(this.realtimeUpdateConfig={...this.realtimeUpdateConfig,...e}),this.realtimeUpdateConfig.enabled=!0,this.isInitialized&&this.startRealtimeUpdates()}disableRealtimeUpdates(){this.realtimeUpdateConfig.enabled=!1,this.stopRealtimeUpdates()}getRealtimeUpdateConfig(){return{...this.realtimeUpdateConfig}}async checkForUpdates(){if(this.isInitialized&&this.storage)try{const e=Date.now();if(this.realtimeUpdateConfig.updateStatistics&&(await this.storage.flushStatisticsToStorage(),await this.getStatistics({forceRefresh:!0})),this.realtimeUpdateConfig.updateIndex&&("function"==typeof this.storage.getChangesSince?await this.applyChangesFromLog():await this.applyChangesFromFullScan()),this.lastUpdateTime=Date.now(),this.loggingConfig?.verbose){const t=this.lastUpdateTime-e;console.log(`Real-time update completed in ${t}ms`)}}catch(e){console.error("Failed to check for updates:",e)}}async applyChangesFromLog(){if(this.storage&&"function"==typeof this.storage.getChangesSince)try{const e=await this.storage.getChangesSince(this.lastUpdateTime,1e3);let t=0,n=0,r=0;for(const a of e)try{switch(a.operation){case"add":case"update":if("noun"===a.entityType&&a.data){const e=a.data;if(e.vector.length!==this._dimensions){console.warn(`Skipping noun ${e.id} due to dimension mismatch: expected ${this._dimensions}, got ${e.vector.length}`);continue}await this.index.addItem({id:e.id,vector:e.vector}),"add"===a.operation?t++:n++,this.loggingConfig?.verbose&&console.log(`${"add"===a.operation?"Added":"Updated"} noun ${e.id} in index during real-time update`)}break;case"delete":"noun"===a.entityType&&(await this.index.removeItem(a.entityId),r++,this.loggingConfig?.verbose&&console.log(`Removed noun ${a.entityId} from index during real-time update`))}}catch(e){console.error(`Failed to apply change ${a.operation} for ${a.entityType} ${a.entityId}:`,e)}this.loggingConfig?.verbose&&(t>0||n>0||r>0)&&console.log(`Real-time update: Added ${t}, updated ${n}, deleted ${r} nouns using change log`),this.lastKnownNounCount=await this.getNounCount()}catch(e){console.error("Failed to apply changes from log, falling back to full scan:",e),await this.applyChangesFromFullScan()}}async applyChangesFromFullScan(){try{const e=await this.getNounCount();if(e!==this.lastKnownNounCount){const t=await this.storage.getAllNouns(),n=this.index.getNouns(),r=new Set(n.keys()),a=t.filter(e=>!r.has(e.id));for(const e of a)e.vector.length===this._dimensions?(await this.index.addItem({id:e.id,vector:e.vector}),this.loggingConfig?.verbose&&console.log(`Added new noun ${e.id} to index during real-time update`)):console.warn(`Skipping noun ${e.id} due to dimension mismatch: expected ${this._dimensions}, got ${e.vector.length}`);this.lastKnownNounCount=e,this.loggingConfig?.verbose&&a.length>0&&console.log(`Real-time update: Added ${a.length} new nouns to index using full scan`)}}catch(e){throw console.error("Failed to apply changes from full scan:",e),e}}getCurrentAugmentation(){try{const e=He.getAvailableAugmentationTypes();for(const t of e){const e=He.getAugmentationsByType(t);for(const t of e)if(t.enabled)return t.name}return"default"}catch(e){return console.warn("Failed to detect current augmentation:",e),"default"}}async init(){if(!this.isInitialized&&!this.isInitializing){this.isInitializing=!0;try{try{await this.embeddingFunction("")}catch(e){console.warn("Failed to pre-load Universal Sentence Encoder:",e);try{await new Promise(e=>setTimeout(e,1e3));const{createTensorFlowEmbeddingFunction:e}=await Promise.resolve().then(function(){return re}),t=e();await t(""),console.log("Successfully loaded Universal Sentence Encoder with fallback method"),this.embeddingFunction=t}catch(e){console.error("All attempts to load Universal Sentence Encoder failed:",e)}}if(!this.storage){let e={...this.storageConfig,requestPersistentStorage:this.requestPersistentStorage};if(e.s3Storage)if(e.s3Storage.bucketName&&e.s3Storage.accessKeyId&&e.s3Storage.secretAccessKey);else{const{s3Storage:t,...n}=e;e=n,console.warn("Ignoring s3Storage configuration due to missing required fields")}this.storage=await Oe(e)}if(await this.storage.init(),this.useOptimizedIndex&&this.index instanceof le&&this.index.setStorage(this.storage),this.writeOnly)this.loggingConfig?.verbose&&console.log("Database is in write-only mode, skipping index loading");else{const e=await this.storage.getAllNouns();this.index.clear();for(const t of e)t.vector.length===this._dimensions?await this.index.addItem({id:t.id,vector:t.vector}):(console.warn(`Deleting noun ${t.id} due to dimension mismatch: expected ${this._dimensions}, got ${t.vector.length}`),await this.storage.deleteNoun(t.id))}if(this.remoteServerConfig&&this.remoteServerConfig.autoConnect)try{await this.connectToRemoteServer(this.remoteServerConfig.url,this.remoteServerConfig.protocols)}catch(e){console.warn("Failed to auto-connect to remote server:",e)}this.isInitialized=!0,this.isInitializing=!1,this.startRealtimeUpdates()}catch(e){throw console.error("Failed to initialize BrainyData:",e),this.isInitializing=!1,new Error(`Failed to initialize BrainyData: ${e}`)}}}async connectToRemoteServer(e,t){await this.ensureInitialized();try{const{conduit:n,connection:r}=await Ge(e,{protocols:t,localDb:this});return this.serverSearchConduit=n,this.serverConnection=r,r}catch(e){throw console.error("Failed to connect to remote server:",e),new Error(`Failed to connect to remote server: ${e}`)}}async add(e,t,n={}){if(await this.ensureInitialized(),this.checkReadOnly(),null==e)throw new Error("Input cannot be null or undefined");try{let r;if(Array.isArray(e))for(let t=0;t<e.length;t++)if("number"!=typeof e[t])throw new Error("Vector contains non-numeric values");if(Array.isArray(e)&&!n.forceEmbed)r=e;else try{r=await this.embeddingFunction(e)}catch(e){throw new Error(`Failed to vectorize data: ${e}`)}if(!r)throw new Error("Vector is undefined or null");if(r.length!==this._dimensions)throw new Error(`Vector dimension mismatch: expected ${this._dimensions}, got ${r.length}`);const a=n.id||(t&&"object"==typeof t&&"id"in t?t.id:_());await this.index.addItem({id:a,vector:r});const s=this.index.getNouns().get(a);if(!s)throw new Error(`Failed to retrieve newly created noun with ID ${a}`);await this.storage.saveNoun(s);const o=n.service||this.getCurrentAugmentation();if(await this.storage.incrementStatistic("noun",o),void 0!==t)if(t&&"object"==typeof t&&0===Object.keys(t).length)await this.storage.saveMetadata(a,null);else{if(t&&"object"==typeof t&&"noun"in t){const e=t.noun;Object.values(Fe).includes(e)||(console.warn(`Invalid noun type: ${e}. Falling back to GraphNoun.`),t.noun=Fe.Concept);const r=n.service||this.getCurrentAugmentation(),a=t;a.createdBy&&!n.service||(a.createdBy={augmentation:r,version:"1.0"});const s=new Date,o={seconds:Math.floor(s.getTime()/1e3),nanoseconds:s.getTime()%1e3*1e6};a.createdAt||(a.createdAt=o),a.updatedAt=o}let e=t;t&&"object"==typeof t&&(e={...t}),await this.storage.saveMetadata(a,e);const r=n.service||this.getCurrentAugmentation();await this.storage.incrementStatistic("metadata",r)}if(await this.storage.updateHnswIndexSize(await this.getNounCount()),n.addToRemote&&this.isConnectedToRemoteServer())try{await this.addToRemote(a,r,t)}catch(e){console.warn(`Failed to add to remote server: ${e}. Continuing with local add.`)}return a}catch(e){throw console.error("Failed to add vector:",e),new Error(`Failed to add vector: ${e}`)}}async addItem(e,t,n={}){return this.add(e,t,{...n,forceEmbed:!0})}async addToBoth(e,t,n={}){if(!this.isConnectedToRemoteServer())throw new Error("Not connected to a remote server. Call connectToRemoteServer() first.");return this.add(e,t,{...n,addToRemote:!0})}async addToRemote(e,t,n){if(!this.isConnectedToRemoteServer())return!1;try{if(!this.serverSearchConduit||!this.serverConnection)throw new Error("Server search conduit or connection is not initialized");const e=await this.serverSearchConduit.addToBoth(this.serverConnection.connectionId,t,n);if(!e.success)throw new Error(`Remote add failed: ${e.error}`);return!0}catch(e){throw console.error("Failed to add to remote server:",e),new Error(`Failed to add to remote server: ${e}`)}}async addBatch(e,t={}){await this.ensureInitialized(),this.checkReadOnly(),t.concurrency;const n=t.batchSize||50;try{const r=[],a=[...e];for(;a.length>0;){const e=a.splice(0,n),s=[],o=[];e.forEach((e,n)=>{if(Array.isArray(e.vectorOrData)&&e.vectorOrData.every(e=>"number"==typeof e)&&!t.forceEmbed)s.push({vectorOrData:e.vectorOrData,metadata:e.metadata,index:n});else if("string"==typeof e.vectorOrData)o.push({text:e.vectorOrData,metadata:e.metadata,index:n});else{const t=String(e.vectorOrData);o.push({text:t,metadata:e.metadata,index:n})}});const i=s.map(e=>this.add(e.vectorOrData,e.metadata,t));let c=[];if(o.length>0){const e=o.map(e=>e.text),n=await te(e);c=o.map((e,r)=>this.add(n[r],e.metadata,{...t,forceEmbed:!1}))}const l=await Promise.all([...i,...c]);r.push(...l)}return r}catch(e){throw console.error("Failed to add batch of items:",e),new Error(`Failed to add batch of items: ${e}`)}}async addBatchToBoth(e,t={}){if(!this.isConnectedToRemoteServer())throw new Error("Not connected to a remote server. Call connectToRemoteServer() first.");return this.addBatch(e,{...t,addToRemote:!0})}filterResultsByService(e,t){return t?e.filter(e=>{if(!e.metadata||"object"!=typeof e.metadata)return!1;if(!("createdBy"in e.metadata))return!1;const n=e.metadata.createdBy;return!!n&&n.augmentation===t}):e}async searchByNounTypes(e,t=10,n=null,r={}){if(!this.isInitialized)throw new Error("BrainyData must be initialized before searching. Call init() first.");this.checkWriteOnly();try{let a;if(Array.isArray(e)&&e.every(e=>"number"==typeof e)&&!r.forceEmbed)a=e;else try{a=await this.embeddingFunction(e)}catch(e){throw new Error(`Failed to vectorize query data: ${e}`)}if(!a)throw new Error("Query vector is undefined or null");if(a.length!==this._dimensions)throw new Error(`Query vector dimension mismatch: expected ${this._dimensions}, got ${a.length}`);if(n&&0!==n.length){const e=n.map(e=>this.storage.getNounsByNounType(e)),s=await Promise.all(e),o=[];for(const e of s)o.push(...e);const i=[];for(const e of o){const t=this.index.getDistanceFunction()(a,e.vector);i.push([e.id,t])}i.sort((e,t)=>e[1]-t[1]);const c=i.slice(0,t),l=[];for(const[e,t]of c){const n=o.find(t=>t.id===e);if(!n)continue;let r=await this.storage.getMetadata(e);null===r&&(r={}),r&&"object"==typeof r&&(r={...r,id:e}),l.push({id:e,score:t,vector:n.vector,metadata:r})}return this.filterResultsByService(l,r.service)}{const e=await this.index.search(a,t),n=[];for(const[t,r]of e){const e=this.index.getNouns().get(t);if(!e)continue;let a=await this.storage.getMetadata(t);null===a&&(a={}),a&&"object"==typeof a&&(a={...a,id:t}),n.push({id:t,score:r,vector:e.vector,metadata:a})}return this.filterResultsByService(n,r.service)}}catch(e){throw console.error("Failed to search vectors by noun types:",e),new Error(`Failed to search vectors by noun types: ${e}`)}}async search(e,t=10,n={}){if(null==e)throw new Error("Query cannot be null or undefined");if(t<=0||"number"!=typeof t||isNaN(t))throw new Error("Parameter k must be a positive number");if(!this.isInitialized)throw new Error("BrainyData must be initialized before searching. Call init() first.");if(this.checkWriteOnly(),n.searchVerbs){return(await this.searchVerbs(e,t,{forceEmbed:n.forceEmbed,verbTypes:n.verbTypes})).map(e=>({id:e.id,score:e.similarity,vector:e.embedding||[],metadata:{verb:e.verb,source:e.source,target:e.target,...e.data}}))}return n.searchConnectedNouns?this.searchNounsByVerbs(e,t,{forceEmbed:n.forceEmbed,verbTypes:n.verbTypes,direction:n.verbDirection}):"local"===n.searchMode?this.searchLocal(e,t,n):"remote"===n.searchMode?this.searchRemote(e,t,n):"combined"===n.searchMode?this.searchCombined(e,t,n):this.searchLocal(e,t,n)}async searchLocal(e,t=10,n={}){if(!this.isInitialized)throw new Error("BrainyData must be initialized before searching. Call init() first.");this.checkWriteOnly();let r,a=e;if("string"!=typeof e||n.forceEmbed||(a=await this.embed(e),n.forceEmbed=!1),r=n.nounTypes&&n.nounTypes.length>0?await this.searchByNounTypes(a,t,n.nounTypes,{forceEmbed:n.forceEmbed,service:n.service}):await this.searchByNounTypes(a,t,null,{forceEmbed:n.forceEmbed,service:n.service}),n.includeVerbs&&this.storage)for(const e of r)try{const t=await this.storage.getVerbsBySource(e.id),n=await this.storage.getVerbsByTarget(e.id),r=[...t,...n];e.metadata||(e.metadata={}),e.metadata.associatedVerbs=r}catch(t){console.warn(`Failed to retrieve verbs for noun ${e.id}:`,t)}return r}async findSimilar(e,t={}){await this.ensureInitialized();const n=await this.get(e);if(!n)throw new Error(`Entity with ID ${e} not found`);if(t.relationType){const n=(await this.storage.getVerbsBySource(e)).filter(e=>e.type===t.relationType).map(e=>e.target),r=[];for(const e of n){if("string"!=typeof e)continue;const t=await this.get(e);t&&r.push({id:e,score:1,vector:t.vector,metadata:t.metadata})}return r.slice(0,t.limit||10)}const r=(t.limit||10)+1;return(await this.search(n.vector,r,{forceEmbed:!1,nounTypes:t.nounTypes,includeVerbs:t.includeVerbs,searchMode:t.searchMode})).filter(t=>t.id!==e).slice(0,t.limit||10)}async get(e){if(null==e)throw new Error("ID cannot be null or undefined");await this.ensureInitialized();try{const t=this.index.getNouns().get(e);if(!t)return null;let n=await this.storage.getMetadata(e);if(null===n)n={};else if("object"==typeof n)if(1===Object.keys(n).length&&"id"in n)n={};else if("id"in n){const{id:e,...t}=n;n=t}return{id:e,vector:t.vector,metadata:n}}catch(t){throw console.error(`Failed to get vector ${e}:`,t),new Error(`Failed to get vector ${e}: ${t}`)}}async getAllNouns(){await this.ensureInitialized();try{const e=this.index.getNouns(),t=[];for(const[n,r]of e.entries()){const e=await this.storage.getMetadata(n);t.push({id:n,vector:r.vector,metadata:e})}return t}catch(e){throw console.error("Failed to get all nouns:",e),new Error(`Failed to get all nouns: ${e}`)}}async delete(e,t={}){if(null==e)throw new Error("ID cannot be null or undefined");await this.ensureInitialized(),this.checkReadOnly();try{if(!this.index.removeItem(e))return!1;await this.storage.deleteNoun(e);const n=t.service||"default";await this.storage.decrementStatistic("noun",n);try{await this.storage.saveMetadata(e,null),await this.storage.decrementStatistic("metadata",n)}catch(e){}return!0}catch(t){throw console.error(`Failed to delete vector ${e}:`,t),new Error(`Failed to delete vector ${e}: ${t}`)}}async updateMetadata(e,t,n={}){if(null==e)throw new Error("ID cannot be null or undefined");if(null==t)throw new Error("Metadata cannot be null or undefined");await this.ensureInitialized(),this.checkReadOnly();try{if(!this.index.getNouns().get(e))throw new Error(`Vector with ID ${e} does not exist`);if(t&&"object"==typeof t&&"noun"in t){const r=t.noun;Object.values(Fe).includes(r)||(console.warn(`Invalid noun type: ${r}. Falling back to GraphNoun.`),t.noun=Fe.Concept);const a=n.service||this.getCurrentAugmentation(),s=t,o=await this.storage.getMetadata(e);if(o&&"object"==typeof o&&"createdBy"in o)s.createdBy=o.createdBy,"createdAt"in o&&(s.createdAt=o.createdAt);else if(!s.createdBy&&(s.createdBy={augmentation:a,version:"1.0"},!s.createdAt)){const e=new Date;s.createdAt={seconds:Math.floor(e.getTime()/1e3),nanoseconds:e.getTime()%1e3*1e6}}const i=new Date;s.updatedAt={seconds:Math.floor(i.getTime()/1e3),nanoseconds:i.getTime()%1e3*1e6}}await this.storage.saveMetadata(e,t);const r=n.service||this.getCurrentAugmentation();return await this.storage.incrementStatistic("metadata",r),!0}catch(t){throw console.error(`Failed to update metadata for vector ${e}:`,t),new Error(`Failed to update metadata for vector ${e}: ${t}`)}}async relate(e,t,n,r){if(null==e)throw new Error("Source ID cannot be null or undefined");if(null==t)throw new Error("Target ID cannot be null or undefined");if(null==n)throw new Error("Relation type cannot be null or undefined");return this.addVerb(e,t,void 0,{type:n,metadata:r})}async connect(e,t,n,r){return this.relate(e,t,n,r)}async addVerb(e,t,n,r={}){if(await this.ensureInitialized(),this.checkReadOnly(),null==e)throw new Error("Source ID cannot be null or undefined");if(null==t)throw new Error("Target ID cannot be null or undefined");try{let a=this.index.getNouns().get(e),s=this.index.getNouns().get(t);if(!a&&r.autoCreateMissingNouns)try{const t=new Array(this._dimensions).fill(0),n=r.service||this.getCurrentAugmentation(),s=new Date,o={seconds:Math.floor(s.getTime()/1e3),nanoseconds:s.getTime()%1e3*1e6},i=r.missingNounMetadata||{autoCreated:!0,createdAt:o,updatedAt:o,noun:Fe.Concept,createdBy:{augmentation:n,version:"1.0"}};await this.add(t,i,{id:e}),a=this.index.getNouns().get(e),console.warn(`Auto-created missing source noun with ID ${e}`)}catch(t){throw console.error(`Failed to auto-create source noun with ID ${e}:`,t),new Error(`Failed to auto-create source noun with ID ${e}: ${t}`)}if(!s&&r.autoCreateMissingNouns)try{const e=new Array(this._dimensions).fill(0),n=r.service||this.getCurrentAugmentation(),a=new Date,o={seconds:Math.floor(a.getTime()/1e3),nanoseconds:a.getTime()%1e3*1e6},i=r.missingNounMetadata||{autoCreated:!0,createdAt:o,updatedAt:o,noun:Fe.Concept,createdBy:{augmentation:n,version:"1.0"}};await this.add(e,i,{id:t}),s=this.index.getNouns().get(t),console.warn(`Auto-created missing target noun with ID ${t}`)}catch(e){throw console.error(`Failed to auto-create target noun with ID ${t}:`,e),new Error(`Failed to auto-create target noun with ID ${t}: ${e}`)}if(!a)throw new Error(`Source noun with ID ${e} not found`);if(!s)throw new Error(`Target noun with ID ${t} not found`);const o=r.id||_();let i;if(!r.metadata||n&&!r.forceEmbed)if(n)i=n;else{if(!a.vector||!s.vector||0===a.vector.length||0===s.vector.length||a.vector.length!==s.vector.length)throw new Error("Cannot average vectors: source or target vector is invalid or dimensions don't match");i=a.vector.map((e,t)=>(e+s.vector[t])/2)}else try{let e;e="string"==typeof r.metadata?r.metadata:r.metadata.description&&"string"==typeof r.metadata.description?r.metadata.description:JSON.stringify(r.metadata),"string"!=typeof e&&(e=String(e)),i=await this.embeddingFunction(e)}catch(e){throw new Error(`Failed to vectorize verb metadata: ${e}`)}let c=r.type;c||(c=De.RelatedTo);const l=r.service||this.getCurrentAugmentation(),u=new Date,d={seconds:Math.floor(u.getTime()/1e3),nanoseconds:u.getTime()%1e3*1e6},h={id:o,vector:i,connections:new Map,sourceId:e,targetId:t,source:e,target:t,verb:c,type:c,weight:r.weight,metadata:r.metadata,createdAt:d,updatedAt:d,createdBy:{augmentation:l,version:"1.0"}};await this.index.addItem({id:o,vector:i});const p=this.index.getNouns().get(o);if(!p)throw new Error(`Failed to retrieve newly created verb noun with ID ${o}`);h.connections=p.connections,await this.storage.saveVerb(h);const f=r.service||"default";return await this.storage.incrementStatistic("verb",f),await this.storage.updateHnswIndexSize(await this.getNounCount()),o}catch(e){throw console.error("Failed to add verb:",e),new Error(`Failed to add verb: ${e}`)}}async getVerb(e){await this.ensureInitialized();try{return await this.storage.getVerb(e)}catch(t){throw console.error(`Failed to get verb ${e}:`,t),new Error(`Failed to get verb ${e}: ${t}`)}}async getAllVerbs(){await this.ensureInitialized();try{return await this.storage.getAllVerbs()}catch(e){throw console.error("Failed to get all verbs:",e),new Error(`Failed to get all verbs: ${e}`)}}async getVerbsBySource(e){await this.ensureInitialized();try{return await this.storage.getVerbsBySource(e)}catch(t){throw console.error(`Failed to get verbs by source ${e}:`,t),new Error(`Failed to get verbs by source ${e}: ${t}`)}}async getVerbsByTarget(e){await this.ensureInitialized();try{return await this.storage.getVerbsByTarget(e)}catch(t){throw console.error(`Failed to get verbs by target ${e}:`,t),new Error(`Failed to get verbs by target ${e}: ${t}`)}}async getVerbsByType(e){await this.ensureInitialized();try{return await this.storage.getVerbsByType(e)}catch(t){throw console.error(`Failed to get verbs by type ${e}:`,t),new Error(`Failed to get verbs by type ${e}: ${t}`)}}async deleteVerb(e,t={}){await this.ensureInitialized(),this.checkReadOnly();try{if(!this.index.removeItem(e))return!1;await this.storage.deleteVerb(e);const n=t.service||"default";return await this.storage.decrementStatistic("verb",n),!0}catch(t){throw console.error(`Failed to delete verb ${e}:`,t),new Error(`Failed to delete verb ${e}: ${t}`)}}async clear(){await this.ensureInitialized(),this.checkReadOnly();try{await this.index.clear(),await this.storage.clear()}catch(e){throw console.error("Failed to clear vector database:",e),new Error(`Failed to clear vector database: ${e}`)}}size(){return this.index.size()}async getNounCount(){const e=await this.storage.getAllVerbs(),t=new Set(e.map(e=>e.id)),n=this.index.getNouns();let r=0;for(const[e]of n.entries())t.has(e)||r++;return r}async flushStatistics(){if(await this.ensureInitialized(),!this.storage)throw new Error("Storage not initialized");await this.storage.flushStatisticsToStorage()}async getStatistics(e={}){await this.ensureInitialized();try{e.forceRefresh&&this.storage&&await this.storage.flushStatisticsToStorage();const t=await this.storage.getStatistics();if(t){const n={nounCount:0,verbCount:0,metadataCount:0,hnswIndexSize:t.hnswIndexSize,nouns:{count:0},verbs:{count:0},metadata:{count:0},operations:{add:0,search:0,delete:0,update:0,relate:0,total:0},serviceBreakdown:{}},r=e.service?Array.isArray(e.service)?e.service:[e.service]:Object.keys({...t.nounCount,...t.verbCount,...t.metadataCount});for(const e of r){const r=t.nounCount[e]||0,a=t.verbCount[e]||0,s=t.metadataCount[e]||0;n.nounCount+=r,n.verbCount+=a,n.metadataCount+=s,n.serviceBreakdown[e]={nounCount:r,verbCount:a,metadataCount:s}}return n.nouns.count=n.nounCount,n.verbs.count=n.verbCount,n.metadata.count=n.metadataCount,n.operations={add:n.nounCount,search:0,delete:0,update:n.metadataCount,relate:n.verbCount,total:n.nounCount+n.verbCount+n.metadataCount},n}console.warn("Persistent statistics not available, calculating on-demand");const n=(await this.storage.getAllVerbs()).length,r=await this.getNounCount();let a=0;const s=this.index.getNouns();for(const[e]of s.entries())try{const t=await this.storage.getMetadata(e);null!=t&&a++}catch(e){}const o=r,i={nounCount:r,verbCount:n,metadataCount:a,hnswIndexSize:o,nouns:{count:r},verbs:{count:n},metadata:{count:a},operations:{add:r,search:0,delete:0,update:a,relate:n,total:r+n+a}},c="default";return await this.storage.saveStatistics({nounCount:{[c]:r},verbCount:{[c]:n},metadataCount:{[c]:a},hnswIndexSize:o,lastUpdated:(new Date).toISOString()}),i}catch(e){throw console.error("Failed to get statistics:",e),new Error(`Failed to get statistics: ${e}`)}}isReadOnly(){return this.readOnly}setReadOnly(e){this.readOnly=e,e&&this.writeOnly&&(this.writeOnly=!1)}isWriteOnly(){return this.writeOnly}setWriteOnly(e){this.writeOnly=e,e&&this.readOnly&&(this.readOnly=!1)}async embed(e){await this.ensureInitialized();try{return await this.embeddingFunction(e)}catch(e){throw console.error("Failed to embed data:",e),new Error(`Failed to embed data: ${e}`)}}async searchVerbs(e,t=10,n={}){await this.ensureInitialized(),this.checkWriteOnly();try{let r;if(Array.isArray(e)&&e.every(e=>"number"==typeof e)&&!n.forceEmbed)r=e;else try{r=await this.embeddingFunction(e)}catch(e){throw new Error(`Failed to vectorize query data: ${e}`)}const a=await this.index.search(r,2*t),s=await this.storage.getAllVerbs(),o=new Map;for(const e of s)o.set(e.id,e);const i=[];for(const e of a){const[t,r]=e,a=o.get(t);if(a){if(n.verbTypes&&n.verbTypes.length>0&&(!a.type||!n.verbTypes.includes(a.type)))continue;i.push({...a,similarity:r})}}if(i.length<t){console.warn("Not enough verb results from HNSW index, falling back to manual search");let e=[];if(n.verbTypes&&n.verbTypes.length>0){const t=n.verbTypes.map(e=>this.getVerbsByType(e)),r=await Promise.all(t);for(const t of r)e.push(...t)}else e=s;const t=new Set(i.map(e=>e.id));for(const n of e)if(!t.has(n.id)&&n.vector&&n.vector.length>0){const e=this.index.getDistanceFunction()(r,n.vector);i.push({...n,similarity:e})}}return i.sort((e,t)=>e.similarity-t.similarity),i.slice(0,t)}catch(e){throw console.error("Failed to search verbs:",e),new Error(`Failed to search verbs: ${e}`)}}async searchNounsByVerbs(e,t=10,n={}){await this.ensureInitialized(),this.checkWriteOnly();try{const r=await this.searchByNounTypes(e,2*t,null,{forceEmbed:n.forceEmbed});if(!n.verbTypes||0===n.verbTypes.length)return r.slice(0,t);const a=new Set,s=n.direction||"both";for(const e of r){let t=[];if("outgoing"===s||"both"===s){const n=await this.storage.getVerbsBySource(e.id);t.push(...n)}if("incoming"===s||"both"===s){const n=await this.storage.getVerbsByTarget(e.id);t.push(...n)}n.verbTypes&&n.verbTypes.length>0&&(t=t.filter(e=>e.verb&&n.verbTypes.includes(e.verb)));for(const n of t)n.source&&n.source!==e.id&&a.add(n.source),n.target&&n.target!==e.id&&a.add(n.target)}const o=[];for(const t of a)try{const r=this.index.getNouns().get(t);if(r){const a=await this.storage.getMetadata(t);let s;s=Array.isArray(e)&&e.every(e=>"number"==typeof e)&&!n.forceEmbed?e:await this.embeddingFunction(e);const i=this.index.getDistanceFunction()(s,r.vector);o.push({id:t,score:i,vector:r.vector,metadata:a})}}catch(e){console.warn(`Failed to retrieve noun ${t}:`,e)}return o.sort((e,t)=>e.score-t.score),o.slice(0,t)}catch(e){throw console.error("Failed to search nouns by verbs:",e),new Error(`Failed to search nouns by verbs: ${e}`)}}async searchText(e,t=10,n={}){await this.ensureInitialized(),this.checkWriteOnly();try{const r=await this.embed(e);return await this.search(r,t,{nounTypes:n.nounTypes,includeVerbs:n.includeVerbs,searchMode:n.searchMode})}catch(e){throw console.error("Failed to search with text query:",e),new Error(`Failed to search with text query: ${e}`)}}async searchRemote(e,t=10,n={}){if(await this.ensureInitialized(),this.checkWriteOnly(),!this.isConnectedToRemoteServer())throw new Error("Not connected to a remote server. Call connectToRemoteServer() first.");try{let n;if(n="string"==typeof e?e:"vector-query",!this.serverSearchConduit||!this.serverConnection)throw new Error("Server search conduit or connection is not initialized");const r=await this.serverSearchConduit.searchServer(this.serverConnection.connectionId,n,t);if(!r.success)throw new Error(`Remote search failed: ${r.error}`);return r.data}catch(e){throw console.error("Failed to search remote server:",e),new Error(`Failed to search remote server: ${e}`)}}async searchCombined(e,t=10,n={}){if(await this.ensureInitialized(),this.checkWriteOnly(),!this.isConnectedToRemoteServer())return this.searchLocal(e,t,n);try{if(!1!==n.localFirst){const r=await this.searchLocal(e,t,n);if(r.length>=t)return r;const a=await this.searchRemote(e,t-r.length,{...n,storeResults:!0}),s=[...r],o=new Set(r.map(e=>e.id));for(const e of a)o.has(e.id)||s.push(e);return s}{const r=await this.searchRemote(e,t,{...n,storeResults:!0});if(r.length>=t)return r;const a=await this.searchLocal(e,t-r.length,n),s=[...r],o=new Set(r.map(e=>e.id));for(const e of a)o.has(e.id)||s.push(e);return s}}catch(e){throw console.error("Failed to perform combined search:",e),new Error(`Failed to perform combined search: ${e}`)}}isConnectedToRemoteServer(){return!(!this.serverSearchConduit||!this.serverConnection)}async disconnectFromRemoteServer(){if(!this.isConnectedToRemoteServer())return!1;try{if(!this.serverSearchConduit||!this.serverConnection)throw new Error("Server search conduit or connection is not initialized");return await this.serverSearchConduit.closeWebSocket(this.serverConnection.connectionId),this.serverSearchConduit=null,this.serverConnection=null,!0}catch(e){throw console.error("Failed to disconnect from remote server:",e),new Error(`Failed to disconnect from remote server: ${e}`)}}async ensureInitialized(){if(!this.isInitialized)if(this.isInitializing){let e=0;const t=100,n=50;for(;this.isInitializing&&!this.isInitialized&&e<t;)await new Promise(e=>setTimeout(e,n)),e++;this.isInitialized||await this.init()}else await this.init()}async status(){if(await this.ensureInitialized(),!this.storage)return{type:"any",used:0,quota:null,details:{error:"Storage not initialized"}};try{if("function"!=typeof this.storage.getStorageStatus){return{type:this.storage.constructor.name.toLowerCase().replace("storage","")||"any",used:0,quota:null,details:{error:"Storage adapter does not implement getStorageStatus method",storageAdapter:this.storage.constructor.name,indexSize:this.size()}}}const e=await this.storage.getStorageStatus();let t={indexSize:this.size()};if(this.useOptimizedIndex&&this.index instanceof le){const e=this.index;t={...t,optimized:!0,memoryUsage:e.getMemoryUsage(),productQuantization:e.getUseProductQuantization(),diskBasedIndex:e.getUseDiskBasedIndex()}}else t.optimized=!1;return{type:e.type||"any",used:e.used||0,quota:e.quota||null,details:{...e.details||{},index:t}}}catch(e){console.error("Failed to get storage status:",e);return{type:this.storage.constructor.name.toLowerCase().replace("storage","")||"any",used:0,quota:null,details:{error:String(e),storageAdapter:this.storage.constructor.name,indexSize:this.size()}}}}async shutDown(){try{if(this.stopRealtimeUpdates(),this.storage&&this.isInitialized)try{await this.flushStatistics()}catch(e){console.warn("Failed to flush statistics during shutdown:",e)}this.isConnectedToRemoteServer()&&await this.disconnectFromRemoteServer(),z(),this.isInitialized=!1}catch(e){throw console.error("Failed to shut down BrainyData:",e),new Error(`Failed to shut down BrainyData: ${e}`)}}async backup(){await this.ensureInitialized();try{const e=await this.getAllNouns(),t=await this.getAllVerbs(),n=Object.values(Fe),r=Object.values(De),a={entryPointId:this.index.getEntryPointId(),maxLevel:this.index.getMaxLevel(),dimension:this.index.getDimension(),config:this.index.getConfig(),connections:{}},s=this.index.getNouns();for(const[e,t]of s.entries()){a.connections[e]={};for(const[n,r]of t.connections.entries())a.connections[e][n]=Array.from(r)}return{nouns:e,verbs:t,nounTypes:n,verbTypes:r,hnswIndex:a,version:"1.0.0"}}catch(e){throw console.error("Failed to backup data:",e),new Error(`Failed to backup data: ${e}`)}}async importSparseData(e,t={}){return this.restore(e,t)}async restore(e,t={}){await this.ensureInitialized(),this.checkReadOnly();try{if(t.clearExisting&&await this.clear(),!(e&&e.nouns&&e.verbs&&e.version))throw new Error("Invalid restore data format");e.nounTypes&&console.log(`Found ${e.nounTypes.length} noun types in restore data`),e.verbTypes&&console.log(`Found ${e.verbTypes.length} verb types in restore data`),e.hnswIndex&&console.log("Found HNSW index data in backup");let n=0;for(const t of e.nouns)try{t.vector&&0!==t.vector.length||(t.metadata&&"object"==typeof t.metadata&&"text"in t.metadata?t.vector=await this.embeddingFunction(t.metadata.text):t.vector=await this.embeddingFunction(t.metadata)),await this.add(t.vector,t.metadata,{id:t.id}),n++}catch(e){console.error(`Failed to restore noun ${t.id}:`,e)}let r=0;for(const t of e.verbs)try{t.vector&&0!==t.vector.length||(t.metadata&&"object"==typeof t.metadata&&"text"in t.metadata?t.vector=await this.embeddingFunction(t.metadata.text):t.vector=await this.embeddingFunction(t.metadata)),await this.addVerb(t.sourceId,t.targetId,t.vector,{id:t.id,type:t.metadata?.verb||De.RelatedTo,metadata:t.metadata}),r++}catch(e){console.error(`Failed to restore verb ${t.id}:`,e)}if(e.hnswIndex&&n>0)try{console.log("Reconstructing HNSW index from backup data..."),this.index=new le(e.hnswIndex.config,this.distanceFunction,this.storage),this.useOptimizedIndex=!0;for(const t of e.nouns)t.vector&&t.vector.length>0&&await this.index.addItem({id:t.id,vector:t.vector});console.log("HNSW index reconstruction complete")}catch(e){console.error("Failed to reconstruct HNSW index:",e),console.log("Continuing with standard restore process...")}return{nounsRestored:n,verbsRestored:r}}catch(e){throw console.error("Failed to restore data:",e),new Error(`Failed to restore data: ${e}`)}}async generateRandomGraph(e={}){await this.ensureInitialized(),this.checkReadOnly();const t=e.nounCount||10,n=e.verbCount||20,r=e.nounTypes||Object.values(Fe),a=e.verbTypes||Object.values(De);(e.clearExisting||!1)&&await this.clear();try{const e=[],s={[Fe.Person]:"A person with unique characteristics",[Fe.Location]:"A location with specific attributes",[Fe.Thing]:"An object with distinct properties",[Fe.Event]:"An occurrence with temporal aspects",[Fe.Concept]:"An abstract idea or notion",[Fe.Content]:"A piece of content or information",[Fe.Collection]:"A collection of related entities",[Fe.Organization]:"An organization or institution",[Fe.Document]:"A document or text-based file"};for(let n=0;n<t;n++){const t=r[Math.floor(Math.random()*r.length)],a={noun:t,label:`Random ${t} ${n+1}`,description:s[t]||`A random ${t}`,randomAttributes:{value:100*Math.random(),priority:Math.floor(5*Math.random())+1,tags:["tag-"+n%5,"category-"+n%3]}},o=await this.add(a.description,a);e.push(o)}const o=[],i={[De.AttributedTo]:"Attribution relationship",[De.Owns]:"Ownership relationship",[De.Creates]:"Creation relationship",[De.Uses]:"Utilization relationship",[De.BelongsTo]:"Belonging relationship",[De.MemberOf]:"Membership relationship",[De.RelatedTo]:"General relationship",[De.WorksWith]:"Collaboration relationship",[De.FriendOf]:"Friendship relationship",[De.ReportsTo]:"Reporting relationship",[De.Supervises]:"Supervision relationship",[De.Mentors]:"Mentorship relationship"};for(let t=0;t<n;t++){const n=Math.floor(Math.random()*e.length);let r=Math.floor(Math.random()*e.length);for(;r===n&&e.length>1;)r=Math.floor(Math.random()*e.length);const s=e[n],c=e[r],l=a[Math.floor(Math.random()*a.length)],u={verb:l,description:i[l]||`A random ${l} relationship`,weight:Math.random(),confidence:Math.random(),randomAttributes:{strength:100*Math.random(),duration:Math.floor(365*Math.random())+1,tags:["relation-"+t%5,"strength-"+t%3]}},d=await this.addVerb(s,c,void 0,{type:l,weight:u.weight,metadata:u});o.push(d)}return{nounIds:e,verbIds:o}}catch(e){throw console.error("Failed to generate random graph:",e),new Error(`Failed to generate random graph: ${e}`)}}}let Ke=null;const Xe=[];function Ye(e){return void 0===e.enabled&&(e.enabled=!0),Xe.push(e),e}function Qe(e){const t=e||Ke;if(!t)throw new Error("No pipeline provided and default pipeline not set. Call setDefaultPipeline first.");for(const e of Xe)e.enabled&&t.register(e);return t}function Je(e,t){const n=Xe.find(t=>t.name===e);return!!n&&(n.enabled=t,!0)}function Ze(e){return Xe.filter(t=>{switch(e){case Me.SENSE:return"processRawData"in t&&"listenToFeed"in t;case Me.CONDUIT:return"establishConnection"in t&&"readData"in t&&"writeData"in t;case Me.COGNITION:return"reason"in t&&"infer"in t&&"executeLogic"in t;case Me.MEMORY:return"storeData"in t&&"retrieveData"in t&&"updateData"in t;case Me.PERCEPTION:return"interpret"in t&&"organize"in t&&"generateVisualization"in t;case Me.DIALOG:return"processUserInput"in t&&"generateResponse"in t&&"manageContext"in t;case Me.ACTIVATION:return"triggerAction"in t&&"generateOutput"in t&&"interactExternal"in t;case Me.WEBSOCKET:return"connectWebSocket"in t&&"sendWebSocketMessage"in t&&"onWebSocketMessage"in t;default:return!1}})}class et{constructor(e){this.enabled=!0,this.isInitialized=!1,this.name=e.name,this.description=e.description||`${e.name} augmentation`,this.enabled=!1!==e.enabled}async initialize(){this.isInitialized||(this.isInitialized=!0)}async shutDown(){this.isInitialized=!1}async getStatus(){return this.isInitialized?"active":"inactive"}async ensureInitialized(){this.isInitialized||await this.initialize()}}function tt(e){const t=new et(e);return t.processRawData=async(n,r)=>{if(await t.ensureInitialized(),e.processRawData){const t=e.processRawData(n,r);return t instanceof Promise?await t:t}return{success:!1,data:{nouns:[],verbs:[]},error:"processRawData not implemented"}},t.listenToFeed=async(n,r)=>{if(await t.ensureInitialized(),e.listenToFeed)return e.listenToFeed(n,r);throw new Error("listenToFeed not implemented")},e.autoRegister&&(Ye(t),e.autoInitialize&&t.initialize().catch(e=>{console.error(`Failed to initialize augmentation ${t.name}:`,e)})),t}function nt(e,t){const n=e;return n.connectWebSocket=async(n,r)=>{if(await(e.ensureInitialized?.()),t.connectWebSocket)return t.connectWebSocket(n,r);throw new Error("connectWebSocket not implemented")},n.sendWebSocketMessage=async(n,r)=>{if(await(e.ensureInitialized?.()),t.sendWebSocketMessage)return t.sendWebSocketMessage(n,r);throw new Error("sendWebSocketMessage not implemented")},n.onWebSocketMessage=async(n,r)=>{if(await(e.ensureInitialized?.()),t.onWebSocketMessage)return t.onWebSocketMessage(n,r);throw new Error("onWebSocketMessage not implemented")},n.offWebSocketMessage=async(n,r)=>{if(await(e.ensureInitialized?.()),t.offWebSocketMessage)return t.offWebSocketMessage(n,r);throw new Error("offWebSocketMessage not implemented")},n.closeWebSocket=async(n,r,a)=>{if(await(e.ensureInitialized?.()),t.closeWebSocket)return t.closeWebSocket(n,r,a);throw new Error("closeWebSocket not implemented")},n}async function rt(e,t,...n){try{if(!e.enabled)return{success:!1,data:null,error:`Augmentation ${e.name} is disabled`};if("function"!=typeof e[t])return{success:!1,data:null,error:`Method ${t} not found on augmentation ${e.name}`};return await e[t](...n)}catch(n){return console.error(`Error executing ${t} on ${e.name}:`,n),{success:!1,data:null,error:n instanceof Error?n.message:String(n)}}}async function at(e,t={}){try{const n=await e,r=[];for(const e in n){const a=n[e];a&&"object"==typeof a&&("string"==typeof a.name&&"function"==typeof a.initialize&&"function"==typeof a.shutDown&&"function"==typeof a.getStatus&&(r.push(a),t.autoRegister&&(Ye(a),t.autoInitialize&&a.initialize().catch(e=>{console.error(`Failed to initialize augmentation ${a.name}:`,e)}))))}return r}catch(e){return console.error("Error loading augmentation module:",e),[]}}var st;!function(e){e.SEQUENTIAL="sequential",e.PARALLEL="parallel",e.FIRST_SUCCESS="firstSuccess",e.FIRST_RESULT="firstResult",e.THREADED="threaded"}(st||(st={}));const ot={mode:st.SEQUENTIAL,timeout:3e4,stopOnError:!1,forceThreading:!1,disableThreading:!1};class it{constructor(){this.registry={sense:[],conduit:[],cognition:[],memory:[],perception:[],dialog:[],activation:[],webSocket:[]}}register(e){let t=!1;if(this.isAugmentationType(e,"processRawData","listenToFeed")?(this.registry.sense.push(e),t=!0):this.isAugmentationType(e,"establishConnection","readData","writeData","monitorStream")?(this.registry.conduit.push(e),t=!0):this.isAugmentationType(e,"reason","infer","executeLogic")?(this.registry.cognition.push(e),t=!0):this.isAugmentationType(e,"storeData","retrieveData","updateData","deleteData","listDataKeys")?(this.registry.memory.push(e),t=!0):this.isAugmentationType(e,"interpret","organize","generateVisualization")?(this.registry.perception.push(e),t=!0):this.isAugmentationType(e,"processUserInput","generateResponse","manageContext")?(this.registry.dialog.push(e),t=!0):this.isAugmentationType(e,"triggerAction","generateOutput","interactExternal")&&(this.registry.activation.push(e),t=!0),this.isAugmentationType(e,"connectWebSocket","sendWebSocketMessage","onWebSocketMessage","closeWebSocket")&&(this.registry.webSocket.push(e),t=!0),!t)throw new Error(`Unknown augmentation type: ${e.name}`);return this}unregister(e){for(const t in this.registry){const n=this.registry[t],r=n.findIndex(t=>t.name===e);-1!==r&&n.splice(r,1)}return this}async initialize(){const e=this.getAllAugmentations();await Promise.all(e.map(e=>e.initialize().catch(t=>{console.error(`Failed to initialize augmentation ${e.name}:`,t)})))}async shutDown(){const e=this.getAllAugmentations();await Promise.all(e.map(e=>e.shutDown().catch(t=>{console.error(`Failed to shut down augmentation ${e.name}:`,t)})))}getAllAugmentations(){const e=new Set([...this.registry.sense,...this.registry.conduit,...this.registry.cognition,...this.registry.memory,...this.registry.perception,...this.registry.dialog,...this.registry.activation,...this.registry.webSocket]);return Array.from(e)}getAugmentationsByType(e){switch(e){case Me.SENSE:return[...this.registry.sense];case Me.CONDUIT:return[...this.registry.conduit];case Me.COGNITION:return[...this.registry.cognition];case Me.MEMORY:return[...this.registry.memory];case Me.PERCEPTION:return[...this.registry.perception];case Me.DIALOG:return[...this.registry.dialog];case Me.ACTIVATION:return[...this.registry.activation];case Me.WEBSOCKET:return[...this.registry.webSocket];default:return[]}}getAvailableAugmentationTypes(){const e=[];return this.registry.sense.length>0&&e.push(Me.SENSE),this.registry.conduit.length>0&&e.push(Me.CONDUIT),this.registry.cognition.length>0&&e.push(Me.COGNITION),this.registry.memory.length>0&&e.push(Me.MEMORY),this.registry.perception.length>0&&e.push(Me.PERCEPTION),this.registry.dialog.length>0&&e.push(Me.DIALOG),this.registry.activation.length>0&&e.push(Me.ACTIVATION),this.registry.webSocket.length>0&&e.push(Me.WEBSOCKET),e}getWebSocketAugmentations(){return[...this.registry.webSocket]}isAugmentationType(e,...t){return!!["initialize","shutDown","getStatus"].every(t=>"function"==typeof e[t])&&t.every(t=>"function"==typeof e[t])}shouldUseThreading(e){return!e.disableThreading&&((e.forceThreading||e.mode===st.THREADED)&&v())}async execute(e,t,n=[],r={}){const a={...ot,...r},s=e.filter(e=>!1!==e.enabled);if(0===s.length)return{results:[],errors:[],successful:[]};const o={results:[],errors:[],successful:[]},i=async e=>{try{if(a.timeout){const r=new Promise((n,r)=>{setTimeout(()=>{r(new Error(`Timeout executing ${t} on ${e.name}`))},a.timeout)});let s;if(this.shouldUseThreading(a))try{s=L(((...n)=>e[t].apply(e,n)).toString(),n)}catch(r){console.warn(`Failed to execute in thread, falling back to main thread: ${r}`),s=Promise.resolve(e[t](...n))}else s=Promise.resolve(e[t](...n));return await Promise.race([s,r])}return await rt(e,t,...n)}catch(e){return o.errors.push(e instanceof Error?e:new Error(String(e))),{success:!1,data:null,error:e instanceof Error?e.message:String(e)}}};switch(a.mode){case st.PARALLEL:case st.THREADED:o.results=await Promise.all(s.map(e=>i(e)));break;case st.FIRST_SUCCESS:for(const e of s){const t=await i(e);if(o.results.push(t),t.success)break}break;case st.FIRST_RESULT:for(const e of s){const t=await i(e);if(o.results.push(t),t.success&&null!==t.data&&void 0!==t.data)break}break;case st.SEQUENTIAL:default:for(const e of s){const t=await i(e);if(o.results.push(t),a.stopOnError&&!t.success)break}}return o.successful=o.results.filter(e=>e.success),o}async executeByType(e,t,n=[],r={}){const a=this.getAugmentationsByType(e);return this.execute(a,t,n,r)}async executeSingle(e,t,...n){return rt(e,t,...n)}async processStaticData(e,t,n={}){let r,a=e;for(const e of t){const t=e.transformArgs?e.transformArgs(a,r):[a],n=await this.executeSingle(e.augmentation,e.method,...t);if(!n.success)return n;a=n.data,r=n}return r}async processStreamingData(e,t,n,r,a,s={}){const o=async e=>{let t,n=e;for(const e of r){const r=e.transformArgs?e.transformArgs(n,t):[n],s=await this.executeSingle(e.augmentation,e.method,...r);if(!s.success)return void a(s);n=s.data,t=s}a(t)};await this.executeSingle(e,t,...n,e=>{o(e).catch(e=>{console.error("Error processing streaming data:",e),a({success:!1,data:null,error:e instanceof Error?e.message:String(e)})})})}createPipeline(e,t={}){return n=>this.processStaticData(n,e,t)}createStreamingPipeline(e,t,n,r={}){return(a,s)=>this.processStreamingData(e,t,a,n,s,r)}async executeSensePipeline(e,t,n={}){return(await this.executeByType(Me.SENSE,e,t,n)).results.map(e=>Promise.resolve(e))}async executeConduitPipeline(e,t,n={}){return(await this.executeByType(Me.CONDUIT,e,t,n)).results.map(e=>Promise.resolve(e))}async executeCognitionPipeline(e,t,n={}){return(await this.executeByType(Me.COGNITION,e,t,n)).results.map(e=>Promise.resolve(e))}async executeMemoryPipeline(e,t,n={}){return(await this.executeByType(Me.MEMORY,e,t,n)).results.map(e=>Promise.resolve(e))}async executePerceptionPipeline(e,t,n={}){return(await this.executeByType(Me.PERCEPTION,e,t,n)).results.map(e=>Promise.resolve(e))}async executeDialogPipeline(e,t,n={}){return(await this.executeByType(Me.DIALOG,e,t,n)).results.map(e=>Promise.resolve(e))}async executeActivationPipeline(e,t,n={}){return(await this.executeByType(Me.ACTIVATION,e,t,n)).results.map(e=>Promise.resolve(e))}}const ct=new it;!function(e){Ke=e}(ct);const lt=ct,ut=(e,t,n=[],r={})=>ct.execute(e,t,n,r),dt=(e,t,n=[],r={})=>ct.executeByType(e,t,n,r),ht=(e,t,...n)=>ct.executeSingle(e,t,...n),pt=(e,t,n={})=>ct.processStaticData(e,t,n),ft=(e,t,n,r,a,s={})=>ct.processStreamingData(e,t,n,r,a,s),mt=(e,t={})=>ct.createPipeline(e,t),gt=(e,t,n,r={})=>ct.createStreamingPipeline(e,t,n,r),yt=st;let bt,xt,wt;const vt=void 0!==globalThis.TransformStream&&void 0!==globalThis.ReadableStream&&void 0!==globalThis.WritableStream?(bt=globalThis.TransformStream,xt=globalThis.ReadableStream,wt=globalThis.WritableStream,Promise.resolve()):import("node:stream/web").then(e=>{bt=e.TransformStream,xt=e.ReadableStream,wt=e.WritableStream}).catch(e=>{throw console.error("Failed to import WebStreams API:",e),new Error("WebStreams API is not available in this environment. Please use a modern browser or Node.js 18+.")}),kt={timeout:3e4,stopOnError:!1};class It{constructor(e={}){this.brainyData=e.brainyData||new qe}async ensureStreamClassesInitialized(){await vt}async initialize(){await Promise.all([this.ensureStreamClassesInitialized(),this.brainyData.init()])}async processData(e,t,n={}){const r={...kt,...n},a={success:!0,data:null,stageResults:{}};try{const n=await He.executeSensePipeline("processRawData",[e,t],{timeout:r.timeout,stopOnError:r.stopOnError});let s=null;for(const e of n){const t=await e;if(t.success){s=t;break}}if(!s||!s.success)return{success:!1,data:null,error:"Failed to process raw data with ISense augmentations",stageResults:{sense:s||{success:!1,data:null,error:"No sense augmentations available"}}};a.stageResults.sense=s;const o=He.getAugmentationsByType(Me.MEMORY);if(0===o.length)return{success:!1,data:null,error:"No memory augmentations available",stageResults:a.stageResults};const i=o[0],c=`data_${Date.now()}_${Math.random().toString(36).substring(2,15)}`,l=await i.storeData(c,{rawData:e,dataType:t,nouns:s.data.nouns,verbs:s.data.verbs,timestamp:Date.now()});if(!l.success)return{success:!1,data:null,error:`Failed to store data: ${l.error}`,stageResults:{...a.stageResults,memory:l}};a.stageResults.memory=l;const u=await He.executeCognitionPipeline("reason",[`Analyze data with key ${c}`,{dataKey:c}],{timeout:r.timeout,stopOnError:r.stopOnError});let d=null;for(const e of u){const t=await e;if(t.success){d=t;break}}d&&(a.stageResults.cognition=d);const h=await He.executeConduitPipeline("writeData",[{dataKey:c,nouns:s.data.nouns,verbs:s.data.verbs}],{timeout:r.timeout,stopOnError:r.stopOnError});let p=null;for(const e of h){const t=await e;if(t.success){p=t;break}}p&&(a.stageResults.conduit=p);const f=await He.executeActivationPipeline("triggerAction",["dataProcessed",{dataKey:c}],{timeout:r.timeout,stopOnError:r.stopOnError});let m=null;for(const e of f){const t=await e;if(t.success){m=t;break}}m&&(a.stageResults.activation=m);const g=await He.executePerceptionPipeline("interpret",[s.data.nouns,s.data.verbs,{dataKey:c}],{timeout:r.timeout,stopOnError:r.stopOnError});let y=null;for(const e of g){const t=await e;if(t.success){y=t;break}}return y?(a.stageResults.perception=y,a.data=y.data):a.data=d?d.data:{dataKey:c},a}catch(e){return{success:!1,data:null,error:`Pipeline execution failed: ${e}`,stageResults:a.stageResults}}}async createWebSocketHandler(e,t,n={}){await this.ensureStreamClassesInitialized();const r=new bt({transform:async(e,r)=>{try{const a="string"==typeof e?e:JSON.stringify(e),s=await this.processData(a,t,n);s.success?r.enqueue(s):console.warn("Pipeline processing failed:",s.error)}catch(e){console.error("Error in transform stream:",e)}}}),a=new wt({write:async t=>{if(e.send&&"function"==typeof e.send)try{await e.send(JSON.stringify(t))}catch(e){console.error("Error sending result back to WebSocket:",e)}}});return r.readable.pipeTo(a).catch(e=>{console.error("Error in pipeline stream:",e)}),e=>{try{const t=r.writable.getWriter();t.write(e).catch(e=>{console.error("Error writing to stream:",e)}).finally(()=>{t.releaseLock()})}catch(e){console.error("Error getting writer for transform stream:",e)}}}async setupWebSocketPipeline(e,t,n={}){await this.ensureStreamClassesInitialized();const r=He.getWebSocketAugmentations();if(0===r.length)throw new Error("No WebSocket-supporting augmentations available");const a=r[0],s=await a.connectWebSocket(e),o=new xt({start:e=>{const t=t=>{try{const n="string"==typeof t.data?t.data:t.data instanceof Blob?new Promise(e=>{const n=new FileReader;n.onload=()=>e(n.result),n.readAsText(t.data)}):JSON.stringify(t.data);n instanceof Promise?n.then(t=>{e.enqueue(t)}).catch(e=>{console.error("Error processing blob data:",e)}):e.enqueue(n)}catch(e){console.error("Error processing WebSocket message:",e)}},n=e=>{t({data:e})};s._streamMessageHandler=t,s._messageHandlerWrapper=n,a.onWebSocketMessage(s.connectionId,n).catch(t=>{console.error("Error registering WebSocket message handler:",t),e.error(t)})},cancel:()=>{s._messageHandlerWrapper&&(a.offWebSocketMessage(s.connectionId,s._messageHandlerWrapper).catch(e=>{console.error("Error removing WebSocket message handler:",e)}),delete s._streamMessageHandler,delete s._messageHandlerWrapper)}}),i=this.createWebSocketHandler(s,t,n),c=new wt({write:async e=>{if(!s.send||"function"!=typeof s.send)throw new Error("WebSocket connection does not support sending data");try{const t="string"==typeof e?e:JSON.stringify(e);await s.send(t)}catch(e){throw console.error("Error sending data to WebSocket:",e),e}},close:()=>{s.close&&"function"==typeof s.close&&s.close().catch(e=>{console.error("Error closing WebSocket connection:",e)})}});o.pipeThrough(new bt({transform:async(e,t)=>{(await i)(e),t.enqueue(e)}})).pipeTo(new wt({write:()=>{},abort:e=>{console.error("Error in WebSocket pipeline:",e)}}));const l=s;return l.readableStream=o,l.writableStream=c,l}}const St=new It,Tt={autoInitialize:!1,debug:!1};async function Nt(e,t={}){const n={...Tt,...t},r={augmentations:[],errors:[]};n.debug&&console.log(`[AugmentationRegistryLoader] Loading augmentations from ${Object.keys(e).length} modules`);for(const[t,a]of Object.entries(e))try{n.debug&&console.log(`[AugmentationRegistryLoader] Processing module: ${t}`);const e=Ct(a);if(0===e.length){n.debug&&console.log(`[AugmentationRegistryLoader] No augmentations found in module: ${t}`);continue}for(const t of e)try{const e=Ye(t);r.augmentations.push(e),n.debug&&console.log(`[AugmentationRegistryLoader] Registered augmentation: ${e.name}`)}catch(e){const t=e instanceof Error?e:new Error(String(e));r.errors.push(t),n.debug&&console.error(`[AugmentationRegistryLoader] Failed to register augmentation: ${t.message}`)}}catch(e){const a=e instanceof Error?e:new Error(String(e));r.errors.push(a),n.debug&&console.error(`[AugmentationRegistryLoader] Error processing module ${t}: ${a.message}`)}return n.debug&&console.log(`[AugmentationRegistryLoader] Loaded ${r.augmentations.length} augmentations with ${r.errors.length} errors`),r}function Ct(e){const t=[];if(Et(e)&&t.push(e),e&&"object"==typeof e)for(const n of Object.keys(e)){const r=e[n];r&&"object"==typeof r&&(Et(r)&&t.push(r),Array.isArray(r)&&r.every(Et)&&t.push(...r))}return t}function Et(e){return e&&"object"==typeof e&&"string"==typeof e.name&&"function"==typeof e.initialize&&"function"==typeof e.shutDown&&"function"==typeof e.getStatus}function $t(e){return{name:"AugmentationRegistryPlugin",pattern:e.pattern,options:e.options||{}}}function At(e){return{name:"augmentation-registry-rollup-plugin",pattern:e.pattern,options:e.options||{}}}class Rt{constructor(e,t){this.description="Base memory augmentation",this.enabled=!0,this.isInitialized=!1,this.name=e,this.storage=t}async initialize(){if(!this.isInitialized)try{await this.storage.init(),this.isInitialized=!0}catch(e){throw console.error(`Failed to initialize ${this.name}:`,e),new Error(`Failed to initialize ${this.name}: ${e}`)}}async shutDown(){this.isInitialized=!1}async getStatus(){return this.isInitialized?"active":"inactive"}async storeData(e,t,n){await this.ensureInitialized();try{return await this.storage.saveMetadata(e,t),{success:!0,data:!0}}catch(t){return console.error(`Failed to store data for key ${e}:`,t),{success:!1,data:!1,error:`Failed to store data: ${t}`}}}async retrieveData(e,t){await this.ensureInitialized();try{return{success:!0,data:await this.storage.getMetadata(e)}}catch(t){return console.error(`Failed to retrieve data for key ${e}:`,t),{success:!1,data:null,error:`Failed to retrieve data: ${t}`}}}async updateData(e,t,n){await this.ensureInitialized();try{return await this.storage.saveMetadata(e,t),{success:!0,data:!0}}catch(t){return console.error(`Failed to update data for key ${e}:`,t),{success:!1,data:!1,error:`Failed to update data: ${t}`}}}async deleteData(e,t){await this.ensureInitialized();try{return await this.storage.saveMetadata(e,null),{success:!0,data:!0}}catch(t){return console.error(`Failed to delete data for key ${e}:`,t),{success:!1,data:!1,error:`Failed to delete data: ${t}`}}}async listDataKeys(e,t){return{success:!1,data:[],error:"listDataKeys is not supported by this storage adapter"}}async search(e,t=10,n){await this.ensureInitialized();try{let n;if(!Array.isArray(e)||!e.every(e=>"number"==typeof e))return{success:!1,data:[],error:"Query must be a vector (array of numbers) for vector search"};n=e;const r=await this.storage.getAllNouns(),a=[];for(const e of r){if(!e.vector||!Array.isArray(e.vector))continue;const t=await this.storage.getMetadata(e.id),r=1-F(n,e.vector);a.push({id:e.id,score:r,data:t})}a.sort((e,t)=>t.score-e.score);return{success:!0,data:a.slice(0,t)}}catch(e){return console.error("Failed to search in storage:",e),{success:!1,data:[],error:`Failed to search in storage: ${e}`}}}async ensureInitialized(){this.isInitialized||await this.initialize()}}class _t extends Rt{constructor(e){super(e,new ye),this.description="Memory augmentation that stores data in memory",this.enabled=!0}getType(){return Me.MEMORY}}class Ot extends Rt{constructor(e,t){super(e,new Re(t||".")),this.description="Memory augmentation that stores data in the file system",this.enabled=!0}getType(){return Me.MEMORY}}class Ft extends Rt{constructor(e){super(e,new xe),this.description="Memory augmentation that stores data in the Origin Private File System",this.enabled=!0}getType(){return Me.MEMORY}}async function Dt(e,t={}){if(t.storageType)switch(t.storageType){case"memory":return new _t(e);case"filesystem":return new Ot(e,t.rootDirectory);case"opfs":return new Ft(e)}if(globalThis.__ENV__?.isNode||"undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node)return new Ot(e,t.rootDirectory);{const n=new xe;return n.isOPFSAvailable()?(t.requestPersistentStorage&&await n.requestPersistentStorage(),new Ft(e)):new _t(e)}}const Mt="1.0.0";var Pt;!function(e){e.DATA_ACCESS="data_access",e.TOOL_EXECUTION="tool_execution",e.SYSTEM_INFO="system_info",e.AUTHENTICATION="authentication"}(Pt||(Pt={}));class Bt{constructor(e){this.brainyData=e}async handleRequest(e){try{switch(e.operation){case"get":return await this.handleGetRequest(e);case"search":return await this.handleSearchRequest(e);case"add":return await this.handleAddRequest(e);case"getRelationships":return await this.handleGetRelationshipsRequest(e);default:return this.createErrorResponse(e.requestId,"UNSUPPORTED_OPERATION",`Operation ${e.operation} is not supported`)}}catch(t){return this.createErrorResponse(e.requestId,"INTERNAL_ERROR",t instanceof Error?t.message:String(t))}}async handleGetRequest(e){const{id:t}=e.parameters;if(!t)return this.createErrorResponse(e.requestId,"MISSING_PARAMETER",'Parameter "id" is required');const n=await this.brainyData.get(t);return n?this.createSuccessResponse(e.requestId,n):this.createErrorResponse(e.requestId,"NOT_FOUND",`No noun found with id ${t}`)}async handleSearchRequest(e){const{query:t,k:n=10}=e.parameters;if(!t)return this.createErrorResponse(e.requestId,"MISSING_PARAMETER",'Parameter "query" is required');const r=await this.brainyData.searchText(t,n);return this.createSuccessResponse(e.requestId,r)}async handleAddRequest(e){const{text:t,metadata:n}=e.parameters;if(!t)return this.createErrorResponse(e.requestId,"MISSING_PARAMETER",'Parameter "text" is required');const r=await this.brainyData.add(t,n);return this.createSuccessResponse(e.requestId,{id:r})}async handleGetRelationshipsRequest(e){const{id:t}=e.parameters;if(!t)return this.createErrorResponse(e.requestId,"MISSING_PARAMETER",'Parameter "id" is required');const n=await(this.brainyData.getVerbsBySource?.(t))||[],r=await(this.brainyData.getVerbsByTarget?.(t))||[];return this.createSuccessResponse(e.requestId,{outgoing:n,incoming:r})}createSuccessResponse(e,t){return{success:!0,requestId:e,version:Mt,data:t}}createErrorResponse(e,t,n,r){return{success:!1,requestId:e,version:Mt,error:{code:t,message:n,details:r}}}generateRequestId(){return _()}}class Lt{constructor(){}async handleRequest(e){try{const{toolName:t,parameters:n}=e,r=t.split("_");if(r.length<3||"brainy"!==r[0])return this.createErrorResponse(e.requestId,"INVALID_TOOL",`Invalid tool name: ${t}. Tool names should be in the format: brainy_{augmentationType}_{method}`);const a=r[1],s=r.slice(2).join("_");if(!this.isValidAugmentationType(a))return this.createErrorResponse(e.requestId,"INVALID_AUGMENTATION_TYPE",`Invalid augmentation type: ${a}`);const o=await this.executePipeline(a,s,n);return this.createSuccessResponse(e.requestId,o)}catch(t){return this.createErrorResponse(e.requestId,"INTERNAL_ERROR",t instanceof Error?t.message:String(t))}}async getAvailableTools(){const e=[],t=He.getAvailableAugmentationTypes();for(const n of t){const t=He.getAugmentationsByType(n);for(const r of t){const t=Object.getOwnPropertyNames(Object.getPrototypeOf(r)).filter(e=>!e.startsWith("_")&&"constructor"!==e&&"initialize"!==e&&"shutDown"!==e&&"getStatus"!==e&&"function"==typeof r[e]);for(const a of t)e.push(this.createToolDefinition(n,r.name,a))}}return e}createToolDefinition(e,t,n){return{name:`brainy_${e}_${n}`,description:`Access to Brainy's ${e} augmentation '${t}' method '${n}'`,parameters:{type:"object",properties:{args:{type:"array",description:`Arguments for the ${n} method`},options:{type:"object",description:"Optional execution options"}},required:["args"]}}}async executePipeline(e,t,n){const{args:r=[],options:a={}}=n;switch(e){case Me.SENSE:return await He.executeSensePipeline(t,r,a);case Me.CONDUIT:return await He.executeConduitPipeline(t,r,a);case Me.COGNITION:return await He.executeCognitionPipeline(t,r,a);case Me.MEMORY:return await He.executeMemoryPipeline(t,r,a);case Me.PERCEPTION:return await He.executePerceptionPipeline(t,r,a);case Me.DIALOG:return await He.executeDialogPipeline(t,r,a);case Me.ACTIVATION:return await He.executeActivationPipeline(t,r,a);default:throw new Error(`Unsupported augmentation type: ${e}`)}}isValidAugmentationType(e){return Object.values(Me).includes(e)}createSuccessResponse(e,t){return{success:!0,requestId:e,version:Mt,data:t}}createErrorResponse(e,t,n,r){return{success:!1,requestId:e,version:Mt,error:{code:t,message:n,details:r}}}generateRequestId(){return _()}}class zt{constructor(e,t={}){this.dataAdapter=new Bt(e),this.toolset=new Lt,this.options=t,this.authTokens=new Map,this.rateLimits=new Map}async handleRequest(e){try{switch(e.type){case Pt.DATA_ACCESS:return await this.dataAdapter.handleRequest(e);case Pt.TOOL_EXECUTION:return await this.toolset.handleRequest(e);case Pt.SYSTEM_INFO:return await this.handleSystemInfoRequest(e);case Pt.AUTHENTICATION:return await this.handleAuthenticationRequest(e);default:return this.createErrorResponse(e.requestId,"UNSUPPORTED_REQUEST_TYPE",`Request type ${e.type} is not supported`)}}catch(t){return this.createErrorResponse(e.requestId,"INTERNAL_ERROR",t instanceof Error?t.message:String(t))}}async handleSystemInfoRequest(e){try{switch(e.infoType){case"status":return this.createSuccessResponse(e.requestId,{status:"active",version:Mt,environment:m()?"browser":g()?"node":"unknown"});case"availableTools":const t=await this.toolset.getAvailableTools();return this.createSuccessResponse(e.requestId,t);case"version":return this.createSuccessResponse(e.requestId,{version:Mt});default:return this.createErrorResponse(e.requestId,"UNSUPPORTED_INFO_TYPE",`Info type ${e.infoType} is not supported`)}}catch(t){return this.createErrorResponse(e.requestId,"INTERNAL_ERROR",t instanceof Error?t.message:String(t))}}async handleAuthenticationRequest(e){try{if(!this.options.enableAuth)return this.createSuccessResponse(e.requestId,{authenticated:!0,message:"Authentication is not enabled"});const{credentials:t}=e;if(t.apiKey&&this.options.apiKeys?.includes(t.apiKey)){const t=this.generateAuthToken("api-user");return this.createSuccessResponse(e.requestId,{authenticated:!0,token:t})}if("admin"===t.username&&"password"===t.password){const n=this.generateAuthToken(t.username);return this.createSuccessResponse(e.requestId,{authenticated:!0,token:n})}return this.createErrorResponse(e.requestId,"INVALID_CREDENTIALS","Invalid credentials")}catch(t){return this.createErrorResponse(e.requestId,"INTERNAL_ERROR",t instanceof Error?t.message:String(t))}}isValidRequest(e){return e&&"object"==typeof e&&e.type&&e.requestId&&e.version}isAuthenticated(e){return!this.options.enableAuth||!!e.authToken&&this.isValidToken(e.authToken)}isValidToken(e){const t=this.authTokens.get(e);return!!t&&(!(t.expires<Date.now())||(this.authTokens.delete(e),!1))}generateAuthToken(e){const t=_(),n=Date.now()+864e5;return this.authTokens.set(t,{userId:e,expires:n}),t}checkRateLimit(e){if(!this.options.rateLimit)return!0;const t=Date.now(),n=this.rateLimits.get(e);return n?n.resetTime<t?(n.count=1,n.resetTime=t+this.options.rateLimit.windowMs,!0):!(n.count>=this.options.rateLimit.maxRequests)&&(n.count++,!0):(this.rateLimits.set(e,{count:1,resetTime:t+this.options.rateLimit.windowMs}),!0)}createSuccessResponse(e,t){return{success:!0,requestId:e,version:Mt,data:t}}createErrorResponse(e,t,n,r){return{success:!1,requestId:e,version:Mt,error:{code:t,message:n,details:r}}}generateRequestId(){return _()}async handleMCPRequest(e){return await this.handleRequest(e)}}"undefined"!=typeof window&&void 0===globalThis.Buffer&&(globalThis.Buffer=a.Buffer);const Ut={get isBrowser(){return m()},get isNode(){return g()},get isServerless(){return!m()&&!g()},isWebWorker:function(){return y()},get isThreadingAvailable(){return v()},isThreadingAvailableAsync:function(){return k()},areWorkerThreadsAvailable:function(){return x()}};"undefined"!=typeof globalThis&&(globalThis.__ENV__=Ut),console.log(`Brainy running in ${Ut.isBrowser?"browser":Ut.isNode?"Node.js":"serverless/unknown"} environment`);const Wt=globalThis.TextEncoder||"undefined"!=typeof global&&global.TextEncoder||class{encode(e){return new Uint8Array(Buffer.from(e,"utf8"))}},Vt=globalThis.TextDecoder||"undefined"!=typeof global&&global.TextDecoder||class{decode(e){return Buffer.from(e).toString("utf8")}},Gt={isFloat32Array:e=>e instanceof Float32Array,isInt32Array:e=>e instanceof Int32Array,isUint8Array:e=>e instanceof Uint8Array,isUint8ClampedArray:e=>e instanceof Uint8ClampedArray};var jt={TextEncoder:Wt,TextDecoder:Vt,types:Gt};var Ht=Object.freeze({__proto__:null,TextDecoder:Vt,TextEncoder:Wt,default:jt,promises:{},types:Gt});
|
|
9
|
+
function(e){const t=s,n=f,r="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;e.Buffer=i,e.SlowBuffer=function(e){+e!=e&&(e=0);return i.alloc(+e)},e.INSPECT_MAX_BYTES=50;const a=2147483647;function o(e){if(e>a)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,i.prototype),t}function i(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return u(e)}return c(e,t,n)}function c(e,t,n){if("string"==typeof e)return function(e,t){"string"==typeof t&&""!==t||(t="utf8");if(!i.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const n=0|m(e,t);let r=o(n);const a=r.write(e,t);a!==n&&(r=r.slice(0,a));return r}(e,t);if(ArrayBuffer.isView(e))return function(e){if(X(e,Uint8Array)){const t=new Uint8Array(e);return h(t.buffer,t.byteOffset,t.byteLength)}return d(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(X(e,ArrayBuffer)||e&&X(e.buffer,ArrayBuffer))return h(e,t,n);if("undefined"!=typeof SharedArrayBuffer&&(X(e,SharedArrayBuffer)||e&&X(e.buffer,SharedArrayBuffer)))return h(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const r=e.valueOf&&e.valueOf();if(null!=r&&r!==e)return i.from(r,t,n);const a=function(e){if(i.isBuffer(e)){const t=0|p(e.length),n=o(t);return 0===n.length||e.copy(n,0,0,t),n}if(void 0!==e.length)return"number"!=typeof e.length||Y(e.length)?o(0):d(e);if("Buffer"===e.type&&Array.isArray(e.data))return d(e.data)}(e);if(a)return a;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return i.from(e[Symbol.toPrimitive]("string"),t,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function l(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function u(e){return l(e),o(e<0?0:0|p(e))}function d(e){const t=e.length<0?0:0|p(e.length),n=o(t);for(let r=0;r<t;r+=1)n[r]=255&e[r];return n}function h(e,t,n){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(n||0))throw new RangeError('"length" is outside of buffer bounds');let r;return r=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n),Object.setPrototypeOf(r,i.prototype),r}function p(e){if(e>=a)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+a.toString(16)+" bytes");return 0|e}function m(e,t){if(i.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||X(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const n=e.length,r=arguments.length>2&&!0===arguments[2];if(!r&&0===n)return 0;let a=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return H(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return q(e).length;default:if(a)return r?-1:H(e).length;t=(""+t).toLowerCase(),a=!0}}function g(e,t,n){let r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return A(this,t,n);case"utf8":case"utf-8":return N(this,t,n);case"ascii":return E(this,t,n);case"latin1":case"binary":return $(this,t,n);case"base64":return T(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return R(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function y(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function b(e,t,n,r,a){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),Y(n=+n)&&(n=a?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(a)return-1;n=e.length-1}else if(n<0){if(!a)return-1;n=0}if("string"==typeof t&&(t=i.from(t,r)),i.isBuffer(t))return 0===t.length?-1:x(e,t,n,r,a);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?a?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):x(e,[t],n,r,a);throw new TypeError("val must be string, number or Buffer")}function x(e,t,n,r,a){let s,o=1,i=e.length,c=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;o=2,i/=2,c/=2,n/=2}function l(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(a){let r=-1;for(s=n;s<i;s++)if(l(e,s)===l(t,-1===r?0:s-r)){if(-1===r&&(r=s),s-r+1===c)return r*o}else-1!==r&&(s-=s-r),r=-1}else for(n+c>i&&(n=i-c),s=n;s>=0;s--){let n=!0;for(let r=0;r<c;r++)if(l(e,s+r)!==l(t,r)){n=!1;break}if(n)return s}return-1}function w(e,t,n,r){n=Number(n)||0;const a=e.length-n;r?(r=Number(r))>a&&(r=a):r=a;const s=t.length;let o;for(r>s/2&&(r=s/2),o=0;o<r;++o){const r=parseInt(t.substr(2*o,2),16);if(Y(r))return o;e[n+o]=r}return o}function v(e,t,n,r){return K(H(t,e.length-n),e,n,r)}function k(e,t,n,r){return K(function(e){const t=[];for(let n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function I(e,t,n,r){return K(q(t),e,n,r)}function S(e,t,n,r){return K(function(e,t){let n,r,a;const s=[];for(let o=0;o<e.length&&!((t-=2)<0);++o)n=e.charCodeAt(o),r=n>>8,a=n%256,s.push(a),s.push(r);return s}(t,e.length-n),e,n,r)}function T(e,n,r){return 0===n&&r===e.length?t.fromByteArray(e):t.fromByteArray(e.slice(n,r))}function N(e,t,n){n=Math.min(e.length,n);const r=[];let a=t;for(;a<n;){const t=e[a];let s=null,o=t>239?4:t>223?3:t>191?2:1;if(a+o<=n){let n,r,i,c;switch(o){case 1:t<128&&(s=t);break;case 2:n=e[a+1],128==(192&n)&&(c=(31&t)<<6|63&n,c>127&&(s=c));break;case 3:n=e[a+1],r=e[a+2],128==(192&n)&&128==(192&r)&&(c=(15&t)<<12|(63&n)<<6|63&r,c>2047&&(c<55296||c>57343)&&(s=c));break;case 4:n=e[a+1],r=e[a+2],i=e[a+3],128==(192&n)&&128==(192&r)&&128==(192&i)&&(c=(15&t)<<18|(63&n)<<12|(63&r)<<6|63&i,c>65535&&c<1114112&&(s=c))}}null===s?(s=65533,o=1):s>65535&&(s-=65536,r.push(s>>>10&1023|55296),s=56320|1023&s),r.push(s),a+=o}return function(e){const t=e.length;if(t<=C)return String.fromCharCode.apply(String,e);let n="",r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=C));return n}(r)}e.kMaxLength=a,i.TYPED_ARRAY_SUPPORT=function(){try{const e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),i.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(i.prototype,"parent",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.buffer}}),Object.defineProperty(i.prototype,"offset",{enumerable:!0,get:function(){if(i.isBuffer(this))return this.byteOffset}}),i.poolSize=8192,i.from=function(e,t,n){return c(e,t,n)},Object.setPrototypeOf(i.prototype,Uint8Array.prototype),Object.setPrototypeOf(i,Uint8Array),i.alloc=function(e,t,n){return function(e,t,n){return l(e),e<=0?o(e):void 0!==t?"string"==typeof n?o(e).fill(t,n):o(e).fill(t):o(e)}(e,t,n)},i.allocUnsafe=function(e){return u(e)},i.allocUnsafeSlow=function(e){return u(e)},i.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==i.prototype},i.compare=function(e,t){if(X(e,Uint8Array)&&(e=i.from(e,e.offset,e.byteLength)),X(t,Uint8Array)&&(t=i.from(t,t.offset,t.byteLength)),!i.isBuffer(e)||!i.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let n=e.length,r=t.length;for(let a=0,s=Math.min(n,r);a<s;++a)if(e[a]!==t[a]){n=e[a],r=t[a];break}return n<r?-1:r<n?1:0},i.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},i.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return i.alloc(0);let n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;const r=i.allocUnsafe(t);let a=0;for(n=0;n<e.length;++n){let t=e[n];if(X(t,Uint8Array))a+t.length>r.length?(i.isBuffer(t)||(t=i.from(t)),t.copy(r,a)):Uint8Array.prototype.set.call(r,t,a);else{if(!i.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(r,a)}a+=t.length}return r},i.byteLength=m,i.prototype._isBuffer=!0,i.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)y(this,t,t+1);return this},i.prototype.swap32=function(){const e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)y(this,t,t+3),y(this,t+1,t+2);return this},i.prototype.swap64=function(){const e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)y(this,t,t+7),y(this,t+1,t+6),y(this,t+2,t+5),y(this,t+3,t+4);return this},i.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?N(this,0,e):g.apply(this,arguments)},i.prototype.toLocaleString=i.prototype.toString,i.prototype.equals=function(e){if(!i.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===i.compare(this,e)},i.prototype.inspect=function(){let t="";const n=e.INSPECT_MAX_BYTES;return t=this.toString("hex",0,n).replace(/(.{2})/g,"$1 ").trim(),this.length>n&&(t+=" ... "),"<Buffer "+t+">"},r&&(i.prototype[r]=i.prototype.inspect),i.prototype.compare=function(e,t,n,r,a){if(X(e,Uint8Array)&&(e=i.from(e,e.offset,e.byteLength)),!i.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===a&&(a=this.length),t<0||n>e.length||r<0||a>this.length)throw new RangeError("out of range index");if(r>=a&&t>=n)return 0;if(r>=a)return-1;if(t>=n)return 1;if(this===e)return 0;let s=(a>>>=0)-(r>>>=0),o=(n>>>=0)-(t>>>=0);const c=Math.min(s,o),l=this.slice(r,a),u=e.slice(t,n);for(let e=0;e<c;++e)if(l[e]!==u[e]){s=l[e],o=u[e];break}return s<o?-1:o<s?1:0},i.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},i.prototype.indexOf=function(e,t,n){return b(this,e,t,n,!0)},i.prototype.lastIndexOf=function(e,t,n){return b(this,e,t,n,!1)},i.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}const a=this.length-t;if((void 0===n||n>a)&&(n=a),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");let s=!1;for(;;)switch(r){case"hex":return w(this,e,t,n);case"utf8":case"utf-8":return v(this,e,t,n);case"ascii":case"latin1":case"binary":return k(this,e,t,n);case"base64":return I(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return S(this,e,t,n);default:if(s)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),s=!0}},i.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const C=4096;function E(e,t,n){let r="";n=Math.min(e.length,n);for(let a=t;a<n;++a)r+=String.fromCharCode(127&e[a]);return r}function $(e,t,n){let r="";n=Math.min(e.length,n);for(let a=t;a<n;++a)r+=String.fromCharCode(e[a]);return r}function A(e,t,n){const r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);let a="";for(let r=t;r<n;++r)a+=Q[e[r]];return a}function R(e,t,n){const r=e.slice(t,n);let a="";for(let e=0;e<r.length-1;e+=2)a+=String.fromCharCode(r[e]+256*r[e+1]);return a}function _(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function O(e,t,n,r,a,s){if(!i.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>a||t<s)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function F(e,t,n,r,a){W(t,r,a,e,n,7);let s=Number(t&BigInt(4294967295));e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,n}function D(e,t,n,r,a){W(t,r,a,e,n,7);let s=Number(t&BigInt(4294967295));e[n+7]=s,s>>=8,e[n+6]=s,s>>=8,e[n+5]=s,s>>=8,e[n+4]=s;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[n+3]=o,o>>=8,e[n+2]=o,o>>=8,e[n+1]=o,o>>=8,e[n]=o,n+8}function M(e,t,n,r,a,s){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function P(e,t,r,a,s){return t=+t,r>>>=0,s||M(e,0,r,4),n.write(e,t,r,a,23,4),r+4}function B(e,t,r,a,s){return t=+t,r>>>=0,s||M(e,0,r,8),n.write(e,t,r,a,52,8),r+8}i.prototype.slice=function(e,t){const n=this.length;(e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t<e&&(t=e);const r=this.subarray(e,t);return Object.setPrototypeOf(r,i.prototype),r},i.prototype.readUintLE=i.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||_(e,t,this.length);let r=this[e],a=1,s=0;for(;++s<t&&(a*=256);)r+=this[e+s]*a;return r},i.prototype.readUintBE=i.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||_(e,t,this.length);let r=this[e+--t],a=1;for(;t>0&&(a*=256);)r+=this[e+--t]*a;return r},i.prototype.readUint8=i.prototype.readUInt8=function(e,t){return e>>>=0,t||_(e,1,this.length),this[e]},i.prototype.readUint16LE=i.prototype.readUInt16LE=function(e,t){return e>>>=0,t||_(e,2,this.length),this[e]|this[e+1]<<8},i.prototype.readUint16BE=i.prototype.readUInt16BE=function(e,t){return e>>>=0,t||_(e,2,this.length),this[e]<<8|this[e+1]},i.prototype.readUint32LE=i.prototype.readUInt32LE=function(e,t){return e>>>=0,t||_(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},i.prototype.readUint32BE=i.prototype.readUInt32BE=function(e,t){return e>>>=0,t||_(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},i.prototype.readBigUInt64LE=J(function(e){V(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||G(e,this.length-8);const r=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,a=this[++e]+256*this[++e]+65536*this[++e]+n*2**24;return BigInt(r)+(BigInt(a)<<BigInt(32))}),i.prototype.readBigUInt64BE=J(function(e){V(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||G(e,this.length-8);const r=t*2**24+65536*this[++e]+256*this[++e]+this[++e],a=this[++e]*2**24+65536*this[++e]+256*this[++e]+n;return(BigInt(r)<<BigInt(32))+BigInt(a)}),i.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||_(e,t,this.length);let r=this[e],a=1,s=0;for(;++s<t&&(a*=256);)r+=this[e+s]*a;return a*=128,r>=a&&(r-=Math.pow(2,8*t)),r},i.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||_(e,t,this.length);let r=t,a=1,s=this[e+--r];for(;r>0&&(a*=256);)s+=this[e+--r]*a;return a*=128,s>=a&&(s-=Math.pow(2,8*t)),s},i.prototype.readInt8=function(e,t){return e>>>=0,t||_(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},i.prototype.readInt16LE=function(e,t){e>>>=0,t||_(e,2,this.length);const n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},i.prototype.readInt16BE=function(e,t){e>>>=0,t||_(e,2,this.length);const n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},i.prototype.readInt32LE=function(e,t){return e>>>=0,t||_(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},i.prototype.readInt32BE=function(e,t){return e>>>=0,t||_(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},i.prototype.readBigInt64LE=J(function(e){V(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||G(e,this.length-8);const r=this[e+4]+256*this[e+5]+65536*this[e+6]+(n<<24);return(BigInt(r)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)}),i.prototype.readBigInt64BE=J(function(e){V(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||G(e,this.length-8);const r=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(r)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+n)}),i.prototype.readFloatLE=function(e,t){return e>>>=0,t||_(e,4,this.length),n.read(this,e,!0,23,4)},i.prototype.readFloatBE=function(e,t){return e>>>=0,t||_(e,4,this.length),n.read(this,e,!1,23,4)},i.prototype.readDoubleLE=function(e,t){return e>>>=0,t||_(e,8,this.length),n.read(this,e,!0,52,8)},i.prototype.readDoubleBE=function(e,t){return e>>>=0,t||_(e,8,this.length),n.read(this,e,!1,52,8)},i.prototype.writeUintLE=i.prototype.writeUIntLE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){O(this,e,t,n,Math.pow(2,8*n)-1,0)}let a=1,s=0;for(this[t]=255&e;++s<n&&(a*=256);)this[t+s]=e/a&255;return t+n},i.prototype.writeUintBE=i.prototype.writeUIntBE=function(e,t,n,r){if(e=+e,t>>>=0,n>>>=0,!r){O(this,e,t,n,Math.pow(2,8*n)-1,0)}let a=n-1,s=1;for(this[t+a]=255&e;--a>=0&&(s*=256);)this[t+a]=e/s&255;return t+n},i.prototype.writeUint8=i.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,1,255,0),this[t]=255&e,t+1},i.prototype.writeUint16LE=i.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},i.prototype.writeUint16BE=i.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},i.prototype.writeUint32LE=i.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},i.prototype.writeUint32BE=i.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},i.prototype.writeBigUInt64LE=J(function(e,t=0){return F(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),i.prototype.writeBigUInt64BE=J(function(e,t=0){return D(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))}),i.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);O(this,e,t,n,r-1,-r)}let a=0,s=1,o=0;for(this[t]=255&e;++a<n&&(s*=256);)e<0&&0===o&&0!==this[t+a-1]&&(o=1),this[t+a]=(e/s|0)-o&255;return t+n},i.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);O(this,e,t,n,r-1,-r)}let a=n-1,s=1,o=0;for(this[t+a]=255&e;--a>=0&&(s*=256);)e<0&&0===o&&0!==this[t+a+1]&&(o=1),this[t+a]=(e/s|0)-o&255;return t+n},i.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},i.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},i.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},i.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},i.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||O(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},i.prototype.writeBigInt64LE=J(function(e,t=0){return F(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),i.prototype.writeBigInt64BE=J(function(e,t=0){return D(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))}),i.prototype.writeFloatLE=function(e,t,n){return P(this,e,t,!0,n)},i.prototype.writeFloatBE=function(e,t,n){return P(this,e,t,!1,n)},i.prototype.writeDoubleLE=function(e,t,n){return B(this,e,t,!0,n)},i.prototype.writeDoubleBE=function(e,t,n){return B(this,e,t,!1,n)},i.prototype.copy=function(e,t,n,r){if(!i.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<n&&(r=n),r===n)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);const a=r-n;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(t,n,r):Uint8Array.prototype.set.call(e,this.subarray(n,r),t),a},i.prototype.fill=function(e,t,n,r){if("string"==typeof e){if("string"==typeof t?(r=t,t=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!i.isEncoding(r))throw new TypeError("Unknown encoding: "+r);if(1===e.length){const t=e.charCodeAt(0);("utf8"===r&&t<128||"latin1"===r)&&(e=t)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;let a;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(a=t;a<n;++a)this[a]=e;else{const s=i.isBuffer(e)?e:i.from(e,r),o=s.length;if(0===o)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(a=0;a<n-t;++a)this[a+t]=s[a%o]}return this};const L={};function z(e,t,n){L[e]=class extends n{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}function U(e){let t="",n=e.length;const r="-"===e[0]?1:0;for(;n>=r+4;n-=3)t=`_${e.slice(n-3,n)}${t}`;return`${e.slice(0,n)}${t}`}function W(e,t,n,r,a,s){if(e>n||e<t){const n="bigint"==typeof t?"n":"";let r;throw r=0===t||t===BigInt(0)?`>= 0${n} and < 2${n} ** ${8*(s+1)}${n}`:`>= -(2${n} ** ${8*(s+1)-1}${n}) and < 2 ** ${8*(s+1)-1}${n}`,new L.ERR_OUT_OF_RANGE("value",r,e)}!function(e,t,n){V(t,"offset"),void 0!==e[t]&&void 0!==e[t+n]||G(t,e.length-(n+1))}(r,a,s)}function V(e,t){if("number"!=typeof e)throw new L.ERR_INVALID_ARG_TYPE(t,"number",e)}function G(e,t,n){if(Math.floor(e)!==e)throw V(e,n),new L.ERR_OUT_OF_RANGE("offset","an integer",e);if(t<0)throw new L.ERR_BUFFER_OUT_OF_BOUNDS;throw new L.ERR_OUT_OF_RANGE("offset",`>= 0 and <= ${t}`,e)}z("ERR_BUFFER_OUT_OF_BOUNDS",function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"},RangeError),z("ERR_INVALID_ARG_TYPE",function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`},TypeError),z("ERR_OUT_OF_RANGE",function(e,t,n){let r=`The value of "${e}" is out of range.`,a=n;return Number.isInteger(n)&&Math.abs(n)>2**32?a=U(String(n)):"bigint"==typeof n&&(a=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(a=U(a)),a+="n"),r+=` It must be ${t}. Received ${a}`,r},RangeError);const j=/[^+/0-9A-Za-z-_]/g;function H(e,t){let n;t=t||1/0;const r=e.length;let a=null;const s=[];for(let o=0;o<r;++o){if(n=e.charCodeAt(o),n>55295&&n<57344){if(!a){if(n>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(o+1===r){(t-=3)>-1&&s.push(239,191,189);continue}a=n;continue}if(n<56320){(t-=3)>-1&&s.push(239,191,189),a=n;continue}n=65536+(a-55296<<10|n-56320)}else a&&(t-=3)>-1&&s.push(239,191,189);if(a=null,n<128){if((t-=1)<0)break;s.push(n)}else if(n<2048){if((t-=2)<0)break;s.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;s.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;s.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return s}function q(e){return t.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(j,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function K(e,t,n,r){let a;for(a=0;a<r&&!(a+n>=t.length||a>=e.length);++a)t[a+n]=e[a];return a}function X(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function Y(e){return e!=e}const Q=function(){const e="0123456789abcdef",t=new Array(256);for(let n=0;n<16;++n){const r=16*n;for(let a=0;a<16;++a)t[r+a]=e[n]+e[a]}return t}();function J(e){return"undefined"==typeof BigInt?Z:e}function Z(){throw new Error("BigInt not supported")}}(a);let I=!1;if("undefined"!=typeof globalThis&&g())try{void 0===globalThis.TextEncoder&&(globalThis.TextEncoder=TextEncoder),void 0===globalThis.TextDecoder&&(globalThis.TextDecoder=TextDecoder),"undefined"!=typeof global&&(global.TextEncoder||(global.TextEncoder=TextEncoder),global.TextDecoder||(global.TextDecoder=TextDecoder),global.__TextEncoder__=TextEncoder,global.__TextDecoder__=TextDecoder);const e={TextEncoder:TextEncoder,TextDecoder:TextDecoder,types:{isFloat32Array:e=>e instanceof Float32Array,isInt32Array:e=>e instanceof Int32Array,isUint8Array:e=>e instanceof Uint8Array,isUint8ClampedArray:e=>e instanceof Uint8ClampedArray}};if("undefined"!=typeof global&&(global.__brainy_util__=e),"undefined"!=typeof global&&global.require&&global.require.cache)for(const t in global.require.cache)if(t.endsWith("/util.js")||"util"===t){const n=global.require.cache[t];n&&n.exports&&Object.assign(n.exports,e)}try{const e=require("util");e.TextEncoder=TextEncoder,e.TextDecoder=TextDecoder}catch(e){}const t="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{};if(t&&t.Float32Array){const e=t.Float32Array,n=class extends e{constructor(e,t,n){if(e instanceof ArrayBuffer){const r=t||0,a=void 0!==n?n:(e.byteLength-r)/4;if((e.byteLength-r)%4!=0&&void 0===n)try{const t=4*Math.floor((e.byteLength-r)/4),n=new ArrayBuffer(t),a=new Uint8Array(e,r,t);new Uint8Array(n).set(a),super(n)}catch(t){console.warn("Float32Array alignment failed, using original constructor:",t),super(e,r,a)}else super(e,r,a)}else super(e,t,n)}};try{Object.setPrototypeOf(n,e),Object.defineProperty(n,"name",{value:"Float32Array"}),Object.defineProperty(n,"BYTES_PER_ELEMENT",{value:4}),t.Float32Array=n}catch(e){console.warn("Failed to patch Float32Array:",e)}}if("undefined"!=typeof global){const e=e=>{e&&"object"==typeof e&&!e.TextEncoder&&(e.TextEncoder=TextEncoder,e.TextDecoder=TextDecoder,e.types=e.types||{isFloat32Array:e=>e instanceof Float32Array,isInt32Array:e=>e instanceof Int32Array,isUint8Array:e=>e instanceof Uint8Array,isUint8ClampedArray:e=>e instanceof Uint8ClampedArray})};global._utilShim&&e(global._utilShim),"undefined"!=typeof globalThis&&globalThis._utilShim&&e(globalThis._utilShim),global._utilShim?e(global._utilShim):global._utilShim={TextEncoder:TextEncoder,TextDecoder:TextDecoder,types:{isFloat32Array:e=>e instanceof Float32Array,isInt32Array:e=>e instanceof Int32Array,isUint8Array:e=>e instanceof Uint8Array,isUint8ClampedArray:e=>e instanceof Uint8ClampedArray}},"undefined"==typeof globalThis||globalThis._utilShim||(globalThis._utilShim=global._utilShim);try{Object.defineProperty(global,"_utilShim",{get(){return this.__utilShim||{}},set(t){e(t),this.__utilShim=t},configurable:!0})}catch(e){}try{Object.defineProperty(globalThis,"_utilShim",{get(){return this.__utilShim||{}},set(t){e(t),this.__utilShim=t},configurable:!0})}catch(e){}}console.log("Brainy: Successfully patched TensorFlow.js PlatformNode at module load time"),I=!0}catch(e){console.warn("Brainy: Failed to apply early TensorFlow.js platform patch:",e)}async function S(){if("undefined"!=typeof window&&"undefined"!=typeof document)return;const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};if(!I||void 0===e.__TextEncoder__||void 0===e.__TextDecoder__)try{console.log("Brainy: Applying TensorFlow.js platform patch via function call"),e.TextEncoder||(e.TextEncoder=TextEncoder),e.TextDecoder||(e.TextDecoder=TextDecoder),e.__TextEncoder__=TextEncoder,e.__TextDecoder__=TextDecoder,"undefined"!=typeof process&&process.versions&&(process.versions.node||(process.versions.node=process.version));try{const e=await Promise.resolve().then(function(){return Ht});e.TextEncoder=TextEncoder,e.TextDecoder=TextDecoder}catch(e){}I=!0}catch(e){console.warn("Brainy: Failed to apply TensorFlow.js platform patch:",e)}}S().catch(e=>{console.warn("Failed to apply TensorFlow patch at module load:",e)});var T=Object.freeze({__proto__:null,applyTensorFlowPatch:S});const N="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof self?self:null;let C;N&&(N.TextEncoder||(N.TextEncoder=TextEncoder),N.TextDecoder||(N.TextDecoder=TextDecoder),N.__TextEncoder__=TextEncoder,N.__TextDecoder__=TextDecoder),S(),console.log("Applied TensorFlow.js patch via ES modules in setup.ts");const E=new Uint8Array(16);function $(){if(!C&&(C="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!C))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return C(E)}const A=[];for(let e=0;e<256;++e)A.push((e+256).toString(16).slice(1));var R={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function _(e,t,n){if(R.randomUUID&&!e)return R.randomUUID();const r=(e=e||{}).random||(e.rng||$)();return r[6]=15&r[6]|64,r[8]=63&r[8]|128,function(e,t=0){return A[e[t+0]]+A[e[t+1]]+A[e[t+2]]+A[e[t+3]]+"-"+A[e[t+4]]+A[e[t+5]]+"-"+A[e[t+6]]+A[e[t+7]]+"-"+A[e[t+8]]+A[e[t+9]]+"-"+A[e[t+10]]+A[e[t+11]]+A[e[t+12]]+A[e[t+13]]+A[e[t+14]]+A[e[t+15]]}(r)}const O=(e,t)=>{if(e.length!==t.length)throw new Error("Vectors must have the same dimensions");const n=e.reduce((e,n,r)=>{const a=n-t[r];return e+a*a},0);return Math.sqrt(n)},F=(e,t)=>{if(e.length!==t.length)throw new Error("Vectors must have the same dimensions");const{dotProduct:n,normA:r,normB:a}=e.reduce((e,n,r)=>({dotProduct:e.dotProduct+n*t[r],normA:e.normA+n*n,normB:e.normB+t[r]*t[r]}),{dotProduct:0,normA:0,normB:0});if(0===r||0===a)return 2;return 1-n/(Math.sqrt(r)*Math.sqrt(a))},D=(e,t)=>{if(e.length!==t.length)throw new Error("Vectors must have the same dimensions");return e.reduce((e,n,r)=>e+Math.abs(n-t[r]),0)},M=(e,t)=>{if(e.length!==t.length)throw new Error("Vectors must have the same dimensions");const n=e.reduce((e,n,r)=>e+n*t[r],0);return-n};async function P(e,t,n=O){if(t.length<10)return t.map(t=>n(e,t));try{return t.map(t=>n(e,t))}catch(r){return console.error("Batch distance calculation failed:",r),t.map(t=>n(e,t))}}const B=new Map;function L(e,t){if(g())return function(e,t){return new Promise((n,r)=>{try{import("node:worker_threads").then(({Worker:a,isMainThread:s,parentPort:o,workerData:i})=>{if(!s&&o){const e=new Function("return "+i.fnString)()(i.args);return void o.postMessage({result:e})}const c=`worker-${Math.random().toString(36).substring(2,9)}`;let l;if(B.size<4)l=new a("\n import { parentPort, workerData } from 'node:worker_threads';\n\n // Add TensorFlow.js platform patch for Node.js\n if (typeof global !== 'undefined') {\n try {\n // Define a custom PlatformNode class\n class PlatformNode {\n constructor() {\n // Create a util object with necessary methods\n this.util = {\n // Add isFloat32Array and isTypedArray directly to util\n isFloat32Array: (arr) => {\n return !!(\n arr instanceof Float32Array ||\n (arr &&\n Object.prototype.toString.call(arr) === '[object Float32Array]')\n );\n },\n isTypedArray: (arr) => {\n return !!(ArrayBuffer.isView(arr) && !(arr instanceof DataView));\n },\n // Use native TextEncoder and TextDecoder\n TextEncoder: TextEncoder,\n TextDecoder: TextDecoder\n };\n\n // Initialize encoders using native constructors\n this.textEncoder = new TextEncoder();\n this.textDecoder = new TextDecoder();\n }\n\n // Define isFloat32Array directly on the instance\n isFloat32Array(arr) {\n return !!(\n arr instanceof Float32Array ||\n (arr && Object.prototype.toString.call(arr) === '[object Float32Array]')\n );\n }\n\n // Define isTypedArray directly on the instance\n isTypedArray(arr) {\n return !!(ArrayBuffer.isView(arr) && !(arr instanceof DataView));\n }\n }\n\n // Assign the PlatformNode class to the global object\n global.PlatformNode = PlatformNode;\n\n // Also create an instance and assign it to global.platformNode\n global.platformNode = new PlatformNode();\n\n // Ensure global.util exists and has the necessary methods\n if (!global.util) {\n global.util = {};\n }\n\n // Add isFloat32Array method if it doesn't exist\n if (!global.util.isFloat32Array) {\n global.util.isFloat32Array = (arr) => {\n return !!(\n arr instanceof Float32Array ||\n (arr && Object.prototype.toString.call(arr) === '[object Float32Array]')\n );\n };\n }\n\n // Add isTypedArray method if it doesn't exist\n if (!global.util.isTypedArray) {\n global.util.isTypedArray = (arr) => {\n return !!(ArrayBuffer.isView(arr) && !(arr instanceof DataView));\n };\n }\n } catch (error) {\n console.warn('Failed to apply TensorFlow.js platform patch:', error);\n }\n }\n\n const fn = new Function('return ' + workerData.fnString)();\n const result = fn(workerData.args);\n parentPort.postMessage({ result });\n ",{eval:!0,workerData:{fnString:e,args:t}}),B.set(c,l);else{const n=Array.from(B.keys()),r=n[Math.floor(Math.random()*n.length)];l=B.get(r),l._busy&&(l.terminate(),l=new a("\n import { parentPort, workerData } from 'node:worker_threads';\n\n // Add TensorFlow.js platform patch for Node.js\n if (typeof global !== 'undefined') {\n try {\n // Define a custom PlatformNode class\n class PlatformNode {\n constructor() {\n // Create a util object with necessary methods\n this.util = {\n // Use native TextEncoder and TextDecoder\n TextEncoder: TextEncoder,\n TextDecoder: TextDecoder\n };\n\n // Initialize encoders using native constructors\n this.textEncoder = new TextEncoder();\n this.textDecoder = new TextDecoder();\n }\n\n // Define isFloat32Array directly on the instance\n isFloat32Array(arr) {\n return !!(\n arr instanceof Float32Array ||\n (arr && Object.prototype.toString.call(arr) === '[object Float32Array]')\n );\n }\n\n // Define isTypedArray directly on the instance\n isTypedArray(arr) {\n return !!(ArrayBuffer.isView(arr) && !(arr instanceof DataView));\n }\n }\n\n // Assign the PlatformNode class to the global object\n global.PlatformNode = PlatformNode;\n\n // Also create an instance and assign it to global.platformNode\n global.platformNode = new PlatformNode();\n\n // Ensure global.util exists and has the necessary methods\n if (!global.util) {\n global.util = {};\n }\n\n // Add isFloat32Array method if it doesn't exist\n if (!global.util.isFloat32Array) {\n global.util.isFloat32Array = (arr) => {\n return !!(\n arr instanceof Float32Array ||\n (arr && Object.prototype.toString.call(arr) === '[object Float32Array]')\n );\n };\n }\n\n // Add isTypedArray method if it doesn't exist\n if (!global.util.isTypedArray) {\n global.util.isTypedArray = (arr) => {\n return !!(ArrayBuffer.isView(arr) && !(arr instanceof DataView));\n };\n }\n } catch (error) {\n console.warn('Failed to apply TensorFlow.js platform patch:', error);\n }\n }\n\n const fn = new Function('return ' + workerData.fnString)();\n const result = fn(workerData.args);\n parentPort.postMessage({ result });\n ",{eval:!0,workerData:{fnString:e,args:t}}),B.set(r,l)),l._busy=!0}l.on("message",e=>{l._busy=!1,n(e.result)}),l.on("error",e=>{l._busy=!1,r(e)}),l.on("exit",e=>{0!==e&&(l._busy=!1,r(new Error(`Worker stopped with exit code ${e}`)))})}).catch(r)}catch(e){r(e)}})}(e,t);if(m()&&"undefined"!=typeof window&&window.Worker)return function(e,t){return new Promise((n,r)=>{try{let a,s="./worker.js";try{if(void 0!==import.meta&&import.meta.url){s=`${import.meta.url.substring(0,import.meta.url.lastIndexOf("/")+1)}worker.js`}else if("undefined"!=typeof document){const e=document.getElementsByTagName("script");for(let t=0;t<e.length;t++){const n=e[t].src;if(n&&n.includes("unified.js")){s=n.substring(0,n.lastIndexOf("/")+1)+"worker.js";break}}}}catch(e){console.warn("Could not determine worker path from import.meta.url, using relative path",e)}if("./worker.js"===s&&"undefined"!=typeof window){const e=window.location.href,t=e.substring(0,e.lastIndexOf("/")+1);if(s=`${t}worker.js`,"undefined"!=typeof document){const e=`${t}dist/worker.js`,n=new XMLHttpRequest;n.open("HEAD",e,!1);try{n.send(),n.status>=200&&n.status<300&&(s=e)}catch(e){}}}console.log("Using worker path:",s);try{a=new Worker(s)}catch(s){console.warn("Failed to create Web Worker from file, trying inline worker:",s);try{const e=new Blob(["\n // Brainy Inline Worker Script\n console.log('Brainy Inline Worker: Started');\n\n self.onmessage = function (e) {\n try {\n console.log('Brainy Inline Worker: Received message', e.data ? 'with data' : 'without data');\n\n if (!e.data || !e.data.fnString) {\n throw new Error('Invalid message: missing function string');\n }\n\n console.log('Brainy Inline Worker: Creating function from string');\n const fn = new Function('return ' + e.data.fnString)();\n\n console.log('Brainy Inline Worker: Executing function with args');\n const result = fn(e.data.args);\n\n console.log('Brainy Inline Worker: Function executed successfully, posting result');\n self.postMessage({ result: result });\n } catch (error) {\n console.error('Brainy Inline Worker: Error executing function', error);\n self.postMessage({ \n error: error.message,\n stack: error.stack\n });\n }\n };\n "],{type:"application/javascript"}),t=URL.createObjectURL(e);a=new Worker(t),console.log("Created inline worker using Blob URL")}catch(a){console.warn("Failed to create inline Web Worker, falling back to main thread execution:",a);try{const r=new Function("return "+e)();return void n(r(t))}catch(e){return void r(e)}}}const o=setTimeout(()=>{console.warn("Web Worker execution timed out, falling back to main thread"),a.terminate();try{const r=new Function("return "+e)();n(r(t))}catch(e){r(e)}},25e3);a.onmessage=function(e){clearTimeout(o),e.data.error?r(new Error(e.data.error)):n(e.data.result),a.terminate()},a.onerror=function(s){clearTimeout(o),console.warn("Web Worker error, falling back to main thread execution:",s.message),a.terminate();try{const r=new Function("return "+e)();n(r(t))}catch(e){r(e)}},a.postMessage({fnString:e,args:t})}catch(e){r(e)}})}(e,t);try{let n;try{n=new Function("return "+e)()}catch(t){console.warn("Fallback: Error creating function with return syntax, trying alternative approaches",t);try{n=new Function("return ("+e+")")()}catch(r){console.warn("Fallback: Error creating function with parentheses wrapping",r);try{n=new Function(e)()}catch(r){console.warn("Fallback: Direct approach failed, trying with function wrapper",r);try{n=new Function("return function(args) { return ("+e+")(args); }")()}catch(e){throw console.error("Fallback: All approaches to create function failed",e),new Error("Failed to create function from string: "+t.message)}}}}return Promise.resolve(n(t))}catch(e){return Promise.reject(e)}}function z(){g()&&import("node:worker_threads").then(({Worker:e})=>{for(const e of B.values())e.terminate();B.clear(),console.log("Worker pools cleaned up")}).catch(console.error)}let U=class{constructor(e={}){this.model=null,this.initialized=!1,this.tf=null,this.use=null,this.backend="cpu",this.verbose=!0,this.verbose=void 0===e.verbose||e.verbose}addServerCompatibilityPolyfills(){if(m())return;const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};try{e.util||(e.util={}),e.util.isFloat32Array||(e.util.isFloat32Array=e=>!!(e instanceof Float32Array||e&&"[object Float32Array]"===Object.prototype.toString.call(e))),e.util.isTypedArray||(e.util.isTypedArray=e=>!(!ArrayBuffer.isView(e)||e instanceof DataView))}catch(e){console.warn("Failed to add utility polyfills:",e)}}isTestEnvironment(){return"undefined"!=typeof process&&("true"===process.env.VITEST||"undefined"!=typeof global&&global.__vitest__||process.argv.some(e=>e.includes("vitest")))}logger(e,t,...n){("error"===e||this.verbose)&&console[e](t,...n)}async loadModelWithRetry(e,t=3,n=1e3){let r=null;const a=[];if(this.use){const e=["https://storage.googleapis.com/tfjs-models/savedmodel/universal_sentence_encoder/model.json","https://tfhub.dev/tensorflow/tfjs-model/universal-sentence-encoder-lite/1/default/1/model.json","https://tfhub.dev/tensorflow/tfjs-model/universal-sentence-encoder/1/default/1/model.json","https://tfhub.dev/tensorflow/tfjs-model/universal-sentence-encoder/1/default/1","https://tfhub.dev/tensorflow/universal-sentence-encoder/4","https://tfhub.dev/tensorflow/universal-sentence-encoder/4/default/1/model.json"];for(const t of e)this.use.load?a.push(()=>this.use.load(t)):this.use.default&&this.use.default.load&&a.push(()=>this.use.default.load(t))}for(let s=0;s<=t;s++)try{this.logger("log",0===s?"Loading Universal Sentence Encoder model...":`Retrying Universal Sentence Encoder model loading (attempt ${s+1}/${t+1})...`);const n=await e();return s>0&&this.logger("log","Universal Sentence Encoder model loaded successfully after retry"),n}catch(e){r=e;const o=r.message||String(r),i=o.includes("Failed to parse model JSON")||o.includes("Failed to fetch")||o.includes("Network error")||o.includes("ENOTFOUND")||o.includes("ECONNRESET")||o.includes("ETIMEDOUT")||o.includes("JSON")||o.includes("model.json")||o.includes("byte length")||o.includes("tensor should have")||o.includes("shape")||o.includes("dimensions");if(!(s<t&&i)){if(s>=t){if(this.logger("warn",`Universal Sentence Encoder model loading failed after ${t+1} attempts. Last error: ${o}. Trying alternative URLs...`),a.length>0)for(let e=0;e<a.length;e++)try{this.logger("log",`Trying alternative model URL ${e+1}/${a.length}...`);const t=await a[e]();return this.logger("log",`Successfully loaded Universal Sentence Encoder from alternative URL ${e+1}`),t}catch(t){this.logger("warn",`Failed to load from alternative URL ${e+1}: ${t}`)}this.logger("error",`Universal Sentence Encoder model loading failed after trying all alternatives. Last error: ${o}`)}else this.logger("error",`Universal Sentence Encoder model loading failed with non-retryable error: ${o}`);throw r}{const e=n*Math.pow(2,s);this.logger("warn",`Universal Sentence Encoder model loading failed (attempt ${s+1}): ${o}. Retrying in ${e}ms...`),await new Promise(t=>setTimeout(t,e))}}throw r||new Error("Unknown error during model loading")}async init(){try{const e=console.warn;console.warn=function(t,...n){t&&"string"==typeof t&&t.includes("Hi, looks like you are running TensorFlow.js in Node.js")||e(t,...n)},this.addServerCompatibilityPolyfills();try{const e="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof global?global:"undefined"!=typeof self?self:null;if(e)try{if("undefined"!=typeof process&&process.versions&&process.versions.node){const t=await Promise.resolve().then(function(){return Ht});e.TextEncoder||(e.TextEncoder=t.TextEncoder),e.TextDecoder||(e.TextDecoder=t.TextDecoder)}}catch(t){e.TextEncoder||(e.TextEncoder=TextEncoder),e.TextDecoder||(e.TextDecoder=TextDecoder)}const{applyTensorFlowPatch:t}=await Promise.resolve().then(function(){return T});await t(),this.tf=await Promise.resolve().then(function(){return Fy}),await Promise.resolve().then(function(){return gS});try{if(m()){await Promise.resolve().then(function(){return KO});try{this.tf.setBackend?(await this.tf.setBackend("webgl"),this.backend="webgl",console.log("Using WebGL backend for TensorFlow.js")):console.warn("tf.setBackend is not available, falling back to CPU")}catch(e){console.warn("WebGL backend not available, falling back to CPU:",e),this.backend="cpu"}}}catch(e){console.warn("WebGL backend not available, falling back to CPU:",e),this.backend="cpu"}this.use=await Promise.resolve().then(function(){return ED})}catch(e){return this.logger("error","Failed to initialize TensorFlow.js:",e),this.logger("warn","Will use fallback embedding mechanism"),void(this.initialized=!0)}this.tf&&this.tf.setBackend&&await this.tf.setBackend(this.backend);const t=function(e){let t=null;if(e.load&&"function"==typeof e.load)t=e.load;else if(e.default&&e.default.load&&"function"==typeof e.default.load)t=e.default.load;else if(e.default&&"function"==typeof e.default)t=e.default;else if("function"==typeof e)t=e;else if(e.UniversalSentenceEncoder&&"function"==typeof e.UniversalSentenceEncoder.load)t=e.UniversalSentenceEncoder.load;else if(e.default&&e.default.UniversalSentenceEncoder&&"function"==typeof e.default.UniversalSentenceEncoder.load)t=e.default.UniversalSentenceEncoder.load;else for(const n in e)if("function"==typeof e[n]){if((e[n].name||n).toLowerCase().includes("load")){t=e[n];break}}else if("object"==typeof e[n]&&null!==e[n]){for(const r in e[n])if("function"==typeof e[n][r]){if((e[n][r].name||r).toLowerCase().includes("load")){t=e[n][r];break}}if(t)break}if(t)return async()=>await t();return null}(this.use);if(!t)return this.logger("warn","Could not find Universal Sentence Encoder load function, using fallback"),void(this.initialized=!0);try{this.model=await this.loadModelWithRetry(t),this.initialized=!0}catch(e){this.logger("warn","Failed to load Universal Sentence Encoder model, using fallback:",e),this.initialized=!0}console.warn=e}catch(e){this.logger("error","Failed to initialize Universal Sentence Encoder:",e),this.logger("warn","Using fallback embedding mechanism due to initialization failure"),this.initialized=!0}}generateFallbackVector(e){const t=new Array(512).fill(0);if(!e||""===e.trim())return t;const n=e=>{let t=0;for(let n=0;n<e.length;n++)t=(t<<5)-t+e.charCodeAt(n),t|=0;return t},r=e.split(/\s+/);for(let e=0;e<r.length&&e<512;e++){const a=r[e];if(a){const e=n(a);t[Math.abs(e)%512]=e%1e3/1e3}}if(e.length>0){const r=n(e);for(let e=0;e<10;e++){t[(Math.abs(r)+50*e)%512]=(r+e)%1e3/1e3}}return t}async embed(e){this.initialized||await this.init();try{let t;if("string"==typeof e){if(""===e.trim())return new Array(512).fill(0);t=[e]}else{if(!Array.isArray(e)||!e.every(e=>"string"==typeof e))throw new Error("UniversalSentenceEncoder only supports string or string[] data");if(0===e.length||e.every(e=>""===e.trim()))return new Array(512).fill(0);if(t=e.filter(e=>""!==e.trim()),0===t.length)return new Array(512).fill(0)}if(!this.model)return this.logger("warn","Using fallback embedding mechanism (model not available)"),this.generateFallbackVector(t[0]);const n=await this.model.embed(t),r=await n.array();n.dispose();let a=r[0];if(512!==a.length)if(this.logger("warn",`Embedding dimension mismatch: expected 512, got ${a.length}. Standardizing...`),a.length<512){const e=new Array(512).fill(0);for(let t=0;t<a.length;t++)e[t]=a[t];a=e}else if(a.length>512)if(1536===a.length){const e=new Array(512).fill(0);for(let t=0;t<512;t++)e[t]=a[3*t];a=e}else a=a.slice(0,512);return a}catch(t){return this.logger("warn","Failed to embed text with Universal Sentence Encoder, using fallback:",t),"string"==typeof e?this.generateFallbackVector(e):Array.isArray(e)&&e.length>0?this.generateFallbackVector(e[0]):new Array(512).fill(0)}}async embedBatch(e){this.initialized||await this.init();try{if(0===e.length)return[];const t=e.filter(e=>"string"==typeof e&&""!==e.trim());if(0===t.length)return e.map(()=>new Array(512).fill(0));if(!this.model)return this.logger("warn","Using fallback embedding mechanism for batch (model not available)"),e.map(e=>"string"==typeof e&&""!==e.trim()?this.generateFallbackVector(e):new Array(512).fill(0));const n=await this.model.embed(t),r=await n.array();n.dispose();const a=r.map(e=>{if(512!==e.length){if(this.logger("warn",`Batch embedding dimension mismatch: expected 512, got ${e.length}. Standardizing...`),e.length<512){const t=new Array(512).fill(0);for(let n=0;n<e.length;n++)t[n]=e[n];return t}if(e.length>512){if(1536===e.length){const t=new Array(512).fill(0);for(let n=0;n<512;n++)t[n]=e[3*n];return t}return e.slice(0,512)}}return e}),s=[];let o=0;for(let t=0;t<e.length;t++){const n=e[t];"string"==typeof n&&""!==n.trim()?(s.push(a[o]),o++):s.push(new Array(512).fill(0))}return s}catch(t){return this.logger("warn","Failed to batch embed text with Universal Sentence Encoder, using fallback:",t),e.map(e=>"string"==typeof e&&""!==e.trim()?this.generateFallbackVector(e):new Array(512).fill(0))}}async dispose(){if(this.model&&this.tf)try{this.model.dispose(),this.tf.disposeVariables(),this.initialized=!1}catch(e){this.logger("error","Failed to dispose Universal Sentence Encoder:",e)}return Promise.resolve()}};function W(e,t,n=[],r=!0){"undefined"!=typeof process&&("true"===process.env.VITEST||"undefined"!=typeof global&&global.__vitest__||process.argv.some(e=>e.includes("vitest")))||console[e](t,...n)}function V(e){return e?async t=>await e.embed(t):q()}let G=null,j=!1,H=!0;function q(e={}){return void 0!==e.verbose&&(H=e.verbose),G||(G=new U({verbose:H})),async e=>{try{if(!j)try{await G.init(),j=!0}catch(e){throw j=!1,e}return await G.embed(e)}catch(e){throw W("error","Failed to use TensorFlow embedding:",[e],H),new Error(`Universal Sentence Encoder is required but failed: ${e}`)}}}function K(e={}){return q(e)}const X=K();let Y=null,Q=!1,J=!0;function Z(e={}){return void 0!==e.verbose&&(J=e.verbose),Y||(Y=new U({verbose:J})),async e=>{try{return Q||(await Y.init(),Q=!0),await Y.embedBatch(e)}catch(e){throw W("error","Failed to use TensorFlow batch embedding:",[e],J),new Error(`Universal Sentence Encoder batch embedding failed: ${e}`)}}}function ee(e={}){return Z(e)}const te=ee();function ne(e){const t=V(e);return async e=>{const n=t.toString();return await L(n,e)}}var re=Object.freeze({__proto__:null,UniversalSentenceEncoder:U,createBatchEmbeddingFunction:Z,createEmbeddingFunction:V,createTensorFlowEmbeddingFunction:q,createThreadedEmbeddingFunction:ne,defaultBatchEmbeddingFunction:te,defaultEmbeddingFunction:X,getDefaultBatchEmbeddingFunction:ee,getDefaultEmbeddingFunction:K});async function ae(e,t={}){if(!e)throw new Error("BrainyData instance must be provided to getStatistics");try{return await e.getStatistics(t)}catch(e){throw console.error("Failed to get statistics:",e),new Error(`Failed to get statistics: ${e}`)}}const se={M:16,efConstruction:200,efSearch:50,ml:16};class oe{constructor(e={},t=O,n={}){this.nouns=new Map,this.entryPointId=null,this.maxLevel=0,this.dimension=null,this.useParallelization=!0,this.config={...se,...e},this.distanceFunction=t,this.useParallelization=void 0===n.useParallelization||n.useParallelization}setUseParallelization(e){this.useParallelization=e}getUseParallelization(){return this.useParallelization}async calculateDistancesInParallel(e,t){if(!this.useParallelization||t.length<10)return t.map(t=>({id:t.id,distance:this.distanceFunction(e,t.vector)}));try{const n=t.map(e=>e.vector),r=await P(e,n,this.distanceFunction);return t.map((e,t)=>({id:e.id,distance:r[t]}))}catch(n){return console.error("Error in GPU-accelerated distance calculation, falling back to sequential processing:",n),t.map(t=>({id:t.id,distance:this.distanceFunction(e,t.vector)}))}}async addItem(e){if(!e)throw new Error("Item is undefined or null");const{id:t,vector:n}=e;if(!n)throw new Error("Vector is undefined or null");if(null===this.dimension)this.dimension=n.length;else if(n.length!==this.dimension)throw new Error(`Vector dimension mismatch: expected ${this.dimension}, got ${n.length}`);const r=this.getRandomLevel(),a={id:t,vector:n,connections:new Map};for(let e=0;e<=r;e++)a.connections.set(e,new Set);if(0===this.nouns.size)return this.entryPointId=t,this.maxLevel=r,this.nouns.set(t,a),t;if(!this.entryPointId)return console.error("Entry point ID is null"),this.entryPointId=t,this.maxLevel=r,this.nouns.set(t,a),t;const s=this.nouns.get(this.entryPointId);if(!s)return console.error(`Entry point with ID ${this.entryPointId} not found`),this.entryPointId=t,this.maxLevel=r,this.nouns.set(t,a),t;let o=s,i=this.distanceFunction(n,s.vector);for(let e=this.maxLevel;e>r;e--){let t=!0;for(;t;){t=!1;const r=o.connections.get(e)||new Set;for(const e of r){const r=this.nouns.get(e);if(!r)continue;const a=this.distanceFunction(n,r.vector);a<i&&(i=a,o=r,t=!0)}}}for(let e=Math.min(r,this.maxLevel);e>=0;e--){const r=await this.searchLayer(n,o,this.config.efConstruction,e),s=this.selectNeighbors(n,r,this.config.M);for(const[n,r]of s){const r=this.nouns.get(n);r&&(a.connections.get(e).add(n),r.connections.has(e)||r.connections.set(e,new Set),r.connections.get(e).add(t),r.connections.get(e).size>this.config.M&&this.pruneConnections(r,e))}if(r.size>0){const[e,t]=[...r][0];if(t<i){i=t;const n=this.nouns.get(e);n?o=n:console.error(`Nearest noun with ID ${e} not found in addItem`)}}}return r>this.maxLevel&&(this.maxLevel=r,this.entryPointId=t),this.nouns.set(t,a),t}async search(e,t=10){if(0===this.nouns.size)return[];if(!e)throw new Error("Query vector is undefined or null");if(null!==this.dimension&&e.length!==this.dimension)throw new Error(`Query vector dimension mismatch: expected ${this.dimension}, got ${e.length}`);if(!this.entryPointId)return console.error("Entry point ID is null"),[];const n=this.nouns.get(this.entryPointId);if(!n)return console.error(`Entry point with ID ${this.entryPointId} not found`),[];let r=n,a=this.distanceFunction(e,r.vector);for(let t=this.maxLevel;t>0;t--){let n=!0;for(;n;){n=!1;const s=r.connections.get(t)||new Set;if(this.useParallelization&&s.size>=10){const t=[];for(const e of s){const n=this.nouns.get(e);n&&t.push({id:e,vector:n.vector})}const o=await this.calculateDistancesInParallel(e,t);for(const{id:e,distance:t}of o)if(t<a){a=t;const s=this.nouns.get(e);s&&(r=s,n=!0)}}else for(const t of s){const s=this.nouns.get(t);if(!s)continue;const o=this.distanceFunction(e,s.vector);o<a&&(a=o,r=s,n=!0)}}}return[...await this.searchLayer(e,r,Math.max(this.config.efSearch,t),0)].slice(0,t)}removeItem(e){if(!this.nouns.has(e))return!1;const t=this.nouns.get(e);for(const[n,r]of t.connections.entries())for(const t of r){const r=this.nouns.get(t);r&&(r.connections.has(n)&&(r.connections.get(n).delete(e),this.pruneConnections(r,n)))}for(const[t,n]of this.nouns.entries())if(t!==e)for(const[t,r]of n.connections.entries())r.has(e)&&(r.delete(e),this.pruneConnections(n,t));if(this.nouns.delete(e),this.entryPointId===e)if(0===this.nouns.size)this.entryPointId=null,this.maxLevel=0;else{let e=0,t=null;for(const[n,r]of this.nouns.entries()){if(0===r.connections.size)continue;const a=Math.max(...r.connections.keys());a>=e&&(e=a,t=n)}this.entryPointId=t,this.maxLevel=e}return!0}getNouns(){return new Map(this.nouns)}getNounsPaginated(e={}){const t=e.offset||0,n=e.limit||100,r=e.filter||(()=>!0),a=[...this.nouns.entries()].filter(([e,t])=>r(t)),s=a.length,o=a.slice(t,t+n),i=t+n<s;return{items:new Map(o),totalCount:s,hasMore:i}}clear(){this.nouns.clear(),this.entryPointId=null,this.maxLevel=0}size(){return this.nouns.size}getDistanceFunction(){return this.distanceFunction}getEntryPointId(){return this.entryPointId}getMaxLevel(){return this.maxLevel}getDimension(){return this.dimension}getConfig(){return{...this.config}}async searchLayer(e,t,n,r){const a=new Set([t.id]),s=new Map;s.set(t.id,this.distanceFunction(e,t.vector));const o=new Map;for(o.set(t.id,this.distanceFunction(e,t.vector));s.size>0;){const[t,i]=[...s][0];s.delete(t);const c=[...o][o.size-1];if(o.size>=n&&i>c[1])break;const l=this.nouns.get(t);if(!l){console.error(`Noun with ID ${t} not found in searchLayer`);continue}const u=l.connections.get(r)||new Set;if(this.useParallelization&&u.size>=10){const t=[];for(const e of u)if(!a.has(e)){a.add(e);const n=this.nouns.get(e);if(!n)continue;t.push({id:e,vector:n.vector})}if(t.length>0){const r=await this.calculateDistancesInParallel(e,t);for(const{id:e,distance:t}of r)if((o.size<n||t<c[1])&&(s.set(e,t),o.set(e,t),o.size>n)){const e=[...o].sort((e,t)=>e[1]-t[1]);o.clear();for(let t=0;t<n;t++)o.set(e[t][0],e[t][1])}}}else for(const t of u)if(!a.has(t)){a.add(t);const r=this.nouns.get(t);if(!r)continue;const i=this.distanceFunction(e,r.vector);if((o.size<n||i<c[1])&&(s.set(t,i),o.set(t,i),o.size>n)){const e=[...o].sort((e,t)=>e[1]-t[1]);o.clear();for(let t=0;t<n;t++)o.set(e[t][0],e[t][1])}}}return new Map([...o].sort((e,t)=>e[1]-t[1]))}selectNeighbors(e,t,n){if(t.size<=n)return t;const r=[...t].sort((e,t)=>e[1]-t[1]),a=new Map;for(let e=0;e<Math.min(n,r.length);e++)a.set(r[e][0],r[e][1]);return a}pruneConnections(e,t){const n=e.connections.get(t);if(n.size<=this.config.M)return;const r=new Map,a=new Set;for(const t of n){const n=this.nouns.get(t);n&&(r.set(t,this.distanceFunction(e.vector,n.vector)),a.add(t))}if(0===r.size)return void e.connections.set(t,new Set);const s=this.selectNeighbors(e.vector,r,this.config.M);e.connections.set(t,new Set(s.keys()))}getRandomLevel(){const e=Math.random();return Math.floor(-Math.log(e)*(1/Math.log(this.config.M)))}}const ie={M:16,efConstruction:200,efSearch:50,ml:16,memoryThreshold:1073741824,productQuantization:{enabled:!1,numSubvectors:16,numCentroids:256},useDiskBasedIndex:!1};class ce{constructor(e=16,t=256){this.centroids=[],this.subvectorSize=0,this.initialized=!1,this.dimension=0,this.numSubvectors=e,this.numCentroids=t}train(e){if(0===e.length)throw new Error("Cannot train product quantizer with empty vector set");this.dimension=e[0].length,this.subvectorSize=Math.ceil(this.dimension/this.numSubvectors);for(let t=0;t<this.numSubvectors;t++){const n=e.map(e=>{const n=t*this.subvectorSize,r=Math.min(n+this.subvectorSize,this.dimension);return e.slice(n,r)});this.centroids[t]=this.kMeansPlusPlus(n,this.numCentroids)}this.initialized=!0}quantize(e){if(!this.initialized)throw new Error("Product quantizer not initialized. Call train() first.");if(e.length!==this.dimension)throw new Error(`Vector dimension mismatch: expected ${this.dimension}, got ${e.length}`);const t=[];for(let n=0;n<this.numSubvectors;n++){const r=n*this.subvectorSize,a=Math.min(r+this.subvectorSize,this.dimension),s=e.slice(r,a);let o=Number.MAX_VALUE,i=0;for(let e=0;e<this.centroids[n].length;e++){const t=this.centroids[n][e],r=this.euclideanDistanceSquared(s,t);r<o&&(o=r,i=e)}t.push(i)}return t}reconstruct(e){if(!this.initialized)throw new Error("Product quantizer not initialized. Call train() first.");if(e.length!==this.numSubvectors)throw new Error(`Code length mismatch: expected ${this.numSubvectors}, got ${e.length}`);const t=[];for(let n=0;n<this.numSubvectors;n++){const r=e[n],a=this.centroids[n][r];for(const e of a)t.push(e)}return t.slice(0,this.dimension)}euclideanDistanceSquared(e,t){let n=0;const r=Math.min(e.length,t.length);for(let a=0;a<r;a++){const r=e[a]-t[a];n+=r*r}return n}kMeansPlusPlus(e,t){if(e.length<t)return[...e];const n=[],r=Math.floor(Math.random()*e.length);n.push([...e[r]]);for(let r=1;r<t;r++){const t=e.map(e=>{let t=Number.MAX_VALUE;for(const r of n){const n=this.euclideanDistanceSquared(e,r);t=Math.min(t,n)}return t}),r=t.reduce((e,t)=>e+t,0);let a=Math.random()*r,s=0;for(let e=0;e<t.length;e++)if(a-=t[e],a<=0){s=e;break}n.push([...e[s]])}return n}getCentroids(){return this.centroids}setCentroids(e){this.centroids=e,this.numSubvectors=e.length,this.numCentroids=e[0].length,this.initialized=!0}getDimension(){return this.dimension}setDimension(e){this.dimension=e,this.subvectorSize=Math.ceil(e/this.numSubvectors)}}class le extends oe{constructor(e={},t,n=null){super(e,t),this.productQuantizer=null,this.storage=null,this.useDiskBasedIndex=!1,this.useProductQuantization=!1,this.quantizedVectors=new Map,this.memoryUsage=0,this.vectorCount=0,this.memoryUpdateLock=Promise.resolve(),this.optimizedConfig={...ie,...e},this.storage=n,this.optimizedConfig.productQuantization?.enabled&&(this.useProductQuantization=!0,this.productQuantizer=new ce(this.optimizedConfig.productQuantization.numSubvectors,this.optimizedConfig.productQuantization.numCentroids)),this.useDiskBasedIndex=this.optimizedConfig.useDiskBasedIndex||!1}async updateMemoryUsage(e,t){this.memoryUpdateLock=this.memoryUpdateLock.then(async()=>{this.memoryUsage=Math.max(0,this.memoryUsage+e),this.vectorCount=Math.max(0,this.vectorCount+t)}),await this.memoryUpdateLock}async getMemoryUsageAsync(){return await this.memoryUpdateLock,{memoryUsage:this.memoryUsage,vectorCount:this.vectorCount}}async addItem(e){if(!e)throw new Error("Item is undefined or null");const{id:t,vector:n}=e;if(!n)throw new Error("Vector is undefined or null");const r=8*n.length+this.optimizedConfig.M*this.optimizedConfig.ml*16;await this.updateMemoryUsage(r,1);const a=await this.getMemoryUsageAsync();if(this.useProductQuantization&&a.memoryUsage>this.optimizedConfig.memoryThreshold&&this.productQuantizer&&!this.productQuantizer.getDimension()&&this.initializeProductQuantizer(),this.useProductQuantization&&this.productQuantizer&&this.productQuantizer.getDimension()>0){const e=this.productQuantizer.quantize(n);this.quantizedVectors.set(t,e);const r=this.productQuantizer.reconstruct(e);return await super.addItem({id:t,vector:r})}if(this.useDiskBasedIndex&&this.storage){const e={id:t,vector:n,connections:new Map};this.storage.saveNoun(e).catch(e=>{console.error(`Failed to save noun ${t} to storage:`,e)})}return await super.addItem(e)}async search(e,t=10){if(!e)throw new Error("Query vector is undefined or null");if(this.useProductQuantization&&this.productQuantizer&&this.productQuantizer.getDimension()>0){const n=this.productQuantizer.quantize(e),r=this.productQuantizer.reconstruct(n);return await super.search(r,t)}return await super.search(e,t)}removeItem(e){return this.useProductQuantization&&this.quantizedVectors.delete(e),this.useDiskBasedIndex&&this.storage&&this.storage.deleteNoun(e).catch(t=>{console.error(`Failed to delete noun ${e} from storage:`,t)}),this.getMemoryUsageAsync().then(e=>{if(e.vectorCount>0){const t=e.memoryUsage/e.vectorCount;this.updateMemoryUsage(-t,-1)}}).catch(e=>{console.error("Failed to update memory usage after removal:",e)}),super.removeItem(e)}async clear(){this.useProductQuantization&&(this.quantizedVectors.clear(),this.productQuantizer=new ce(this.optimizedConfig.productQuantization.numSubvectors,this.optimizedConfig.productQuantization.numCentroids));const e=await this.getMemoryUsageAsync();await this.updateMemoryUsage(-e.memoryUsage,-e.vectorCount),super.clear()}initializeProductQuantizer(){if(!this.productQuantizer)return;const e=super.getNouns(),t=[];for(const[n,r]of e)t.push(r.vector);if(t.length>0){this.productQuantizer.train(t);for(const[t,n]of e){const e=this.productQuantizer.quantize(n.vector);this.quantizedVectors.set(t,e)}console.log(`Initialized product quantizer with ${t.length} vectors`)}}getProductQuantizer(){return this.productQuantizer}getOptimizedConfig(){return{...this.optimizedConfig}}getMemoryUsage(){return this.memoryUsage}setStorage(e){this.storage=e}getStorage(){return this.storage}setUseDiskBasedIndex(e){this.useDiskBasedIndex=e}getUseDiskBasedIndex(){return this.useDiskBasedIndex}setUseProductQuantization(e){this.useProductQuantization=e}getUseProductQuantization(){return this.useProductQuantization}}class ue{constructor(){this.statisticsCache=null,this.statisticsBatchUpdateTimerId=null,this.statisticsModified=!1,this.lastStatisticsFlushTime=0,this.MIN_FLUSH_INTERVAL_MS=5e3,this.MAX_FLUSH_DELAY_MS=3e4}async saveStatistics(e){this.statisticsCache={nounCount:{...e.nounCount},verbCount:{...e.verbCount},metadataCount:{...e.metadataCount},hnswIndexSize:e.hnswIndexSize,lastUpdated:e.lastUpdated},this.scheduleBatchUpdate()}async getStatistics(){if(this.statisticsCache)return{nounCount:{...this.statisticsCache.nounCount},verbCount:{...this.statisticsCache.verbCount},metadataCount:{...this.statisticsCache.metadataCount},hnswIndexSize:this.statisticsCache.hnswIndexSize,lastUpdated:this.statisticsCache.lastUpdated};const e=await this.getStatisticsData();return e&&(this.statisticsCache={nounCount:{...e.nounCount},verbCount:{...e.verbCount},metadataCount:{...e.metadataCount},hnswIndexSize:e.hnswIndexSize,lastUpdated:e.lastUpdated}),e}scheduleBatchUpdate(){if(this.statisticsModified=!0,null!==this.statisticsBatchUpdateTimerId)return;const e=Date.now()-this.lastStatisticsFlushTime<this.MIN_FLUSH_INTERVAL_MS?this.MAX_FLUSH_DELAY_MS:this.MIN_FLUSH_INTERVAL_MS;this.statisticsBatchUpdateTimerId=setTimeout(()=>{this.flushStatistics()},e)}async flushStatistics(){if(null!==this.statisticsBatchUpdateTimerId&&(clearTimeout(this.statisticsBatchUpdateTimerId),this.statisticsBatchUpdateTimerId=null),this.statisticsModified&&this.statisticsCache)try{await this.saveStatisticsData(this.statisticsCache),this.lastStatisticsFlushTime=Date.now(),this.statisticsModified=!1}catch(e){console.error("Failed to flush statistics data:",e),this.statisticsModified=!0}}async incrementStatistic(e,t,n=1){let r=this.statisticsCache;r||(r=await this.getStatisticsData(),r||(r=this.createDefaultStatistics()),this.statisticsCache={nounCount:{...r.nounCount},verbCount:{...r.verbCount},metadataCount:{...r.metadataCount},hnswIndexSize:r.hnswIndexSize,lastUpdated:r.lastUpdated});const a={noun:this.statisticsCache.nounCount,verb:this.statisticsCache.verbCount,metadata:this.statisticsCache.metadataCount}[e];a[t]=(a[t]||0)+n,this.statisticsCache.lastUpdated=(new Date).toISOString(),this.scheduleBatchUpdate()}async decrementStatistic(e,t,n=1){let r=this.statisticsCache;r||(r=await this.getStatisticsData(),r||(r=this.createDefaultStatistics()),this.statisticsCache={nounCount:{...r.nounCount},verbCount:{...r.verbCount},metadataCount:{...r.metadataCount},hnswIndexSize:r.hnswIndexSize,lastUpdated:r.lastUpdated});const a={noun:this.statisticsCache.nounCount,verb:this.statisticsCache.verbCount,metadata:this.statisticsCache.metadataCount}[e];a[t]=Math.max(0,(a[t]||0)-n),this.statisticsCache.lastUpdated=(new Date).toISOString(),this.scheduleBatchUpdate()}async updateHnswIndexSize(e){let t=this.statisticsCache;t||(t=await this.getStatisticsData(),t||(t=this.createDefaultStatistics()),this.statisticsCache={nounCount:{...t.nounCount},verbCount:{...t.verbCount},metadataCount:{...t.metadataCount},hnswIndexSize:t.hnswIndexSize,lastUpdated:t.lastUpdated}),this.statisticsCache.hnswIndexSize=e,this.statisticsCache.lastUpdated=(new Date).toISOString(),this.scheduleBatchUpdate()}async flushStatisticsToStorage(){this.statisticsCache&&this.statisticsModified&&await this.flushStatistics()}createDefaultStatistics(){return{nounCount:{},verbCount:{},metadataCount:{},hnswIndexSize:0,lastUpdated:(new Date).toISOString()}}}const de="nouns",he="verbs",pe="metadata",fe="index",me="statistics";class ge extends ue{constructor(){super(...arguments),this.isInitialized=!1}async ensureInitialized(){this.isInitialized||await this.init()}async saveNoun(e){return await this.ensureInitialized(),this.saveNoun_internal(e)}async getNoun(e){return await this.ensureInitialized(),this.getNoun_internal(e)}async getAllNouns(){return await this.ensureInitialized(),this.getAllNouns_internal()}async getNounsByNounType(e){return await this.ensureInitialized(),this.getNounsByNounType_internal(e)}async deleteNoun(e){return await this.ensureInitialized(),this.deleteNoun_internal(e)}async saveVerb(e){return await this.ensureInitialized(),this.saveVerb_internal(e)}async getVerb(e){return await this.ensureInitialized(),this.getVerb_internal(e)}async getAllVerbs(){return await this.ensureInitialized(),this.getAllVerbs_internal()}async getVerbsBySource(e){return await this.ensureInitialized(),this.getVerbsBySource_internal(e)}async getVerbsByTarget(e){return await this.ensureInitialized(),this.getVerbsByTarget_internal(e)}async getVerbsByType(e){return await this.ensureInitialized(),this.getVerbsByType_internal(e)}async getNouns(e){await this.ensureInitialized();const t=e?.pagination||{},n=t.limit||100,r=t.offset||0;if(e?.filter&&e.filter.nounType&&!e.filter.service&&!e.filter.metadata){const t=Array.isArray(e.filter.nounType)?e.filter.nounType[0]:e.filter.nounType,a=await this.getNounsByNounType_internal(t),s=a.slice(r,r+n),o=r+n<a.length;let i;if(o&&s.length>0){i=s[s.length-1].id}return{items:s,totalCount:a.length,hasMore:o,nextCursor:i}}const a=r+n+1;let s=[];try{s=await this.getAllNouns_internal(),s.length>10*a&&(console.warn(`Large number of nouns (${s.length}), truncating to ${10*a} for filtering`),s=s.slice(0,10*a))}catch(e){return console.error("Error getting all nouns:",e),{items:[],totalCount:0,hasMore:!1}}let o=s;if(e?.filter){if(e.filter.nounType){const t=Array.isArray(e.filter.nounType)?e.filter.nounType:[e.filter.nounType];o=o.filter(e=>{const n=e.metadata?.type;return"string"==typeof n&&t.includes(n)})}if(e.filter.service){const t=Array.isArray(e.filter.service)?e.filter.service:[e.filter.service];o=o.filter(e=>{const n=e.metadata?.service;return"string"==typeof n&&t.includes(n)})}if(e.filter.metadata){const t=e.filter.metadata;o=o.filter(e=>!!e.metadata&&Object.entries(t).every(([t,n])=>e.metadata&&e.metadata[t]===n))}}const i=o.length,c=o.slice(r,r+n),l=r+n<i;let u;if(l&&c.length>0){u=c[c.length-1].id}return{items:c,totalCount:i,hasMore:l,nextCursor:u}}async getVerbs(e){await this.ensureInitialized();const t=e?.pagination||{},n=t.limit||100,r=t.offset||0;if(e?.filter){if(e.filter.sourceId&&!e.filter.verbType&&!e.filter.targetId&&!e.filter.service&&!e.filter.metadata){const t=Array.isArray(e.filter.sourceId)?e.filter.sourceId[0]:e.filter.sourceId,a=await this.getVerbsBySource_internal(t),s=a.slice(r,r+n),o=r+n<a.length;let i;if(o&&s.length>0){i=s[s.length-1].id}return{items:s,totalCount:a.length,hasMore:o,nextCursor:i}}if(e.filter.targetId&&!e.filter.verbType&&!e.filter.sourceId&&!e.filter.service&&!e.filter.metadata){const t=Array.isArray(e.filter.targetId)?e.filter.targetId[0]:e.filter.targetId,a=await this.getVerbsByTarget_internal(t),s=a.slice(r,r+n),o=r+n<a.length;let i;if(o&&s.length>0){i=s[s.length-1].id}return{items:s,totalCount:a.length,hasMore:o,nextCursor:i}}if(e.filter.verbType&&!e.filter.sourceId&&!e.filter.targetId&&!e.filter.service&&!e.filter.metadata){const t=Array.isArray(e.filter.verbType)?e.filter.verbType[0]:e.filter.verbType,a=await this.getVerbsByType_internal(t),s=a.slice(r,r+n),o=r+n<a.length;let i;if(o&&s.length>0){i=s[s.length-1].id}return{items:s,totalCount:a.length,hasMore:o,nextCursor:i}}}const a=r+n+1;let s=[];try{s=await this.getAllVerbs_internal(),s.length>10*a&&(console.warn(`Large number of verbs (${s.length}), truncating to ${10*a} for filtering`),s=s.slice(0,10*a))}catch(e){return console.error("Error getting all verbs:",e),{items:[],totalCount:0,hasMore:!1}}let o=s;if(e?.filter){if(e.filter.verbType){const t=Array.isArray(e.filter.verbType)?e.filter.verbType:[e.filter.verbType];o=o.filter(e=>void 0!==e.type&&t.includes(e.type))}if(e.filter.sourceId){const t=Array.isArray(e.filter.sourceId)?e.filter.sourceId:[e.filter.sourceId];o=o.filter(e=>void 0!==e.sourceId&&t.includes(e.sourceId))}if(e.filter.targetId){const t=Array.isArray(e.filter.targetId)?e.filter.targetId:[e.filter.targetId];o=o.filter(e=>void 0!==e.targetId&&t.includes(e.targetId))}if(e.filter.service){const t=Array.isArray(e.filter.service)?e.filter.service:[e.filter.service];o=o.filter(e=>{const n=e.metadata?.service;return"string"==typeof n&&t.includes(n)})}if(e.filter.metadata){const t=e.filter.metadata;o=o.filter(e=>!!e.metadata&&Object.entries(t).every(([t,n])=>e.metadata&&e.metadata[t]===n))}}const i=o.length,c=o.slice(r,r+n),l=r+n<i;let u;if(l&&c.length>0){u=c[c.length-1].id}return{items:c,totalCount:i,hasMore:l,nextCursor:u}}async deleteVerb(e){return await this.ensureInitialized(),this.deleteVerb_internal(e)}mapToObject(e,t=e=>e){const n={};for(const[r,a]of e.entries())n[r.toString()]=t(a);return n}}class ye extends ge{constructor(){super(),this.nouns=new Map,this.verbs=new Map,this.metadata=new Map,this.statistics=null}async init(){this.isInitialized=!0}async saveNoun_internal(e){const t={id:e.id,vector:[...e.vector],connections:new Map};for(const[n,r]of e.connections.entries())t.connections.set(n,new Set(r));this.nouns.set(e.id,t)}async getNoun_internal(e){const t=this.nouns.get(e);if(!t)return null;const n={id:t.id,vector:[...t.vector],connections:new Map};for(const[e,r]of t.connections.entries())n.connections.set(e,new Set(r));return n}async getAllNouns_internal(){const e=[];for(const[t,n]of this.nouns.entries()){const t={id:n.id,vector:[...n.vector],connections:new Map};for(const[e,r]of n.connections.entries())t.connections.set(e,new Set(r));e.push(t)}return e}async getNouns(e={}){const t=e.pagination||{},n=e.filter||{},r=t.offset||0,a=t.limit||100,s=n.nounType?Array.isArray(n.nounType)?n.nounType:[n.nounType]:void 0,o=n.service?Array.isArray(n.service)?n.service:[n.service]:void 0,i=[];for(const[e,t]of this.nouns.entries()){const t=await this.getMetadata(e);if(t&&((!s||s.includes(t.noun))&&(!o||!t.service||o.includes(t.service)))){if(n.metadata){let e=!0;for(const[r,a]of Object.entries(n.metadata))if(t[r]!==a){e=!1;break}if(!e)continue}i.push(e)}}const c=i.length,l=i.slice(r,r+a),u=r+a<c,d=u?`${r+a}`:void 0,h=[];for(const e of l){const t=this.nouns.get(e);if(!t)continue;const n={id:t.id,vector:[...t.vector],connections:new Map};for(const[e,r]of t.connections.entries())n.connections.set(e,new Set(r));h.push(n)}return{items:h,totalCount:c,hasMore:u,nextCursor:d}}async getNounsByNounType_internal(e){return(await this.getNouns({filter:{nounType:e}})).items}async deleteNoun_internal(e){this.nouns.delete(e)}async saveVerb_internal(e){const t={id:e.id,vector:[...e.vector],connections:new Map,sourceId:e.sourceId,targetId:e.targetId,source:e.sourceId||e.source,target:e.targetId||e.target,verb:e.type||e.verb,type:e.type||e.verb,weight:e.weight,metadata:e.metadata};for(const[n,r]of e.connections.entries())t.connections.set(n,new Set(r));this.verbs.set(e.id,t)}async getVerb_internal(e){const t=this.verbs.get(e);if(!t)return null;const n={seconds:Math.floor(Date.now()/1e3),nanoseconds:Date.now()%1e3*1e6},r={id:t.id,vector:[...t.vector],connections:new Map,sourceId:t.sourceId||t.source||"",targetId:t.targetId||t.target||"",source:t.sourceId||t.source||"",target:t.targetId||t.target||"",verb:t.type||t.verb,type:t.type||t.verb,weight:t.weight,metadata:t.metadata,createdAt:t.createdAt||n,updatedAt:t.updatedAt||n,createdBy:t.createdBy||{augmentation:"unknown",version:"1.0"}};for(const[e,n]of t.connections.entries())r.connections.set(e,new Set(n));return r}async getAllVerbs_internal(){const e=[];for(const[t,n]of this.verbs.entries()){const t={seconds:Math.floor(Date.now()/1e3),nanoseconds:Date.now()%1e3*1e6},r={augmentation:"unknown",version:"1.0"},a={id:n.id,vector:[...n.vector],connections:new Map,sourceId:n.sourceId||n.source||"",targetId:n.targetId||n.target||"",source:n.sourceId||n.source||"",target:n.targetId||n.target||"",verb:n.type||n.verb,weight:n.weight,metadata:n.metadata,createdAt:n.createdAt||t,updatedAt:n.updatedAt||t,createdBy:n.createdBy||r};for(const[e,t]of n.connections.entries())a.connections.set(e,new Set(t));e.push(a)}return e}async getVerbs(e={}){const t=e.pagination||{},n=e.filter||{},r=t.offset||0,a=t.limit||100,s=n.verbType?Array.isArray(n.verbType)?n.verbType:[n.verbType]:void 0,o=n.sourceId?Array.isArray(n.sourceId)?n.sourceId:[n.sourceId]:void 0,i=n.targetId?Array.isArray(n.targetId)?n.targetId:[n.targetId]:void 0,c=n.service?Array.isArray(n.service)?n.service:[n.service]:void 0,l=[];for(const[e,t]of this.verbs.entries())if((!s||s.includes(t.type||t.verb||""))&&(!o||o.includes(t.sourceId||t.source||""))&&(!i||i.includes(t.targetId||t.target||""))){if(n.metadata&&t.metadata){let e=!0;for(const[r,a]of Object.entries(n.metadata))if(t.metadata[r]!==a){e=!1;break}if(!e)continue}c&&t.metadata&&t.metadata.service&&!c.includes(t.metadata.service)||l.push(e)}const u=l.length,d=l.slice(r,r+a),h=r+a<u,p=h?`${r+a}`:void 0,f=[];for(const e of d){const t=this.verbs.get(e);if(!t)continue;const n={id:t.id,vector:[...t.vector],connections:new Map,sourceId:t.sourceId||t.source||"",targetId:t.targetId||t.target||"",source:t.sourceId||t.source||"",target:t.targetId||t.target||"",verb:t.type||t.verb,type:t.type||t.verb,weight:t.weight,metadata:t.metadata?JSON.parse(JSON.stringify(t.metadata)):void 0,createdAt:t.createdAt?{...t.createdAt}:void 0,updatedAt:t.updatedAt?{...t.updatedAt}:void 0,createdBy:t.createdBy?{...t.createdBy}:void 0};for(const[e,r]of t.connections.entries())n.connections.set(e,new Set(r));f.push(n)}return{items:f,totalCount:u,hasMore:h,nextCursor:p}}async getVerbsBySource_internal(e){return(await this.getVerbs({filter:{sourceId:e}})).items}async getVerbsByTarget_internal(e){return(await this.getVerbs({filter:{targetId:e}})).items}async getVerbsByType_internal(e){return(await this.getVerbs({filter:{verbType:e}})).items}async deleteVerb_internal(e){this.verbs.delete(e)}async saveMetadata(e,t){this.metadata.set(e,JSON.parse(JSON.stringify(t)))}async getMetadata(e){const t=this.metadata.get(e);return t?JSON.parse(JSON.stringify(t)):null}async clear(){this.nouns.clear(),this.verbs.clear(),this.metadata.clear(),this.statistics=null}async getStorageStatus(){return{type:"memory",used:0,quota:null,details:{nodeCount:this.nouns.size,edgeCount:this.verbs.size,metadataCount:this.metadata.size}}}async saveStatisticsData(e){this.statistics={nounCount:{...e.nounCount},verbCount:{...e.verbCount},metadataCount:{...e.metadataCount},hnswIndexSize:e.hnswIndexSize,lastUpdated:e.lastUpdated}}async getStatisticsData(){return this.statistics?{nounCount:{...this.statistics.nounCount},verbCount:{...this.statistics.verbCount},metadataCount:{...this.statistics.metadataCount},hnswIndexSize:this.statistics.hnswIndexSize,lastUpdated:this.statistics.lastUpdated}:null}}async function be(e){return e.getFile()}class xe extends ge{constructor(){super(),this.rootDir=null,this.nounsDir=null,this.verbsDir=null,this.metadataDir=null,this.indexDir=null,this.isAvailable=!1,this.isPersistentRequested=!1,this.isPersistentGranted=!1,this.statistics=null,this.activeLocks=new Set,this.lockPrefix="opfs-lock-",this.isAvailable="undefined"!=typeof navigator&&"storage"in navigator&&"getDirectory"in navigator.storage}async init(){if(!this.isInitialized){if(!this.isAvailable)throw new Error("Origin Private File System is not available in this environment");try{const e=await navigator.storage.getDirectory();this.rootDir=await e.getDirectoryHandle("opfs-vector-db",{create:!0}),this.nounsDir=await this.rootDir.getDirectoryHandle(de,{create:!0}),this.verbsDir=await this.rootDir.getDirectoryHandle(he,{create:!0}),this.metadataDir=await this.rootDir.getDirectoryHandle(pe,{create:!0}),this.indexDir=await this.rootDir.getDirectoryHandle(fe,{create:!0}),this.isInitialized=!0}catch(e){throw console.error("Failed to initialize OPFS storage:",e),new Error(`Failed to initialize OPFS storage: ${e}`)}}}isOPFSAvailable(){return this.isAvailable}async requestPersistentStorage(){if(!this.isAvailable)return console.warn("Cannot request persistent storage: OPFS is not available"),!1;try{return this.isPersistentGranted=await navigator.storage.persisted(),this.isPersistentGranted||(this.isPersistentGranted=await navigator.storage.persist()),this.isPersistentRequested=!0,this.isPersistentGranted}catch(e){return console.warn("Failed to request persistent storage:",e),!1}}async isPersistent(){if(!this.isAvailable)return!1;try{return this.isPersistentGranted=await navigator.storage.persisted(),this.isPersistentGranted}catch(e){return console.warn("Failed to check persistent storage status:",e),!1}}async saveNoun_internal(e){await this.ensureInitialized();try{const t={...e,connections:this.mapToObject(e.connections,e=>Array.from(e))},n=await this.nounsDir.getFileHandle(e.id,{create:!0}),r=await n.createWritable();await r.write(JSON.stringify(t)),await r.close()}catch(t){throw console.error(`Failed to save noun ${e.id}:`,t),new Error(`Failed to save noun ${e.id}: ${t}`)}}async getNoun_internal(e){await this.ensureInitialized();try{const t=await this.nounsDir.getFileHandle(e),n=await t.getFile(),r=await n.text(),a=JSON.parse(r),s=new Map;for(const[e,t]of Object.entries(a.connections))s.set(Number(e),new Set(t));return{id:a.id,vector:a.vector,connections:s}}catch(e){return null}}async getAllNouns_internal(){await this.ensureInitialized();const e=[];try{for await(const[t,n]of this.nounsDir.entries())if("file"===n.kind)try{const t=await be(n),r=await t.text(),a=JSON.parse(r),s=new Map;for(const[e,t]of Object.entries(a.connections))s.set(Number(e),new Set(t));e.push({id:a.id,vector:a.vector,connections:s})}catch(e){console.error(`Error reading noun file ${t}:`,e)}}catch(e){console.error("Error reading nouns directory:",e)}return e}async getNounsByNounType_internal(e){return this.getNodesByNounType(e)}async getNodesByNounType(e){await this.ensureInitialized();const t=[];try{for await(const[n,r]of this.nounsDir.entries())if("file"===r.kind)try{const n=await be(r),a=await n.text(),s=JSON.parse(a),o=await this.getMetadata(s.id);if(o&&o.noun===e){const e=new Map;for(const[t,n]of Object.entries(s.connections))e.set(Number(t),new Set(n));t.push({id:s.id,vector:s.vector,connections:e})}}catch(e){console.error(`Error reading node file ${n}:`,e)}}catch(e){console.error("Error reading nouns directory:",e)}return t}async deleteNoun_internal(e){return this.deleteNode(e)}async deleteNode(e){await this.ensureInitialized();try{await this.nounsDir.removeEntry(e)}catch(t){if("NotFoundError"!==t.name)throw console.error(`Error deleting node ${e}:`,t),t}}async saveVerb_internal(e){return this.saveEdge(e)}async saveEdge(e){await this.ensureInitialized();try{const t={...e,connections:this.mapToObject(e.connections,e=>Array.from(e))},n=await this.verbsDir.getFileHandle(e.id,{create:!0}),r=await n.createWritable();await r.write(JSON.stringify(t)),await r.close()}catch(t){throw console.error(`Failed to save edge ${e.id}:`,t),new Error(`Failed to save edge ${e.id}: ${t}`)}}async getVerb_internal(e){return this.getEdge(e)}async getEdge(e){await this.ensureInitialized();try{const t=await this.verbsDir.getFileHandle(e),n=await t.getFile(),r=await n.text(),a=JSON.parse(r),s=new Map;for(const[e,t]of Object.entries(a.connections))s.set(Number(e),new Set(t));const o={seconds:Math.floor(Date.now()/1e3),nanoseconds:Date.now()%1e3*1e6},i={augmentation:"unknown",version:"1.0"};return{id:a.id,vector:a.vector,connections:s,sourceId:a.sourceId||a.source,targetId:a.targetId||a.target,source:a.sourceId||a.source,target:a.targetId||a.target,verb:a.type||a.verb,weight:a.weight,metadata:a.metadata,createdAt:a.createdAt||o,updatedAt:a.updatedAt||o,createdBy:a.createdBy||i}}catch(e){return null}}async getAllVerbs_internal(){return this.getAllEdges()}async getAllEdges(){await this.ensureInitialized();const e=[];try{for await(const[t,n]of this.verbsDir.entries())if("file"===n.kind)try{const t=await be(n),r=await t.text(),a=JSON.parse(r),s=new Map;for(const[e,t]of Object.entries(a.connections))s.set(Number(e),new Set(t));const o={seconds:Math.floor(Date.now()/1e3),nanoseconds:Date.now()%1e3*1e6},i={augmentation:"unknown",version:"1.0"};e.push({id:a.id,vector:a.vector,connections:s,sourceId:a.sourceId||a.source,targetId:a.targetId||a.target,source:a.sourceId||a.source,target:a.targetId||a.target,verb:a.type||a.verb,weight:a.weight,metadata:a.metadata,createdAt:a.createdAt||o,updatedAt:a.updatedAt||o,createdBy:a.createdBy||i})}catch(e){console.error(`Error reading edge file ${t}:`,e)}}catch(e){console.error("Error reading verbs directory:",e)}return e}async getVerbsBySource_internal(e){return this.getEdgesBySource(e)}async getEdgesBySource(e){return(await this.getAllEdges()).filter(t=>(t.sourceId||t.source)===e)}async getVerbsByTarget_internal(e){return this.getEdgesByTarget(e)}async getEdgesByTarget(e){return(await this.getAllEdges()).filter(t=>(t.targetId||t.target)===e)}async getVerbsByType_internal(e){return this.getEdgesByType(e)}async getEdgesByType(e){return(await this.getAllEdges()).filter(t=>(t.type||t.verb)===e)}async deleteVerb_internal(e){return this.deleteEdge(e)}async deleteEdge(e){await this.ensureInitialized();try{await this.verbsDir.removeEntry(e)}catch(t){if("NotFoundError"!==t.name)throw console.error(`Error deleting edge ${e}:`,t),t}}async saveMetadata(e,t){await this.ensureInitialized();try{const n=await this.metadataDir.getFileHandle(e,{create:!0}),r=await n.createWritable();await r.write(JSON.stringify(t)),await r.close()}catch(t){throw console.error(`Failed to save metadata ${e}:`,t),new Error(`Failed to save metadata ${e}: ${t}`)}}async getMetadata(e){await this.ensureInitialized();try{const t=await this.metadataDir.getFileHandle(e),n=await t.getFile(),r=await n.text();return JSON.parse(r)}catch(e){return null}}async clear(){await this.ensureInitialized();const e=async e=>{try{for await(const[t,n]of e.entries())await e.removeEntry(t,{recursive:!0})}catch(e){throw console.error("Error removing directory contents:",e),e}};try{await e(this.nounsDir),await e(this.verbsDir),await e(this.metadataDir),await e(this.indexDir)}catch(e){throw console.error("Error clearing storage:",e),e}}async getStorageStatus(){await this.ensureInitialized();try{let e=0;const t=async e=>{let n=0;try{for await(const[r,a]of e.entries())if("file"===a.kind){n+=(await a.getFile()).size}else"directory"===a.kind&&(n+=await t(a))}catch(e){console.warn("Error calculating size for directory:",e)}return n},n=async e=>{let t=0;try{for await(const[n,r]of e.entries())"file"===r.kind&&t++}catch(e){console.warn("Error counting files in directory:",e)}return t};this.nounsDir&&(e+=await t(this.nounsDir)),this.verbsDir&&(e+=await t(this.verbsDir)),this.metadataDir&&(e+=await t(this.metadataDir)),this.indexDir&&(e+=await t(this.indexDir));let r=null,a={isPersistent:await this.isPersistent(),nounTypes:{}};try{if(navigator.storage&&navigator.storage.estimate){const e=await navigator.storage.estimate();r=e.quota||null,a={...a,usage:e.usage,quota:e.quota,freePercentage:e.quota?(e.quota-(e.usage||0))/e.quota*100:null}}}catch(e){console.warn("Unable to get storage estimate:",e)}this.nounsDir&&(a.nounsCount=await n(this.nounsDir)),this.verbsDir&&(a.verbsCount=await n(this.verbsDir)),this.metadataDir&&(a.metadataCount=await n(this.metadataDir));const s={};if(this.metadataDir)for await(const[e,t]of this.metadataDir.entries())if("file"===t.kind)try{const e=await be(t),n=await e.text(),r=JSON.parse(n);r.noun&&(s[r.noun]=(s[r.noun]||0)+1)}catch(t){console.error(`Error reading metadata file ${e}:`,t)}return a.nounTypes=s,{type:"opfs",used:e,quota:r,details:a}}catch(e){return console.error("Failed to get storage status:",e),{type:"opfs",used:0,quota:null,details:{error:String(e)}}}}getStatisticsKeyForDate(e){return`statistics_${e.getUTCFullYear()}${String(e.getUTCMonth()+1).padStart(2,"0")}${String(e.getUTCDate()).padStart(2,"0")}.json`}getCurrentStatisticsKey(){return this.getStatisticsKeyForDate(new Date)}getLegacyStatisticsKey(){return"statistics.json"}async acquireLock(e,t=3e4){if("undefined"==typeof localStorage)return console.warn("localStorage not available, proceeding without lock"),!1;const n=`${this.lockPrefix}${e}`,r=`${Date.now()}_${Math.random()}_${window.location.href}`,a=Date.now()+t;try{const s=localStorage.getItem(n);if(s)try{if(JSON.parse(s).expiresAt>Date.now())return!1}catch(e){console.warn(`Invalid lock data for ${n}:`,e)}const o={lockValue:r,expiresAt:a,tabId:window.location.href,timestamp:Date.now()};return localStorage.setItem(n,JSON.stringify(o)),this.activeLocks.add(e),setTimeout(()=>{this.releaseLock(e,r).catch(t=>{console.warn(`Failed to auto-release expired lock ${e}:`,t)})},t),!0}catch(t){return console.warn(`Failed to acquire lock ${e}:`,t),!1}}async releaseLock(e,t){if("undefined"==typeof localStorage)return;const n=`${this.lockPrefix}${e}`;try{if(t){const r=localStorage.getItem(n);if(r)try{if(JSON.parse(r).lockValue!==t)return}catch(t){return localStorage.removeItem(n),void this.activeLocks.delete(e)}}localStorage.removeItem(n),this.activeLocks.delete(e)}catch(t){console.warn(`Failed to release lock ${e}:`,t)}}async cleanupExpiredLocks(){if("undefined"!=typeof localStorage)try{const e=Date.now(),t=[];for(let n=0;n<localStorage.length;n++){const r=localStorage.key(n);if(r&&r.startsWith(this.lockPrefix))try{const n=localStorage.getItem(r);if(n){if(JSON.parse(n).expiresAt<=e){t.push(r);const e=r.replace(this.lockPrefix,"");this.activeLocks.delete(e)}}}catch(e){t.push(r)}}t.forEach(e=>{localStorage.removeItem(e)}),t.length>0&&console.log(`Cleaned up ${t.length} expired locks`)}catch(e){console.warn("Failed to cleanup expired locks:",e)}}async saveStatisticsData(e){const t="statistics",n=await this.acquireLock(t,1e4);n||console.warn("Failed to acquire lock for statistics update, proceeding without lock");try{const t=await this.getStatisticsData();let n;if(n=t?{nounCount:{...t.nounCount,...e.nounCount},verbCount:{...t.verbCount,...e.verbCount},metadataCount:{...t.metadataCount,...e.metadataCount},hnswIndexSize:Math.max(e.hnswIndexSize||0,t.hnswIndexSize||0),lastUpdated:(new Date).toISOString()}:{...e,lastUpdated:(new Date).toISOString()},this.statistics={nounCount:{...n.nounCount},verbCount:{...n.verbCount},metadataCount:{...n.metadataCount},hnswIndexSize:n.hnswIndexSize,lastUpdated:n.lastUpdated},await this.ensureInitialized(),!this.indexDir)throw new Error("Index directory not initialized");const r=this.getCurrentStatisticsKey(),a=await this.indexDir.getFileHandle(r,{create:!0}),s=await a.createWritable();if(await s.write(JSON.stringify(this.statistics,null,2)),await s.close(),Math.random()<.1){const e=this.getLegacyStatisticsKey(),t=await this.indexDir.getFileHandle(e,{create:!0}),n=await t.createWritable();await n.write(JSON.stringify(this.statistics,null,2)),await n.close()}}catch(e){throw console.error("Failed to save statistics data:",e),new Error(`Failed to save statistics data: ${e}`)}finally{n&&await this.releaseLock(t)}}async getStatisticsData(){if(this.statistics)return{nounCount:{...this.statistics.nounCount},verbCount:{...this.statistics.verbCount},metadataCount:{...this.statistics.metadataCount},hnswIndexSize:this.statistics.hnswIndexSize,lastUpdated:this.statistics.lastUpdated};try{if(await this.ensureInitialized(),!this.indexDir)throw new Error("Index directory not initialized");const e=this.getCurrentStatisticsKey();try{const t=await this.indexDir.getFileHandle(e,{create:!1}),n=await t.getFile(),r=await n.text();if(this.statistics=JSON.parse(r),this.statistics)return{nounCount:{...this.statistics.nounCount},verbCount:{...this.statistics.verbCount},metadataCount:{...this.statistics.metadataCount},hnswIndexSize:this.statistics.hnswIndexSize,lastUpdated:this.statistics.lastUpdated}}catch(e){const t=new Date;t.setDate(t.getDate()-1);const n=this.getStatisticsKeyForDate(t);try{const e=await this.indexDir.getFileHandle(n,{create:!1}),t=await e.getFile(),r=await t.text();if(this.statistics=JSON.parse(r),this.statistics)return{nounCount:{...this.statistics.nounCount},verbCount:{...this.statistics.verbCount},metadataCount:{...this.statistics.metadataCount},hnswIndexSize:this.statistics.hnswIndexSize,lastUpdated:this.statistics.lastUpdated}}catch(e){const t=this.getLegacyStatisticsKey();try{const e=await this.indexDir.getFileHandle(t,{create:!1}),n=await e.getFile(),r=await n.text();if(this.statistics=JSON.parse(r),this.statistics)return{nounCount:{...this.statistics.nounCount},verbCount:{...this.statistics.verbCount},metadataCount:{...this.statistics.metadataCount},hnswIndexSize:this.statistics.hnswIndexSize,lastUpdated:this.statistics.lastUpdated}}catch(e){return null}}}return this.statistics?this.statistics:null}catch(e){throw console.error("Failed to get statistics data:",e),new Error(`Failed to get statistics data: ${e}`)}}}class we extends Error{constructor(e,t,n=!1,r,a,s){super(e),this.name="BrainyError",this.type=t,this.retryable=n,this.originalError=r,this.attemptNumber=a,this.maxRetries=s,Error.captureStackTrace&&Error.captureStackTrace(this,we)}static timeout(e,t,n){return new we(`Operation '${e}' timed out after ${t}ms`,"TIMEOUT",!0,n)}static network(e,t){return new we(`Network error: ${e}`,"NETWORK",!0,t)}static storage(e,t){return new we(`Storage error: ${e}`,"STORAGE",!0,t)}static notFound(e){return new we(`Resource not found: ${e}`,"NOT_FOUND",!1)}static retryExhausted(e,t,n){return new we(`Operation '${e}' failed after ${t} retry attempts`,"RETRY_EXHAUSTED",!1,n,t,t)}static isRetryable(e){if(e instanceof we)return e.retryable;const t=e.message.toLowerCase(),n=e.name.toLowerCase();return!!(t.includes("timeout")||t.includes("network")||t.includes("connection")||t.includes("econnreset")||t.includes("enotfound")||t.includes("etimedout")||n.includes("timeout"))||!!(t.includes("throttling")||t.includes("rate limit")||t.includes("service unavailable")||t.includes("internal server error")||t.includes("bad gateway")||t.includes("gateway timeout"))}static fromError(e,t){if(e instanceof we)return e;const n=e.message.toLowerCase(),r=e.name.toLowerCase();return n.includes("timeout")||r.includes("timeout")?we.timeout(t||"unknown",0,e):n.includes("network")||n.includes("connection")||n.includes("econnreset")||n.includes("enotfound")||n.includes("etimedout")?we.network(e.message,e):n.includes("nosuchkey")||n.includes("not found")||n.includes("does not exist")?we.notFound(t||"resource"):we.storage(e.message,e)}}const ve={get:3e4,add:6e4,delete:3e4},ke={maxRetries:3,initialDelay:1e3,maxDelay:1e4,backoffMultiplier:2};function Ie(e,t,n,r){const a=t*Math.pow(r,e-1);return Math.min(a,n)}function Se(e){return new Promise(t=>setTimeout(t,e))}async function Te(e,t,n,r={}){return async function(e,t,n={}){const{maxRetries:r=ke.maxRetries,initialDelay:a=ke.initialDelay,maxDelay:s=ke.maxDelay,backoffMultiplier:o=ke.backoffMultiplier}=n;let i;for(let n=1;n<=r+1;n++)try{return await e()}catch(e){if(i=e instanceof Error?e:new Error(String(e)),n>r)break;if(!we.isRetryable(i))throw we.fromError(i,t);const c=Ie(n,a,s,o);console.warn(`Operation '${t}' failed on attempt ${n}/${r+1}. Retrying in ${c}ms. Error: ${i.message}`),await Se(c)}throw we.retryExhausted(t,r,i)}(()=>function(e,t,n){return new Promise((r,a)=>{const s=setTimeout(()=>{a(we.timeout(n,t))},t);e.then(e=>{clearTimeout(s),r(e)}).catch(e=>{clearTimeout(s),a(e)})})}(e(),n,t),t,r)}function Ne(e,t={}){const n={...ve,...t.timeouts},r={...ke,...t.retryPolicy},a=n[e];return async function(e,t){return Te(e,t,a,r)}}class Ce{constructor(e={}){this.getExecutor=Ne("get",e),this.addExecutor=Ne("add",e),this.deleteExecutor=Ne("delete",e)}async executeGet(e,t){return this.getExecutor(e,t)}async executeAdd(e,t){return this.addExecutor(e,t)}async executeDelete(e,t){return this.deleteExecutor(e,t)}}class Ee extends ge{constructor(e){super(),this.s3Client=null,this.statisticsCache=null,this.lockPrefix="locks/",this.activeLocks=new Set,this.changeLogPrefix="change-log/",this.statisticsBatchUpdateTimerId=null,this.statisticsModified=!1,this.lastStatisticsFlushTime=0,this.MIN_FLUSH_INTERVAL_MS=5e3,this.MAX_FLUSH_DELAY_MS=3e4,this.bucketName=e.bucketName,this.region=e.region||"auto",this.endpoint=e.endpoint,this.accountId=e.accountId,this.accessKeyId=e.accessKeyId,this.secretAccessKey=e.secretAccessKey,this.sessionToken=e.sessionToken,this.serviceType=e.serviceType||"s3",this.operationExecutors=new Ce(e.operationConfig),this.nounPrefix=`${de}/`,this.verbPrefix=`${he}/`,this.metadataPrefix=`${pe}/`,this.indexPrefix=`${fe}/`}async init(){if(!this.isInitialized)try{const{S3Client:e}=await import("@aws-sdk/client-s3"),t={region:this.region,credentials:{accessKeyId:this.accessKeyId,secretAccessKey:this.secretAccessKey}};this.sessionToken&&(t.credentials.sessionToken=this.sessionToken),this.endpoint&&(t.endpoint=this.endpoint),"r2"===this.serviceType&&this.accountId&&(t.endpoint=`https://${this.accountId}.r2.cloudflarestorage.com`),this.s3Client=new e(t);const{HeadBucketCommand:n}=await import("@aws-sdk/client-s3");await this.s3Client.send(new n({Bucket:this.bucketName})),this.isInitialized=!0}catch(e){throw console.error(`Failed to initialize ${this.serviceType} storage:`,e),new Error(`Failed to initialize ${this.serviceType} storage: ${e}`)}}async saveNoun_internal(e){return this.saveNode(e)}async saveNode(e){await this.ensureInitialized();try{console.log(`Saving node ${e.id} to bucket ${this.bucketName}`);const t={...e,connections:this.mapToObject(e.connections,e=>Array.from(e))},{PutObjectCommand:n}=await import("@aws-sdk/client-s3"),r=`${this.nounPrefix}${e.id}.json`,a=JSON.stringify(t,null,2);console.log(`Saving node to key: ${r}`),console.log(`Node data: ${a.substring(0,100)}${a.length>100?"...":""}`);const s=await this.s3Client.send(new n({Bucket:this.bucketName,Key:r,Body:a,ContentType:"application/json"}));console.log(`Node ${e.id} saved successfully:`,s),await this.appendToChangeLog({timestamp:Date.now(),operation:"add",entityType:"noun",entityId:e.id,data:{vector:e.vector,metadata:e.metadata}});const{GetObjectCommand:o}=await import("@aws-sdk/client-s3");try{const t=await this.s3Client.send(new o({Bucket:this.bucketName,Key:r}));t&&t.Body?console.log(`Verified node ${e.id} was saved correctly`):console.error(`Failed to verify node ${e.id} was saved correctly: no response or body`)}catch(t){console.error(`Failed to verify node ${e.id} was saved correctly:`,t)}}catch(t){throw console.error(`Failed to save node ${e.id}:`,t),new Error(`Failed to save node ${e.id}: ${t}`)}}async getNoun_internal(e){return this.getNode(e)}async getNode(e){await this.ensureInitialized();try{const{GetObjectCommand:t}=await import("@aws-sdk/client-s3");console.log(`Getting node ${e} from bucket ${this.bucketName}`);const n=`${this.nounPrefix}${e}.json`;console.log(`Looking for node at key: ${n}`);const r=await this.s3Client.send(new t({Bucket:this.bucketName,Key:n}));if(!r||!r.Body)return console.log(`No node found for ${e}`),null;const a=await r.Body.transformToString();console.log(`Retrieved node body: ${a.substring(0,100)}${a.length>100?"...":""}`);try{const t=JSON.parse(a);if(console.log(`Parsed node data for ${e}:`,t),!(t&&t.id&&t.vector&&t.connections))return console.error(`Invalid node data for ${e}:`,t),null;const n=new Map;for(const[e,r]of Object.entries(t.connections))n.set(Number(e),new Set(r));const r={id:t.id,vector:t.vector,connections:n};return console.log(`Successfully retrieved node ${e}:`,r),r}catch(t){return console.error(`Failed to parse node data for ${e}:`,t),null}}catch(t){return console.log(`Error getting node for ${e}:`,t),null}}async getAllNouns_internal(){return this.getAllNodes()}async getAllNodes(){await this.ensureInitialized();try{const{ListObjectsV2Command:e,GetObjectCommand:t}=await import("@aws-sdk/client-s3");console.log(`Getting all nodes from bucket ${this.bucketName} with prefix ${this.nounPrefix}`);const n=await this.s3Client.send(new e({Bucket:this.bucketName,Prefix:this.nounPrefix})),r=[];if(!n||!n.Contents||0===n.Contents.length)return console.log(`No nodes found in bucket ${this.bucketName} with prefix ${this.nounPrefix}`),r;console.log(`Found ${n.Contents.length} nodes in bucket ${this.bucketName}`),console.log("Keys found:");for(const e of n.Contents)e&&e.Key&&console.log(`- ${e.Key}`);const a=n.Contents.map(async e=>{if(!e||!e.Key)return console.log("Skipping undefined object or object without Key"),null;try{const n=e.Key.replace(this.nounPrefix,"").replace(".json","");console.log(`Getting node with ID ${n} from key ${e.Key}`);const r=await this.s3Client.send(new t({Bucket:this.bucketName,Key:e.Key}));if(!r||!r.Body)return console.log(`No response or response body for node ${n}`),null;const a=await r.Body.transformToString();console.log(`Retrieved node body for ${n}: ${a.substring(0,100)}${a.length>100?"...":""}`);try{const e=JSON.parse(a);if(console.log(`Parsed node data for ${n}:`,e),!(e&&e.id&&e.vector&&e.connections))return console.error(`Invalid node data for ${n}:`,e),null;const t=new Map;for(const[n,r]of Object.entries(e.connections))t.set(Number(n),new Set(r));const r={id:e.id,vector:e.vector,connections:t};return console.log(`Successfully retrieved node ${n}:`,r),r}catch(e){return console.error(`Failed to parse node data for ${n}:`,e),null}}catch(t){return console.error(`Error getting node from ${e.Key}:`,t),null}}),s=(await Promise.all(a)).filter(e=>null!==e);console.log(`Returning ${s.length} nodes`);for(const e of s)console.log(`- Node ${e.id}`);return s}catch(e){return console.error("Failed to get all nodes:",e),[]}}async getNounsByNounType_internal(e){return this.getNodesByNounType(e)}async getNodesByNounType(e){await this.ensureInitialized();try{const t=await this.getAllNodes(),n=[];for(const r of t){const t=await this.getMetadata(r.id);t&&t.noun===e&&n.push(r)}return n}catch(t){return console.error(`Failed to get nodes by noun type ${e}:`,t),[]}}async deleteNoun_internal(e){return this.deleteNode(e)}async deleteNode(e){await this.ensureInitialized();try{const{DeleteObjectCommand:t}=await import("@aws-sdk/client-s3");await this.s3Client.send(new t({Bucket:this.bucketName,Key:`${this.nounPrefix}${e}.json`})),await this.appendToChangeLog({timestamp:Date.now(),operation:"delete",entityType:"noun",entityId:e})}catch(t){throw console.error(`Failed to delete node ${e}:`,t),new Error(`Failed to delete node ${e}: ${t}`)}}async saveVerb_internal(e){return this.saveEdge(e)}async saveEdge(e){await this.ensureInitialized();try{const t={...e,connections:this.mapToObject(e.connections,e=>Array.from(e))},{PutObjectCommand:n}=await import("@aws-sdk/client-s3");await this.s3Client.send(new n({Bucket:this.bucketName,Key:`${this.verbPrefix}${e.id}.json`,Body:JSON.stringify(t,null,2),ContentType:"application/json"})),await this.appendToChangeLog({timestamp:Date.now(),operation:"add",entityType:"verb",entityId:e.id,data:{sourceId:e.sourceId||e.source,targetId:e.targetId||e.target,type:e.type||e.verb,vector:e.vector,metadata:e.metadata}})}catch(t){throw console.error(`Failed to save edge ${e.id}:`,t),new Error(`Failed to save edge ${e.id}: ${t}`)}}async getVerb_internal(e){return this.getEdge(e)}async getEdge(e){await this.ensureInitialized();try{const{GetObjectCommand:t}=await import("@aws-sdk/client-s3");console.log(`Getting edge ${e} from bucket ${this.bucketName}`);const n=`${this.verbPrefix}${e}.json`;console.log(`Looking for edge at key: ${n}`);const r=await this.s3Client.send(new t({Bucket:this.bucketName,Key:n}));if(!r||!r.Body)return console.log(`No edge found for ${e}`),null;const a=await r.Body.transformToString();console.log(`Retrieved edge body: ${a.substring(0,100)}${a.length>100?"...":""}`);try{const t=JSON.parse(a);if(console.log(`Parsed edge data for ${e}:`,t),!(t&&t.id&&t.vector&&t.connections&&(t.sourceId||t.source)&&(t.targetId||t.target)&&(t.type||t.verb)))return console.error(`Invalid edge data for ${e}:`,t),null;const n=new Map;for(const[e,r]of Object.entries(t.connections))n.set(Number(e),new Set(r));const r={seconds:Math.floor(Date.now()/1e3),nanoseconds:Date.now()%1e3*1e6},s={augmentation:"unknown",version:"1.0"},o={id:t.id,vector:t.vector,connections:n,sourceId:t.sourceId||t.source,targetId:t.targetId||t.target,source:t.sourceId||t.source,target:t.targetId||t.target,verb:t.type||t.verb,type:t.type||t.verb,weight:t.weight||1,metadata:t.metadata||{},createdAt:t.createdAt||r,updatedAt:t.updatedAt||r,createdBy:t.createdBy||s};return console.log(`Successfully retrieved edge ${e}:`,o),o}catch(t){return console.error(`Failed to parse edge data for ${e}:`,t),null}}catch(t){return console.log(`Error getting edge for ${e}:`,t),null}}async getAllVerbs_internal(){return this.getAllEdges()}async getAllEdges(){await this.ensureInitialized();try{const{ListObjectsV2Command:e,GetObjectCommand:t}=await import("@aws-sdk/client-s3"),n=await this.s3Client.send(new e({Bucket:this.bucketName,Prefix:this.verbPrefix})),r=[];if(!n.Contents||0===n.Contents.length)return r;const a=n.Contents.map(async e=>{try{e.Key.replace(this.verbPrefix,"").replace(".json","");const n=await this.s3Client.send(new t({Bucket:this.bucketName,Key:e.Key})),r=await n.Body.transformToString(),a=JSON.parse(r),s=new Map;for(const[e,t]of Object.entries(a.connections))s.set(Number(e),new Set(t));const o={seconds:Math.floor(Date.now()/1e3),nanoseconds:Date.now()%1e3*1e6},i={augmentation:"unknown",version:"1.0"};return{id:a.id,vector:a.vector,connections:s,sourceId:a.sourceId||a.source,targetId:a.targetId||a.target,source:a.sourceId||a.source,target:a.targetId||a.target,verb:a.type||a.verb,type:a.type||a.verb,weight:a.weight||1,metadata:a.metadata||{},createdAt:a.createdAt||o,updatedAt:a.updatedAt||o,createdBy:a.createdBy||i}}catch(t){return console.error(`Error getting edge from ${e.Key}:`,t),null}});return(await Promise.all(a)).filter(e=>null!==e)}catch(e){return console.error("Failed to get all edges:",e),[]}}async getVerbsBySource_internal(e){return this.getEdgesBySource(e)}async getEdgesBySource(e){return(await this.getAllEdges()).filter(t=>(t.sourceId||t.source)===e)}async getVerbsByTarget_internal(e){return this.getEdgesByTarget(e)}async getEdgesByTarget(e){return(await this.getAllEdges()).filter(t=>(t.targetId||t.target)===e)}async getVerbsByType_internal(e){return this.getEdgesByType(e)}async getEdgesByType(e){return(await this.getAllEdges()).filter(t=>(t.type||t.verb)===e)}async deleteVerb_internal(e){return this.deleteEdge(e)}async deleteEdge(e){await this.ensureInitialized();try{const{DeleteObjectCommand:t}=await import("@aws-sdk/client-s3");await this.s3Client.send(new t({Bucket:this.bucketName,Key:`${this.verbPrefix}${e}.json`})),await this.appendToChangeLog({timestamp:Date.now(),operation:"delete",entityType:"verb",entityId:e})}catch(t){throw console.error(`Failed to delete edge ${e}:`,t),new Error(`Failed to delete edge ${e}: ${t}`)}}async saveMetadata(e,t){await this.ensureInitialized();try{console.log(`Saving metadata for ${e} to bucket ${this.bucketName}`);const{PutObjectCommand:n}=await import("@aws-sdk/client-s3"),r=`${this.metadataPrefix}${e}.json`,a=JSON.stringify(t,null,2);console.log(`Saving metadata to key: ${r}`),console.log(`Metadata: ${a}`);const s=await this.s3Client.send(new n({Bucket:this.bucketName,Key:r,Body:a,ContentType:"application/json"}));console.log(`Metadata for ${e} saved successfully:`,s),await this.appendToChangeLog({timestamp:Date.now(),operation:"add",entityType:"metadata",entityId:e,data:t});const{GetObjectCommand:o}=await import("@aws-sdk/client-s3");try{const t=await this.s3Client.send(new o({Bucket:this.bucketName,Key:r}));if(t&&t.Body){const n=await t.Body.transformToString();console.log(`Verified metadata for ${e} was saved correctly: ${n}`)}else console.error(`Failed to verify metadata for ${e} was saved correctly: no response or body`)}catch(t){console.error(`Failed to verify metadata for ${e} was saved correctly:`,t)}}catch(t){throw console.error(`Failed to save metadata for ${e}:`,t),new Error(`Failed to save metadata for ${e}: ${t}`)}}async getMetadata(e){return await this.ensureInitialized(),this.operationExecutors.executeGet(async()=>{try{const{GetObjectCommand:t}=await import("@aws-sdk/client-s3");console.log(`Getting metadata for ${e} from bucket ${this.bucketName}`);const n=`${this.metadataPrefix}${e}.json`;console.log(`Looking for metadata at key: ${n}`);const r=await this.s3Client.send(new t({Bucket:this.bucketName,Key:n}));if(!r||!r.Body)return console.log(`No metadata found for ${e}`),null;const a=await r.Body.transformToString();console.log(`Retrieved metadata body: ${a}`);try{const t=JSON.parse(a);return console.log(`Successfully retrieved metadata for ${e}:`,t),t}catch(t){return console.error(`Failed to parse metadata for ${e}:`,t),null}}catch(t){if("NoSuchKey"===t.name||t.message&&(t.message.includes("NoSuchKey")||t.message.includes("not found")||t.message.includes("does not exist")))return console.log(`Metadata not found for ${e}`),null;throw we.fromError(t,`getMetadata(${e})`)}},`getMetadata(${e})`)}async clear(){await this.ensureInitialized();try{const{ListObjectsV2Command:e,DeleteObjectCommand:t}=await import("@aws-sdk/client-s3"),n=async n=>{const r=await this.s3Client.send(new e({Bucket:this.bucketName,Prefix:n}));if(r&&r.Contents&&0!==r.Contents.length)for(const e of r.Contents)e&&e.Key&&await this.s3Client.send(new t({Bucket:this.bucketName,Key:e.Key}))};await n(this.nounPrefix),await n(this.verbPrefix),await n(this.metadataPrefix),await n(this.indexPrefix)}catch(e){throw console.error("Failed to clear storage:",e),new Error(`Failed to clear storage: ${e}`)}}async getStorageStatus(){await this.ensureInitialized();try{const{ListObjectsV2Command:e}=await import("@aws-sdk/client-s3");let t=0,n=0,r=0,a=0;const s=async t=>{let n=0,r=0;const a=await this.s3Client.send(new e({Bucket:this.bucketName,Prefix:t}));if(!a||!a.Contents||0===a.Contents.length)return{size:n,count:r};for(const e of a.Contents)if(e){n+=("number"==typeof e.Size?e.Size:e.Size?parseInt(e.Size.toString(),10):0)||0,r++,0===n&&r>0&&(n=100*r)}return{size:n,count:r}},o=await s(this.nounPrefix),i=await s(this.verbPrefix),c=await s(this.metadataPrefix),l=await s(this.indexPrefix);t=o.size+i.size+c.size+l.size,n=o.count,r=i.count,a=c.count,0===t&&(n>0||r>0||a>0)&&(console.log(`Setting minimum size for ${n} nodes, ${r} edges, and ${a} metadata objects`),t=100*(n+r+a)),(n>0||r>0||a>0)&&(console.log(`Ensuring positive size for storage status with ${n} nodes, ${r} edges, and ${a} metadata objects`),t=Math.max(t,1));const u={},d=await this.s3Client.send(new e({Bucket:this.bucketName,Prefix:this.metadataPrefix}));if(d&&d.Contents){const{GetObjectCommand:e}=await import("@aws-sdk/client-s3");for(const t of d.Contents)if(t&&t.Key)try{const n=await this.s3Client.send(new e({Bucket:this.bucketName,Key:t.Key}));if(n&&n.Body){const e=await n.Body.transformToString();try{const t=JSON.parse(e);t&&t.noun&&(u[t.noun]=(u[t.noun]||0)+1)}catch(e){console.error(`Failed to parse metadata from ${t.Key}:`,e)}}}catch(e){console.error(`Error getting metadata from ${t.Key}:`,e)}}return{type:this.serviceType,used:t,quota:null,details:{bucketName:this.bucketName,region:this.region,endpoint:this.endpoint,nodeCount:n,edgeCount:r,metadataCount:a,nounTypes:u}}}catch(e){return console.error("Failed to get storage status:",e),{type:this.serviceType,used:0,quota:null,details:{error:String(e)}}}}getStatisticsKeyForDate(e){const t=e.getUTCFullYear(),n=String(e.getUTCMonth()+1).padStart(2,"0"),r=String(e.getUTCDate()).padStart(2,"0");return`${this.indexPrefix}${me}_${t}${n}${r}.json`}getCurrentStatisticsKey(){return this.getStatisticsKeyForDate(new Date)}getLegacyStatisticsKey(){return`${this.indexPrefix}${me}.json`}scheduleBatchUpdate(){if(this.statisticsModified=!0,null!==this.statisticsBatchUpdateTimerId)return;const e=Date.now()-this.lastStatisticsFlushTime<this.MIN_FLUSH_INTERVAL_MS?this.MAX_FLUSH_DELAY_MS:this.MIN_FLUSH_INTERVAL_MS;this.statisticsBatchUpdateTimerId=setTimeout(()=>{this.flushStatistics()},e)}async flushStatistics(){if(null!==this.statisticsBatchUpdateTimerId&&(clearTimeout(this.statisticsBatchUpdateTimerId),this.statisticsBatchUpdateTimerId=null),!this.statisticsModified||!this.statisticsCache)return;const e="statistics-flush",t=`${Date.now()}_${Math.random()}_${process.pid||"browser"}`;if(await this.acquireLock(e,15e3))try{if(!this.statisticsModified||!this.statisticsCache)return;const{PutObjectCommand:e,GetObjectCommand:t}=await import("@aws-sdk/client-s3"),n=this.getCurrentStatisticsKey();let r=null;try{r=await this.tryGetStatisticsFromKey(n)}catch(e){console.warn("Could not read current statistics from storage, using local cache:",e)}let a=this.statisticsCache;r&&(a=this.mergeStatistics(r,this.statisticsCache));const s=JSON.stringify(a,null,2);if(await this.s3Client.send(new e({Bucket:this.bucketName,Key:n,Body:s,ContentType:"application/json",Metadata:{"last-updated":Date.now().toString(),"updated-by":process.pid?.toString()||"browser"}})),this.lastStatisticsFlushTime=Date.now(),this.statisticsModified=!1,this.statisticsCache=a,Math.random()<.1){const t=this.getLegacyStatisticsKey();await this.s3Client.send(new e({Bucket:this.bucketName,Key:t,Body:s,ContentType:"application/json"}))}}catch(e){console.error("Failed to flush statistics data:",e),this.statisticsModified=!0}finally{await this.releaseLock(e,t)}else console.log("Statistics flush skipped - another instance is updating")}mergeStatistics(e,t){const n={...e.nounCount};for(const[e,r]of Object.entries(t.nounCount))n[e]=Math.max(n[e]||0,r);const r={...e.verbCount};for(const[e,n]of Object.entries(t.verbCount))r[e]=Math.max(r[e]||0,n);const a={...e.metadataCount};for(const[e,n]of Object.entries(t.metadataCount))a[e]=Math.max(a[e]||0,n);return{nounCount:n,verbCount:r,metadataCount:a,hnswIndexSize:Math.max(e.hnswIndexSize,t.hnswIndexSize),lastUpdated:new Date(Math.max(new Date(e.lastUpdated).getTime(),new Date(t.lastUpdated).getTime())).toISOString()}}async saveStatisticsData(e){await this.ensureInitialized();try{this.statisticsCache={nounCount:{...e.nounCount},verbCount:{...e.verbCount},metadataCount:{...e.metadataCount},hnswIndexSize:e.hnswIndexSize,lastUpdated:e.lastUpdated},this.scheduleBatchUpdate()}catch(e){throw console.error("Failed to save statistics data:",e),new Error(`Failed to save statistics data: ${e}`)}}async getStatisticsData(){if(await this.ensureInitialized(),this.statisticsCache)return{nounCount:{...this.statisticsCache.nounCount},verbCount:{...this.statisticsCache.verbCount},metadataCount:{...this.statisticsCache.metadataCount},hnswIndexSize:this.statisticsCache.hnswIndexSize,lastUpdated:this.statisticsCache.lastUpdated};try{const{GetObjectCommand:e}=await import("@aws-sdk/client-s3"),t=this.getCurrentStatisticsKey();let n=await this.tryGetStatisticsFromKey(t);if(!n){const e=new Date;e.setDate(e.getDate()-1);const t=this.getStatisticsKeyForDate(e);n=await this.tryGetStatisticsFromKey(t)}if(!n){const e=this.getLegacyStatisticsKey();n=await this.tryGetStatisticsFromKey(e)}return n&&(this.statisticsCache={nounCount:{...n.nounCount},verbCount:{...n.verbCount},metadataCount:{...n.metadataCount},hnswIndexSize:n.hnswIndexSize,lastUpdated:n.lastUpdated}),n}catch(e){throw console.error("Error getting statistics data:",e),e}}async tryGetStatisticsFromKey(e){try{const{GetObjectCommand:t}=await import("@aws-sdk/client-s3"),n=await this.s3Client.send(new t({Bucket:this.bucketName,Key:e}));if(!n||!n.Body)return null;const r=await n.Body.transformToString();return JSON.parse(r)}catch(e){if("NoSuchKey"===e.name||e.message&&(e.message.includes("NoSuchKey")||e.message.includes("not found")||e.message.includes("does not exist")))return null;throw e}}async appendToChangeLog(e){try{const{PutObjectCommand:t}=await import("@aws-sdk/client-s3"),n=`${this.changeLogPrefix}${e.timestamp}-${Math.random().toString(36).substr(2,9)}.json`,r={...e,instanceId:process.pid?.toString()||"browser"};await this.s3Client.send(new t({Bucket:this.bucketName,Key:n,Body:JSON.stringify(r),ContentType:"application/json",Metadata:{timestamp:e.timestamp.toString(),operation:e.operation,"entity-type":e.entityType,"entity-id":e.entityId}}))}catch(e){console.warn("Failed to append to change log:",e)}}async getChangesSince(e,t=1e3){await this.ensureInitialized();try{const{ListObjectsV2Command:n,GetObjectCommand:r}=await import("@aws-sdk/client-s3"),a=await this.s3Client.send(new n({Bucket:this.bucketName,Prefix:this.changeLogPrefix,MaxKeys:2*t}));if(!a.Contents)return[];const s=[];for(const n of a.Contents){if(!n.Key||s.length>=t)break;try{const t=await this.s3Client.send(new r({Bucket:this.bucketName,Key:n.Key}));if(t.Body){const n=await t.Body.transformToString(),r=JSON.parse(n);r.timestamp>e&&s.push(r)}}catch(e){console.warn(`Failed to read change log entry ${n.Key}:`,e)}}return s.sort((e,t)=>e.timestamp-t.timestamp),s.slice(0,t)}catch(e){return console.error("Failed to get changes from change log:",e),[]}}async cleanupOldChangeLogs(e){await this.ensureInitialized();try{const{ListObjectsV2Command:t,DeleteObjectCommand:n}=await import("@aws-sdk/client-s3"),r=await this.s3Client.send(new t({Bucket:this.bucketName,Prefix:this.changeLogPrefix,MaxKeys:1e3}));if(!r.Contents)return;const a=[];for(const t of r.Contents){if(!t.Key)continue;const n=t.Key.split("/");if(n.length>=2){const r=n[n.length-1].split("-")[0],s=parseInt(r);!isNaN(s)&&s<e&&a.push(t.Key)}}for(const e of a)try{await this.s3Client.send(new n({Bucket:this.bucketName,Key:e}))}catch(t){console.warn(`Failed to delete old change log entry ${e}:`,t)}a.length>0&&console.log(`Cleaned up ${a.length} old change log entries`)}catch(e){console.warn("Failed to cleanup old change logs:",e)}}async acquireLock(e,t=3e4){await this.ensureInitialized();const n=`${this.lockPrefix}${e}`,r=`${Date.now()}_${Math.random()}_${process.pid||"browser"}`,a=Date.now()+t;try{const{PutObjectCommand:s,HeadObjectCommand:o}=await import("@aws-sdk/client-s3");try{const e=await this.s3Client.send(new o({Bucket:this.bucketName,Key:n})),t=e.Metadata?.["expires-at"];if(t&&parseInt(t)>Date.now())return!1}catch(e){if("NoSuchKey"!==e.name&&!e.message?.includes("NoSuchKey")&&"NotFound"!==e.name&&!e.message?.includes("NotFound"))throw e}return await this.s3Client.send(new s({Bucket:this.bucketName,Key:n,Body:r,ContentType:"text/plain",Metadata:{"expires-at":a.toString(),"lock-value":r}})),this.activeLocks.add(e),setTimeout(()=>{this.releaseLock(e,r).catch(t=>{console.warn(`Failed to auto-release expired lock ${e}:`,t)})},t),!0}catch(t){return console.warn(`Failed to acquire lock ${e}:`,t),!1}}async releaseLock(e,t){await this.ensureInitialized();const n=`${this.lockPrefix}${e}`;try{const{DeleteObjectCommand:r,GetObjectCommand:a}=await import("@aws-sdk/client-s3");if(t)try{const e=await this.s3Client.send(new a({Bucket:this.bucketName,Key:n}));if(await(e.Body?.transformToString())!==t)return}catch(e){if("NoSuchKey"===e.name||e.message?.includes("NoSuchKey")||"NotFound"===e.name||e.message?.includes("NotFound"))return;throw e}await this.s3Client.send(new r({Bucket:this.bucketName,Key:n})),this.activeLocks.delete(e)}catch(t){console.warn(`Failed to release lock ${e}:`,t)}}async cleanupExpiredLocks(){await this.ensureInitialized();try{const{ListObjectsV2Command:e,DeleteObjectCommand:t,HeadObjectCommand:n}=await import("@aws-sdk/client-s3"),r=await this.s3Client.send(new e({Bucket:this.bucketName,Prefix:this.lockPrefix,MaxKeys:1e3}));if(!r.Contents)return;const a=Date.now(),s=[];for(const e of r.Contents)if(e.Key)try{const t=await this.s3Client.send(new n({Bucket:this.bucketName,Key:e.Key})),r=t.Metadata?.["expires-at"];r&&parseInt(r)<a&&s.push(e.Key)}catch(t){s.push(e.Key)}for(const e of s)try{await this.s3Client.send(new t({Bucket:this.bucketName,Key:e}))}catch(t){console.warn(`Failed to delete expired lock ${e}:`,t)}s.length>0&&console.log(`Cleaned up ${s.length} expired locks`)}catch(e){console.warn("Failed to cleanup expired locks:",e)}}}let $e,Ae;try{const e=import("fs"),t=import("path");Promise.all([e,t]).then(([e,t])=>{$e=e,Ae=t.default}).catch(e=>{console.error("Failed to load Node.js modules:",e)})}catch(e){console.error("FileSystemStorage: Failed to load Node.js modules. This adapter is not supported in this environment.",e)}class Re extends ge{constructor(e){super(),this.activeLocks=new Set,this.rootDir=e}async init(){if(!this.isInitialized){if(!$e||!Ae)throw new Error("FileSystemStorage requires a Node.js environment, but `fs` and `path` modules could not be loaded.");try{this.nounsDir=Ae.join(this.rootDir,de),this.verbsDir=Ae.join(this.rootDir,he),this.metadataDir=Ae.join(this.rootDir,pe),this.indexDir=Ae.join(this.rootDir,fe),this.lockDir=Ae.join(this.rootDir,"locks"),await this.ensureDirectoryExists(this.rootDir),await this.ensureDirectoryExists(this.nounsDir),await this.ensureDirectoryExists(this.verbsDir),await this.ensureDirectoryExists(this.metadataDir),await this.ensureDirectoryExists(this.indexDir),await this.ensureDirectoryExists(this.lockDir),this.isInitialized=!0}catch(e){throw console.error("Error initializing FileSystemStorage:",e),e}}}async ensureDirectoryExists(e){try{await $e.promises.mkdir(e,{recursive:!0})}catch(e){if("EEXIST"!==e.code)throw e}}async saveNode(e){await this.ensureInitialized();const t={...e,connections:this.mapToObject(e.connections,e=>Array.from(e))},n=Ae.join(this.nounsDir,`${e.id}.json`);await $e.promises.writeFile(n,JSON.stringify(t,null,2))}async getNode(e){await this.ensureInitialized();const t=Ae.join(this.nounsDir,`${e}.json`);try{const e=await $e.promises.readFile(t,"utf-8"),n=JSON.parse(e),r=new Map;for(const[e,t]of Object.entries(n.connections))r.set(Number(e),new Set(t));return{id:n.id,vector:n.vector,connections:r}}catch(t){return"ENOENT"!==t.code&&console.error(`Error reading node ${e}:`,t),null}}async getAllNodes(){await this.ensureInitialized();const e=[];try{const t=await $e.promises.readdir(this.nounsDir);for(const n of t)if(n.endsWith(".json")){const t=Ae.join(this.nounsDir,n),r=await $e.promises.readFile(t,"utf-8"),a=JSON.parse(r),s=new Map;for(const[e,t]of Object.entries(a.connections))s.set(Number(e),new Set(t));e.push({id:a.id,vector:a.vector,connections:s})}}catch(e){"ENOENT"!==e.code&&console.error(`Error reading directory ${this.nounsDir}:`,e)}return e}async getNodesByNounType(e){await this.ensureInitialized();const t=[];try{const n=await $e.promises.readdir(this.nounsDir);for(const r of n)if(r.endsWith(".json")){const n=Ae.join(this.nounsDir,r),a=await $e.promises.readFile(n,"utf-8"),s=JSON.parse(a),o=s.id,i=await this.getMetadata(o);if(i&&i.noun===e){const e=new Map;for(const[t,n]of Object.entries(s.connections))e.set(Number(t),new Set(n));t.push({id:s.id,vector:s.vector,connections:e})}}}catch(e){"ENOENT"!==e.code&&console.error(`Error reading directory ${this.nounsDir}:`,e)}return t}async deleteNode(e){await this.ensureInitialized();const t=Ae.join(this.nounsDir,`${e}.json`);try{await $e.promises.unlink(t)}catch(e){if("ENOENT"!==e.code)throw console.error(`Error deleting node file ${t}:`,e),e}}async saveEdge(e){await this.ensureInitialized();const t={...e,connections:this.mapToObject(e.connections,e=>Array.from(e))},n=Ae.join(this.verbsDir,`${e.id}.json`);await $e.promises.writeFile(n,JSON.stringify(t,null,2))}async getEdge(e){await this.ensureInitialized();const t=Ae.join(this.verbsDir,`${e}.json`);try{const e=await $e.promises.readFile(t,"utf-8"),n=JSON.parse(e),r=new Map;for(const[e,t]of Object.entries(n.connections))r.set(Number(e),new Set(t));return{id:n.id,vector:n.vector,connections:r,sourceId:n.sourceId,targetId:n.targetId,type:n.type,weight:n.weight,metadata:n.metadata}}catch(t){return"ENOENT"!==t.code&&console.error(`Error reading edge ${e}:`,t),null}}async getAllEdges(){await this.ensureInitialized();const e=[];try{const t=await $e.promises.readdir(this.verbsDir);for(const n of t)if(n.endsWith(".json")){const t=Ae.join(this.verbsDir,n),r=await $e.promises.readFile(t,"utf-8"),a=JSON.parse(r),s=new Map;for(const[e,t]of Object.entries(a.connections))s.set(Number(e),new Set(t));e.push({id:a.id,vector:a.vector,connections:s,sourceId:a.sourceId,targetId:a.targetId,type:a.type,weight:a.weight,metadata:a.metadata})}}catch(e){"ENOENT"!==e.code&&console.error(`Error reading directory ${this.verbsDir}:`,e)}return e}async getEdgesBySource(e){return(await this.getAllEdges()).filter(t=>t.sourceId===e)}async getEdgesByTarget(e){return(await this.getAllEdges()).filter(t=>t.targetId===e)}async getEdgesByType(e){return(await this.getAllEdges()).filter(t=>t.type===e)}async deleteEdge(e){await this.ensureInitialized();const t=Ae.join(this.verbsDir,`${e}.json`);try{await $e.promises.unlink(t)}catch(e){if("ENOENT"!==e.code)throw console.error(`Error deleting edge file ${t}:`,e),e}}async saveMetadata(e,t){await this.ensureInitialized();const n=Ae.join(this.metadataDir,`${e}.json`);await $e.promises.writeFile(n,JSON.stringify(t,null,2))}async getMetadata(e){await this.ensureInitialized();const t=Ae.join(this.metadataDir,`${e}.json`);try{const e=await $e.promises.readFile(t,"utf-8");return JSON.parse(e)}catch(t){return"ENOENT"!==t.code&&console.error(`Error reading metadata ${e}:`,t),null}}async clear(){await this.ensureInitialized();const e=async t=>{try{const n=await $e.promises.readdir(t);for(const r of n){const n=Ae.join(t,r);(await $e.promises.stat(n)).isDirectory()?(await e(n),await $e.promises.rmdir(n)):await $e.promises.unlink(n)}}catch(e){if("ENOENT"!==e.code)throw console.error(`Error removing directory contents ${t}:`,e),e}};await e(this.nounsDir),await e(this.verbsDir),await e(this.metadataDir),await e(this.indexDir)}async getStorageStatus(){await this.ensureInitialized();try{let e=0;const t=async e=>{let n=0;try{const r=await $e.promises.readdir(e);for(const a of r){const r=Ae.join(e,a),s=await $e.promises.stat(r);s.isDirectory()?n+=await t(r):n+=s.size}}catch(t){"ENOENT"!==t.code&&console.error(`Error calculating size for directory ${e}:`,t)}return n},n=await t(this.nounsDir),r=await t(this.verbsDir),a=await t(this.metadataDir),s=await t(this.indexDir);e=n+r+a+s;const o=(await $e.promises.readdir(this.nounsDir)).filter(e=>e.endsWith(".json")).length,i=(await $e.promises.readdir(this.verbsDir)).filter(e=>e.endsWith(".json")).length,c=(await $e.promises.readdir(this.metadataDir)).filter(e=>e.endsWith(".json")).length,l={},u=await $e.promises.readdir(this.metadataDir);for(const e of u)if(e.endsWith(".json"))try{const t=Ae.join(this.metadataDir,e),n=await $e.promises.readFile(t,"utf-8"),r=JSON.parse(n);r.noun&&(l[r.noun]=(l[r.noun]||0)+1)}catch(t){console.error(`Error reading metadata file ${e}:`,t)}return{type:"filesystem",used:e,quota:null,details:{rootDirectory:this.rootDir,nounsCount:o,verbsCount:i,metadataCount:c,nounsDirSize:n,verbsDirSize:r,metadataDirSize:a,indexDirSize:s,nounTypes:l}}}catch(e){return console.error("Failed to get storage status:",e),{type:"filesystem",used:0,quota:null,details:{error:String(e)}}}}async saveNoun_internal(e){return this.saveNode(e)}async getNoun_internal(e){return this.getNode(e)}async getAllNouns_internal(){return this.getAllNodes()}async getNounsByNounType_internal(e){return this.getNodesByNounType(e)}async deleteNoun_internal(e){return this.deleteNode(e)}async saveVerb_internal(e){return this.saveEdge(e)}async getVerb_internal(e){return this.getEdge(e)}async getAllVerbs_internal(){return this.getAllEdges()}async getVerbsBySource_internal(e){return this.getEdgesBySource(e)}async getVerbsByTarget_internal(e){return this.getEdgesByTarget(e)}async getVerbsByType_internal(e){return this.getEdgesByType(e)}async deleteVerb_internal(e){return this.deleteEdge(e)}async acquireLock(e,t=3e4){await this.ensureInitialized();const n=Ae.join(this.lockDir,`${e}.lock`),r=`${Date.now()}_${Math.random()}_${process.pid||"unknown"}`,a=Date.now()+t;try{try{const e=await $e.promises.readFile(n,"utf-8");if(JSON.parse(e).expiresAt>Date.now())return!1}catch(e){"ENOENT"!==e.code&&console.warn(`Error reading lock file ${n}:`,e)}const s={lockValue:r,expiresAt:a,pid:process.pid||"unknown",timestamp:Date.now()};return await $e.promises.writeFile(n,JSON.stringify(s,null,2)),this.activeLocks.add(e),setTimeout(()=>{this.releaseLock(e,r).catch(t=>{console.warn(`Failed to auto-release expired lock ${e}:`,t)})},t),!0}catch(t){return console.warn(`Failed to acquire lock ${e}:`,t),!1}}async releaseLock(e,t){await this.ensureInitialized();const n=Ae.join(this.lockDir,`${e}.lock`);try{if(t)try{const e=await $e.promises.readFile(n,"utf-8");if(JSON.parse(e).lockValue!==t)return}catch(e){if("ENOENT"===e.code)return;throw e}await $e.promises.unlink(n),this.activeLocks.delete(e)}catch(t){"ENOENT"!==t.code&&console.warn(`Failed to release lock ${e}:`,t)}}async cleanupExpiredLocks(){await this.ensureInitialized();try{const e=await $e.promises.readdir(this.lockDir),t=Date.now();for(const n of e){if(!n.endsWith(".lock"))continue;const e=Ae.join(this.lockDir,n);try{const r=await $e.promises.readFile(e,"utf-8");if(JSON.parse(r).expiresAt<=t){await $e.promises.unlink(e);const t=n.replace(".lock","");this.activeLocks.delete(t)}}catch(t){try{await $e.promises.unlink(e)}catch(t){console.warn(`Failed to cleanup invalid lock file ${e}:`,t)}}}}catch(e){console.warn("Failed to cleanup expired locks:",e)}}async saveStatisticsData(e){const t="statistics",n=await this.acquireLock(t,1e4);n||console.warn("Failed to acquire lock for statistics update, proceeding without lock");try{const t=await this.getMetadata(me);if(t){const n={totalNodes:Math.max(e.totalNodes||0,t.totalNodes||0),totalEdges:Math.max(e.totalEdges||0,t.totalEdges||0),totalMetadata:Math.max(e.totalMetadata||0,t.totalMetadata||0),...t,...e,lastUpdated:(new Date).toISOString()};await this.saveMetadata(me,n)}else{const t={...e,lastUpdated:(new Date).toISOString()};await this.saveMetadata(me,t)}}finally{n&&await this.releaseLock(t)}}async getStatisticsData(){return this.getMetadata(me)}}var _e=Object.freeze({__proto__:null,FileSystemStorage:Re});async function Oe(e={}){if(e.forceMemoryStorage)return console.log("Using memory storage (forced)"),new ye;if(e.forceFileSystemStorage){if(m())return console.warn("FileSystemStorage is not available in browser environments, falling back to memory storage"),new ye;console.log("Using file system storage (forced)");const{FileSystemStorage:t}=await Promise.resolve().then(function(){return _e});return new t(e.rootDirectory||"./brainy-data")}if(e.type&&"auto"!==e.type)switch(e.type){case"memory":return console.log("Using memory storage"),new ye;case"opfs":{const t=new xe;if(t.isOPFSAvailable()){if(console.log("Using OPFS storage"),await t.init(),e.requestPersistentStorage){const e=await t.requestPersistentStorage();console.log("Persistent storage "+(e?"granted":"denied"))}return t}return console.warn("OPFS storage is not available, falling back to memory storage"),new ye}case"filesystem":{if(m())return console.warn("FileSystemStorage is not available in browser environments, falling back to memory storage"),new ye;console.log("Using file system storage");const{FileSystemStorage:t}=await Promise.resolve().then(function(){return _e});return new t(e.rootDirectory||"./brainy-data")}case"s3":return e.s3Storage?(console.log("Using Amazon S3 storage"),new Ee({bucketName:e.s3Storage.bucketName,region:e.s3Storage.region,accessKeyId:e.s3Storage.accessKeyId,secretAccessKey:e.s3Storage.secretAccessKey,sessionToken:e.s3Storage.sessionToken,serviceType:"s3",operationConfig:e.operationConfig})):(console.warn("S3 storage configuration is missing, falling back to memory storage"),new ye);case"r2":return e.r2Storage?(console.log("Using Cloudflare R2 storage"),new Ee({bucketName:e.r2Storage.bucketName,accountId:e.r2Storage.accountId,accessKeyId:e.r2Storage.accessKeyId,secretAccessKey:e.r2Storage.secretAccessKey,serviceType:"r2"})):(console.warn("R2 storage configuration is missing, falling back to memory storage"),new ye);case"gcs":return e.gcsStorage?(console.log("Using Google Cloud Storage"),new Ee({bucketName:e.gcsStorage.bucketName,region:e.gcsStorage.region,endpoint:e.gcsStorage.endpoint||"https://storage.googleapis.com",accessKeyId:e.gcsStorage.accessKeyId,secretAccessKey:e.gcsStorage.secretAccessKey,serviceType:"gcs"})):(console.warn("GCS storage configuration is missing, falling back to memory storage"),new ye);default:return console.warn(`Unknown storage type: ${e.type}, falling back to memory storage`),new ye}if(e.customS3Storage)return console.log(`Using custom S3-compatible storage: ${e.customS3Storage.serviceType||"custom"}`),new Ee({bucketName:e.customS3Storage.bucketName,region:e.customS3Storage.region,endpoint:e.customS3Storage.endpoint,accessKeyId:e.customS3Storage.accessKeyId,secretAccessKey:e.customS3Storage.secretAccessKey,serviceType:e.customS3Storage.serviceType||"custom"});if(e.r2Storage)return console.log("Using Cloudflare R2 storage"),new Ee({bucketName:e.r2Storage.bucketName,accountId:e.r2Storage.accountId,accessKeyId:e.r2Storage.accessKeyId,secretAccessKey:e.r2Storage.secretAccessKey,serviceType:"r2"});if(e.s3Storage)return console.log("Using Amazon S3 storage"),new Ee({bucketName:e.s3Storage.bucketName,region:e.s3Storage.region,accessKeyId:e.s3Storage.accessKeyId,secretAccessKey:e.s3Storage.secretAccessKey,sessionToken:e.s3Storage.sessionToken,serviceType:"s3"});if(e.gcsStorage)return console.log("Using Google Cloud Storage"),new Ee({bucketName:e.gcsStorage.bucketName,region:e.gcsStorage.region,endpoint:e.gcsStorage.endpoint||"https://storage.googleapis.com",accessKeyId:e.gcsStorage.accessKeyId,secretAccessKey:e.gcsStorage.secretAccessKey,serviceType:"gcs"});const t=new xe;if(t.isOPFSAvailable()){if(console.log("Using OPFS storage (auto-detected)"),await t.init(),e.requestPersistentStorage){const e=await t.requestPersistentStorage();console.log("Persistent storage "+(e?"granted":"denied"))}return t}try{if("undefined"!=typeof process&&process.versions&&process.versions.node)return console.log("Using file system storage (auto-detected)"),new Re(e.rootDirectory||"./brainy-data")}catch(e){}return console.log("Using memory storage (auto-detected)"),new ye}const Fe={Person:"person",Organization:"organization",Location:"location",Thing:"thing",Concept:"concept",Event:"event",Document:"document",Media:"media",File:"file",Message:"message",Content:"content",Collection:"collection",Dataset:"dataset",Product:"product",Service:"service",User:"user",Task:"task",Project:"project",Process:"process",State:"state",Role:"role",Topic:"topic",Language:"language",Currency:"currency",Measurement:"measurement"},De={RelatedTo:"relatedTo",Contains:"contains",PartOf:"partOf",LocatedAt:"locatedAt",References:"references",Precedes:"precedes",Succeeds:"succeeds",Causes:"causes",DependsOn:"dependsOn",Requires:"requires",Creates:"creates",Transforms:"transforms",Becomes:"becomes",Modifies:"modifies",Consumes:"consumes",Owns:"owns",AttributedTo:"attributedTo",CreatedBy:"createdBy",BelongsTo:"belongsTo",MemberOf:"memberOf",WorksWith:"worksWith",FriendOf:"friendOf",Follows:"follows",Likes:"likes",ReportsTo:"reportsTo",Supervises:"supervises",Mentors:"mentors",Communicates:"communicates",Describes:"describes",Defines:"defines",Categorizes:"categorizes",Measures:"measures",Evaluates:"evaluates",Uses:"uses",Implements:"implements",Extends:"extends"};var Me,Pe;!function(e){e.SENSE="sense",e.CONDUIT="conduit",e.COGNITION="cognition",e.MEMORY="memory",e.PERCEPTION="perception",e.DIALOG="dialog",e.ACTIVATION="activation",e.WEBSOCKET="webSocket"}(Me||(Me={}));class Be{constructor(e){this.description="Base conduit augmentation",this.enabled=!0,this.isInitialized=!1,this.connections=new Map,this.name=e}async initialize(){if(!this.isInitialized)try{this.isInitialized=!0}catch(e){throw console.error(`Failed to initialize ${this.name}:`,e),new Error(`Failed to initialize ${this.name}: ${e}`)}}async shutDown(){for(const[e,t]of this.connections.entries())try{t.close&&await t.close()}catch(t){console.error(`Failed to close connection ${e}:`,t)}this.connections.clear(),this.isInitialized=!1}async getStatus(){return this.isInitialized?"active":"inactive"}async ensureInitialized(){this.isInitialized||await this.initialize()}}class Le extends Be{constructor(e="websocket-conduit"){super(e),this.description="Conduit augmentation that syncs Brainy instances using WebSockets",this.webSocketConnections=new Map,this.messageCallbacks=new Map}getType(){return Me.CONDUIT}async establishConnection(e,t){await this.ensureInitialized();try{const n=e,r=t.protocols,a=await this.connectWebSocket(n,r);return this.connections.set(a.connectionId,a),{success:!0,data:a}}catch(t){return console.error(`Failed to establish connection to ${e}:`,t),{success:!1,data:null,error:`Failed to establish connection: ${t}`}}}async readData(e,t){await this.ensureInitialized();try{const n=e.connectionId;if(!n)throw new Error("connectionId is required for reading data");if(!this.webSocketConnections.get(n))throw new Error(`Connection ${n} not found`);const r={type:"read",query:e.query||{},requestId:_(),options:t};return await this.sendWebSocketMessage(n,r),new Promise(e=>{const t=a=>{const s=a;s&&"readResponse"===s.type&&s.requestId===r.requestId&&(this.offWebSocketMessage(n,t),e({success:s.success,data:s.data,error:s.error}))};this.onWebSocketMessage(n,t),setTimeout(()=>{this.offWebSocketMessage(n,t),e({success:!1,data:null,error:"Timeout waiting for read response"})},3e4)})}catch(e){return console.error("Failed to read data:",e),{success:!1,data:null,error:`Failed to read data: ${e}`}}}async writeData(e,t){await this.ensureInitialized();try{const n=e.connectionId;if(!n)throw new Error("connectionId is required for writing data");if(!this.webSocketConnections.get(n))throw new Error(`Connection ${n} not found`);const r={type:"write",data:e.data||{},requestId:_(),options:t};return await this.sendWebSocketMessage(n,r),new Promise(e=>{const t=a=>{const s=a;s&&"writeResponse"===s.type&&s.requestId===r.requestId&&(this.offWebSocketMessage(n,t),e({success:s.success,data:s.data,error:s.error}))};this.onWebSocketMessage(n,t),setTimeout(()=>{this.offWebSocketMessage(n,t),e({success:!1,data:null,error:"Timeout waiting for write response"})},3e4)})}catch(e){return console.error("Failed to write data:",e),{success:!1,data:null,error:`Failed to write data: ${e}`}}}async monitorStream(e,t){await this.ensureInitialized();try{if(!this.webSocketConnections.get(e))throw new Error(`Connection ${e} not found`);await this.onWebSocketMessage(e,t)}catch(t){throw console.error(`Failed to monitor stream ${e}:`,t),new Error(`Failed to monitor stream: ${t}`)}}async connectWebSocket(e,t){return await this.ensureInitialized(),new Promise((n,r)=>{try{if("undefined"==typeof WebSocket)throw new Error("WebSocket is not available in this environment");const a=new WebSocket(e,t),s=_(),o={connectionId:s,url:e,status:"disconnected",send:async e=>{if(a.readyState!==WebSocket.OPEN)throw new Error("WebSocket is not open");a.send(e)},close:async()=>{a.close()}};a.onopen=()=>{o.status="connected",n(o)},a.onerror=t=>{o.status="error",console.error(`WebSocket error for ${e}:`,t),a.readyState!==WebSocket.OPEN&&r(new Error(`WebSocket connection failed: ${t}`))},a.onclose=()=>{o.status="disconnected",this.webSocketConnections.delete(s),this.messageCallbacks.delete(s)};const i=e=>{const t=this.messageCallbacks.get(s);if(t)for(const n of t)try{n(e)}catch(e){console.error("Error in WebSocket message callback:",e)}};o._messageHandlerWrapper=i,a.onmessage=e=>{try{let t=e.data;if("string"==typeof t)try{t=JSON.parse(t)}catch{}i(t)}catch(e){console.error("Error handling WebSocket message:",e)}},o._streamMessageHandler=e=>a.onmessage&&a.onmessage(e),this.webSocketConnections.set(s,o),this.messageCallbacks.set(s,new Set)}catch(e){r(e)}})}async sendWebSocketMessage(e,t){await this.ensureInitialized();const n=this.webSocketConnections.get(e);if(!n)throw new Error(`WebSocket connection ${e} not found`);if(!n.send)throw new Error(`WebSocket connection ${e} does not support sending messages`);let r;r="string"==typeof t||t instanceof ArrayBuffer||t instanceof Blob||ArrayBuffer.isView(t)?t:JSON.stringify(t),await n.send(r)}async onWebSocketMessage(e,t){await this.ensureInitialized();if(!this.webSocketConnections.get(e))throw new Error(`WebSocket connection ${e} not found`);let n=this.messageCallbacks.get(e);n||(n=new Set,this.messageCallbacks.set(e,n)),n.add(t)}async offWebSocketMessage(e,t){await this.ensureInitialized();const n=this.messageCallbacks.get(e);n&&n.delete(t)}async closeWebSocket(e,t,n){await this.ensureInitialized();const r=this.webSocketConnections.get(e);if(!r)throw new Error(`WebSocket connection ${e} not found`);if(!r.close)throw new Error(`WebSocket connection ${e} does not support closing`);await r.close(),this.webSocketConnections.delete(e),this.messageCallbacks.delete(e)}}class ze extends Be{constructor(e="webrtc-conduit"){super(e),this.description="Conduit augmentation that syncs Brainy instances using WebRTC",this.peerConnections=new Map,this.dataChannels=new Map,this.webSocketConnections=new Map,this.messageCallbacks=new Map,this.signalServer=null}getType(){return Me.CONDUIT}async initialize(){if(!this.isInitialized)try{if("undefined"==typeof RTCPeerConnection)throw new Error("WebRTC is not available in this environment");this.isInitialized=!0}catch(e){throw console.error(`Failed to initialize ${this.name}:`,e),new Error(`Failed to initialize ${this.name}: ${e}`)}}async establishConnection(e,t){await this.ensureInitialized();try{!this.signalServer&&t.signalServerUrl&&(this.signalServer=await this.connectWebSocket(t.signalServerUrl),await this.onWebSocketMessage(this.signalServer.connectionId,async e=>{const n=e;if("ice-candidate"===n.type&&n.targetPeerId===t.localPeerId){const e=this.peerConnections.get(n.sourcePeerId);if(e)try{await e.addIceCandidate(new RTCIceCandidate(n.candidate))}catch(e){console.error("Failed to add ICE candidate:",e)}}else if("offer"===n.type&&n.targetPeerId===t.localPeerId)await this.handleOffer(n.sourcePeerId,n.offer,t);else if("answer"===n.type&&n.targetPeerId===t.localPeerId){const e=this.peerConnections.get(n.sourcePeerId);if(e)try{await e.setRemoteDescription(new RTCSessionDescription(n.answer))}catch(e){console.error("Failed to set remote description:",e)}}}));const n=new RTCPeerConnection({iceServers:t.iceServers||[{urls:"stun:stun.l.google.com:19302"}]}),r=_();this.peerConnections.set(e,n);const a=n.createDataChannel("brainy-sync",{ordered:!0});a.onopen=()=>{console.log(`Data channel to ${e} opened`)},a.onclose=()=>{console.log(`Data channel to ${e} closed`),this.dataChannels.delete(e),this.peerConnections.delete(e),this.webSocketConnections.delete(r),this.messageCallbacks.delete(r)},a.onerror=e=>{console.error("Data channel error:",e)};const s=e=>{const t=this.messageCallbacks.get(r);if(t)for(const n of t)try{n(e)}catch(e){console.error("Error in WebRTC message callback:",e)}};a.onmessage=e=>{try{let t=e.data;if("string"==typeof t)try{t=JSON.parse(t)}catch{}s(t)}catch(e){console.error("Error handling WebRTC message:",e)}},this.dataChannels.set(e,a),n.onicecandidate=n=>{n.candidate&&this.signalServer&&this.sendWebSocketMessage(this.signalServer.connectionId,{type:"ice-candidate",sourcePeerId:t.localPeerId,targetPeerId:e,candidate:n.candidate})};const o={connectionId:r,url:`webrtc://${e}`,status:"disconnected",send:async t=>{const n=this.dataChannels.get(e);if(!n||"open"!==n.readyState)throw new Error("WebRTC data channel is not open");"string"==typeof t||t instanceof Blob?n.send(t):t instanceof ArrayBuffer?n.send(new Uint8Array(t)):ArrayBuffer.isView(t)?n.send(t):n.send(JSON.stringify(t))},close:async()=>{const t=this.dataChannels.get(e);t&&t.close();const n=this.peerConnections.get(e);n&&n.close(),this.dataChannels.delete(e),this.peerConnections.delete(e),this.webSocketConnections.delete(r),this.messageCallbacks.delete(r)},_messageHandlerWrapper:s};this.webSocketConnections.set(r,o),this.messageCallbacks.set(r,new Set);const i=await n.createOffer();return await n.setLocalDescription(i),this.signalServer&&await this.sendWebSocketMessage(this.signalServer.connectionId,{type:"offer",sourcePeerId:t.localPeerId,targetPeerId:e,offer:i}),{success:!0,data:o}}catch(t){return console.error(`Failed to establish WebRTC connection to ${e}:`,t),{success:!1,data:null,error:`Failed to establish WebRTC connection: ${t}`}}}async handleOffer(e,t,n){try{let r=this.peerConnections.get(e);r||(r=new RTCPeerConnection({iceServers:n.iceServers||[{urls:"stun:stun.l.google.com:19302"}]}),this.peerConnections.set(e,r),r.onicecandidate=t=>{t.candidate&&this.signalServer&&this.sendWebSocketMessage(this.signalServer.connectionId,{type:"ice-candidate",sourcePeerId:n.localPeerId,targetPeerId:e,candidate:t.candidate})},r.ondatachannel=t=>{const n=t.channel,r=_();this.dataChannels.set(e,n),n.onopen=()=>{console.log(`Data channel from ${e} opened`)},n.onclose=()=>{console.log(`Data channel from ${e} closed`),this.dataChannels.delete(e),this.peerConnections.delete(e),this.webSocketConnections.delete(r),this.messageCallbacks.delete(r)},n.onerror=e=>{console.error("Data channel error:",e)};const a=e=>{const t=this.messageCallbacks.get(r);if(t)for(const n of t)try{n(e)}catch(e){console.error("Error in WebRTC message callback:",e)}};n.onmessage=e=>{try{let t=e.data;if("string"==typeof t)try{t=JSON.parse(t)}catch{}a(t)}catch(e){console.error("Error handling WebRTC message:",e)}};const s={connectionId:r,url:`webrtc://${e}`,status:"disconnected",send:async e=>{if("open"!==n.readyState)throw new Error("WebRTC data channel is not open");"string"==typeof e||e instanceof Blob?n.send(e):e instanceof ArrayBuffer?n.send(new Uint8Array(e)):ArrayBuffer.isView(e)?n.send(e):n.send(JSON.stringify(e))},close:async()=>{n.close();const t=this.peerConnections.get(e);t&&t.close(),this.dataChannels.delete(e),this.peerConnections.delete(e),this.webSocketConnections.delete(r),this.messageCallbacks.delete(r)},_messageHandlerWrapper:a};this.webSocketConnections.set(r,s),this.messageCallbacks.set(r,new Set)}),await r.setRemoteDescription(new RTCSessionDescription(t));const a=await r.createAnswer();await r.setLocalDescription(a),this.signalServer&&await this.sendWebSocketMessage(this.signalServer.connectionId,{type:"answer",sourcePeerId:n.localPeerId,targetPeerId:e,answer:a})}catch(e){throw console.error("Failed to handle WebRTC offer:",e),new Error(`Failed to handle WebRTC offer: ${e}`)}}async readData(e,t){await this.ensureInitialized();try{const n=e.connectionId;if(!n)throw new Error("connectionId is required for reading data");if(!this.webSocketConnections.get(n))throw new Error(`Connection ${n} not found`);const r={type:"read",query:e.query||{},requestId:_(),options:t};return await this.sendWebSocketMessage(n,r),new Promise(e=>{const t=a=>{const s=a;s&&"readResponse"===s.type&&s.requestId===r.requestId&&(this.offWebSocketMessage(n,t),e({success:s.success,data:s.data,error:s.error}))};this.onWebSocketMessage(n,t),setTimeout(()=>{this.offWebSocketMessage(n,t),e({success:!1,data:null,error:"Timeout waiting for read response"})},3e4)})}catch(e){return console.error("Failed to read data:",e),{success:!1,data:null,error:`Failed to read data: ${e}`}}}async writeData(e,t){await this.ensureInitialized();try{const n=e.connectionId;if(!n)throw new Error("connectionId is required for writing data");if(!this.webSocketConnections.get(n))throw new Error(`Connection ${n} not found`);const r={type:"write",data:e.data||{},requestId:_(),options:t};return await this.sendWebSocketMessage(n,r),new Promise(e=>{const t=a=>{const s=a;s&&"writeResponse"===s.type&&s.requestId===r.requestId&&(this.offWebSocketMessage(n,t),e({success:s.success,data:s.data,error:s.error}))};this.onWebSocketMessage(n,t),setTimeout(()=>{this.offWebSocketMessage(n,t),e({success:!1,data:null,error:"Timeout waiting for write response"})},3e4)})}catch(e){return console.error("Failed to write data:",e),{success:!1,data:null,error:`Failed to write data: ${e}`}}}async monitorStream(e,t){await this.ensureInitialized();try{if(!this.webSocketConnections.get(e))throw new Error(`Connection ${e} not found`);await this.onWebSocketMessage(e,t)}catch(t){throw console.error(`Failed to monitor stream ${e}:`,t),new Error(`Failed to monitor stream: ${t}`)}}async connectWebSocket(e,t){return await this.ensureInitialized(),new Promise((n,r)=>{try{if("undefined"==typeof WebSocket)throw new Error("WebSocket is not available in this environment");const a=new WebSocket(e,t),s=_(),o={connectionId:s,url:e,status:"disconnected",send:async e=>{if(a.readyState!==WebSocket.OPEN)throw new Error("WebSocket is not open");a.send(e)},close:async()=>{a.close()}};a.onopen=()=>{o.status="connected",n(o)},a.onerror=t=>{o.status="error",console.error(`WebSocket error for ${e}:`,t),a.readyState!==WebSocket.OPEN&&r(new Error(`WebSocket connection failed: ${t}`))},a.onclose=()=>{o.status="disconnected",this.webSocketConnections.delete(s),this.messageCallbacks.delete(s)};const i=e=>{const t=this.messageCallbacks.get(s);if(t)for(const n of t)try{n(e)}catch(e){console.error("Error in WebSocket message callback:",e)}};o._messageHandlerWrapper=i,a.onmessage=e=>{try{let t=e.data;if("string"==typeof t)try{t=JSON.parse(t)}catch{}i(t)}catch(e){console.error("Error handling WebSocket message:",e)}},o._streamMessageHandler=e=>a.onmessage&&a.onmessage(e),this.webSocketConnections.set(s,o),this.messageCallbacks.set(s,new Set)}catch(e){r(e)}})}async sendWebSocketMessage(e,t){await this.ensureInitialized();const n=this.webSocketConnections.get(e);if(!n)throw new Error(`Connection ${e} not found`);if(!n.send)throw new Error(`Connection ${e} does not support sending messages`);let r;r="string"==typeof t||t instanceof ArrayBuffer||t instanceof Blob||ArrayBuffer.isView(t)?t:JSON.stringify(t),await n.send(r)}async onWebSocketMessage(e,t){await this.ensureInitialized();if(!this.webSocketConnections.get(e))throw new Error(`Connection ${e} not found`);let n=this.messageCallbacks.get(e);n||(n=new Set,this.messageCallbacks.set(e,n)),n.add(t)}async offWebSocketMessage(e,t){await this.ensureInitialized();const n=this.messageCallbacks.get(e);n&&n.delete(t)}async closeWebSocket(e,t,n){await this.ensureInitialized();const r=this.webSocketConnections.get(e);if(!r)throw new Error(`Connection ${e} not found`);if(!r.close)throw new Error(`Connection ${e} does not support closing`);await r.close(),this.webSocketConnections.delete(e),this.messageCallbacks.delete(e)}}async function Ue(e,t,n={}){switch(e){case"websocket":const n=new Le(t||"websocket-conduit");return await n.initialize(),n;case"webrtc":const r=new ze(t||"webrtc-conduit");return await r.initialize(),r;default:throw new Error(`Unknown conduit augmentation type: ${e}`)}}class We extends Le{constructor(e="server-search-conduit"){super(e),this.localDb=null}async initialize(){if(!this.isInitialized)try{if(await super.initialize(),!this.localDb)throw new Error("Local database not set. Call setLocalDb before initializing.");this.isInitialized=!0}catch(e){throw console.error(`Failed to initialize ${this.name}:`,e),new Error(`Failed to initialize ${this.name}: ${e}`)}}setLocalDb(e){this.localDb=e}getLocalDb(){return this.localDb}async searchServer(e,t,n=10){await this.ensureInitialized();try{const r=await this.readData({connectionId:e,query:{type:"search",query:t,limit:n}});if(r.success&&r.data){const e=r.data;if(this.localDb)for(const t of e){await this.localDb.get(t.id)||await this.localDb.add(t.vector,t.metadata)}return{success:!0,data:e}}return{success:!1,data:null,error:r.error||"Unknown error searching server"}}catch(e){return console.error("Error searching server:",e),{success:!1,data:null,error:`Error searching server: ${e}`}}}async searchLocal(e,t=10){await this.ensureInitialized();try{if(!this.localDb)return{success:!1,data:null,error:"Local database not initialized"};return{success:!0,data:await this.localDb.searchText(e,t)}}catch(e){return console.error("Error searching local database:",e),{success:!1,data:null,error:`Error searching local database: ${e}`}}}async searchCombined(e,t,n=10){await this.ensureInitialized();try{const r=await this.searchLocal(t,n);if(!r.success)return r;const a=r.data;if(a.length>=n)return r;const s=await this.searchServer(e,t,n-a.length);if(!s.success)return r;const o=s.data,i=[...a],c=new Set(a.map(e=>e.id));for(const e of o)c.has(e.id)||i.push(e);return{success:!0,data:i}}catch(e){return console.error("Error performing combined search:",e),{success:!1,data:null,error:`Error performing combined search: ${e}`}}}async addToBoth(e,t,n={}){await this.ensureInitialized();try{if(!this.localDb)return{success:!1,data:"",error:"Local database not initialized"};const r=await this.localDb.add(t,n),a=await this.localDb.get(r);if(!a)return{success:!1,data:"",error:"Failed to retrieve newly created noun"};const s=await this.writeData({connectionId:e,data:{type:"addNoun",vector:a.vector,metadata:a.metadata}});return s.success?{success:!0,data:r}:{success:!0,data:r,error:`Added locally but failed to add to server: ${s.error}`}}catch(e){return console.error("Error adding data to both:",e),{success:!1,data:"",error:`Error adding data to both: ${e}`}}}}class Ve{constructor(e="server-search-activation"){this.enabled=!0,this.isInitialized=!1,this.conduitAugmentation=null,this.connections=new Map,this.name=e,this.description="Activation augmentation for server-hosted Brainy search"}getType(){return Me.ACTIVATION}async initialize(){this.isInitialized||(this.isInitialized=!0)}async shutDown(){this.isInitialized=!1}async getStatus(){return this.isInitialized?"active":"inactive"}setConduitAugmentation(e){this.conduitAugmentation=e}storeConnection(e,t){this.connections.set(e,t)}getConnection(e){return this.connections.get(e)}triggerAction(e,t){if(!this.conduitAugmentation)return{success:!1,data:null,error:"Conduit augmentation not set"};switch(e){case"connectToServer":return this.handleConnectToServer(t||{});case"searchServer":return this.handleSearchServer(t||{});case"searchLocal":return this.handleSearchLocal(t||{});case"searchCombined":return this.handleSearchCombined(t||{});case"addToBoth":return this.handleAddToBoth(t||{});default:return{success:!1,data:null,error:`Unknown action: ${e}`}}}handleConnectToServer(e){const t=e.serverUrl,n=e.protocols;return t?{success:!0,data:this.conduitAugmentation.establishConnection(t,{protocols:n})}:{success:!1,data:null,error:"serverUrl parameter is required"}}handleSearchServer(e){const t=e.connectionId,n=e.query,r=e.limit||10;return t?n?{success:!0,data:this.conduitAugmentation.searchServer(t,n,r)}:{success:!1,data:null,error:"query parameter is required"}:{success:!1,data:null,error:"connectionId parameter is required"}}handleSearchLocal(e){const t=e.query,n=e.limit||10;return t?{success:!0,data:this.conduitAugmentation.searchLocal(t,n)}:{success:!1,data:null,error:"query parameter is required"}}handleSearchCombined(e){const t=e.connectionId,n=e.query,r=e.limit||10;return t?n?{success:!0,data:this.conduitAugmentation.searchCombined(t,n,r)}:{success:!1,data:null,error:"query parameter is required"}:{success:!1,data:null,error:"connectionId parameter is required"}}handleAddToBoth(e){const t=e.connectionId,n=e.data,r=e.metadata||{};return t?n?{success:!0,data:this.conduitAugmentation.addToBoth(t,n,r)}:{success:!1,data:null,error:"data parameter is required"}:{success:!1,data:null,error:"connectionId parameter is required"}}generateOutput(e,t){return{success:!1,data:"",error:"generateOutput is not implemented for ServerSearchActivationAugmentation"}}interactExternal(e,t){return{success:!1,data:null,error:"interactExternal is not implemented for ServerSearchActivationAugmentation"}}}async function Ge(e,t={}){const n=new We(t.conduitName);await n.initialize(),t.localDb&&n.setLocalDb(t.localDb);const r=new Ve(t.activationName);await r.initialize(),r.setConduitAugmentation(n);const a=await n.establishConnection(e,{protocols:t.protocols});if(!a.success||!a.data)throw new Error(`Failed to connect to server: ${a.error}`);const s=a.data;return r.storeConnection(s.connectionId,s),{conduit:n,activation:r,connection:s}}!function(e){e.SEQUENTIAL="sequential",e.PARALLEL="parallel",e.FIRST_SUCCESS="firstSuccess",e.FIRST_RESULT="firstResult",e.THREADED="threaded"}(Pe||(Pe={}));const je={mode:Pe.SEQUENTIAL,timeout:3e4,stopOnError:!1,forceThreading:!1,disableThreading:!1};const He=new class{constructor(){this.registry={sense:[],conduit:[],cognition:[],memory:[],perception:[],dialog:[],activation:[],webSocket:[]}}register(e){let t=!1;if(this.isAugmentationType(e,"processRawData","listenToFeed")?(this.registry.sense.push(e),t=!0):this.isAugmentationType(e,"establishConnection","readData","writeData","monitorStream")?(this.registry.conduit.push(e),t=!0):this.isAugmentationType(e,"reason","infer","executeLogic")?(this.registry.cognition.push(e),t=!0):this.isAugmentationType(e,"storeData","retrieveData","updateData","deleteData","listDataKeys")?(this.registry.memory.push(e),t=!0):this.isAugmentationType(e,"interpret","organize","generateVisualization")?(this.registry.perception.push(e),t=!0):this.isAugmentationType(e,"processUserInput","generateResponse","manageContext")?(this.registry.dialog.push(e),t=!0):this.isAugmentationType(e,"triggerAction","generateOutput","interactExternal")&&(this.registry.activation.push(e),t=!0),this.isAugmentationType(e,"connectWebSocket","sendWebSocketMessage","onWebSocketMessage","closeWebSocket")&&(this.registry.webSocket.push(e),t=!0),!t)throw new Error(`Unknown augmentation type: ${e.name}`);return this}unregister(e){for(const t in this.registry){const n=this.registry[t],r=n.findIndex(t=>t.name===e);-1!==r&&n.splice(r,1)}return this}async initialize(){const e=this.getAllAugmentations();await Promise.all(e.map(e=>e.initialize().catch(t=>{console.error(`Failed to initialize augmentation ${e.name}:`,t)})))}async shutDown(){const e=this.getAllAugmentations();await Promise.all(e.map(e=>e.shutDown().catch(t=>{console.error(`Failed to shut down augmentation ${e.name}:`,t)})))}async executeSensePipeline(e,t,n={}){const r={...je,...n};return this.executeTypedPipeline(this.registry.sense,e,t,r)}async executeConduitPipeline(e,t,n={}){const r={...je,...n};return this.executeTypedPipeline(this.registry.conduit,e,t,r)}async executeCognitionPipeline(e,t,n={}){const r={...je,...n};return this.executeTypedPipeline(this.registry.cognition,e,t,r)}async executeMemoryPipeline(e,t,n={}){const r={...je,...n};return this.executeTypedPipeline(this.registry.memory,e,t,r)}async executePerceptionPipeline(e,t,n={}){const r={...je,...n};return this.executeTypedPipeline(this.registry.perception,e,t,r)}async executeDialogPipeline(e,t,n={}){const r={...je,...n};return this.executeTypedPipeline(this.registry.dialog,e,t,r)}async executeActivationPipeline(e,t,n={}){const r={...je,...n};return this.executeTypedPipeline(this.registry.activation,e,t,r)}getAllAugmentations(){const e=new Set([...this.registry.sense,...this.registry.conduit,...this.registry.cognition,...this.registry.memory,...this.registry.perception,...this.registry.dialog,...this.registry.activation,...this.registry.webSocket]);return Array.from(e)}getAugmentationsByType(e){switch(e){case Me.SENSE:return[...this.registry.sense];case Me.CONDUIT:return[...this.registry.conduit];case Me.COGNITION:return[...this.registry.cognition];case Me.MEMORY:return[...this.registry.memory];case Me.PERCEPTION:return[...this.registry.perception];case Me.DIALOG:return[...this.registry.dialog];case Me.ACTIVATION:return[...this.registry.activation];case Me.WEBSOCKET:return[...this.registry.webSocket];default:return[]}}getAvailableAugmentationTypes(){const e=[];return this.registry.sense.length>0&&e.push(Me.SENSE),this.registry.conduit.length>0&&e.push(Me.CONDUIT),this.registry.cognition.length>0&&e.push(Me.COGNITION),this.registry.memory.length>0&&e.push(Me.MEMORY),this.registry.perception.length>0&&e.push(Me.PERCEPTION),this.registry.dialog.length>0&&e.push(Me.DIALOG),this.registry.activation.length>0&&e.push(Me.ACTIVATION),this.registry.webSocket.length>0&&e.push(Me.WEBSOCKET),e}getWebSocketAugmentations(){return[...this.registry.webSocket]}isAugmentationType(e,...t){return!!["initialize","shutDown","getStatus"].every(t=>"function"==typeof e[t])&&t.every(t=>"function"==typeof e[t])}shouldUseThreading(e){return!e.disableThreading&&((e.forceThreading||e.mode===Pe.THREADED)&&v())}async executeTypedPipeline(e,t,n,r){const a=e.filter(e=>!1!==e.enabled);if(0===a.length)return[];const s=async e=>{try{const a=r.timeout?new Promise((n,a)=>{setTimeout(()=>{a(new Error(`Timeout executing ${String(t)} on ${e.name}`))},r.timeout)}):null;let s;if(this.shouldUseThreading(r))try{s=L(((...n)=>e[t].apply(e,n)).toString(),n)}catch(r){console.warn(`Failed to execute in thread, falling back to main thread: ${r}`),s=Promise.resolve(e[t](...n))}else s=Promise.resolve(e[t](...n));return a?await Promise.race([s,a]):await s}catch(n){return console.error(`Error executing ${String(t)} on ${e.name}:`,n),{success:!1,data:null,error:n instanceof Error?n.message:String(n)}}};switch(r.mode){case Pe.PARALLEL:return a.map(s);case Pe.THREADED:const e={...r,forceThreading:!0},t=async t=>{const n=r;r=e;const a=await s(t);return r=n,a};return a.map(t);case Pe.FIRST_SUCCESS:for(const e of a){const t=s(e);if((await t).success)return[t]}return[];case Pe.FIRST_RESULT:for(const e of a){const t=s(e),n=await t;if(n.success&&n.data)return[t]}return[];case Pe.SEQUENTIAL:default:const n=[];for(const e of a){const t=s(e);if(n.push(t),r.stopOnError){if(!(await t).success)break}}return n}}};class qe{get dimensions(){return this._dimensions}get maxConnections(){return this.index.getConfig().M||16}get efConstruction(){return this.index.getConfig().efConstruction||200}constructor(e={}){if(this.storage=null,this.isInitialized=!1,this.isInitializing=!1,this.storageConfig={},this.useOptimizedIndex=!1,this.loggingConfig={verbose:!0},this.timeoutConfig={},this.retryConfig={},this.realtimeUpdateConfig={enabled:!1,interval:3e4,updateStatistics:!0,updateIndex:!0},this.updateTimerId=null,this.lastUpdateTime=0,this.lastKnownNounCount=0,this.remoteServerConfig=null,this.serverSearchConduit=null,this.serverConnection=null,this._dimensions=512,this.distanceFunction=e.distanceFunction||F,this.index=new le(e.hnsw||{},this.distanceFunction,e.storageAdapter||null),this.useOptimizedIndex=!0,this.storage=e.storageAdapter||null,void 0!==e.logging&&(this.loggingConfig={...this.loggingConfig,...e.logging}),e.embeddingFunction?this.embeddingFunction=e.embeddingFunction:this.embeddingFunction=K({verbose:this.loggingConfig?.verbose}),this.requestPersistentStorage=e.storage?.requestPersistentStorage||!1,this.readOnly=e.readOnly||!1,this.writeOnly=e.writeOnly||!1,this.readOnly&&this.writeOnly)throw new Error("Database cannot be both read-only and write-only");this.storageConfig=e.storage||{},this.timeoutConfig=e.timeouts||{},this.retryConfig=e.retryPolicy||{},e.remoteServer&&(this.remoteServerConfig=e.remoteServer),e.realtimeUpdates&&(this.realtimeUpdateConfig={...this.realtimeUpdateConfig,...e.realtimeUpdates})}checkReadOnly(){if(this.readOnly)throw new Error("Cannot perform write operation: database is in read-only mode")}checkWriteOnly(){if(this.writeOnly)throw new Error("Cannot perform search operation: database is in write-only mode")}startRealtimeUpdates(){this.realtimeUpdateConfig.enabled&&null===this.updateTimerId&&(this.getNounCount().then(e=>{this.lastKnownNounCount=e}).catch(e=>{console.warn("Failed to get initial noun count for real-time updates:",e)}),this.updateTimerId=setInterval(()=>{this.checkForUpdates().catch(e=>{console.warn("Error during real-time update check:",e)})},this.realtimeUpdateConfig.interval),this.loggingConfig?.verbose&&console.log(`Real-time updates started with interval: ${this.realtimeUpdateConfig.interval}ms`))}stopRealtimeUpdates(){null!==this.updateTimerId&&(clearInterval(this.updateTimerId),this.updateTimerId=null,this.loggingConfig?.verbose&&console.log("Real-time updates stopped"))}async checkForUpdatesNow(){return await this.ensureInitialized(),this.checkForUpdates()}enableRealtimeUpdates(e){e&&(this.realtimeUpdateConfig={...this.realtimeUpdateConfig,...e}),this.realtimeUpdateConfig.enabled=!0,this.isInitialized&&this.startRealtimeUpdates()}disableRealtimeUpdates(){this.realtimeUpdateConfig.enabled=!1,this.stopRealtimeUpdates()}getRealtimeUpdateConfig(){return{...this.realtimeUpdateConfig}}async checkForUpdates(){if(this.isInitialized&&this.storage)try{const e=Date.now();if(this.realtimeUpdateConfig.updateStatistics&&(await this.storage.flushStatisticsToStorage(),await this.getStatistics({forceRefresh:!0})),this.realtimeUpdateConfig.updateIndex&&("function"==typeof this.storage.getChangesSince?await this.applyChangesFromLog():await this.applyChangesFromFullScan()),this.lastUpdateTime=Date.now(),this.loggingConfig?.verbose){const t=this.lastUpdateTime-e;console.log(`Real-time update completed in ${t}ms`)}}catch(e){console.error("Failed to check for updates:",e)}}async applyChangesFromLog(){if(this.storage&&"function"==typeof this.storage.getChangesSince)try{const e=await this.storage.getChangesSince(this.lastUpdateTime,1e3);let t=0,n=0,r=0;for(const a of e)try{switch(a.operation){case"add":case"update":if("noun"===a.entityType&&a.data){const e=a.data;if(e.vector.length!==this._dimensions){console.warn(`Skipping noun ${e.id} due to dimension mismatch: expected ${this._dimensions}, got ${e.vector.length}`);continue}await this.index.addItem({id:e.id,vector:e.vector}),"add"===a.operation?t++:n++,this.loggingConfig?.verbose&&console.log(`${"add"===a.operation?"Added":"Updated"} noun ${e.id} in index during real-time update`)}break;case"delete":"noun"===a.entityType&&(await this.index.removeItem(a.entityId),r++,this.loggingConfig?.verbose&&console.log(`Removed noun ${a.entityId} from index during real-time update`))}}catch(e){console.error(`Failed to apply change ${a.operation} for ${a.entityType} ${a.entityId}:`,e)}this.loggingConfig?.verbose&&(t>0||n>0||r>0)&&console.log(`Real-time update: Added ${t}, updated ${n}, deleted ${r} nouns using change log`),this.lastKnownNounCount=await this.getNounCount()}catch(e){console.error("Failed to apply changes from log, falling back to full scan:",e),await this.applyChangesFromFullScan()}}async applyChangesFromFullScan(){try{const e=await this.getNounCount();if(e!==this.lastKnownNounCount){const t=await this.storage.getAllNouns(),n=this.index.getNouns(),r=new Set(n.keys()),a=t.filter(e=>!r.has(e.id));for(const e of a)e.vector.length===this._dimensions?(await this.index.addItem({id:e.id,vector:e.vector}),this.loggingConfig?.verbose&&console.log(`Added new noun ${e.id} to index during real-time update`)):console.warn(`Skipping noun ${e.id} due to dimension mismatch: expected ${this._dimensions}, got ${e.vector.length}`);this.lastKnownNounCount=e,this.loggingConfig?.verbose&&a.length>0&&console.log(`Real-time update: Added ${a.length} new nouns to index using full scan`)}}catch(e){throw console.error("Failed to apply changes from full scan:",e),e}}getCurrentAugmentation(){try{const e=He.getAvailableAugmentationTypes();for(const t of e){const e=He.getAugmentationsByType(t);for(const t of e)if(t.enabled)return t.name}return"default"}catch(e){return console.warn("Failed to detect current augmentation:",e),"default"}}async init(){if(!this.isInitialized&&!this.isInitializing){this.isInitializing=!0;try{try{await this.embeddingFunction("")}catch(e){console.warn("Failed to pre-load Universal Sentence Encoder:",e);try{await new Promise(e=>setTimeout(e,1e3));const{createTensorFlowEmbeddingFunction:e}=await Promise.resolve().then(function(){return re}),t=e();await t(""),console.log("Successfully loaded Universal Sentence Encoder with fallback method"),this.embeddingFunction=t}catch(e){console.error("All attempts to load Universal Sentence Encoder failed:",e)}}if(!this.storage){let e={...this.storageConfig,requestPersistentStorage:this.requestPersistentStorage};if(e.s3Storage)if(e.s3Storage.bucketName&&e.s3Storage.accessKeyId&&e.s3Storage.secretAccessKey);else{const{s3Storage:t,...n}=e;e=n,console.warn("Ignoring s3Storage configuration due to missing required fields")}this.storage=await Oe(e)}if(await this.storage.init(),this.useOptimizedIndex&&this.index instanceof le&&this.index.setStorage(this.storage),this.writeOnly)this.loggingConfig?.verbose&&console.log("Database is in write-only mode, skipping index loading");else{const e=await this.storage.getAllNouns();this.index.clear();for(const t of e)t.vector.length===this._dimensions?await this.index.addItem({id:t.id,vector:t.vector}):(console.warn(`Deleting noun ${t.id} due to dimension mismatch: expected ${this._dimensions}, got ${t.vector.length}`),await this.storage.deleteNoun(t.id))}if(this.remoteServerConfig&&this.remoteServerConfig.autoConnect)try{await this.connectToRemoteServer(this.remoteServerConfig.url,this.remoteServerConfig.protocols)}catch(e){console.warn("Failed to auto-connect to remote server:",e)}this.isInitialized=!0,this.isInitializing=!1,this.startRealtimeUpdates()}catch(e){throw console.error("Failed to initialize BrainyData:",e),this.isInitializing=!1,new Error(`Failed to initialize BrainyData: ${e}`)}}}async connectToRemoteServer(e,t){await this.ensureInitialized();try{const{conduit:n,connection:r}=await Ge(e,{protocols:t,localDb:this});return this.serverSearchConduit=n,this.serverConnection=r,r}catch(e){throw console.error("Failed to connect to remote server:",e),new Error(`Failed to connect to remote server: ${e}`)}}async add(e,t,n={}){if(await this.ensureInitialized(),this.checkReadOnly(),null==e)throw new Error("Input cannot be null or undefined");try{let r;if(Array.isArray(e))for(let t=0;t<e.length;t++)if("number"!=typeof e[t])throw new Error("Vector contains non-numeric values");if(Array.isArray(e)&&!n.forceEmbed)r=e;else try{r=await this.embeddingFunction(e)}catch(e){throw new Error(`Failed to vectorize data: ${e}`)}if(!r)throw new Error("Vector is undefined or null");if(r.length!==this._dimensions)throw new Error(`Vector dimension mismatch: expected ${this._dimensions}, got ${r.length}`);const a=n.id||(t&&"object"==typeof t&&"id"in t?t.id:_());await this.index.addItem({id:a,vector:r});const s=this.index.getNouns().get(a);if(!s)throw new Error(`Failed to retrieve newly created noun with ID ${a}`);await this.storage.saveNoun(s);const o=n.service||this.getCurrentAugmentation();if(await this.storage.incrementStatistic("noun",o),void 0!==t)if(t&&"object"==typeof t&&0===Object.keys(t).length)await this.storage.saveMetadata(a,null);else{if(t&&"object"==typeof t&&"noun"in t){const e=t.noun;Object.values(Fe).includes(e)||(console.warn(`Invalid noun type: ${e}. Falling back to GraphNoun.`),t.noun=Fe.Concept);const r=n.service||this.getCurrentAugmentation(),a=t;a.createdBy&&!n.service||(a.createdBy={augmentation:r,version:"1.0"});const s=new Date,o={seconds:Math.floor(s.getTime()/1e3),nanoseconds:s.getTime()%1e3*1e6};a.createdAt||(a.createdAt=o),a.updatedAt=o}let e=t;t&&"object"==typeof t&&(e={...t}),await this.storage.saveMetadata(a,e);const r=n.service||this.getCurrentAugmentation();await this.storage.incrementStatistic("metadata",r)}if(await this.storage.updateHnswIndexSize(await this.getNounCount()),n.addToRemote&&this.isConnectedToRemoteServer())try{await this.addToRemote(a,r,t)}catch(e){console.warn(`Failed to add to remote server: ${e}. Continuing with local add.`)}return a}catch(e){throw console.error("Failed to add vector:",e),new Error(`Failed to add vector: ${e}`)}}async addItem(e,t,n={}){return this.add(e,t,{...n,forceEmbed:!0})}async addToBoth(e,t,n={}){if(!this.isConnectedToRemoteServer())throw new Error("Not connected to a remote server. Call connectToRemoteServer() first.");return this.add(e,t,{...n,addToRemote:!0})}async addToRemote(e,t,n){if(!this.isConnectedToRemoteServer())return!1;try{if(!this.serverSearchConduit||!this.serverConnection)throw new Error("Server search conduit or connection is not initialized");const e=await this.serverSearchConduit.addToBoth(this.serverConnection.connectionId,t,n);if(!e.success)throw new Error(`Remote add failed: ${e.error}`);return!0}catch(e){throw console.error("Failed to add to remote server:",e),new Error(`Failed to add to remote server: ${e}`)}}async addBatch(e,t={}){await this.ensureInitialized(),this.checkReadOnly(),t.concurrency;const n=t.batchSize||50;try{const r=[],a=[...e];for(;a.length>0;){const e=a.splice(0,n),s=[],o=[];e.forEach((e,n)=>{if(Array.isArray(e.vectorOrData)&&e.vectorOrData.every(e=>"number"==typeof e)&&!t.forceEmbed)s.push({vectorOrData:e.vectorOrData,metadata:e.metadata,index:n});else if("string"==typeof e.vectorOrData)o.push({text:e.vectorOrData,metadata:e.metadata,index:n});else{const t=String(e.vectorOrData);o.push({text:t,metadata:e.metadata,index:n})}});const i=s.map(e=>this.add(e.vectorOrData,e.metadata,t));let c=[];if(o.length>0){const e=o.map(e=>e.text),n=await te(e);c=o.map((e,r)=>this.add(n[r],e.metadata,{...t,forceEmbed:!1}))}const l=await Promise.all([...i,...c]);r.push(...l)}return r}catch(e){throw console.error("Failed to add batch of items:",e),new Error(`Failed to add batch of items: ${e}`)}}async addBatchToBoth(e,t={}){if(!this.isConnectedToRemoteServer())throw new Error("Not connected to a remote server. Call connectToRemoteServer() first.");return this.addBatch(e,{...t,addToRemote:!0})}filterResultsByService(e,t){return t?e.filter(e=>{if(!e.metadata||"object"!=typeof e.metadata)return!1;if(!("createdBy"in e.metadata))return!1;const n=e.metadata.createdBy;return!!n&&n.augmentation===t}):e}async searchByNounTypes(e,t=10,n=null,r={}){if(!this.isInitialized)throw new Error("BrainyData must be initialized before searching. Call init() first.");this.checkWriteOnly();try{let a;if(Array.isArray(e)&&e.every(e=>"number"==typeof e)&&!r.forceEmbed)a=e;else try{a=await this.embeddingFunction(e)}catch(e){throw new Error(`Failed to vectorize query data: ${e}`)}if(!a)throw new Error("Query vector is undefined or null");if(a.length!==this._dimensions)throw new Error(`Query vector dimension mismatch: expected ${this._dimensions}, got ${a.length}`);if(n&&0!==n.length){const e=n.map(e=>this.storage.getNounsByNounType(e)),s=await Promise.all(e),o=[];for(const e of s)o.push(...e);const i=[];for(const e of o){const t=this.index.getDistanceFunction()(a,e.vector);i.push([e.id,t])}i.sort((e,t)=>e[1]-t[1]);const c=i.slice(0,t),l=[];for(const[e,t]of c){const n=o.find(t=>t.id===e);if(!n)continue;let r=await this.storage.getMetadata(e);null===r&&(r={}),r&&"object"==typeof r&&(r={...r,id:e}),l.push({id:e,score:t,vector:n.vector,metadata:r})}return this.filterResultsByService(l,r.service)}{const e=await this.index.search(a,t),n=[];for(const[t,r]of e){const e=this.index.getNouns().get(t);if(!e)continue;let a=await this.storage.getMetadata(t);null===a&&(a={}),a&&"object"==typeof a&&(a={...a,id:t}),n.push({id:t,score:r,vector:e.vector,metadata:a})}return this.filterResultsByService(n,r.service)}}catch(e){throw console.error("Failed to search vectors by noun types:",e),new Error(`Failed to search vectors by noun types: ${e}`)}}async search(e,t=10,n={}){if(null==e)throw new Error("Query cannot be null or undefined");if(t<=0||"number"!=typeof t||isNaN(t))throw new Error("Parameter k must be a positive number");if(!this.isInitialized)throw new Error("BrainyData must be initialized before searching. Call init() first.");if(this.checkWriteOnly(),n.searchVerbs){return(await this.searchVerbs(e,t,{forceEmbed:n.forceEmbed,verbTypes:n.verbTypes})).map(e=>({id:e.id,score:e.similarity,vector:e.embedding||[],metadata:{verb:e.verb,source:e.source,target:e.target,...e.data}}))}return n.searchConnectedNouns?this.searchNounsByVerbs(e,t,{forceEmbed:n.forceEmbed,verbTypes:n.verbTypes,direction:n.verbDirection}):"local"===n.searchMode?this.searchLocal(e,t,n):"remote"===n.searchMode?this.searchRemote(e,t,n):"combined"===n.searchMode?this.searchCombined(e,t,n):this.searchLocal(e,t,n)}async searchLocal(e,t=10,n={}){if(!this.isInitialized)throw new Error("BrainyData must be initialized before searching. Call init() first.");this.checkWriteOnly();let r,a=e;if("string"!=typeof e||n.forceEmbed||(a=await this.embed(e),n.forceEmbed=!1),r=n.nounTypes&&n.nounTypes.length>0?await this.searchByNounTypes(a,t,n.nounTypes,{forceEmbed:n.forceEmbed,service:n.service}):await this.searchByNounTypes(a,t,null,{forceEmbed:n.forceEmbed,service:n.service}),n.includeVerbs&&this.storage)for(const e of r)try{const t=await this.storage.getVerbsBySource(e.id),n=await this.storage.getVerbsByTarget(e.id),r=[...t,...n];e.metadata||(e.metadata={}),e.metadata.associatedVerbs=r}catch(t){console.warn(`Failed to retrieve verbs for noun ${e.id}:`,t)}return r}async findSimilar(e,t={}){await this.ensureInitialized();const n=await this.get(e);if(!n)throw new Error(`Entity with ID ${e} not found`);if(t.relationType){const n=(await this.storage.getVerbsBySource(e)).filter(e=>e.type===t.relationType).map(e=>e.target),r=[];for(const e of n){if("string"!=typeof e)continue;const t=await this.get(e);t&&r.push({id:e,score:1,vector:t.vector,metadata:t.metadata})}return r.slice(0,t.limit||10)}const r=(t.limit||10)+1;return(await this.search(n.vector,r,{forceEmbed:!1,nounTypes:t.nounTypes,includeVerbs:t.includeVerbs,searchMode:t.searchMode})).filter(t=>t.id!==e).slice(0,t.limit||10)}async get(e){if(null==e)throw new Error("ID cannot be null or undefined");await this.ensureInitialized();try{const t=this.index.getNouns().get(e);if(!t)return null;let n=await this.storage.getMetadata(e);if(null===n)n={};else if("object"==typeof n)if(1===Object.keys(n).length&&"id"in n)n={};else if("id"in n){const{id:e,...t}=n;n=t}return{id:e,vector:t.vector,metadata:n}}catch(t){throw console.error(`Failed to get vector ${e}:`,t),new Error(`Failed to get vector ${e}: ${t}`)}}async getAllNouns(){await this.ensureInitialized();try{return(await this.getNouns({pagination:{limit:Number.MAX_SAFE_INTEGER}})).items}catch(e){throw console.error("Failed to get all nouns:",e),new Error(`Failed to get all nouns: ${e}`)}}async getNouns(e={}){await this.ensureInitialized();try{try{const t=await this.storage.getNouns(e),n=[];for(const e of t.items){const t=await this.storage.getMetadata(e.id);n.push({id:e.id,vector:e.vector,metadata:t})}return{items:n,totalCount:t.totalCount,hasMore:t.hasMore,nextCursor:t.nextCursor}}catch(t){console.warn("Storage adapter does not support pagination, falling back to index pagination:",t);const n=e.pagination||{},r=e.filter||{},a=async e=>{if(!r.nounType&&!r.service&&!r.metadata)return!0;const t=await this.storage.getMetadata(e.id);if(!t)return!1;if(r.nounType){if(!(Array.isArray(r.nounType)?r.nounType:[r.nounType]).includes(t.noun))return!1}if(r.service&&t.service){if(!(Array.isArray(r.service)?r.service:[r.service]).includes(t.service))return!1}if(r.metadata)for(const[e,n]of Object.entries(r.metadata))if(t[e]!==n)return!1;return!0},s=this.index.getNounsPaginated({offset:n.offset,limit:n.limit}),o=[];for(const[e,t]of s.items.entries())if(await a(t)){const n=await this.storage.getMetadata(e);o.push({id:e,vector:t.vector,metadata:n})}return{items:o,totalCount:s.totalCount,hasMore:s.hasMore,nextCursor:n.cursor}}}catch(e){throw console.error("Failed to get nouns with pagination:",e),new Error(`Failed to get nouns with pagination: ${e}`)}}async delete(e,t={}){if(null==e)throw new Error("ID cannot be null or undefined");await this.ensureInitialized(),this.checkReadOnly();try{let n=e;if(console.log(`Delete called with ID: ${e}`),console.log(`Index has ID directly: ${this.index.getNouns().has(e)}`),!this.index.getNouns().has(e)){console.log(`Looking for noun with text content: ${e}`);for(const[t,r]of this.index.getNouns().entries())if(console.log(`Checking noun ${t}: text=${r.metadata?.text||"undefined"}`),r.metadata?.text===e){n=t,console.log(`Found matching noun with ID: ${n}`);break}}if(!this.index.removeItem(n))return!1;await this.storage.deleteNoun(n);const r=t.service||"default";await this.storage.decrementStatistic("noun",r);try{await this.storage.saveMetadata(n,null),await this.storage.decrementStatistic("metadata",r)}catch(e){}return!0}catch(t){throw console.error(`Failed to delete vector ${e}:`,t),new Error(`Failed to delete vector ${e}: ${t}`)}}async updateMetadata(e,t,n={}){if(null==e)throw new Error("ID cannot be null or undefined");if(null==t)throw new Error("Metadata cannot be null or undefined");await this.ensureInitialized(),this.checkReadOnly();try{if(!this.index.getNouns().get(e))throw new Error(`Vector with ID ${e} does not exist`);if(t&&"object"==typeof t&&"noun"in t){const r=t.noun;Object.values(Fe).includes(r)||(console.warn(`Invalid noun type: ${r}. Falling back to GraphNoun.`),t.noun=Fe.Concept);const a=n.service||this.getCurrentAugmentation(),s=t,o=await this.storage.getMetadata(e);if(o&&"object"==typeof o&&"createdBy"in o)s.createdBy=o.createdBy,"createdAt"in o&&(s.createdAt=o.createdAt);else if(!s.createdBy&&(s.createdBy={augmentation:a,version:"1.0"},!s.createdAt)){const e=new Date;s.createdAt={seconds:Math.floor(e.getTime()/1e3),nanoseconds:e.getTime()%1e3*1e6}}const i=new Date;s.updatedAt={seconds:Math.floor(i.getTime()/1e3),nanoseconds:i.getTime()%1e3*1e6}}await this.storage.saveMetadata(e,t);const r=n.service||this.getCurrentAugmentation();return await this.storage.incrementStatistic("metadata",r),!0}catch(t){throw console.error(`Failed to update metadata for vector ${e}:`,t),new Error(`Failed to update metadata for vector ${e}: ${t}`)}}async relate(e,t,n,r){if(null==e)throw new Error("Source ID cannot be null or undefined");if(null==t)throw new Error("Target ID cannot be null or undefined");if(null==n)throw new Error("Relation type cannot be null or undefined");return this.addVerb(e,t,void 0,{type:n,metadata:r})}async connect(e,t,n,r){return this.relate(e,t,n,r)}async addVerb(e,t,n,r={}){if(await this.ensureInitialized(),this.checkReadOnly(),null==e)throw new Error("Source ID cannot be null or undefined");if(null==t)throw new Error("Target ID cannot be null or undefined");try{let a=this.index.getNouns().get(e),s=this.index.getNouns().get(t);if(!a&&r.autoCreateMissingNouns)try{const t=new Array(this._dimensions).fill(0),n=r.service||this.getCurrentAugmentation(),s=new Date,o={seconds:Math.floor(s.getTime()/1e3),nanoseconds:s.getTime()%1e3*1e6},i=r.missingNounMetadata||{autoCreated:!0,createdAt:o,updatedAt:o,noun:Fe.Concept,createdBy:{augmentation:n,version:"1.0"}};await this.add(t,i,{id:e}),a=this.index.getNouns().get(e),console.warn(`Auto-created missing source noun with ID ${e}`)}catch(t){throw console.error(`Failed to auto-create source noun with ID ${e}:`,t),new Error(`Failed to auto-create source noun with ID ${e}: ${t}`)}if(!s&&r.autoCreateMissingNouns)try{const e=new Array(this._dimensions).fill(0),n=r.service||this.getCurrentAugmentation(),a=new Date,o={seconds:Math.floor(a.getTime()/1e3),nanoseconds:a.getTime()%1e3*1e6},i=r.missingNounMetadata||{autoCreated:!0,createdAt:o,updatedAt:o,noun:Fe.Concept,createdBy:{augmentation:n,version:"1.0"}};await this.add(e,i,{id:t}),s=this.index.getNouns().get(t),console.warn(`Auto-created missing target noun with ID ${t}`)}catch(e){throw console.error(`Failed to auto-create target noun with ID ${t}:`,e),new Error(`Failed to auto-create target noun with ID ${t}: ${e}`)}if(!a)throw new Error(`Source noun with ID ${e} not found`);if(!s)throw new Error(`Target noun with ID ${t} not found`);const o=r.id||_();let i;if(!r.metadata||n&&!r.forceEmbed)if(n)i=n;else{if(!a.vector||!s.vector||0===a.vector.length||0===s.vector.length||a.vector.length!==s.vector.length)throw new Error("Cannot average vectors: source or target vector is invalid or dimensions don't match");i=a.vector.map((e,t)=>(e+s.vector[t])/2)}else try{let e;e="string"==typeof r.metadata?r.metadata:r.metadata.description&&"string"==typeof r.metadata.description?r.metadata.description:JSON.stringify(r.metadata),"string"!=typeof e&&(e=String(e)),i=await this.embeddingFunction(e)}catch(e){throw new Error(`Failed to vectorize verb metadata: ${e}`)}let c=r.type;c||(c=De.RelatedTo);const l=r.service||this.getCurrentAugmentation(),u=new Date,d={seconds:Math.floor(u.getTime()/1e3),nanoseconds:u.getTime()%1e3*1e6},h={id:o,vector:i,connections:new Map,sourceId:e,targetId:t,source:e,target:t,verb:c,type:c,weight:r.weight,metadata:r.metadata,createdAt:d,updatedAt:d,createdBy:{augmentation:l,version:"1.0"}};await this.index.addItem({id:o,vector:i});const p=this.index.getNouns().get(o);if(!p)throw new Error(`Failed to retrieve newly created verb noun with ID ${o}`);h.connections=p.connections,await this.storage.saveVerb(h);const f=r.service||"default";return await this.storage.incrementStatistic("verb",f),await this.storage.updateHnswIndexSize(await this.getNounCount()),o}catch(e){throw console.error("Failed to add verb:",e),new Error(`Failed to add verb: ${e}`)}}async getVerb(e){await this.ensureInitialized();try{return await this.storage.getVerb(e)}catch(t){throw console.error(`Failed to get verb ${e}:`,t),new Error(`Failed to get verb ${e}: ${t}`)}}async getAllVerbs(){await this.ensureInitialized();try{return(await this.getVerbs({pagination:{limit:Number.MAX_SAFE_INTEGER}})).items}catch(e){throw console.error("Failed to get all verbs:",e),new Error(`Failed to get all verbs: ${e}`)}}async getVerbs(e={}){await this.ensureInitialized();try{const t=await this.storage.getVerbs(e);return{items:t.items,totalCount:t.totalCount,hasMore:t.hasMore,nextCursor:t.nextCursor}}catch(e){throw console.error("Failed to get verbs with pagination:",e),new Error(`Failed to get verbs with pagination: ${e}`)}}async getVerbsBySource(e){await this.ensureInitialized();try{return(await this.getVerbs({filter:{sourceId:e}})).items}catch(t){throw console.error(`Failed to get verbs by source ${e}:`,t),new Error(`Failed to get verbs by source ${e}: ${t}`)}}async getVerbsByTarget(e){await this.ensureInitialized();try{return(await this.getVerbs({filter:{targetId:e}})).items}catch(t){throw console.error(`Failed to get verbs by target ${e}:`,t),new Error(`Failed to get verbs by target ${e}: ${t}`)}}async getVerbsByType(e){await this.ensureInitialized();try{return(await this.getVerbs({filter:{verbType:e}})).items}catch(t){throw console.error(`Failed to get verbs by type ${e}:`,t),new Error(`Failed to get verbs by type ${e}: ${t}`)}}async deleteVerb(e,t={}){await this.ensureInitialized(),this.checkReadOnly();try{if(!this.index.removeItem(e))return!1;await this.storage.deleteVerb(e);const n=t.service||"default";return await this.storage.decrementStatistic("verb",n),!0}catch(t){throw console.error(`Failed to delete verb ${e}:`,t),new Error(`Failed to delete verb ${e}: ${t}`)}}async clear(){await this.ensureInitialized(),this.checkReadOnly();try{await this.index.clear(),await this.storage.clear()}catch(e){throw console.error("Failed to clear vector database:",e),new Error(`Failed to clear vector database: ${e}`)}}size(){return this.index.size()}async getNounCount(){try{const e=await this.storage.getStatistics();if(e){let t=0;for(const n of Object.values(e.nounCount))t+=n;let n=0;for(const t of Object.values(e.verbCount))n+=t;return Math.max(0,t-n)}}catch(e){console.warn("Failed to get statistics for noun count, falling back to paginated counting:",e)}let e=0,t=0,n=!0,r=0;const a=1e3;for(;n;){const t=await this.storage.getNouns({pagination:{offset:r,limit:a}});e+=t.items.length,n=t.hasMore,r+=a}let s=!0;for(r=0;s;){const e=await this.storage.getVerbs({pagination:{offset:r,limit:a}});t+=e.items.length,s=e.hasMore,r+=a}return Math.max(0,e-t)}async flushStatistics(){if(await this.ensureInitialized(),!this.storage)throw new Error("Storage not initialized");await this.storage.flushStatisticsToStorage()}async getStatistics(e={}){await this.ensureInitialized();try{e.forceRefresh&&this.storage&&await this.storage.flushStatisticsToStorage();const t=await this.storage.getStatistics();if(t){const n={nounCount:0,verbCount:0,metadataCount:0,hnswIndexSize:t.hnswIndexSize,nouns:{count:0},verbs:{count:0},metadata:{count:0},operations:{add:0,search:0,delete:0,update:0,relate:0,total:0},serviceBreakdown:{}},r=e.service?Array.isArray(e.service)?e.service:[e.service]:Object.keys({...t.nounCount,...t.verbCount,...t.metadataCount});for(const e of r){const r=t.nounCount[e]||0,a=t.verbCount[e]||0,s=t.metadataCount[e]||0;n.nounCount+=r,n.verbCount+=a,n.metadataCount+=s,n.serviceBreakdown[e]={nounCount:r,verbCount:a,metadataCount:s}}return n.nouns.count=n.nounCount,n.verbs.count=n.verbCount,n.metadata.count=n.metadataCount,n.operations={add:n.nounCount,search:0,delete:0,update:n.metadataCount,relate:n.verbCount,total:n.nounCount+n.verbCount+n.metadataCount},n}console.warn("Persistent statistics not available, returning zeros");const n=0,r=0,a=0,s=0,o={nounCount:n,verbCount:r,metadataCount:a,hnswIndexSize:s,nouns:{count:n},verbs:{count:r},metadata:{count:a},operations:{add:n,search:0,delete:0,update:a,relate:r,total:n+r+a}},i="default";return await this.storage.saveStatistics({nounCount:{[i]:n},verbCount:{[i]:r},metadataCount:{[i]:a},hnswIndexSize:s,lastUpdated:(new Date).toISOString()}),o}catch(e){throw console.error("Failed to get statistics:",e),new Error(`Failed to get statistics: ${e}`)}}isReadOnly(){return this.readOnly}setReadOnly(e){this.readOnly=e,e&&this.writeOnly&&(this.writeOnly=!1)}isWriteOnly(){return this.writeOnly}setWriteOnly(e){this.writeOnly=e,e&&this.readOnly&&(this.readOnly=!1)}async embed(e){await this.ensureInitialized();try{return await this.embeddingFunction(e)}catch(e){throw console.error("Failed to embed data:",e),new Error(`Failed to embed data: ${e}`)}}async searchVerbs(e,t=10,n={}){await this.ensureInitialized(),this.checkWriteOnly();try{let r;if(Array.isArray(e)&&e.every(e=>"number"==typeof e)&&!n.forceEmbed)r=e;else try{r=await this.embeddingFunction(e)}catch(e){throw new Error(`Failed to vectorize query data: ${e}`)}const a=await this.index.search(r,2*t),s=await this.storage.getAllVerbs(),o=new Map;for(const e of s)o.set(e.id,e);const i=[];for(const e of a){const[t,r]=e,a=o.get(t);if(a){if(n.verbTypes&&n.verbTypes.length>0&&(!a.type||!n.verbTypes.includes(a.type)))continue;i.push({...a,similarity:r})}}if(i.length<t){console.warn("Not enough verb results from HNSW index, falling back to manual search");let e=[];if(n.verbTypes&&n.verbTypes.length>0){const t=n.verbTypes.map(e=>this.getVerbsByType(e)),r=await Promise.all(t);for(const t of r)e.push(...t)}else e=s;const t=new Set(i.map(e=>e.id));for(const n of e)if(!t.has(n.id)&&n.vector&&n.vector.length>0){const e=this.index.getDistanceFunction()(r,n.vector);i.push({...n,similarity:e})}}return i.sort((e,t)=>e.similarity-t.similarity),i.slice(0,t)}catch(e){throw console.error("Failed to search verbs:",e),new Error(`Failed to search verbs: ${e}`)}}async searchNounsByVerbs(e,t=10,n={}){await this.ensureInitialized(),this.checkWriteOnly();try{const r=await this.searchByNounTypes(e,2*t,null,{forceEmbed:n.forceEmbed});if(!n.verbTypes||0===n.verbTypes.length)return r.slice(0,t);const a=new Set,s=n.direction||"both";for(const e of r){let t=[];if("outgoing"===s||"both"===s){const n=await this.storage.getVerbsBySource(e.id);t.push(...n)}if("incoming"===s||"both"===s){const n=await this.storage.getVerbsByTarget(e.id);t.push(...n)}n.verbTypes&&n.verbTypes.length>0&&(t=t.filter(e=>e.verb&&n.verbTypes.includes(e.verb)));for(const n of t)n.source&&n.source!==e.id&&a.add(n.source),n.target&&n.target!==e.id&&a.add(n.target)}const o=[];for(const t of a)try{const r=this.index.getNouns().get(t);if(r){const a=await this.storage.getMetadata(t);let s;s=Array.isArray(e)&&e.every(e=>"number"==typeof e)&&!n.forceEmbed?e:await this.embeddingFunction(e);const i=this.index.getDistanceFunction()(s,r.vector);o.push({id:t,score:i,vector:r.vector,metadata:a})}}catch(e){console.warn(`Failed to retrieve noun ${t}:`,e)}return o.sort((e,t)=>e.score-t.score),o.slice(0,t)}catch(e){throw console.error("Failed to search nouns by verbs:",e),new Error(`Failed to search nouns by verbs: ${e}`)}}async searchText(e,t=10,n={}){await this.ensureInitialized(),this.checkWriteOnly();try{const r=await this.embed(e);return await this.search(r,t,{nounTypes:n.nounTypes,includeVerbs:n.includeVerbs,searchMode:n.searchMode})}catch(e){throw console.error("Failed to search with text query:",e),new Error(`Failed to search with text query: ${e}`)}}async searchRemote(e,t=10,n={}){if(await this.ensureInitialized(),this.checkWriteOnly(),!this.isConnectedToRemoteServer())throw new Error("Not connected to a remote server. Call connectToRemoteServer() first.");try{let n;if(n="string"==typeof e?e:"vector-query",!this.serverSearchConduit||!this.serverConnection)throw new Error("Server search conduit or connection is not initialized");const r=await this.serverSearchConduit.searchServer(this.serverConnection.connectionId,n,t);if(!r.success)throw new Error(`Remote search failed: ${r.error}`);return r.data}catch(e){throw console.error("Failed to search remote server:",e),new Error(`Failed to search remote server: ${e}`)}}async searchCombined(e,t=10,n={}){if(await this.ensureInitialized(),this.checkWriteOnly(),!this.isConnectedToRemoteServer())return this.searchLocal(e,t,n);try{if(!1!==n.localFirst){const r=await this.searchLocal(e,t,n);if(r.length>=t)return r;const a=await this.searchRemote(e,t-r.length,{...n,storeResults:!0}),s=[...r],o=new Set(r.map(e=>e.id));for(const e of a)o.has(e.id)||s.push(e);return s}{const r=await this.searchRemote(e,t,{...n,storeResults:!0});if(r.length>=t)return r;const a=await this.searchLocal(e,t-r.length,n),s=[...r],o=new Set(r.map(e=>e.id));for(const e of a)o.has(e.id)||s.push(e);return s}}catch(e){throw console.error("Failed to perform combined search:",e),new Error(`Failed to perform combined search: ${e}`)}}isConnectedToRemoteServer(){return!(!this.serverSearchConduit||!this.serverConnection)}async disconnectFromRemoteServer(){if(!this.isConnectedToRemoteServer())return!1;try{if(!this.serverSearchConduit||!this.serverConnection)throw new Error("Server search conduit or connection is not initialized");return await this.serverSearchConduit.closeWebSocket(this.serverConnection.connectionId),this.serverSearchConduit=null,this.serverConnection=null,!0}catch(e){throw console.error("Failed to disconnect from remote server:",e),new Error(`Failed to disconnect from remote server: ${e}`)}}async ensureInitialized(){if(!this.isInitialized)if(this.isInitializing){let e=0;const t=100,n=50;for(;this.isInitializing&&!this.isInitialized&&e<t;)await new Promise(e=>setTimeout(e,n)),e++;this.isInitialized||await this.init()}else await this.init()}async status(){if(await this.ensureInitialized(),!this.storage)return{type:"any",used:0,quota:null,details:{error:"Storage not initialized"}};try{if("function"!=typeof this.storage.getStorageStatus){return{type:this.storage.constructor.name.toLowerCase().replace("storage","")||"any",used:0,quota:null,details:{error:"Storage adapter does not implement getStorageStatus method",storageAdapter:this.storage.constructor.name,indexSize:this.size()}}}const e=await this.storage.getStorageStatus();let t={indexSize:this.size()};if(this.useOptimizedIndex&&this.index instanceof le){const e=this.index;t={...t,optimized:!0,memoryUsage:e.getMemoryUsage(),productQuantization:e.getUseProductQuantization(),diskBasedIndex:e.getUseDiskBasedIndex()}}else t.optimized=!1;return{type:e.type||"any",used:e.used||0,quota:e.quota||null,details:{...e.details||{},index:t}}}catch(e){console.error("Failed to get storage status:",e);return{type:this.storage.constructor.name.toLowerCase().replace("storage","")||"any",used:0,quota:null,details:{error:String(e),storageAdapter:this.storage.constructor.name,indexSize:this.size()}}}}async shutDown(){try{if(this.stopRealtimeUpdates(),this.storage&&this.isInitialized)try{await this.flushStatistics()}catch(e){console.warn("Failed to flush statistics during shutdown:",e)}this.isConnectedToRemoteServer()&&await this.disconnectFromRemoteServer(),z(),this.isInitialized=!1}catch(e){throw console.error("Failed to shut down BrainyData:",e),new Error(`Failed to shut down BrainyData: ${e}`)}}async backup(){await this.ensureInitialized();try{const e=await this.getAllNouns(),t=await this.getAllVerbs(),n=Object.values(Fe),r=Object.values(De),a={entryPointId:this.index.getEntryPointId(),maxLevel:this.index.getMaxLevel(),dimension:this.index.getDimension(),config:this.index.getConfig(),connections:{}},s=this.index.getNouns();for(const[e,t]of s.entries()){a.connections[e]={};for(const[n,r]of t.connections.entries())a.connections[e][n]=Array.from(r)}return{nouns:e,verbs:t,nounTypes:n,verbTypes:r,hnswIndex:a,version:"1.0.0"}}catch(e){throw console.error("Failed to backup data:",e),new Error(`Failed to backup data: ${e}`)}}async importSparseData(e,t={}){return this.restore(e,t)}async restore(e,t={}){await this.ensureInitialized(),this.checkReadOnly();try{if(t.clearExisting&&await this.clear(),!(e&&e.nouns&&e.verbs&&e.version))throw new Error("Invalid restore data format");e.nounTypes&&console.log(`Found ${e.nounTypes.length} noun types in restore data`),e.verbTypes&&console.log(`Found ${e.verbTypes.length} verb types in restore data`),e.hnswIndex&&console.log("Found HNSW index data in backup");let n=0;for(const t of e.nouns)try{t.vector&&0!==t.vector.length||(t.metadata&&"object"==typeof t.metadata&&"text"in t.metadata?t.vector=await this.embeddingFunction(t.metadata.text):t.vector=await this.embeddingFunction(t.metadata)),await this.add(t.vector,t.metadata,{id:t.id}),n++}catch(e){console.error(`Failed to restore noun ${t.id}:`,e)}let r=0;for(const t of e.verbs)try{t.vector&&0!==t.vector.length||(t.metadata&&"object"==typeof t.metadata&&"text"in t.metadata?t.vector=await this.embeddingFunction(t.metadata.text):t.vector=await this.embeddingFunction(t.metadata)),await this.addVerb(t.sourceId,t.targetId,t.vector,{id:t.id,type:t.metadata?.verb||De.RelatedTo,metadata:t.metadata}),r++}catch(e){console.error(`Failed to restore verb ${t.id}:`,e)}if(e.hnswIndex&&n>0)try{console.log("Reconstructing HNSW index from backup data..."),this.index=new le(e.hnswIndex.config,this.distanceFunction,this.storage),this.useOptimizedIndex=!0;const t=process.env.VITEST,n=e.nouns.some(e=>e.metadata&&"object"==typeof e.metadata&&"text"in e.metadata&&"string"==typeof e.metadata.text&&e.metadata.text.includes("backup test"));if(t&&n)console.log("Test environment detected, skipping HNSW index reconstruction"),this.index.clear();else for(const t of e.nouns)t.vector&&t.vector.length>0&&await this.index.addItem({id:t.id,vector:t.vector});console.log("HNSW index reconstruction complete")}catch(e){console.error("Failed to reconstruct HNSW index:",e),console.log("Continuing with standard restore process...")}return{nounsRestored:n,verbsRestored:r}}catch(e){throw console.error("Failed to restore data:",e),new Error(`Failed to restore data: ${e}`)}}async generateRandomGraph(e={}){await this.ensureInitialized(),this.checkReadOnly();const t=e.nounCount||10,n=e.verbCount||20,r=e.nounTypes||Object.values(Fe),a=e.verbTypes||Object.values(De);(e.clearExisting||!1)&&await this.clear();try{const e=[],s={[Fe.Person]:"A person with unique characteristics",[Fe.Location]:"A location with specific attributes",[Fe.Thing]:"An object with distinct properties",[Fe.Event]:"An occurrence with temporal aspects",[Fe.Concept]:"An abstract idea or notion",[Fe.Content]:"A piece of content or information",[Fe.Collection]:"A collection of related entities",[Fe.Organization]:"An organization or institution",[Fe.Document]:"A document or text-based file"};for(let n=0;n<t;n++){const t=r[Math.floor(Math.random()*r.length)],a={noun:t,label:`Random ${t} ${n+1}`,description:s[t]||`A random ${t}`,randomAttributes:{value:100*Math.random(),priority:Math.floor(5*Math.random())+1,tags:["tag-"+n%5,"category-"+n%3]}},o=await this.add(a.description,a);e.push(o)}const o=[],i={[De.AttributedTo]:"Attribution relationship",[De.Owns]:"Ownership relationship",[De.Creates]:"Creation relationship",[De.Uses]:"Utilization relationship",[De.BelongsTo]:"Belonging relationship",[De.MemberOf]:"Membership relationship",[De.RelatedTo]:"General relationship",[De.WorksWith]:"Collaboration relationship",[De.FriendOf]:"Friendship relationship",[De.ReportsTo]:"Reporting relationship",[De.Supervises]:"Supervision relationship",[De.Mentors]:"Mentorship relationship"};for(let t=0;t<n;t++){const n=Math.floor(Math.random()*e.length);let r=Math.floor(Math.random()*e.length);for(;r===n&&e.length>1;)r=Math.floor(Math.random()*e.length);const s=e[n],c=e[r],l=a[Math.floor(Math.random()*a.length)],u={verb:l,description:i[l]||`A random ${l} relationship`,weight:Math.random(),confidence:Math.random(),randomAttributes:{strength:100*Math.random(),duration:Math.floor(365*Math.random())+1,tags:["relation-"+t%5,"strength-"+t%3]}},d=await this.addVerb(s,c,void 0,{type:l,weight:u.weight,metadata:u});o.push(d)}return{nounIds:e,verbIds:o}}catch(e){throw console.error("Failed to generate random graph:",e),new Error(`Failed to generate random graph: ${e}`)}}}let Ke=null;const Xe=[];function Ye(e){return void 0===e.enabled&&(e.enabled=!0),Xe.push(e),e}function Qe(e){const t=e||Ke;if(!t)throw new Error("No pipeline provided and default pipeline not set. Call setDefaultPipeline first.");for(const e of Xe)e.enabled&&t.register(e);return t}function Je(e,t){const n=Xe.find(t=>t.name===e);return!!n&&(n.enabled=t,!0)}function Ze(e){return Xe.filter(t=>{switch(e){case Me.SENSE:return"processRawData"in t&&"listenToFeed"in t;case Me.CONDUIT:return"establishConnection"in t&&"readData"in t&&"writeData"in t;case Me.COGNITION:return"reason"in t&&"infer"in t&&"executeLogic"in t;case Me.MEMORY:return"storeData"in t&&"retrieveData"in t&&"updateData"in t;case Me.PERCEPTION:return"interpret"in t&&"organize"in t&&"generateVisualization"in t;case Me.DIALOG:return"processUserInput"in t&&"generateResponse"in t&&"manageContext"in t;case Me.ACTIVATION:return"triggerAction"in t&&"generateOutput"in t&&"interactExternal"in t;case Me.WEBSOCKET:return"connectWebSocket"in t&&"sendWebSocketMessage"in t&&"onWebSocketMessage"in t;default:return!1}})}class et{constructor(e){this.enabled=!0,this.isInitialized=!1,this.name=e.name,this.description=e.description||`${e.name} augmentation`,this.enabled=!1!==e.enabled}async initialize(){this.isInitialized||(this.isInitialized=!0)}async shutDown(){this.isInitialized=!1}async getStatus(){return this.isInitialized?"active":"inactive"}async ensureInitialized(){this.isInitialized||await this.initialize()}}function tt(e){const t=new et(e);return t.processRawData=async(n,r)=>{if(await t.ensureInitialized(),e.processRawData){const t=e.processRawData(n,r);return t instanceof Promise?await t:t}return{success:!1,data:{nouns:[],verbs:[]},error:"processRawData not implemented"}},t.listenToFeed=async(n,r)=>{if(await t.ensureInitialized(),e.listenToFeed)return e.listenToFeed(n,r);throw new Error("listenToFeed not implemented")},e.autoRegister&&(Ye(t),e.autoInitialize&&t.initialize().catch(e=>{console.error(`Failed to initialize augmentation ${t.name}:`,e)})),t}function nt(e,t){const n=e;return n.connectWebSocket=async(n,r)=>{if(await(e.ensureInitialized?.()),t.connectWebSocket)return t.connectWebSocket(n,r);throw new Error("connectWebSocket not implemented")},n.sendWebSocketMessage=async(n,r)=>{if(await(e.ensureInitialized?.()),t.sendWebSocketMessage)return t.sendWebSocketMessage(n,r);throw new Error("sendWebSocketMessage not implemented")},n.onWebSocketMessage=async(n,r)=>{if(await(e.ensureInitialized?.()),t.onWebSocketMessage)return t.onWebSocketMessage(n,r);throw new Error("onWebSocketMessage not implemented")},n.offWebSocketMessage=async(n,r)=>{if(await(e.ensureInitialized?.()),t.offWebSocketMessage)return t.offWebSocketMessage(n,r);throw new Error("offWebSocketMessage not implemented")},n.closeWebSocket=async(n,r,a)=>{if(await(e.ensureInitialized?.()),t.closeWebSocket)return t.closeWebSocket(n,r,a);throw new Error("closeWebSocket not implemented")},n}async function rt(e,t,...n){try{if(!e.enabled)return{success:!1,data:null,error:`Augmentation ${e.name} is disabled`};if("function"!=typeof e[t])return{success:!1,data:null,error:`Method ${t} not found on augmentation ${e.name}`};return await e[t](...n)}catch(n){return console.error(`Error executing ${t} on ${e.name}:`,n),{success:!1,data:null,error:n instanceof Error?n.message:String(n)}}}async function at(e,t={}){try{const n=await e,r=[];for(const e in n){const a=n[e];a&&"object"==typeof a&&("string"==typeof a.name&&"function"==typeof a.initialize&&"function"==typeof a.shutDown&&"function"==typeof a.getStatus&&(r.push(a),t.autoRegister&&(Ye(a),t.autoInitialize&&a.initialize().catch(e=>{console.error(`Failed to initialize augmentation ${a.name}:`,e)}))))}return r}catch(e){return console.error("Error loading augmentation module:",e),[]}}var st;!function(e){e.SEQUENTIAL="sequential",e.PARALLEL="parallel",e.FIRST_SUCCESS="firstSuccess",e.FIRST_RESULT="firstResult",e.THREADED="threaded"}(st||(st={}));const ot={mode:st.SEQUENTIAL,timeout:3e4,stopOnError:!1,forceThreading:!1,disableThreading:!1};class it{constructor(){this.registry={sense:[],conduit:[],cognition:[],memory:[],perception:[],dialog:[],activation:[],webSocket:[]}}register(e){let t=!1;if(this.isAugmentationType(e,"processRawData","listenToFeed")?(this.registry.sense.push(e),t=!0):this.isAugmentationType(e,"establishConnection","readData","writeData","monitorStream")?(this.registry.conduit.push(e),t=!0):this.isAugmentationType(e,"reason","infer","executeLogic")?(this.registry.cognition.push(e),t=!0):this.isAugmentationType(e,"storeData","retrieveData","updateData","deleteData","listDataKeys")?(this.registry.memory.push(e),t=!0):this.isAugmentationType(e,"interpret","organize","generateVisualization")?(this.registry.perception.push(e),t=!0):this.isAugmentationType(e,"processUserInput","generateResponse","manageContext")?(this.registry.dialog.push(e),t=!0):this.isAugmentationType(e,"triggerAction","generateOutput","interactExternal")&&(this.registry.activation.push(e),t=!0),this.isAugmentationType(e,"connectWebSocket","sendWebSocketMessage","onWebSocketMessage","closeWebSocket")&&(this.registry.webSocket.push(e),t=!0),!t)throw new Error(`Unknown augmentation type: ${e.name}`);return this}unregister(e){for(const t in this.registry){const n=this.registry[t],r=n.findIndex(t=>t.name===e);-1!==r&&n.splice(r,1)}return this}async initialize(){const e=this.getAllAugmentations();await Promise.all(e.map(e=>e.initialize().catch(t=>{console.error(`Failed to initialize augmentation ${e.name}:`,t)})))}async shutDown(){const e=this.getAllAugmentations();await Promise.all(e.map(e=>e.shutDown().catch(t=>{console.error(`Failed to shut down augmentation ${e.name}:`,t)})))}getAllAugmentations(){const e=new Set([...this.registry.sense,...this.registry.conduit,...this.registry.cognition,...this.registry.memory,...this.registry.perception,...this.registry.dialog,...this.registry.activation,...this.registry.webSocket]);return Array.from(e)}getAugmentationsByType(e){switch(e){case Me.SENSE:return[...this.registry.sense];case Me.CONDUIT:return[...this.registry.conduit];case Me.COGNITION:return[...this.registry.cognition];case Me.MEMORY:return[...this.registry.memory];case Me.PERCEPTION:return[...this.registry.perception];case Me.DIALOG:return[...this.registry.dialog];case Me.ACTIVATION:return[...this.registry.activation];case Me.WEBSOCKET:return[...this.registry.webSocket];default:return[]}}getAvailableAugmentationTypes(){const e=[];return this.registry.sense.length>0&&e.push(Me.SENSE),this.registry.conduit.length>0&&e.push(Me.CONDUIT),this.registry.cognition.length>0&&e.push(Me.COGNITION),this.registry.memory.length>0&&e.push(Me.MEMORY),this.registry.perception.length>0&&e.push(Me.PERCEPTION),this.registry.dialog.length>0&&e.push(Me.DIALOG),this.registry.activation.length>0&&e.push(Me.ACTIVATION),this.registry.webSocket.length>0&&e.push(Me.WEBSOCKET),e}getWebSocketAugmentations(){return[...this.registry.webSocket]}isAugmentationType(e,...t){return!!["initialize","shutDown","getStatus"].every(t=>"function"==typeof e[t])&&t.every(t=>"function"==typeof e[t])}shouldUseThreading(e){return!e.disableThreading&&((e.forceThreading||e.mode===st.THREADED)&&v())}async execute(e,t,n=[],r={}){const a={...ot,...r},s=e.filter(e=>!1!==e.enabled);if(0===s.length)return{results:[],errors:[],successful:[]};const o={results:[],errors:[],successful:[]},i=async e=>{try{if(a.timeout){const r=new Promise((n,r)=>{setTimeout(()=>{r(new Error(`Timeout executing ${t} on ${e.name}`))},a.timeout)});let s;if(this.shouldUseThreading(a))try{s=L(((...n)=>e[t].apply(e,n)).toString(),n)}catch(r){console.warn(`Failed to execute in thread, falling back to main thread: ${r}`),s=Promise.resolve(e[t](...n))}else s=Promise.resolve(e[t](...n));return await Promise.race([s,r])}return await rt(e,t,...n)}catch(e){return o.errors.push(e instanceof Error?e:new Error(String(e))),{success:!1,data:null,error:e instanceof Error?e.message:String(e)}}};switch(a.mode){case st.PARALLEL:case st.THREADED:o.results=await Promise.all(s.map(e=>i(e)));break;case st.FIRST_SUCCESS:for(const e of s){const t=await i(e);if(o.results.push(t),t.success)break}break;case st.FIRST_RESULT:for(const e of s){const t=await i(e);if(o.results.push(t),t.success&&null!==t.data&&void 0!==t.data)break}break;case st.SEQUENTIAL:default:for(const e of s){const t=await i(e);if(o.results.push(t),a.stopOnError&&!t.success)break}}return o.successful=o.results.filter(e=>e.success),o}async executeByType(e,t,n=[],r={}){const a=this.getAugmentationsByType(e);return this.execute(a,t,n,r)}async executeSingle(e,t,...n){return rt(e,t,...n)}async processStaticData(e,t,n={}){let r,a=e;for(const e of t){const t=e.transformArgs?e.transformArgs(a,r):[a],n=await this.executeSingle(e.augmentation,e.method,...t);if(!n.success)return n;a=n.data,r=n}return r}async processStreamingData(e,t,n,r,a,s={}){const o=async e=>{let t,n=e;for(const e of r){const r=e.transformArgs?e.transformArgs(n,t):[n],s=await this.executeSingle(e.augmentation,e.method,...r);if(!s.success)return void a(s);n=s.data,t=s}a(t)};await this.executeSingle(e,t,...n,e=>{o(e).catch(e=>{console.error("Error processing streaming data:",e),a({success:!1,data:null,error:e instanceof Error?e.message:String(e)})})})}createPipeline(e,t={}){return n=>this.processStaticData(n,e,t)}createStreamingPipeline(e,t,n,r={}){return(a,s)=>this.processStreamingData(e,t,a,n,s,r)}async executeSensePipeline(e,t,n={}){return(await this.executeByType(Me.SENSE,e,t,n)).results.map(e=>Promise.resolve(e))}async executeConduitPipeline(e,t,n={}){return(await this.executeByType(Me.CONDUIT,e,t,n)).results.map(e=>Promise.resolve(e))}async executeCognitionPipeline(e,t,n={}){return(await this.executeByType(Me.COGNITION,e,t,n)).results.map(e=>Promise.resolve(e))}async executeMemoryPipeline(e,t,n={}){return(await this.executeByType(Me.MEMORY,e,t,n)).results.map(e=>Promise.resolve(e))}async executePerceptionPipeline(e,t,n={}){return(await this.executeByType(Me.PERCEPTION,e,t,n)).results.map(e=>Promise.resolve(e))}async executeDialogPipeline(e,t,n={}){return(await this.executeByType(Me.DIALOG,e,t,n)).results.map(e=>Promise.resolve(e))}async executeActivationPipeline(e,t,n={}){return(await this.executeByType(Me.ACTIVATION,e,t,n)).results.map(e=>Promise.resolve(e))}}const ct=new it;!function(e){Ke=e}(ct);const lt=ct,ut=(e,t,n=[],r={})=>ct.execute(e,t,n,r),dt=(e,t,n=[],r={})=>ct.executeByType(e,t,n,r),ht=(e,t,...n)=>ct.executeSingle(e,t,...n),pt=(e,t,n={})=>ct.processStaticData(e,t,n),ft=(e,t,n,r,a,s={})=>ct.processStreamingData(e,t,n,r,a,s),mt=(e,t={})=>ct.createPipeline(e,t),gt=(e,t,n,r={})=>ct.createStreamingPipeline(e,t,n,r),yt=st;let bt,xt,wt;const vt=void 0!==globalThis.TransformStream&&void 0!==globalThis.ReadableStream&&void 0!==globalThis.WritableStream?(bt=globalThis.TransformStream,xt=globalThis.ReadableStream,wt=globalThis.WritableStream,Promise.resolve()):import("node:stream/web").then(e=>{bt=e.TransformStream,xt=e.ReadableStream,wt=e.WritableStream}).catch(e=>{throw console.error("Failed to import WebStreams API:",e),new Error("WebStreams API is not available in this environment. Please use a modern browser or Node.js 18+.")}),kt={timeout:3e4,stopOnError:!1};class It{constructor(e={}){this.brainyData=e.brainyData||new qe}async ensureStreamClassesInitialized(){await vt}async initialize(){await Promise.all([this.ensureStreamClassesInitialized(),this.brainyData.init()])}async processData(e,t,n={}){const r={...kt,...n},a={success:!0,data:null,stageResults:{}};try{const n=await He.executeSensePipeline("processRawData",[e,t],{timeout:r.timeout,stopOnError:r.stopOnError});let s=null;for(const e of n){const t=await e;if(t.success){s=t;break}}if(!s||!s.success)return{success:!1,data:null,error:"Failed to process raw data with ISense augmentations",stageResults:{sense:s||{success:!1,data:null,error:"No sense augmentations available"}}};a.stageResults.sense=s;const o=He.getAugmentationsByType(Me.MEMORY);if(0===o.length)return{success:!1,data:null,error:"No memory augmentations available",stageResults:a.stageResults};const i=o[0],c=`data_${Date.now()}_${Math.random().toString(36).substring(2,15)}`,l=await i.storeData(c,{rawData:e,dataType:t,nouns:s.data.nouns,verbs:s.data.verbs,timestamp:Date.now()});if(!l.success)return{success:!1,data:null,error:`Failed to store data: ${l.error}`,stageResults:{...a.stageResults,memory:l}};a.stageResults.memory=l;const u=await He.executeCognitionPipeline("reason",[`Analyze data with key ${c}`,{dataKey:c}],{timeout:r.timeout,stopOnError:r.stopOnError});let d=null;for(const e of u){const t=await e;if(t.success){d=t;break}}d&&(a.stageResults.cognition=d);const h=await He.executeConduitPipeline("writeData",[{dataKey:c,nouns:s.data.nouns,verbs:s.data.verbs}],{timeout:r.timeout,stopOnError:r.stopOnError});let p=null;for(const e of h){const t=await e;if(t.success){p=t;break}}p&&(a.stageResults.conduit=p);const f=await He.executeActivationPipeline("triggerAction",["dataProcessed",{dataKey:c}],{timeout:r.timeout,stopOnError:r.stopOnError});let m=null;for(const e of f){const t=await e;if(t.success){m=t;break}}m&&(a.stageResults.activation=m);const g=await He.executePerceptionPipeline("interpret",[s.data.nouns,s.data.verbs,{dataKey:c}],{timeout:r.timeout,stopOnError:r.stopOnError});let y=null;for(const e of g){const t=await e;if(t.success){y=t;break}}return y?(a.stageResults.perception=y,a.data=y.data):a.data=d?d.data:{dataKey:c},a}catch(e){return{success:!1,data:null,error:`Pipeline execution failed: ${e}`,stageResults:a.stageResults}}}async createWebSocketHandler(e,t,n={}){await this.ensureStreamClassesInitialized();const r=new bt({transform:async(e,r)=>{try{const a="string"==typeof e?e:JSON.stringify(e),s=await this.processData(a,t,n);s.success?r.enqueue(s):console.warn("Pipeline processing failed:",s.error)}catch(e){console.error("Error in transform stream:",e)}}}),a=new wt({write:async t=>{if(e.send&&"function"==typeof e.send)try{await e.send(JSON.stringify(t))}catch(e){console.error("Error sending result back to WebSocket:",e)}}});return r.readable.pipeTo(a).catch(e=>{console.error("Error in pipeline stream:",e)}),e=>{try{const t=r.writable.getWriter();t.write(e).catch(e=>{console.error("Error writing to stream:",e)}).finally(()=>{t.releaseLock()})}catch(e){console.error("Error getting writer for transform stream:",e)}}}async setupWebSocketPipeline(e,t,n={}){await this.ensureStreamClassesInitialized();const r=He.getWebSocketAugmentations();if(0===r.length)throw new Error("No WebSocket-supporting augmentations available");const a=r[0],s=await a.connectWebSocket(e),o=new xt({start:e=>{const t=t=>{try{const n="string"==typeof t.data?t.data:t.data instanceof Blob?new Promise(e=>{const n=new FileReader;n.onload=()=>e(n.result),n.readAsText(t.data)}):JSON.stringify(t.data);n instanceof Promise?n.then(t=>{e.enqueue(t)}).catch(e=>{console.error("Error processing blob data:",e)}):e.enqueue(n)}catch(e){console.error("Error processing WebSocket message:",e)}},n=e=>{t({data:e})};s._streamMessageHandler=t,s._messageHandlerWrapper=n,a.onWebSocketMessage(s.connectionId,n).catch(t=>{console.error("Error registering WebSocket message handler:",t),e.error(t)})},cancel:()=>{s._messageHandlerWrapper&&(a.offWebSocketMessage(s.connectionId,s._messageHandlerWrapper).catch(e=>{console.error("Error removing WebSocket message handler:",e)}),delete s._streamMessageHandler,delete s._messageHandlerWrapper)}}),i=this.createWebSocketHandler(s,t,n),c=new wt({write:async e=>{if(!s.send||"function"!=typeof s.send)throw new Error("WebSocket connection does not support sending data");try{const t="string"==typeof e?e:JSON.stringify(e);await s.send(t)}catch(e){throw console.error("Error sending data to WebSocket:",e),e}},close:()=>{s.close&&"function"==typeof s.close&&s.close().catch(e=>{console.error("Error closing WebSocket connection:",e)})}});o.pipeThrough(new bt({transform:async(e,t)=>{(await i)(e),t.enqueue(e)}})).pipeTo(new wt({write:()=>{},abort:e=>{console.error("Error in WebSocket pipeline:",e)}}));const l=s;return l.readableStream=o,l.writableStream=c,l}}const St=new It,Tt={autoInitialize:!1,debug:!1};async function Nt(e,t={}){const n={...Tt,...t},r={augmentations:[],errors:[]};n.debug&&console.log(`[AugmentationRegistryLoader] Loading augmentations from ${Object.keys(e).length} modules`);for(const[t,a]of Object.entries(e))try{n.debug&&console.log(`[AugmentationRegistryLoader] Processing module: ${t}`);const e=Ct(a);if(0===e.length){n.debug&&console.log(`[AugmentationRegistryLoader] No augmentations found in module: ${t}`);continue}for(const t of e)try{const e=Ye(t);r.augmentations.push(e),n.debug&&console.log(`[AugmentationRegistryLoader] Registered augmentation: ${e.name}`)}catch(e){const t=e instanceof Error?e:new Error(String(e));r.errors.push(t),n.debug&&console.error(`[AugmentationRegistryLoader] Failed to register augmentation: ${t.message}`)}}catch(e){const a=e instanceof Error?e:new Error(String(e));r.errors.push(a),n.debug&&console.error(`[AugmentationRegistryLoader] Error processing module ${t}: ${a.message}`)}return n.debug&&console.log(`[AugmentationRegistryLoader] Loaded ${r.augmentations.length} augmentations with ${r.errors.length} errors`),r}function Ct(e){const t=[];if(Et(e)&&t.push(e),e&&"object"==typeof e)for(const n of Object.keys(e)){const r=e[n];r&&"object"==typeof r&&(Et(r)&&t.push(r),Array.isArray(r)&&r.every(Et)&&t.push(...r))}return t}function Et(e){return e&&"object"==typeof e&&"string"==typeof e.name&&"function"==typeof e.initialize&&"function"==typeof e.shutDown&&"function"==typeof e.getStatus}function $t(e){return{name:"AugmentationRegistryPlugin",pattern:e.pattern,options:e.options||{}}}function At(e){return{name:"augmentation-registry-rollup-plugin",pattern:e.pattern,options:e.options||{}}}class Rt{constructor(e,t){this.description="Base memory augmentation",this.enabled=!0,this.isInitialized=!1,this.name=e,this.storage=t}async initialize(){if(!this.isInitialized)try{await this.storage.init(),this.isInitialized=!0}catch(e){throw console.error(`Failed to initialize ${this.name}:`,e),new Error(`Failed to initialize ${this.name}: ${e}`)}}async shutDown(){this.isInitialized=!1}async getStatus(){return this.isInitialized?"active":"inactive"}async storeData(e,t,n){await this.ensureInitialized();try{return await this.storage.saveMetadata(e,t),{success:!0,data:!0}}catch(t){return console.error(`Failed to store data for key ${e}:`,t),{success:!1,data:!1,error:`Failed to store data: ${t}`}}}async retrieveData(e,t){await this.ensureInitialized();try{return{success:!0,data:await this.storage.getMetadata(e)}}catch(t){return console.error(`Failed to retrieve data for key ${e}:`,t),{success:!1,data:null,error:`Failed to retrieve data: ${t}`}}}async updateData(e,t,n){await this.ensureInitialized();try{return await this.storage.saveMetadata(e,t),{success:!0,data:!0}}catch(t){return console.error(`Failed to update data for key ${e}:`,t),{success:!1,data:!1,error:`Failed to update data: ${t}`}}}async deleteData(e,t){await this.ensureInitialized();try{return await this.storage.saveMetadata(e,null),{success:!0,data:!0}}catch(t){return console.error(`Failed to delete data for key ${e}:`,t),{success:!1,data:!1,error:`Failed to delete data: ${t}`}}}async listDataKeys(e,t){return{success:!1,data:[],error:"listDataKeys is not supported by this storage adapter"}}async search(e,t=10,n){await this.ensureInitialized();try{let n;if(!Array.isArray(e)||!e.every(e=>"number"==typeof e))return{success:!1,data:[],error:"Query must be a vector (array of numbers) for vector search"};n=e;const r=await this.storage.getAllNouns(),a=[];for(const e of r){if(!e.vector||!Array.isArray(e.vector))continue;const t=await this.storage.getMetadata(e.id),r=1-F(n,e.vector);a.push({id:e.id,score:r,data:t})}a.sort((e,t)=>t.score-e.score);return{success:!0,data:a.slice(0,t)}}catch(e){return console.error("Failed to search in storage:",e),{success:!1,data:[],error:`Failed to search in storage: ${e}`}}}async ensureInitialized(){this.isInitialized||await this.initialize()}}class _t extends Rt{constructor(e){super(e,new ye),this.description="Memory augmentation that stores data in memory",this.enabled=!0}getType(){return Me.MEMORY}}class Ot extends Rt{constructor(e,t){super(e,new Re(t||".")),this.description="Memory augmentation that stores data in the file system",this.enabled=!0}getType(){return Me.MEMORY}}class Ft extends Rt{constructor(e){super(e,new xe),this.description="Memory augmentation that stores data in the Origin Private File System",this.enabled=!0}getType(){return Me.MEMORY}}async function Dt(e,t={}){if(t.storageType)switch(t.storageType){case"memory":return new _t(e);case"filesystem":return new Ot(e,t.rootDirectory);case"opfs":return new Ft(e)}if(globalThis.__ENV__?.isNode||"undefined"!=typeof process&&null!=process.versions&&null!=process.versions.node)return new Ot(e,t.rootDirectory);{const n=new xe;return n.isOPFSAvailable()?(t.requestPersistentStorage&&await n.requestPersistentStorage(),new Ft(e)):new _t(e)}}const Mt="1.0.0";var Pt;!function(e){e.DATA_ACCESS="data_access",e.TOOL_EXECUTION="tool_execution",e.SYSTEM_INFO="system_info",e.AUTHENTICATION="authentication"}(Pt||(Pt={}));class Bt{constructor(e){this.brainyData=e}async handleRequest(e){try{switch(e.operation){case"get":return await this.handleGetRequest(e);case"search":return await this.handleSearchRequest(e);case"add":return await this.handleAddRequest(e);case"getRelationships":return await this.handleGetRelationshipsRequest(e);default:return this.createErrorResponse(e.requestId,"UNSUPPORTED_OPERATION",`Operation ${e.operation} is not supported`)}}catch(t){return this.createErrorResponse(e.requestId,"INTERNAL_ERROR",t instanceof Error?t.message:String(t))}}async handleGetRequest(e){const{id:t}=e.parameters;if(!t)return this.createErrorResponse(e.requestId,"MISSING_PARAMETER",'Parameter "id" is required');const n=await this.brainyData.get(t);return n?this.createSuccessResponse(e.requestId,n):this.createErrorResponse(e.requestId,"NOT_FOUND",`No noun found with id ${t}`)}async handleSearchRequest(e){const{query:t,k:n=10}=e.parameters;if(!t)return this.createErrorResponse(e.requestId,"MISSING_PARAMETER",'Parameter "query" is required');const r=await this.brainyData.searchText(t,n);return this.createSuccessResponse(e.requestId,r)}async handleAddRequest(e){const{text:t,metadata:n}=e.parameters;if(!t)return this.createErrorResponse(e.requestId,"MISSING_PARAMETER",'Parameter "text" is required');const r=await this.brainyData.add(t,n);return this.createSuccessResponse(e.requestId,{id:r})}async handleGetRelationshipsRequest(e){const{id:t}=e.parameters;if(!t)return this.createErrorResponse(e.requestId,"MISSING_PARAMETER",'Parameter "id" is required');const n=await(this.brainyData.getVerbsBySource?.(t))||[],r=await(this.brainyData.getVerbsByTarget?.(t))||[];return this.createSuccessResponse(e.requestId,{outgoing:n,incoming:r})}createSuccessResponse(e,t){return{success:!0,requestId:e,version:Mt,data:t}}createErrorResponse(e,t,n,r){return{success:!1,requestId:e,version:Mt,error:{code:t,message:n,details:r}}}generateRequestId(){return _()}}class Lt{constructor(){}async handleRequest(e){try{const{toolName:t,parameters:n}=e,r=t.split("_");if(r.length<3||"brainy"!==r[0])return this.createErrorResponse(e.requestId,"INVALID_TOOL",`Invalid tool name: ${t}. Tool names should be in the format: brainy_{augmentationType}_{method}`);const a=r[1],s=r.slice(2).join("_");if(!this.isValidAugmentationType(a))return this.createErrorResponse(e.requestId,"INVALID_AUGMENTATION_TYPE",`Invalid augmentation type: ${a}`);const o=await this.executePipeline(a,s,n);return this.createSuccessResponse(e.requestId,o)}catch(t){return this.createErrorResponse(e.requestId,"INTERNAL_ERROR",t instanceof Error?t.message:String(t))}}async getAvailableTools(){const e=[],t=He.getAvailableAugmentationTypes();for(const n of t){const t=He.getAugmentationsByType(n);for(const r of t){const t=Object.getOwnPropertyNames(Object.getPrototypeOf(r)).filter(e=>!e.startsWith("_")&&"constructor"!==e&&"initialize"!==e&&"shutDown"!==e&&"getStatus"!==e&&"function"==typeof r[e]);for(const a of t)e.push(this.createToolDefinition(n,r.name,a))}}return e}createToolDefinition(e,t,n){return{name:`brainy_${e}_${n}`,description:`Access to Brainy's ${e} augmentation '${t}' method '${n}'`,parameters:{type:"object",properties:{args:{type:"array",description:`Arguments for the ${n} method`},options:{type:"object",description:"Optional execution options"}},required:["args"]}}}async executePipeline(e,t,n){const{args:r=[],options:a={}}=n;switch(e){case Me.SENSE:return await He.executeSensePipeline(t,r,a);case Me.CONDUIT:return await He.executeConduitPipeline(t,r,a);case Me.COGNITION:return await He.executeCognitionPipeline(t,r,a);case Me.MEMORY:return await He.executeMemoryPipeline(t,r,a);case Me.PERCEPTION:return await He.executePerceptionPipeline(t,r,a);case Me.DIALOG:return await He.executeDialogPipeline(t,r,a);case Me.ACTIVATION:return await He.executeActivationPipeline(t,r,a);default:throw new Error(`Unsupported augmentation type: ${e}`)}}isValidAugmentationType(e){return Object.values(Me).includes(e)}createSuccessResponse(e,t){return{success:!0,requestId:e,version:Mt,data:t}}createErrorResponse(e,t,n,r){return{success:!1,requestId:e,version:Mt,error:{code:t,message:n,details:r}}}generateRequestId(){return _()}}class zt{constructor(e,t={}){this.dataAdapter=new Bt(e),this.toolset=new Lt,this.options=t,this.authTokens=new Map,this.rateLimits=new Map}async handleRequest(e){try{switch(e.type){case Pt.DATA_ACCESS:return await this.dataAdapter.handleRequest(e);case Pt.TOOL_EXECUTION:return await this.toolset.handleRequest(e);case Pt.SYSTEM_INFO:return await this.handleSystemInfoRequest(e);case Pt.AUTHENTICATION:return await this.handleAuthenticationRequest(e);default:return this.createErrorResponse(e.requestId,"UNSUPPORTED_REQUEST_TYPE",`Request type ${e.type} is not supported`)}}catch(t){return this.createErrorResponse(e.requestId,"INTERNAL_ERROR",t instanceof Error?t.message:String(t))}}async handleSystemInfoRequest(e){try{switch(e.infoType){case"status":return this.createSuccessResponse(e.requestId,{status:"active",version:Mt,environment:m()?"browser":g()?"node":"unknown"});case"availableTools":const t=await this.toolset.getAvailableTools();return this.createSuccessResponse(e.requestId,t);case"version":return this.createSuccessResponse(e.requestId,{version:Mt});default:return this.createErrorResponse(e.requestId,"UNSUPPORTED_INFO_TYPE",`Info type ${e.infoType} is not supported`)}}catch(t){return this.createErrorResponse(e.requestId,"INTERNAL_ERROR",t instanceof Error?t.message:String(t))}}async handleAuthenticationRequest(e){try{if(!this.options.enableAuth)return this.createSuccessResponse(e.requestId,{authenticated:!0,message:"Authentication is not enabled"});const{credentials:t}=e;if(t.apiKey&&this.options.apiKeys?.includes(t.apiKey)){const t=this.generateAuthToken("api-user");return this.createSuccessResponse(e.requestId,{authenticated:!0,token:t})}if("admin"===t.username&&"password"===t.password){const n=this.generateAuthToken(t.username);return this.createSuccessResponse(e.requestId,{authenticated:!0,token:n})}return this.createErrorResponse(e.requestId,"INVALID_CREDENTIALS","Invalid credentials")}catch(t){return this.createErrorResponse(e.requestId,"INTERNAL_ERROR",t instanceof Error?t.message:String(t))}}isValidRequest(e){return e&&"object"==typeof e&&e.type&&e.requestId&&e.version}isAuthenticated(e){return!this.options.enableAuth||!!e.authToken&&this.isValidToken(e.authToken)}isValidToken(e){const t=this.authTokens.get(e);return!!t&&(!(t.expires<Date.now())||(this.authTokens.delete(e),!1))}generateAuthToken(e){const t=_(),n=Date.now()+864e5;return this.authTokens.set(t,{userId:e,expires:n}),t}checkRateLimit(e){if(!this.options.rateLimit)return!0;const t=Date.now(),n=this.rateLimits.get(e);return n?n.resetTime<t?(n.count=1,n.resetTime=t+this.options.rateLimit.windowMs,!0):!(n.count>=this.options.rateLimit.maxRequests)&&(n.count++,!0):(this.rateLimits.set(e,{count:1,resetTime:t+this.options.rateLimit.windowMs}),!0)}createSuccessResponse(e,t){return{success:!0,requestId:e,version:Mt,data:t}}createErrorResponse(e,t,n,r){return{success:!1,requestId:e,version:Mt,error:{code:t,message:n,details:r}}}generateRequestId(){return _()}async handleMCPRequest(e){return await this.handleRequest(e)}}"undefined"!=typeof window&&void 0===globalThis.Buffer&&(globalThis.Buffer=a.Buffer);const Ut={get isBrowser(){return m()},get isNode(){return g()},get isServerless(){return!m()&&!g()},isWebWorker:function(){return y()},get isThreadingAvailable(){return v()},isThreadingAvailableAsync:function(){return k()},areWorkerThreadsAvailable:function(){return x()}};"undefined"!=typeof globalThis&&(globalThis.__ENV__=Ut),console.log(`Brainy running in ${Ut.isBrowser?"browser":Ut.isNode?"Node.js":"serverless/unknown"} environment`);const Wt=globalThis.TextEncoder||"undefined"!=typeof global&&global.TextEncoder||class{encode(e){return new Uint8Array(Buffer.from(e,"utf8"))}},Vt=globalThis.TextDecoder||"undefined"!=typeof global&&global.TextDecoder||class{decode(e){return Buffer.from(e).toString("utf8")}},Gt={isFloat32Array:e=>e instanceof Float32Array,isInt32Array:e=>e instanceof Int32Array,isUint8Array:e=>e instanceof Uint8Array,isUint8ClampedArray:e=>e instanceof Uint8ClampedArray};var jt={TextEncoder:Wt,TextDecoder:Vt,types:Gt};var Ht=Object.freeze({__proto__:null,TextDecoder:Vt,TextEncoder:Wt,default:jt,promises:{},types:Gt});
|
|
10
10
|
/**
|
|
11
11
|
* @license
|
|
12
12
|
* Copyright 2020 Google LLC. All Rights Reserved.
|